-
Notifications
You must be signed in to change notification settings - Fork 0
/
modem.py
313 lines (264 loc) · 9.6 KB
/
modem.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
# Software for communicating with the SmartHome PowerLinc serial modem.
# This module sends pydispatch signals with the following names:
#
# 'MODEM_COMMAND' for receivers that care about what messages
# are sent to the Insteon mode
# 'MODEM_RESPONSE' for messages that are received back from
# the Insteon modem.
import actions
from pydispatch import dispatcher
import datetime
import serial
import time
import config
import translator
from translator import *
import insteon_logging
debug = False
def hexdump(msg):
s = ""
for b in msg:
if len(s) > 0: s += " "
s += "%02x" % b
return s
class DeviceExists(Exception):
def __init__(self, id):
self.id = id
def __str__(self):
return "%device %s already exists" % self.id
class UnexpectedResponse(Exception):
def __init__(self, command, response):
self.command = command
self.response = response
def __str__(self):
return "Unexpected response: %s for command %s" % (
hexdump(self.response),
hexdump(self.command))
class Device(object):
def __init__(self):
self.name = ""
pass
class InsteonDevice(Device):
devices = {}
@classmethod
def lookup(cls, *args):
addr = InsteonAddress(*args)
if addr in cls.devices:
return cls.devices[addr]
return None
@classmethod
def list_devices(cls):
for d in cls:
print(str(d))
@staticmethod
# If this method is called explicitly one can use the resulting
# iterator. For some reason, the iter built-in function raises a
# TypeError rather than calling this method.
def __iter__():
return iter(InsteonDevice.devices.values())
def __init__(self, insteonAddress):
assert isinstance(insteonAddress, InsteonAddress)
super(InsteonDevice, self).__init__()
if self.__class__.lookup(insteonAddress):
raise DeviceExists(id)
self.address = insteonAddress
self.location = ''
self.category = None
self.subcategory = None
self.firmware_version = None
# Most recently received responses from this device
self.cmd1 = None
self.cmd2 = None
self.received_timestamp = None
self.__class__.devices[self.address] = self
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.address)
def process_message_from_me(self, msg):
assert isinstance(msg, Translator)
pattern1 = StandardMessageReceived(
StartByte(), StandardMessageReceivedCode(),
FromAddress(self.address), MatchVariable("to_address"),
MatchVariable("message_flags"),
MatchVariable("cmd1"), MatchVariable("cmd2"))
m = match(msg, pattern1)
if m == False:
return
self.received_timestamp = config.now()
self.cmd1 = m["cmd1"]
self.cmd2 = m["cmd2"]
def _simple_command(self, modem, cmd, cmd2):
response_index = 0
assert isinstance(modem, InsteonModem)
assert isinstance(cmd, StandardDirectCommand)
command = SendMessageCommand(self.address,
MessageFlags(extended=False,
max_hops=3,
hops_remaining=3),
cmd, cmd2)
modem.sendCommand(bytearray(command.encode()))
response = modem.readResponse()
echoed, length = ReadFromModem.interpret(response, response_index)
response_index += length
### Should check echo.
return echoed.AckNack is Ack(), response, response_index
def ping(self, modem):
return self._simple_command(modem, PingCmd(), Command2(0x01))
def id_request(self, modem):
return self._simple_command(modem, IdRequestCmd(), Command2(0x01))
def status(self, modem):
acked, response, _ = self._simple_command(modem, StatusRequestCmd(), Command2(0x00))
if not acked:
return
rfm, length1 = ReadFromModem.interpret(response, 0)
smr, length2 = StandardMessageReceived.interpret(response, length1)
assert len(response) == length1 + length2
return smr.Byte.byte
def on(self, modem):
return self._simple_command(modem, OnCmd(), Command2(0x01))
def off(self, modem):
return self._simple_command(modem, OffCmd(), Command2(0))
class InsteonLinkGroup(object):
groups = {}
@classmethod
def lookup(cls, link_group):
if isinstance(link_group, int):
link_group = translator.LinkGroup(link_group)
assert isinstance(link_group, translator.LinkGroup)
if link_group in cls.groups:
return cls.groups[link_group]
return None
def __init__(self, link_group, devices=[]):
if isinstance(link_group, int):
link_group = translator.LinkGroup(link_group)
assert isinstance(link_group, translator.LinkGroup)
if self.__class__.lookup(link_group):
raise GroupExists(link_group)
self.link_group = link_group
self.devices = devices
self.__class__.groups[self.link_group] = self
def add_device(self, device):
assert isinstance(device, InsteonDevice)
if device in self.devices:
return
self.devices.append(device)
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.link_group, self.devices)
class InsteonModem (object):
'''
InsteonModem mediates communication with an Insteon serial modem.
'''
def __init__(self, port_path):
self.port_path = port_path
self.serial = serial.Serial(port_path)
self.serial.bytesize = serial.EIGHTBITS
self.serial.baudrate = 19200
self.serial.timeout = 1
self.devices = {}
actions.run('onInsteonModemInitialized', modem=self)
def __repr__(self):
return 'InsteonModem(%r)' % (self.port_path,)
def sendCommand(self, command):
assert isinstance(command, bytearray)
# dispatch results are ignored.
dispatcher.send(signal='MODEM_COMMAND',
sender=self,
timestamp=config.now(),
bytes=command)
if debug: print("sending command %s" % hexdump(command))
self.serial.write(command)
def readResponse(self):
msg = bytearray()
while True:
b = self.serial.read(1)
if not b:
break
msg.append(ord(b))
if debug: print("receiving response %s" % hexdump(msg))
if len(msg) > 0:
# dispatch results are ignored.
dispatcher.send(signal='MODEM_RESPONSE',
sender=self,
timestamp=config.now(),
bytes=msg)
return msg
def process_incoming(self, bytes):
messages, end_index, err = interpret_all(bytes, ReadFromModem)
if end_index < len(bytes):
insteon_logging.info("failed to interpret all of byte array %r"
% bytes)
if err:
insteon_logging.info("Exception %r while interpreting byte array %r"
% (e, bytes))
for msg in messages:
for elt in msg:
if isinstance(elt, FromAddress):
device = InsteonDevice.lookup(elt)
if device:
device.process_message_from_me(msg)
break
def modeminfo(self):
self.sendCommand(bytearray(GetModemInfo().encode()))
response = self.readResponse()
i, length = ModemInfoResponse.interpret(response, 0)
device = InsteonDevice.lookup(i.InsteonAddress)
if not device:
device = InsteonDevice(i.InsteonAddress)
device.category = i.Category
device.subcategory = i.Subcategory
device.firmware_version = i.FirmwareVersion
return device
# Verify that the response echos the command
def check_echo(self, command, response):
for i in range(len(command)):
if command[i] != response[i]:
raise UnexpectedResponse(command, response)
def read_link_db(self):
links = []
self.sendCommand(bytearray(Get1stLinkCommand().encode()))
while True:
response = self.readResponse()
i, length = ReadFromModem.interpret(response, 0)
if debug: print("interpreted response: %r" % i)
if not isinstance(i.AckNack, Ack):
break
interpreted, length = AllLinkRecordResponse.interpret(response, length)
if debug: print(repr(interpreted))
record = interpreted.LinkDBRecord
flags = record.LinkDBRecordFlags
group = record.LinkGroup
group_obj = InsteonLinkGroup.lookup(group)
if not group_obj:
group_obj = InsteonLinkGroup(group)
address = record.InsteonAddress
# Add the device to our internal database if it's not already there
device = InsteonDevice.lookup(address)
if not device:
device = InsteonDevice(address)
group_obj.add_device(device)
if debug: print(repr(device))
self.sendCommand(bytearray(GetNextLinkCommand().encode()))
def load_devices(self):
self.modeminfo()
self.read_link_db()
def groupOn(self, group_number):
command = SendAllLinkCommand(LinkGroup(group_number), OnCmd(), Byte(0))
self.sendCommand(bytearray(command.encode()))
response = self.readResponse()
def groupOff(self, group_number):
command = SendAllLinkCommand(LinkGroup(group_number), OffCmd(), Byte(0))
self.sendCommand(bytearray(command.encode()))
response = self.readResponse()
class InsteonCommandAction(object):
'''InsteonCommandAction is a callable, which, when called, sends the
specified command to the specified InsteonModem. It can be used
as the action_function of an Event.'''
def __init__(self, modem_, command):
assert isinstance(modem_, InsteonModem)
assert isinstance(command, translator.Command), repr(command)
self.modem = modem_
self.command = command
def __call__(self):
self.modem.sendCommand(bytearray(self.command.encode()))
self.modem.readResponse()
def __repr__(self):
return 'InsteonCommandAction(%r, %r)' % (self.modem, self.command)