-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpyinsteon.py
754 lines (578 loc) · 36.6 KB
/
pyinsteon.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
'''
File:
pyinsteon.py
Description:
InsteonPLM Home Automation Protocol library for Python (Smarthome 2412N, 2412S, 2412U)
For more information regarding the technical details of the PLM:
http://www.smarthome.com/manuals/2412sdevguide.pdf
Author(s):
Pyjamasam@github <>
Jason Sharpee <[email protected]> http://www.sharpee.com
Based loosely on the Insteon_PLM.pm code:
- Expanded by Gregg Liming <[email protected]>
License:
This free software is licensed under the terms of the GNU public license, Version 1
Usage:
- Instantiate InsteonPLM by passing in an interface
- Call its methods
- ?
- Profit
Example: (see bottom of PyInsteon.py file)
Notes:
- Supports both 2412N and 2412S right now
-
- Todo: Read Style Guide @: http://www.python.org/dev/peps/pep-0008/
Created on Mar 26, 2011
'''
import select
import traceback
import threading
import time
import binascii
import struct
import sys
import string
import hashlib
from collections import deque
from ha_common import *
import serial
def _byteIdToStringId(idHigh, idMid, idLow):
return '%02X.%02X.%02X' % (idHigh, idMid, idLow)
def _cleanStringId(stringId):
return stringId[0:2] + stringId[3:5] + stringId[6:8]
def _stringIdToByteIds(stringId):
return binascii.unhexlify(_cleanStringId(stringId))
def _buildFlags():
#todo: impliment this
return '\x0f'
def hashPacket(packetData):
return hashlib.md5(packetData).hexdigest()
def simpleMap(value, in_min, in_max, out_min, out_max):
#stolen from the arduino implimentation. I am sure there is a nice python way to do it, but I have yet to stublem across it
return (float(value) - float(in_min)) * (float(out_max) - float(out_min)) / (float(in_max) - float(in_min)) + float(out_min);
class InsteonPLM(HAInterface):
def __init__(self, interface):
super(InsteonPLM, self).__init__(interface)
self.__modemCommands = {'60': {
'responseSize':7,
'callBack':self.__process_PLMInfo
},
'62': {
'responseSize':7,
'callBack':self.__process_StandardInsteonMessagePLMEcho
},
'50': {
'responseSize':9,
'callBack':self.__process_InboundStandardInsteonMessage
},
'51': {
'responseSize':23,
'callBack':self.__process_InboundExtendedInsteonMessage
},
'63': {
'responseSize':4,
'callBack':self.__process_StandardX10MessagePLMEcho
},
'52': {
'responseSize':4,
'callBack':self.__process_InboundX10Message
},
}
self.__insteonCommands = {
#Direct Messages/Responses
'SD03': { #Product Data Request (generally an Ack)
'callBack' : self.__handle_StandardDirect_IgnoreAck
},
'SD0D': { #Get InsteonPLM Engine
'callBack' : self.__handle_StandardDirect_EngineResponse,
'validResponseCommands' : ['SD0D']
},
'SD0F': { #Ping Device
'callBack' : self.__handle_StandardDirect_AckCompletesCommand,
'validResponseCommands' : ['SD0F']
},
'SD10': { #ID Request (generally an Ack)
'callBack' : self.__handle_StandardDirect_IgnoreAck,
'validResponseCommands' : ['SD10', 'SB01']
},
'SD11': { #Devce On
'callBack' : self.__handle_StandardDirect_AckCompletesCommand,
'validResponseCommands' : ['SD11']
},
'SD12': { #Devce On Fast
'callBack' : self.__handle_StandardDirect_AckCompletesCommand,
'validResponseCommands' : ['SD12']
},
'SD13': { #Devce Off
'callBack' : self.__handle_StandardDirect_AckCompletesCommand,
'validResponseCommands' : ['SD13']
},
'SD14': { #Devce Off Fast
'callBack' : self.__handle_StandardDirect_AckCompletesCommand,
'validResponseCommands' : ['SD14']
},
'SD15': { #Brighten one step
'callBack' : self.__handle_StandardDirect_AckCompletesCommand,
'validResponseCommands' : ['SD15']
},
'SD16': { #Dim one step
'callBack' : self.__handle_StandardDirect_AckCompletesCommand,
'validResponseCommands' : ['SD16']
},
'SD19': { #Light Status Response
'callBack' : self.__handle_StandardDirect_LightStatusResponse,
'validResponseCommands' : ['SD19']
},
#Broadcast Messages/Responses
'SB01': {
#Set button pushed
'callBack' : self.__handle_StandardBroadcast_SetButtonPressed
},
}
self.__x10HouseCodes = Lookup(zip((
'm',
'e',
'c',
'k',
'o',
'g',
'a',
'i',
'n',
'f',
'd',
'l',
'p',
'h',
'n',
'j' ),xrange(0x0, 0xF)))
self.__x10UnitCodes = Lookup(zip((
'13',
'5',
'3',
'11',
'15',
'7',
'1',
'9',
'14',
'6',
'4',
'12',
'16',
'8',
'2',
'10'
),xrange(0x0,0xF)))
self._allLinkDatabase = dict()
self.__shutdownEvent = threading.Event()
self.__interfaceRunningEvent = threading.Event()
self.__commandLock = threading.Lock()
self.__outboundQueue = deque()
self.__outboundCommandDetails = dict()
self.__retryCount = dict()
self.__pendingCommandDetails = dict()
self.__commandReturnData = dict()
self.__intersend_delay = 0.15 #150 ms between network sends
self.__lastSendTime = 0
# print "Using %s for PLM communication" % serialDevicePath
# self.__serialDevice = serial.Serial(serialDevicePath, 19200, timeout = 0.1)
self.__interface = interface
def shutdown(self):
if self.__interfaceRunningEvent.isSet():
self.__shutdownEvent.set()
#wait 2 seconds for the interface to shut down
self.__interfaceRunningEvent.wait(2000)
def run(self):
self.__interfaceRunningEvent.set();
#for checking for duplicate messages received in a row
lastPacketHash = None
while not self.__shutdownEvent.isSet():
#check to see if there are any outbound messages to deal with
self.__commandLock.acquire()
if (len(self.__outboundQueue) > 0) and (time.time() - self.__lastSendTime > self.__intersend_delay):
commandHash = self.__outboundQueue.popleft()
commandExecutionDetails = self.__outboundCommandDetails[commandHash]
bytesToSend = commandExecutionDetails['bytesToSend']
print "> ", hex_dump(bytesToSend, len(bytesToSend)),
self.__interface.write(bytesToSend)
self.__pendingCommandDetails[commandHash] = commandExecutionDetails
del self.__outboundCommandDetails[commandHash]
self.__lastSendTime = time.time()
self.__commandLock.release()
#check to see if there is anyting we need to read
firstByte = self.__interface.read(1)
if len(firstByte) == 1:
#got at least one byte. Check to see what kind of byte it is (helps us sort out how many bytes we need to read now)
if firstByte[0] == '\x02':
#modem command (could be an echo or a response)
#read another byte to sort that out
secondByte = self.__interface.read(1)
responseSize = -1
callBack = None
modemCommand = binascii.hexlify(secondByte).upper()
if self.__modemCommands.has_key(modemCommand):
if self.__modemCommands[modemCommand].has_key('responseSize'):
responseSize = self.__modemCommands[modemCommand]['responseSize']
if self.__modemCommands[modemCommand].has_key('callBack'):
callBack = self.__modemCommands[modemCommand]['callBack']
if responseSize != -1:
remainingBytes = self.__interface.read(responseSize)
print "< ",
print hex_dump(firstByte + secondByte + remainingBytes, len(firstByte + secondByte + remainingBytes)),
currentPacketHash = hashPacket(firstByte + secondByte + remainingBytes)
if lastPacketHash and lastPacketHash == currentPacketHash:
#duplicate packet. Ignore
pass
else:
if callBack:
callBack(firstByte + secondByte + remainingBytes)
else:
print "No callBack defined for for modem command %s" % modemCommand
lastPacketHash = currentPacketHash
else:
print "No responseSize defined for modem command %s" % modemCommand
elif firstByte[0] == '\x15':
print "Received a Modem NAK!"
else:
print "Unknown first byte %s" % binascii.hexlify(firstByte[0])
else:
#print "Sleeping"
#X10 is slow. Need to adjust based on protocol sent. Or pay attention to NAK and auto adjust
#time.sleep(0.1)
time.sleep(0.5)
self.__interfaceRunningEvent.clear()
def __sendModemCommand(self, modemCommand, commandDataString = None, extraCommandDetails = None):
returnValue = False
try:
bytesToSend = '\x02' + binascii.unhexlify(modemCommand)
if commandDataString != None:
bytesToSend += commandDataString
commandHash = hashPacket(bytesToSend)
self.__commandLock.acquire()
if self.__outboundCommandDetails.has_key(commandHash):
#duplicate command. Ignore
pass
else:
waitEvent = threading.Event()
basicCommandDetails = { 'bytesToSend': bytesToSend, 'waitEvent': waitEvent, 'modemCommand': modemCommand }
if extraCommandDetails != None:
basicCommandDetails = dict(basicCommandDetails.items() + extraCommandDetails.items())
self.__outboundCommandDetails[commandHash] = basicCommandDetails
self.__outboundQueue.append(commandHash)
self.__retryCount[commandHash] = 0
print "Queued %s" % commandHash
returnValue = {'commandHash': commandHash, 'waitEvent': waitEvent}
self.__commandLock.release()
except Exception, ex:
print traceback.format_exc()
finally:
#ensure that we unlock the thread lock
#the code below will ensure that we have a valid lock before we call release
self.__commandLock.acquire(False)
self.__commandLock.release()
return returnValue
def __sendStandardP2PInsteonCommand(self, destinationDevice, commandId1, commandId2):
print "Command: %s %s %s" % (destinationDevice, commandId1, commandId2)
return self.__sendModemCommand('62', _stringIdToByteIds(destinationDevice) + _buildFlags() + binascii.unhexlify(commandId1) + binascii.unhexlify(commandId2), extraCommandDetails = { 'destinationDevice': destinationDevice, 'commandId1': 'SD' + commandId1, 'commandId2': commandId2})
def __getX10UnitCommand(self,deviceId):
"Send just an X10 unit code message"
deviceId = deviceId.lower()
return "%02x00" % ((self.__x10HouseCodes[deviceId[0:1]] << 4) | self.__x10UnitCodes[deviceId[1:2]])
def __getX10CommandCommand(self,deviceId,commandCode):
"Send just an X10 command code message"
deviceId = deviceId.lower()
return "%02x80" % ((self.__x10HouseCodes[deviceId[0:1]] << 4) | int(commandCode,16))
def __sendStandardP2PX10Command(self,destinationDevice,commandId1, commandId2 = None):
# X10 sends 1 complete message in two commands
print "Command: %s %s %s" % (destinationDevice, commandId1, commandId2)
print "C: %s" % self.__getX10UnitCommand(destinationDevice)
print "c1: %s" % self.__getX10CommandCommand(destinationDevice, commandId1)
self.__sendModemCommand('63', binascii.unhexlify(self.__getX10UnitCommand(destinationDevice)))
return self.__sendModemCommand('63', binascii.unhexlify(self.__getX10CommandCommand(destinationDevice, commandId1)))
def __waitForCommandToFinish(self, commandExecutionDetails, timeout = None):
if type(commandExecutionDetails) != type(dict()):
print "Unable to wait without a valid commandExecutionDetails parameter"
return False
waitEvent = commandExecutionDetails['waitEvent']
commandHash = commandExecutionDetails['commandHash']
realTimeout = 2 #default timeout of 2 seconds
if timeout:
realTimeout = timeout
timeoutOccured = False
if sys.version_info[:2] > (2,6):
#python 2.7 and above waits correctly on events
timeoutOccured = not waitEvent.wait(realTimeout)
else:
#< then python 2.7 and we need to do the waiting manually
while not waitEvent.isSet() and realTimeout > 0:
time.sleep(0.1)
realTimeout -= 0.1
if realTimeout == 0:
timeoutOccured = True
if not timeoutOccured:
if self.__commandReturnData.has_key(commandHash):
return self.__commandReturnData[commandHash]
else:
return True
else:
#re-queue the command to try again
self.__commandLock.acquire()
if self.__retryCount[commandHash] >= 5:
#too many retries. Bail out
self.__commandLock.release()
return False
print "Timed out for %s - Requeueing (already had %d retries)" % (commandHash, self.__retryCount[commandHash])
requiresRetry = True
if self.__pendingCommandDetails.has_key(commandHash):
self.__outboundCommandDetails[commandHash] = self.__pendingCommandDetails[commandHash]
del self.__pendingCommandDetails[commandHash]
self.__outboundQueue.append(commandHash)
self.__retryCount[commandHash] += 1
else:
print "Interesting. timed out for %s, but there is no pending command details" % commandHash
#to prevent a huge loop here we bail out
requiresRetry = False
self.__commandLock.release()
if requiresRetry:
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
else:
return False
#low level processing methods
def __process_PLMInfo(self, responseBytes):
(modemCommand, idHigh, idMid, idLow, deviceCat, deviceSubCat, firmwareVer, acknak) = struct.unpack('xBBBBBBBB', responseBytes)
foundCommandHash = None
#find our pending command in the list so we can say that we're done (if we are running in syncronous mode - if not well then the caller didn't care)
for (commandHash, commandDetails) in self.__pendingCommandDetails.items():
if binascii.unhexlify(commandDetails['modemCommand']) == chr(modemCommand):
#Looks like this is our command. Lets deal with it.
self.__commandReturnData[commandHash] = { 'id': _byteIdToStringId(idHigh,idMid,idLow), 'deviceCategory': '%02X' % deviceCat, 'deviceSubCategory': '%02X' % deviceSubCat, 'firmwareVersion': '%02X' % firmwareVer }
waitEvent = commandDetails['waitEvent']
waitEvent.set()
foundCommandHash = commandHash
break
if foundCommandHash:
del self.__pendingCommandDetails[foundCommandHash]
else:
print "Unable to find pending command details for the following packet:"
print hex_dump(responseBytes, len(responseBytes))
def __process_StandardInsteonMessagePLMEcho(self, responseBytes):
#print utilities.hex_dump(responseBytes, len(responseBytes))
#we don't do anything here. Just eat the echoed bytes
pass
def __process_StandardX10MessagePLMEcho(self, responseBytes):
# Just ack / error echo from sending an X10 command
pass
def __validResponseMessagesForCommandId(self, commandId):
if self.__insteonCommands.has_key(commandId):
commandInfo = self.__insteonCommands[commandId]
if commandInfo.has_key('validResponseCommands'):
return commandInfo['validResponseCommands']
return False
def __process_InboundStandardInsteonMessage(self, responseBytes):
(insteonCommand, fromIdHigh, fromIdMid, fromIdLow, toIdHigh, toIdMid, toIdLow, messageFlags, command1, command2) = struct.unpack('xBBBBBBBBBB', responseBytes)
foundCommandHash = None
waitEvent = None
#check to see what kind of message this was (based on message flags)
isBroadcast = messageFlags & (1 << 7) == (1 << 7)
isDirect = not isBroadcast
isAck = messageFlags & (1 << 5) == (1 << 5)
isNak = isAck and isBroadcast
insteonCommandCode = "%02X" % command1
if isBroadcast:
#standard broadcast
insteonCommandCode = 'SB' + insteonCommandCode
else:
#standard direct
insteonCommandCode = 'SD' + insteonCommandCode
if insteonCommandCode == 'SD00':
#this is a strange special case...
#lightStatusRequest returns a standard message and overwrites the cmd1 and cmd2 bytes with "data"
#cmd1 (that we use here to sort out what kind of incoming message we got) contains an
#"ALL-Link Database Delta number that increments every time there is a change in the addressee's ALL-Link Database"
#which makes is super hard to deal with this response (cause cmd1 can likley change)
#for now my testing has show that its 0 (at least with my dimmer switch - my guess is cause I haven't linked it with anything)
#so we treat the SD00 message special and pretend its really a SD19 message (and that works fine for now cause we only really
#care about cmd2 - as it has our light status in it)
insteonCommandCode = 'SD19'
#print insteonCommandCode
#find our pending command in the list so we can say that we're done (if we are running in syncronous mode - if not well then the caller didn't care)
for (commandHash, commandDetails) in self.__pendingCommandDetails.items():
#since this was a standard insteon message the modem command used to send it was a 0x62 so we check for that
if binascii.unhexlify(commandDetails['modemCommand']) == '\x62':
originatingCommandId1 = None
if commandDetails.has_key('commandId1'):
originatingCommandId1 = commandDetails['commandId1']
validResponseMessages = self.__validResponseMessagesForCommandId(originatingCommandId1)
if validResponseMessages and len(validResponseMessages):
#Check to see if this received command is one that this pending command is waiting for
if validResponseMessages.count(insteonCommandCode) == 0:
#this pending command isn't waiting for a response with this command code... Move along
continue
else:
print "Unable to find a list of valid response messages for command %s" % originatingCommandId1
continue
#since there could be multiple insteon messages flying out over the wire, check to see if this one is from the device we send this command to
destDeviceId = None
if commandDetails.has_key('destinationDevice'):
destDeviceId = commandDetails['destinationDevice']
if destDeviceId:
if destDeviceId == _byteIdToStringId(fromIdHigh, fromIdMid, fromIdLow):
returnData = {} #{'isBroadcast': isBroadcast, 'isDirect': isDirect, 'isAck': isAck}
#try and look up a handler for this command code
if self.__insteonCommands.has_key(insteonCommandCode):
if self.__insteonCommands[insteonCommandCode].has_key('callBack'):
(requestCycleDone, extraReturnData) = self.__insteonCommands[insteonCommandCode]['callBack'](responseBytes)
if extraReturnData:
returnData = dict(returnData.items() + extraReturnData.items())
if requestCycleDone:
waitEvent = commandDetails['waitEvent']
else:
print "No callBack for insteon command code %s" % insteonCommandCode
else:
print "No insteonCommand lookup defined for insteon command code %s" % insteonCommandCode
if len(returnData):
self.__commandReturnData[commandHash] = returnData
foundCommandHash = commandHash
break
if foundCommandHash == None:
print "Unhandled packet (couldn't find any pending command to deal with it)"
print "This could be an unsolocicited broadcast message"
if waitEvent and foundCommandHash:
waitEvent.set()
del self.__pendingCommandDetails[foundCommandHash]
print "Command %s completed" % foundCommandHash
def __process_InboundExtendedInsteonMessage(self, responseBytes):
#51
#17 C4 4A from
#18 BA 62 to
#50 flags
#FF cmd1
#C0 cmd2
#02 90 00 00 00 00 00 00 00 00 00 00 00 00 data
(insteonCommand, fromIdHigh, fromIdMid, fromIdLow, toIdHigh, toIdMid, toIdLow, messageFlags, command1, command2, data) = struct.unpack('xBBBBBBBBBB14s', responseBytes)
pass
def __process_InboundX10Message(self, responseBytes):
"Receive Handler for X10 Data"
#X10 sends commands fully in two separate messages. Not sure how to handle this yet
#TODO not implemented
unitCode = None
commandCode = None
print "X10> ", hex_dump(responseBytes, len(responseBytes)),
# (insteonCommand, fromIdHigh, fromIdMid, fromIdLow, toIdHigh, toIdMid, toIdLow, messageFlags, command1, command2) = struct.unpack('xBBBBBBBBBB', responseBytes)
# houseCode = (int(responseBytes[4:6],16) & 0b11110000) >> 4
# houseCodeDec = X10_House_Codes.get_key(houseCode)
# keyCode = (int(responseBytes[4:6],16) & 0b00001111)
# flag = int(responseBytes[6:8],16)
#insteon message handlers
def __handle_StandardDirect_IgnoreAck(self, messageBytes):
#just ignore the ack for what ever command triggered us
#there is most likley more data coming for what ever command we are handling
return (False, None)
def __handle_StandardDirect_AckCompletesCommand(self, messageBytes):
#the ack for our command completes things. So let the system know so
return (True, None)
def __handle_StandardBroadcast_SetButtonPressed(self, messageBytes):
#02 50 17 C4 4A 01 19 38 8B 01 00
(idHigh, idMid, idLow, deviceCat, deviceSubCat, deviceRevision) = struct.unpack('xxBBBBBBxxx', messageBytes)
return (True, {'deviceType': '%02X%02X' % (deviceCat, deviceSubCat), 'deviceRevision':'%02X' % deviceRevision})
def __handle_StandardDirect_EngineResponse(self, messageBytes):
#02 50 17 C4 4A 18 BA 62 2B 0D 01
engineVersionIdentifier = messageBytes[10]
return (True, {'engineVersion': engineVersionIdentifier == '\x01' and 'i2' or 'i1'})
def __handle_StandardDirect_LightStatusResponse(self, messageBytes):
#02 50 17 C4 4A 18 BA 62 2B 00 00
lightLevelRaw = messageBytes[10]
#map the lightLevelRaw value to a sane value between 0 and 1
normalizedLightLevel = simpleMap(ord(lightLevelRaw), 0, 255, 0, 1)
return (True, {'lightStatus': round(normalizedLightLevel, 2) })
#public methods
def getPLMInfo(self, timeout = None):
commandExecutionDetails = self.__sendModemCommand('60')
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
def pingDevice(self, deviceId, timeout = None):
startTime = time.time()
commandExecutionDetails = self.__sendStandardP2PInsteonCommand(deviceId, '0F', '00')
#Wait for ping result
commandReturnCode = self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
endTime = time.time()
if commandReturnCode:
return endTime - startTime
else:
return False
def idRequest(self, deviceId, timeout = None):
commandExecutionDetails = self.__sendStandardP2PInsteonCommand(deviceId, '10', '00')
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
def getInsteonEngineVersion(self, deviceId, timeout = None):
commandExecutionDetails = self.__sendStandardP2PInsteonCommand(deviceId, '0D', '00')
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
def getProductData(self, deviceId, timeout = None):
commandExecutionDetails = self.__sendStandardP2PInsteonCommand(deviceId, '03', '00')
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
def lightStatusRequest(self, deviceId, timeout = None):
commandExecutionDetails = self.__sendStandardP2PInsteonCommand(deviceId, '19', '00')
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
def command(self, device, command, timeout = None):
command = command.lower()
if isinstance(device, InsteonDevice):
print "InsteonA"
commandExecutionDetails = self.__sendStandardP2PInsteonCommand(device.deviceId, "%02x" % (HACommand()[command]['primary']['insteon']), "%02x" % (HACommand()[command]['secondary']['insteon']))
elif isinstance(device, X10Device):
print "X10A"
commandExecutionDetails = self.__sendStandardP2PX10Command(device.deviceId,"%02x" % (HACommand()[command]['primary']['x10']))
else:
print "stuffing"
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
def onCommand(self,callback):
pass
def turnOn(self, deviceId, timeout = None):
if len(deviceId) != 2: #insteon device address
commandExecutionDetails = self.__sendStandardP2PInsteonCommand(deviceId, '11', 'ff')
else: #X10 device address
commandExecutionDetails = self.__sendStandardP2PX10Command(deviceId,'02')
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
def turnOff(self, deviceId, timeout = None):
if len(deviceId) != 2: #insteon device address
commandExecutionDetails = self.__sendStandardP2PInsteonCommand(deviceId, '13', '00')
else: #X10 device address
commandExecutionDetails = self.__sendStandardP2PX10Command(deviceId,'03')
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
def turnOnFast(self, deviceId, timeout = None):
commandExecutionDetails = self.__sendStandardP2PInsteonCommand(deviceId, '12', 'ff')
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
def turnOffFast(self, deviceId, timeout = None):
commandExecutionDetails = self.__sendStandardP2PInsteonCommand(deviceId, '14', '00')
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
def dimTo(self, deviceId, level, timeout = None):
#organize what dim level we are heading to (figgure out the byte we need to send)
lightLevelByte = simpleMap(level, 0, 1, 0, 255)
commandExecutionDetails = self.__sendStandardP2PInsteonCommand(deviceId, '11', '%02x' % lightLevelByte)
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
def brightenOneStep(self, deviceId, timeout = None):
commandExecutionDetails = self.__sendStandardP2PInsteonCommand(deviceId, '15', '00')
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
def dimOneStep(self, deviceId, timeout = None):
commandExecutionDetails = self.__sendStandardP2PInsteonCommand(deviceId, '16', '00')
return self.__waitForCommandToFinish(commandExecutionDetails, timeout = timeout)
######################
# EXAMPLE #
######################
def x10_received(houseCode, unitCode, commandCode):
print 'X10 Received: %s%s->%s' % (houseCode, unitCode, commandCode)
def insteon_received(*params):
print 'InsteonPLM Received:', params
if __name__ == "__main__":
#Lets get this party started
insteonPLM = InsteonPLM(TCP('192.168.13.146',9761))
# insteonPLM = InsteonPLM(Serial('/dev/ttyMI0'))
jlight = InsteonDevice('19.05.7b',insteonPLM)
jRelay = X10Device('m1',insteonPLM)
insteonPLM.start()
jlight.set('faston')
jlight.set('fastoff')
jRelay.set('on')
jRelay.set('off')
# Need to get a callback implemented
# insteon.onReceivedInsteon(insteon_received)
#sit and spin, let the magic happen
select.select([],[],[])