-
Notifications
You must be signed in to change notification settings - Fork 3
/
LogikGen.py
2212 lines (1973 loc) · 95 KB
/
LogikGen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
## -----------------------------------------------------
## Logik-Generator V2.021
## -----------------------------------------------------
## Copyright © 2011, knx-user-forum e.V, All rights reserved.
##
## 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.de/documents/gpl-3.0.de.html>.
LGTVERSION = 2.021
#######################
### Changelog #########
#######################
## 2.021 * PREEXEC für hsb hinzugefügt
## * TagList.GrpListAll hinzugefügt
## * iko Standalone + Attribute wie name,endpoint_description ...
##
## 2.020 * fix _hslparser 5012 regex include spaces
##
## 2.019 * hsl20 Support
##
## 2.018 * füge diverse interne Funktionen hinzu
##
## 2.017 * entferne --register
##
## 2.016 * XXXXXXXXXXXXXXXXXXXXX
## * XXXXXXXXXXXXXXXXXXXXX
##
## 2.015 * 'names' zeigt jetzt SN and Timer
## * colorama Unterstützung für farbliche Ausgabe
## * Überprüfung der Zeilenende auf Kommentarzeichen #
## * Timer ON[x] erhällt Wert der Formel
## * fix AC wurde teilweise zu früh auf 0 gesetzt
## * 'timer' zeigt jetzt ohne Parameter die verfügbaren an
## * 'timer [x]' führt die Logik Berechnung bei aktivem autorun auch aus
## * 'print' und 'import' als Befehl direkt ohne exec möglich
## * 'formel' zeigt die Formelzeilen und dekodierten Base64 Bytecode
## * Syntax Highlighting
## * Homeserver Variablen können an der Debugkonsole auch verkürzt als en1= oder en2= etc gesetzt werden
## * removed import popen2
##
## 2.014 * interne IP
##
## 2.013 * diverse HS interne Objekte hinzugefügt
## * überwachung von AC[x] auf änderungen
## * __import__ gegen Funktion ausgetauscht um hs interne Module zu imitieren
## * KO Gateway Verbindung timeout geändert
## * eingaben string-decode um zum Beispiel bei EN[1]="d100=1\x03" das Steuerzeichen hex 03 zu senden
## * Fix Ausgang beim internen schreiben über SetWert des iko
## * --register nun je Python Version (Debug 2.4/Debug 2.6)
##
## 2.012 * runTime je Formelzeile
## * --register zum registrieren der Debug Erweiterung für .hsl Dateien
##
## 2.011 * Name von TimerThreads entsprechend dem OC
##
## 2.010 * Bugfix 'names'
##
## 2.009 * 'connect' zum manuellen verbinden aus dem Debugger
## * EN[1]=$IKO$1/0/100 aus dem debugger heraus
## * Bugfix .config nicht aus dem Installationspfad geladen beim Rechtsklick aus hsl
##
## 2.008 * Timer laufen automatisch bei autorun
## * Bugfixes beim Beenden
## * globals werden nicht mehr an die Formel übergeben
## * Zeilenummer beim Bedingungstest
## * Autorun per .config default und pro LogikID
## * Autorun override per Befehlszeile -a 1|0
##
## 2.007 * Bugfixes KO-Gateway
## * AutoRun
##
## 2.006 * KO-Gateway für Ein/ausgänge
##
## 2.005 * Anzeige auf SystemCodepage angepasst, sodass Umlaute angezeigt werden
## * Option -n zum erstellen von .LGT Dateien aus .hsl
## * Kontrollen für EI bei nicht startetenden Bausteinen
## * Kontrolle auf Remanente Speicher bei nicht Remanenten Baustein
## * Kontrolle der Timer Anzahl
##
## 2.004 * BugFixes _defline
## * einige Dacom Bausteine (z.B. Codeschloss) haben keine gültige Definition
##
## 2.003 * 'names' zeigen jetzt auch die derzeitigen Werte
## * LogikGen.config hinzugefügt
## * Ausgang von intern beschreiben
## * Ausgaben auf Deutsch
##
## 2.002 * Parse Error in der 5001er Zeile
## * einige interne HS Klassen hinzugfügt
## * Timer ON/OC werden unterstützt
##
## 2.001 * Initial Release
##
import sys
import threading
STDOUT_MUTEX = threading.RLock()
## Threadsafe STDOUT
class flushed_stdout(object):
MAXBUFFER = 1000
def __init__(self,stream):
self.stream = stream
self.buffer = []
self.pause = 0
def set_pause(self,pause):
try:
STDOUT_MUTEX.acquire()
self.pause = pause
if pause == 0 and len(self.buffer) > 0:
self.stream.writelines(self.buffer)
self.buffer = []
finally:
STDOUT_MUTEX.release()
def write(self,msg):
try:
STDOUT_MUTEX.acquire()
if self.pause == 0:
self.stream.write(msg)
self.stream.flush()
else:
self.buffer.append(msg)
self.buffer = self.buffer[:1000]
finally:
STDOUT_MUTEX.release()
def writelines(self, lines):
try:
STDOUT_MUTEX.acquire()
if self.pause == 0:
self.stream.writelines(lines)
self.stream.flush()
else:
self.buffer += lines
self.buffer = self.buffer[:1000]
finally:
STDOUT_MUTEX.release()
def flush(self):
pass
def __getattr__(self, attr):
return getattr(self.stream, attr)
try:
from colorama import init,Fore, Back, Style
init()
except ImportError:
print "für farbliche Ausgaben -> https://pypi.python.org/pypi/colorama"
## Dummy Klasse erstellen
class AnsiCodes(object):
BLACK = ""
RED = ""
GREEN = ""
YELLOW = ""
BLUE = ""
MAGENTA = ""
CYAN = ""
WHITE = ""
RESET = ""
BRIGHT = ""
DIM = ""
NORMAL = ""
RESET_ALL = ""
Fore = Back = Style = AnsiCodes()
sys.stdout = flushed_stdout(sys.stdout)
import codecs
import os
import base64
import marshal
import re
import glob
import getopt
import hashlib
import inspect
import types
import signal
import time
from datetime import datetime
import socket
import select
import StringIO
import ConfigParser
#import popen2
import random
import zlib
import zipfile
import traceback
import Queue
import string
import io
import tokenize
## Weil der HS zu viele alte Module erwartet ;) so einfach könnte auch der HS diese blöden Meldungen nicht an der Konsole zeigen.
import warnings
warnings.simplefilter("ignore",DeprecationWarning)
##############
### Config ###
##############
DEBUG = False
SYNTAXHIGHLIGHT = True
## kleine Hilfsfunktionen
def debug(msg):
print(msg)
COLORRESET = Style.RESET_ALL
COLORINFO= Fore.YELLOW+Style.BRIGHT
COLORINTERN = Fore.GREEN+Style.BRIGHT
RE_SYSTEMLOG_FINDER = re.compile("<log>.*?</log>")
RE_SYSTEMLOG_GRABBER = re.compile("<log>(?=.*<facility>(?P<facility>.*?)</facility>)(?=.*<severity>(?P<severity>.*?)</severity>)(?=.*<message>(?P<message>.*?)</message>).*</log>")
RE_SYNTAX_HIGHLIGHT_COMMENT = re.compile("(^#+.*?$|###.*?###)",re.MULTILINE)
RE_SYNTAX_HIGHLIGHT_FUNCTIONS = re.compile(r"(\bprint|\btry:|\bexcept\b.*?:|\bfinally:|\bfor\b.*?in.*?:|\bwhile\b.*?:|\belif\b.*?:|\bif\b.*?:|\belse:|\band\b|\bor\b|\bTrue\b|\bFalse\b|\bNone\b|\bdict\b|\blist\b|\bint\b|\bfloat\b|\bstr\b|\blen\b)",re.MULTILINE)
RE_SYNTAX_HIGHLIGHT_BFUNCTIONS = re.compile(r"(__import__\(.*?\)[\.\w+]+\b|\bdef\b.*?:|\bclass\b.*?:|\bfrom\b.*?import.*?$|\bimport\s.*?\bas\b\.*?$|\bimport\b.*?$|\blambda\b|\bcontinue\b|\breturn\b)",re.MULTILINE)
RE_SYNTAX_HIGHLIGHT_MODULES = re.compile(r"(\b\w+\.[\.\w+]+\b)")
RE_SYNTAX_HIGHLIGHT_HSVARS = re.compile(r"((?:[O|E|S|A][N|A|C]\[([0-9]{1,2})\])|\bEI\b|\bpItem\b)")
def console(msg,color=None):
if type(msg) <> str:
msg = str(msg)
if len(msg.strip(" \n")) == 0:
return
if color:
msg = "\r{0}{1}{2}\r\n>> ".format(color, msg, Style.RESET_ALL)
else:
msg = "\r{0}\r\n>> ".format(msg)
sys.stdout.write (msg.decode("latin1").encode(sys.stdout.encoding)),
def console_error(msg):
console(msg,color=Fore.RED+Style.BRIGHT)
def console_info(msg):
console(msg,color=COLORINFO)
def console_info_ko(msg):
if DEBUG:
console(msg,color=COLORINFO)
def console_intern(msg):
_color = COLORINTERN
_is_systemlog_message = RE_SYSTEMLOG_FINDER.findall(msg)
if _is_systemlog_message:
_outmsg = ""
for _logmsg in _is_systemlog_message:
_logdetails = RE_SYSTEMLOG_GRABBER.search(_logmsg)
if not _logdetails:
continue
if len(_outmsg) > 0:
_outmsg += "\n"
_logdict = _logdetails.groupdict()
_logdict['time'] = time.strftime("%H:%M:%S",time.localtime())
_logdict['message'] = _logdict['message'].decode("string-escape").strip()
_outmsg += "SYSTEMLOG: {time} - {severity} {facility} - {message}".format(**_logdict)
if len(_outmsg) > 0:
msg = _outmsg
_color = Back.RED + Fore.YELLOW
else:
msg = "{0} {1}".format(time.strftime("%H:%M:%S",time.localtime()), msg)
console(msg,color=_color)
def console_code(msg,color=COLORINFO):
_color = color
if Style.RESET_ALL <> "" and SYNTAXHIGHLIGHT:
msg = RE_SYNTAX_HIGHLIGHT_COMMENT.sub(Fore.RED + Style.DIM + "\\1" + _color,msg)
msg = RE_SYNTAX_HIGHLIGHT_FUNCTIONS.sub(Fore.WHITE + Style.DIM + "\\1" + _color,msg)
msg = RE_SYNTAX_HIGHLIGHT_BFUNCTIONS.sub(Fore.MAGENTA + Style.DIM + "\\1" + _color,msg)
msg = RE_SYNTAX_HIGHLIGHT_MODULES.sub(Fore.YELLOW + Style.DIM + "\\1" + _color,msg)
msg = RE_SYNTAX_HIGHLIGHT_HSVARS.sub(Fore.CYAN + Style.DIM + "\\1" + _color,msg)
console(msg,color=_color)
def console_debug(msg):
if DEBUG:
console_code(msg,color=Fore.CYAN+Style.BRIGHT)
def nocomment(s):
result = []
g = tokenize.generate_tokens(io.BytesIO(s).readline)
for toknum, tokval, _, _, _ in g:
# print(toknum,tokval)
if toknum != tokenize.COMMENT:
result.append((toknum, tokval))
_result = tokenize.untokenize(result)
console_info("Remove all comments {0}/{1}".format(len(_result),len(s)))
return _result
def unquote(text):
## entfernt die Anführungszeichen
if type(text) <> str:
try:
text = str(text)
except:
return ""
return re.sub("^[\"|\']|[\"|\']$","",text)
def quoteVal(e):
## setzt Anführungszeichen wenn typ string
if e['isalpha']:
return "\"" + e['value'] + "\""
return str(e['value'])
def grp2str(_i):
return "%d/%d/%d" % (_i >> 11 & 0xff, _x >> 8 & 0x07, x & 0xff)
def str2grp(_s):
_t = _s.split("/")
return int(_t[0]) << 11 | int(_t[1]) << 8 | int(_t[2])
### Homeserver Klassen ###
class HomerServerDummy:
pass
class HSLogikItemDummy:
pass
class HSLogikSelfDummy:
pass
class dummy:
pass
class debug_dummy:
Version = "4.111.LOGIKDEBUGGER"
def __init__(self):
self.Daten = []
self.Index = {}
def setErr(self,pException,pComment=''):
console(Fore.RED + Style.BRIGHT + "Error:" + Fore.MAGENTA)
try:
STDOUT_MUTEX.acquire()
traceback.print_exception(pException[0],pException[1],pException[2],file=sys.stdout)
finally:
STDOUT_MUTEX.release()
console_intern(pComment)
def setErrDirekt(self,pText):
console_error("Error: %r" % pText)
def addGruppe(self,pGruppe,pItems):
console_intern("addGruppe %r with Items %r" % (pGruppe,pItems))
self.Index[pGruppe[0]] = dict((_x[0],_x) for _x in pItems)
self.Daten.append(pGruppe+[pItems,])
def setWert(self,pGruppe,pToken,pWert):
console_intern("setWert %s - %s to %s%r" % (pGruppe,pToken,Fore.YELLOW,pWert))
def addWert(self,pGruppe,pToken,pWert):
console_intern("addWert %s - %s to %s%r" % (pGruppe,pToken,Fore.YELLOW,pWert))
def addDauer(self,pGruppe,pToken,pWert):
console_intern("addDauer %s - %s to %s%r" % (pGruppe,pToken,Fore.YELLOW,pWert))
def __str__(self):
_ret = ""
for _data in self.Daten:
_ret += _data[1] + "\n"
_ret += "*"*20 + "\n"
for _line in _data[2]:
_ret += " " + re.sub(r'<.*?>',"",_line[1]) +"\n"
_ret += " " + re.sub(r'<.*?>'," ",_line[3]) + "\n"
return _ret
class HSIKOdummy:
def __init__(self,LGT,attached_out,name="",**kwargs):
self.LGT = LGT
self.MC = LGT.MC
self.Value = ''
if name:
self.name = name
self.endpoint_description = name
self.Format = 22
self.ReadFlag = 1
self.SpeicherID = 1
for _k,_v in kwargs.items():
setattr(self,_k,_v)
self._attached_out = attached_out
self.mutex = threading.Lock()
def setWert(self,out,wert):
try:
self.mutex.acquire()
self.Value = wert
if self.attached_out > 0:
console("** intern ** auf AN[%d]: %s%s" % (self._attached_out,Fore.YELLOW,repr(wert)))
self.LGT.setVar("AN",self._attached_out,wert)
else:
console("** intern ** auf iko[%s]: %s%s" % (getattr(self,"name",getattr(self,"RPCText","")),Fore.YELLOW,repr(wert)))
finally:
self.mutex.release()
def getWert(self):
try:
self.mutex.acquire()
return self.Value
finally:
self.mutex.release()
def checkLogik(self,out):
pass
__old_import__ = __import__
class hs_timer(threading._Timer):
def __init__(self,interval,function):
self.starttime = time.strftime("%H:%M:%S",time.localtime())
self.calctime = time.time() + interval
threading._Timer.__init__(self,interval, function)
def get_time(self):
return "start: %s remain %.2f s" % ( self.starttime,self.calctime - time.time() )
class hs_queue_queue(Queue.Queue):
def put(self,item,*args,**kwargs):
Queue.Queue.put(self,[time.time(),item],*args,**kwargs)
def get(self,*args, **kwargs):
return Queue.Queue.get(self,*args,**kwargs)[1]
import posixpath
import mimetypes
class ExtDatItem(object):
def __init__(self,path,mc):
import os
self.MC = mc
self.source_file = path
_path = path.replace(self.MC.LGT.hsupload_dir,"")
_path = _path.replace("\\","/")
console_info("-> Datei '{0}'".format(_path))
self.DatName = "OPT/{0}".format(_path.upper())
_extension = posixpath.splitext(_path)[1]
self.Typ = mimetypes.types_map.get(_extension,"application/octet-stream")
self.UrlPfad = _path.upper()
self.DatPos = 0
self.DatLen = os.path.getsize(path)
self.MC.GUI.ExtDatUrl[_path.upper()] = self
def getDaten(self):
return open(self.source_file,"rb").read()
def getQuadDaten(self):
return open(self.source_file,"rb").read()
def getDatenStream(self,stream):
stream.write(open(self.source_file,"rb").read())
def getQuadDatenStream(self,stream):
stream.write(open(self.source_file,"rb").read())
def dummy_return_all(self,*args,**kwargs):
console_debug("called '{0}' with args [{1}]".format(traceback.extract_stack(None, 2)[0][2],args))
class dummy_regex(object):
def search(*msg):
return True
def addZyklustimer(self,logik,nextstart):
import time
_nextstart_time = time.localtime(nextstart)
_seconds = nextstart - time.time()
console_debug("Set Timer {0} to {1} {2} seconds".format(logik,time.strftime("%H:%M:%S",_nextstart_time),_seconds))
for t in xrange(0,len(logik.OutOfset)):
if LGT.Offset[t+1][0] <> logik.OutOfset[t][0] and logik.OutOfset[t][0] > 0:
LGT.Offset[t+1][0] = logik.OutOfset[t][0]
LGT.Offset[t+1][1] = logik.OutOfset[t][1]
try:
LGT.Offset[t+1][2].cancel()
except:
pass
LGT.Offset[t+1][2] = hs_timer(_seconds,logik.MC.LGT.TimerCalc)
LGT.Offset[t+1][2].start()
def taglist_setwert(self,FLAG,iko,value):
if iko._attached_out > 0:
console_intern("*** setwert ** auf AN[{0}]: {1}{2}".format(iko._attached_out,Fore.YELLOW,value))
self.LGT.setVar("AN",iko._attached_out,value)
self.LGT.setVar("AC",iko._attached_out,0)
else:
console("** setwert ** auf iko[%s]: %s%s" % (getattr(iko,"name",getattr(iko,"RPCText","")),Fore.YELLOW,repr(value)))
def dummyThreadsigner(self,pName):
console_intern("*** SIGN THREAD {0} ***".format(pName))
class hs_queue(object):
Queue = hs_queue_queue
hs_threading = threading
class hs_fkt(object):
GlobalMC = None
@staticmethod
def SockConnect(pHost,pPort,pTo):
pass
sys.modules['hs_threading'] = threading
sys.modules['hs_queue'] = hs_queue
sys.modules['hs_fkt'] = hs_fkt
def __import__(module):
console_debug("Lade Modul %r" % module)
if module in ['hs_queue','sys','hs_fkt']:
print "FROM GLOBAL"
return globals().get(module)
return __old_import__(module)
def get_local_ip():
try:
_ip = socket.gethostbyname( socket.gethostname() )
except:
_ip = "127"
if _ip.startswith("127"):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('google.com', 0))
_ip = s.getsockname()[0]
s.close()
return _ip
###########################
FLAG_EIB_LOGIK=1
FLAG_EIB_ZENTRAL=2
FLAG_EIB_UNKNOWN=12
FLAG_EIB_REQUEST=13
FLAG_EIB_COMMAND=14
class LogikGeneratorClass:
def __init__(self):
self.GeneratorVersion = LGTVERSION
self.LogikNum = 10100
self.LogikName = "unamedLogik"
self.LogikiName = self.LogikName
self.LogikCat = ""
self.LOGIKVARS = {
"LOGIKNAME" : "unbenannt",
"LOGIKID" : "10001",
"LOGIKCATEGORY" : "KNXUF",
"LOGIKVERSION" : "1.00",
"LOGIKDESCRIPTION" : "\n",
"LOGIKDEBUG" : 0,
"LOGIKCOMPILEMODE" : 1,
"COMPILERCHECK" : "__import__('sys').version[:3] == '{0}'".format(sys.version[:3]),
"COMPILERVERSION" : sys.version[:3],
"LOGIKNOW" : time.strftime("%Y-%m-%d %H:%M"),
"LOGIKYEAR" : time.strftime("%Y"),
"LOGIKFILENAME" : "{LOGIKID}_{LOGIKNAME}"
}
self.LogikHeader = []
self.Eingang = [{'value':0}]
self.Ausgang = [{'value':0}]
self.Speicher = [{'value':0}]
self.Offset = [[0,0,None]]
self.Formel = []
self.runStart = False
self.isRemanent = False
self.iscrypted = False
self.rawlines = []
self.bCode = []
self.Options = { 'decode':False,'strict':False}
self.Errors = {'warning':0, 'error':0}
self.KOGW = {'running':False,'thread':None,'socket':None,'connected':False,'hsip': '','gwport':0,'gwsecret': ''}
self.KOGWInObj = {}
self.AutoRun = True
self.AutoConnect = False
self.hsupload_dir = None
self.mutex = threading.RLock()
## some dummy Vars
_mc = HomerServerDummy()
hs_fkt.GlobalMC = _mc
self.MC = _mc
_mc.LGT = self
_mc.SystemID = "0123456789ab"
_mc.ProjectID = time.strftime("%Y%m%d%H%M%S000",time.localtime())
_mc.SichQueue = Queue.Queue()
## GUI
_mc.GUI = dummy()
_mc.GUI.ExtDatUrl = {}
_guiclient = dummy()
_guiclient.BGList = { "DUMMYBG": [0,4321, "image/png" ] }
_guiclient.IconList = { "DUMMYICO" : [20,1234, "image/png" ] }
_guiclient.BGHash = hashlib.md5("")
_guiclient.IconHash = hashlib.md5("")
_mc.GUI.ClientKeyList = {
"D1024V" : _guiclient
}
## LogikList
_mc.LogikList = dummy()
_mc.LogikList.ConnectList = []
_mc.LogikList.calcLock = threading.RLock()
_mc.EIBTreiber = dummy()
_mc.EIBTreiber.BcuVersion = 2
_mc.EIBTreiber.BcuPhysAdr = 1
_mc.ThreadSign = types.MethodType(dummyThreadsigner,_mc)
## TagList
_mc.TagList = dummy()
_mc.TagList.LGT = self
_mc.TagList.TagList = {}
_mc.TagList.GrpListAll = {1 : HSIKOdummy(self,1)}
_mc.TagList.setWert = types.MethodType(taglist_setwert,_mc.TagList) ## FIXME
## Zyklustimer
_mc.ZyklusTimer = dummy()
_mc.ZyklusTimer.addTimerList = types.MethodType(addZyklustimer,_mc.ZyklusTimer) ## FIXME
## KameraList
_mc.KameraList = dummy()
_mc.KameraList.KamList = {}
## IP
_mc.Ethernet = dummy()
_mc.Ethernet.IPAdr = get_local_ip()
_mc.Ethernet.IPPort = 8080
## Default HS Resolver
_mc.DNSResolver = dummy()
_mc.DNSResolver.NameServer = ["192.168.232.1"] #["8.8.8.8","8.8.4.4"]
_mc.DNSResolver.getHostIP = socket.gethostbyname
## Debug
_mc.Debug = debug_dummy()
_mc.ServerQueueGUI = Queue.Queue()
## HS Telefonbedienung
_mc.TelefonInterface = dummy()
_mc.TelefonInterface.DoBefehl = lambda pZielnr,pAbsendernr: console_intern("Telefonbedienung: Ziel:{0} Absender:{1}".format(pZielnr,pAbsendernr))
## HS self dummy
_HSself = HSLogikSelfDummy()
_HSself.MC = _mc
_HSself.ID = self.LogikNum
_HSself.makeCheckSum = lambda: hashlib.md5(str(random.random())).hexdigest()
## HS Logik dummy
_pItem = HSLogikItemDummy()
_pItem.MC = _mc
_pItem.NextStart = 0
_pItem.SendIntervall = 0
_pItem.ID = 1
_pItem.Speicher = 0
_pItem.SpeicherWert = []
_pItem.Eingang = []
_pItem.Ausgang = []
_pItem.SpeicherWert = []
_pItem.OutWert = []
_pItem.InWert = []
_pItem.OutOfset = []
_pItem.LogikItem = _HSself
_pItem.LogikItem.Speicher = []
_pItem.LogikItem.AnzSpeicher = 0
_pItem.LogikItem.AnzOutput = 0
_mc.LogikList.GatterList = {
_pItem.ID : _pItem
}
## make them local
self.localVars = {
'self':_HSself,
'pItem':_pItem,
'Timer':[[None,None]],
'EI':1,
'EN':[None],
'EC':[None],
'EA':[None],
'SN':[None],
'SC':[None],
'SA':[None],
'AN':[None],
'AC':[None],
'AA':[None],
'ON':[None],
'OC':[None],
'OA':[None]
}
self.globalVars = globals()
def readConfig(self,configFile):
global DEBUG
self.Licences = {}
configparse = ConfigParser.SafeConfigParser()
configparse.read(configFile)
#for _lic in configparse.options("licences"):
# self.Licences[_lic] = configparse.get("licences",_lic)
_setoptions = {}
if self.LogikNum == 10100:
console_info("Looking for global Config")
else:
console_info("Looking for %s%r%s Config" % (Fore.GREEN,self.LogikNum,COLORINFO))
try:
DEBUG = configparse.getboolean('default','debug')
_setoptions["DEBUG"] = str(DEBUG)
except (ConfigParser.NoOptionError,ConfigParser.NoSectionError):
pass
try:
self.AutoRun = configparse.getboolean('default','autorun')
_setoptions["AUTORUN"] = str(self.AutoRun)
except (ConfigParser.NoOptionError,ConfigParser.NoSectionError):
pass
try:
self.hsupload_dir = "{0}\\".format(configparse.get('default','hsupload').rstrip("\\"))
_setoptions["HSUPLOAD"] = self.hsupload_dir
except (ConfigParser.NoOptionError,ConfigParser.NoSectionError):
pass
if configparse.has_section(str(self.LogikNum)):
console_info("Found Config for %s%r%s" % (Fore.GREEN,self.LogikNum,COLORINFO))
try:
DEBUG = configparse.getboolean(str(self.LogikNum),'debug')
_setoptions["DEBUG"] = str(DEBUG)
except ConfigParser.NoOptionError:
pass
try:
self.AutoRun = configparse.getboolean(str(self.LogikNum),'autorun')
_setoptions["AUTORUN"] = str(self.AutoRun)
except ConfigParser.NoOptionError:
pass
try:
self.AutoConnect = configparse.getboolean(str(self.LogikNum),'autoconnect')
_setoptions["AUTOCONNECT"] = str(self.AutoConnect)
except ConfigParser.NoOptionError:
pass
try:
if configparse.getboolean(str(self.LogikNum),'admin'):
if sys.platform == "win32":
import ctypes
if not ctypes.windll.shell32.IsUserAnAdmin():
ctypes.windll.shell32.ShellExecuteW(None,u"runas",unicode(sys.executable),unicode(" ".join(['"{0}"'.format(_x) for _x in sys.argv[:]])),None,8)
sys.exit(0)
except ConfigParser.NoOptionError:
pass
for _v in configparse.options(str(self.LogikNum)):
_defSet = re.findall("^([e|a|s][n|a|c])\[(\d+)\]",_v)
if _defSet:
_defSet = _defSet[0]
_vals = configparse.get(str(self.LogikNum),_v)
for _val in _vals.split("|"):
if _val.startswith("$IKO$"):
try:
#_iko = (lambda x: (lambda y: int(y[0]) <<11 | int(y[1]) << 8 | int(y[2]))(x.split("/")))(_val[5:])
_iko = str2grp(_val[5:])
if _defSet[0].upper() == "EN":
self.KOGWInObj[_iko] = int(_defSet[1])
self.Eingang[int(_defSet[1])]['ikos'].append(_val[5:])
console_info("** Setze IKO %s auf %sEN[%d]" % (Fore.GREEN + _val[5:] + COLORINFO,Fore.GREEN,int(_defSet[1])))
elif _defSet[0].upper() == "AN":
self.Ausgang[int(_defSet[1])]['ikos'].append(_val[5:])
console_info("** Setze IKO %s auf %sAN[%d]" % (Fore.GREEN + _val[5:] + COLORINFO,Fore.GREEN,int(_defSet[1])))
except:
pass
else:
self.setVar(_defSet[0].upper(),int(_defSet[1]),_val)
#print "%s: %r" % (_v,configparse.get(str(self.LogikNum),_v))
try:
self.KOGW['hsip'] = configparse.get('kogw','hsip')
self.KOGW['gwport'] = configparse.getint('kogw','gwport')
self.KOGW['gwsecret'] = configparse.get('kogw','gwsecret')
_setoptions["KOGW"] = "{0}:{1}".format(self.KOGW['hsip'],self.KOGW['gwport'])
except (ConfigParser.NoOptionError,ConfigParser.NoSectionError):
pass
if _setoptions:
console_debug("\n".join(["{0}:{1}".format(k,v) for k,v in _setoptions.iteritems()]))
#print self.KOGW
def _readConfig(self,cfile='LogikGen.config'):
cfg = ConfigParser.SafeConfigParser()
cfg.read(cfile)
console(cfg.get('default','copyright',''))
console(cfg.get('default','compiler',''))
#print sys.executable
def showHSLhelp(self):
return ""
def Header(self,header):
self.LogikHeader = header.split("\n")
def connectKOGW(self):
if self.KOGW['socket']:
console_info("*** KO-Gateway schon verbunden ***")
return
self.KOGW['thread'] = threading.Thread(target=self.__connectKOGW)
self.KOGW['running'] = True
self.KOGW['thread'].setDaemon(True)
self.KOGW['thread'].start()
def disconnectKOGW(self):
self.KOGW['running'] = False
console_info("*** warte auf KO-Gateway ***")
self.KOGW['thread'].join()
def __connectKOGW(self):
while self.KOGW['running']:
try:
if not self.KOGW['socket']:
try:
self.KOGW['socket'] = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.KOGW['socket'].connect((self.KOGW['hsip'],self.KOGW['gwport']))
self.KOGW['socket'].send(self.KOGW['gwsecret']+"\x00")
console_info("*** Verbindung zum KO-Gateway hergestellt ***")
self.KOGW['connected'] = True
self.__readKOGW()
except:
self.KOGW['connected'] = False
traceback.print_exc(file=sys.stdout)
console_error("*** Fehler beim verbinden zum KO-Gateway des HS: %s:%d" % (self.KOGW['hsip'],self.KOGW['gwport']))
if not self.KOGW['running']:
break
_t = 0
while self.KOGW['running'] and _t < 20:
_t += 1
time.sleep(0.5)
finally:
self.KOGW['connected'] = False
console_info("*** Verbindung zum KO-Gateway getrennt ***")
self.KOGW['socket'].close()
self.KOGW['socket'] = None
def __readKOGW(self):
buf = ""
while self.KOGW['running']:
_r,_w,_e = select.select([self.KOGW['socket']],[],[],1)
if self.KOGW['socket'] in _r:
_buf = self.KOGW['socket'].recv(8192)
if not _buf:
break
buf += _buf
while buf.find("\x00"):
try:
line,buf = buf.split("\x00",1)
except ValueError:
break
info = line.split("|")
if len(info) > 2:
if not info[1]:
continue
address = int(info[1])
#addr = "%d/%d/%d" % ((address >> 11) & 0xff, (address >> 8) & 0x07, (address) & 0xff)
_io = self.KOGWInObj.get(address,None)
if _io:
console_info_ko("KO-Gateway Eingang {0}: Wert: {1}".format(_io,info[2]))
self.setVar("EN",_io,info[2])
## nicht beim INIT
if self.AutoRun and info[0] <> "2":
self.LogikCalc()
def __sendKOGW(self,iko,val):
if self.KOGW['socket']:
try:
_a = (lambda x: (lambda y: int(y[0]) <<11 | int(y[1]) << 8 | int(y[2]))(x.split("/")))(iko)
_s = "1|"+str(_a)+"|"+str(val)+"\x00"
self.KOGW['socket'].send(_s)
except:
traceback.print_exc(file=sys.stdout)
pass
def LogikError(self,typ,line,LineNum,msg=" ",console=console):
if typ == "5000":
console_error("*** Fehler bei Experte Definition 5000: Zeile %d %s***" % (LineNum,msg))
console_info("\n#5000|\"Text\"|Remanent(1/0)|Anz.Eingänge|.n.|Anzahl Ausgänge|.n.|.n.")
elif typ == "5001":
console_error("*** Fehler bei HS Logik Definition 5001: Zeile %d %s***" % (LineNum,msg))
console_info("\n#5001|Anzahl Eingänge|Ausgänge|Offset|Speicher|Berechnung bei Start")
elif typ == "5002":
console_error("*** Fehler bei Eingangsdefinition 5002: Zeile %d %s***" % (LineNum,msg))
console_info("\n#5002|Index Eingang|Default Wert|0=numerisch 1=alphanummerisch")
elif typ =="5003":
console_error("*** Fehler bei Speicherdefinition 5003: Zeile %d %s***" % (LineNum,msg))
console_info("\n#5003|Speicher|Initwert|Remanent")
elif typ =="5004":
console_error("*** Fehler bei Ausgangsdefinition 5004: Zeile %d %s***" % (LineNum,msg))
console_info("\n#5004|ausgang|Initwert|runden binär (0/1)|typ (1-send/2-sbc)|0=numerisch 1=alphanummerisch")
elif typ =="5012":
console_error("*** Fehler bei Formel Definition 5012: Zeile %d %s***" % (LineNum,msg))
console_info("\n#5012|abbruch bei bed. (0/1)|bedingung|formel|zeit|pin-ausgang|pin-offset|pin-speicher|pin-neg.ausgang")
else:
console("TYPE %r" % (typ),color=Back.RED)
console("--------------------------------------------------------------------------")
console(line)
console("--------------------------------------------------------------------------")
#__import__('traceback').print_exc(file=__import__('sys').stdout)
self.Errors['error'] +=1
if self.Options['strict']:
self.exitall(1)
def exitall(self,_r):
if _r > 0:
traceback.print_exc(file=sys.stdout)
if self.KOGW['running']:
self.KOGW['running'] = False
console("** Warte auf KO-Gateway *** ")
self.KOGW['thread'].join()
for _t in self.Offset:
try:
_t[2].cancel()
except:
pass
_active_threads = threading.enumerate()
for _thread in _active_threads:
if _thread <> threading.currentThread():
try:
console_debug("Beende Thread: %r " % (_thread.name))
if type(_thread) == hs_timer:
_thread.cancel()
else:
_thread._Thread__stop()
console_error("--> killed thread: {0}".format(_thread.name))
_thread.join(2)
except:
traceback.print_exc(file=sys.stdout)
print ("Failed")
## Farben wiederherstellen
console( "** CLEANUP **")
if hasattr(sys.stdout,"TEE"):
sys.stdout = sys.stdout.stdout
#print Fore.WHITE,Back.BLACK,Style.RESET_ALL,
if hasattr(os,"kill"):
#print ("raise SIGTERM")
_pid = os.getpid()
os.kill(_pid,signal.SIGTERM)
time.sleep(0.5)
#sys.exit(int(_r <> 0))
raise SystemExit(int(_t <> 0))
def LogikDebug(self):
console("\n\n### Logik Debugger ###\n")
if self.hsupload_dir:
console_info("lade hsupload-Verzeichnis '{0}' hoch".format(self.hsupload_dir))
for _root,_dirs,_files in os.walk(self.hsupload_dir):
for _file in _files:
ExtDatItem(os.path.join(_root,_file),self.MC)
console_info("")
if self.AutoConnect:
self.connectKOGW()
while True:
time.sleep(0.5)
if self.KOGW['connected']:
break
time.sleep(0.5)
console_info("*** Waiting for KOGW ***")
if self.AutoRun and self.runStart:
self.LogikCalc()
while True:
try:
_cmd = raw_input("\r>> ")
if hasattr(sys.stdout,"TEE") and len(_cmd) > 1 :
sys.stdout.log(">> " + _cmd)
except (KeyboardInterrupt,SystemExit):
self.exitall(0)
_lcmd = _cmd.lower()
try:
if _lcmd.startswith("quit") or _lcmd.startswith("exit"):
self.exitall(0)
break