-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvoltwerk2mqtt.py
executable file
·147 lines (116 loc) · 4.08 KB
/
voltwerk2mqtt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env python3
'''
start CAN bus with
ip link set can0 up type can bitrate 125000
'''
import can
import sys, os
import logging
from logging.handlers import RotatingFileHandler
from time import sleep
import paho.mqtt.client as mqtt
from signal import *
Broker_Address = '192.168.168.112' # change to your own broker ip or url
Mqtt_Prefix = 'iot/pv/voltwerk'
Topics = {
'current':'iot/pv/voltwerk/ac_current_A',
'voltage':'iot/pv/voltwerk/ac_voltage_V',
'power':'iot/pv/voltwerk/ac_active_power_kW',
'freq':'iot/pv/voltwerk/grid_frequency_Hz',
'status':'iot/pv/voltwerk/service',
}
Subscriptions = {}
requests = [can.Message(arbitration_id=0x0f89c101, dlc=1, data=[0x20]),
can.Message(arbitration_id=0x0f8a0101, dlc=1, data=[0x20]),
can.Message(arbitration_id=0x0f8a4101, dlc=1, data=[0x20]),
can.Message(arbitration_id=0x0f890101, dlc=1, data=[0x20])]
request_count = 0
def on_disconnect(client, userdata, rc):
logging.info("MQTT disconnected")
if rc != 0:
logging.error(f"Unexpected MQTT disconnect rc={rc}. Will auto-reconnect")
print('Unexpected MQTT disconnect. Will auto-reconnect')
try:
client.connect(Broker_Address)
except Exception as e:
logging.error("Failed to Reconnect to " + Broker_Address + " " + str(e))
print("Failed to Reconnect to " + Broker_Address + " " + str(e))
sys.exit(2)
def on_connect(client, userdata, flags, rc):
if rc == 0:
logging.info("Connected to MQTT Broker " + Broker_Address)
for topic in Subscriptions.values():
print("subcribe to " + topic)
client.subscribe(topic)
client.publish(Topics['status'], 'online')
else:
logging.error("Failed to connect, return code %d\n", rc)
sys.exit(3)
def on_message(client, userdata, msg):
try:
pass #we don't expect messages yet
except Exception as e:
logging.warning("Message parsing error " + str(e))
print(e)
client = mqtt.Client('Voltwerk2Mqtt')
client.on_disconnect = on_disconnect
client.on_connect = on_connect
client.on_message = on_message
def go_offline(*args):
client.publish(Topics['status'], 'offline')
client.disconnect()
logging.info("Disconnect")
sys.exit(0)
try:
for sig in (SIGABRT, SIGINT, SIGTERM):
signal(sig, go_offline)
logging.basicConfig(format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO,
handlers=[
RotatingFileHandler("/opt/voltwerk2mqtt/log", maxBytes=100000, backupCount=2),
logging.StreamHandler()
])
client.connect(Broker_Address) # connect to broker
client.will_set(Topics['status'], 'offline', qos=1, retain=True)
client.loop_start()
logging.info("Start Voltwerk2MQTT service")
with can.interface.Bus(channel='can0', interface="socketcan", bitrate=125000) as bus:
while True:
sleep(0.25)
bus.send(requests[request_count])
request_count = (request_count + 1) % len(requests)
multiplier = 1
topic = ''
for msg in bus:
if msg.arbitration_id == 0x0f0a4082:
multiplier = 4
topic = 'power'
elif msg.arbitration_id == 0x0f0a0082:
multiplier = 16
topic = 'current'
elif msg.arbitration_id == 0x0f09c082:
multiplier = 256
topic = 'voltage'
elif msg.arbitration_id == 0x0f090082:
multiplier = 64
topic = 'freq'
if len(topic)==0 or len(msg.data)<2:
break
data = bytearray(msg.data)
# to little endian
data[0], data[1] = data[1], data[0]
dataBin = data[0]<<8 | data[1]
if dataBin&0x8000>0:
dataBin = ((~dataBin) & 0x7fff) + 1
data = -(dataBin/0x2000) * multiplier
else:
dataBin = dataBin & 0x7fff
data = (dataBin/0x2000) * multiplier
client.publish(Topics[topic],f'{data}')
break
except Exception as e:
logging.error("Error: ", exc_info=e)
finally:
client.publish(Topics['status'], 'offline')
sys.exit(1)