-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplugin.py
263 lines (222 loc) · 10 KB
/
plugin.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# -*- coding: utf-8 -*-
#
# UniPi Plugin for Domoticz
#
# Manage and monitor your UniPi controller from Domoticz. This plugin imports all available inputs, 1Wire sensors
# and relay outputs.
#
# Communication is done via the UniPi EVOK API. Tested and developed on UniPi Neuron L203.
#
# © 2019 - 2024 January - mccwdev <https://github.com/mccwdev/>
#
"""
<plugin key="UniPi" name="UniPi EVOK" author="mccwdev" version="1.0.1"
wikilink="https://www.domoticz.com/wiki/Using_Python_plugins" externallink="https://github.com/mccwdev/domoticz-unipi">
<description>
<h2>UniPi Plugin</h2><br/>
Manage your UniPi with Domoticz using the Api from EVOK control software
<h3>Features</h3>
<ul style="list-style-type:square">
<li>Import inputs, relays and external sensors</li>
<li>Control relays from Domoticz</li>
<li>Read and log input and external sensor data</li>
</ul>
<h3>Devices</h3>
<ul style="list-style-type:square">
<li>Tested on UniPi Neuron L203</li>
</ul>
</description>
<params>
<param field="Address" label="IP Address" width="200px" required="true" default="127.0.0.1"/>
<param field="Port" label="Port" width="30px" required="true" default="8080"/>
<param field="Mode1" label="Debug" width="75px">
<options>
<option label="True" value="Debug"/>
<option label="False" value="Normal" default="true" />
</options>
</param>
</params>
</plugin>
"""
import json
import requests
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
import Domoticz
TIMEOUT_REQUESTS = 3
UNIPI_DEVICES = { # Tuple with (Name, Type, SubType, SwitchType), Type=0 means not supported
'input': ('Input', 244, 73, 2),
'temp': ('Temp', 80, 5, 0),
'relay': ('Relay', 244, 62, 0),
'ai': ('Analog Input', 243, 8, 0),
'ao': ('Analog Output', 244, 62, 7),
'led': ('ULED', 244, 73, 18),
'wd': ('Watch Dog', 0, 0, 0),
'neuro': ('Evok Devices', 0, 0, 0),
'uart': ('UART Serial Port', 0, 0, 0)
}
class BasePlugin:
enabled = True
unipi_url = ''
def __init__(self):
return
def request(self, url_path, variables=None, method='get'):
url_vars = ''
url = self.unipi_url + url_path
Domoticz.Debug("Url request %s" % url)
resp = None
if method == 'get':
if variables is None:
variables = {}
if variables:
url_vars = '?' + urlencode(variables)
url += url_vars
try:
resp = requests.get(url, timeout=TIMEOUT_REQUESTS)
except Exception as err:
Domoticz.Error("Could not connect to url url %s: %s" % (url, err))
return dict()
elif method == 'post':
resp = requests.post(url, data=variables, timeout=TIMEOUT_REQUESTS)
if not(resp.status_code == 200 or resp.status_code == 201):
Domoticz.Error("Could not connect to url %s, response %d" % (url, resp.status_code))
return dict()
return json.loads(resp.text)
def onStart(self):
self.unipi_url = "http://" + Parameters["Address"] + ":" + Parameters["Port"]
Domoticz.Log("Connect to UniPi EVOK API on URL %s" % self.unipi_url)
if Parameters["Mode1"] == "Debug":
Domoticz.Debugging(1)
if not len(Devices):
dev_id = 1
data = self.request("/rest/all")
for device in data:
unipi_dev_id = device["circuit"]
if device["dev"] not in UNIPI_DEVICES:
Domoticz.Log("Unipi device %s not found in devices definitions" % device["dev"])
continue
dev_tpl = UNIPI_DEVICES[device["dev"]]
if dev_tpl[1] == 0:
Domoticz.Log("Device type %s (%s) not supported" % (device["dev"], unipi_dev_id))
else:
dev_name = dev_tpl[0] + ' ' + unipi_dev_id
Domoticz.Device(Name=dev_name, Unit=dev_id, Type=dev_tpl[1], Subtype=dev_tpl[2],
Switchtype=dev_tpl[3], DeviceID=unipi_dev_id).Create()
dev_id += 1
Domoticz.Heartbeat(2)
return True
def onStop(self):
Domoticz.Log("onStop called")
def onConnect(self, Connection, Status, Description):
Domoticz.Log("onConnect called")
def onMessage(self, Connection, Data):
Domoticz.Log("onMessage called")
def onCommand(self, Unit, Command, Level, Hue):
Domoticz.Log("onCommand called for Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level))
unipi_dev_id = Devices[Unit].DeviceID
value = 0 if Command == 'Off' else 1
Domoticz.Log("Command '%s' for device %s" % (Command, unipi_dev_id))
res = self.request('/rest/relay/' + unipi_dev_id, {"value": value}, method='post')
if 'success' in res and res['success']:
# Domoticz.Log("Command send, response: %s" % res)
UpdateDevice(Unit, value, str(value))
else:
Domoticz.Error("Could not update Relay, response:" % res)
def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile):
Domoticz.Log("Notification: " + Name + "," + Subject + "," + Text + "," + Status + "," + str(Priority) + "," + Sound + "," + ImageFile)
def onDisconnect(self, Connection):
Domoticz.Log("onDisconnect called")
def onHeartbeat(self):
data = self.request("/rest/all")
for device in data:
if device["dev"] not in ["input", "temp", "ai"]:
continue # Skip outputs and unsupported devices
device_id = self.getDeviceID(device['circuit'], device['dev'])
if not device_id:
# Create new temp devices if found, or recreate deleted / newly found or supported devices
# if device["dev"] == 'temp':
dev_list = [id for (id, dev) in Devices.items()]
if dev_list:
device_id = max(dev_list) + 1
else:
device_id = 1
unipi_dev_id = device["circuit"]
dev_tpl = UNIPI_DEVICES[device["dev"]]
if dev_tpl[1] == 0:
Domoticz.Log("Device type %s (%s) not supported" % (device["dev"], unipi_dev_id))
else:
dev_name = dev_tpl[0] + ' ' + unipi_dev_id
Domoticz.Device(Name=dev_name, Unit=device_id, Type=dev_tpl[1], Subtype=dev_tpl[2],
Switchtype=dev_tpl[3], DeviceID=unipi_dev_id).Create()
if device["value"] is None or device["value"] == 'null':
Domoticz.Log("No value from device %s (%s)" % (device['circuit'], device_id))
continue
value_str = str(device["value"])
value_int = int(round(device["value"]))
dev_value_str = Devices[device_id].sValue
if not dev_value_str:
dev_value_str = "0"
if (device['dev'] == 'ai' and round(float(value_str), 2) != round(float(dev_value_str), 2)) or \
(device['dev'] != 'ai' and
value_str != Devices[device_id].sValue or value_int != Devices[device_id].nValue):
UpdateDevice(device_id, value_int, value_str)
# TODO: Update names from Domo to UniPi
def getDeviceID(self, unipi_dev_id, dev_type):
dev_tpl = UNIPI_DEVICES[dev_type]
dev_list = [id for (id, dev) in Devices.items() if dev.DeviceID == unipi_dev_id and dev.Type == dev_tpl[1] and
dev.SubType == dev_tpl[2] and dev.SwitchType == dev_tpl[3]]
if not dev_list:
Domoticz.Log("Device with ID %s not found!" % unipi_dev_id)
return
elif len(dev_list) > 1:
Domoticz.Log("Multiple devices with ID %s found, cannot update!" % unipi_dev_id)
return
return dev_list[0]
_plugin = BasePlugin()
def onStart():
global _plugin
_plugin.onStart()
def onStop():
global _plugin
_plugin.onStop()
def onConnect(Connection, Status, Description):
global _plugin
_plugin.onConnect(Connection, Status, Description)
def onMessage(Connection, Data):
global _plugin
_plugin.onMessage(Connection, Data)
def onCommand(Unit, Command, Level, Hue):
global _plugin
_plugin.onCommand(Unit, Command, Level, Hue)
def onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile):
global _plugin
_plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile)
def onDisconnect(Connection):
global _plugin
_plugin.onDisconnect(Connection)
def onHeartbeat():
global _plugin
_plugin.onHeartbeat()
# Generic helper functions
def DumpConfigToLog():
for x in Parameters:
if Parameters[x] != "":
Domoticz.Debug("'" + x + "':'" + str(Parameters[x]) + "'")
Domoticz.Debug("Device count: " + str(len(Devices)))
for x in Devices:
Domoticz.Debug("Device: " + str(x) + " - " + str(Devices[x]))
Domoticz.Debug("Device ID: '" + str(Devices[x].ID) + "'")
Domoticz.Debug("Device Name: '" + Devices[x].Name + "'")
Domoticz.Debug("Device nValue: " + str(Devices[x].nValue))
Domoticz.Debug("Device sValue: '" + Devices[x].sValue + "'")
Domoticz.Debug("Device LastLevel: " + str(Devices[x].LastLevel))
return
def UpdateDevice(Unit, nValue, sValue=''):
# Make sure that the Domoticz device still exists (they can be deleted) before updating it
if Unit in Devices:
if (Devices[Unit].nValue != nValue) or (Devices[Unit].sValue != sValue):
Devices[Unit].Update(nValue=nValue, sValue=str(sValue))
Domoticz.Log("Update %s, nValue %s / sValue %s" % (Devices[Unit].Name, nValue, sValue))
return