-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathswpi.py
1402 lines (1206 loc) · 49.1 KB
/
swpi.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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###########################################################################
# Sint Wind PI
# Copyright 2012 by Tonino Tarsi <tony.tarsi@gmail.com>
#
# Please refer to the LICENSE file for conditions
# Visit http://www.vololiberomontecucco.it
#
##########################################################################
""" Main program """
import time
import sqlite3
import os
import humod
import config
import webcam
import sys
import urllib2, urllib
import datetime
import camera
from TTLib import *
import version
import sensor_thread
import globalvars
import radio
import ntplib
import meteodata
import math
import service
import tarfile
import signal
import thread
import database
import web_server
import socket
import pluginmanager
import importlib
import subprocess
import cameraPI
import IPCam
import traceback
socket.setdefaulttimeout(30)
dictModel = {}
dictModel[ '0002' ] = 'Raspberry Model B PCB 1.0'
dictModel[ '0003' ] = 'Raspberry Model B(ECN0001) PCB 1.0'
dictModel[ '0004' ] = 'Raspberry Model B PCB 2.0'
dictModel[ '0005' ] = 'Raspberry Model B PCB 2.0'
dictModel[ '0006' ] = 'Raspberry Model B PCB 2.0'
dictModel[ '0007' ] = 'Raspberry Model A PCB 2.0'
dictModel[ '0008' ] = 'Raspberry Model A PCB 2.0'
dictModel[ '0009' ] = 'Raspberry Model A PCB 2.0'
dictModel[ '000d' ] = 'Raspberry Model B PCB 2.0'
dictModel[ '000e' ] = 'Raspberry Model B PCB 2.0'
dictModel[ '000f' ] = 'Raspberry Model B PCB 2.0'
dictModel[ '0010' ] = 'Raspberry Model B+ PCB 1.0'
dictModel[ '0011' ] = 'Raspberry Model ComputeModule1 PCB 1.0'
dictModel[ '0012' ] = 'Raspberry Model A+ PCB 1.1'
dictModel[ '0013' ] = 'Raspberry Model B+ PCB 1.2'
dictModel[ '0014' ] = 'Raspberry Model ComputeModule1 PCB 1.0'
dictModel[ '0015' ] = 'Raspberry Model A+ PCB 1.1'
dictModel[ 'a01040' ] = 'Raspberry Model 2ModelB PCB 1.0'
dictModel[ 'a01041' ] = 'Raspberry Model 2ModelB PCB 1.1'
dictModel[ 'a21041' ] = 'Raspberry Model 2ModelB PCB 1.1'
dictModel[ 'a22042' ] = 'Raspberry Model 2ModelB(withBCM2837) PCB 1.2'
dictModel[ '900021' ] = 'Raspberry Model A+ PCB 1.1'
dictModel[ '900032' ] = 'Raspberry Model B+ PCB 1.2'
dictModel[ '900092' ] = 'Raspberry Model Zero PCB 1.2'
dictModel[ '900093' ] = 'Raspberry Model Zero PCB 1.3'
dictModel[ '920093' ] = 'Raspberry Model Zero PCB 1.3'
dictModel[ '9000c1' ] = 'Raspberry Model ZeroW PCB 1.1'
dictModel[ 'a02082' ] = 'Raspberry Model 3ModelB PCB 1.2'
dictModel[ 'a020a0' ] = 'Raspberry Model ComputeModule3(andCM3Lite) PCB 1.0'
dictModel[ 'a22082' ] = 'Raspberry Model 3ModelB PCB 1.2'
dictModel[ 'a32082' ] = 'Raspberry Model 3ModelB PCB 1.2'
################################ functions############################
def reset_sms(modem):
modem.enable_textmode(True)
modem.enable_clip(True)
modem.enable_nmi(True)
log ("sms reset")
def new_sms(modem, message):
"""Event Function for new incoming SMS"""
log( 'New message arrived: %r' % message)
waitForHandUP()
msg_num = int(message[12:].strip())
process_sms(modem,msg_num)
def process_sms(modem, smsID):
"""Parse SMS number smsID"""
try:
waitForHandUP()
global cfg
global logFileDate
msgID = smsID
smslist = modem.sms_list()
bFound = False
for message in smslist:
if (message[0] == msgID ):
bFound = True
break
if ( not bFound ):
print "ERROR - SMS not found"
return();
msgText = modem.sms_read(msgID)
msgSender = message[2]
msgDate = message[4]
log( "Processind SMS : " + str(msgID) + " - Text: " + msgText + " - Sender :" + msgSender)
command = msgText.split()
if ( len(command) < 2 ):
log( "Bad Command .. Deleting")
modem.sms_del(msgID)
return False
pwd = command[0]
if ( pwd.upper() != cfg.SMSPwd.upper() ):
log( "Bad SMS Password .. deleting")
modem.sms_del(msgID)
return False
cmd = command[1].upper()
if ( len(command) == 3 ):
param = command[2]
conn = sqlite3.connect('db/swpi.s3db',200)
dbCursor = conn.cursor()
#----------------------------------------------------------------------------------------
# SMS COMMANDS
# command param desc
#
# RBT reboot
# HLT halt
# SHUT hh:mm Set Shutdown time
# MDB mail database to sender
# RDB Reset Database
# MCFG mail cfg to sender
# MLOG mail current logfiles
# MALOG mail all logfiles
# DATE date set date ex 01011963
# DELIMG delete images
# DELLOG delete logs
# DF Send Disk space to sender
# MSG [0/1] Disable/Enable message.raw ( restored from message_save.raw )
# OFF [0/1] Set online or offline
# BMP085 [0/1] Use BMP084
# BME280 [0/1] Use BME280
# DHT [0/1] Use DHT
# LPW value Set LoRA Transmition power ( reboot is neaded )
# LBW value Set LoRA Band Width ( reboot is neaded )
# LCR value Set LoRA coding rate ( reboot is neaded )
# LSF value Set LoRA SPREADING_FACTOR ( reboot is neaded )
# BCK backup
# RST Restore
# CAM X set camera/logging interval to X seconds
# LOG [0/1] enable [1] or disable [0] internet data logging
# UPL [0/1] enable [1] or disable [0] internet data uploading
# AOI [0/1] set [1] or reset [0] always on internet parameter
# UDN [0/1] set [1] or reset [0] use dongle net parameter
# IP send sms with current IP to sender
# UPD Update software
# WSO X set calibration wind speed offset to X
# WSG X set calibration wind speed gain to X
# CRES x Change camera resolution 0 640x480
# 1 800x600
# 2 1024x768
# 3 1280x960
# 4 1400x1050
# 5 1600x1200
# 6 2048x1536
#---------------------------------------------------------------------------------------
if (len(command) == 2 and cmd == "DF" ):
modem.sms_del(msgID)
disk_space = disk_free()/1000000
msg = datetime.datetime.now().strftime("%d%m%Y %H%M")
msg += " DF = %d MB" % disk_space
log( "Sending SMS : " + msg )
modem.sms_send(msgSender,msg )
log( "SMS sent: " + msg )
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "MSG" ):
modem.sms_del(msgID)
if ( param == '0'):
if ( os.path.isfile("audio/message.raw") ):
if ( os.path.isfile("audio/message_save.raw") ):
os.remove("audio/message_save.raw")
os.rename("audio/message.raw","audio/message_save.raw")
if ( param == '1'):
if ( os.path.isfile("audio/message_save.raw") ):
if ( os.path.isfile("audio/message.raw") ):
os.remove("audio/message.raw")
os.rename("audio/message_save.raw","audio/message.raw")
#---------------------------------------------------------------------------------------
elif (len(command) == 2 and cmd == "DELIMG" ):
modem.sms_del(msgID)
os.system('rm -f /swpi/img/*')
log( "Detaled alla images " )
#---------------------------------------------------------------------------------------
elif (len(command) == 2 and cmd == "DELLOG" ):
modem.sms_del(msgID)
os.system('rm -f /swpi/log/*')
log( "Detaled all logs " )
#---------------------------------------------------------------------------------------
elif (len(command) == 2 and cmd == "RBT" ):
modem.sms_del(msgID)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
log( "Receiced rebooting command " )
systemRestart()
#---------------------------------------------------------------------------------------
elif (len(command) == 2 and cmd == "BCK" ):
modem.sms_del(msgID)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
log( "Receiced backup command " )
os.system("backup")
#---------------------------------------------------------------------------------------
elif (len(command) == 2 and cmd == "RST" ):
modem.sms_del(msgID)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
log( "Receiced Restore command " )
os.system("restore")
#---------------------------------------------------------------------------------------
elif (len(command) == 2 and cmd == "HLT" ):
modem.sms_del(msgID)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
log( "Receiced halt command " )
systemHalt()
#---------------------------------------------------------------------------------------
elif (len(command) == 2 and cmd == "RDB" ):
modem.sms_del(msgID)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
dbCursor.execute("delete from METEO")
conn.commit()
log( "Database resetted " )
#---------------------------------------------------------------------------------------
elif (len(command) == 2 and cmd == "MDB" ):
modem.sms_del(msgID)
tarname = "db.tar.gz"
tar = tarfile.open(tarname, "w:gz")
tar.add("./db")
tar.close()
bbConnected = False
if ( ( not internet_on()) and cfg.UseDongleNet and dongle_detected):
log( "Trying to connect to internet with 3G dongle ....")
time.sleep(1)
modem.connectwvdial()
time.sleep(2)
waitForIP()
bbConnected = True
if ( internet_on() ):
SendMail(cfg, "DB", "Here your DB", tarname)
os.remove(tarname)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
if (bbConnected ):
log("Try to disconnect")
modem.disconnectwvdial()
#reset_sms(modem)
#modem.enable_textmode(True)
#modem.enable_clip(True)
#modem.enable_nmi(True)
log( "DB sent by mail" )
#---------------------------------------------------------------------------------------
elif (len(command) == 2 and cmd == "MCFG" ):
modem.sms_del(msgID)
tarname = "cfg.tar.gz"
tar = tarfile.open(tarname, "w:gz")
tar.add("swpi.cfg")
tar.close()
bbConnected = False
if ( ( not internet_on()) and cfg.UseDongleNet and dongle_detected):
log( "Trying to connect to internet with 3G dongle ....")
time.sleep(1)
modem.connectwvdial()
time.sleep(2)
waitForIP()
bbConnected = True
if ( internet_on() ):
SendMail(cfg, "CFG", "Here your CFG", tarname)
os.remove(tarname)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
if (bbConnected ):
log("Try to disconnect")
modem.disconnectwvdial()
#reset_sms(modem)
#modem.enable_textmode(True)
#modem.enable_clip(True)
#modem.enable_nmi(True)
log( "CFG sent by mail" )
#---------------------------------------------------------------------------------------
elif (len(command) == 2 and cmd == "MLOG" ):
modem.sms_del(msgID)
tarname = "log.tar.gz"
tar = tarfile.open(tarname, "w:gz")
filetoadd = "log/log"+logFileDate+".log"
if ( os.path.isfile(filetoadd) ) :
tar.add(filetoadd)
filetoadd = "log/gphoto2"+logFileDate+".log"
if ( os.path.isfile(filetoadd) ) :
tar.add(filetoadd)
tar.close()
bbConnected = False
if ( ( not internet_on()) and cfg.UseDongleNet and dongle_detected):
log( "Trying to connect to internet with 3G dongle ....")
time.sleep(1)
modem.connectwvdial()
time.sleep(2)
waitForIP()
bbConnected = True
if ( internet_on() ):
SendMail(cfg, "LOF", "Here your LOG", tarname)
os.remove(tarname)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
if (bbConnected ):
log("Try to disconnect")
modem.disconnectwvdial()
#reset_sms(modem)
#modem.enable_textmode(True)
#modem.enable_clip(True)
#modem.enable_nmi(True)
log( "LOG sent by mail" )
#---------------------------------------------------------------------------------------
elif (len(command) == 2 and cmd == "MALOG" ):
modem.sms_del(msgID)
tarname = "alog.tar.gz"
tar = tarfile.open(tarname, "w:gz")
tar.add("log")
tar.close()
bbConnected = False
if ( ( not internet_on()) and cfg.UseDongleNet and dongle_detected):
log( "Trying to connect to internet with 3G dongle ....")
time.sleep(1)
modem.connectwvdial()
time.sleep(2)
waitForIP()
bbConnected = True
if ( internet_on() ):
SendMail(cfg, "LOF", "Here your LOG", tarname)
os.remove(tarname)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
if (bbConnected ):
log("Try to disconnect")
modem.disconnectwvdial()
#reset_sms(modem)
#modem.enable_textmode(True)
#modem.enable_clip(True)
#modem.enable_nmi(True)
log( "All LOG sent by mail" )
#---------------------------------------------------------------------------------------
elif (len(command) > 2 and cmd == "SYS" ):
modem.sms_del(msgID)
syscmd = ''.join(command[2:])
log( 'Executing %r' % syscmd)
cmd_exec = os.popen(syscmd)
output = cmd_exec.read()
if ( len(output) > 250 ):
output = output[:250]
output = "SYS OK"
log( 'Sending the output back to %s output: %s' % (msgSender, output))
modem.sms_send(msgSender, output)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
systemRestart()
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "DATE" ):
newdatestr = param
theDay = int(param[0:2])
theMonth = int(param[2:4])
theYear = int(param[4:8])
date1 = datetime.date(year=theYear,day=theDay,month=theMonth)
new_date = datetime.datetime.combine(date1,datetime.datetime.now().time())
os.system("sudo date -s '%s'" % new_date)
date_file = "/home/pi/swpi/date.txt"
in_file = open(date_file,"w")
in_file.write(new_date.strftime("%Y-%m-%d")+"\n")
in_file.close()
log( "New DATE set to : " + str(param))
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "SHUT" ):
modem.sms_del(msgID)
cfg.setShutdownTime(param)
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "CAM" ):
modem.sms_del(msgID)
WebCamInterval = int(param)
cfg.setWebCamInterval(WebCamInterval)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
log( "New CAM interval set to : " + str(cfg.WebCamInterval))
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "LPW" ):
modem.sms_del(msgID)
LoRa_power = int(param)
cfg.setLoRa_power(LoRa_power)
log( "New LoRa_power set to : " + str(cfg.LoRa_power))
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "LBW" ):
modem.sms_del(msgID)
LoRa_BW = str(param)
cfg.setLoRa_BW(LoRa_BW)
log( "New LoRa_BW set to : " + str(cfg.LoRa_BW))
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "LCR" ):
modem.sms_del(msgID)
LoRa_CR = str(param)
cfg.setLoRa_CR(LoRa_CR)
log( "New LoRa_BW set to : " + str(cfg.LoRa_CR))
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "LSF" ):
modem.sms_del(msgID)
LoRa_SF = str(param)
cfg.setLoRa_SF(LoRa_SF)
log( "New LoRa_BW set to : " + str(cfg.LoRa_SF))
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "LOG" ):
modem.sms_del(msgID)
if ( param == '0' or param == '1' ):
cfg.setDataLogging(param)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
if param == '0':
log( "Internet logging disabled ")
else:
log( "Internet logging enabled ")
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "OFF" ):
modem.sms_del(msgID)
if ( param == '0' or param == '1' ):
cfg.setOffline(param)
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "BMP085" ):
modem.sms_del(msgID)
if ( param == '0' or param == '1' ):
cfg.setBMP085(param)
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "BME280" ):
modem.sms_del(msgID)
if ( param == '0' or param == '1' ):
cfg.setBME280(param)
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "DHT" ):
modem.sms_del(msgID)
if ( param == '0' or param == '1' ):
cfg.setDHT(param)
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "UPL" ):
modem.sms_del(msgID)
if ( param == '0' or param == '1' ):
cfg.setDataUpload(param)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
if param == '0':
log( "Internet Uploading disabled ")
else:
log( "Internet Uploading enabled ")
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "AOI" ):
modem.sms_del(msgID)
AlwaysOnInternet = param
cfg.setAlwaysOnInternet(AlwaysOnInternet)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
log( "New Always On Internet set to : " + cfg.AlwaysOnInternet )
systemRestart()
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "UDN" ):
modem.sms_del(msgID)
UseDongleNet = param
cfg.setUseDongleNet(UseDongleNet)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
log( "UseDongleNet set to : " + cfg.UseDongleNet )
systemRestart()
#---------------------------------------------------------------------------------------
elif (len(command) == 2 and cmd == "IP" ):
modem.sms_del(msgID)
if ( IP != None and cfg.usedongle ):
try:
modem.sms_send(msgSender, IP)
log ("SMS sent to %s" % msgSender)
except:
log("Error sending IP by SMS")
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
log( "Sent IP" )
#----------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "WSO" ):
modem.sms_del(msgID)
cfg.setWindSpeed_offset(param)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
log( "Wind Speed offset set to : " + str(cfg.windspeed_offset ))
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "WSG" ):
modem.sms_del(msgID)
cfg.setWindSpeed_gain(param)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
log( "Wind Speed gain set to : " + str(cfg.windspeed_gain ))
#---------------------------------------------------------------------------------------
elif (len(command) == 3 and cmd == "CRES" ):
modem.sms_del(msgID)
cfg.setCamera_resolution(param)
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
log( "Camera_resolution : " + str(cfg.cameradivicefinalresolution ))
#---------------------------------------------------------------------------------------
elif (len(command) == 2 and cmd == "UPD" ):
modem.sms_del(msgID)
bbConnected = False
if ( ( not internet_on()) and cfg.UseDongleNet and dongle_detected):
log( "Trying to connect to internet with 3G dongle ....")
time.sleep(1)
modem.connectwvdial()
time.sleep(2)
waitForIP()
bbConnected = True
if ( internet_on() ):
swpi_update()
dbCursor.execute("insert into SMS(Number, Date,Message) values (?,?,?)", (msgSender,msgDate,msgText,))
conn.commit()
if (bbConnected ):
log("Try to disconnect")
modem.disconnectwvdial()
log( "SWPI-UPDATE" )
systemRestart()
else:
print "Unknown command"
#----------------------------------------------------------------------------
if conn:
conn.close()
modem.sms_del(msgID)
#log("alla fine dei messaggi reset sms")
reset_sms(modem)
return True
except Exception as e:
log( "D - Exept in MSG" )
modem.sms_del(msgID)
#log("se errore in sms reset ")
reset_sms(modem)
if conn:
conn.close()
print e.message
print e.__class__.__name__
log(traceback.format_exc())
return False
return True
################################################## CALL ##############################################################
def answer_call(modem, message):
#global ws
try:
if ( globalvars.bCapturingCamera ):
log("Not answering because capturing camera images")
return
if ( globalvars.meteo_data.last_measure_time == None or globalvars.meteo_data.status != 0 ):
log("Not answering because no valid meteo data yet")
return
if ( len(message) > 7 and message[:6] == '+CLIP:' ):
callingNumber = message[6:].split(',')[0]
else:
callingNumber = 'Error'
log( "Receiving call from : " + callingNumber )
delay = (datetime.datetime.now() - globalvars.meteo_data.last_measure_time)
delay_seconds = int(delay.total_seconds())
log("Answering with data of %d seconds old" % delay_seconds )
#prepare list of messages
listOfMessages = []
listOfMessages.append("./audio/silence05s.raw")
listOfMessages.append("./audio/hello.raw")
# Message
listOfMessages.append("./audio/message.raw")
if ( globalvars.offline or delay_seconds > 600):
listOfMessages.append("./audio/offline.raw")
else:
if ( cfg.sensor_type.upper() == "SIMULATE" ):
listOfMessages.append("./audio/simulate.raw")
# if (delay_seconds > 600 ):
# listOfMessages.append("./audio/some_problem.raw")
if( globalvars.meteo_data.rain_rate_1h != None and globalvars.meteo_data.rain_rate_1h >= 0.001 ):
listOfMessages.append("./audio/raining.raw")
# Wind Direction
listOfMessages.append("./audio/winddirection.raw")
listOfMessages.append("./audio/" + str(globalvars.meteo_data.wind_dir_code) + ".raw")
# Wind Speed
listOfMessages.append("./audio/from.raw")
if ( int(globalvars.meteo_data.wind_ave) <= 120):
listOfMessages.append("./audio/" + str(int(globalvars.meteo_data.wind_ave)) + ".raw")
else:
thousands, rem = divmod(round(globalvars.meteo_data.wind_ave), 1000)
thousands = int(thousands * 1000)
hundreds, tens = divmod(rem, 100)
hundreds = int(hundreds * 100)
tens = int(round(tens))
if ( thousands != 0):
listOfMessages.append("./audio/" + str(thousands) + ".raw")
if ( hundreds != 0):
listOfMessages.append("./audio/" + str(hundreds) + ".raw")
if ( tens != 0 ):
listOfMessages.append("./audio/" + str(tens) + ".raw")
listOfMessages.append("./audio/to.raw")
if ( int(globalvars.meteo_data.wind_gust) <= 120):
listOfMessages.append("./audio/" + str(int(globalvars.meteo_data.wind_gust)) + ".raw")
else:
thousands, rem = divmod(round(globalvars.meteo_data.wind_gust), 1000)
thousands = int(thousands * 1000)
hundreds, tens = divmod(rem, 100)
hundreds = int(hundreds * 100)
tens = int(round(tens))
if ( thousands != 0):
listOfMessages.append("./audio/" + str(thousands) + ".raw")
if ( hundreds != 0):
listOfMessages.append("./audio/" + str(hundreds) + ".raw")
if ( tens != 0 ):
listOfMessages.append("./audio/" + str(tens) + ".raw")
listOfMessages.append("./audio/km.raw")
#wind trend
if ( globalvars.meteo_data.wind_trend != None ):
if ( globalvars.meteo_data.wind_trend < - cfg.wind_trend_limit) :
listOfMessages.append("./audio/winddown.raw")
if ( globalvars.meteo_data.wind_trend > cfg.wind_trend_limit) :
listOfMessages.append("./audio/windup.raw")
# Temperature
if ( globalvars.meteo_data.temp_out != None ):
listOfMessages.append("./audio/silence05s.raw")
listOfMessages.append("./audio/temperature.raw")
if ( globalvars.meteo_data.temp_out < 0) :
listOfMessages.append("./audio/minus.raw")
# intera = int( math.floor(abs(globalvars.meteo_data.temp_out)) )
# dec = int( (abs(globalvars.meteo_data.temp_out)-intera)*10 )
# listOfMessages.append("./audio/temperature.raw")
# listOfMessages.append("./audio/" + str(intera) + ".raw")
# listOfMessages.append("./audio/comma.raw")
# listOfMessages.append("./audio/" + str(dec ) + ".raw")
intera = int(round( abs(globalvars.meteo_data.temp_out) ))
listOfMessages.append("./audio/" + str(intera) + ".raw")
listOfMessages.append("./audio/degree.raw")
# Pressure
if ( globalvars.meteo_data.rel_pressure != None ):
thousands, rem = divmod(round(globalvars.meteo_data.rel_pressure), 1000)
thousands = int(thousands * 1000)
hundreds, tens = divmod(rem, 100)
hundreds = int(hundreds * 100)
tens = int(round(tens))
listOfMessages.append("./audio/silence05s.raw")
listOfMessages.append("./audio/pressure.raw")
if ( thousands != 0):
listOfMessages.append("./audio/" + str(thousands) + ".raw")
if ( hundreds != 0):
listOfMessages.append("./audio/" + str(hundreds) + ".raw")
if ( tens != 0 ):
listOfMessages.append("./audio/" + str(tens) + ".raw")
listOfMessages.append("./audio/hpa.raw")
inCloud = False
# Humidity
if ( globalvars.meteo_data.hum_out != None ):
listOfMessages.append("./audio/silence05s.raw")
intera = int( globalvars.meteo_data.hum_out)
listOfMessages.append("./audio/umidity.raw")
listOfMessages.append("./audio/" + str(intera) + ".raw")
listOfMessages.append("./audio/percent.raw")
if ( globalvars.meteo_data.hum_out >= 100 ):
inCloud = True
listOfMessages.append("./audio/silence05s.raw")
listOfMessages.append("./audio/cloud.raw")
# # Dew point
# if ( globalvars.meteo_data.dew_point != None ):
# listOfMessages.append("./audio/silence05s.raw")
# listOfMessages.append("./audio/dewpoint.raw")
# if ( globalvars.meteo_data.dew_point < 0) :
# listOfMessages.append("./audio/minus.raw")
# intera = int(round( abs(globalvars.meteo_data.dew_point) ))
# listOfMessages.append("./audio/" + str(intera) + ".raw")
# listOfMessages.append("./audio/degree.raw")
#Cloud base
if (globalvars.meteo_data.cloud_base_altitude != None and not inCloud ) :
if ( globalvars.meteo_data.cloud_base_altitude != -1 ) :
thousands, rem = divmod(round(globalvars.meteo_data.cloud_base_altitude), 1000)
thousands = int(thousands * 1000)
hundreds, tens = divmod(rem, 100)
hundreds = int(hundreds * 100)
tens = int(round(tens))
listOfMessages.append("./audio/silence05s.raw")
listOfMessages.append("./audio/cloudbase.raw")
if ( thousands != 0):
listOfMessages.append("./audio/" + str(thousands) + ".raw")
if ( hundreds != 0):
listOfMessages.append("./audio/" + str(hundreds) + ".raw")
if ( tens != 0 ):
listOfMessages.append("./audio/" + str(tens) + ".raw")
listOfMessages.append("./audio/meters.raw")
else:
listOfMessages.append("./audio/incloud.raw")
# Statistics
if ( globalvars.meteo_data.winDayMin != None ):
listOfMessages.append("./audio/minday.raw")
if ( int(globalvars.meteo_data.winDayMin) <= 120):
listOfMessages.append("./audio/" + str(int(globalvars.meteo_data.winDayMin)) + ".raw")
else:
thousands, rem = divmod(round(globalvars.meteo_data.winDayMin), 1000)
thousands = int(thousands * 1000)
hundreds, tens = divmod(rem, 100)
hundreds = int(hundreds * 100)
tens = int(round(tens))
if ( thousands != 0):
listOfMessages.append("./audio/" + str(thousands) + ".raw")
if ( hundreds != 0):
listOfMessages.append("./audio/" + str(hundreds) + ".raw")
if ( tens != 0 ):
listOfMessages.append("./audio/" + str(tens) + ".raw")
if ( globalvars.meteo_data.winDayMax != None ):
listOfMessages.append("./audio/maxday.raw")
if ( int(globalvars.meteo_data.winDayMax) <= 120):
listOfMessages.append("./audio/" + str(int(globalvars.meteo_data.winDayMax)) + ".raw")
else:
thousands, rem = divmod(round(globalvars.meteo_data.winDayMax), 1000)
thousands = int(thousands * 1000)
hundreds, tens = divmod(rem, 100)
hundreds = int(hundreds * 100)
tens = int(round(tens))
if ( thousands != 0):
listOfMessages.append("./audio/" + str(thousands) + ".raw")
if ( hundreds != 0):
listOfMessages.append("./audio/" + str(hundreds) + ".raw")
if ( tens != 0 ):
listOfMessages.append("./audio/" + str(tens) + ".raw")
listOfMessages.append("./audio/silence05s.raw")
listOfMessages.append("./audio/thanks.raw")
listOfMessages.append("./audio/www.raw")
listOfMessages.append("./audio/silence05s.raw")
listOfMessages.append("./audio/swpi.raw")
modem.answerCallNew(listOfMessages)
#log to database
conn = sqlite3.connect('db/swpi.s3db',200)
dbCursor = conn.cursor()
dbCursor.execute("insert into CALL(Number) values (?)", (callingNumber,))
conn.commit()
conn.close()
except :
log("Error in answering %s" % sys.exc_info()[0])
pass
# Load Configuration
configfile = 'swpi.cfg'
if not os.path.isfile(configfile):
cfg = config.config(configfile,False)
os.system( "sudo chown pi swpi.cfg" )
log("Configuration file created with default option. Now edit the file : %s and restart with command : swpi " % (configfile))
#exit(0)
else:
cfg = config.config(configfile,False)
##################################################################################
v = version.Version("VERSION").getVersion()
log( "Starting SINT WIND PI ... ")
############################ MAIN ###############################################
print "************************************************************************"
print "* Sint Wind PI "+v+" *"
print "* *"
print "* 2012-2018 by Tonino Tarsi <tony.tarsi@gmail.com> *"
print "* *"
print "* System will start in 10 seconds - Press Ctrl-C to cancel *"
print "************************************************************************"
# Get curret log file
globalvars.TimeSetFromNTP = False
globalvars.logFileDate = datetime.datetime.now().strftime("%d%m%Y")
logFileDate = datetime.datetime.now().strftime("%d%m%Y")
SecondsToWait = 10
# give 10 seconds for interrupt the application
try:
#print sys.argv
if not ( '-i' in sys.argv ) :
for i in range(0,SecondsToWait):
sys.stdout.write(str(SecondsToWait-i) + ".....")
sys.stdout.flush()
time.sleep(1)
print ""
except KeyboardInterrupt:
#print "Stopping swpi"
exit(0)
# Radio Voice output shoud go to the analog device
#os.system( "sudo amixer cset numid=3 1 > /dev/null " )
myrevision = getrevision()
mymodel = ''
try:
mymodel = dictModel[myrevision]
except:
pass
log("System revision (" + myrevision + ") : " + mymodel)
if ( cfg.disable_hdmi):
log("Running power save ...")
os.system( "sudo /opt/vc/bin/tvservice -o > /dev/null" )
if ( myrevision == "900092" or myrevision == "900093" or myrevision == "920093" or myrevision == "9000c1" ): # Raspberry PI Zero
os.system( "echo 0 | sudo tee /sys/class/leds/led0/brightness > /dev/null" )
os.system( "echo 1 | sudo tee /sys/class/leds/led0/brightness > /dev/null" )
else:
os.system( "echo 1 | sudo tee /sys/class/leds/led0/brightness > /dev/null" )
os.system( "echo 0 | sudo tee /sys/class/leds/led0/brightness > /dev/null" )
os.system( "sudo chown -R pi:root /swpi" )
#Make sure every executable is executable
os.system( "sudo chmod +x ./dwcfg.sh" )
os.system( "sudo chmod +x ./usbreset" )
os.system( "sudo chmod +x ./wifi_reset.sh" )
os.system( "sudo chmod +x ./swpi.sh" )
os.system( "sudo chmod +x ./swpi-update.sh" )
os.system( "sudo chmod +x ./killswpi.sh" )
os.system( "sudo chmod +x ./DHT/DHT" )
os.system( "sudo chmod +x ./DHT/DHT_rf" )
os.system( "sudo chmod +x ./wh1080_rf/wh1080_rf" )
os.system( "sudo chmod +x ./wh1080_rf/spi_init" )
os.system( "sudo chown pi ./DHT" )
os.system( "sudo chown pi ./mcp3002" )
os.system( "sudo chown pi ./TX23" )
os.system( "sudo chown pi ./wh1080_rf" )
os.system( "sudo chown -R pi ./jscolor" )
os.system( "sudo chmod -R 777 ./jscolor" )
if(os.path.isfile("webcamtmp")):
os.system( "sudo rm ./webcamtmp")
if(os.path.isfile("wget-log")):
os.system( "sudo rm ./wget-log")
# Some Globasl :-(
globalvars.bAnswering = False
globalvars.bCapturingCamera = False
globalvars.meteo_data = meteodata.MeteoData(cfg)
globalvars.takenPicture = meteodata.CameraFiles()
IP = None
publicIP = None
# Start sensors thread ##
if ( cfg.use_wind_sensor ):
wind_sensor_thread = sensor_thread.WindSensorThread(cfg)
wind_sensor_thread.start()
# load plugins
pl = pluginmanager.PluginLoader("./plugins",cfg)
pl.loadAll()
if os.path.exists('./plugins/sync_plugin.py'):
log("Loading sync plugin")
from plugins.sync_plugin import *
plugin_sync = swpi_sync_plugin(cfg)
else:
plugin_sync = None
# start config eweb server
if ( cfg.config_web_server ):
webserver = web_server.config_webserver(cfg)
webserver.start()
# Set Time from NTP ( using a thread to avoid strange freezing )
if ( cfg.set_system_time_from_ntp_server_at_startup ):
thread.start_new_thread(SetTimeFromNTP, (cfg.ntp_server,))
# Init Dongle
bConnected = False
x=os.system("ls " + cfg.dongleDataPort )
if x==0:
dongle_detected = True
else:
dongle_detected = False
if ( dongle_detected ):
modem = humod.Modem(cfg.dongleDataPort,cfg.dongleAudioPort,cfg.dongleCtrlPort,cfg)
else:
modem = None
if cfg.usedongle :
if ( dongle_detected ):
sms_action = (humod.actions.PATTERN['new sms'], new_sms)
call_action = (humod.actions.PATTERN['incoming callclip'], answer_call)
actions = [sms_action , call_action]
modem.prober.start(actions) # Starts the prober.
#modem.enable_nmi(True)
reset_sms(modem)
print ""
log( "Modem Model : " + modem.show_model())
log( "Revision : " + modem.show_revision())
log( "Modem Serial Number : " + modem.show_sn())
log( "Pin Status : " + modem.get_pin_status())
log( "Device Center : " + modem.get_service_center()[0] + " " + str(modem.get_service_center()[1]))
log( "Signal quality : " + str(modem.get_rssi()))
log( "Checking new sms messages...")
smslist = modem.sms_list()
for message in smslist:
smsID = message[0]
process_sms(modem,smsID)
else:
log("3G Dongle not detected")
if ( ( not internet_on()) and cfg.UseDongleNet and dongle_detected ):