-
Notifications
You must be signed in to change notification settings - Fork 23
/
rockBlock.py
631 lines (345 loc) · 18.8 KB
/
rockBlock.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
# Copyright 2015 Makersnake
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import glob
import signal
import sys
import time
import serial
class rockBlockProtocol(object):
def rockBlockConnected(self):pass
def rockBlockDisconnected(self):pass
#SIGNAL
def rockBlockSignalUpdate(self,signal):pass
def rockBlockSignalPass(self):pass
def rockBlockSignalFail(self):pass
#MT
def rockBlockRxStarted(self):pass
def rockBlockRxFailed(self):pass
def rockBlockRxReceived(self,mtmsn,data):pass
def rockBlockRxMessageQueue(self,count):pass
#MO
def rockBlockTxStarted(self):pass
def rockBlockTxFailed(self):pass
def rockBlockTxSuccess(self,momsn):pass
class rockBlockException(Exception):
pass
class rockBlock(object):
IRIDIUM_EPOCH = 1399818235000 #May 11, 2014, at 14:23:55 (This will be 're-epoched' every couple of years!)
def __init__(self, portId, callback):
self.s = None
self.portId = portId
self.callback = callback
self.autoSession = True #When True, we'll automatically initiate additional sessions if more messages to download
try:
self.s = serial.Serial(self.portId, 19200, timeout=5)
if( self._configurePort() ):
self.ping() #KEEP SACRIFICIAL!
self.s.timeout = 60
if( self.ping() ):
if(self.callback != None and callable(self.callback.rockBlockConnected) ):
self.callback.rockBlockConnected()
return
self.close()
raise rockBlockException()
except (Exception):
raise rockBlockException
#Ensure that the connection is still alive
def ping(self):
self._ensureConnectionStatus()
command = "AT"
self.s.write(command + "\r")
if( self.s.readline().strip() == command ):
if( self.s.readline().strip() == "OK" ):
return True
return False
#Handy function to check the connection is still alive, else throw an Exception
def pingception(self):
self._ensureConnectionStatus()
self.s.timeout = 5
if(self.ping() == False):
raise rockBlockException
self.s.timeout = 60
def requestSignalStrength(self):
self._ensureConnectionStatus()
command = "AT+CSQ"
self.s.write(command + "\r")
if( self.s.readline().strip() == command):
response = self.s.readline().strip()
if( response.find("+CSQ") >= 0 ):
self.s.readline().strip() #OK
self.s.readline().strip() #BLANK
if( len(response) == 6):
return int( response[5] )
return -1
def messageCheck(self):
self._ensureConnectionStatus()
if(self.callback != None and callable(self.callback.rockBlockRxStarted) ):
self.callback.rockBlockRxStarted()
if( self._attemptConnection() and self._attemptSession() ):
return True
else:
if(self.callback != None and callable(self.callback.rockBlockRxFailed) ):
self.callback.rockBlockRxFailed()
def networkTime(self):
self._ensureConnectionStatus()
command = "AT-MSSTM"
self.s.write(command + "\r")
if(self.s.readline().strip() == command):
response = self.s.readline().strip()
self.s.readline().strip() #BLANK
self.s.readline().strip() #OK
if( not "no network service" in response ):
utc = int(response[8:], 16)
utc = int((self.IRIDIUM_EPOCH + (utc * 90))/1000)
return utc
else:
return 0;
def sendMessage(self, msg):
self._ensureConnectionStatus()
if(self.callback != None and callable(self.callback.rockBlockTxStarted) ):
self.callback.rockBlockTxStarted()
if( self._queueMessage(msg) and self._attemptConnection() ):
SESSION_DELAY = 1
SESSION_ATTEMPTS = 3
while(True):
SESSION_ATTEMPTS = SESSION_ATTEMPTS - 1
if(SESSION_ATTEMPTS == 0):
break
if( self._attemptSession() ):
return True
else:
time.sleep(SESSION_DELAY)
if(self.callback != None and callable(self.callback.rockBlockTxFailed) ):
self.callback.rockBlockTxFailed()
return False
def getSerialIdentifier(self):
self._ensureConnectionStatus()
command = "AT+GSN"
self.s.write(command + "\r")
if(self.s.readline().strip() == command):
response = self.s.readline().strip()
self.s.readline().strip() #BLANK
self.s.readline().strip() #OK
return response
#One-time initial setup function (Disables Flow Control)
#This only needs to be called once, as is stored in non-volitile memory
#Make sure you DISCONNECT RockBLOCK from power for a few minutes after this command has been issued...
def setup(self):
self._ensureConnectionStatus()
#Disable Flow Control
command = "AT&K0"
self.s.write(command + "\r")
if(self.s.readline().strip() == command and self.s.readline().strip() == "OK"):
#Store Configuration into Profile0
command = "AT&W0"
self.s.write(command + "\r")
if(self.s.readline().strip() == command and self.s.readline().strip() == "OK"):
#Use Profile0 as default
command = "AT&Y0"
self.s.write(command + "\r")
if(self.s.readline().strip() == command and self.s.readline().strip() == "OK"):
#Flush Memory
command = "AT*F"
self.s.write(command + "\r")
if(self.s.readline().strip() == command and self.s.readline().strip() == "OK"):
#self.close()
return True
return False
def close(self):
if(self.s != None):
self.s.close()
self.s = None
@staticmethod
def listPorts():
if sys.platform.startswith('win'):
ports = ['COM' + str(i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
#Private Methods - Don't call these directly!
def _queueMessage(self, msg):
self._ensureConnectionStatus()
if( len(msg) > 340):
print "sendMessageWithBytes bytes should be <= 340 bytes"
return False
command = "AT+SBDWB=" + str( len(msg) )
self.s.write(command + "\r")
if(self.s.readline().strip() == command):
if(self.s.readline().strip() == "READY"):
checksum = 0
for c in msg:
checksum = checksum + ord(c)
self.s.write( str(msg) )
self.s.write( chr( checksum >> 8 ) )
self.s.write( chr( checksum & 0xFF ) )
self.s.readline().strip() #BLANK
result = False
if(self.s.readline().strip() == "0"):
result = True
self.s.readline().strip() #BLANK
self.s.readline().strip() #OK
return result
return False
def _configurePort(self):
if( self._enableEcho() and self._disableFlowControl and self._disableRingAlerts() and self.ping() ):
return True
else:
return False
def _enableEcho(self):
self._ensureConnectionStatus()
command = "ATE1"
self.s.write(command + "\r")
response = self.s.readline().strip()
if(response == command or response == ""):
if( self.s.readline().strip() == "OK" ):
return True
return False
def _disableFlowControl(self):
self._ensureConnectionStatus()
command = "AT&K0"
self.s.write(command + "\r")
if(self.s.readline().strip() == command):
if( self.s.readline().strip() == "OK" ):
return True
return False
def _disableRingAlerts(self):
self._ensureConnectionStatus()
command = "AT+SBDMTA=0"
self.s.write(command + "\r")
if( self.s.readline().strip() == command ):
if( self.s.readline().strip() == "OK" ):
return True
return False
def _attemptSession(self):
self._ensureConnectionStatus()
SESSION_ATTEMPTS = 3
while(True):
if(SESSION_ATTEMPTS == 0):
return False
SESSION_ATTEMPTS = SESSION_ATTEMPTS - 1
command = "AT+SBDIX"
self.s.write(command + "\r")
if( self.s.readline().strip() == command ):
response = self.s.readline().strip()
if( response.find("+SBDIX:") >= 0 ):
self.s.readline() #BLANK
self.s.readline() #OK
response = response.replace("+SBDIX: ", "") #+SBDIX:<MO status>,<MOMSN>,<MT status>,<MTMSN>,<MT length>,<MTqueued>
parts = response.split(",")
moStatus = int(parts[0])
moMsn = int(parts[1])
mtStatus = int(parts[2])
mtMsn = int(parts[3])
mtLength = int(parts[4])
mtQueued = int(parts[5])
#Mobile Originated
if(moStatus <= 4):
self._clearMoBuffer()
if(self.callback != None and callable(self.callback.rockBlockTxSuccess) ):
self.callback.rockBlockTxSuccess( moMsn )
pass
else:
if(self.callback != None and callable(self.callback.rockBlockTxFailed) ):
self.callback.rockBlockTxFailed()
if(mtStatus == 1 and mtLength > 0): #SBD message successfully received from the GSS.
self._processMtMessage(mtMsn)
#AUTOGET NEXT MESSAGE
if(self.callback != None and callable(self.callback.rockBlockRxMessageQueue) ):
self.callback.rockBlockRxMessageQueue(mtQueued)
#There are additional MT messages to queued to download
if(mtQueued > 0 and self.autoSession == True):
self._attemptSession()
if(moStatus <= 4):
return True
return False
def _attemptConnection(self):
self._ensureConnectionStatus()
TIME_ATTEMPTS = 20
TIME_DELAY = 1
SIGNAL_ATTEMPTS = 10
RESCAN_DELAY = 10
SIGNAL_THRESHOLD = 2
#Wait for valid Network Time
while True:
if(TIME_ATTEMPTS == 0):
if(self.callback != None and callable(self.callback.rockBlockSignalFail) ):
self.callback.rockBlockSignalFail()
return False
if( self._isNetworkTimeValid() ):
break
TIME_ATTEMPTS = TIME_ATTEMPTS - 1;
time.sleep(TIME_DELAY)
#Wait for acceptable signal strength
while True:
signal = self.requestSignalStrength()
if(SIGNAL_ATTEMPTS == 0 or signal < 0):
print "NO SIGNAL"
if(self.callback != None and callable(self.callback.rockBlockSignalFail) ):
self.callback.rockBlockSignalFail()
return False
self.callback.rockBlockSignalUpdate( signal )
if( signal >= SIGNAL_THRESHOLD ):
if(self.callback != None and callable(self.callback.rockBlockSignalPass) ):
self.callback.rockBlockSignalPass()
return True;
SIGNAL_ATTEMPTS = SIGNAL_ATTEMPTS - 1
time.sleep(RESCAN_DELAY)
def _processMtMessage(self, mtMsn):
self._ensureConnectionStatus()
self.s.write("AT+SBDRB\r")
response = self.s.readline().strip().replace("AT+SBDRB\r","").strip()
if( response == "OK" ):
print "No message content.. strange!"
if(self.callback != None and callable(self.callback.rockBlockRxReceived) ):
self.callback.rockBlockRxReceived(mtMsn, "")
else:
content = response[2:-2]
if(self.callback != None and callable(self.callback.rockBlockRxReceived) ):
self.callback.rockBlockRxReceived(mtMsn, content)
self.s.readline() #BLANK?
def _isNetworkTimeValid(self):
self._ensureConnectionStatus()
command = "AT-MSSTM"
self.s.write(command + "\r")
if( self.s.readline().strip() == command ): #Echo
response = self.s.readline().strip()
if( response.startswith("-MSSTM") ): #-MSSTM: a5cb42ad / no network service
self.s.readline() #OK
self.s.readline() #BLANK
if( len(response) == 16):
return True
return False
def _clearMoBuffer(self):
self._ensureConnectionStatus()
command = "AT+SBDD0"
self.s.write(command + "\r")
if(self.s.readline().strip() == command):
if(self.s.readline().strip() == "0"):
self.s.readline() #BLANK
if(self.s.readline().strip() == "OK"):
return True
return False
def _ensureConnectionStatus(self):
if(self.s == None or self.s.isOpen() == False):
raise rockBlockException()