Created
October 3, 2024 13:18
-
-
Save jmb/89b7ac0a5c96735f505ba2868ccb3fd9 to your computer and use it in GitHub Desktop.
Current Cost Serial to EmonCMS data logger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import serial | |
import re | |
import requests | |
import json | |
port = "/dev/ttyUSB0" | |
baudrate = 2400 | |
emon_api_key = "..." | |
emon_api_url = "http://localhost/input/post" | |
emon_node = "currentcost" | |
watts_regex = r"<watts>(\d+)</watts>" | |
ser = serial.Serial() | |
ser.port = port | |
ser.baudrate = baudrate | |
ser.timeout = 3 | |
while True: | |
try: | |
print(f"Connecting to {port}") | |
ser.open() | |
while True: | |
data = ser.readline() | |
print(f"RAW DATA:\n{data}") | |
if data.startswith(b"\x00") and data.endswith(b"\x00"): | |
raise ValueError | |
if b"<watts>" in data: | |
msg = data.decode("ascii", errors="replace") | |
print(f"DECODED:\n{msg}") | |
match = re.search(watts_regex, msg) | |
if match != None: | |
watts = int(match.group(1)) | |
print(f"Watts: {watts}") | |
if watts > 0: | |
fulljson = {'power1':watts} | |
response = requests.post(emon_api_url, | |
data = { | |
'apikey': emon_api_key, | |
'node': emon_node, | |
'fulljson': json.dumps(fulljson) | |
}) | |
print(f"API Response: {response}") | |
except (serial.serialutil.SerialException, ValueError): | |
ser.close() | |
print(f"{port} closed") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment