Эх сурвалжийг харах

refactor: nodescan2 TK-Nodescannert

micha 3 сар өмнө
parent
commit
9de8c48fb7
3 өөрчлөгдсөн 160 нэмэгдсэн , 60 устгасан
  1. 131 55
      tool/TK-Nodescanner.py
  2. 6 5
      tool/nodescan.py
  3. 23 0
      tool/nodescan2.py

+ 131 - 55
tool/TK-Nodescanner.py

@@ -14,6 +14,7 @@ import struct
 import sys
 import tkinter as Tkinter
 import _thread as thread
+import datetime
 
 import nodescan 
 #import nodescan2 #as nodescaner
@@ -21,6 +22,14 @@ import nodescan
 title = "TK-ArtNet-Nodscaner"
 sys.stdout.write("\x1b]2;"+title+"\x07")
 
+mc = None
+try:
+    import memcache
+    mc = memcache.Client(['127.0.0.1:11211'], debug=0)
+    #mc.set("dmx-1", [1]*512)
+except Exception as e:
+    print("Exception",e)
+
 #lock.acquire()
 #lock.release()
 class LOCK_BUF():
@@ -94,9 +103,9 @@ def fill_form(event=None):
     univ = "0"
     try:
         if node_list2[sel]["PortTypes"][0] == "@":
-            univ = ord(node_list2[sel]["SwIn"][0]) 
+            univ = ord(node_list2[sel]["SwIn"][0:1]) 
         else:
-            univ = ord(node_list2[sel]["SwOut"][0]) 
+            univ = ord(node_list2[sel]["SwOut"][0:1]) 
     except Exception as e:
         print("load Exception",e)
         MSG["text"] = e
@@ -154,34 +163,65 @@ def scan():
     global rx,node_list,old_tick,Scrollbar
     print("get node from cache "    )
     li_nodes.insert("end",str("----"))
-    rx.loop()
+    ##rx.loop()
+
     while 1:
         try:
             _scan()
         except Exception as e:
-            print("_scan Exception as",e,e.argv[0])
+            print("_scan Exception as",e) #,e.argv)
             MSG["text"] = e
             MSG["bg"] = "red"
         time.sleep(0.3)
 
+import nodescan2 #as nodescan2
 def _scan():
     #print(sys._getframe().f_code.co_name)
     global rx,node_list,old_tick,Scrollbar
-    
-    tick = rx.tick()
-    if tick == old_tick:
-        return 0
-    old_tick=tick
+    ips = nodescan2.os_list_ip() #example
+    for i,v in ips.items():
+        print(i,v)
+        #get_mask(ips)
+    nodescan2.ArtPoll()
+
+    nodes = []
+    if mc:
+        nodes = []
+        artpoll = mc.get("index-artpoll")
+        #print()
+        #print()
+        for k in artpoll:
+            #print("_scan",k)
+            data = mc.get(k)
+            #print(k,data)
+            #opcode=convert_to_hex("<h",data[8:10])
+            opcode= nodescan2.artnet_get_opcode(data)
+            #print(opcode)
+            if "ArtPollReplay" in opcode: # != '0x2100': #OpPollReplay
+                node = nodescan2.ArtNet_decode_pollreplay(data)
+                s = artpoll[k][1]
+                s = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
+                s = s.timestamp()
+                #s = int(time.time()-s.timestamp())
+                node["UPDATESTAMP"]  = s
+                node["BOOT"]         = 0
+                node["REFRESHSTAMP"] = s 
+                node["LASTPING"] = 0
+                #print("---",node)
+                node1 = nodescan.ArtNet_decode_pollreplay(data)
+                #print("+++",node1)
+                #node=node1
+                nodes.append(node)
+                #print()
 
-    nodes    = rx.get()
-    rx.clear()
     ok=0
     for n in nodes:
         if n not in node_list.get():
             node_list.append(n)
             ok=1
-    if ok:
+    if 1: #ok:
         refresh_node_list()
+    time.sleep(10)
 
 def refresh_node_list():
     print(sys._getframe().f_code.co_name)
@@ -195,7 +235,7 @@ def refresh_node_list():
         k = node["MAC"]
         nodesB[k] = node
         
-    print("k",nodesB.keys())
+    #print("k",nodesB.keys())
 
     k_sort = list(nodesB.keys())
     k_sort.sort()
@@ -204,9 +244,10 @@ def refresh_node_list():
     for k in k_sort:
         node_list.append(nodesB[k])
 
-    print("k sort",k_sort)
+    #print("k sort",k_sort)
     for k in k_sort:
         node = nodesB[k]
