Skip to content

Commit

Permalink
1.2.4
Browse files Browse the repository at this point in the history
  • Loading branch information
Hans IJntema committed Mar 20, 2022
1 parent 960251f commit 7d004af
Show file tree
Hide file tree
Showing 8 changed files with 48 additions and 61 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Includes Home Assistant MQTT Auto Discovery.
* Copy `systemd/trannergy-mqtt.service` to `/etc/systemd/system`
* Adapt path in `trannergy-mqtt.service` to your install location (default: `/opt/iot/trannergy`)
* Copy `config.rename.py` to `config.py` and adapt for your configuration (minimal: mqtt ip, username, password)
* `sudo systemctl enable trannery-mqtt`
* `sudo systemctl enable trannergy-mqtt`
* `sudo systemctl start trannergy-mqtt`

The are 2 clients integrated:
Expand Down Expand Up @@ -37,5 +37,8 @@ Tested under Linux; there is no reason why it does not work under Windows.
GPL v3

## Versions
1.2.4:
* Fix exit code (SUCCESS vs FAILURE)

1.2.2:
* Initial version on github
4 changes: 2 additions & 2 deletions config.rename.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
#!/usr/bin/python3

"""
Rename to config.py
Configure:
- MQTT client
- Debug level
- Home Assistant
- InfluxDB
"""

