-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrgc-server.py
1995 lines (1950 loc) · 123 KB
/
rgc-server.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
import SocketServer
import socket
import sys
import hashlib
from datetime import datetime
import _strptime
import os
import signal
import glob
import sqlite3
import threading
import time
import RPi.GPIO as GPIO
import logging
from systemd.journal import JournalHandler
import re
import zlib
from random import choice
from string import ascii_uppercase
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import urlparse
import urllib2
import json
import subprocess
log = logging.getLogger('demo')
log.addHandler(JournalHandler())
log.setLevel(logging.INFO)
import base64
from Crypto import Random
from Crypto.Cipher import AES
import multiprocessing
import psycopg2
from psycopg2.extras import DictCursor
from ConfigParser import SafeConfigParser
import psutil
import traceback
def encrypt(key, message):
try:
bs = 16
message = message + (bs - len(message) % bs) * chr(bs - len(message) % bs)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
s = base64.b64encode(iv + cipher.encrypt(message))
except:
s = "error"
return s
def decrypt(key, enc_message):
try:
enc_message = base64.b64decode(enc_message)
iv = enc_message[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
s = cipher.decrypt(enc_message[AES.block_size:])
s = s[:-ord(s[len(s)-1:])]
except:
s = "error"
return s
HOST = ''
parser = SafeConfigParser()
parser.read('rgc-config.ini')
PASSWORD = ''
MODE = parser.get('main','mode')
ENC_KEY = ''
CODE_VERSION = 8
TAG_VERSION = 3.4
startTime = None
DS = None
TSL = None
pwm = {k: [] for k in range(2)}
RF_TX_BCM = 0
RF_RX_BCM = 0
RANGE_SENSORS = {}
RE_COUNTERS = {}
GPIO_EVENTS_PINS = []
debug = parser.getboolean('main','debug')
strptime = datetime.strptime
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
exit_event = multiprocessing.Event()
doRestartAfterReply = -1
pms7003 = None
running_proceses = []
mesured_proceses = {}
def services():
conn, conndbth = newDBConnP()
global exit_event
while not exit_event.is_set():
conndbth.execute("SELECT * FROM akcje where Rodzaj > 0 OR Rodzaj = -1")
rows = conndbth.fetchall()
for row in rows:
isRunning = False
if row[17]:
#if psutil.pid_exists(row[17]):
if any(p.pid == row[17] for p in running_proceses):
isRunning = True
#print row[10]+str(isRunning)+str(row[17])
conndbth.execute("SELECT Id FROM wyzwalaczeAkcji WHERE Id_a = %s AND Warunek = 'in chain'",(str(row[0]),))
rowChain = conndbth.fetchone()
if not isRunning and rowChain is None:
p1 = multiprocessing.Process(target=action, args=(row[0],))
p1.daemon = True
p1.start()
running_proceses.append(p1)
conndbth.execute("UPDATE akcje set Pid=%s where Id=%s", (str(p1.pid),row[0]))
time.sleep(0.01)
elif rowChain is None and isRunning:
try: pu = mesured_proceses[row[17]]
except KeyError: mesured_proceses[row[17]] = pu = psutil.Process(row[17])
cpuUsage = pu.cpu_percent()/psutil.cpu_count()
conndbth.execute("UPDATE akcje set Cpu_usage=%s where Id=%s", (str(cpuUsage),row[0]))
for p in running_proceses:
#print str(p.pid)+str(p.is_alive())
if not p.is_alive():running_proceses.remove(p)
time.sleep(5)
conndbth.close()
conn.close()
def action(id,idCE = 0,changedBy="scheduled"):
updateCD = 30
startTime = time.time()
trigger_timer = {}
conn, conndb4 = newDBConnP()
log = logging.getLogger('demo')
log.addHandler(JournalHandler())
log.setLevel(logging.ERROR)
proc = multiprocessing.current_process()
global exit_event
while not exit_event.is_set():
try:
conndb4.execute("SELECT * FROM akcje WHERE Id = %s",(id,))
row = conndb4.fetchone()
if row is None: sys.exit()
conndb4.execute("SELECT * FROM wyzwalaczeAkcji w left join sensory s on w.Id_s = s.Id left join stany st on w.Id_s = CAST(st.Id AS TEXT) left join pwm p on w.Id_s = CAST(p.Id AS TEXT) left join rf r on w.Id_s=CAST(r.Id AS TEXT) left join globalVariables v on w.Id_s=CAST(v.Id AS TEXT) WHERE w.Id_a = %s ORDER BY w.Lp",(row[0],))
conditions = []
conditionsLog = []
conditionString = ''
conditionStringLog = ''
triggers = []
for rowW in conndb4.fetchall():
triggers.append(rowW[4])
if rowW[4] == 'date':
conditions.append(eval("strptime('"+rowW[6]+"','%Y-%m-%d %H:%M')"+rowW[5]+"datetime.utcnow().replace(microsecond=0,second=0)"))
conditionsLog.append(rowW[4]+":"+rowW[6]+rowW[5]+datetime.utcnow().replace(microsecond=0,second=0).strftime('%Y-%m-%d %H:%M'))
elif rowW[4] == 'hour':
triggerHour = datetime.strptime(rowW[6],'%H:%M')
currentHour = datetime.utcnow().replace(1900,1,1,microsecond=0,second=0)
conditions.append(eval('triggerHour'+rowW[5]+'currentHour'))
conditionsLog.append(rowW[4]+":"+triggerHour.strftime('%H:%M')+rowW[5]+currentHour.strftime('%H:%M'))
elif rowW[4] == 'timer':
timelist = rowW[6].split(",")
if rowW[0] not in trigger_timer or trigger_timer[rowW[0]][0] != int(timelist[0])*1000:
trigger_timer[rowW[0]] = (int(timelist[0])*1000,int(timelist[1])*1000,int(round(time.time()*1000)))
timeS = trigger_timer[rowW[0]][1] - (int(round(time.time()*1000)) - trigger_timer[rowW[0]][2])
conditions.append(timeS <= 0)
conditionsLog.append(rowW[4]+":"+str(timeS) +'<=0')
if timeS > 0:
trigger_timer[rowW[0]] =(trigger_timer[rowW[0]][0],timeS,int(round(time.time()*1000)))
if updateCD <= 0:
conndb4.execute("UPDATE wyzwalaczeAkcji set Dane=%s where Id=%s", (str(trigger_timer[rowW[0]][0]/1000)+','+str(timeS/1000), rowW[0]))
else:
trigger_timer[rowW[0]] = (trigger_timer[rowW[0]][0],trigger_timer[rowW[0]][0],int(round(time.time()*1000)))
elif rowW[4] == 'sensor':
sensorValue = getCurrentSensorValue(rowW[2],conndb4)
if sensorValue != None:
conditions.append(eval(str(sensorValue)+rowW[5]+rowW[6]))
conditionsLog.append(rowW[4]+":"+str(sensorValue)+rowW[5]+rowW[6])
else: conditions.append(False)
elif rowW[4] == 'weekday':
conditions.append(eval("datetime.now().weekday()"+rowW[5]+rowW[6]))
conditionsLog.append(rowW[4]+":"+str(datetime.now().weekday())+rowW[5]+rowW[6])
elif rowW[4] == 'i/o':
planned = int(rowW[6])
cState = int(rowW[21])
reverse = int(rowW[25])
conditions.append(True if ((planned==cState and not reverse) or (planned==2 and planned==cState) or (planned!=cState and reverse and planned!=2)) else False)
conditionsLog.append("State equals" if ((planned==cState and not reverse) or (planned==2 and planned==cState) or (planned!=cState and reverse and planned!=2)) else "State not equals")
elif rowW[4] == 'pwm state':
conditions.append(int(rowW[6]) == int(rowW[32]))
conditionsLog.append("State equals" if (int(rowW[6]) == int(rowW[32])) else "State not equals")
elif rowW[4] == 'pwm fr':
conditions.append(eval(str(rowW[30])+rowW[5]+rowW[6]) and int(rowW[32] == 1))
conditionsLog.append(rowW[4]+":"+str(rowW[30])+"Hz"+rowW[5]+rowW[6]+"Hz")
elif rowW[4] == 'pwm dc':
conditions.append(eval(str(rowW[31])+rowW[5]+rowW[6]) and int(rowW[32] == 1))
conditionsLog.append(rowW[4]+":"+str(rowW[31])+"%"+rowW[5]+rowW[6]+"%")
elif rowW[4] == 'in chain':
conditions.append(eval(rowW[6]+rowW[5]+str(idCE != 0)))
conditionsLog.append('In chain run')
elif rowW[4] == 'ping':
response = os.system("ping -c 1 -w 2 -t 2 "+rowW[2]+" > /dev/null 2>&1")
if response == 0: isPinging = True
else: isPinging = False
conditions.append(eval(rowW[6]+rowW[5]+str(isPinging)))
conditionsLog.append(rowW[2]+rowW[6]+rowW[5]+'Pinging:'+str(isPinging))
elif rowW[4] == 'rfrecived':
conndb4.execute("select h.Id from rfHistoria h left join rf r on h.Id = r.Id where Type LIKE 'Recive' and Timestamp >= %s and h.Id = %s",(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'),rowW[2]))
conditions.append(eval(rowW[6]+rowW[5]+str(bool(conndb4.rowcount))))
conditionsLog.append(rowW[4]+":"+rowW[6]+rowW[5]+str(bool(conndb4.rowcount)))
elif rowW[4] == 'cmd':
execCmd = execCustomCmd(conndb4,rowW[2],changedBy,False,True)
if execCmd[0]:
conditions.append(eval(str(execCmd[1]).rstrip()+rowW[5]+rowW[6]))
conditionsLog.append(rowW[4]+":"+str(execCmd[1]).rstrip()+rowW[5]+rowW[6])
else: conditions.append(False)
elif rowW[4] == 'var':
if rowW[47] == "String": conditions.append(eval("'"+str(rowW[46])+"'"+rowW[5]+"'"+str(rowW[6])+"'"))
elif rowW[47] == "Date": conditions.append(eval("strptime('"+rowW[46]+"','%Y-%m-%d %H:%M')"+rowW[5]+"strptime('"+rowW[6]+"','%Y-%m-%d %H:%M')"))
elif rowW[47] == "Time":
triggerHour = datetime.strptime(rowW[6],'%H:%M')
varHour = datetime.strptime(rowW[46],'%H:%M')
conditions.append(eval('varHour'+rowW[5]+'triggerHour'))
else: conditions.append(eval(str(rowW[46])+rowW[5]+rowW[6]))
conditionsLog.append(rowW[4]+":"+str(rowW[46])+rowW[5]+rowW[6])
elif rowW[4] == 'i/o link':
res = callLinkedPi(rowW[7],'Get_GPIO;'+rowW[2],conndb4)
# print res
if res:
planned = int(rowW[6])
cState = int(res[4])
reverse = int(res[8])
conditions.append(True if ((planned==cState and not reverse) or (planned==2 and planned==cState) or (planned!=cState and reverse and planned!=2)) else False)
conditionsLog.append(rowW[4]+":"+"State equals" if ((planned==cState and not reverse) or (planned==2 and planned==cState) or (planned!=cState and reverse and planned!=2)) else "State not equals")
else: conditions.append(False)
elif rowW[4] == 'sensor link':
res = callLinkedPi(rowW[7],'SENSOR_value;'+rowW[2],conndb4,1)
if res:
conditions.append(eval(res[2]+rowW[5]+rowW[6]))
conditionsLog.append(rowW[4]+":"+res[2]+rowW[5]+rowW[6])
else: conditions.append(False)
elif rowW[4] == 'rfrecived link':
res = callLinkedPi(rowW[7],'GetRfRecivedNow;'+rowW[2],conndb4,1)
if res:
conditions.append(eval(rowW[6]+rowW[5]+str(bool(int(res[2])))))
conditionsLog.append(rowW[4]+":"+rowW[6]+rowW[5]+str(bool(int(res[2]))))
else: conditions.append(False)
elif rowW[4] == 'var link':
res = callLinkedPi(rowW[7],'GetGlobalVar;'+rowW[2],conndb4,1)
if res:
if res[3] == 'String': conditions.append(eval("'"+str(res[2])+"'"+rowW[5]+"'"+str(rowW[6])+"'"))
elif res[3] == "Date": conditions.append(eval("strptime('"+res[2]+"','%Y-%m-%d %H:%M')"+rowW[5]+"strptime('"+rowW[6]+"','%Y-%m-%d %H:%M')"))
elif res[3] == "Time":
triggerHour = datetime.strptime(rowW[6],'%H:%M')
varHour = datetime.strptime(res[2],'%H:%M')
conditions.append(eval('varHour'+rowW[5]+'triggerHour'))
else: conditions.append(eval(res[2]+rowW[5]+rowW[6]))
conditionsLog.append(rowW[4]+":"+str(rowW[46])+rowW[5]+rowW[6])
else: conditions.append(False)
# print str(id)+str(conditions)
if len(conditions) > 0:
if row[3] == None or not row[3]:
i=1
for cond in conditions:
if len(conditions)==i:
conditionString+=str(cond)
else:
conditionString+=str(cond)+" and "
i+=1
i=1
for cond in conditionsLog:
if len(conditionsLog)==i:
conditionStringLog+=str(cond)
else:
conditionStringLog+=str(cond)+" and "
i+=1
else:
i=1
conditionString = row[3]
for cond in conditions:
conditionString = re.sub('#'+str(i)+'#', str(cond), conditionString)
i+=1
i=1
conditionStringLog = row[3]
for cond in conditionsLog:
conditionStringLog = re.sub('#'+str(i)+'#', str(cond), conditionStringLog)
i+=1
conjunctionValid = True
try:
eval(str(conditionString))
except:
pass
log.error("Wrong conjunction at "+row[10]+":"+str(conditionString))
conjunctionValid = False
noe = int(row[2])
if conditionString != '' and conjunctionValid and (noe > 0 or noe == -1):
if eval(str(conditionString)):
execuded = False
lastExecTime = strptime(row[11],'%Y-%m-%d %H:%M:%S.%f').replace(microsecond=0,second=0)
currentTime = datetime.utcnow().replace(microsecond=0,second=0)
isThereTimeTrigger = False
if ('date' in triggers or 'hour' in triggers) and 'cmd' not in triggers and 'sensors' not in triggers and 'rfrecived' not in triggers:
isThereTimeTrigger = True
if (row[1] == 'output' and not isThereTimeTrigger) or (row[1] == 'output' and isThereTimeTrigger and lastExecTime != currentTime):
execuded = outputChange(int(row[5]),row[4],conndb4,changedBy,True if row[13] else False)
elif (row[1] == 'pwm' and not isThereTimeTrigger) or (row[1] == 'pwm' and isThereTimeTrigger and lastExecTime != currentTime):
execuded = pwmChange(row[9],row[8],row[7],row[6],conndb4,changedBy,True if row[13] else False)
elif (row[1] == 'chain' and not isThereTimeTrigger) or (row[1] == 'chain' and isThereTimeTrigger and lastExecTime != currentTime):
#if int(row[5]): threading.Thread(target=chainExecude, args=(row[12], changedBy, True if row[13] else False)).start()
if int(row[5]): chainExecude(row[12],changedBy, True if row[13] else False)
else: conndb4.execute("UPDATE lancuchy set Status=0 WHERE Id=%s",(row[12],))
execuded = True
elif (row[1] == 'rfsend' and not isThereTimeTrigger) or (row[1] == 'rfsend' and isThereTimeTrigger and lastExecTime != currentTime):
sendRfCode(conndb4,row[14],False,True if row[13] else False)
execuded = True
elif (row[1] == 'cmd' and not isThereTimeTrigger) or (row[1] == 'cmd' and isThereTimeTrigger and lastExecTime != currentTime):
execCustomCmd(conndb4,row[16],changedBy,True if row[13] else False)
execuded = True
elif (row[1] == 'var' and not isThereTimeTrigger) or (row[1] == 'var' and isThereTimeTrigger and lastExecTime != currentTime):
conndb4.execute("UPDATE globalVariables set Val=%s,Timestamp=%s where Id=%s",(str(row[20]),datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),str(row[19])))
execuded = True
elif (row[1] == 'action_noe' and not isThereTimeTrigger) or (row[1] == 'action_noe' and isThereTimeTrigger and lastExecTime != currentTime):
conndb4.execute("UPDATE akcje set Rodzaj=%s, Edit_time=%s where Id=%s", (str(row[22]), datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),str(row[21])))
execuded = True
elif (row[1] == 'chain_ec' and not isThereTimeTrigger) or (row[1] == 'chain_ec' and isThereTimeTrigger and lastExecTime != currentTime):
conndb4.execute("Update lancuchy SET Edit_time=%s,ExecCountdown=%s WHERE Id=%s",(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),str(row[23]),str(row[12])))
execuded = True
if noe > 0 and execuded:
conndb4.execute("UPDATE akcje set Rodzaj=%s,Edit_time=%s where Id = %s", (str(noe-1),datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),row[0]))
elif execuded:
conndb4.execute("UPDATE akcje set Edit_time=%s where Id = %s", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),row[0]))
if execuded and row[13]: conndb4.execute("INSERT INTO historia(Typ, Id_a, Stan) VALUES(%s,%s,%s)", (conditionStringLog, str(row[0]), row[1]))
# conndb4.commit()
elif noe <= 0: break
if row[15] is not None: sleepTime = float(row[15])
else: sleepTime = 0.3
if idCE != 0: break
if updateCD <= 0: updateCD = 30
updateCD -= (time.time()-startTime)
startTime = time.time()
time.sleep(sleepTime)
except Exception as e:
print e.message
log.error(e.message)
log.error(traceback.format_exc())
conndb4.close()
conn.close()
sys.exit()
def chainExecude(id,changedBy,log=True):
conn, conndb = newDBConnP()
def cancelIf():
conndb.execute("SELECT Status from lancuchy WHERE Id=%s",(id,))
row1 = conndb.fetchone()
if row1[0] == 0: sys.exit()
conndb.execute("SELECT * FROM spoiwaLancuchow s WHERE Id_c = %s ORDER BY Lp",(id,))
chainBonds = conndb.fetchall()
conndb.execute("SELECT Status,ExecCountdown from lancuchy WHERE Id=%s",(id,))
sRow = conndb.fetchone()
status = int(sRow[0])
countdown = int(sRow[1])
if status == 0:
while (countdown > 0 or countdown == -1) and not exit_event.is_set():
for row in chainBonds:
if log and status == 0: conndb.execute("INSERT INTO historia(Typ, Id_c, Stan) VALUES(%s,%s,%s)", (changedBy, id, "START"))
status = row[2]
conndb.execute("UPDATE lancuchy SET Status=%s,Edit_time=%s WHERE Id=%s",(row[2],datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),id))
daley = float(row[3])
while daley > 0 and not exit_event.is_set():
start_time = time.time()
cancelIf()
time.sleep(1)
daley = daley-(time.time() - start_time)
cancelIf()
if row[4] == 'output':
if row[14]: callLinkedPi(row[14],'outputChange;'+str(row[7])+';'+str(row[6])+';'+str(int(log))+';'+changedBy,conndb,15)
else: outputChange(int(row[7]),row[6],conndb,changedBy,log)
elif row[4] == 'pwm':
if row[14]: callLinkedPi(row[14],'GPIO_PFRDC;'+str(row[8])+';0;'+str(row[9])+';'+str(row[10])+';0;'+str(row[11])+';'+str(int(log))+';'+changedBy,conndb,15)
else: pwmChange(row[11],row[10],row[9],row[8],conndb,changedBy,log)
elif row[4] == 'action':
if row[14]: callLinkedPi(row[14],'ActionCheck;'+str(row[5])+';'+changedBy,conndb,15)
else: action(row[5],int(id),changedBy)
elif row[4] == 'rfsend':
if row[14]: callLinkedPi(row[14],'SendRfCode;'+str(row[12])+';'+str(int(log))+';'+changedBy,conndb,15)
else: sendRfCode(conndb,row[12],False,log)
elif row[4] == 'cmd':
if row[14]: callLinkedPi(row[14],'ExecCustomCmd;'+str(row[13])+';0;'+changedBy+';'+str(int(log)),conndb,15)
else: execCustomCmd(conndb,row[13],changedBy,log)
elif row[4] == 'chain':
if int(row[7]) and row[14]: callLinkedPi(row[14],'GPIO_ChainExecute;'+str(row[16])+';'+changedBy,conndb,15)
elif int(row[7]) and not row[14]: chainExecude(row[16],changedBy,log)
elif not int(row[7]) and row[14]: callLinkedPi(row[14],'GPIO_ChainCancel;'+str(row[16])+';'+changedBy,conndb,15)
else: conndb.execute("UPDATE lancuchy set Status=0 WHERE Id=%s",(row[12],))
elif row[4] == 'var':
if row[14]: callLinkedPi(row[14],'SetGlobalVar;'+str(row[17])+';'+str(row[18])+';'+changedBy+';'+str(int(log)),conndb,15)
else: conndb.execute("UPDATE globalVariables set Val=%s,Timestamp=%s where Id=%s",(str(row[18]),datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),str(row[17])))
elif row[4] == 'action_noe':
if row[14]: callLinkedPi(row[14],'SetActionNOE;'+str(row[5])+';'+str(row[19])+';'+changedBy+';'+str(int(log)),conndb,15)
else: conndb.execute("UPDATE akcje set Rodzaj=%s, Edit_time=%s where Id=%s", (str(row[19]), datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),str(row[5])))
elif row[4] == 'chain_ec':
if row[14]: callLinkedPi(row[14],'SetChainEC;'+str(row[16])+';'+str(row[20])+';'+changedBy+';'+str(int(log)),conndb,15)
else: conndb.execute("Update lancuchy SET Edit_time=%s,ExecCountdown=%s WHERE Id=%s",(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),str(row[20]),str(row[16])))
if (len(chainBonds)) == row[2] and countdown == 1:
conndb.execute("UPDATE lancuchy SET Status=%s,Edit_time=%s WHERE Id=%s",(0,datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),id))
if log: conndb.execute("INSERT INTO historia(Typ, Id_c, Stan) VALUES(%s,%s,%s)", (changedBy, id, "END"))
if countdown != -1: countdown -= 1
conndb.close()
conn.close()
def execCustomCmd(conndb,id,changedBy,log=True,disableThreading=False):
def afterExec(cmdProcess,inThread=False):
output, errors = cmdProcess.communicate()
if cmdProcess.returncode:
log.error(errors)
return (False,errors)
else:
if log:
conndb.execute("INSERT INTO Historia(Typ, Stan, Id_cmd) VALUES(%s,%s,%s)", (changedBy,output,id))
return (True,output)
conndb.execute("SELECT * from customCmds WHERE Id = %s", (id,))
row = conndb.fetchone()
cmdProcess = subprocess.Popen(row[2], stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=4096, shell=True)
if row[3] or disableThreading: return afterExec(cmdProcess)
else:
threading.Thread(target=afterExec, args=(cmdProcess,True)).start()
return (True,'Exec started')
def outputChange(plannedState,id,cdb,changedBy,log=True):
cdb.execute("SELECT * FROM Stany WHERE Id=%s",(id,))
row = cdb.fetchone()
currentState = int(row[2])
Reverse = int(row[6])
GPIO_BCM = row[1]
if (currentState != plannedState and not Reverse) or (currentState == plannedState and Reverse) or plannedState == 2:
if plannedState == 2:
set = int(not currentState)
elif Reverse:
set = int(not plannedState)
else:
set = plannedState
GPIOset(str(GPIO_BCM), set)
gpiolist = str(GPIO_BCM).split(",")
for gpio in gpiolist:
cdb.execute("UPDATE stany set Stan =2,Edit_time=%s where (GPIO_BCM like %s and Id!=%s and IN_OUT like 'out') or (GPIO_BCM like %s and Id!=%s and IN_OUT like 'out');", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), "%"+gpio+",%", id, "%,"+gpio+"%", id))
cdb.execute("UPDATE stany set Stan =%s,Edit_time=%s where GPIO_BCM =%s and Id!=%s and IN_OUT like 'out' ;", (set, datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), gpio, id))
cdb.execute("UPDATE stany set Stan =%s, Edit_time=%s where Id=%s", (set, datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), id))
if log: cdb.execute("INSERT INTO historia(Typ, Id_IO, Stan) VALUES(%s,%s,%s)", (changedBy, id, "ON" if ((set and not Reverse) or (not set and Reverse)) else "OFF"))
return True
else: return False
def pwmChange(planed_ss,planned_dc,planned_fr,id,cdb,changedBy,log=True):
cdb.execute("SELECT * FROM Pwm WHERE Id=%s",(id,))
row = cdb.fetchone()
current_ss = row[4]
current_dc = row[3]
current_fr = row[2]
pwmpins = row[1].split(",")
if planed_ss == 2:
set = not current_ss
else:
set = planed_ss
for pin in pwmpins:
if current_ss!=set and set == 1:
pwm[pin].start(int(planned_dc) if planned_dc else int(current_dc))
if (current_ss!=set and set == 1) or (planned_fr!=current_fr and planned_fr and set == 1):
pwm[pin].ChangeFrequency(float(planned_fr) if (planned_fr)else float(current_fr))
if planned_dc and current_dc!=planned_dc and set == 1:
pwm[pin].ChangeDutyCycle(int(planned_dc))
if current_ss!=set and set == 0:
pwm[pin].stop()
if current_ss!=set or (current_dc!=planned_dc and planned_dc) or (current_fr!=planned_fr and planned_fr):
cdb.execute("UPDATE pwm set FR=%s,DC=%s,Edit_time=%s,SS=%s where Id=%s",(planned_fr if (planned_fr)else current_fr,planned_dc if (planned_dc)else current_dc, datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), set, id))
if log: cdb.execute("INSERT INTO historia(Typ, Id_Pwm, Stan) VALUES(%s,%s,%s)", (changedBy, id, ("OFF" if set==0 else "ON")+":DC="+(str(planned_dc) if planned_dc else str(current_dc))+"%,FR="+(str(planned_fr) if planned_fr else str(current_fr))+"Hz"))
if debug: print 'BY SHEDULED:'+str(id)+(" OFF" if set==0 else " ON")+":DC="+(str(planned_dc) if planned_dc else str(current_dc))+"%,FR="+(str(planned_fr) if planned_fr else str(current_fr))+"Hz"
return True
else: return False
def GPIOset(pinout, onoff):
pins = pinout.split(",")
onoff = int(onoff)
if onoff < 2:
for pin in pins:
pin = int(pin)
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, onoff)
def GPIOinputSet(inpin, resistor, method, id, stan, reverse, time):
channel = int(inpin)
if resistor == 1: GPIO.setup(channel, GPIO.IN, GPIO.PUD_UP)
elif resistor == 2: GPIO.setup(channel, GPIO.IN, GPIO.PUD_DOWN)
else: GPIO.setup(channel, GPIO.IN)
if(method == 'ined'):
cb = debounceHandler(channel, lambda channel, id=id, reverse=reverse: inputCallback(channel, id, reverse),bouncetime=200 if not time else int(time))
cb.daemon = True
cb.start()
GPIO.add_event_detect(channel, GPIO.BOTH, callback=cb)
else:
p1 = multiprocessing.Process(target=inputLoop, args=(id, channel, stan, reverse, time))
p1.daemon = True
p1.start()
running_proceses.append(p1)
def GPIOPWM(inpin, fr):
GPIO.setup(inpin, GPIO.OUT)
return GPIO.PWM(inpin, fr)
def inputCallback(channel, id, reverse):
conn, conndb = newDBConnP()
#print str(GPIO.input(channel))+';'+str(reverse)+';'+str(channel)
if GPIO.input(channel):
conndb.execute("UPDATE stany set Stan =0,Edit_time=%s where Id=%s", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), str(id)))
conndb.execute("INSERT INTO historia(Typ, Id_IO, Stan) VALUES(%s,%s,%s)",("input", id, "ON" if reverse else "OFF"))
else:
conndb.execute("UPDATE stany set Stan =1,Edit_time=%s where Id=%s", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), str(id)))
conndb.execute("INSERT INTO historia(Typ, Id_IO, Stan) VALUES(%s,%s,%s)",("input", id, "ON" if (not reverse) else "OFF"))
conndb.close()
conn.close()
class debounceHandler(threading.Thread):
def __init__(self, pin, func, edge='both', bouncetime=200):
super(debounceHandler,self).__init__()
self.edge = edge
self.func = func
self.pin = pin
self.bouncetime = float(bouncetime)/1000
self.lastpinval = GPIO.input(self.pin)
self.lock = threading.Lock()
def __call__(self, *args):
if not self.lock.acquire():
return
t = threading.Timer(self.bouncetime, self.read, args=args)
t.start()
def read(self, *args):
pinval = GPIO.input(self.pin)
if (
((pinval == 0 and self.lastpinval == 1) and
(self.edge in ['falling', 'both'])) or
((pinval == 1 and self.lastpinval == 0) and
(self.edge in ['rising', 'both']))
):
self.func(*args)
self.lastpinval = pinval
self.lock.release()
def inputLoop(id, inpin, Stan, reverse, SleepTime):
def exitLoop(conn,conndb):
conndb.close()
conn.close()
sys.exit()
inpin = int(inpin)
Stan = int(Stan)
if Stan == 0: stan = 2
elif Stan == 1: stan = 4
else: stan = 2
conn, conndb = newDBConnP()
sleepTime = 0.05
if SleepTime:
if float(SleepTime) > 0: sleepTime = float(SleepTime)/1000
global exit_event
while not exit_event.is_set():
conndb.execute("SELECT id FROM stany WHERE Id = %s",(id,))
row = conndb.fetchone()
if row is None:
exitLoop(conn, conndb)
if stan == 2:
if GPIO.input(inpin) == 0:
conndb.execute("UPDATE stany set Stan =1,Edit_time=%s where Id=%s", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), str(id)))
conndb.execute("INSERT INTO historia(Typ, Id_IO, Stan) VALUES(%s,%s,%s)",("input", id, "ON" if (not reverse) else "OFF"))
stan = 4
if stan == 4:
if GPIO.input(inpin) == 1:
conndb.execute("UPDATE stany set Stan =0,Edit_time=%s where Id=%s", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), str(id)))
conndb.execute("INSERT INTO historia(Typ, Id_IO, Stan) VALUES(%s,%s,%s)",("input", id, "ON" if reverse else "OFF"))
stan = 2
time.sleep(sleepTime)
exitLoop(conn,conndb)
def newDBConnP():
connectionString = "dbname='{}' user='{}' host='{}' password='{}'".format(parser.get('postgresql','db'),parser.get('postgresql','user'),parser.get('postgresql','host'),parser.get('postgresql','password'))
conn = psycopg2.connect(connectionString)
conn.set_session(autocommit=True)
cur = conn.cursor(cursor_factory=DictCursor)
return conn,cur
def callLinkedPi(id,data,conndb,timeout=5):
try:
conndb.execute("SELECT * FROM linkedPis WHERE Id = %s",(id,))
row = conndb.fetchone()
if row[3]:
L_PASSWORD = hashlib.sha256(row[3].encode()).hexdigest()
L_ENC_KEY = hashlib.md5(row[3].encode()).hexdigest()
data = L_PASSWORD+";"+encrypt(L_ENC_KEY, data+";"+os.uname()[1])
else: data = "1;"+data+";"+os.uname()[1]
if row[4] == 'UDP':
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(timeout)
sock.sendto(data, (row[2],row[5]))
response = sock.recvfrom(1024)[0].split(';')
sock.close()
else:
req = urllib2.Request(row[2], data, {'Content-Type': 'raw'})
f = urllib2.urlopen(req, timeout = timeout)
response = f.read().split(';')
f.close()
if response[0] == 'false': raise Exception(response[1])
if row[3]: response = decrypt(L_ENC_KEY,response[1]).split(';')
#print response
return response
except Exception as e:
log.error(e)
return False
def requestMethod(data):
datalist = data.split(";")
passwalidation = False
httpCode = 200
if PASSWORD == '':
passwalidation = True
else:
if datalist[0] == PASSWORD:
temp = decrypt(ENC_KEY, datalist[1])
if temp == 'error':
passwalidation = False
print 'Decrytion error'
else:
datalist = ("0;"+temp).split(";")
data = temp
passwalidation = True
else:
passwalidation = False
if debug: print 'RECIVED: '+data
conn,conndb = newDBConnP()
global doRestartAfterReply
if passwalidation == True:
if datalist[1] == 'version_check':
reply = 'true;version_check;'+str(CODE_VERSION)+';'
elif datalist[1] == 'GPIO_OEtime':
cursor = conndb.execute("SELECT Max(Edit_time) FROM stany where IN_OUT like 'out'")
for row in conndb.fetchall():
reply = 'true;GPIO_OEtime;'+str(row[0])+';'
elif datalist[1] == 'GPIO_Olist':
cursor = conndb.execute("SELECT * from stany where IN_OUT like 'out' ORDER BY Id DESC")
reply = 'true;GPIO_Olist;'
for row in conndb.fetchall():
reply += str(row[0])+';'+str(row[1])+';'+str(row[2]) +';'+str(row[3])+';'+str(row[6])+';'+str(row[8])+';'
elif datalist[1] == 'Get_GPIO':
conndb.execute("SELECT * from stany where Id = %s",(datalist[2],))
row = conndb.fetchone()
reply = 'true;Get_GPIO;'+";".join(map(str, row))+";"
elif datalist[1] == 'GPIO_OlistT0':
cursor = conndb.execute("SELECT * from stany where IN_OUT like 'out' AND Bindtype = 0 ORDER BY Id DESC")
reply = 'true;GPIO_OlistT0;'
for row in conndb.fetchall():
reply += str(row[0])+';'+str(row[1])+';'+str(row[2])+';'+str(row[3])+';'+str(row[6])+';'+str(row[8])+';'
elif datalist[1] == 'Add_GPIO_out':
conndb.execute("INSERT INTO stany VALUES (DEFAULT,%s,2,%s,'out',%s,%s,null,%s) RETURNING Id", (datalist[2], datalist[3], datalist[4], datalist[5], datalist[6]))
idio = conndb.fetchone()[0]
conndb.execute("INSERT INTO historia(Typ, Id_IO, Stan) VALUES(%s,%s,%s)", (datalist[7], str(idio), "ADDED"))
reply = 'true;Add_GPIO_out;'
elif datalist[1] == 'Edit_GPIO_out':
conndb.execute("UPDATE stany set Stan=2, GPIO_BCM=%s,Name=%s, Edit_time=%s, reverse=%s, Bindtype=%s where Id=%s", (
datalist[3], datalist[4], datalist[5], datalist[6], datalist[8], datalist[2]))
conndb.execute("INSERT INTO historia(Typ, Id_IO, Stan) VALUES(%s,%s,%s)", (datalist[9], datalist[2], "EDITED"))
pwmpins = datalist[3].split(',')
pwmpins2 = datalist[7].split(',')
for pin2 in pwmpins2:
if pin2 not in pwmpins:
GPIO.cleanup(int(pin2))
reply = 'true;Edit_GPIO_out;'
elif datalist[1] == 'Delete_GPIO_out':
conndb.execute("DELETE from stany where Id=%s", (datalist[2],))
conndb.execute("UPDATE stany set Edit_time=%s where Id in (SELECT Id FROM stany LIMIT 1)", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),))
conndb.execute("DELETE from historia where Id_IO=%s", (datalist[2],))
conndb.execute("INSERT INTO historia(Typ, Id_IO, Stan) VALUES(%s,%s,%s)",(datalist[5], datalist[2], datalist[4]+" DELETED"))
conndb.execute("DELETE FROM spoiwaLancuchow WHERE Out_id=%s", (datalist[2],))
r2 = conndb.rowcount
if r2 > 0:
conndb.execute("UPDATE lancuchy set Edit_time=%s where Id in (SELECT Id FROM lancuchy LIMIT 1)", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),))
conndb.execute("DELETE FROM akcje WHERE Out_id=%s", (datalist[2],))
r3 = conndb.rowcount
conndb.execute("DELETE FROM wyzwalaczeAkcji WHERE Id_s=%s AND Warunek = 'i/o'", (datalist[2],))
r4 = conndb.rowcount
if r3 > 0 or r4 > 0:
conndb.execute("UPDATE akcje set Edit_time=%s where Id in (SELECT Id FROM akcje LIMIT 1)", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),))
pwmpins = datalist[3].split(",")
for pin in pwmpins:
GPIO.cleanup(int(pin))
if datalist[4] == 'ined':
GPIO.remove_event_detect(int(datalist[3]))
reply = 'true;Delete_GPIO_out;'+datalist[2]+';'
elif datalist[1] == 'GPIO_IEtime':
cursor = conndb.execute("SELECT Max(Edit_time) FROM stany where IN_OUT like 'in%'")
for row in conndb.fetchall():
reply = 'true;GPIO_IEtime;'+str(row[0])+';'
elif datalist[1] == 'GPIO_Ilist':
cursor = conndb.execute("SELECT * from stany where IN_OUT like 'in%' ORDER BY Id DESC")
reply = 'true;GPIO_Ilist;'
for row in conndb.fetchall():
reply += str(row[0])+';'+str(row[1])+';'+str(row[2])+';'+str(row[3])+';'+str(row[6])+';'+str(row[7])+';'+str(row[8])+';'+row[4]+';'
elif datalist[1] == 'Add_GPIO_in':
conndb.execute("INSERT INTO stany VALUES (DEFAULT,%s,0,%s,%s,%s,%s,%s,%s) RETURNING Id", (datalist[2], datalist[3],datalist[8], datalist[4], datalist[5], (float(datalist[6])*1000), datalist[7]))
id = conndb.fetchone()[0]
conndb.execute("INSERT INTO historia(Typ, Id_IO, Stan) VALUES(%s,%s,%s)", (datalist[9], str(id), "ADDED"))
GPIOinputSet(datalist[2],1 if not datalist[7] else int(datalist[7]), datalist[8], id, 0, int(datalist[5]), (float(datalist[6])*1000))
reply = 'true;Add_GPIO_in;'
elif datalist[1] == 'Edit_GPIO_in':
conndb.execute("DELETE from stany where Id=%s", (datalist[2],))
conndb.execute("DELETE from historia where Id_IO=%s", (datalist[2],))
conndb.execute("INSERT INTO stany VALUES (DEFAULT,%s,0,%s,%s,%s,%s,%s,%s) RETURNING Id", (datalist[3], datalist[4],datalist[10], datalist[5], datalist[6], (float(datalist[7])*1000), datalist[8]))
id = conndb.fetchone()[0]
conndb.execute("INSERT INTO historia(Typ, Id_IO, Stan) VALUES(%s,%s,%s)", (datalist[11], str(id), "EDITED"))
if(datalist[10] == 'ined'): GPIO.remove_event_detect(int(datalist[9]))
GPIO.cleanup(int(datalist[9]))
GPIOinputSet(datalist[3],1 if not datalist[8] else int(datalist[8]), datalist[10], id, 0, int(datalist[6]), (float(datalist[7])*1000))
reply = 'true;Edit_GPIO_in;'
elif datalist[1] == 'GPIO_Oname':
cursor = conndb.execute("SELECT Id,Name,GPIO_BCM,Reverse from stany where IN_OUT like 'out' ORDER BY Id DESC")
reply = 'true;GPIO_Oname;'
for row in conndb.fetchall():
reply += str(row[0])+';'+str(row[1]) +';'+str(row[2])+';'+str(row[3])+';'
elif datalist[1] == 'GPIO_PEtime':
cursor = conndb.execute("SELECT Max(Edit_time) FROM pwm")
for row in conndb.fetchall():
reply = 'true;GPIO_PEtime;'+str(row[0])+';'
elif datalist[1] == 'GPIO_Plist':
cursor = conndb.execute("SELECT * from pwm ORDER BY Id DESC")
reply = 'true;GPIO_Plist;'
for row in conndb.fetchall():
reply += str(row[0])+';'+str(row[1])+';'+str(row[2])+';'+str(row[3])+';'+str(row[4])+';'+str(row[5])+';'+str(row[6])+';'
elif datalist[1] == 'GPIO_PDC':
pwmpins = datalist[3].split(",")
for pin in pwmpins:
pwm[pin].ChangeDutyCycle(int(datalist[4]))
reply = 'true;GPIO_PDC;'+datalist[4]+';'
elif datalist[1] == 'GPIO_PDCu':
conndb.execute("UPDATE pwm set DC=%s,Edit_time=%s where Id=%s",(datalist[4], datalist[5], datalist[2]))
conndb.execute("INSERT INTO historia(Typ, Id_Pwm, Stan) VALUES(%s,%s,%s)",(datalist[6], datalist[2], "DC="+datalist[4]+"%"))
reply = 'true;GPIO_PDCu;'+datalist[4]+';'+datalist[5]+';'
elif datalist[1] == 'GPIO_PFRDC':
pwmChange(int(datalist[7]),int(datalist[5]),float(datalist[4]),datalist[2],conndb,datalist[9],bool(int(datalist[8])))
reply = 'true;GPIO_PFRDC;' + datalist[4]+';'+datalist[6]+';'+datalist[5]+';'
elif datalist[1] == 'GPIO_PSS':
pwmpins = datalist[3].split(",")
for pin in pwmpins:
if datalist[6] == '1':
pwm[pin].start(int(datalist[4]))
pwm[pin].ChangeFrequency(float(datalist[7]))
conndb.execute("INSERT INTO historia(Typ, Id_Pwm, Stan) VALUES(%s,%s,%s)", (datalist[8], datalist[2], "ON:DC="+datalist[4]+"%,FR="+datalist[7]+"Hz"))
elif datalist[6] == '0':
pwm[pin].stop()
conndb.execute("INSERT INTO historia(Typ, Id_Pwm, Stan) VALUES(%s,%s,%s)", (datalist[8], datalist[2], "OFF"))
conndb.execute("UPDATE pwm set DC=%s,Edit_time=%s,SS=%s where Id=%s",(datalist[4], datalist[5], datalist[6], datalist[2]))
reply = 'true;GPIO_PSS;' + datalist[4]+';'+datalist[5]+';'+datalist[6]+';'
elif datalist[1] == 'Add_GPIO_pwm':
pwmpins = datalist[2].split(',')
for pin in pwmpins:
pwm[pin] = GPIOPWM(int(pin), float(datalist[3]))
pwm[pin].start(int(datalist[4]))
conndb.execute("INSERT INTO pwm VALUES (DEFAULT,%s,%s,%s,1,%s,%s,%s) RETURNING Id", (datalist[2], datalist[3], datalist[4], datalist[5], datalist[6], datalist[7]))
idpwm = conndb.fetchone()[0]
conndb.execute("INSERT INTO historia(Typ, Id_Pwm, Stan) VALUES(%s,%s,%s)", (datalist[8], str(idpwm), "ADDED:DC="+datalist[4]+"%,FR="+datalist[3]+"Hz"))
reply = 'true;Add_GPIO_pwm;'
elif datalist[1] == 'Delete_GPIO_pwm':
conndb.execute("DELETE from pwm where Id=%s", (datalist[2],))
conndb.execute("DELETE from historia where Id_Pwm=%s", (datalist[2],))
conndb.execute("UPDATE pwm set Edit_time=%s where Id in (SELECT Id FROM pwm LIMIT 1)", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),))
conndb.execute("INSERT INTO historia(Typ, Id_Pwm, Stan) VALUES(%s,%s,%s)",(datalist[5], datalist[2], datalist[4]+" DELETED"))
conndb.execute("DELETE FROM spoiwaLancuchow WHERE Pwm_id=%s", (datalist[2],))
r2 = conndb.rowcount
if r2 > 0:
conndb.execute("UPDATE lancuchy set Edit_time=%s where Id in (SELECT Id FROM lancuchy LIMIT 1)", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),))
conndb.execute("DELETE FROM akcje WHERE Pwm_id=%s", (datalist[2],))
r3 = conndb.rowcount
conndb.execute("DELETE FROM wyzwalaczeAkcji WHERE Id_s=%s AND Warunek LIKE 'pwm%%'", (datalist[2],))
r4 = conndb.rowcount
if r3 > 0 or r4 > 0:
conndb.execute("UPDATE akcje set Edit_time=%s where Id in (SELECT Id FROM akcje LIMIT 1)", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),))
pwmpins = datalist[3].split(',')
for pin in pwmpins:
pwm[pin].stop()
pwm.pop(pin)
GPIO.cleanup(int(pin))
reply = 'true;Delete_GPIO_pwm;'
elif datalist[1] == 'Edit_GPIO_pwm':
pwmpins = datalist[3].split(',')
pwmpins2 = datalist[4].split(',')
for pin in pwmpins:
if pin not in pwmpins2:
pwm[pin].stop()
pwm.pop(pin)
GPIO.cleanup(int(pin))
for pin2 in pwmpins2:
if pin2 not in pwmpins:
pwm[pin2] = GPIOPWM(int(pin2), float(datalist[5]))
pwm[pin2].start(int(datalist[6]))
else:
pwm[pin2].ChangeDutyCycle(int(datalist[6]))
pwm[pin2].ChangeFrequency(float(datalist[5]))
conndb.execute("UPDATE pwm set GPIO_BCM=%s, FR=%s, DC=%s, SS=1, Name=%s, Reverse=%s, Edit_time=%s where Id=%s", (datalist[4], datalist[5], datalist[6], datalist[7], datalist[8], datalist[9], datalist[2]))
conndb.execute("INSERT INTO historia(Typ, Id_Pwm, Stan) VALUES(%s,%s,%s)", (datalist[10], datalist[2], "EDITED:DC="+datalist[6]+"%,FR="+datalist[5]+"Hz"))
reply = 'true;Edit_GPIO_pwm;'
elif datalist[1] == 'Allpins_GPIO_pwm':
reply = 'true;Allpins_GPIO_pwm;'
cursor = conndb.execute("SELECT GPIO_BCM from pwm")
for row in conndb.fetchall():
pins = row[0].split(',')
for pin in pins:
reply += pin+';'
elif datalist[1] == 'Allpins_GPIO_out':
reply = 'true;Allpins_GPIO_out;'
cursor = conndb.execute("SELECT GPIO_BCM from stany where IN_OUT like 'out'")
for row in conndb.fetchall():
pins = str(row[0]).split(',')
for pin in pins: reply += pin+';'
elif datalist[1] == 'AllUsedPins_GPIO':
reply = 'true;AllUsedPins_GPIO;'
sqlExec ='''
(SELECT GPIO_BCM from stany WHERE IN_OUT like 'out' AND Id != {id_out})
UNION
(SELECT GPIO_BCM from stany WHERE IN_OUT like 'in%' AND Id != {id_in})
UNION
(SELECT GPIO_BCM from pwm WHERE Id != {id_pwm})
UNION
(SELECT GPIO_BCM from sensory WHERE Id NOT LIKE '{id_s}')
'''.format(id_out = datalist[3] if datalist[2] == 'out' else 0,id_in = datalist[3] if datalist[2] == 'in' else 0,id_pwm = datalist[3] if datalist[2] == 'pwm' else 0,id_s = datalist[3] if datalist[2] == 'sensor' else '')
if datalist[2] == 'out': sqlExec = sqlExec.split("\n",3)[3]
cursor = conndb.execute(sqlExec)
for row in conndb.fetchall():
pins = str(row[0]).split(',')
for pin in pins: reply += pin+';'
elif datalist[1] == 'Allpins_GPIO_in':
reply = 'true;Allpins_GPIO_in;'
cursor = conndb.execute("SELECT GPIO_BCM from stany where IN_OUT like 'in%'")
for row in conndb.fetchall():
reply += str(row[0])+';'
elif datalist[1] == 'ActionCheck':
action(datalist[2],1,datalist[3])
reply = 'true;ActionCheck;'
elif datalist[1] == 'outputChange':
outputChange(int(datalist[2]),datalist[3],conndb,datalist[5],bool(int(datalist[4])))
reply = 'true;outputChange;'
elif datalist[1] == 'GPIO_set':
GPIOset(datalist[3], datalist[4])
reply = 'true;GPIO_set;'+datalist[4]+';'+datalist[5]+';'
gpiolist = datalist[3].split(",")
for gpio in gpiolist:
conndb.execute("UPDATE stany set Stan =2,Edit_time=%s where (GPIO_BCM like %s and Id!=%s and IN_OUT like 'out') or (GPIO_BCM like %s and Id!=%s and IN_OUT like 'out');", (datalist[5], "%"+gpio+",%", datalist[2], "%,"+gpio+"%", datalist[2]))
r1 = conndb.rowcount
conndb.execute("UPDATE stany set Stan =%s,Edit_time=%s where GPIO_BCM =%s and Id!=%s and IN_OUT like 'out' ;", (datalist[4], datalist[5], gpio, datalist[2]))
r2 = conndb.rowcount
conndb.execute("UPDATE stany set Stan =%s,Edit_time=%s where Id=%s",(datalist[4], datalist[5], datalist[2]))
stan = int(datalist[4])
reverse = int(datalist[6])
conndb.execute("INSERT INTO historia(Typ, Id_IO, Stan) VALUES(%s,%s,%s)", (datalist[7], datalist[2], "ON" if ((stan and not reverse) or (not stan and reverse)) else "OFF"))
if r1 > 0 or r2 > 0:
reply = 'true;GPIO_set;' +datalist[4]+';2000-01-01 00:00:00.000;'
elif datalist[1] == 'GPIO_state':
GPIO.setup(int(datalist[2]), GPIO.OUT)
reply = 'true;GPIO_state;' + str(datalist[2])+';'+str(GPIO.input(int(pin)))+';'
elif datalist[1] == 'HR_count':
cursor = conndb.execute("SELECT COUNT(*) FROM historia where Czas between %s and %s", (datalist[2], datalist[3]))
for row in conndb.fetchall(): reply = 'true;HR_count;'+str(row[0])+';'
elif datalist[1] == 'SENSOR_list':
reply = 'true;SENSOR_list;'
cursor = conndb.execute("SELECT *,(SELECT Value from sensoryHistoria h WHERE h.Id=s.Id ORDER BY Timestamp DESC LIMIT 1),(SELECT Timestamp from sensoryHistoria h WHERE h.Id=s.Id ORDER BY Timestamp DESC LIMIT 1) from sensory s")
for row in conndb.fetchall():
reply += str(row[0])+";"+str(row[1])+";"+str(row[4])+";"+str(row[10])+";"+str(row[2])+";"+str(row[3])+";"+str(row[5])+";"+str(row[11])+";"+str(row[9])+";"+str(row[7])+";"+str(row[8])+";"
elif datalist[1] == 'SENSOR_value':
value = getCurrentSensorValue(datalist[2],conndb)
if value == None: reply = 'false;SENSOR_value;'+str(value)+";"
else: reply = 'true;SENSOR_value;'+str(value)+";"
elif datalist[1] == 'SENSOR_names':
reply = 'true;SENSOR_names;'
cursor = conndb.execute("SELECT * from sensory ORDER BY Id DESC")
for row in conndb.fetchall():
reply += str(row[0])+";"+str(row[1]) + ";"+str(row[5])+";"
elif datalist[1] == 'SENSOR_update':
reply = 'true;SENSOR_update;'
conndb.execute("UPDATE sensory set Name =%s,H_refresh_sec=%s,H_keep_days=%s where Id=%s", (datalist[3], datalist[4], datalist[5], datalist[2]))
elif datalist[1] == 'SENSOR_addCustom':
conndb.execute("SELECT * from sensory where Type like 'custom'")
cursor = conndb.fetchall()
customNumber = len(cursor)+1
while True:
conndb.execute("SELECT * from sensory where Id = %s",('Custom'+str(customNumber),))
cursor = conndb.fetchall()
if len(cursor) == 0: break
else: customNumber+=1
conndb.execute("INSERT INTO sensory(Id,Name,H_refresh_sec,H_keep_days,Type,Unit,GPIO_BCM,Data_Name,Cmd_id) VALUES(%s,%s,%s,%s,'custom',%s,%s,%s,%s) RETURNING Id", ('Custom'+str(customNumber),datalist[2],datalist[3],datalist[4],datalist[5],datalist[6],datalist[7],datalist[8]))
reply = 'true;SENSOR_addCustom;'+str(conndb.fetchone()[0])
updateSensorHistory('Custom'+str(customNumber),conndb)
elif datalist[1] == 'SENSOR_updateCustom':
reply = 'true;SENSOR_updateCustom;'
conndb.execute("UPDATE sensory set Name=%s,H_refresh_sec=%s,H_keep_days=%s,Unit=%s,GPIO_BCM=%s,Data_Name=%s,Cmd_id=%s where Id=%s", (datalist[3], datalist[4], datalist[5],datalist[6],datalist[7],datalist[8],datalist[9], datalist[2]))
elif datalist[1] == 'SENSOR_remove':
reply = 'true;SENSOR_remove;'
conndb.execute("DELETE from sensory where Id=%s", (datalist[2],))
conndb.execute("DELETE from sensoryHistoria WHERE Id=%s", (datalist[2],))
conndb.execute("DELETE FROM wyzwalaczeAkcji WHERE Id_s=%s AND Warunek LIKE 'sensor'", (datalist[2],))
if conndb.rowcount > 0:
conndb.execute("UPDATE akcje set Edit_time=%s where Id in (SELECT Id FROM akcje LIMIT 1)", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),))
elif datalist[1] == 'NOTIF_check':
reply = 'true;NOTIF_check;'
if datalist[3] == "i/o":
reply += "0;"
if datalist[4] == "ANY":
cursor = conndb.execute("SELECT * from historia h JOIN stany s ON h.Id_IO=s.Id WHERE h.Id_IO = %s AND h.Czas > %s ORDER BY h.Czas DESC", (datalist[2], datalist[6]))
else:
cursor = conndb.execute("SELECT * from historia h JOIN stany s ON h.Id_IO=s.Id WHERE h.Id_IO = %s AND h.Czas > %s AND h.Stan = %s ORDER BY h.Czas DESC", (datalist[2], datalist[6], datalist[4]))
for row in conndb.fetchall():
reply += str(row[12])+';'+str(row[1]) +';'+str(row[2])+';'+str(row[5])+';'
elif datalist[3] == "sensor":
updateSensorHistory(datalist[2],conndb)
cursor = conndb.execute("SELECT * from sensoryHistoria h JOIN sensory s ON h.Id = s.Id WHERE h.Id = %s AND h.Timestamp > %s AND h.Value "+datalist[5]+" %s ORDER BY h.Timestamp DESC", (datalist[2], datalist[6], datalist[4]))
i = 0
for row in conndb.fetchall():
if i == 0: reply += str(row[8])+';'
reply += str(row[4])+';'+str(row[1]) + ';'+str(row[7])+';'+str(row[2])+';'
i = i+1
elif datalist[1] == 'GPIO_OInames':
cursor = conndb.execute("SELECT Id,Name from stany ORDER BY Id DESC")
reply = 'true;GPIO_OInames;'
for row in conndb.fetchall():
reply += str(row[0])+';'+str(row[1])+';'
elif datalist[1] == 'GPIO_PWMnames':
cursor = conndb.execute("SELECT Id,Name from pwm ORDER BY Id DESC")
reply = 'true;GPIO_PWMnames;'
for row in conndb.fetchall():
reply += str(row[0])+';'+str(row[1])+';'
elif datalist[1] == 'GPIO_ASAEtime':
cursor = conndb.execute("SELECT Max(Edit_time) FROM akcje")
reply = 'true;GPIO_ASAEtime;'+str(conndb.fetchone()[0])+';'
elif datalist[1] == 'startStopASA':
conndb.execute("UPDATE akcje set Cpu_usage=0, Rodzaj=%s, Edit_time=%s where Id=%s", (datalist[3], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), datalist[2]))
reply = 'true;startStopASA;'
elif datalist[1] == 'GPIO_ASAlist':
cursor = conndb.execute('SELECT a.id as "a_id", a.typ as "a_type", a.rodzaj as "a_noe", a.koniunkcja, a.out_id, a.out_stan, a.pwm_id, a.pwm_fr, a.pwm_dc, a.pwm_ss, a.nazwa as "a_name", s.name as "out_name",s.reverse as "out_reverse", p.name as "pwm_name",a.chain_id, a.log as "a_log",l.nazwa as "chain_name", a.rf_id, r.name as "rf_name", a.cmd_id, c.name as "cmd_name", a.refresh_rate, a.cpu_usage, a.v_id, a.v_val, v.name as "v_name", a.a_id, a.a_noe, a.chain_ec from akcje a left join stany s on a.Out_id = s.Id left join pwm p on a.Pwm_id = p.Id left join lancuchy l on a.Chain_id = l.Id left join rf r on a.Rf_id = r.Id left join customCmds c on a.Cmd_id = c.Id LEFT JOIN globalVariables v ON a.V_id = v.Id ORDER BY a.Id DESC')
reply = 'true;GPIO_ASAlist;'
for row in conndb.fetchall():
reply += ";".join(map(str, [row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9],row[10],row[11],row[12],row[13],row[14],row[15],row[16],row[17],row[18],row[19],row[20],row[21],row[22],row[23],row[24],row[25],row[26],row[27],row[28]]))+";"
conndb.execute('SELECT w.id as "w_id",w.id_s as "w_sourceid",w.lp,w.warunek as "w_type",w.operator,w.dane as "w_data",s.name as "io_name",s.reverse,p.name as "pwm_name",se.name as "se_name",se.unit,r.name as "rf_name",c.name as "cmd_name",w.id_link,w.name_link,l.name as "link_dname", v.name as "v_name" FROM wyzwalaczeAkcji w left join stany s on w.Id_s=CAST(s.Id AS TEXT) left join pwm p on w.Id_s=CAST(p.Id AS text) left join sensory se on w.Id_s=se.Id left join rf r on w.Id_s=CAST(r.Id AS TEXT) left join customCmds c on w.Id_s=CAST(c.Id AS TEXT) left join linkedPis l on w.Id_link = l.Id left join globalVariables v on w.Id_s=CAST(v.Id AS TEXT) WHERE w.Id_a=%s ORDER BY w.Lp',(str(row[0]),))
for row1 in conndb.fetchall():
reply+=str(row1[0])+'$'+str(row1[1])+'$'+str(row1[2])+'$'+str(row1[3])+'$'+str(row1[4])+'$'+str(row1[5])+'$'+str(row1[6])+'$'+str(row1[7])+'$'+str(row1[8])+'$'+str(row1[9])+'$'+str(row1[10])+'$'+str(row1[11])+'$'+str(row1[12])+'$'+str(row1[13])+'$'+str(row1[14])+'$'+str(row1[15])+'$'+str(row1[16])+'$'
reply+=';'
elif datalist[1] == 'GPIO_ASA_Add':
if datalist[3] == 'output':
conndb.execute("INSERT INTO akcje(Nazwa, Typ, Out_id, Rodzaj, Out_stan, Edit_time, Log, Refresh_rate) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)", (
datalist[2], datalist[3], datalist[4], datalist[5], datalist[6], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),datalist[9],datalist[10]))
elif datalist[3] == 'pwm':
conndb.execute("INSERT INTO akcje(Nazwa, Typ, Pwm_id, Rodzaj, Pwm_ss, Pwm_fr,Pwm_dc, Edit_time, Log, Refresh_rate) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", (
datalist[2], datalist[3], datalist[4], datalist[5], datalist[6],datalist[7],datalist[8], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), datalist[9],datalist[10]))
elif datalist[3] == 'chain':
conndb.execute("INSERT INTO akcje(Nazwa, Typ, Chain_id, Rodzaj, Edit_time, Log, Refresh_rate, Out_stan) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)", (
datalist[2], datalist[3], datalist[4], datalist[5], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), datalist[9],datalist[10],datalist[6]))
elif datalist[3] == 'rfsend':
conndb.execute("INSERT INTO akcje(Nazwa, Typ, Rf_id, Rodzaj, Edit_time, Log, Refresh_rate) VALUES(%s,%s,%s,%s,%s,%s,%s)", (
datalist[2], datalist[3], datalist[4], datalist[5], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), datalist[9],datalist[10]))
elif datalist[3] == 'cmd':
conndb.execute("INSERT INTO akcje(Nazwa, Typ, Cmd_id, Rodzaj, Edit_time, Log, Refresh_rate) VALUES(%s,%s,%s,%s,%s,%s,%s)", (
datalist[2], datalist[3], datalist[4], datalist[5], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), datalist[9],datalist[10]))
elif datalist[3] == 'var':
conndb.execute("INSERT INTO akcje(Nazwa, Typ, V_id, Rodzaj, V_val, Edit_time, Log, Refresh_rate) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)", (
datalist[2], datalist[3], datalist[4], datalist[5], datalist[6], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),datalist[9],datalist[10]))
elif datalist[3] == 'action_noe':
conndb.execute("INSERT INTO akcje(Nazwa, Typ, A_id, Rodzaj, A_noe, Edit_time, Log, Refresh_rate) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)", (
datalist[2], datalist[3], datalist[4], datalist[5], datalist[6], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),datalist[9],datalist[10]))
elif datalist[3] == 'chain_ec':
conndb.execute("INSERT INTO akcje(Nazwa, Typ, Chain_id, Rodzaj, Chain_ec, Edit_time, Log, Refresh_rate) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)", (
datalist[2], datalist[3], datalist[4], datalist[5], datalist[6], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),datalist[9],datalist[10]))
reply = 'true;GPIO_ASA_Add;'
elif datalist[1] == 'GPIO_ASA_Update':
if datalist[3] == 'output':
conndb.execute("UPDATE akcje set Nazwa=%s, Typ=%s, Out_id=%s, Rodzaj=%s, Out_stan=%s, Edit_time=%s, Log=%s, Refresh_rate=%s where Id=%s", (
datalist[2], datalist[3], datalist[4], datalist[5], datalist[6], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),datalist[10],datalist[11], datalist[9]))
elif datalist[3] == 'pwm':
conndb.execute("UPDATE akcje set Nazwa=%s, Typ=%s, Pwm_id=%s, Rodzaj=%s, Pwm_ss=%s, Pwm_fr=%s, Pwm_dc=%s, Edit_time=%s, Log=%s, Refresh_rate=%s where Id=%s", (
datalist[2], datalist[3], datalist[4], datalist[5], datalist[6],datalist[7],datalist[8],datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),datalist[10],datalist[11],datalist[9]))
elif datalist[3] == 'chain':
conndb.execute("UPDATE akcje set Nazwa=%s, Typ=%s, Chain_id=%s, Rodzaj=%s, Edit_time=%s, Log=%s, Refresh_rate=%s, Out_stan=%s where Id=%s", (
datalist[2], datalist[3], datalist[4], datalist[5], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),datalist[10],datalist[11],datalist[6],datalist[9]))
elif datalist[3] == 'rfsend':
conndb.execute("UPDATE akcje set Nazwa=%s, Typ=%s, Rf_id=%s, Rodzaj=%s, Edit_time=%s, Log=%s, Refresh_rate=%s where Id=%s", (
datalist[2], datalist[3], datalist[4], datalist[5], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),datalist[10],datalist[11], datalist[9]))
elif datalist[3] == 'cmd':
conndb.execute("UPDATE akcje set Nazwa=%s, Typ=%s, Cmd_id=%s, Rodzaj=%s, Edit_time=%s, Log=%s, Refresh_rate=%s where Id=%s", (
datalist[2], datalist[3], datalist[4], datalist[5], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),datalist[10],datalist[11], datalist[9]))
elif datalist[3] == 'var':
conndb.execute("UPDATE akcje set Nazwa=%s, Typ=%s, V_id=%s, Rodzaj=%s, V_val=%s, Edit_time=%s, Log=%s, Refresh_rate=%s where Id=%s", (
datalist[2], datalist[3], datalist[4], datalist[5], datalist[6], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),datalist[10],datalist[11], datalist[9]))
elif datalist[3] == 'action_noe':
conndb.execute("UPDATE akcje set Nazwa=%s, Typ=%s, A_id=%s, Rodzaj=%s, A_noe=%s, Edit_time=%s, Log=%s, Refresh_rate=%s where Id=%s", (
datalist[2], datalist[3], datalist[4], datalist[5], datalist[6], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),datalist[10],datalist[11], datalist[9]))
elif datalist[3] == 'chain_ec':
conndb.execute("UPDATE akcje set Nazwa=%s, Typ=%s, Chain_id=%s, Rodzaj=%s, Chain_ec=%s, Edit_time=%s, Log=%s, Refresh_rate=%s where Id=%s", (
datalist[2], datalist[3], datalist[4], datalist[5], datalist[6], datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),datalist[10],datalist[11], datalist[9]))
reply = 'true;GPIO_ASA_Update;'
elif datalist[1] == 'GPIO_ASA_Delete':
conndb.execute("DELETE from akcje where Id=%s", (datalist[2],))
conndb.execute("DELETE from wyzwalaczeAkcji where Id_a=%s", (datalist[2],))
conndb.execute("UPDATE akcje set Edit_time=%s where Id in (SELECT Id FROM akcje LIMIT 1)", (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'),))