Skip to content

Commit

Permalink
Code style cleanup with black, flake8 and isort (#77)
Browse files Browse the repository at this point in the history
* Test for membership should be 'not in' (Flake8 rule E713)

* Whitespace fixes (various Flake8 rules)

* Don't import unused functions getProperties and getAttribute (Flake8 rule F401)

* Don't use f-string when there's no placeholder (Flake8 rule F541)

* Do not use bare 'except' (Flake8 rule E722)

* Run black and add it to pre-commit

* Use lazy % formatting in logging functions

* Add flake8 to pre-commit

* Add use of pre-commit to development docs

* Run pre-commit in GitHub Actions workflow

* Run isort

* Specify encoding when opening file (Pylint rule W1514)

* Remove useless super() delegation (Pylint rule W0246)

* Remove useless super() delegation (Pylint rule W0246)

* Add docstrings to classes and methods

* Use PascalCase naming style for classes

* Use snake_case for variable and argument names

* Explicitly re-raise new exception from other one for better tracebacks (Pylint rule W0707)

* Remove unneeded run invocation from ble_gateway.py
  • Loading branch information
koenvervloesem authored Dec 2, 2022
1 parent e398a5e commit 22d5eb1
Show file tree
Hide file tree
Showing 8 changed files with 484 additions and 269 deletions.
20 changes: 20 additions & 0 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: check

on:
push:
branches:
- development
pull_request:

jobs:
pre-commit:
runs-on: ubuntu-22.04
steps:
- name: Checkout repository
uses: actions/[email protected]
- name: Set up Python
uses: actions/[email protected]
with:
python-version: "3.11"
- name: Run pre-commit
uses: pre-commit/[email protected]
14 changes: 14 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
repos:
- repo: https://github.com/psf/black
rev: 22.10.0
hooks:
- id: black
- repo: https://github.com/pycqa/flake8
rev: 5.0.4
hooks:
- id: flake8
- repo: https://github.com/pycqa/isort
rev: 5.10.1
hooks:
- id: isort
221 changes: 152 additions & 69 deletions TheengsGateway/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,20 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""

import sys
import os
import json
import argparse
import json
import os
import sys

from .ble_gateway import run

default_config = {
"host":"",
"port":1883,
"user":"",
"pass":"",
"ble_scan_time":5,
"ble_time_between_scans":5,
"host": "",
"port": 1883,
"user": "",
"pass": "",
"ble_scan_time": 5,
"ble_time_between_scans": 5,
"publish_topic": "home/TheengsGateway/BTtoMQTT",
"subscribe_topic": "home/+/BTtoMQTT/undecoded",
"log_level": "WARNING",
Expand All @@ -41,106 +42,188 @@
"discovery_device_name": "TheengsGateway",
"discovery_filter": ["IBEACON", "GAEN", "MS-CDP"],
"adapter": "",
"scanning_mode": "active"
"scanning_mode": "active",
}

conf_path = os.path.expanduser('~') + '/theengsgw.conf'

parser = argparse.ArgumentParser()
parser.add_argument('-H', '--host', dest='host', type=str, help="MQTT host address")
parser.add_argument('-P', '--port', dest='port', type=int, help="MQTT host port")
parser.add_argument('-u', '--user', dest='user', type=str, help="MQTT username")
parser.add_argument('-p', '--pass', dest='pwd', type=str, help="MQTT password")
parser.add_argument('-pt', '--pub_topic', dest='pub_topic', type=str, help="MQTT publish topic")
parser.add_argument('-st', '--sub_topic', dest='sub_topic', type=str, help="MQTT subscribe topic")
parser.add_argument('-pa', '--publish_all', dest='publish_all', type=int, help="Enable(1) or disable(0) publishing of all beacons")
parser.add_argument('-sd', '--scan_duration', dest='scan_dur', type=int, help="BLE scan duration (seconds)")
parser.add_argument('-tb', '--time_between', dest='time_between', type=int, help="Seconds to wait between scans")
parser.add_argument('-ll', '--log_level', dest='log_level', type=str, help="TheengsGateway log level",
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'])
parser.add_argument('-Dt', '--discovery-topic', dest='discovery_topic', type=str, help="MQTT Discovery topic")
parser.add_argument('-D', '--discovery', dest='discovery', type=int, help="Enable(1) or disable(0) MQTT discovery")
parser.add_argument('-Dh', '--hass_discovery', dest='hass_discovery', type=int, help="Enable(1) or disable(0) Home Assistant-specific MQTT discovery (default: 1)")
parser.add_argument('-Dn', '--discovery_name', dest='discovery_device_name', type=str, help="Device name for Home Assistant")
parser.add_argument('-Df', '--discovery_filter', dest='discovery_filter', nargs='+', default=[],
help="Device discovery filter list for Home Assistant")
parser.add_argument('-a', '--adapter', dest='adapter', type=str, help="Bluetooth adapter (e.g. hci1 on Linux)")
parser.add_argument('-s', '--scanning_mode', dest='scanning_mode', type=str, choices=("active", "passive"), help="Scanning mode (default: active)")
conf_path = os.path.expanduser("~") + "/theengsgw.conf"

parser = argparse.ArgumentParser()
parser.add_argument(
"-H", "--host", dest="host", type=str, help="MQTT host address"
)
parser.add_argument(
"-P", "--port", dest="port", type=int, help="MQTT host port"
)
parser.add_argument(
"-u", "--user", dest="user", type=str, help="MQTT username"
)
parser.add_argument("-p", "--pass", dest="pwd", type=str, help="MQTT password")
parser.add_argument(
"-pt", "--pub_topic", dest="pub_topic", type=str, help="MQTT publish topic"
)
parser.add_argument(
"-st",
"--sub_topic",
dest="sub_topic",
type=str,
help="MQTT subscribe topic",
)
parser.add_argument(
"-pa",
"--publish_all",
dest="publish_all",
type=int,
help="Enable(1) or disable(0) publishing of all beacons",
)
parser.add_argument(
"-sd",
"--scan_duration",
dest="scan_dur",
type=int,
help="BLE scan duration (seconds)",
)
parser.add_argument(
"-tb",
"--time_between",
dest="time_between",
type=int,
help="Seconds to wait between scans",
)
parser.add_argument(
"-ll",
"--log_level",
dest="log_level",
type=str,
help="TheengsGateway log level",
choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
)
parser.add_argument(
"-Dt",
"--discovery-topic",
dest="discovery_topic",
type=str,
help="MQTT Discovery topic",
)
parser.add_argument(
"-D",
"--discovery",
dest="discovery",
type=int,
help="Enable(1) or disable(0) MQTT discovery",
)
parser.add_argument(
"-Dh",
"--hass_discovery",
dest="hass_discovery",
type=int,
help="Enable(1) or disable(0) Home Assistant MQTT discovery (default: 1)",
)
parser.add_argument(
"-Dn",
"--discovery_name",
dest="discovery_device_name",
type=str,
help="Device name for Home Assistant",
)
parser.add_argument(
"-Df",
"--discovery_filter",
dest="discovery_filter",
nargs="+",
default=[],
help="Device discovery filter list for Home Assistant",
)
parser.add_argument(
"-a",
"--adapter",
dest="adapter",
type=str,
help="Bluetooth adapter (e.g. hci1 on Linux)",
)
parser.add_argument(
"-s",
"--scanning_mode",
dest="scanning_mode",
type=str,
choices=("active", "passive"),
help="Scanning mode (default: active)",
)
args = parser.parse_args()

try:
with open(conf_path, 'r') as config_file:
with open(conf_path, encoding="utf-8") as config_file:
config = json.load(config_file)
except:
except Exception:
config = default_config

# Merge default configuration, with data read from the configuration file overriding default data.
# Merge default configuration, with data read from the configuration file
# overriding default data.
# This guarantees that all keys we refer to are in the dictionary.
config = {**default_config, **config}

if args.host:
config['host'] = args.host
config["host"] = args.host
if args.port:
config['port'] = args.port
config["port"] = args.port
if args.user:
config['user'] = args.user
config["user"] = args.user
if args.pwd:
config['pass'] = args.pwd
config["pass"] = args.pwd
if args.pub_topic:
config['publish_topic'] = args.pub_topic
config["publish_topic"] = args.pub_topic
if args.sub_topic:
config['subscribe_topic'] = args.sub_topic
config["subscribe_topic"] = args.sub_topic
if args.publish_all:
config['publish_all'] = args.publish_all
config["publish_all"] = args.publish_all
if args.scan_dur:
config['ble_scan_time'] = args.scan_dur
config["ble_scan_time"] = args.scan_dur
if args.time_between:
config['ble_time_between_scans'] = args.time_between
config["ble_time_between_scans"] = args.time_between
if args.log_level:
config['log_level'] = args.log_level
config["log_level"] = args.log_level

if args.discovery is not None:
config['discovery'] = args.discovery
elif not 'discovery' in config.keys():
config['discovery'] = default_config['discovery']
config['discovery_topic'] = default_config['discovery_topic']
config['discovery_device_name'] = default_config['discovery_device_name']
config['discovery_filter'] = default_config['discovery_filter']
config["discovery"] = args.discovery
elif "discovery" not in config.keys():
config["discovery"] = default_config["discovery"]
config["discovery_topic"] = default_config["discovery_topic"]
config["discovery_device_name"] = default_config["discovery_device_name"]
config["discovery_filter"] = default_config["discovery_filter"]

if args.hass_discovery is not None:
config['hass_discovery'] = args.hass_discovery
config["hass_discovery"] = args.hass_discovery

if args.discovery_topic:
config['discovery_topic'] = args.discovery_topic
elif not 'discovery_topic' in config.keys():
config['discovery_topic'] = default_config['discovery_topic']
config["discovery_topic"] = args.discovery_topic
elif "discovery_topic" not in config.keys():
config["discovery_topic"] = default_config["discovery_topic"]

if args.discovery_device_name:
config['discovery_device_name'] = args.discovery_device_name
elif not 'discovery_device_name' in config.keys():
config['discovery_device_name'] = default_config['discovery_device_name']
config["discovery_device_name"] = args.discovery_device_name
elif "discovery_device_name" not in config.keys():
config["discovery_device_name"] = default_config["discovery_device_name"]

if args.discovery_filter:
config['discovery_filter'] = default_config['discovery_filter']
config["discovery_filter"] = default_config["discovery_filter"]
if args.discovery_filter[0] != "reset":
for item in args.discovery_filter:
config['discovery_filter'].append(item)
elif not 'discovery_filter' in config.keys():
config['discovery_filter'] = default_config['discovery_filter']
config["discovery_filter"].append(item)
elif "discovery_filter" not in config.keys():
config["discovery_filter"] = default_config["discovery_filter"]

if args.adapter:
config['adapter'] = args.adapter
config["adapter"] = args.adapter

if args.scanning_mode:
config['scanning_mode'] = args.scanning_mode
config["scanning_mode"] = args.scanning_mode

if not config['host']:
sys.exit('Invalid MQTT host')
if not config["host"]:
sys.exit("Invalid MQTT host")

try:
with open(conf_path, 'w') as config_file:
with open(conf_path, mode="w", encoding="utf-8") as config_file:
config_file.write(json.dumps(config, sort_keys=True, indent=4))
except:
raise SystemExit('Unable to open config file')
except Exception as exception:
raise SystemExit("Unable to write config file") from exception

run(conf_path)
Loading

0 comments on commit 22d5eb1

Please sign in to comment.