+        #print("lll",node)
 
         li_nodes.insert("end",str(node_nr).rjust(3," ") +" "+ node["lname"])
         bg = "lightgrey"
@@ -230,27 +271,36 @@ def refresh_node_list():
         if bg:
             color = li_nodes.itemconfig("end", bg=bg)
         
-        inout = " UNIVERS OUT="+ str(ord(node["SwOut"][0]))+" IN="+ str(ord(node["SwIn"][0]))
+        inout = " UNIVERS OUT="+ str(ord(node["SwOut"][0:1]))+" IN="+ str(ord(node["SwIn"][0:1]))
         li_nodes.insert("end",str(node_nr).rjust(3," ") + inout)
         
         li_nodes.insert("end",str(node_nr).rjust(3," ") +" MAC:"+ node["MAC"])
         
-        last_change=time.time()-float(node["UPDATESTAMP"]) 
-        timeline = ""
-        timeline += " LASTCHANGE:%0.1f"% (last_change)
-        REFRESHSTAMP = time.time()-float(node["REFRESHSTAMP"])
-        timeline +="  LASTPING:%0.1f"% REFRESHSTAMP 
-        li_nodes.insert("end",str(node_nr).rjust(3," ") +timeline )
-        if last_change > 10:
-            color = li_nodes.itemconfig("end", bg="ORANGE")
-        
-        if node["BOOT"]:
-            BOOT = time.time()-float(node["BOOT"])
-        else:
-            BOOT = 0
-        timeline ="  BOOT:%0.1f"% BOOT
-        li_nodes.insert("end",str(node_nr).rjust(3," ") +timeline +" sec" )
-        bg = ""
+        try:
+            last_change=time.time()-float(node["UPDATESTAMP"]) 
+            timeline = ""
+            timeline += " CHANGE:%0.1f"% (last_change)
+            REFRESHSTAMP = time.time()-float(node["REFRESHSTAMP"])
+            timeline +="  PING:%0.1f"% REFRESHSTAMP 
+            li_nodes.insert("end",str(node_nr).rjust(3," ") +timeline )
+            if last_change > 10:
+                color = li_nodes.itemconfig("end", bg="ORANGE")
+        except Exception as e:
+            li_nodes.insert("end",str(e)+"\n" )
+            li_nodes.itemconfig("end", bg="red")
+
+        try:
+            if node["BOOT"]:
+                BOOT = time.time()-float(node["BOOT"])
+            else:
+                BOOT = 0
+            timeline ="  BOOT:%0.1f"% BOOT
+            li_nodes.insert("end",str(node_nr).rjust(3," ") +timeline +" sec" )
+            bg = ""
+        except Exception as e:
+            li_nodes.insert("end",str(e)+"\n" )
+            li_nodes.itemconfig("end", bg="red")
+
 
         if bg:
             li_nodes.itemconfig("end", bg=bg)
@@ -328,6 +378,13 @@ def send_dmx_store(event=None):
     nodescan.send_node_cmd(cur_ip,cmd)
     poll(delay=1.5)
 
+def SEND_CMD(cmd="NIX"):
+    print(sys._getframe().f_code.co_name)
+    def cb(event=None):
+        print(sys._getframe().f_code.co_name,cmd)
+        _send_cmd(cmd=cmd)
+    return cb
+
 def send_cmd(event=None):
     print(sys._getframe().f_code.co_name)
     cmd = e_cmd.get() #"CMD DMX STORE "
@@ -366,6 +423,10 @@ def _send_cmd(event=None,cmd=""):
     print("_send_cmd:",cmd)
     cmd=" ".join(map(str,cmd) )
     a = e_ip.get().replace("[","").replace("]","")
+    if not a:
+        print("ERR: _send_cmd STOP no Node-IP selected !! ---------")
+        return 0
+
     cur_ip = []
     sep = "xx"
     if "," in a:
@@ -375,6 +436,11 @@ def _send_cmd(event=None,cmd=""):
     for i in a.split(sep):
         cur_ip +=[int(i)]
     print("SEND:",cur_ip,cmd)
+    b_scan.insert("end", "SendCMD: "+str(cur_ip)+cmd+"\n")
+    #import socket
+    #sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+    #sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
+    #nodescan.sock = sock
     nodescan.send_node_cmd(cur_ip,cmd)
     #poll(delay=1.5)
 
@@ -512,7 +578,7 @@ b_scan.pack(side="left",expand=0,fill="y")
 
 b_scan = Tkinter.Button(fframe,text="ArtNetPoll ->",width=10,command=poll,font=font2)
 b_scan.configure(bg="#0f0")
