Skip to content

Commit 096ea8c

Browse files
authored
Merge pull request #1 from yeyeto2788/master
A bit of refactoring and linting
2 parents b319191 + c647efe commit 096ea8c

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

59 files changed

+3842
-2930
lines changed

action.py

+47-38
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,54 @@
1-
import time
21
import json
3-
import redis
42
import subprocess
53
import sys
4+
5+
import redis
6+
67
sys.path.append('..')
78

9+
810
class Action():
911

10-
def __init__(self, config):
11-
self.config = config
12-
self.name = config.get("name", "Action")
13-
self.type = config.get("type", "event")
14-
self.key = config.get("key", None).replace(" ", "_").lower() if config.get("key") is not None else self.name.replace(" ", "_").lower()
15-
# Actions will be either objects to publish for events or a command string to execute
16-
self.action = config.get("action")
17-
try:
18-
self.r = config["redis"] if config["redis"] is not None else redis.Redis(host='127.0.0.1', port=6379)
19-
except KeyError:
20-
self.r = redis.Redis(host='127.0.0.1', port=6379)
21-
return
22-
23-
def init_action(self):
24-
if self.type == 'event':
25-
self.topic = self.config.get("topic", "mudpi")
26-
elif self.type == 'command':
27-
self.shell = self.config.get("shell", False)
28-
29-
def trigger(self, value=None):
30-
if self.type == 'event':
31-
self.emitEvent()
32-
elif self.type == 'command':
33-
self.runCommand(value)
34-
return
35-
36-
def emitEvent(self):
37-
self.r.publish(self.topic, json.dumps(self.action))
38-
return
39-
40-
def runCommand(self, value=None):
41-
if value is None:
42-
completed_process = subprocess.run([self.action], shell=self.shell)
43-
else:
44-
completed_process = subprocess.run([self.action, json.dumps(value)], shell=self.shell)
45-
return
12+
def __init__(self, config):
13+
self.config = config
14+
self.name = config.get("name", "Action")
15+
self.type = config.get("type", "event")
16+
self.key = config.get("key", None).replace(" ",
17+
"_").lower() if config.get(
18+
"key") is not None else self.name.replace(" ", "_").lower()
19+
# Actions will be either objects to publish for events
20+
# or a command string to execute
21+
self.action = config.get("action")
22+
23+
try:
24+
self.r = config["redis"] if config[
25+
"redis"] is not None else redis.Redis(
26+
host='127.0.0.1', port=6379)
27+
except KeyError:
28+
self.r = redis.Redis(host='127.0.0.1', port=6379)
29+
return
30+
31+
def init_action(self):
32+
if self.type == 'event':
33+
self.topic = self.config.get("topic", "mudpi")
34+
elif self.type == 'command':
35+
self.shell = self.config.get("shell", False)
36+
37+
def trigger(self, value=None):
38+
if self.type == 'event':
39+
self.emit_event()
40+
elif self.type == 'command':
41+
self.run_command(value)
42+
return
43+
44+
def emit_event(self):
45+
self.r.publish(self.topic, json.dumps(self.action))
46+
return
47+
48+
def run_command(self, value=None):
49+
if value is None:
50+
completed_process = subprocess.run([self.action], shell=self.shell)
51+
else:
52+
completed_process = subprocess.run(
53+
[self.action, json.dumps(value)], shell=self.shell)
54+
return

config_load.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
import json
1+
import json
22

3-
def loadConfigJson():
4-
configs = {}
5-
with open('mudpi.config') as loadedfile:
6-
configs = json.load(loadedfile)
7-
loadedfile.close()
8-
return configs
3+
4+
def load_config_json():
5+
configs = {}
6+
7+
with open('mudpi.config') as loadedfile:
8+
configs = json.load(loadedfile)
9+
loadedfile.close()
10+
return configs

controls/arduino/button_control.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,5 +35,5 @@ def read(self):
3535
self.previous_state = state
3636
return state
3737

38-
def readRaw(self):
38+
def read_raw(self):
3939
return super().read()

controls/arduino/control.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,13 @@ def init_control(self):
3939

4040
def read(self):
4141
#Read the sensor(s), parse the data and store it in redis if redis is configured
42-
return self.readPin()
42+
return self.read_pin()
4343

44-
def readRaw(self):
44+
def read_raw(self):
4545
#Read the sensor(s) but return the raw data, useful for debugging
4646
pass
4747

48-
def readPin(self):
48+
def read_pin(self):
4949
#Read the pin from the ardiuno. Can be analog or digital based on "analog_pin_mode"
5050
data = self.api.analogRead(self.pin) if self.analog_pin_mode else self.api.digitalRead(self.pin)
5151
return data

controls/arduino/potentiometer_control.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,6 @@ def read(self):
3333
self.previous_state = state
3434
return state
3535

36-
def readRaw(self):
36+
def read_raw(self):
3737
return super().read()
3838

controls/arduino/switch_control.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,5 +36,5 @@ def read(self):
3636
self.previous_state = state
3737
return state
3838

39-
def readRaw(self):
39+
def read_raw(self):
4040
return super().read()

controls/pi/button_control.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,6 @@ def read(self):
2525
super().emitEvent(1)
2626
return state
2727

