Run daily Python script (Warmtemeter) including Imports ( HA on HassOS @ ESX)

Tags: #<Tag:0x00007f3263ddd208> #<Tag:0x00007f3263ddd118> #<Tag:0x00007f3263ddcf88>

All,

I have this modified script (See below) in my python_script folder and it works fine when run from SSH console. Now I want to retrieve the data from my district theater once a day so I need to schedule it. Tried/reviewed online very quickly with Node-RED, Crontab, Python-script, Custom Components, AppDaemon but was not successful yet.

Hoped for simply doing a automation calling the python-script once a day but due to imports and limited functionality on that side can’t get this to work. Crontab no option as this is not persistent and running in the SSH console container probably. Node-red and Custom components were still too complex for me, need to learn a bit more by trial and error.

Any advise? Thanks!
-Tom

#!/usr/bin/python3
###############################################################################
# Stadsverwarming UT550 script for Home Assistant                             #
# Version 0.3 - Author: RuntimeError123 / L. Bosch                            #
# Updated for UT50/550T by [email protected] - 30/Mar/2020                       #
###############################################################################
# Importing modules
#################################
import os
import re
import serial
import requests
from time import sleep
import yaml
import json

# Loading config YAML file
#################################
configfile = os.path.join(os.path.dirname(os.path.realpath(__file__)), \
'stadsverwarming-config.yaml')
config = yaml.safe_load(open(configfile))
destination = config['main']['destination']

# Load mqtt and ssl if mqtt is selected
#################################
if destination == 'mqtt':
    import paho.mqtt.client as mqtt
    if 'certificate' in config['mqtt']:
        import ssl

# Declaring variables
#################################
    broker = config['mqtt']['broker']
    port = config['mqtt']['port']
    if 'username' in config['mqtt']:
        username = config['mqtt']['username']
        password = config['mqtt']['password']
    if 'certificate' in config['mqtt']:
        certificate = config['mqtt']['certificate']
        tls_version = config['mqtt']['tls_version']
        tls_insecure = config['mqtt']['tls_insecure']
    topic = config['mqtt']['topic']
    retain = config['mqtt']['retain']

# Function Lees telegram
#################################

conn = serial.Serial('/dev/ttyUSB1',
                     baudrate=300,
                     bytesize=serial.SEVENBITS,
                     parity=serial.PARITY_EVEN,
                     stopbits=serial.STOPBITS_TWO,
                     timeout=1,
                     xonxoff=0,
                     rtscts=0
                     )

# Wake up
conn.setRTS(False)
conn.setDTR(False)
sleep(5)
conn.setDTR(True)
conn.setRTS(True)

# send /?!
conn.write(str.encode("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x2F\x3F\x21\x0D\x0A"))

# Read at 300 BAUD, typenr
print(conn.readline())
print(conn.readline())

# Read at 2400 BAUD, higher might be possible
conn.baudrate=2400

# Read 18 lines (the size of the telegram)
counter = 0
try:
    while counter < 18:
        line=conn.readline().decode('utf-8')
        print(line)

        # This will match on the first line of the telegram with GJ and m3 values.
        matchObj = re.match(r".+6\.8\(([0-9]{4}\.[0-9]{3})\*GJ\)6\.26\(([0-9]{5}\.[0-9]{2})\*m3\)9\.21\(([0-9]{8})\).+", line, re.I|re.S)
        if matchObj:
            kjValue=round(float(matchObj.group(1))*1000)
            m3Value=round(float(matchObj.group(2))*1000)
            print("GJ : " + str(kjValue))
            print("m3: " + str(m3Value))
        counter = counter + 1
finally:
    conn.close()

# Decode and transform new data
###############################
new_energy = str(kjValue)
new_volume = str(m3Value)
new_temp_in = 0  # Looks like this data is not available in heater's datagram
new_temp_out = 0
    
# Updating values
###############################

state = json.dumps({'Energy' : new_energy, \
'Volume' : new_volume, \
'Temperature_in' : new_temp_in, \
'Temperature_out' : new_temp_out})
mqttc = mqtt.Client()
mqttc.connect(broker, port=port)
mqttc.loop_start()
mqttc.publish(topic, state, retain=retain)
mqttc.disconnect()
mqttc.loop_stop()
print("MQTT data published: " +state)
print("Energy: "+str(new_energy))
print("Volume: "+str(new_volume))
print("Temperature in: "+str(new_temp_in))
print("Temperature out: "+str(new_temp_out))

You’re right a python_script can not import anything so that is out. Maybe a command_line sensor paired with an automation will do the trick.

You can do imports with AppDaemon and also install additional python libs. Where was your problem with AppDaemon?

Hi - thanks for responding. Yes I understood that would be possible but thing is I didnt really dive deep into it yet as I was already happy to get it working (alot of copy / paste) on the shell console itself at all! No python gury. Looking at the examples for Appdeamon it looks like the file structure is a little different to “normal” PY files.

I guess I need to investigate this page:
https://appdaemon.readthedocs.io/en/latest/APPGUIDE.html
And see how I can transform the above Python script into a new format to be accepted by Appdaemon and integrate it in the correct way into an daily automation on HA.

AppDaemon is still Python, the code doesn’t need to be in a special format. There’s just some things around it, like you need to setup a class and a configuration file etc. Maybe I’ll take a detailed look at your tonight if I find som e time

I know. But I am wondering if there isn’t an more “easy” way to run the script once a day at a set time without needing to “install” another component. That’s why I hope I can do with a custom component that includes the script and triggers it. Idea is there, now need to understand how to do it. :wink:

Another option is take the approach of a custom integration (with a docker container in the backend) that only runst the script daily or or maybe on request. What about that?

(See example https://www.martinvdm.nl/2020/02/16/measuring-watermeter-with-homeassistant/ )

Hi Tom, I also have this meter and would be great to have a custom component for continuous monitoring, would you consider making one? Thx!

Hi Tom, I have the same problem.
have you found something on it yet?

Hi all, had a busy time moving from ESX TO PROMOX and now I need to find out what changed on Home Assistant as it looks there have been some chnages on the Python side and I am not a guru there. Manually running the script works fine but as Addon (so ass container) it doesnt work.