-b_scan.pack(side="left",expand=0,fill="y")
+#b_scan.pack(side="left",expand=0,fill="y")
 
 
 #POLL ['192.168.0.255', 6454] OK ;
@@ -526,11 +592,11 @@ def get_ips():
     #local_ips.append("2.0.0.255")
     cmd='ip a | grep " inet " | cut -d " " -f 6 | sort -h'
     r=os.popen(cmd)
-    print("cmd",cmd)
+    #print("cmd",cmd)
     txt=r.readlines()
     for ip in txt:
         ip = ip.strip()
-        print([ip])
+        #print([ip])
         if ip.startswith("127."):
             continue
         if ip.count(".") != 3:
@@ -544,7 +610,7 @@ def get_ips():
             ip = ".".join(ip[0])+".255.255.255"
         else:
             continue
-        print("-",ip)
+        #print("-",ip)
         #if ip == "2.255.255.255":
         #    print("- workaround -")
         #    local_ips.append("2.0.0.255")
@@ -564,15 +630,15 @@ e_poll_new["bg"] = "#fff"
 #print(dir(e_poll_new))
 e_poll_new.option_add("end","") #', 'option_clear', 'option_get
 e_poll_new.option_add("end","215.0.0.0")
-e_poll_new.pack(side="left")
+#e_poll_new.pack(side="left")
 #exit()
 
 b_scan = Tkinter.Button(fframe,text="Librelight:",font=font2,relief="flat",bg="orange")
-b_scan.pack(side="left",expand=0)
+#b_scan.pack(side="left",expand=0)
 b_scan = Tkinter.Button(fframe,text="KILL !",command=kill_librelight,width=6,font=font2,bg="red")
-b_scan.pack(side="left",expand=0)
+#b_scan.pack(side="left",expand=0)
 b_scan = Tkinter.Button(fframe,text="START ",command=start_librelight,width=6,font=font2,bg="green")
-b_scan.pack(side="left",expand=0)
+#b_scan.pack(side="left",expand=0)
 
 scrollbar = Tkinter.Scrollbar(cframe)
 scrollbar.pack(side=Tkinter.RIGHT, fill="y")
@@ -607,7 +673,7 @@ x=Tkinter.Label(line_frame,text="MSG:",font=font3,width=6)
 x.pack(side="left",expand=0,fill="y")
 x.configure(bg="darkgrey")
 
-MSG = Tkinter.Label(line_frame,text="xxx",font=font1,width=30,anchor="w")
+MSG = Tkinter.Label(line_frame,text="xxx",font=font1,width=60,anchor="w")
 MSG.pack(side="left",expand=0,fill="y")
 MSG.configure(bg="darkgrey")
 
@@ -754,41 +820,49 @@ line_frame.pack(side="top",expand=0,fill="x")
 
 Tkinter.Label(line_frame,text="CMD",font=font3,width=6).pack(side="left",expand=0,fill="y")
 e_cmd2 = Tkinter.Entry(line_frame,font=font3,width=16)
-e_cmd2.insert("end","DMX ERASE ")
-e_cmd2.bind("<Return>", send_cmd2 )
+CMD="- DMX ERASE"
+c=SEND_CMD(CMD)
+e_cmd2.insert("end",CMD)
+e_cmd2.bind("<Return>", c )
 e_cmd2.pack(side="left")
 #-------------------------------------------- line
 line_frame = Tkinter.Frame(eframe1)
 line_frame.pack(side="top",expand=0,fill="x")
 Tkinter.Label(line_frame,text="CMD",font=font3,width=6).pack(side="left",expand=0,fill="y")
 e_cmd3 = Tkinter.Entry(line_frame,font=font3,width=16)
-e_cmd3.insert("end","DMX OUT STORE ")
-e_cmd3.bind("<Return>", send_cmd3 )
+CMD="DMX OUT STORE"
+c=SEND_CMD(CMD)
+e_cmd3.insert("end",CMD)
+e_cmd3.bind("<Return>", c )
 e_cmd3.pack(side="left")
 #-------------------------------------------- line
 line_frame = Tkinter.Frame(eframe1)
 line_frame.pack(side="top",expand=0,fill="x")
 Tkinter.Label(line_frame,text="CMD",font=font3,width=6).pack(side="left",expand=0,fill="y")
 e_cmd4 = Tkinter.Entry(line_frame,font=font3,width=16)
