forked from Hydrosys4/Master
-
Notifications
You must be signed in to change notification settings - Fork 0
/
start.py
2208 lines (1698 loc) · 71.1 KB
/
start.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
# -*- coding: utf-8 -*-
Release="0.96"
#---------------------
from loggerconfig import LOG_SETTINGS
import logging, logging.config, logging.handlers
import basicSetting
DEBUGMODE=basicSetting.data["DEBUGMODE"]
PUBLICMODE=basicSetting.data["PUBLICMODE"]
if DEBUGMODE:
# below line is required for the loggin of the apscheduler, this might not be needed in the puthon 3.x
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
filename='logfiles/apscheduler_hydrosystem.log',
filemode='w')
# dedicated logging for the standard operation
logging.config.dictConfig(LOG_SETTINGS)
logger = logging.getLogger('hydrosys4')
exc_logger = logging.getLogger('exception')
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash, _app_ctx_stack, jsonify , Response
from datetime import datetime,date,timedelta
import systemtimeMod
import time
import os
import shutil
import sys
import string
import random
import json
import hardwaremod
import videomod
import sensordbmod
import actuatordbmod
import selectedplanmod
import wateringdbmod
import autowateringdbmod
import autowateringmod
import automationdbmod
import automationmod
import autofertilizerdbmod
import autofertilizermod
import fertilizerdbmod
import advancedmod
import networkmod
import networkdbmod
import emailmod
import emaildbmod
import logindbmod
import clockmod
import clockdbmod
import countryinfo
import cameradbmod
import sysconfigfilemod
import debuggingmod
# Raspberry Pi camera module (requires picamera package)
from camera_pi import Camera
# ///////////////// -- GLOBAL VARIABLES AND INIZIALIZATION --- //////////////////////////////////////////
application = Flask(__name__)
application.config.from_object('flasksettings') #read the configuration variables from a separate module (.py) file, this file is mandatory for Flask operations
print "-----------------" , basicSetting.data["INTRO"], "--------------------"
MYPATH=""
# ///////////////// --- END GLOBAL VARIABLES ------
# ///////////////// -- MODULE INIZIALIZATION --- //////////////////////////////////////////
#-- start LOGGING utility--------////////////////////////////////////////////////////////////////////////////////////
#setup log file ---------------------------------------
print "starting new log session", datetime.now().strftime("%Y-%m-%d %H:%M:%S")
logger.info('Start logging -------------------------------------------- %s' , datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
logger.debug('This is a sample DEBUG message')
logger.info('This is a sample INFO message')
logger.warning('This is a sample WARNING message')
logger.error('This is a sample ERROR message')
# finish logging init
def runallconsistencycheck():
wateringdbmod.consitencycheck()
autowateringdbmod.consistencycheck()
automationdbmod.consistencycheck()
fertilizerdbmod.consitencycheck()
autofertilizerdbmod.consistencycheck()
sensordbmod.consistencycheck()
actuatordbmod.consistencycheck()
return True
# Setup mode of operation------------------------------
selectedplanmod.FASTSCHEDULER=False
# set minimum time in case the clock is gone, in future might be improved ------------------
#important for Arch linux OS
systemtimeMod.set_min_datetime()
#initiate the GPIO OUT pins
hardwaremod.initallGPIOoutput()
# GET path ---------------------------------------------
print "path ",hardwaremod.get_path()
MYPATH=hardwaremod.get_path()
# RUN ALL consistency chacks ------------------------
runallconsistencycheck()
#setup network connecton --------------------
try:
print "start networking"
networkmod.init_network()
except:
print "No WiFi available"
#scheduler setup---------------------
selectedplanmod.start_scheduler()
# after internet connection because ofter the time is abruptly changed after connection
selectedplanmod.waitandsetmastercallback(networkmod.WAITTOCONNECT, 15) # plus 40 seconds respect to internet connection
#prove varie qui ---------------------------------------------------
#selectedplanmod.startpump("1","10","25","10")
#selectedplanmod.setlight("","")
#periodicdatarequest(0)
#selectedplanmod.pulsenutrient("10","","","3")
#selectedplanmod.sendmail()
#ret_data=hardwaremod.takephoto()
# ///////////////// --- END init
@application.teardown_appcontext
def close_db_connection(exception):
"""Closes the database again at the end of the request."""
top = _app_ctx_stack.top
if hasattr(top, 'sqlite_db'):
top.sqlite_db.close()
@application.route('/')
def show_entries():
if not session.get('logged_in'):
return render_template('login.html',error=None, change=False)
print "preparing home page"
currentday=date.today()
#Picture panel------------------------------------
#folderpath=os.path.join(MYPATH, "static")
#folderpath=os.path.join(folderpath, "hydropicture")
#sortedlist=sorted(os.listdir(folderpath))
#sortedlist.reverse()
photolist=hardwaremod.photolist(MYPATH)
photopanellist=[]
if photolist:
referencestr=photolist[0][0].split(",")[0]
for items in photolist:
if referencestr in items[0]:
photopanel={}
photopanel["type"]="photo"
photopanel["active"]="yes"
photopanel["title"]=""
photopanel["subtitle"]=""
photopanel["file"]=items[0]
photopanel["thumb"]=items[3]
photopanel["link"]=url_for('imageshow')
photopanel["linktitle"]="Go to Gallery"
#print photopanel
photopanellist.append(photopanel)
panelinfolist=[] # all the info relevant to a type of panel
# temperature panels -------------------------------------------- (new version)
MeasureType="Temperature"
namelist=hardwaremod.searchdatalist(hardwaremod.HW_INFO_MEASURE,MeasureType,hardwaremod.HW_INFO_NAME)
#print "------------------------- namelist " , namelist
if namelist:
paneldict={}
paneldict["icon"]="icons/temperature-transp.png"
paneldict["color"]="green"
paneldict["type"]="sensor"
paneldict["link"]=url_for('show_sensordata' , elementtype="", period="Day", actionbtn="sensor")
paneldict["linktitle"]="Go to Sensordata"
paneldict["title"]=MeasureType
paneldict["subtitle"]=""
paneldict["active"]="yes"
paneldata=[]
endtime=datetime.now()
for name in namelist:
sensordata=[]
sensordbmod.getsensordbdatadays(name,sensordata,1)
#set date interval for average
starttime= endtime - timedelta(days=1)
evaluateddata=sensordbmod.EvaluateDataPeriod(sensordata,starttime,endtime)
paneldatarow={}
paneldatarow["name"]=name
paneldatarow["average"]=str('%.1f' % evaluateddata["average"])
paneldatarow["min"]=str('%.1f' % evaluateddata["min"])
paneldatarow["max"]=str('%.1f' % evaluateddata["max"])
paneldatarow["unit"]=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,name,hardwaremod.HW_INFO_MEASUREUNIT)
paneldata.append(paneldatarow)
paneldict["data"]=paneldata
panelinfolist.append(paneldict)
# humidity panel --------------------------------------------
MeasureType="Humidity"
namelist=hardwaremod.searchdatalist(hardwaremod.HW_INFO_MEASURE,MeasureType,hardwaremod.HW_INFO_NAME)
#print "------------------------- namelist " , namelist
if namelist:
paneldict={}
paneldict["icon"]="icons/humidity-transp.png"
paneldict["color"]="primary"
paneldict["type"]="sensor"
paneldict["link"]=url_for('show_sensordata' , elementtype="", period="Day", actionbtn="sensor")
paneldict["linktitle"]="Go to Sensordata"
paneldict["title"]=MeasureType
paneldict["subtitle"]=""
paneldict["active"]="yes"
paneldata=[]
endtime=datetime.now()
for name in namelist:
sensordata=[]
sensordbmod.getsensordbdatadays(name,sensordata,1)
#set date interval for average
starttime= endtime - timedelta(days=1)
evaluateddata=sensordbmod.EvaluateDataPeriod(sensordata,starttime,endtime)
paneldatarow={}
paneldatarow["name"]=name
paneldatarow["average"]=str('%.1f' % evaluateddata["average"])
paneldatarow["min"]=str('%.1f' % evaluateddata["min"])
paneldatarow["max"]=str('%.1f' % evaluateddata["max"])
paneldatarow["unit"]=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,name,hardwaremod.HW_INFO_MEASUREUNIT)
paneldata.append(paneldatarow)
paneldict["data"]=paneldata
panelinfolist.append(paneldict)
# pressure panel --------------------------------------------
MeasureType="Pressure"
namelist=hardwaremod.searchdatalist(hardwaremod.HW_INFO_MEASURE,MeasureType,hardwaremod.HW_INFO_NAME)
#print "------------------------- namelist " , namelist
if namelist:
paneldict={}
paneldict["icon"]="icons/pressure-transp.png"
paneldict["color"]="yellow"
paneldict["type"]="sensor"
paneldict["link"]=url_for('show_sensordata' , elementtype="", period="Day", actionbtn="sensor")
paneldict["linktitle"]="Go to Sensordata"
paneldict["title"]=MeasureType
paneldict["subtitle"]=""
paneldict["active"]="yes"
paneldata=[]
endtime=datetime.now()
for name in namelist:
sensordata=[]
sensordbmod.getsensordbdatadays(name,sensordata,1)
#set date interval for average
starttime= endtime - timedelta(days=1)
evaluateddata=sensordbmod.EvaluateDataPeriod(sensordata,starttime,endtime)
paneldatarow={}
paneldatarow["name"]=name
paneldatarow["average"]=str('%.1f' % evaluateddata["average"])
paneldatarow["min"]=str('%.1f' % evaluateddata["min"])
paneldatarow["max"]=str('%.1f' % evaluateddata["max"])
paneldatarow["unit"]=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,name,hardwaremod.HW_INFO_MEASUREUNIT)
paneldata.append(paneldatarow)
paneldict["data"]=paneldata
panelinfolist.append(paneldict)
# light panel --------------------------------------------
MeasureType="Light"
namelist=hardwaremod.searchdatalist(hardwaremod.HW_INFO_MEASURE,MeasureType,hardwaremod.HW_INFO_NAME)
#print "------------------------- namelist " , namelist
if namelist:
paneldict={}
paneldict["icon"]="icons/light-transp.png"
paneldict["color"]="red"
paneldict["type"]="sensor"
paneldict["link"]=url_for('show_sensordata' , elementtype="", period="Day", actionbtn="sensor")
paneldict["linktitle"]="Go to Sensordata"
paneldict["title"]=MeasureType
paneldict["subtitle"]=""
paneldict["active"]="yes"
paneldata=[]
endtime=datetime.now()
for name in namelist:
sensordata=[]
sensordbmod.getsensordbdatadays(name,sensordata,1)
#set date interval for average
starttime= endtime - timedelta(days=1)
evaluateddata=sensordbmod.EvaluateDataPeriod(sensordata,starttime,endtime)
paneldatarow={}
paneldatarow["name"]=name
paneldatarow["average"]=str('%.1f' % evaluateddata["average"])
paneldatarow["min"]=str('%.1f' % evaluateddata["min"])
paneldatarow["max"]=str('%.1f' % evaluateddata["max"])
paneldatarow["unit"]=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,name,hardwaremod.HW_INFO_MEASUREUNIT)
paneldata.append(paneldatarow)
paneldict["data"]=paneldata
panelinfolist.append(paneldict)
# Hygrometer panel --------------------------------------------
MeasureType="Moisture"
namelist=hardwaremod.searchdatalist(hardwaremod.HW_INFO_MEASURE,MeasureType,hardwaremod.HW_INFO_NAME)
#print "------------------------- namelist " , namelist
if namelist:
paneldict={}
paneldict["icon"]="icons/moisture-transp.png"
paneldict["color"]="primary"
paneldict["type"]="sensor"
paneldict["link"]=url_for('show_sensordata' , elementtype="", period="Day", actionbtn="sensor")
paneldict["linktitle"]="Go to Sensordata"
paneldict["title"]=MeasureType
paneldict["subtitle"]="booooo"
paneldict["active"]="yes"
paneldata=[]
endtime=datetime.now()
for name in namelist:
sensordata=[]
sensordbmod.getsensordbdatadays(name,sensordata,1)
#set date interval for average
starttime= endtime - timedelta(days=1)
evaluateddata=sensordbmod.EvaluateDataPeriod(sensordata,starttime,endtime)
paneldatarow={}
paneldatarow["name"]=name
paneldatarow["average"]=str('%.1f' % evaluateddata["average"])
paneldatarow["min"]=str('%.1f' % evaluateddata["min"])
paneldatarow["max"]=str('%.1f' % evaluateddata["max"])
paneldatarow["unit"]=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,name,hardwaremod.HW_INFO_MEASUREUNIT)
paneldata.append(paneldatarow)
paneldict["data"]=paneldata
panelinfolist.append(paneldict)
# watertap panel --------------------------------------------
usedfor="watercontrol"
namelist=hardwaremod.searchdatalist(hardwaremod.HW_FUNC_USEDFOR,usedfor,hardwaremod.HW_INFO_NAME)
#print "------------------------- namelist " , namelist
if namelist:
paneldict={}
paneldict["icon"]="icons/watertap-transp.png"
paneldict["color"]="primary"
paneldict["type"]="actuator"
paneldict["link"]=url_for('wateringplan' , selectedelement=namelist[0])
paneldict["linktitle"]="Go to WateringPlan"
paneldict["title"]="Water"
paneldict["active"]="yes"
paneldata=[]
endtime=datetime.now()
for name in namelist:
sensordata=[]
starttime= endtime - timedelta(days=1)
data=[]
actuatordbmod.getActuatordbdata(name,data)
evaluateddata=sensordbmod.EvaluateDataPeriod(data,starttime,endtime) #set date interval for average
paneldatarow={}
paneldatarow["name"]=name
paneldatarow["average"]=str('%.1f' % (evaluateddata["sum"]/1000))
paneldatarow["min"]=""
paneldatarow["max"]=""
paneldatarow["unit"]=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,name,hardwaremod.HW_INFO_MEASUREUNIT)
paneldata.append(paneldatarow)
paneldict["data"]=paneldata
panelinfolist.append(paneldict)
# fertilizer panel --------------------------------------------
usedfor="fertilizercontrol"
namelist=hardwaremod.searchdatalist(hardwaremod.HW_FUNC_USEDFOR,usedfor,hardwaremod.HW_INFO_NAME)
#print "------------------------- namelist " , namelist
if namelist:
paneldict={}
paneldict["icon"]="icons/fertilizer-transp.png"
paneldict["color"]="green"
paneldict["type"]="actuator"
paneldict["link"]=url_for('fertilizerplan' , selectedelement=namelist[0])
paneldict["linktitle"]="Go to FertilizerPlan"
paneldict["title"]="Fertilizer"
paneldict["active"]="yes"
paneldata=[]
endtime=datetime.now()
for name in namelist:
sensordata=[]
starttime= endtime - timedelta(days=1)
data=[]
actuatordbmod.getActuatordbdata(name,data)
evaluateddata=sensordbmod.EvaluateDataPeriod(data,starttime,endtime) #set date interval for average
paneldatarow={}
paneldatarow["name"]=name
paneldatarow["average"]=str('%.1f' % (evaluateddata["sum"]/1000))
paneldatarow["min"]=""
paneldatarow["max"]=""
paneldatarow["unit"]=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,name,hardwaremod.HW_INFO_MEASUREUNIT)
paneldata.append(paneldatarow)
paneldict["data"]=paneldata
panelinfolist.append(paneldict)
networklink=url_for('network')
settinglink=url_for('show_Calibration')
videolink=url_for('videostream')
return render_template('homepage.html',panelinfolist=panelinfolist,photopanellist=photopanellist,currentday=currentday, networklink=networklink, settinglink=settinglink , videolink=videolink)
@application.route('/network/', methods=['GET', 'POST'])
def network():
if not session.get('logged_in'):
return render_template('login.html',error=None, change=False)
wifilist=[]
savedssid=[]
filenamelist="wifi networks"
print "visualizzazione menu network:"
iplocal=networkmod.get_local_ip()
iplocalwifi=networkmod.IPADDRESS
ipport=networkmod.PUBLICPORT
connectedssidlist=networkmod.connectedssid()
if len(connectedssidlist)>0:
connectedssid=connectedssidlist[0]
else:
connectedssid=""
localwifisystem=networkmod.localwifisystem
print " localwifisystem = ", localwifisystem , " connectedssid ", connectedssid
return render_template('network.html',filenamelist=filenamelist, connectedssid=connectedssid,localwifisystem=localwifisystem, iplocal=iplocal, iplocalwifi=iplocalwifi , ipport=ipport)
@application.route('/wificonfig/', methods=['GET', 'POST'])
def wificonfig():
if not session.get('logged_in'):
return render_template('login.html',error=None, change=False)
print "method " , request.method
if request.method == 'GET':
ssid = request.args.get('ssid')
print " argument = ", ssid
if request.method == 'POST':
ssid = request.form['ssid']
if request.form['buttonsub'] == "Save":
password=request.form['password']
networkmod.savewifi(ssid, password)
networkmod.waitandconnect(7)
print "Save"
return redirect(url_for('show_entries'))
elif request.form['buttonsub'] == "Forget":
print "forget"
networkmod.waitandremovewifi(6,ssid)
print "remove network ", ssid
print "Try to connect AP"
networkmod.waitandconnect_AP(7)
return redirect(url_for('show_entries'))
else:
print "cancel"
return redirect(url_for('network'))
return render_template('wificonfig.html', ssid=ssid)
@application.route('/Imageshow/', methods=['GET', 'POST'])
def imageshow():
if not session.get('logged_in'):
return render_template('login.html',error=None, change=False)
monthdict= {1: "jan", 10: "oct", 11: "nov", 12: "dec", 2: "feb", 3: "mar", 4: "apr", 5: "may", 6: "jun", 7: "jul", 8: "aug", 9: "sep"}
monthlist=[]
for i in range(12):
monthlist.append(monthdict[i+1])
todaydate = date.today()
currentmonth = todaydate.month
monthtoshow=currentmonth
if request.method == 'POST':
actiontype=request.form['actionbtn']
if actiontype=="DeleteAll":
# delete all files in the folder
deletedfilenumber=hardwaremod.deleteallpictures(MYPATH)
print " picture files deleted " , deletedfilenumber
logger.info(' all image files deleted ')
else:
monthtoshow=monthlist.index(actiontype)+1
sortedlist=hardwaremod.photolist(MYPATH)
filenamelist=[]
wlist=[]
hlist=[]
titlelist=[]
thumbfilenamelist=[]
for files in sortedlist:
filemonthnumber=files[2].month
print filemonthnumber
if filemonthnumber==monthtoshow :
filenamelist.append(files[0])
titlelist.append(files[1])
(w,h)=hardwaremod.get_image_size(files[0])
wlist.append(w)
hlist.append(h)
thumbfilenamelist.append(files[3])
print filenamelist
selectedmothname=monthdict[monthtoshow]
print selectedmothname
return render_template('showimages.html',filenamelist=filenamelist,titlelist=titlelist,wlist=wlist,hlist=hlist,monthlist=monthlist,selectedmothname=selectedmothname, thumbfilenamelist=thumbfilenamelist)
@application.route('/echo/', methods=['GET'])
def echo():
element=request.args['element']
if element=="all":
# take reading for all sensors
ret_data = hardwaremod.readallsensors()
else:
sensorvalue={}
sensorvalue[element]=hardwaremod.getsensordata(element,3)
ret_data=sensorvalue
print ret_data
return jsonify(ret_data)
@application.route('/echodatabase/', methods=['GET'])
def echodatabase():
element=request.args['element']
if element=="all":
# take reading for all sensors
ret_data = sensordbmod.readallsensorsdatabase()
else:
ret_data={}
print ret_data
return jsonify(ret_data)
@application.route('/echowifi/', methods=['GET'])
def echowifi():
ret_data={}
element=request.args['element']
if element=="all":
# get wifi list
wifilist=[]
wifilist=networkmod.wifilist_ssid()
connectedssidlist=networkmod.connectedssid()
if len(connectedssidlist)>0:
connectedssid=connectedssidlist[0]
else:
connectedssid=""
savedssid=networkmod.savedwifilist_ssid()
for ssid in wifilist:
connected="0"
if ssid==connectedssid:
connected="1"
idstatus="Unknown"
if ssid in savedssid:
idstatus="Saved"
ret_data[ssid]=[idstatus , connected]
print "Wifi Data " , ret_data
return jsonify(ret_data)
@application.route('/doit/', methods=['GET'])
def doit():
if not session.get('logged_in'):
ret_data = {"answer":"Login Needed"}
return jsonify(ret_data)
# send command to the actuator for test
cmd=""
sendstring=""
recdata=[]
ret_data={}
argumentlist=request.args.getlist('name')
name=argumentlist[0]
print "value passed ", argumentlist
print "type " , name
if name=="pulse":
idx=1
if idx < len(argumentlist):
testpulsetime=argumentlist[idx]
else:
testpulsetime="20"
element=request.args['element']
print "starting pulse test " , testpulsetime
answer=selectedplanmod.activateandregister(element,testpulsetime)
ret_data = {"answer": answer}
elif name=="stoppulse":
idx=1
element=request.args['element']
print "stop pulse " , element
answer=hardwaremod.stoppulse(element)
ret_data = {"answer": answer}
elif name=="servo2":
print "want to test servo"
idx=1
if idx < len(argumentlist):
steps=int(argumentlist[idx])
idx=2
if idx < len(argumentlist):
direction=argumentlist[idx]
element=request.args['element']
position=int(hardwaremod.getservopercentage(element))
if direction=="FORWARD":
position=position+steps
elif direction=="BACKWARD":
position=position-steps
# move servo
delay=0.5
position , isok=hardwaremod.servoangle(element,position,delay)
ret_data = {"answer": position}
elif name=="stepper":
print "want to test stepper"
idx=1
if idx < len(argumentlist):
steps=argumentlist[idx]
idx=2
if idx < len(argumentlist):
direction=argumentlist[idx]
element=request.args['element']
# move stepper
position , isok=hardwaremod.GO_stepper(element,steps,direction)
ret_data = {"answer": position}
elif name=="setstepper":
print "want to set stepper position"
idx=1
if idx < len(argumentlist):
newposition=argumentlist[idx]
element=request.args['element']
# set stepper position without moving it
hardwaremod.setstepperposition(element, newposition)
ret_data = {"answer": newposition}
# elif name=="stepperbusyflagdown":
# print "want to set stepper busyfleg to false"
# element=request.args['element']
# hardwaremod.setstepperbusyflag(element, False)
# ret_data = {"answer": "busyflag Down"} """
elif name=="photo":
print "want to test photo"
idx=1
if idx < len(argumentlist):
video=argumentlist[idx]
logger.info('testing photo %s', video)
resolution=request.args.getlist('resolution')[0]
position=request.args.getlist('position')[0]
servo=request.args.getlist('servo')[0]
vdirection=request.args.getlist('vflip')[0]
print "resolution ", resolution , " position ", position
positionlist=position.split(",")
position=""
if positionlist:
print "only use the first position for testing " , positionlist[0]
# move servo
position=positionlist[0]
logger.info('Move servo to position %s', position)
hardwaremod.servoangle(servo,position,1)
# take picture
#vdirection=hardwaremod.searchdata(hardwaremod.HW_FUNC_USEDFOR,"photocontrol",hardwaremod.HW_CTRL_LOGIC)
ret_data=hardwaremod.shotit(video,True,resolution,position,vdirection)
elif name=="mail":
mailaname=request.args['element']
mailaddress=request.args['address']
mailtitle=request.args['title']
cmd=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,mailaname,hardwaremod.HW_CTRL_CMD)
print "want to test mail, address=" , mailaddress , " Title=" , mailtitle
issent=emailmod.send_email_main(mailaddress,mailtitle,cmd,"report","Periodic system report generated automatically")
if issent:
ret_data = {"answer": "Mail sent"}
else:
ret_data = {"answer": "Error mail not sent"}
elif name=="clock":
element=request.args['element']
datetime=request.args['datetime']
if element=="system":
datetime=clockmod.readsystemdatetime()
answer="ready"
elif element=="network":
datetime=clockmod.getNTPTime()
if datetime=="":
answer="Error not able to get the Network time using NTP protocol"
else:
answer="ready"
elif element=="setHWClock":
print "datetime Local ->" ,datetime
answer=clockmod.setsystemclock(datetime)
answer=clockmod.setHWclock(datetime)
selectedplanmod.checkheartbeat()
ret_data = {"answer":answer, "value":datetime}
elif name=="timezone":
element=request.args['element']
timezone=request.args['timezone']
if element=="settimezone":
print "Set timezone ->" ,timezone
answer=clockmod.settimezone(timezone)
clockdbmod.changesavesetting("timezone",timezone)
# reset scheduling
selectedplanmod.resetmastercallback()
ret_data = {"answer":"Saved"}
return jsonify(ret_data)
@application.route('/saveit/', methods=['GET'])
def saveit():
if not session.get('logged_in'):
ret_data = {"answer":"Login needed"}
return jsonify(ret_data)
# send command to the actuator for test
cmd=""
sendstring=""
recdata=[]
ret_data={}
name=request.args['name']
print "Saving .." , name
if name=="mail":
mailaname=request.args['element']
mailaddress=request.args['address']
mailtitle=request.args['title']
mailtime=request.args['time']
print "save mail, name " ,mailaname , " address=" , mailaddress , " Title=" , mailtitle , " Time=", mailtime
hardwaremod.changesavecalibartion(mailaname,hardwaremod.HW_CTRL_MAILADDR,mailaddress)
hardwaremod.changesavecalibartion(mailaname,hardwaremod.HW_CTRL_MAILTITLE,mailtitle)
hardwaremod.changesavecalibartion(mailaname,hardwaremod.HW_FUNC_TIME,mailtime)
elif name=="photo":
# save photo time
phototime=""
phototime=request.args['time']
print "save photo setting, time=" , phototime
hwname=hardwaremod.searchdata(hardwaremod.HW_FUNC_USEDFOR,"photocontrol",hardwaremod.HW_INFO_NAME)
hardwaremod.changesavecalibartion(hwname,hardwaremod.HW_FUNC_TIME,phototime)
#hardwaremod.changesavecalibartion(hwname,hardwaremod.HW_CTRL_LOGIC,vdirection)
camname=request.args['element']
resolution=request.args['resolution']
position=request.args['position']
servo=request.args['servo']
active=request.args['active']
vflip=request.args['vflip']
print "save camera name " ,camname , " resolution=" , resolution , " position=" , position , " servo=" , servo ," time=", phototime ," Active=", active, " vflip ", vflip
cameradbmod.changecreatesetting("camera",camname,"resolution",resolution)
cameradbmod.changecreatesetting("camera",camname,"position",position)
cameradbmod.changecreatesetting("camera",camname,"servo",servo)
cameradbmod.changecreatesetting("camera",camname,"time",phototime)
cameradbmod.changecreatesetting("camera",camname,"active",active)
cameradbmod.changecreatesetting("camera",camname,"vflip",vflip)
cameradbmod.savesetting()
elif name=="light1":
lighttime=""
lighttime=request.args['time']
print "save light setting, time=" , lighttime
hardwaremod.changesavecalibartion(name,hardwaremod.HW_FUNC_TIME,lighttime)
ret_data = {"answer": "saved"}
print "The actuator ", ret_data
return jsonify(ret_data)
@application.route('/downloadit/', methods=['GET'])
def downloadit():
if not session.get('logged_in'):
ret_data = {"answer":"Login Needed"}
return jsonify(ret_data)
# check the download destination folder exist otherwise create it
folderpath=os.path.join(MYPATH, "static")
folderpath=os.path.join(folderpath, "download")
if not os.path.exists(folderpath):
os.makedirs(folderpath)
recdata=[]
ret_data={}
name=request.args['name']
if name=="downloadlog":
dstfilename="log"+datetime.now().strftime("%Y-%m-%d-time:%H:%M")+".log"
filename=LOG_SETTINGS['handlers']['access_file_handler']['filename']
folderpath=os.path.join(MYPATH, "static")
folderpath=os.path.join(folderpath, "download")
dst=os.path.join(folderpath, dstfilename+".txt")
print "prepare file for download, address=" , filename, "destination " , dst
try:
shutil.copyfile(filename, dst)
answer="ready"
except:
answer="problem copying file"
dstfilenamelist=[]
dstfilenamelist.append("download/"+dstfilename+".txt")
elif name=="downloadprevlog":
filenamestring=LOG_SETTINGS['handlers']['access_file_handler']['filename']
logfolder=filenamestring.split('/')[0]
filename=filenamestring.split('/')[1]
sortedlist=hardwaremod.loglist(MYPATH,logfolder,filename)
folderpath=os.path.join(MYPATH, "static")
folderpath=os.path.join(folderpath, "download")
answer="files not available"
dstfilenamelist=[]
for dstfilename in sortedlist:
dst=os.path.join(folderpath, dstfilename+".txt")
source=os.path.join(logfolder, dstfilename)
print "prepare file for download, address=" , source, "destination " , dst
try:
shutil.copyfile(source, dst)
answer="ready"
except:
answer="problem copying file"
dstfilenamelist.append("download/"+dstfilename+".txt")
elif name=="downloadlogSCHED":
dstfilename="Sched_log"+datetime.now().strftime("%Y-%m-%d-time:%H:%M")+".log"
filename="logfiles/apscheduler_hydrosystem.log"
folderpath=os.path.join(MYPATH, "static")
folderpath=os.path.join(folderpath, "download")
dst=os.path.join(folderpath, dstfilename+".txt")
print "prepare file for download, address=" , filename, "destination " , dst
try:
shutil.copyfile(filename, dst)
answer="ready"
except:
answer="problem copying file"
dstfilenamelist=[]
dstfilenamelist.append("download/"+dstfilename+".txt")
elif name=="downloadHW":
dstfilename=hardwaremod.HWDATAFILENAME
filename=os.path.join(hardwaremod.DATABASEPATH, hardwaremod.HWDATAFILENAME)
folderpath=os.path.join(MYPATH, "static")
folderpath=os.path.join(folderpath, "download")
dst=os.path.join(folderpath, hardwaremod.HWDATAFILENAME)
print "prepare file for download, address=" , filename, "destination " , dst
try:
shutil.copyfile(filename, dst)
answer="ready"
except:
answer="problem copying file"
dstfilenamelist=[]
dstfilenamelist.append("download/"+dstfilename)
elif name=="downloadsyslog":
dstfilename="syslog"+datetime.now().strftime("%Y-%m-%d-time:%H:%M")+".txt"
folderpath=os.path.join(MYPATH, "static")
folderpath=os.path.join(folderpath, "download")
dst=os.path.join(folderpath, dstfilename)
print "prepare file for download, destination " , dst
# create the file using the tail command
isok=debuggingmod.createfiletailsyslog(dst)
if not isok:
answer="problem cretating file"
else:
answer="ready"
dstfilenamelist=[]
dstfilenamelist.append("download/"+dstfilename)
ret_data = {"answer": answer, "filename": dstfilenamelist}
print "The actuator ", ret_data
return jsonify(ret_data)
@application.route('/testit/', methods=['GET'])
def testit():
if not session.get('logged_in'):
ret_data = {"answer":"Login Needed"}
return jsonify(ret_data)
# this is used for debugging purposes, activate the functiontest from web button
recdata=[]
ret_data={}
name=request.args['name']
if name=="testing":
answer="done"
print "testing"
answer=functiontest()
ret_data = {"answer": answer}
print "The actuator ", ret_data
return jsonify(ret_data)
@application.route('/ShowRealTimeData/', methods=['GET', 'POST'])
def show_realtimedata():
if not session.get('logged_in'):
return render_template('login.html',error=None, change=False)
sensorlist=sensordbmod.gettablelist()
selectedsensor=sensorlist[0]
if request.method == 'POST':
selectedsensor=request.form['postsensor']
unitdict={}
for item in sensorlist:
unitdict[item]=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,item,hardwaremod.HW_INFO_MEASUREUNIT)
print "unitdict " , unitdict
return render_template('ShowRealTimeSensor.html', sensorlist=sensorlist, unitdict=unitdict, selectedsensor=selectedsensor)
@application.route('/systemmailsetting/', methods=['GET', 'POST'])
def systemmailsetting():