-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIoT_Bit_library.py
More file actions
502 lines (399 loc) · 16 KB
/
IoT_Bit_library.py
File metadata and controls
502 lines (399 loc) · 16 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
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
'''
Name: IOTBit Library
Purpose: Library to interface with the IOTBit HAT on the Raspberry Pi,
tested on the latest version of Raspbian using a Raspberry Pi 3b.
'''
import serial
import time
import struct
import subprocess
import serial.tools.list_ports
import RPi.GPIO as GPIO
from datetime import datetime
'''
Gets the current time in milliseconds. Required for timeout implementation
'''
def Getmills():
mills = int(round(time.time()*1000))
return mills
class Modem:
'''
Set up the system only works if no other ttyUSB ports are on board
'''
def __init__(self, APN, Device = '4G'):
self.APN = APN
self.end = '\r'
USB_ports = list(serial.tools.list_ports.comports())
if Device == '4G':
GPS = USB_ports[3].device
AT = USB_ports[2].device
PPP = USB_ports[1].device
Audio = USB_ports[0].device
self.GPSPort = serial.Serial(GPS, baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=1, rtscts=True, dsrdtr=True)
self.ATPort = serial.Serial(AT, baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=1, rtscts=True, dsrdtr=True)
self.PPPPort = serial.Serial(PPP, baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=1, rtscts=True, dsrdtr=True)
self.AudioPort = serial.Serial(Audio, baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=1, rtscts=True, dsrdtr=True)
elif Device == '3G':
GPS = USB_ports[2].device
AT = USB_ports[1].device
PPP = USB_ports[0].device
self.GPSPort = serial.Serial(GPS, baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=1, rtscts=True, dsrdtr=True)
self.ATPort = serial.Serial(AT, baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=1, rtscts=True, dsrdtr=True)
self.PPPPort = serial.Serial(PPP, baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=1, rtscts=True, dsrdtr=True)
elif Device == 'GSM':
UARTPort = '/dev/serial0' # Serial Port for Raspbian Strech and higher
self.PassthroughPort = serial.Serial(UARTPort, baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=1, rtscts=True, dsrdtr=True)
'''
Uncomment both lines below if you have enabled UART on your Raspberry Pi, you can then
interface with the 4G or 3G models via UART. use sendATcmdUART to send AT commands
directly to the modem. replace /dev/serial0 with your UART Port.
'''
#UARTPort = '/dev/serial0'
#self.PassthroughPort = serial.Serial(UARTPort, baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=1, rtscts=True, dsrdtr=True)
########################################### BASE FUNCTIONS ##########################################################################
'''
Function to Send commands via the serial interface.
Waits for a response and returns the respons if there is one.
'''
def sendATcmd(self, ATcmd, Timeout):
# Modify the ATcmd so that it has the end of line character
cmd = ATcmd + self.end
# Send the cmd to the device
self.ATPort.write(cmd.encode("utf-8"))
time.sleep(0.01)
# Check the serial buffer to see if there is a response waiting
bytestoread = self.ATPort.inWaiting()
# While timeout not reached keep checking buffer
if (bytestoread == 0):
curtime = Getmills()
while (bytestoread == 0) and ((Getmills()-curtime)<Timeout):
bytestoread = self.ATPort.inWaiting()
# Store the response
self.response = self.ATPort.read(bytestoread).decode("utf-8")
else:
self.response = self.ATPort.read(bytestoread).decode("utf-8")
return self.response
'''
Function to read the a port to see if there data is waiting to be read.
'''
def ReadPort(self, Port, timeout):
# Check the serial buffer to see if there is a response waiting
bytestoread = Port.inWaiting()
# While timeout not reached keep checking buffer
if (bytestoread == 0):
curtime = Getmills()
while (bytestoread == 0) and ((Getmills()-curtime)<Timeout):
bytestoread = Port.inWaiting()
# Store the response
response = Port.read(bytestoread)
else:
response = Port.read(bytestoread)
return response
'''
Function to Send commands via the serial interface
Waits for a response and returns the respons if there is one.
Usable only with firmware verison 1.5
To test your firmare version use the function VersionCheck().
'''
def sendATcmdUART(self, ATcmd, Timeout):
# Modify the ATcmd so that it has the end of line character
cmd = ATcmd + self.end
# Wait for modem to be ready
ready = ""
ready = self.PassthroughPort.readline()
if 'Modem Ready' in ready:
self.PassthroughPort.write('P')
Sendcmd = ""
Sendcmd = self.PassthroughPort.readline()
if 'Send CMD' in Sendcmd:
# Send the cmd to the device
self.PassthroughPort.write(cmd)
# Check the serial buffer to see if there is a response waiting
bytestoread = self.PassthroughPort.inWaiting()
# While timeout not reached keep checking buffer
if (bytestoread == 0):
curtime = Getmills()
while (bytestoread == 0) and ((Getmills()-curtime)<Timeout):
bytestoread = self.PassthroughPort.inWaiting()
time.sleep(0.15)
# Store the response
self.response = self.PassthroughPort.read(bytestoread)
else:
self.response = self.PassthroughPort.readline()
else:
print ('Cmd not sent')
else:
print ('Modem not ready')
########################################### STATUS FUNCTIONS ##########################################################################
'''
Test if the modem is responding
'''
def Test(self):
self.sendATcmd('AT',100)
'''
Check if the SIM is being detected
'''
def CheckSIM(self):
msg = self.sendATcmd('AT+CPIN?',100)
if 'OK' in msg:
print ('SIM inserted')
else:
print ('SIM not inserted')
'''
Get GSM network status
'''
def StatusGSM(self):
self.sendATcmd('AT+MONI?',1000)
'''
GEt LTE network status
'''
def StatusLTE(self):
self.sendATcmd('AT+CMGSI=4',1000)
'''
Function to check signal quality
'''
def SignalCheck(self):
'''See Signal Quality'''
self.sendATcmd('AT+CSQ',1000)
signal = self.response
if (',' in self.response[8:10]):
signal = signal.replace(',','')
signal = int(signal[8:9])
else:
signal = int(self.response[8:10])
if (signal < 10):
signal = "Poor Signal"
elif(signal > 10 and signal < 14):
signal = "OK Signal"
elif(signal > 14 and signal < 20):
signal = "Good Signal"
elif(signal >= 20 and signal < 99):
signal = "Exceptional Signal"
elif(signal >= 99):
signal = "No Connection"
return signal
########################################### BOARD FUNCTIONS ##########################################################################
'''
Hard reset the modem, usable only with firmware verison 1.5
'''
def ResetModem(self):
# Wait for modem to be ready
ready = ""
ready = self.PassthroughPort.readline()
print (ready)
if 'Modem Ready' in ready:
self.PassthroughPort.write('R')
time.sleep(15)
bytestoread = self.PassthroughPort.inWaiting()
# While timeout not reached keep checking buffer
if (bytestoread == 0):
curtime = Getmills()
while (bytestoread == 0) & ((Getmills()-curtime)<1000):
bytestoread = self.PassthroughPort.inWaiting()
time.sleep(0.15)
# Store the response
self.response = self.PassthroughPort.read(bytestoread)
else:
self.response = self.PassthroughPort.readline()
'''
Reset the IOTBit
'''
def ResetAll(self):
# Wait for modem to be ready
ready = ""
ready = self.PassthroughPort.readline()
if 'Modem Ready' in ready:
self.PassthroughPort.write('S')
'''
Check the firmware version if you get no response this means
the firmware version is older than 1.5
'''
def VersionCheck(self):
# Wait for modem to be ready
ready = ""
ready = self.PassthroughPort.readline()
if 'Modem Ready' in ready:
self.PassthroughPort.write('V')
self.response = self.PassthroughPort.readline()
########################################### CALL FUNCTIONS ##########################################################################
'''
Function to make a call
'''
def MakeCall(self, number):
cmd = 'ATD'
cmd = cmd + number + ';'
self.sendATcmd(cmd, 1)
print ('Calling...')
'''
Function to hang up a call
'''
def Hangup(self):
print (' Hanging up...')
self.sendATcmd('ATH',1)
########################################### SMS FUNCTIONS ##########################################################################
'''
Function to configure SMS
'''
def SMSConfig(self, mem1,mem2,mem3):
print ('Configuring Modem for SMS...')
q = '"'
c = ','
self.sendATcmd('AT+CMGF=1',10)
time.sleep(0.01)
cmd = 'AT+CPMS='
cmd = cmd + q + mem1 + q + c + q + mem2 + q + c + q + mem3 + q
self.sendATcmd(cmd,10)
time.sleep(0.01)
self.sendATcmd('AT+CNMI=2,1',1)
time.sleep(0.01)
if 'OK' in self.response:
print('Setup Complete')
'''
Function to Send an sms
'''
def SendSMS(self, number, message):
print ('Sending SMS ...')
q = '"'
cmd = 'AT+CMGSO='
cmd = cmd + q + number + q + ',' + q + message + q
msg = self.sendATcmd(cmd,16000)
if 'OK' in msg:
print (' Sending successful')
else:
print (' Sending Unsuccessful')
'''
Function to read the sms in storage, if index is 0 print all msgs
'''
def ReadSMS(self, index):
if int(index) == 0:
self.content = self.sendATcmd('AT+CMGL="ALL"',3000)
elif index > 0:
cmd = 'AT+CMGR='
index = str(index - 1)
cmd = cmd + index
self.content = self.sendATcmd(cmd,3000)
return self.content
'''
Function to delete an sms in storeage, index refers to the position of the message
'''
def DeleteSMS(self, index):
cmd = 'AT+CMGD='
index = str(index)
cmd = cmd + index
self.content = self.sendATcmd(cmd,3000)
return self.content
'''
Function to read the command sent over sms
'''
def ReadSMSCmd(self):
self.ReadSMS(0)
time.sleep(2)
REC = '"REC READ"'
CMGL = '+CMGL: '
index = '0'
counter = 0
for i, _ in enumerate(self.response):
if self.response[i:i + len(CMGL)] == CMGL:
c_index = self.response[i + len(CMGL)]
if c_index > index:
index = c_index
cmd = 'AT+CMGR='
index = str(index)
cmd = cmd + index
self.sendATcmd(cmd,3000)
'''
Function to set GPIO pins high or low depending on the SMS
'''
def SetPins(self):
#Read cmd sent over SMS
self.ReadSMSCmd()
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
signalB = self.response
#Set desirded pins as high or low output
if 'PIN26H' in self.response:
GPIO.setup(26,GPIO.OUT)
GPIO.output(26,GPIO.HIGH)
signalB = "Pin 26 set to High"
elif 'PIN26L' in self.response:
GPIO.setup(26,GPIO.OUT)
GPIO.output(26,GPIO.LOW)
signalB = "Pin 26 set to Low"
elif 'PIN19H' in self.response:
GPIO.setup(19,GPIO.OUT)
GPIO.output(26,GPIO.HIGH)
signalB = "Pin 19 set to High"
elif 'PIN19L' in self.response:
GPIO.setup(19,GPIO.OUT)
GPIO.output(19,GPIO.LOW)
signalB = "Pin 19 set to Low"
elif 'PIN13H' in self.response:
GPIO.setup(13,GPIO.OUT)
GPIO.output(13,GPIO.HIGH)
signalB = "Pin 13 set to High"
elif 'PIN13L' in self.response:
GPIO.setup(13,GPIO.OUT)
GPIO.output(13,GPIO.LOW)
signalB = "Pin 13 set to Low"
else:
signalB = "NO Signals Sent"
return signalB
########################################### GPS FUNCTIONS ##########################################################################
'''
Function to start the GPS in Standalone mode
Modes can be 0,1 and 2 for cold, hot or normal start.
'''
def StartGPS_S(self, mode):
print (' Configuring ....')
# Set the NMEA port to output GLNOass and GPRS data
self.sendATcmd('AT+CGPSNMEA=3',100)
if 'OK' in self.response:
print ('NMEA Port configured')
else:
print (self.response)
time.sleep(0.01)
# Make sure the GPS is actually off
self.sendATcmd('AT+CGPS=0',100)
if 'OK' in self.response:
print ('Resetting GPS')
else:
print (self.response)
time.sleep(0.01)
# Check which mode has been chosen to turn on GPS
if mode == 0:
self.sendATcmd('AT+CGPSCOLD',100)
if 'OK' in self.response:
print (' Cold starting GPS')
else:
print (self.response)
elif mode == 1:
self.sendATcmd('AT+CGPSHOT',100)
if 'OK' in self.response:
print (' Hot starting GPS')
else:
print (self.response)
elif mode == 2:
self.sendATcmd('AT+CGPS=1',100)
if 'OK' in self.response:
print (' Starting GPS')
else:
print (self.response)
else:
print ("Mode not set")
time.sleep(0.01)
'''
Fuction to turn off the GPS
'''
def StopGPS(self):
self.sendATcmd('AT+CGPS=0',1)
if 'OK' in self.response:
print (' Stopping GPS')
else:
print (self.response)
time.sleep(0.01)
'''
Function to get current GPS information from the nmea port
'''
def GetGPSposition(self):
self.GPS = self.sendATcmd('AT+CGPSINFO',1)
return self.GPS