-e_cmd4.insert("end","DMX OUT SET 2")
-e_cmd4.bind("<Return>", send_cmd4 )
+CMD="DMX OUT SET 2"
+c=SEND_CMD(CMD)
+e_cmd4.insert("end",CMD)
+e_cmd4.bind("<Return>", c )
 e_cmd4.pack(side="left")
 #-------------------------------------------- line
 line_frame = Tkinter.Frame(eframe1)
 line_frame.pack(side="top",expand=0,fill="x")
 Tkinter.Label(line_frame,text="CMD",font=font3,width=6).pack(side="left",expand=0,fill="y")
 e_cmd5 = Tkinter.Entry(line_frame,font=font3,width=16)
-e_cmd5.insert("end","REBOOT ")
-e_cmd5.bind("<Return>", send_cmd5 )
+CMD="REBOOT"
+c=SEND_CMD(CMD)
+e_cmd5.insert("end",CMD)
+e_cmd5.bind("<Return>", c )
 e_cmd5.pack(side="left")
 
 
-nodescan.bind_cmd_node()
 
 def network_listenet():
     print(sys._getframe().f_code.co_name)
     b_scan.insert("end", "log:\n" )
     while 1:
+        #print(".")
         if nodescan.node_cmd_buf_list:
             msg = str(nodescan.node_cmd_buf_list)
             print("read_cmd_buf msg",msg)
@@ -812,12 +886,12 @@ def update_idletask():
         #print(nodescan.sock)
         #print(dir(nodescan.sock))
         #print(nodescan.sock.getsockopt())
-        if nodescan.sock.connected == 0:
-            MSG["text"] = "Nodescanner not Connected !"
-            MSG["bg"] = "red"
-        else:
-            MSG["text"] = ""
-            MSG["bg"] = "grey"
+        #if nodescan.sock.connected == 0:
+        #    MSG["text"] = "Nodescanner not Connected !"
+        #    MSG["bg"] = "red"
+        #else:
+        #    MSG["text"] = ""
+        #    MSG["bg"] = "grey"
         
 
 def main():
@@ -827,6 +901,8 @@ def main():
     thread.start_new_thread(network_listenet, () )
     thread.start_new_thread(update_idletask, () )
 
+    #nodescan.bind_cmd_node()
+
 main()
 root.mainloop()
 

+ 6 - 5
tool/nodescan.py

@@ -84,7 +84,7 @@ def bind_cmd_node():
         sock_cmd.bind(('', 7601)) #7601
         #sock_cmd.bind(('', 49737))
         sock_cmd.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
-        
+        print("bind_cmd_node",7601, "OK")   
     except socket_cmd.error as e:
         print("Socket 6454 ", "ERR: {0} ".format(e.args))
         sys.exit()
@@ -358,8 +358,8 @@ def ArtNet_decode_pollreplay(data):
         if opcode == struct.pack("<H",0x2100): #OpPollReplay
             if len(data) >= 207: #Mal
                 #if debug:print("-----------------------------------------")
-                print("===================================================================-")
-                print("decode",data[:13])           
+                #print("===================================================================-")
+                #print("decode",data[:13])           
                 if debug:print([opcode] ,"OpPollReplay")
                 _ip = []
                 #print("data[10]",data[10])
@@ -713,10 +713,11 @@ def node_cmd_recive():
     global node_cmd_buf_list
     #sock.sendto('\x00\x00\x00\x00\x00',(ip,port)) # ArtPol / ping
     is_running = 1
-    while is_running:
+    while 1:#is_running:
+        print("...")
         data, addr = sock_cmd.recvfrom(5000)
         #print(len(data))
-        #print([addr,data])
+        print("node_cmd_rcv",[addr,data])
         if len(data) == 207:
             print()
         else:

+ 23 - 0
tool/nodescan2.py

@@ -82,6 +82,23 @@ def convert_to_hex(x,d):
         pass
     return out 
 
+def artnet_get_opcode(head):
+    #print([head]) #[9:10])
+    opcode=0x0000
+    name ="unkown"
+    try:
+        opcode=hex(struct.unpack('<h', head[8:10])[0])
+    except:
+        print("opcode error",[head])
+
+    if opcode == '0x5000':
+        name = "ArtDMX"
+    elif opcode == '0x2000':
+        name = "ArtPoll"
+    elif opcode == '0x2100':
+        name = "ArtPollReplay"
+    return (name,opcode)
+
 def ArtNet_decode_pollreplay(data):
     debug = 0
     node = {}
@@ -266,7 +283,13 @@ def os_list_ip():
                     ips[dev].append(ip)
                     #print("  ",[dev,ip])
     return ips
+
+
+#ips = os_list_ip() #example
+#get_mask(ips)
+
 def get_mask(IP):
+
     print(sys._getframe().f_code.co_name)
     import ipaddress
     #mask=ipaddress.IPv4Network(IP+'/8',False)