Expand Down
69 changes: 24 additions & 45 deletions mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@
"""

__version__ = "1.0.2"
__author__ = "Hans IJntema"
__version__ = "1.0.3"
__author__ = "Hans IJntema"
__license__ = "GPLv3"

import time
Expand Down Expand Up @@ -119,7 +119,7 @@ def __init__(self, mqtt_broker, mqtt_port, mqtt_client_id, mqtt_rate, mqtt_qos,

self.__mqtt_broker = mqtt_broker
self.__mqtt_port = mqtt_port
#self.__mqtt_client_id = mqtt_client_id
# self.__mqtt_client_id = mqtt_client_id

self.__mqtt_stopper = mqtt_stopper
self.__threads_stopper = threads_stopper
Expand Down Expand Up @@ -151,17 +151,15 @@ def __init__(self, mqtt_broker, mqtt_port, mqtt_client_id, mqtt_rate, mqtt_qos,
# - To allow for throttling of MQTT messages (but maybe this can be implemented via the call-back functions
# - Initially, I did not realize that PAHO has a queue mechanism
# - Too lazy to remove.....
self.__queue = queue.Queue(maxsize = self.__maxqueuesize)
self.__queue = queue.Queue(maxsize=self.__maxqueuesize)
self.__mqtt.username_pw_set(username, password)

self.__status_topic = None
self.__status_payload = None
self.__status_retain = None


def __del__(self):
logger.info( f">>" )

logger.info(f">>")

def __internet_on(self):
"""
Expand All @@ -176,15 +174,14 @@ def __internet_on(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Format: s.connect((HOST, PORT))
s.connect( (f"{self.__mqtt_broker}", int(self.__mqtt_port)) )
s.connect((f"{self.__mqtt_broker}", int(self.__mqtt_port)))
s.shutdown(socket.SHUT_RDWR)
logger.debug(f"Internet connectivity to MQTT broker {self.__mqtt_broker} at port {self.__mqtt_port} available")
return True
except:
logger.info(f"Internet connectivity to MQTT broker {self.__mqtt_broker} at port {self.__mqtt_port} NOT yet available")
except Exception as e:
logger.info(f"Internet connectivity to MQTT broker {self.__mqtt_broker} at port {self.__mqtt_port} NOT yet available; Exception {e}")
return False


def __on_connect(self, client, userdata, flags, rc):
"""
Callback: when the client receives a CONNACK response from the broker.
Expand All @@ -199,13 +196,12 @@ def __on_connect(self, client, userdata, flags, rc):
None
"""
if rc == 0:
logger.debug( f"Connected: client={client}; userdata={userdata}; flags={flags}; rc={rc}" )
self.__connected_flag=True
logger.debug(f"Connected: client={client}; userdata={userdata}; flags={flags}; rc={rc}")
self.__connected_flag = True
self.__set_status()
else:
logger.error( f"userdata={userdata}; flags={flags}; rc={rc}; {connack_dict[rc]}" )
self.__connected_flag=False

logger.error(f"userdata={userdata}; flags={flags}; rc={rc}; {connack_dict[rc]}")
self.__connected_flag = False

def __on_disconnect(self, client, userdata, rc):
"""
Expand All @@ -220,13 +216,12 @@ def __on_disconnect(self, client, userdata, rc):
None
"""
logger.debug(f"Disconnected: userdata={userdata}; rc={rc}")
self.__connected_flag=False
self.__connected_flag = False

if rc == 0:
logger.debug( f"Disconnected" )
logger.debug(f"Disconnected")
else:
logger.error( f"Unexpected disconnect, rc = {rc}, {rc_dict[rc]}" )

logger.error(f"Unexpected disconnect, rc = {rc}, {rc_dict[rc]}")

def __on_publish(self, client, userdata, mid):
"""
Expand All @@ -241,8 +236,7 @@ def __on_publish(self, client, userdata, mid):
None
"""
None
#logger.debug( f"userdata={userdata}; mid={mid}" )

# logger.debug( f"userdata={userdata}; mid={mid}" )

def __on_log(self, client, obj, level, buf):
"""
Expand All @@ -259,15 +253,9 @@ def __on_log(self, client, obj, level, buf):
"""
logger.debug(f"obj={obj}; level={level}; buf={buf}")


def __set_status(self):
"""
Set status
:param str topic:
:param str payload:
:param int qos:
:param bool retain:
:return: None
"""

Expand All @@ -290,8 +278,6 @@ def set_status(self, topic, payload=None, retain=False):
self.__status_retain = retain
self.__set_status()



def will_set(self, topic, payload=None, qos=0, retain=False):
"""
Set last will/testament
Expand All @@ -310,8 +296,7 @@ def will_set(self, topic, payload=None, qos=0, retain=False):

self.__mqtt.will_set(topic, payload, qos, retain)


def do_publish(self, topic, message, retain = False):
def do_publish(self, topic, message, retain=False):
"""
Publish topic & message to MQTT broker
(by storing topic & message in message queue)
Expand All @@ -327,8 +312,7 @@ def do_publish(self, topic, message, retain = False):

# Queue is used to allow for throttling of MQTT messages
self.__queue.put((topic, message, retain))
#logger.debug(f"{self.__queue.qsize()} MQTT messages are queued; Queue message: topic={topic}; message={message}")

# logger.debug(f"{self.__queue.qsize()} MQTT messages are queued; Queue message: topic={topic}; message={message}")

def __do_mqtt(self):
"""
Expand All @@ -341,10 +325,10 @@ def __do_mqtt(self):

# Check connectivity
if self.__connected_flag is False:
logger.warning( f"No connection with MQTT Broker; {self.__queue.qsize()} messages queued")
logger.warning(f"No connection with MQTT Broker; {self.__queue.qsize()} messages queued")
return None

logger.info( f"Connection with MQTT Broker; {self.__queue.qsize()} messages queued")
logger.info(f"Connection with MQTT Broker; {self.__queue.qsize()} messages queued")

# Maintain a mqtt message count
counter = 0
Expand All @@ -366,8 +350,7 @@ def __do_mqtt(self):
time.sleep(self.__mqtt_delay)

# stopper is set...
logger.info( f"Shutting down MQTT Client... {counter} MQTT messages have been published" )

logger.info(f"Shutting down MQTT Client... {counter} MQTT messages have been published")

def run(self):
logger.info(f"Broker = {self.__mqtt_broker}>>")
Expand All @@ -391,16 +374,15 @@ def run(self):
self.__mqtt.connect_async(self.__mqtt_broker, self.__mqtt_port, self.__keepalive)

except Exception as e:
logger.exception( f"Exception {format(e)}" )
logger.exception(f"Exception {format(e)}")
self.__mqtt.disconnect()
self.__mqtt_stopper.set()
self.__threads_stopper.set()
return

else:
self.__mqtt.loop_start()
logger.info( f"mqtt loop started..." )

logger.info(f"mqtt loop started...")

# Start infinite loop which sends queued messages every second
while not self.__mqtt_stopper.is_set():
Expand All @@ -413,7 +395,4 @@ def run(self):
self.__mqtt.disconnect()
self.__mqtt_stopper.set()
self.__threads_stopper.set()
logger.info( f"<<" )



logger.info(f"<<")
4 changes: 1 addition & 3 deletions systemd/trannergy-mqtt.service
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,8 @@ Environment="PYTHONPATH=/opt/python/lib"
Restart=on-failure
RestartSec=60s

#Type=oneshot
Type=simple
Type=idle
ExecStart=/opt/iot/trannergy/trannergy-mqtt.py
RemainAfterExit=true

[Install]
WantedBy=network-online.target
21 changes: 14 additions & 7 deletions trannergy-mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""

__version__ = "1.2.2"
__author__ = "Hans IJntema"
__version__ = "1.2.4"
__author__ = "Hans IJntema"
__license__ = "GPLv3"

import signal
Expand All @@ -58,6 +58,9 @@
from log import logger
logger.setLevel(cfg.loglevel)

# DEFAULT exit code
# status=1/FAILURE
__exit_code = 1

# ------------------------------------------------------------------------------------
# Instance running?
Expand All @@ -79,17 +82,17 @@
sys.exit(1)


def close(exit_code):
def close():
"""
Args:
:param int exit_code: 0 success; 1 error
Returns:
None
"""

logger.info(f"Exitcode = {exit_code} >>")
sys.exit(exit_code)
logger.info(f"Exitcode = {__exit_code} >>")
sys.exit(__exit_code)



# ------------------------------------------------------------------------------------
Expand Down Expand Up @@ -146,6 +149,10 @@ def exit_gracefully(signal, stackframe):
"""

logger.debug(f"Signal {signal}: >>")

# status=0/SUCCESS
__exit_code = 0

threads_stopper.set()
logger.info("<<")

Expand Down Expand Up @@ -194,4 +201,4 @@ def main():
main()

logger.debug("__main__: <<")
close(0)
close()
Empty file modified trannergy.PNG
100644 → 100755
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion trannergy_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def __decode_telegrams(self, telegram):
# values["p_ac3"] = float(int(hexdata[126:130], 16))
# unknown = float(int(hexdata[130:134],16))/100
values["yield_today"] = int(hexdata[138+offset:142+offset], 16) * 10
#values["yield_yesterday"] = int(hexdata[134+offset:138+offset], 16) * 10 # not implemented
# values["yield_yesterday"] = int(hexdata[134+offset:138+offset], 16) * 10 # not implemented
values["yield_total"] = int(hexdata[142+offset:150+offset], 16) * 100
values["hrs_total"] = int(hexdata[150+offset:158+offset], 16)
values["runstate"] = int(hexdata[158 + offset:160 + offset], 16)
Expand Down
4 changes: 2 additions & 2 deletions trannergy_serial.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
import os
script = os.path.basename(__main__.__file__)
script = os.path.splitext(script)[0]
logger = logging.getLogger(script + "." + __name__)
logger = logging.getLogger(script + "." + __name__)


class TaskReadSerial(threading.Thread):

Expand Down Expand Up @@ -127,7 +128,6 @@ def __read_serial(self):

logger.debug("<<")


def run(self):
logger.debug(">>")
try:
Expand Down

0 comments on commit 7d004af

Please sign in to comment.