28-
def readRaw(self):
28+
def read_raw(self):
2929
return super().read()
3030

controls/pi/control.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -60,13 +60,13 @@ def init_control(self):
6060
def read(self):
6161
#Read the sensor(s), parse the data and store it in redis if redis is configured
6262
#If edge detection is being used return the detection event instead
63-
return self.readPin() if self.edge_detection is None else GPIO.event_detected(self.pin)
63+
return self.read_pin() if self.edge_detection is None else GPIO.event_detected(self.pin)
6464

65-
def readRaw(self):
65+
def read_raw(self):
6666
#Read the sensor(s) but return the raw data, useful for debugging
6767
pass
6868

69-
def readPin(self):
69+
def read_pin(self):
7070
#Read the pin from the pi digital reads only
7171
data = self.gpio.input(self.pin)
7272
return data

controls/pi/switch_control.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,6 @@ def read(self):
3737
self.previous_state = state
3838
return state
3939

40-
def readRaw(self):
40+
def read_raw(self):
4141
return super().read()
4242

logger/Logger.py

+21-15
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import logging
22
import sys
33

4-
54
LOG_LEVEL = {
65
"unknown": logging.NOTSET,
76
"debug": logging.DEBUG,
@@ -11,8 +10,8 @@
1110
"error": logging.ERROR,
1211
}
1312

14-
class Logger:
1513

14+
class Logger:
1615
logger = None
1716

1817
def __init__(self, config: dict):
@@ -25,24 +24,28 @@ def __init__(self, config: dict):
2524
"terminal_log_level": "info"
2625
}
2726
# raise Exception("No Logger configs were found!")
28-
29-
self.__log = logging.getLogger(config['name']+"_stream")
27+
28+
self.__log = logging.getLogger(config['name'] + "_stream")
3029
self.__file_log = logging.getLogger(config['name'])
3130

3231
try:
33-
file_log_level = LOG_LEVEL[logger_config["file_log_level"]] if not config["debug"] else LOG_LEVEL["debug"]
34-
stream_log_level = LOG_LEVEL[logger_config["terminal_log_level"]] if not config["debug"] else LOG_LEVEL["debug"]
32+
file_log_level = LOG_LEVEL[logger_config["file_log_level"]] if not \
33+
config["debug"] else LOG_LEVEL["debug"]
34+
stream_log_level = LOG_LEVEL[
35+
logger_config["terminal_log_level"]] if not config[
36+
"debug"] else LOG_LEVEL["debug"]
3537
except KeyError:
3638
file_log_level = LOG_LEVEL["unknown"]
3739
stream_log_level = LOG_LEVEL["unknown"]
38-
40+
3941
self.__log.setLevel(stream_log_level)
4042
self.__file_log.setLevel(file_log_level)
4143

4244
try:
4345
try:
4446
if len(logger_config['file']) != 0:
45-
open(logger_config['file'], 'w').close() # testing file path
47+
open(logger_config['file'],
48+
'w').close() # testing file path
4649
file_handler = logging.FileHandler(logger_config['file'])
4750
file_handler.setLevel(file_log_level)
4851

@@ -51,32 +54,35 @@ def __init__(self, config: dict):
5154
self.WRITE_TO_FILE = False
5255
except FileNotFoundError:
5356
self.WRITE_TO_FILE = False
54-
57+
5558
except KeyError as e:
5659
self.WRITE_TO_FILE = False
5760

58-
self.log(LOG_LEVEL["warning"], "File Handler could not be started due to a KeyError: {0}".format(e))
59-
61+
self.log(LOG_LEVEL["warning"],
62+
"File Handler could not be started due to a KeyError: {0}".format(
63+
e))
64+
6065
stream_handler = logging.StreamHandler(sys.stdout)
6166
stream_handler.setLevel(stream_log_level)
6267

63-
file_formatter = logging.Formatter("[%(asctime)s][%(name)s][%(levelname)s] %(message)s", "%H:%M:%S")
68+
file_formatter = logging.Formatter(
69+
"[%(asctime)s][%(name)s][%(levelname)s] %(message)s", "%H:%M:%S")
6470
stream_formatter = logging.Formatter("%(message)s")
6571
file_handler.setFormatter(file_formatter)
6672
stream_handler.setFormatter(stream_formatter)
6773

6874
if self.WRITE_TO_FILE:
6975
self.__file_log.addHandler(file_handler)
7076
self.__log.addHandler(stream_handler)
71-
77+
7278
@staticmethod
7379
def log_to_file(log_level: int, msg: str):
7480
"""
7581
Logs the given message ONLY to the log file.
7682
"""
7783
if Logger.log is not None:
7884
Logger.logger.log_this_file(log_level, msg)
79-
85+
8086
@staticmethod
8187
def log(log_level: int, msg: str): # for ease of access from outside
8288
"""
@@ -94,7 +100,7 @@ def log_this_file(self, log_level: int, msg: str):
94100
msg = msg.replace("\033[1;31m", "")
95101
msg = msg.replace("\033[0;0m", "")
96102
self.__file_log.log(log_level, msg)
97-
103+
98104
def log_this(self, log_level: int, msg: str):
99105
self.__log.log(log_level, msg)
100106
if self.WRITE_TO_FILE:

0 commit comments

Comments
 (0)