Repository navigation
Expand file tree
/
Copy pathModBusDL.py
More file actions
4222 lines (3817 loc) · 192 KB
/
Copy pathModBusDL.py
File metadata and controls
4222 lines (3817 loc) · 192 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
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
# Built for python 2.7
# Copyright 2012 Dave Umrysh
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import pygtk,gtk,glib,csv,string,sys,os,subprocess,re,time,struct,binascii,threading,pango,shutil,datetime
pygtk.require('2.0')
import MySQLdb as mdb
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
#from pymodbus.client.sync import ModbusUdpClient as ModbusClient
#from pymodbus.client.sync import ModbusSerialClient as ModbusClient
path = ""
textlog = ""
TheSlash = "/"
dayofWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
monthofYear = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
convertwindow = gtk.Window(gtk.WINDOW_TOPLEVEL)
startwindow = gtk.Window(gtk.WINDOW_TOPLEVEL)
newplcwindow = gtk.Window(gtk.WINDOW_TOPLEVEL)
removeplcwindow = gtk.Window(gtk.WINDOW_TOPLEVEL)
#SplitBy = "day"
def getmysqlstring(plc):
counter = 1;
mysqlstring = "RecordNo INT PRIMARY KEY AUTO_INCREMENT"
for count in range(0,globals()['NumOfRegisters' + plc]):
if globals()['DataTypes' + plc][count] != "0" and globals()['DataTypes' + plc][count-1] != "7" and globals()['DataTypes' + plc][count-1] != "8" and globals()['DataTypes' + plc][count-1] != "9" and globals()['DataTypes' + plc][count-1] != "10" and globals()['DataTypes' + plc][count-1] != "17" and globals()['DataTypes' + plc][count-1] != "18" and globals()['DataTypes' + plc][count-1] != "19" and globals()['DataTypes' + plc][count-1] != "20" and globals()['DataTypes' + plc][count-1] != "21" and globals()['DataTypes' + plc][count-1] != "22" and globals()['DataTypes' + plc][count-1] != "23" and globals()['DataTypes' + plc][count-1] != "24" and count != globals()['FlagReg' + plc]:
# what type of data are we storing?
if globals()['DataTypes' + plc][count] == "1" or globals()['DataTypes' + plc][count] == "11":
mysqlstring = mysqlstring + ",%s varchar(16)" % ''.join(e for e in globals()['headings' + plc][counter].replace(" ", "_") if e.isalnum())
elif globals()['DataTypes' + plc][count] == "2" or globals()['DataTypes' + plc][count] == "12":
mysqlstring = mysqlstring + ",%s varchar(16)" % ''.join(e for e in globals()['headings' + plc][counter].replace(" ", "_") if e.isalnum())
elif globals()['DataTypes' + plc][count] == "3" or globals()['DataTypes' + plc][count] == "13":
mysqlstring = mysqlstring + ",%s varchar(16)" % ''.join(e for e in globals()['headings' + plc][counter].replace(" ", "_") if e.isalnum())
elif globals()['DataTypes' + plc][count] == "4" or globals()['DataTypes' + plc][count] == "14":
mysqlstring = mysqlstring + ",%s decimal" % ''.join(e for e in globals()['headings' + plc][counter].replace(" ", "_") if e.isalnum())
elif globals()['DataTypes' + plc][count] == "5" or globals()['DataTypes' + plc][count] == "15":
mysqlstring = mysqlstring + ",%s decimal" % ''.join(e for e in globals()['headings' + plc][counter].replace(" ", "_") if e.isalnum())
elif globals()['DataTypes' + plc][count] == "6" or globals()['DataTypes' + plc][count] == "16":
mysqlstring = mysqlstring + ",%s varchar(2)" % ''.join(e for e in globals()['headings' + plc][counter].replace(" ", "_") if e.isalnum())
elif globals()['DataTypes' + plc][count] == "7" or globals()['DataTypes' + plc][count] == "17":
mysqlstring = mysqlstring + ",%s real" % ''.join(e for e in globals()['headings' + plc][counter].replace(" ", "_") if e.isalnum())
elif globals()['DataTypes' + plc][count] == "8" or globals()['DataTypes' + plc][count] == "18":
mysqlstring = mysqlstring + ",%s real" % ''.join(e for e in globals()['headings' + plc][counter].replace(" ", "_") if e.isalnum())
elif globals()['DataTypes' + plc][count] == "9" or globals()['DataTypes' + plc][count] == "19":
mysqlstring = mysqlstring + ",%s real" % ''.join(e for e in globals()['headings' + plc][counter].replace(" ", "_") if e.isalnum())
elif globals()['DataTypes' + plc][count] == "10" or globals()['DataTypes' + plc][count] == "20":
mysqlstring = mysqlstring + ",%s real" % ''.join(e for e in globals()['headings' + plc][counter].replace(" ", "_") if e.isalnum())
elif globals()['DataTypes' + plc][count] == "21" or globals()['DataTypes' + plc][count] == "22" or globals()['DataTypes' + plc][count] == "23" or globals()['DataTypes' + plc][count] == "24":
mysqlstring = mysqlstring + ",%s decimal" % ''.join(e for e in globals()['headings' + plc][counter].replace(" ", "_") if e.isalnum())
counter=counter +1;
mysqlstring = "%s, mysql_datetime TIMESTAMP DEFAULT CURRENT_TIMESTAMP" % mysqlstring
return mysqlstring;
def ReverseByteOrder(data):
"""
Method to reverse the byte order of a given unsigned data value
Input:
data: data value whose byte order needs to be swap
data can only be as big as 4 bytes
Output:
revD: data value with its byte order reversed
"""
s = "Error: Only 'unsigned' data of type 'int' or 'long' is allowed"
if not ((type(data) == int)or(type(data) == long)):
s1 = "Error: Invalid data type: %s" % type(data)
print(''.join([s,'\n',s1]))
return data
if(data < 0):
s2 = "Error: Data is signed. Value is less than 0"
print(''.join([s,'\n',s2]))
return data
seq = ["0x"]
while(data > 0):
d = data & 0xFF # extract the least significant(LS) byte
seq.append('%02x'%d)# convert to appropriate string, append to sequence
data >>= 8 # push next higher byte to LS position
revD = int(''.join(seq),16)
return revD
def is_valid_ipv4(ip):
"""Validates IPv4 addresses.
"""
pattern = re.compile(r"""
^
(?:
# Dotted variants:
(?:
# Decimal 1-255 (no leading 0's)
[3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}
|
0x0*[0-9a-f]{1,2} # Hexadecimal 0x0 - 0xFF (possible leading 0's)
|
0+[1-3]?[0-7]{0,2} # Octal 0 - 0377 (possible leading 0's)
)
(?: # Repeat 0-3 times, separated by a dot
\.
(?:
[3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}
|
0x0*[0-9a-f]{1,2}
|
0+[1-3]?[0-7]{0,2}
)
){0,3}
|
0x0*[0-9a-f]{1,8} # Hexadecimal notation, 0x0 - 0xffffffff
|
0+[0-3]?[0-7]{0,10} # Octal notation, 0 - 037777777777
|
# Decimal notation, 1-4294967295:
429496729[0-5]|42949672[0-8]\d|4294967[01]\d\d|429496[0-6]\d{3}|
42949[0-5]\d{4}|4294[0-8]\d{5}|429[0-3]\d{6}|42[0-8]\d{7}|
4[01]\d{8}|[1-3]\d{0,9}|[4-9]\d{0,8}
)
$
""", re.VERBOSE | re.IGNORECASE)
return pattern.match(ip) is not None
def is_valid_ipv6(ip):
"""Validates IPv6 addresses.
"""
pattern = re.compile(r"""
^
\s* # Leading whitespace
(?!.*::.*::) # Only a single whildcard allowed
(?:(?!:)|:(?=:)) # Colon iff it would be part of a wildcard
(?: # Repeat 6 times:
[0-9a-f]{0,4} # A group of at most four hexadecimal digits
(?:(?<=::)|(?<!::):) # Colon unless preceeded by wildcard
){6} #
(?: # Either
[0-9a-f]{0,4} # Another group
(?:(?<=::)|(?<!::):) # Colon unless preceeded by wildcard
[0-9a-f]{0,4} # Last group
(?: (?<=::) # Colon iff preceeded by exacly one colon
| (?<!:) #
| (?<=:) (?<!::) : #
) # OR
| # A v4 address with NO leading zeros
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]?\d)
(?: \.
(?:25[threading0-4]|2[0-4]\d|1\d\d|[1-9]?\d)
){3}
)
\s* # Trailing whitespace
$
""", re.VERBOSE | re.IGNORECASE | re.DOTALL)
return pattern.match(ip) is not None
def is_valid_ip(ip):
"""Validates IP addresses.
"""
return is_valid_ipv4(ip) or is_valid_ipv6(ip)
def make_menu_item(named, callback, data1, data2,plc):
item = gtk.MenuItem(named)
item.connect("activate", callback, data1, data2,plc)
item.show()
return item
def make_menu_item_database(named, callback, data1, data2, data3, data4, data5, data6,data7,plc):
item = gtk.MenuItem(named)
item.connect("activate", callback, data1, data2, data3, data4, data5, data6,data7,plc)
item.show()
return item
class TaskThread(threading.Thread):
"""Thread that executes a task every N seconds"""
def __init__(self):
threading.Thread.__init__(self)
self._finished = threading.Event()
self._interval = 15.0
def setInterval(self, interval):
"""Set the number of seconds we sleep between executing our task"""
self._interval = interval
def shutdown(self, widget, button2, button3,button,textbuffer,sw,button4):
"""Stop this thread"""
button3.hide()
button2.show()
button.show()
button4.show()
textbuffer.insert_at_cursor("[Halt] Data collection stopped.\n")
while(gtk.events_pending()):
gtk.main_iteration()
adj = sw.get_vadjustment()
adj.set_value( adj.upper - adj.page_size )
self._finished.set()
def run(self, widget, button2, button3, spinner, textbuffer, sw,button,button4,plc):
button2.hide()
button3.show()
button.hide()
button4.hide()
self.setInterval(spinner.get_value())
delay = spinner.get_value()
globals()['counter' + plc] = 1
count = int(self._interval*10)
while not self._finished.isSet():
if count == int(self._interval*10):
self.task(textbuffer,delay,sw,button,button2,button3,button4,widget,plc)
count = 1
else:
# sleep for interval or until shutdown
time.sleep(0.1)
count = count + 1;
fileOUT = open("%s%s%s%sModBusDLData4" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("%s/%s/%s" % (datetime.date.today().day,datetime.date.today().month,datetime.date.today().year))
fileOUT.close()
while gtk.events_pending():
gtk.main_iteration(False)
def task(self,textbuffer,delay,sw,button,button2,button3,button4,widget,plc):
"""The task done by this thread - override in subclasses"""
fileIN = open("%s%s%s%sModBusDLData3" % (path,TheSlash,plc,TheSlash), "r")
RecordNo = int(fileIN.readline())
fileIN.close()
client = ModbusClient(globals()['address' + plc])
if client.connect() == False:
textbuffer.insert_at_cursor("[IP Error] No ModBus server at %s, re-check in 5 minutes\n" % globals()['address' + plc])
noconnect = True;
count = 1
while (not self._finished.isSet()) and noconnect:
if count == 3000:
client = ModbusClient(globals()['address' + plc])
if client.connect() == False:
textbuffer.insert_at_cursor("[IP Error] No ModBus server at %s, re-check in 5 minutes\n" % globals()['address' + plc])
count = 1
else:
noconnect = False
else:
# sleep for interval or until shutdown
time.sleep(0.1)
count = count + 1;
fileOUT = open("%s%s%s%sModBusDLData4" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("%s/%s/%s" % (datetime.date.today().day,datetime.date.today().month,datetime.date.today().year))
fileOUT.close()
while gtk.events_pending():
gtk.main_iteration(False)
else:
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "]Checking for new data\n")
read_registers = []
read_counter = 0
read_start = globals()['StartAddress' + plc]
# Read in 50 register chunks
if globals()['NumOfRegisters' + plc] < 50:
read_counter = globals()['NumOfRegisters' + plc]
else:
read_counter = 50
while len(read_registers) < globals()['NumOfRegisters' + plc]:
rr = client.read_holding_registers(read_start,read_counter)
try:
test = rr.registers[0]
except:
textbuffer.insert_at_cursor("[Register Error] Attempting to read outside of the server's register bounds.\n")
self.shutdown(widget, button2, button3,button,textbuffer,sw,button4)
return
read_registers = read_registers + rr.registers
# next batch
read_start = read_start+read_counter
if globals()['NumOfRegisters' + plc] < read_start+50-1:
read_counter = globals()['NumOfRegisters' + plc]-read_start+1
else:
read_counter = 50
if read_registers[globals()['FlagReg' + plc]-1] != 0:
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] Data Found, Enter into database\n")
count = 0;
NewLineStr = []
NewLineStr.append(RecordNo)
while (count < globals()['NumOfRegisters' + plc]):
if globals()['DataTypes' + plc][count] != "0" and count != (globals()['FlagReg' + plc]-1):
if globals()['DataTypes' + plc][count] == "1":
temp = bin(read_registers[count])
NewLineStr.append(temp.lstrip('0b'))
elif globals()['DataTypes' + plc][count] == "2":
NewLineStr.append("%o" % read_registers[count])
elif globals()['DataTypes' + plc][count] == "3":
NewLineStr.append("%0X" % read_registers[count])
elif globals()['DataTypes' + plc][count] == "4":
NewLineStr.append("%u" % read_registers[count])
elif globals()['DataTypes' + plc][count] == "5":
temp = "%i" % read_registers[count]
if (int(temp) > 32767):
temp = int(temp) - 65536
NewLineStr.append(temp)
elif globals()['DataTypes' + plc][count] == "6":
temp = binascii.unhexlify("%0X" % read_registers[count])
NewLineStr.append("%s" % temp)
elif globals()['DataTypes' + plc][count] == "7":
first = "%s" % ("%0X" % read_registers[count+1])
second = "%s" % ("%0X" % read_registers[count])
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append("%e" % temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "8":
first = "%s" % ("%0X" % read_registers[count+1])
second = "%s" % ("%0X" % read_registers[count])
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append(temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "9":
first = "%s" % ("%0X" % read_registers[count])
second = "%s" % ("%0X" % read_registers[count+1])
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append("%e" % temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "10":
first = "%s" % ("%0X" % read_registers[count])
second = "%s" % ("%0X" % read_registers[count+1])
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append(temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "11":
temp = bin(ReverseByteOrder(read_registers[count]))
NewLineStr.append(temp.lstrip('0b'))
elif globals()['DataTypes' + plc][count] == "12":
NewLineStr.append("%o" % ReverseByteOrder(read_registers[count]))
elif globals()['DataTypes' + plc][count] == "13":
NewLineStr.append("%0X" % ReverseByteOrder(read_registers[count]))
elif globals()['DataTypes' + plc][count] == "14":
NewLineStr.append("%u" % ReverseByteOrder(read_registers[count]))
elif globals()['DataTypes' + plc][count] == "15":
temp = "%i" % ReverseByteOrder(read_registers[count])
if (int(temp) > 32767):
temp = int(temp) - 65536
NewLineStr.append(temp)
elif globals()['DataTypes' + plc][count] == "16":
temp = binascii.unhexlify("%0X" % ReverseByteOrder(read_registers[count]))
NewLineStr.append("%s" % temp)
elif globals()['DataTypes' + plc][count] == "17":
first = "%s" % ("%0X" % ReverseByteOrder(read_registers[count+1]))
second = "%s" % ("%0X" % ReverseByteOrder(read_registers[count]))
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append("%e" % temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "18":
first = "%s" % ("%0X" % ReverseByteOrder(read_registers[count+1]))
second = "%s" % ("%0X" % ReverseByteOrder(read_registers[count]))
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append(temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "19":
first = "%s" % ("%0X" % ReverseByteOrder(read_registers[count]))
second = "%s" % ("%0X" % ReverseByteOrder(read_registers[count+1]))
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append("%e" % temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "20":
first = "%s" % ("%0X" % ReverseByteOrder(read_registers[count]))
second = "%s" % ("%0X" % ReverseByteOrder(read_registers[count+1]))
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append(temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "21":
first = "%s" % bin(read_registers[count+1])
first = first.lstrip('0b')
second = "%s" % bin(read_registers[count])
second = second.lstrip('0b')
while (len(first) < 16):
first = "0%s" % first
while (len(second) < 16):
second = "0%s" % second
temp = "%s%s" % (first,second)
NewLineStr.append(int(str(temp),2))
count = count + 1
#NewLineStr.append("%u" % read_registers[count])
elif globals()['DataTypes' + plc][count] == "22":
first = "%s" % bin(read_registers[count])
first = first.lstrip('0b')
second = "%s" % bin(read_registers[count+1])
second = second.lstrip('0b')
while (len(first) < 16):
first = "0%s" % first
while (len(second) < 16):
second = "0%s" % second
temp = "%s%s" % (first,second)
NewLineStr.append(int(str(temp),2))
count = count + 1
elif globals()['DataTypes' + plc][count] == "23":
first = "%s" % bin(ReverseByteOrder(read_registers[count+1]))
first = first.lstrip('0b')
second = "%s" % bin(ReverseByteOrder(read_registers[count]))
second = second.lstrip('0b')
while (len(first) < 16):
first = "0%s" % first
while (len(second) < 16):
second = "0%s" % second
temp = "%s%s" % (first,second)
NewLineStr.append(int(str(temp),2))
count = count + 1
elif globals()['DataTypes' + plc][count] == "24":
first = "%s" % bin(ReverseByteOrder(read_registers[count]))
first = first.lstrip('0b')
second = "%s" % bin(ReverseByteOrder(read_registers[count+1]))
second = second.lstrip('0b')
while (len(first) < 16):
first = "0%s" % first
while (len(second) < 16):
second = "0%s" % second
temp = "%s%s" % (first,second)
NewLineStr.append(int(str(temp),2))
count = count + 1
count = count + 1
###################################
## Test for new day, month, year
###################################
if globals()['splitby' + plc] == "1":#Day of Week
if globals()['dayofWeek' + plc] != datetime.date.today().weekday():
globals()['dayofWeek' + plc] = datetime.date.today().weekday()
# Check if we are required to delete csv
if globals()['perdroptable' + plc]:
if (os.path.isfile("%s%s.csv" % (globals()['LocOfCSV' + plc], dayofWeek[globals()['dayofWeek' + plc]]))):
os.remove("%s%s.csv" % (globals()['LocOfCSV' + plc], dayofWeek[globals()['dayofWeek' + plc]]))
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] Delete CSV\n")
RecordNo = 1
NewLineStr[0] = "1"
fileOUT = open("%s%s%s%sModBusDLData3" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("%s" % RecordNo)
fileOUT.close()
try:
fileInT = open("%s%s.csv" % (globals()['LocOfCSV' + plc], dayofWeek[globals()['dayofWeek' + plc]]))
lines = [line for line in fileInT]
fileInT.close()
lastrow = string.split(lines[len(lines)-1].replace('\n', '').replace('\r', ''),',')
if lastrow[0] == "RecordNo":
RecordNo = 1
NewLineStr[0] = 1
else:
RecordNo = int(lastrow[0])+1
NewLineStr[0] = int(lastrow[0])+1
fileOUT = open("%s%s%s%sModBusDLData3" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("%s" % RecordNo)
fileOUT.close()
except IOError as e:
try:
f = csv.writer(open("%s%s.csv" % (globals()['LocOfCSV' + plc], dayofWeek[globals()['dayofWeek' + plc]]), 'wb'), delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
except IOError as e:
textbuffer.insert_at_cursor("Could not create CSV file.\nDid the folder name change?\nTry deleting the .ModBusDL folder in the root of your user directory and restart the program.\n")
return
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] Create CSV\n")
f.writerow(globals()['headings' + plc])
fileOUT = open("%s%s%s%sModBusDLData3" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("1")
fileOUT.close()
RecordNo = 1
f = csv.writer(open("%s%s.csv" % (globals()['LocOfCSV' + plc], dayofWeek[globals()['dayofWeek' + plc]]), 'ab'), delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
elif globals()['splitby' + plc] == "2": # Month
if globals()['month' + plc] != datetime.date.today().month:
globals()['month' + plc] = datetime.date.today().month
# Check if we are required to delete csv
if globals()['perdroptable' + plc]:
if (os.path.isfile("%s%s.csv" % (globals()['LocOfCSV' + plc], monthofYear[globals()['month' + plc]]))):
os.remove("%s%s.csv" % (globals()['LocOfCSV' + plc], monthofYear[globals()['month' + plc]]))
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] Delete CSV\n")
RecordNo = 1
NewLineStr[0] = "1"
fileOUT = open("%s%s%s%sModBusDLData3" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("%s" % RecordNo)
fileOUT.close()
try:
fileInT = open("%s%s.csv" % (globals()['LocOfCSV' + plc], monthofYear[globals()['month' + plc]]))
lines = [line for line in fileInT]
fileInT.close()
lastrow = string.split(lines[len(lines)-1].replace('\n', '').replace('\r', ''),',')
if lastrow[0] == "RecordNo":
RecordNo = 1
NewLineStr[0] = 1
else:
RecordNo = int(lastrow[0])+1
NewLineStr[0] = int(lastrow[0])+1
fileOUT = open("%s%s%s%sModBusDLData3" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("%s" % RecordNo)
fileOUT.close()
except IOError as e:
try:
f = csv.writer(open("%s%s.csv" % (globals()['LocOfCSV' + plc], monthofYear[globals()['month' + plc]]), 'wb'), delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
except IOError as e:
textbuffer.insert_at_cursor("Could not create CSV file.\nDid the folder name change?\nTry deleting the .ModBusDL folder in the root of your user directory and restart the program.\n")
return
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] Create CSV\n")
f.writerow(globals()['headings' + plc])
fileOUT = open("%s%s%s%sModBusDLData3" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("1")
fileOUT.close()
RecordNo = 1
f = csv.writer(open("%s%s.csv" % (globals()['LocOfCSV' + plc], monthofYear[globals()['month' + plc]]), 'ab'), delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
elif globals()['splitby' + plc] == "3": # Year
if globals()['year' + plc] != datetime.date.today().year:
globals()['year' + plc] = datetime.date.today().year
# Check if we are required to delete csv
if globals()['perdroptable' + plc]:
if (os.path.isfile("%s%s.csv" % (globals()['LocOfCSV' + plc], str(globals()['year' + plc])))):
os.remove("%s%s.csv" % (globals()['LocOfCSV' + plc], str(globals()['year' + plc])))
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] Delete CSV\n")
RecordNo = 1
NewLineStr[0] = "1"
fileOUT = open("%s%s%s%sModBusDLData3" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("%s" % RecordNo)
fileOUT.close()
try:
fileInT = open("%s%s.csv" % (globals()['LocOfCSV' + plc], str(globals()['year' + plc])))
lines = [line for line in fileInT]
fileInT.close()
lastrow = string.split(lines[len(lines)-1].replace('\n', '').replace('\r', ''),',')
if lastrow[0] == "RecordNo":
RecordNo = 1
NewLineStr[0] = 1
else:
RecordNo = int(lastrow[0])+1
NewLineStr[0] = int(lastrow[0])+1
fileOUT = open("%s%s%s%sModBusDLData3" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("%s" % RecordNo)
fileOUT.close()
except IOError as e:
try:
f = csv.writer(open("%s%s.csv" % (globals()['LocOfCSV' + plc], str(globals()['year' + plc])), 'wb'), delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
except IOError as e:
textbuffer.insert_at_cursor("Could not create CSV file.\nDid the folder name change?\nTry deleting the .ModBusDL folder in the root of your user directory and restart the program.\n")
return
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] Create CSV\n")
f.writerow(globals()['headings' + plc])
fileOUT = open("%s%s%s%sModBusDLData3" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("1")
fileOUT.close()
RecordNo = 1
f = csv.writer(open("%s%s.csv" % (globals()['LocOfCSV' + plc], str(globals()['year' + plc])), 'ab'), delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
else:
f = csv.writer(open("%s.csv" % globals()['LocOfCSV' + plc], 'ab'), delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
###################################
f.writerow(NewLineStr)
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] ")
for i in NewLineStr:
textbuffer.insert_at_cursor('"%s" ' % i)
textbuffer.insert_at_cursor("\n")
RecordNo = RecordNo +1
fileOUT = open("%s%s%s%sModBusDLData3" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("%s" % RecordNo)
fileOUT.close()
rq = client.write_register(globals()['StartAddress' + plc]+globals()['FlagReg' + plc]-1, 0)
if (rq.function_code >= 0x80):
textbuffer.insert_at_cursor("[Register Error] Cannot write to 'new data available' register.\n")
self.shutdown(widget, button2, button3,button,textbuffer,sw,button4)
return
else:
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] No New Data\n")
client.close()
#Wait the delay
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "]Sleep for %s seconds\n" % delay)
while(gtk.events_pending()):
gtk.main_iteration()
adj = sw.get_vadjustment()
adj.set_value( adj.upper - adj.page_size )
globals()['counter' + plc] = globals()['counter' + plc] + 1
class TaskThreadMySQL(threading.Thread):
"""Thread that executes a task every N seconds"""
def __init__(self):
threading.Thread.__init__(self)
self._finished = threading.Event()
self._interval = 15.0
def setInterval(self, interval):
"""Set the number of seconds we sleep between executing our task"""
self._interval = interval
def shutdown(self, widget, button2, button3,button,textbuffer,sw,button4):
"""Stop this thread"""
button3.hide()
button2.show()
button.show()
button4.show()
textbuffer.insert_at_cursor("[Halt] Data collection stopped.\n")
while(gtk.events_pending()):
gtk.main_iteration()
adj = sw.get_vadjustment()
adj.set_value( adj.upper - adj.page_size )
self._finished.set()
def hide(self, plc):
globals()['errorwindow' + plc].hide()
def run(self, widget, button2, button3, spinner, textbuffer, sw,button,button4,plc):
button2.hide()
button3.show()
button.hide()
button4.hide()
self.setInterval(spinner.get_value())
delay = spinner.get_value()
globals()['counter' + plc] = 1
count = int(self._interval*10)
while not self._finished.isSet():
if count == int(self._interval*10):
self.task(textbuffer,delay,sw,button,button2,button3,button4,widget,plc)
count = 1
else:
# sleep for interval or until shutdown
time.sleep(0.1)
count = count + 1;
fileOUT = open("%s%s%s%sModBusDLData4" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("%s/%s/%s" % (datetime.date.today().day,datetime.date.today().month,datetime.date.today().year))
fileOUT.close()
while gtk.events_pending():
gtk.main_iteration(False)
def task(self,textbuffer,delay,sw,button,button2,button3,button4,widget,plc):
"""The task done by this thread - override in subclasses"""
client = ModbusClient(globals()['address' + plc])
if client.connect() == False:
textbuffer.insert_at_cursor("[IP Error] No ModBus server at %s, re-check in 5 minutes\n" % globals()['address' + plc])
noconnect = True;
count = 1
while (not self._finished.isSet()) and noconnect:
if count == 3000:
client = ModbusClient(globals()['address' + plc])
if client.connect() == False:
textbuffer.insert_at_cursor("[IP Error] No ModBus server at %s, re-check in 5 minutes\n" % globals()['address' + plc])
count = 1
else:
noconnect = False
else:
# sleep for interval or until shutdown
time.sleep(0.1)
count = count + 1;
fileOUT = open("%s%s%s%sModBusDLData4" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("%s/%s/%s" % (datetime.date.today().day,datetime.date.today().month,datetime.date.today().year))
fileOUT.close()
while gtk.events_pending():
gtk.main_iteration(False)
else:
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "]Checking for new data\n")
read_registers = []
read_counter = 0
read_start = globals()['StartAddress' + plc]
# Read in 50 register chunks
if globals()['NumOfRegisters' + plc] < 50:
read_counter = globals()['NumOfRegisters' + plc]
else:
read_counter = 50
while len(read_registers) < globals()['NumOfRegisters' + plc]:
rr = client.read_holding_registers(read_start,read_counter)
try:
test = rr.registers[0]
except:
textbuffer.insert_at_cursor("[Register Error] Attempting to read outside of the server's register bounds.\n")
self.shutdown(widget, button2, button3,button,textbuffer,sw,button4)
return
read_registers = read_registers + rr.registers
# next batch
read_start = read_start+read_counter
if globals()['NumOfRegisters' + plc] < read_start+50-1:
read_counter = globals()['NumOfRegisters' + plc]-read_start+1
else:
read_counter = 50
if read_registers[globals()['FlagReg' + plc]-1] != 0:
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] Data Found, Enter into database\n")
count = 0;
NewLineStr = []
while (count < globals()['NumOfRegisters' + plc]):
if globals()['DataTypes' + plc][count] != "0" and count != (globals()['FlagReg' + plc]-1):
if globals()['DataTypes' + plc][count] == "1":
temp = bin(read_registers[count])
NewLineStr.append(temp.lstrip('0b'))
elif globals()['DataTypes' + plc][count] == "2":
NewLineStr.append("%o" % read_registers[count])
elif globals()['DataTypes' + plc][count] == "3":
NewLineStr.append("%0X" % read_registers[count])
elif globals()['DataTypes' + plc][count] == "4":
NewLineStr.append("%u" % read_registers[count])
elif globals()['DataTypes' + plc][count] == "5":
temp = "%i" % read_registers[count]
if (int(temp) > 32767):
temp = int(temp) - 65536
NewLineStr.append(temp)
elif globals()['DataTypes' + plc][count] == "6":
temp = binascii.unhexlify("%0X" % read_registers[count])
NewLineStr.append("%s" % temp)
elif globals()['DataTypes' + plc][count] == "7":
first = "%s" % ("%0X" % read_registers[count+1])
second = "%s" % ("%0X" % read_registers[count])
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append("%e" % temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "8":
first = "%s" % ("%0X" % read_registers[count+1])
second = "%s" % ("%0X" % read_registers[count])
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append(temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "9":
first = "%s" % ("%0X" % read_registers[count])
second = "%s" % ("%0X" % read_registers[count+1])
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append("%e" % temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "10":
first = "%s" % ("%0X" % read_registers[count])
second = "%s" % ("%0X" % read_registers[count+1])
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append(temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "11":
temp = bin(ReverseByteOrder(read_registers[count]))
NewLineStr.append(temp.lstrip('0b'))
elif globals()['DataTypes' + plc][count] == "12":
NewLineStr.append("%o" % ReverseByteOrder(read_registers[count]))
elif globals()['DataTypes' + plc][count] == "13":
NewLineStr.append("%0X" % ReverseByteOrder(read_registers[count]))
elif globals()['DataTypes' + plc][count] == "14":
NewLineStr.append("%u" % ReverseByteOrder(read_registers[count]))
elif globals()['DataTypes' + plc][count] == "15":
temp = "%i" % ReverseByteOrder(read_registers[count])
if (int(temp) > 32767):
temp = int(temp) - 65536
NewLineStr.append(temp)
elif globals()['DataTypes' + plc][count] == "16":
temp = binascii.unhexlify("%0X" % ReverseByteOrder(read_registers[count]))
NewLineStr.append("%s" % temp)
elif globals()['DataTypes' + plc][count] == "17":
first = "%s" % ("%0X" % ReverseByteOrder(read_registers[count+1]))
second = "%s" % ("%0X" % ReverseByteOrder(read_registers[count]))
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append("%e" % temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "18":
first = "%s" % ("%0X" % ReverseByteOrder(read_registers[count+1]))
second = "%s" % ("%0X" % ReverseByteOrder(read_registers[count]))
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append(temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "19":
first = "%s" % ("%0X" % ReverseByteOrder(read_registers[count]))
second = "%s" % ("%0X" % ReverseByteOrder(read_registers[count+1]))
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append("%e" % temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "20":
first = "%s" % ("%0X" % ReverseByteOrder(read_registers[count]))
second = "%s" % ("%0X" % ReverseByteOrder(read_registers[count+1]))
while (len(first) < 4):
first = "0%s" % first
while (len(second) < 4):
second = "0%s" % second
temp = "%s%s" % (first,second)
temp = struct.unpack('!f', temp.decode('hex'))
NewLineStr.append(temp[0])
count = count + 1
elif globals()['DataTypes' + plc][count] == "21":
first = "%s" % bin(read_registers[count+1])
first = first.lstrip('0b')
second = "%s" % bin(read_registers[count])
second = second.lstrip('0b')
while (len(first) < 16):
first = "0%s" % first
while (len(second) < 16):
second = "0%s" % second
temp = "%s%s" % (first,second)
NewLineStr.append(int(str(temp),2))
count = count + 1
#NewLineStr.append("%u" % read_registers[count])
elif globals()['DataTypes' + plc][count] == "22":
first = "%s" % bin(read_registers[count])
first = first.lstrip('0b')
second = "%s" % bin(read_registers[count+1])
second = second.lstrip('0b')
while (len(first) < 16):
first = "0%s" % first
while (len(second) < 16):
second = "0%s" % second
temp = "%s%s" % (first,second)
NewLineStr.append(int(str(temp),2))
count = count + 1
elif globals()['DataTypes' + plc][count] == "23":
first = "%s" % bin(ReverseByteOrder(read_registers[count+1]))
first = first.lstrip('0b')
second = "%s" % bin(ReverseByteOrder(read_registers[count]))
second = second.lstrip('0b')
while (len(first) < 16):
first = "0%s" % first
while (len(second) < 16):
second = "0%s" % second
temp = "%s%s" % (first,second)
NewLineStr.append(int(str(temp),2))
count = count + 1
elif globals()['DataTypes' + plc][count] == "24":
first = "%s" % bin(ReverseByteOrder(read_registers[count]))
first = first.lstrip('0b')
second = "%s" % bin(ReverseByteOrder(read_registers[count+1]))
second = second.lstrip('0b')
while (len(first) < 16):
first = "0%s" % first
while (len(second) < 16):
second = "0%s" % second
temp = "%s%s" % (first,second)
NewLineStr.append(int(str(temp),2))
count = count + 1
count = count + 1
try:
globals()['con' + plc] = mdb.connect(host=globals()['mysqladdress' + plc], port=int(globals()['mysqlport' + plc]),user=globals()['mysqlusername' + plc], passwd=globals()['mysqlpassword' + plc], db=globals()['mysqldbname' + plc])
except:
textbuffer.insert_at_cursor("[Database Error] Could not connect to MySQL database, re-check in 5 minutes.\n")
noconnect = True;
count = 1
while (not self._finished.isSet()) and noconnect:
if count == 3000:
noconnect = False
try:
globals()['con' + plc] = mdb.connect(host=globals()['mysqladdress' + plc], port=int(globals()['mysqlport' + plc]),user=globals()['mysqlusername' + plc], passwd=globals()['mysqlpassword' + plc], db=globals()['mysqldbname' + plc])
except:
textbuffer.insert_at_cursor("[Database Error] Could not connect to MySQL database, re-check in 5 minutes.\n")
count = 1
noconnect = True;
else:
# sleep for interval or until shutdown
time.sleep(0.1)
count = count + 1;
fileOUT = open("%s%s%s%sModBusDLData4" % (path,TheSlash,plc,TheSlash), "w")
fileOUT.writelines("%s/%s/%s" % (datetime.date.today().day,datetime.date.today().month,datetime.date.today().year))
fileOUT.close()
while gtk.events_pending():
gtk.main_iteration(False)
globals()['con' + plc].autocommit(True)
globals()['cur' + plc] = globals()['con' + plc].cursor()
###################################
## Test for new day, month, year
###################################
if globals()['splitby' + plc] == "1":#Day of Week
if globals()['dayofWeek' + plc] != datetime.date.today().weekday():
globals()['dayofWeek' + plc] = datetime.date.today().weekday()
# Check if we are required to drop table
if globals()['perdroptable' + plc]:
globals()['cur' + plc].execute("drop table if exists %s%s" % (globals()['mysqltablename' + plc], dayofWeek[globals()['dayofWeek' + plc]]))
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] Drop Table\n")
#Check if table exists, then check if we are allowed to make it
globals()['cur' + plc].execute('show tables like "%s%s"' % (globals()['mysqltablename' + plc] , dayofWeek[globals()['dayofWeek' + plc]]))
if not globals()['cur' + plc].fetchall():
# Table name doesn't exist
if globals()['createtable' + plc]:
# Create table
mysqlstring = getmysqlstring(plc)
globals()['cur' + plc].execute("create table %s%s(%s)" % (globals()['mysqltablename' + plc] , dayofWeek[globals()['dayofWeek' + plc]],mysqlstring))
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] Create Table\n")
else:
#Throw Error
textbuffer.insert_at_cursor("Could not find a table \"%s%s\" in the MySQL database.\n" % (globals()['mysqltablename' + plc] , dayofWeek[globals()['dayofWeek' + plc]]))
self.shutdown(widget, button2, button3,button,textbuffer,sw,button4)
return
# EndIF
try:
globals()['cur' + plc].execute('INSERT INTO %s%s VALUES(NULL,"%s",NULL)' % (globals()['mysqltablename' + plc] , dayofWeek[globals()['dayofWeek' + plc]],'","'.join(map(str, NewLineStr))))
except :
textbuffer.insert_at_cursor("[Database Error] Could not insert into MySQL database.\n")
self.shutdown(widget, button2, button3,button,textbuffer,sw,button4)
return
elif globals()['splitby' + plc] == "2": # Month
if globals()['month' + plc] != datetime.date.today().month:
globals()['month' + plc] = datetime.date.today().month
# Check if we are required to drop table
if globals()['perdroptable' + plc]:
globals()['cur' + plc].execute("drop table if exists %s%s" % (globals()['mysqltablename' + plc], monthofYear[globals()['month' + plc]]))
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] Drop Table\n")
#Check if table exists, then check if we are allowed to make it
globals()['cur' + plc].execute('show tables like "%s%s"' % (globals()['mysqltablename' + plc] , monthofYear[globals()['month' + plc]]))
if not globals()['cur' + plc].fetchall():
# Table name doesn't exist
if globals()['createtable' + plc]:
# Create table
mysqlstring = getmysqlstring(plc)
globals()['cur' + plc].execute("create table %s%s(%s)" % (globals()['mysqltablename' + plc] , monthofYear[globals()['month' + plc]],mysqlstring))
textbuffer.insert_at_cursor("[" + str(globals()['counter' + plc]) + "] Create Table\n")
else:
#Throw Error
textbuffer.insert_at_cursor("Could not find a table \"%s%s\" in the MySQL database.\n" % (globals()['mysqltablename' + plc] , monthofYear[globals()['month' + plc]]))