Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code simplifications #102

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
4 changes: 2 additions & 2 deletions solarman/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ def main():
args = parser.parse_args()
solarman = SolarmanPV(args.file)
if args.single:
solarman.single_run_loop(args.file)
solarman.single_run_loop()
elif args.daemon:
solarman.daemon(args.file, args.interval)
solarman.daemon(args.interval)
elif args.validate:
solarman.validate_config(args.file)
elif args.create_passhash:
Expand Down
19 changes: 0 additions & 19 deletions solarman/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,22 +88,3 @@ def __init__(self, config):
print(err.message)
sys.exit(1)
print(_VALID)


class HashPassword: # pylint: disable=too-few-public-methods
"""
Hash the password
"""

def __init__(self, password):
self.password = password
self.hashed = ""
HashPassword.hash(self)

def hash(self):
"""
Return hashed string
:return:
"""
self.hashed = hashlib.sha256(self.password.encode("utf-8")).hexdigest()
return self.hashed
11 changes: 6 additions & 5 deletions solarman/mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ def __init__(self, config):
self.username = config["username"]
self.password = config["password"]
self.qos = config.get("qos", 0)
self.topic_prefix = config["topic"]
self.retain = config.get("retain", False)
self.client = Mqtt.connect(self)
self.client = self.connect()

def connect(self):
"""
Expand All @@ -36,15 +37,15 @@ def connect(self):
client.connect(self.broker, self.port)
return client

def publish(self, client, topic, msg):
def publish(self, topic, msg):
"""
Publish a message on a MQTT topic
:param client: Connect parameters
:param topic: MQTT topic
:param msg: Message payload
:return:
"""
result = client.publish(topic, msg, self.qos, self.retain)
topic = self.topic_prefix + topic
result = self.client.publish(topic, msg, self.qos, self.retain)
# result: [0, 1]
status = result[0]
if status == 0:
Expand All @@ -56,4 +57,4 @@ def message(self, topic, msg):
"""
MQTT Send message to selected topic
"""
Mqtt.publish(self, self.client, topic, msg)
self.publish(self, topic, msg)
52 changes: 23 additions & 29 deletions solarman/solarmanpv.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
import time

from .api import SolarmanApi, ConstructData
from .helpers import ConfigCheck, HashPassword
from .helpers import ConfigCheck
from .mqtt import Mqtt
from hashlib import sha256

logging.basicConfig(level=logging.INFO)

Expand Down Expand Up @@ -83,19 +84,12 @@
logging.info(json.dumps(meter_data_list, indent=4, sort_keys=True))

discard = ["code", "msg", "requestId", "success"]
topic = config["mqtt"]["topic"]

_t = time.strftime("%Y-%m-%d %H:%M:%S")
try:
inverter_device_state = inverter_data["deviceState"]
except KeyError:
inverter_device_state = 128
inverter_device_state = inverter_data.get("deviceState", 128)

if meter_data:
try:
meter_state = meter_data["deviceState"]
except KeyError:
meter_state = 128
meter_state = meter_data.get("deviceState", 128)

mqtt_connection = Mqtt(config["mqtt"])

Expand All @@ -105,9 +99,9 @@
)
for i in meter_data:
if meter_data[i]:
mqtt_connection.message(topic + "/meter/" + i, meter_data[i])
mqtt_connection.message("/meter/" + i, meter_data[i])
mqtt_connection.message(
topic + "/meter/attributes", json.dumps(meter_data_list)
"/meter/attributes", json.dumps(meter_data_list)
)

if inverter_device_state == 1:
Expand All @@ -118,23 +112,23 @@
)
for i in station_data:
if station_data[i] and i not in discard:
mqtt_connection.message(topic + "/station/" + i, station_data[i])
mqtt_connection.message("/station/" + i, station_data[i])

for i in inverter_data:
if inverter_data[i] and i not in discard:
mqtt_connection.message(topic + "/inverter/" + i, inverter_data[i])
mqtt_connection.message("/inverter/" + i, inverter_data[i])

mqtt_connection.message(
topic + "/inverter/attributes",
"/inverter/attributes",
json.dumps(inverter_data_list),
)

for i in logger_data:
if logger_data[i] and i not in discard:
mqtt_connection.message(topic + "/logger/" + i, logger_data[i])
mqtt_connection.message("/logger/" + i, logger_data[i])

mqtt_connection.message(
topic + "/logger/attributes",
"/logger/attributes",
json.dumps(logger_data_list),
)

Expand All @@ -147,10 +141,10 @@
)
else:
mqtt_connection.message(
topic + "/inverter/deviceState", inverter_data.get("deviceState")
"/inverter/deviceState", inverter_data.get("deviceState")
)
mqtt_connection.message(
topic + "/logger/deviceState", logger_data.get("deviceState")
"/logger/deviceState", logger_data.get("deviceState")
)
logging.info(
"%s - Inverter DeviceState: %s"
Expand All @@ -159,15 +153,14 @@
inverter_device_state,
)

def single_run_loop(self, file):
def single_run_loop(self):
"""
Perform single runs for all config instances
"""
config = self.load_config(file)
for conf in config:
for conf in self.config:
self.single_run(conf)

def daemon(self, file, interval):
def daemon(self, interval):
"""
Run as a daemon process
:param file: Config file
Expand All @@ -180,20 +173,21 @@
)
while True:
try:
SolarmanPV.single_run_loop(self, file)
self.single_run_loop()
time.sleep(interval)
except Exception as error: # pylint: disable=broad-except
logging.error("Error on start: %s", str(error))
sys.exit(1)
except KeyboardInterrupt:
logging.info("Exiting on keyboard interrupt")
sys.exit(0)
except Exception as error: # pylint: disable=broad-except
logging.error("Error on start: %s", str(error))
sys.exit(1)

def create_passhash(self, password):
"""
Create passhash from password
:param password: Password
:return:
"""
pwstring = HashPassword(password)
print(pwstring.hashed)
passhash = sha256(password.encode()).hexdigest()

Check failure

Code scanning / CodeQL

Use of a broken or weak cryptographic hashing algorithm on sensitive data High

Sensitive data (password)
is used in a hashing algorithm (SHA256) that is insecure for password hashing, since it is not a computationally expensive hash function.
print(passhash)
return passhash
Loading