-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathllrp2hrp.py
481 lines (437 loc) · 18.4 KB
/
llrp2hrp.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
#!/usr/bin/env python
import argparse
import codecs
import lcddriver
import logging
import SocketServer
import socket
import struct
import time
from binascii import hexlify
from sllurp.llrp import LLRPMessage
from sllurp.llrp_proto import LLRPError
from hrp import HRP, const, exception
from hrp.exception import HRPFrameError, HRPNetworkError
from hrp.tag import TidReadParameter, TagAddress, MatchParameter
HOST = ''
PORT = 5084
HRP_HOST = '192.168.100.116'
HRP_PORT = 9090
HRP_TAG_FILTER_MS = 100
HRP_TAG_FILTER_RSSI = 0
KEEPALIVE_THRESHOLD = 5
BACKOFF_TIME = 30
HAVE_LCD = True
# Don't try connecting the HRP reader
FAKE_MODE = False
logger = logging.getLogger(__name__)
try:
display = lcddriver.lcd()
display.lcd_clear()
except:
HAVE_LCD = False
message_seq = 0
class LLRPMessageHandler(SocketServer.StreamRequestHandler):
def __init__(self, request, client_address, server):
self.request = request
self.client_address = client_address
self.server = server
# for partial data transfers
self.expectingRemainingBytes = 0
self.partialData = ''
# set up HRP connection
if not FAKE_MODE:
self.hrp = HRP(ip=HRP_HOST, port=HRP_PORT, ommit_ping=False, timeout=10)
# self.hrp.set_log_level_debug()
logger.info('Connecting to HRP reader...')
if HAVE_LCD:
display.lcd_display_string('Connecting:HRP', 2)
connected = False
while not connected:
try:
self.hrp.connect()
self.hrp_filter_time, self.hrp_rssi_threshold = self.hrp.tag_filter()
self.hrp.tag_filter(HRP_TAG_FILTER_MS, HRP_TAG_FILTER_RSSI)
connected = True
except HRPFrameError:
logger.warning('Connect didn\'t work, disconnecting and trying again ...')
self.hrp.disconnect()
except HRPNetworkError:
logger.warning('Could not connect to reader, waiting and trying again ...')
self.hrp.disconnect()
time.sleep(BACKOFF_TIME)
self.setup()
try:
self.handle()
finally:
self.finish()
def handle(self):
global message_seq
# send a ReaderEventNotification on connection
msg_dict = {'READER_EVENT_NOTIFICATION': {
'Ver': 1,
'Type': 63,
'ID': 0,
'ReaderEventNotificationData':
{
'UTCTimestamp':
{
'Microseconds': int(time.time() * 10e5)
},
'ConnectionAttemptEvent':
{
'Status': 'Success'
}
}
}}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
message_seq = message_seq + 1
data = self.request.recv(1024)
logger.debug('got %d bytes from reader: %s', len(data),
hexlify(data))
"""
XXX this block could be deleted
"""
if self.expectingRemainingBytes:
if len(data) >= self.expectingRemainingBytes:
data = self.partialData + data
self.partialData = ''
self.expectingRemainingBytes -= len(data)
else:
# still not enough; wait until next time
self.partialData += data
self.expectingRemainingBytes -= len(data)
return
while data:
# parse the message header to grab its length
if len(data) >= LLRPMessage.full_hdr_len:
msg_type, msg_len, message_id = \
struct.unpack(LLRPMessage.full_hdr_fmt,
data[:LLRPMessage.full_hdr_len])
else:
# XXX
logger.warning('Too few bytes (%d) to unpack message header',
len(data))
self.partialData = data
self.expectingRemainingBytes = \
LLRPMessage.full_hdr_len - len(data)
break
logger.debug('expect %d bytes (have %d)', msg_len, len(data))
if len(data) < msg_len:
# XXX
# got too few bytes
logger.debug("Less than an LLRP Message Size")
self.partialData = data
self.expectingRemainingBytes = msg_len - len(data)
break
else:
# got at least the right number of bytes
self.expectingRemainingBytes = 0
try:
lmsg = LLRPMessage(msgbytes=data[:msg_len])
self.handle_message(lmsg, message_seq)
message_seq = message_seq + 1
data = self.request.recv(1024)
except LLRPError:
logger.exception('Failed to decode LLRPMessage; '
'will not decode %d remaining bytes',
len(data))
break
except HRPFrameError:
logger.exception('Error with HRP Reader. Disconnecting')
break
message_seq = 1
def handle_message(self, lmsg, message_seq):
msg_type = lmsg.getName()
if msg_type == 'GET_SUPPORTED_VERSION':
# we only support reader version 1, this is a v2 command.
msg_dict = {'GET_SUPPORTED_VERSION_RESPONSE': {
'Ver': 1,
'Type': 56,
'ID': message_seq,
'CurrentVersion': 1,
'SupportedVersion': 1,
'LLRPStatus': {
'Type': 287,
'StatusCode': 'UnsupportedVersion',
'ErrorDescription': 'We only support v1',
}
}}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
if msg_type == 'GET_READER_CAPABILITIES':
msg_dict = {'GET_READER_CAPABILITIES_RESPONSE': {
'Ver': 1,
'Type': 11,
'ID': message_seq,
'LLRPStatus': {
'Type': 287,
'StatusCode': 'Success',
'ErrorDescription': '',
},
'GeneralDeviceCapabilities': {
'MaxNumberOfAntennaSupported': 4,
'CanSetAntennaProperties': 0,
'HasUTCClockCapability': 1,
'DeviceManufacturerName': 0,
'ModelName': 7206,
'ReaderFirmwareVersion': '1',
},
}}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
if msg_type == 'GET_ROSPECS':
# send a GET_ROSPECS_RESPONSE
msg_dict = {'GET_ROSPECS_RESPONSE': {
'Ver': 1,
'Type': 36,
'ID': message_seq,
'LLRPStatus': {
'Type': 287,
'StatusCode': 'Success',
'ErrorDescription': '',
},
}}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
if msg_type == 'DELETE_ACCESSSPEC':
# send a DELETE_ACCESSSPEC_RESPONSE
msg_dict = {'DELETE_ACCESSSPEC_RESPONSE': {
'Ver': 1,
'Type': 51,
'ID': message_seq,
'LLRPStatus': {
'Type': 287,
'StatusCode': 'Success',
'ErrorDescription': '',
},
}}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
if msg_type == 'DELETE_ROSPEC':
# send a DELETE_ROSPEC_RESPONSE
msg_dict = {'DELETE_ROSPEC_RESPONSE': {
'Ver': 1,
'Type': 31,
'ID': message_seq,
'LLRPStatus': {
'Type': 287,
'StatusCode': 'Success',
'ErrorDescription': '',
},
}}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
# New in WebScorer 4.3.0 update
if msg_type == 'GET_READER_CONFIG':
# send a GET_READER_CONFIG_RESPONSE
msg_dict = {'GET_READER_CONFIG_RESPONSE': {
'Ver': 1,
'Type': 12,
'ID': message_seq,
'LLRPStatus': {
'Type': 287,
'StatusCode': 'Success',
'ErrorDescription': '',
},
}}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
if msg_type == 'SET_READER_CONFIG':
# send a SET_READER_CONFIG_RESPONSE
msg_dict = {'SET_READER_CONFIG_RESPONSE': {
'Ver': 1,
'Type': 13,
'ID': message_seq,
'LLRPStatus': {
'Type': 287,
'StatusCode': 'Success',
'ErrorDescription': '',
},
}}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
if msg_type == 'ADD_ROSPEC':
# send a ADD_ROSPEC_RESPONSE
msg_dict = {'ADD_ROSPEC_RESPONSE': {
'Ver': 1,
'Type': 30,
'ID': message_seq,
'LLRPStatus': {
'Type': 287,
'StatusCode': 'Success',
'ErrorDescription': '',
},
}}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
if msg_type == 'ENABLE_ROSPEC':
# send a ADD_ROSPEC_RESPONSE
msg_dict = {'ENABLE_ROSPEC_RESPONSE': {
'Ver': 1,
'Type': 34,
'ID': message_seq,
'LLRPStatus': {
'Type': 287,
'StatusCode': 'Success',
'ErrorDescription': '',
},
}}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
if HAVE_LCD:
display.lcd_display_string('Reading tags ', 2)
if msg_type == 'ENABLE_ROSPEC' or msg_type == 'KEEPALIVE_ACK':
# send some tags!
if FAKE_MODE:
timestamp = int(time.time() * 10e5)
msg_dict = {'RO_ACCESS_REPORT': {
'Ver': 1,
'Type': 61,
'ID': message_seq,
'TagReportData': [{
'Type': 240,
'EPCData': {
'Type': 241,
'EPCLengthBits': 96,
'EPC': '001060310000000000000881'
},
'FirstSeenTimestampUTC': {
'Type': 2,
'Microseconds': timestamp
},
'LastSeenTimestampUTC': {
'Type': 4,
'Microseconds': timestamp
}
}, {
'Type': 240,
'EPCData': {
'Type': 241,
'EPCLengthBits': 96,
'EPC': '001060310000000000000882'
},
'FirstSeenTimestampUTC': {
'Type': 2,
'Microseconds': timestamp
},
'LastSeenTimestampUTC': {
'Type': 4,
'Microseconds': timestamp
}
}],
}}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
if not FAKE_MODE:
keepalive_timer = 0
# This enables antenna port 1 and 3.
for tag in self.hrp.read_tag(antennas=5, match=MatchParameter(const.MATCH_EPC, 0x20, codecs.decode('b20200411666', 'hex'))):
#for tag in self.hrp.read_tag(antennas=5):
if tag is not None:
timestamp = int(time.time() * 10e5)
tag_hex = codecs.encode(tag.epc, 'hex')
logger.info("TAG FOUND: " + tag_hex)
msg_dict = {'RO_ACCESS_REPORT': {
'Ver': 1,
'Type': 61,
'ID': message_seq,
'TagReportData': [{
'Type': 240,
'EPCData': {
'Type': 241,
'EPCLengthBits': len(tag_hex) * 4,
'EPC': tag_hex
},
'FirstSeenTimestampUTC': {
'Type': 2,
'Microseconds': timestamp
},
'LastSeenTimestampUTC': {
'Type': 4,
'Microseconds': timestamp
},
'PeakRSSI': {
'Type': 6,
'PeakRSSI': tag.rssi
}}]
}
}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
else:
logger.info("TIMEOUT")
keepalive_timer = keepalive_timer + 1
if keepalive_timer > KEEPALIVE_THRESHOLD:
self.hrp.end_read_tag = True
message_seq = message_seq + 1
msg_dict = {'KEEPALIVE': {
'Ver': 1,
'Type': 62,
'ID': message_seq
}}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
self.hrp.tag_filter(self.hrp_filter_time, self.hrp_rssi_threshold)
if msg_type == 'CLOSE_CONNECTION':
# send a CLOSE_CONNECTION_RESPONSE
msg_dict = {'CLOSE_CONNECTION_RESPONSE': {
'Ver': 1,
'Type': 4,
'ID': message_seq,
'LLRPStatus': {
'Type': 287,
'StatusCode': 'Success',
'ErrorDescription': '',
},
}}
llrp_msg = LLRPMessage(msgdict=msg_dict)
self.request.send(llrp_msg.msgbytes)
def finish(self):
if not FAKE_MODE:
self.hrp.disconnect()
if HAVE_LCD:
display.lcd_display_string('Disconnected', 2)
def get_real_ip():
"""
Attempts to get the IP address that's used for interesting things.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("8.8.8.8", 53))
except:
return False
ip_address = s.getsockname()[0]
first_octet = ip_address.split('.')
if first_octet != '127' and first_octet != '169':
return ip_address
else:
return False
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'-r',
'--reader',
help='IP address of reader'
)
args = parser.parse_args()
logging.basicConfig(level=logging.INFO)
# get the local IP address
real_ip = get_real_ip()
while real_ip is False:
real_ip = get_real_ip()
display.lcd_display_string("No Network.", 1)
display.lcd_display_string("Set up hotspot", 2)
time.sleep(BACKOFF_TIME)
if HAVE_LCD:
display.lcd_display_string(real_ip, 1)
SocketServer.TCPServer.allow_reuse_address = True
server = SocketServer.TCPServer((HOST, PORT), LLRPMessageHandler)
logger.info("LLRP server running...")
if HAVE_LCD:
display.lcd_display_string("LLRP server on", 2)
server.serve_forever()
server.server_close()
if __name__ == '__main__':
main()