Skip to content

Commit

Permalink
Feature release 2023.10.3-2
Browse files Browse the repository at this point in the history
  • Loading branch information
mazocode committed Oct 22, 2023
1 parent 02ef5e8 commit 7fbb461
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 24 deletions.
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ docker-run:
export-requirements:
poetry export -f requirements.txt --output requirements.txt

init-env:
poetry env use $(which python3.11)

check-code:
poetry run pflake8 .

Expand Down
46 changes: 22 additions & 24 deletions modbus2mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ def on_connect(self, client, userdata, flags, rc):
log.error(flags)

def on_message(self, client, userdata, message):
log.debug("message received '",str(message.payload.decode("utf-8")),\
"' via topic '",message.topic,"' (retained=",message.retain,").")
log.debug("message received '", str(message.payload.decode("utf-8")),
"' via topic '", message.topic, "' (retained=", message.retain, ").")

subscriber = self.subscribers.get(message.topic, None)
if subscriber is not None:
Expand Down Expand Up @@ -171,16 +171,16 @@ def get_value(self, src):

rr = src.client.read_coils(self.start, self.length, slave=unitid)
if not rr:
raise ModbusException(f"Received empty modbus respone.")
raise ModbusException("Received empty modbus respone.")
if rr.isError():
raise ModbusException(f"Received Modbus library error({rr}).")
if isinstance(rr, ExceptionResponse):
raise ModbusException(f"Received Modbus library exception ({rr}).")

val = {}
for c in self.coils:
name = re.sub('/\s\s+/g', '_', str(c["name"]).strip())
if rr.bits[c["bit"]-1] == 0:
name = re.sub(r'/\s\s+/g', '_', str(c["name"]).strip())
if rr.bits[c["bit"] - 1] == 0:
val[name] = c["off_value"]
else:
val[name] = c["on_value"]
Expand All @@ -204,7 +204,7 @@ def set_value(self, src, params):
# Find the coil to set
coil = None
for c in self.coils:
name = re.sub('/\s\s+/g', '_', str(c["name"]).strip())
name = re.sub(r'/\s\s+/g', '_', str(c["name"]).strip())
if cname == name or cname == str(c["name"]):
if 'w' in c["mode"]:
# Can't write to this coil
Expand All @@ -222,7 +222,7 @@ def set_value(self, src, params):

rr = src.client.write_coil(self.start + int(coil["bit"]), value, slave=unitid)
if not rr:
raise ModbusException(f"Received empty modbus respone.")
raise ModbusException("Received empty modbus respone.")
if rr.isError():
raise ModbusException(f"Received Modbus library error({rr}).")
if isinstance(rr, ExceptionResponse):
Expand All @@ -232,8 +232,8 @@ def set_value(self, src, params):
class HoldingRegister(Register):

def __init__(self, name: str, topic: str, register: int, length: int = 2,
mode: str = "r", substract: float = 0, divide: float = 1,
decimals: int = 0, signed: bool = False, unitid: int=None, **kvargs):
mode: str = "r", substract: float = 0, divide: float = 1,
decimals: int = 0, signed: bool = False, unitid: int = None, **kvargs):
super().__init__(name, topic, register, length, mode, unitid=unitid)
self.divide = divide
self.decimals = decimals
Expand All @@ -247,7 +247,7 @@ def get_value(self, src):

rr = src.client.read_holding_registers(self.start, self.length, slave=unitid)
if not rr:
raise ModbusException(f"Received empty modbus respone.")
raise ModbusException("Received empty modbus respone.")
if rr.isError():
raise ModbusException(f"Received Modbus library error({rr}).")
if isinstance(rr, ExceptionResponse):
Expand All @@ -274,7 +274,7 @@ def __init__(self, name: str, readings: List[Register]):
class ModbusSource:

def __init__(self, name: str, broker: MqttBroker, host: str, port: int,
schema: Schema, unitid: int = 1, topic_prefix: str = None,
schema: Schema, unitid: int = 1, topic_prefix: str = None,
pollms: int = 100, enabled: bool = True):
self.mqtt = broker
self.host = host
Expand Down Expand Up @@ -302,7 +302,7 @@ def __init__(self, name: str, broker: MqttBroker, host: str, port: int,
if topic_prefix:
self.topic_prefix = topic_prefix
else:
self.topic_prefix = re.sub('/\s\s+/g', '_', self.name.strip().lower())
self.topic_prefix = re.sub(r'/\s\s+/g', '_', self.name.strip().lower())

self.mqtt.rpc_subscribe(self)

Expand Down Expand Up @@ -345,7 +345,7 @@ def poller_thread(self):
if sigStop:
break

msg = self.queue.get();
msg = self.queue.get()
if not msg:
continue

Expand All @@ -354,7 +354,7 @@ def poller_thread(self):
continue

# Find the target
targe = None
target = None
for r in self.schema.readings:
if r.topic == name or r.name == name:
target = r
Expand All @@ -365,8 +365,7 @@ def poller_thread(self):
case "set":
target.set_value(self, msg.get("params", {}))


time.sleep(self.pollms/1000)
time.sleep(self.pollms / 1000)
finally:
try:
self.client.close()
Expand Down Expand Up @@ -435,14 +434,13 @@ def main(argv):

log.debug("Configuring mqtt broker %s", config["mqtt"]["host"])
broker = MqttBroker(
str(config["mqtt"].get("host", "localhost")),
int(config["mqtt"].get("port", 1883)),
str(config["mqtt"].get("username", None)),
str(config["mqtt"].get("password", None)),
str(config["mqtt"].get("topic_prefix", None)),
bool(config["mqtt"].get("tls", False)),
clientid=str(config["mqtt"].get("clientid", "modbus2mqtt"))
)
str(config["mqtt"].get("host", "localhost")),
int(config["mqtt"].get("port", 1883)),
str(config["mqtt"].get("username", None)),
str(config["mqtt"].get("password", None)),
str(config["mqtt"].get("topic_prefix", None)),
bool(config["mqtt"].get("tls", False)),
clientid=str(config["mqtt"].get("clientid", "modbus2mqtt")))

for source in config["sources"]:
log.debug("Configuring source %s", source["name"])
Expand Down

0 comments on commit 7fbb461

Please sign in to comment.