-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.py
More file actions
262 lines (225 loc) · 8.14 KB
/
plugin.py
File metadata and controls
262 lines (225 loc) · 8.14 KB
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
# Awox SmartPlug Plugin
#
# Author: zaraki673, 2017
#
# source : https://github.com/sourceperl/smartplugctl
#
#install bluepy first (https://github.com/IanHarvey/bluepy - install it from source)
#then you should need to make a symlink : sudo ln -s /usr/local/lib/python3.5/dist-packages/bluepy /usr/lib/python3.5/
#
"""
<plugin key="AwoxSMP" name="Awox SmartPlug" author="zaraki673" version="1.0.2" wikilink="https://github.com/sasu-drooz/Domoticz-AwoxSMP" externallink="http://www.awox.com/awox_product/smartplug/4/">
<params>
<param field="Address" label="MAC Address" width="150px" required="true"/>
<param field="Mode6" label="Debug" width="75px">
<options>
<option label="True" value="Debug"/>
<option label="False" value="Normal" default="true" />
</options>
</param>
</params>
</plugin>
"""
import Domoticz
import binascii
import struct
import lib.pySmartPlugSmpB16
from bluepy import btle
START_OF_MESSAGE = b'\x0f'
END_OF_MESSAGE = b'\xff\xff'
SMPstate = 0
SMPconso = 0
class BasePlugin:
enabled = False
pluginState = "Not Ready"
sessionCookie = ""
privateKey = b""
socketOn = "FALSE"
def __init__(self):
return
def onStart(self):
global SMPstate, SMPconso
if Parameters["Mode6"] == "Debug":
Domoticz.Debugging(1)
if (len(Devices) == 0):
Domoticz.Device(Name="Status", Unit=1, Type=17, Switchtype=0).Create()
Domoticz.Device(Name="Conso", Unit=2, TypeName="Usage").Create()
Domoticz.Log("Devices created.")
else:
if (1 in Devices): SMPstate = Devices[1].nValue
if (2 in Devices): SMPconso = Devices[2].nValue
DumpConfigToLog()
Domoticz.Log("Plugin is started.")
Domoticz.Heartbeat(20)
def onStop(self):
Domoticz.Log("Plugin is stopping.")
def onConnect(self, Connection, Status, Description):
return
def onMessage(self, Connection, Data):
return
def onCommand(self, Unit, Command, Level, Hue):
Domoticz.Debug("onCommand called for Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level))
Command = Command.strip()
action, sep, params = Command.partition(' ')
action = action.capitalize()
if (action == 'On'):
try:
plug = SmartPlug(Parameters["Address"])
plug.on()
UpdateDevice(1,1,'On')
plug.disconnect()
except btle.BTLEException as err:
Domoticz.Log('error when setting plug %s on (code %d)' % (Parameters["Address"], err.code))
elif (action == 'Off'):
try:
plug = SmartPlug(Parameters["Address"])
plug.off()
UpdateDevice(1,0,'Off')
plug.disconnect()
except btle.BTLEException as err:
Domoticz.Log('error when setting plug %s on (code %d)' % (Parameters["Address"], err.code))
return True
def onDisconnect(self, Connection):
return
def onHeartbeat(self):
global SMPstate, SMPconso
try:
plug = SmartPlug(Parameters["Address"])
(SMPstate, SMPconso) = plug.status_request()
plug.disconnect()
SMPstate = 'on' if SMPstate else 'off'
Domoticz.Log('plug state = %s' % SMPstate)
if (SMPstate == 'off'): UpdateDevice(1,0,'Off')
else: UpdateDevice(1,1,'On')
Domoticz.Log('plug power = %d W' % SMPconso)
UpdateDevice(2,0,str(SMPconso))
except btle.BTLEException as err:
Domoticz.Log('error when requesting stat to plug %s (code %d)' % (Parameters["Address"], err.code))
return True
def SetSocketSettings(self, power):
return
def GetSocketSettings(self):
return
def genericPOST(self, commandName):
return
global _plugin
_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(Data):
global _plugin
_plugin.onNotification(Data)
def onDisconnect(Connection):
global _plugin
_plugin.onDisconnect(Connection)
def onHeartbeat():
global _plugin
_plugin.onHeartbeat()
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, str(sValue))
Domoticz.Log("Update "+str(nValue)+":'"+str(sValue)+"' ("+Devices[Unit].Name+")")
return
# 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
class SmartPlug(btle.Peripheral):
def __init__(self, addr):
btle.Peripheral.__init__(self, addr)
self.delegate = NotificationDelegate()
self.setDelegate(self.delegate)
self.plug_svc = self.getServiceByUUID('0000fff0-0000-1000-8000-00805f9b34fb')
self.plug_cmd_ch = self.plug_svc.getCharacteristics('0000fff3-0000-1000-8000-00805f9b34fb')[0]
def on(self):
self.delegate.chg_is_ok = False
self.plug_cmd_ch.write(self.get_buffer(binascii.unhexlify('0300010000')))
self.wait_data(0.5)
return self.delegate.chg_is_ok
def off(self):
self.delegate.chg_is_ok = False
self.plug_cmd_ch.write(self.get_buffer(binascii.unhexlify('0300000000')))
self.wait_data(0.5)
return self.delegate.chg_is_ok
def status_request(self):
self.plug_cmd_ch.write(self.get_buffer(binascii.unhexlify('04000000')))
self.wait_data(2.0)
return self.delegate.state, self.delegate.power
def program_request(self):
self.plug_cmd_ch.write(self.get_buffer(binascii.unhexlify('07000000')))
self.wait_data(2.0)
return self.delegate.programs
def calculate_checksum(self, message):
return (sum(bytearray(message)) + 1) & 0xff
def get_buffer(self, message):
return START_OF_MESSAGE + struct.pack("b",len(message) + 1) + message + struct.pack("b",self.calculate_checksum(message)) + END_OF_MESSAGE
def wait_data(self, timeout):
self.delegate.need_data = True
while self.delegate.need_data and self.waitForNotifications(timeout):
pass
class NotificationDelegate(btle.DefaultDelegate):
def __init__(self):
btle.DefaultDelegate.__init__(self)
self.state = False
self.power = 0
self.chg_is_ok = False
self.programs = []
self._buffer = b''
self.need_data = True
def handleNotification(self, cHandle, data):
#not sure 0x0f indicate begin of buffer but
if data[:1] == START_OF_MESSAGE:
self._buffer = data
else:
self._buffer = self._buffer + data
if self._buffer[-2:] == END_OF_MESSAGE:
self.handle_data(self._buffer)
self._buffer = b''
self.need_data = False
def handle_data(self, bytes_data):
# it's a state change confirm notification ?
if bytes_data[0:3] == b'\x0f\x04\x03':
self.chg_is_ok = True
# it's a state/power notification ?
if bytes_data[0:3] == b'\x0f\x0f\x04':
(state, dummy, power) = struct.unpack_from(">?BI", bytes_data, offset=4)
self.state = state
self.power = power / 1000
# it's a 0x0a notif ?
if bytes_data[0:3] == b'\x0f\x33\x0a':
print ("0A notif %s" % bytes_data)
# it's a programs notif ?
if bytes_data[0:3] == b'\x0f\x71\x07' :
program_offset = 4
self.programs = []
while program_offset + 21 < len(bytes_data):
(present, name, flags, start_hour, start_minute, end_hour, end_minute) = struct.unpack_from(">?16sbbbbb", bytes_data, program_offset)
#TODO interpret flags (day of program ?)
if present:
self.programs.append({ "name" : name.decode('iso-8859-1').strip('\0'), "flags":flags, "start":"{0:02d}:{1:02d}".format(start_hour, start_minute), "end":"{0:02d}:{1:02d}".format(end_hour, end_minute)})
program_offset += 22