I did something similar, but I needed different informations.
My goal was to publish two tasmota-like topics every x
minutes with STATE
and SENSOR
json
s.
tele/p2p_server/LWT Online
tele/p2p_server/STATE {"Time":"2020-04-29T18:53:15","Uptime":"54T21:04:37","CPULoad":2.7,"MemoryTotal":926.1,"MemoryAvailable":512.4,"MemoryPercent":44.7,"DiskTotal":77.8,"DiskFree":48.7,"DiskPercent":34.0,"POWER":"ON"}
tele/p2p_server/SENSOR {"Time":"2020-04-29T18:53:15","AMULE":{"Upload":25.01,"Download":0.0},"TRANSMISSION":{"Upload":0.0,"Download":0.0}}
My script once started will loop forever and publishes an LWT topic to share the availability. You can easily convert it into a service and manage it with systemctl
command.
Here is the code I used:
#!/usr/bin/python3
import os
import re
import time
from datetime import datetime
import paho.mqtt.client as mqtt
import psutil
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("tele/p2p_server/#")
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
def time_now():
data_now_obj = datetime.now()
data_now_str = data_now_obj.strftime("%Y-%m-%dT%H:%M:%S")
return (data_now_str.strip())
def uptime():
data_now_obj = datetime.now()
data_now_str = data_now_obj.strftime("%Y-%m-%dT%H:%M:%S")
data_uptime_str = os.popen("uptime -s").readline().strip()
data_uptime_obj = datetime.strptime(data_uptime_str,"%Y-%m-%d %H:%M:%S")
uptime_obj = data_now_obj - data_uptime_obj
uptime_str = "%dT%02d:%02d:%02d" % (uptime_obj.days, (uptime_obj.seconds // 3600), (uptime_obj.seconds % 3600 // 60), (uptime_obj.seconds % 60))
return (uptime_str.strip())
def load():
cpu = psutil.cpu_percent(interval=None)
mem = psutil.virtual_memory()
disk = psutil.disk_usage('/mnt/usbdisk')
temp = "\"CPULoad\":%s,\"MemoryTotal\":%s,\"MemoryAvailable\":%s,\"MemoryPercent\":%s,\"DiskTotal\":%s,\"DiskFree\":%s,\"DiskPercent\":%s" % (cpu,(round(mem.total / 1048576,1)),(round(mem.available / 1048576,1)),mem.percent,(round(disk.total / 1073741824,1)),(round(disk.free / 1073741824,1)),disk.percent)
return (temp)
def transmission():
temp = os.popen("transmission-remote -n transmission:frigor -l|grep ^Sum:").readline()
return (re.sub(r'^.*(\d+\.\d+)\s+(\d+\.\d+)$', r'"TRANSMISSION":{"Upload":\1,"Download":\2}', temp.strip()))
def amule():
dlstr = 0
upstr = 0
temp = os.popen("amulecmd -P frigor -p 4713 -c 'status'").read()
for item in temp.split("\n"):
if "Download" in item:
dlstr = re.sub(r'^.+\s(\d+\S*).*$', r'\1', item.strip())
if "bytes" in item:
dlstr = round(eval('float(dlstr)/1024'),1)
elif "Upload" in item:
upstr = re.sub(r'^.+\s(\d+\S*).*$', r'\1', item.strip())
if "bytes" in item:
upstr = round(eval('float(upstr)/1024'),1)
temp = "\"AMULE\":{\"Upload\":%s,\"Download\":%s}" % (upstr, dlstr)
return (temp)
qos=0
retain=True
topic_id="YOUR_TOPIC"
client=mqtt.Client(topic_id)
client.username_pw_set("USERNAME", password="SECRET_PWD")
topic = "tele/%s/LWT" % topic_id
payload = "Offline"
client.will_set(topic, payload, qos, retain)
client.reconnect_delay_set(min_delay=1, max_delay=120)
client.connect("IP_ADDRESS", 1883, 60)
payload = "Online"
client.publish(topic, payload, qos, retain)
#client.loop_forever()
while True:
retain=False
topic = "tele/%s/STATE" % topic_id
payload = "{\"Time\":\"%s\",\"Uptime\":\"%s\",%s,\"POWER\":\"ON\"}" % (time_now(),uptime(),load())
client.publish(topic, payload, qos, retain)
topic = "tele/%s/SENSOR" % topic_id
payload = "{\"Time\":\"%s\",%s,%s}" % (time_now(),amule(),transmission())
client.publish(topic, payload, qos, retain)
time.sleep(60)