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

cleanup TK-Nodescanner and nodescan2

micha 3 сар өмнө
parent
commit
4db52f5d6c

+ 117 - 272
tool/TK-Nodescanner.py

@@ -15,11 +15,11 @@ import sys
 import tkinter as Tkinter
 import _thread as thread
 import datetime
+import traceback
 
 from cprint import cprint
 
 import nodescan 
-#import nodescan2 #as nodescaner
 
 _file_path = "/opt/LibreLight/Xdesk/"
 sys.path.insert(0,"/opt/LibreLight/Xdesk/")
@@ -27,16 +27,18 @@ sys.path.insert(0,"/opt/LibreLight/Xdesk/")
 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:
-    cprint("Exception",e,color="red")
+def connect_mc():
+    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:
+        cprint("Exception",e,color="red")
+    return mc
+
+mc = connect_mc()
 
-#lock.acquire()
-#lock.release()
 class LOCK_BUF():
     def __init__(self):
         self.data = []
@@ -62,6 +64,7 @@ class LOCK_BUF():
             self.lock.release()
         return out
 
+
 node_list = LOCK_BUF() #[]
 
 def fill_form(event=None):
@@ -129,119 +132,86 @@ def clear_form():
     e_lname.delete("0","end")
     e_sname.delete("0","end")
     e_artnet_uni1.delete("0","end")
-
     
-def clear_node_list():
-    cprint(sys._getframe().f_code.co_name,color="yellow")
-    li_nodes.delete("0","end")
 
-    
-def poll(delay=1,ip=""):
-    cprint(sys._getframe().f_code.co_name,color="yellow")
+def main_loop():
+    while 1:
+        try: 
+            poll()
+        except Exception as e:
+            print()
+            cprint("Err main()",e,color="red")
+            cprint(traceback.format_exc(),color="red")
+            cprint("="*20,color="red")
+        time.sleep(3)
 
+def poll(delay=1,ip=""):
+    print()
+    cprint(sys._getframe().f_code.co_name,"="*30,color="yellow")
+    
+    ip = "2.255.255.255"
     if not ip:
-        ip = p_variable.get()
+        cprint("err poll() no ip !",color="red")
+        return
 
     b_scan.insert("end", "ArtNetPoll -> "+str(ip)+"\n")
-    nodescan.ArtNet_poll(ip)    
-    time.sleep(1)
-    fill_form()
-    
-def clear(event= None):
-    cprint(sys._getframe().f_code.co_name,color="yellow")
-    clear_node_list()
-    clear_form()
-    
-def poll_loop():
-    cprint(sys._getframe().f_code.co_name,color="yellow")
-    time.sleep(1)
-    while 1:
-        poll()
-        time.sleep(1)
+    b_scan.yview("end")
+    nodescan2.ArtPoll(ip=ip) 
+    nodes = load_node_list()
+    refresh_node_list(nodes)
 
-old_tick = 0
-rx = nodescan.ArtNetNodes()
-#rx = nodescan2        
+    
 
-def scan():
-    cprint(sys._getframe().f_code.co_name,color="yellow")
-    global rx,node_list,old_tick,Scrollbar
-    print("get node from cache "    )
-    li_nodes.insert("end",str("----"))
-    ##rx.loop()
+import nodescan2 
 
-    while 1:
-        try:
-            _scan()
-        except Exception as e:
-            cprint("_scan Exception as",e,color="red") #,e.argv)
-            MSG["text"] = e
-            MSG["bg"] = "red"
-            time.sleep(1)
-        time.sleep(0.3)
-
-import nodescan2 #as nodescan2
-def _scan():
-    cprint(sys._getframe().f_code.co_name,color="yellow")
-    global rx,node_list,old_tick,Scrollbar
+def load_node_list():
+    cprint(sys._getframe().f_code.co_name,"------------",color="yellow")
+    global node_list,Scrollbar,mc
+    li_nodes.delete("0","end")
 
     ips = nodescan2.os_list_ip() #example
-    nodescan2.ArtPoll()
 
     nodes = []
     if not mc:
         cprint("mc (memcached) is none",color="red")
-        time.sleep(2)
+        mc = connect_mc()
         return 
 
     nodes = []
     artpoll = mc.get("index-artpoll")
     if not artpoll:
-        time.sleep(2)
+        cprint("mc.get('index-artpoll') is none ",color="red")
+        mc = connect_mc()
         return 
 
-    #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
+            #node1 = nodescan2.ArtNet_decode_pollreplay(data)
             nodes.append(node)
-            #print()
 
     ok=0
     for n in nodes:
         if n not in node_list.get():
             node_list.append(n)
             ok=1
-    if 1: #ok:
-        refresh_node_list()
-    time.sleep(10)
-
-def refresh_node_list():
-    cprint(sys._getframe().f_code.co_name,color="yellow")
-    refresh_node_list2()
 
+    return node_list
     
-def refresh_node_list2():
+def refresh_node_list(nodes):
     cprint(sys._getframe().f_code.co_name,color="yellow")
+    li_nodes.delete("0","end")
+    li_nodes.insert("end","  - none -")
+
     node_nr = 1
     nodesB = {}
     for node in node_list.get(): #nodes:
@@ -336,8 +306,9 @@ def refresh_node_list2():
         out.append({"txt":"","bg":"white"})
 
     # insert nodes in listbox
-    li_node_scroll = li_nodes.yview()
-    li_nodes.delete("0","end")
+    if out:
+        li_node_scroll = li_nodes.yview()
+        li_nodes.delete("0","end")
     for i in out:
         #print("list:",i)
         li_nodes.insert("end",i["txt"])
@@ -348,14 +319,6 @@ def refresh_node_list2():
         li_nodes.itemconfig("end", bg=bg)
 
 
-def get_new_ip_str(event=None):
-    cprint(sys._getframe().f_code.co_name,color="yellow")
-    x = e_ip_new.get().replace("[","").replace("]","")
-    x = x.strip()
-    x = x.replace(" ","")
-    x = x.split(",")
-    print( "get_new_ip_str",x)
-    return x
 
 def get_form(event=None):
     cprint(sys._getframe().f_code.co_name,color="yellow")
@@ -366,7 +329,7 @@ def get_form(event=None):
     x = x.split(",")
     ip2 = ".".join(x)
 
-    ip = e_ip_new.get()
+    ip = e_ip.get()
     ip = ip.replace(" ","")
     ip = ip.replace(",",".")
     MASK = variable.get() #e_mask_new.get()
@@ -388,7 +351,7 @@ def get_form(event=None):
     data["univ"] = univ
     print("FORM:")
     for k,v in data.items():
-        print("  ",k,v)
+        print("  ",[k,v])
     return data
 
 def send_artaddr(event=None):
@@ -406,9 +369,7 @@ def send_artaddr(event=None):
     print("SEND ArtAddress:",[ln,sn,ip,univ])
 
     if ln and sn and ip and univ:
-        nodescan.ArtAddress(ip=ip ,ShortName=sn, LongName=ln,Port="",Universes=univ)
-        time.sleep(1)
-        poll()
+        nodescan2.ArtAddress(ip=ip ,ShortName=sn, LongName=ln,Port="",Universes=univ)
 
 
 def send_none(event=None):
@@ -427,9 +388,7 @@ def send_mac(event=None):
     for i in a.split(","):
         cur_ip +=[int(i)]
     print("SEND MAC:",cur_ip,new_mac)
-    nodescan.send_node_cmd(cur_ip,cmd=new_mac)
-    # nodescan.sock.sendto(cmddata2 ,(ip,port))
-    #poll(delay=1.5)
+    nodescan2.send_node_cmd(cur_ip,cmd=new_mac)
 
 
 def SEND_CMD(cmd="NIX",entry=None):
@@ -463,7 +422,8 @@ def SEND_CMD(cmd="NIX",entry=None):
             _cmd2 = bytes(_cmd2)
             print("  _cmd2",_cmd2)
 
-            nodescan.sock.sendto(_cmd2 ,(form["IP2"],port))
+            sock = nodescan2.UDP_Socket()
+            sock.sendto(_cmd2 ,(form["IP2"],port))
 
     return cb
 
@@ -473,6 +433,9 @@ def send_artdmx(val=127):
         print(form)
         import lib.ArtNetNode as an
         if form["IP2"] and form["univ"]:
+            #artnet = an.ArtNetNode(to=form["netmask"],univ=form["univ"],port=4566)
+            b_scan.insert("end", "ArtDMX -> "+str(form["IP2"])+" univ:"+str(form["univ"])+" v="+ str(val)+"\n")
+            b_scan.yview("end")
             artnet = an.ArtNetNode(to=form["IP2"],univ=form["univ"],port=4566)
             artnet.send([val]*512,port=6454)
             print(artnet._data)
@@ -505,125 +468,72 @@ def _send_cmd(event=None,cmd=""):
     for i in a.split(sep):
         cur_ip +=[int(i)]
     cprint("_cmd_send:",cur_ip ,"CMD:",[cmd],color="yellow")
-    nodescan.send_node_cmd(cur_ip,cmd)
-    #poll(delay=1.5)
-
-def kill_librelight(event=None):
-    print(sys._getframe().f_code.co_name)
-    #for i in ["CONSOLE.py","EDITOR.py","ASP"]:
-    for i in ["ASP"]:
-        cmd='screen -XS "{}" quit | echo ""'.format(i)
-        print(cmd)
-        b_scan.insert("end",cmd+"\n")
-        os.system(cmd)
-
-    cmd="screen -ls"
-    os.system(cmd)
-    time.sleep(1)
-    BASE_PATH = "/opt/LibreLight/Xdesk/"
-    cmd="_LibreLightDesk.py"
-    cmd="tool/TK-Nodescanner.py" #&"
-
-    b_scan.insert("end",cmd+"\n")
-    arg = ""
-    #os.execl("/usr/bin/python3", BASE_PATH, cmd,arg)
-
-    global nodescan
-    nodescan.is_running = 0 # exit all thread loop's
-
-    nodescan.sock.close()
-    time.sleep(1) 
-    nodescan.sock = nodescan.socket_warp()
-    time.sleep(1) 
-    thread.start_new_thread(nodescan.node_cmd_recive, () )
-    rx.loop()
-    time.sleep(1) 
-    poll()
-
-def start_librelight(event=None):
-    #for i in ["CONSOLE.py","EDITOR.py","ASP"]:
-    for i in ["ASP"]:
-        cmd='screen -XS "{}" quit | echo ""'.format(i)
-        print(cmd)
-        os.system(cmd)
-
-    global nodescan,rx
-    nodescan.is_running = 0 # exit all thread loop's
-
-    nodescan.sock.close()
-    time.sleep(1) 
-    #root.quit()
-    thread.start_new_thread(nodescan.node_cmd_recive, () )
-    rx.loop()
-    time.sleep(0.5)
-
-    BASE_PATH = "/opt/LibreLight/Xdesk/"
-    cmd="init/10-ASP.sh"
-    arg = ""
-    os.system(cmd)
-    #os.execl("/usr/bin/sh", BASE_PATH, cmd,arg)
-
-
+    nodescan2.send_node_cmd(cur_ip,cmd)
+
+
+def ip_to_byte(ip):
+    x = ip.strip()
+    if "." in x:
+        x = x.split(".")
+        print(x)
+    elif ":" in x:
+        x = x.replace(":","")
+        print(x)
+        x = bytes.fromhex(x)
+       
+    else:
+        return [0,0,0,0]
+
+    y = []
+    for i in x:
+        y.append(int(i))
+    return y
 
 def set_ip(event=None):
     print("SET NEW IP")
 
-    cur_ip=(2,0,0,94)
-    new_ip=(2,0,0,201)
-    new_netmask=(255,0,0,0)
-    
-    a = e_ip.get().replace("[","").replace("]","")
-    b = e_ip_new.get().replace("[","").replace("]","")
-    c = variable.get() #e_mask_new.get()
-    new_netmask = [] #c.split(".") #list(c)
-    for i in c.split("."):
-        new_netmask +=[int(i)]
-    cur_ip = []    
-    for i in a.split(","):
-        cur_ip +=[int(i)]
-    new_ip = []
-    for i in b.split(","):
-        new_ip +=[int(i)]
+    d=get_form()
+    cur_ip = ip_to_byte(d["IP"])
+    new_ip = ip_to_byte(d["IP2"])
+    #new_netmask = ip_to_byte( d["mac"])
+    new_netmask = ip_to_byte( d["netmask"])
         
+    print("new",[cur_ip, new_ip, new_netmask])
     if new_ip == cur_ip:
-        print("neu und als IP sind gleich"  )
+        cprint("ERR set_ip() neu und als IP sind gleich" ,color="red" )
         return 0
-    #cur_ip=(2,0,0,94)
-    #new_ip=(2,0,0,201)
     
     print("new",[cur_ip, new_ip, new_netmask])
     print()
-    nodescan.set_ip4(cur_ip,new_ip, new_netmask)
-    poll(delay=1.5)
+    nodescan2.set_ip4(cur_ip,new_ip, new_netmask)
     
 def set_node_pin(evnet=None):
     cprint(sys._getframe().f_code.co_name,color="yellow")
     cmd = "CMD DMX=PIN"
-    ip = get_new_ip_str()
+    ip = get_form()["IP"]
     print("ip",[ip])
-    nodescan.send_node_cmd(ip,cmd=cmd)
-    poll(delay=1.5)
+    nodescan2.send_node_cmd(ip,cmd=cmd)
     
 def set_node_in(evnet=None):
     cprint(sys._getframe().f_code.co_name,color="yellow")
     cmd="CMD DMX=IN"
-    ip = get_new_ip_str()
-    nodescan.send_node_cmd(ip,cmd=cmd)
-    poll(delay=1.5)
+    ip = get_form()["IP"]
+    nodescan2.send_node_cmd(ip,cmd=cmd)
     
 def set_node_out(evnet=None):
     cprint(sys._getframe().f_code.co_name,color="yellow")
     cmd="CMD DMX=OUT"
-    ip = get_new_ip_str()
-    nodescan.send_node_cmd(ip,cmd=cmd)
-    poll(delay=1.5)
+    ip = get_form()["IP"]
+    nodescan2.send_node_cmd(ip,cmd=cmd)
 
 
-    
+# ----------------------------------------------
+#  TK-WINDOW
+# ----------------------------------------------
 root = Tkinter.Tk()
-#root.geometry("900x700+100+100")
 root.geometry("700x600+100+100")
 root.title( title)
+
 fframe = Tkinter.Frame(root)
 fframe.pack(side="top",expand=0,fill="x")
 cframe = Tkinter.Frame(root)
@@ -635,78 +545,16 @@ font3 = ("Helvetica", 12) # 16
 font20 = font=("Helvetica", 12) # 22
 font120 = font=("Helvetica", 22) # 22
 
-b_scan = Tkinter.Button(fframe,text="refresh list",width=8,command=refresh_node_list,font=font2)
+b_scan = Tkinter.Button(fframe,text="refresh",width=8,command=poll,font=font2)
 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")
-
 
-#POLL ['192.168.0.255', 6454] OK ;
-#POLL ['192.168.0.99', 6454] OK ;
-#POLL ['2.255.255.255', 6454] OK ;
-#POLL ['2.0.0.255', 6454] OK ;
-#POLL ['2.255.255.255', 6454] OK ;
-
-def get_ips():
-    cprint(sys._getframe().f_code.co_name,color="yellow")
-    local_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)
-    txt=r.readlines()
-    for ip in txt:
-        ip = ip.strip()
-        #print([ip])
-        if ip.startswith("127."):
-            continue
-        if ip.count(".") != 3:
-            continue
-        
-        if ip.endswith("/24"):
-            ip = ip.split(".")
-            ip = ".".join(ip[:3])+".255"
-        elif ip.endswith("/8"):
-            ip = ip.split(".")
-            ip = ".".join(ip[0])+".255.255.255"
-        else:
-            continue
-        #print("-",ip)
-        #if ip == "2.255.255.255":
-        #    print("- workaround -")
-        #    local_ips.append("2.0.0.255")
-
-        local_ips.append(ip)
-    return local_ips
-
-local_ips =get_ips()
-
-option_list=local_ips
-p_variable = Tkinter.StringVar(root)
-p_variable.set(option_list[0]) # default value
-e_poll_new = Tkinter.OptionMenu(fframe, p_variable,*option_list,)
-e_poll_new.configure(font=("Helvetica", 13))
-e_poll_new.configure(width=13)
-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")
-#exit()
-
-b_scan = Tkinter.Button(fframe,text="Librelight:",font=font2,relief="flat",bg="orange")
-#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 = Tkinter.Button(fframe,text="START ",command=start_librelight,width=6,font=font2,bg="green")
-#b_scan.pack(side="left",expand=0)
 
 scrollbar = Tkinter.Scrollbar(cframe)
 scrollbar.pack(side=Tkinter.RIGHT, fill="y")
 
-#pool = Tkinter.Listbox(root,selectmode="extended",exportselection=0)
 li_nodes = Tkinter.Listbox(cframe,exportselection=0,width=35,font=font1)
 li_nodes.pack(side="left",expand=0,fill="y")
 li_nodes.bind("<ButtonRelease-1>",fill_form )
@@ -727,8 +575,11 @@ line_frame.pack(side="top",expand=0,fill="x")
 x=Tkinter.Label(line_frame,text=" ",font=font2,width=6)
 c= Tkinter.Label(line_frame,text=" ",font=font1,width=30,anchor="w")
 c.pack(side="left",expand=0,fill="y")
-# ----------------------------------------------
+
+
 
+# ----------------------------------------------
+#  TK-FORM
 # ----------------------------------------------
 line_frame = Tkinter.Frame(eframe)
 line_frame.pack(side="top",expand=0,fill="x")
@@ -740,8 +591,6 @@ 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")
 
-#msg["bg"] = "lightgrey"
-#msg.pack(side="left")
 # ----------------------------------------------
 line_frame = Tkinter.Frame(eframe)
 line_frame.pack(side="top",expand=0,fill="x")
@@ -768,7 +617,6 @@ e_ip_label.pack(side="left",expand=0,fill="y")
 e_ip_new = Tkinter.Entry(line_frame,font=font20,width=26)
 e_ip_new.bind("<Return>", set_ip )
 e_ip_new.bind("<KP_Enter>", set_ip)
-#e_ip_new.bind("<Tab>", update_name)
 e_ip_new.bind("<ISO_Left_Tab>", set_ip)
 e_ip_new.pack(side="left")
 
@@ -784,13 +632,10 @@ e_mask_new = Tkinter.OptionMenu(line_frame, variable,"255.255.255.0","255.0.0.0"
 e_mask_new.configure(font=("Helvetica", 12))
 e_mask_new.configure(width=12)
 e_mask_new["bg"] = "#fff"
-#heigh=1,font=("Helvetica", 20)
 e_mask_new.pack(side="left")
 e=Tkinter.Label(line_frame,text="")
 e.configure(width=11)
 e.pack(side="left")
-#e_mask_new.insert("end","255.0.0.0")
-#e_mask_new.insert("end","255.255.255.0")
 
 b_scan = Tkinter.Button(line_frame,text="SEND TO NODE",command=set_ip,width=14,font=font1)
 b_scan.pack(side="left",expand=0)
@@ -813,13 +658,9 @@ line_frame = Tkinter.Frame(eframe)
 line_frame.pack(side="top",expand=0,fill="x")
 c= Tkinter.Label(line_frame,text=" ",font=font120,width=30,anchor="w")
 c.pack(side="left",expand=0,fill="y")
-# ----------------------------------------------
 #-------------------------------------------- line
 
 
-#b_scan = Tkinter.Button(eframe1,width=14,font=font3)
-#b_scan.pack(side="top",expand=0)
-
 line_frame = Tkinter.Frame(eframe)
 line_frame.pack(side="top",expand=0,fill="x")
 Tkinter.Label(line_frame,text="DMX:",font=font3,width=6).pack(side="left",expand=0,fill="y")
@@ -950,10 +791,10 @@ def network_listenet():
     b_scan.insert("end", "log:\n" )
     while 1:
         #print(".")
-        if nodescan.node_cmd_buf_list:
-            msg = str(nodescan.node_cmd_buf_list)
+        if nodescan2.node_cmd_buf_list:
+            msg = str(nodescan2.node_cmd_buf_list)
             print("read_cmd_buf msg",msg)
-            nodescan.node_cmd_buf_list = []
+            nodescan2.node_cmd_buf_list = []
 
             stamp = str(time.time())+"\n"
             stamp = time.strftime("%Y-%m-%d %X\n")
@@ -965,8 +806,7 @@ def network_listenet():
         time.sleep(0.1)
 
 
-def update_idletask():
-    cprint(sys._getframe().f_code.co_name,color="yellow")
+def tk_loop():
     while 1:
         root.update_idletasks()
         time.sleep(1)
@@ -974,10 +814,15 @@ def update_idletask():
 
 def main():
     cprint(sys._getframe().f_code.co_name,color="yellow")
-    thread.start_new_thread(scan, () )
-    thread.start_new_thread(nodescan.node_cmd_recive, () )
-    thread.start_new_thread(network_listenet, () )
-    thread.start_new_thread(update_idletask, () )
+
+
+    thread.start_new_thread(main_loop, () )
+
+    #thread.start_new_thread(nodescan.node_cmd_recive, () )
+    #thread.start_new_thread(network_listenet, () )
+
+    thread.start_new_thread(tk_loop, () )
+    thread.start_new_thread(nodescan2.ArtNet_Server,())
 
     #nodescan.bind_cmd_node()
 

+ 0 - 0
tool/TK-Nodescanner2.py → tool/TK-Nodescanner_old.py


+ 2 - 1
tool/nodescan.py

@@ -111,7 +111,8 @@ class socket_warp():
     def rcv(self):
         print(sys._getframe().f_code.co_name)
 
-sock = socket_warp()
+if __name__ == "__main__":
+    sock = socket_warp()
     
     
 try:

+ 279 - 12
tool/nodescan2.py

@@ -15,19 +15,23 @@ import _thread as thread
 import copy
 import random
 import traceback
+from cprint import cprint
 
-sys.stdout.write("\x1b]2;Nodescan\x07")
-
+if __name__ == "__main__":
+    sys.stdout.write("\x1b]2;Nodescan\x07")
 
 def UDP_Socket(bind=False,ip='',port=6454):
     sock = False
     try:
+        print(sys._getframe().f_code.co_name,"BIND",(ip,port,bind),"?")
         sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
         sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
         if bind:
             sock.bind((ip, port))
+            print(sys._getframe().f_code.co_name,"BIND",(ip,port),"OK")
+
     except socket.error as e:
-        print("Socket 6454 ", "ERR: {0} ".format(e.args))
+        cprint(" Socket 6454 ", "ERR: {0} ".format(e.args),color="red")
         sock = False
 
     return sock
@@ -40,9 +44,10 @@ def ArtPoll(sock=None,ip="2.255.255.255",port=6454):
     #port=6454
     #ip="2.255.255.255"
     PKG=b'Art-Net\x00\x00 \x00\x0e\x06\x00'
-    print("SEND:",[PKG])
+    print(" -> SEND:",[PKG])
     sock.sendto(PKG,(ip,port)) # ArtPol / ping
     sock.close()
+    time.sleep(1)
 
 
 def convert_mac(MAC):
@@ -82,6 +87,63 @@ def convert_to_hex(x,d):
         pass
     return out 
 
+mc = None
+
+def connect_memcache():
+    global mc
+    try:
+        import memcache
+        mc = memcache.Client(['127.0.0.1:11211'], debug=0)
+        return 1
+    except Exception as e:
+        cprint("Err connect_memcache",e,color="red")
+    return 0
+
+#thread.start_new_thread(connect_memcache, () )
+connect_memcache()
+
+from datetime import datetime
+
+if mc:
+    INDEX="index-artpoll"
+    mc.set(INDEX ,{})
+
+def update_mc_artpoll_index(key,val=""):
+    try:
+        INDEX="index-artpoll"
+        _index =  mc.get(INDEX)
+        #print("A",_index)
+        if type(_index) is type(None):
+            _index = {} 
+        #print("A",_index)
+        #now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
+        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
+        if key not in _index:
+            _index[key] = [0,""]
+        _index[key][0] += 1
+        _index[key][1] = now #val
+
+        mc.set(INDEX ,_index)
+    except Exception as e:
+        cprint(sys._getframe().f_code.co_name,opcode,color="red")
+        cprint(" memcach exception",e,color="red")
+
+
+def ArtPollRawStore(data,addr):
+    opcode=artnet_get_opcode(data)
+    cprint("   ",sys._getframe().f_code.co_name,opcode,color="green")
+    if "ArtPoll" in opcode or  "ArtPollReplay" in opcode:
+         #print("PKG3",addr, opcode,len(data))
+         try:
+               k = "{}:{}".format(addr[0],opcode[0])
+               x=mc.set(k, data)
+               if not x:
+                   cprint("    ArtPollRawStore memcache.not Connected mc.set",k,x,color="red")
+                   connect_memcache()
+               update_mc_artpoll_index(k,val="")
+         except Exception as e:
+               cprint("   ArtPollRawStore err:",e,color="red")
+
 def artnet_get_opcode(head):
     #print([head]) #[9:10])
     opcode=0x0000
@@ -288,6 +350,203 @@ def os_list_ip():
 #ips = os_list_ip() #example
 #get_mask(ips)
 
+def ArtAddress(ip="192.168.0.99" ,ShortName="ShortName", LongName="LongName",Port="",Universes=0,raw=0):
+    sock = UDP_Socket()
+    node_nr = 1
+
+    #send port
+    port = 7600
+    port = 6454
+
+    print( ip)
+    data = [] # [struct.pack('<B', 0)]*150
+    header = []
+    # Name, 7byte + 0x00
+    header.append(b"Art-Net\x00")
+    # OpCode ArtDMX -> 0x6000, Low Byte first
+    header.append(struct.pack('<H', 0x6000))
+    # Protocol Version 14, High Byte first
+    header.append(struct.pack('>H', 14))
+
+    data = header[:]
+    # NetSwitch
+    data.append(struct.pack('<B',128)) # no change 0x7f
+    data.append(struct.pack('<B', 0))     # filler
+
+    #Short Name
+    sname = ShortName[:17] 
+    sname = sname.ljust(18,"\x00")
+    data.append( sname )
+
+    lname = LongName[:63] 
+    lname = lname.ljust(64,"\x00") 
+    #lname = lname[:-2]+"X\x00"
+    data.append( lname )
+
+    print( "len sname:lname",len(sname),len(lname))
+
+    #SwIn 4; Port-Adress
+    # univers 0-f == \x80 - \x8f
+    i = 4
+    i=int(Universes)+1 #random.randint(0,99)
+    data.append(struct.pack('<B', 127+i))
+    data.append(struct.pack('<B', 127+i))
+    data.append(struct.pack('<B', 127+i))
+    data.append(struct.pack('<B', 127+i))
+
+
+    #SwOut 4; Port-Adress
+    data.append(struct.pack('<B', 127+i))
+    data.append(struct.pack('<B', 127+i))
+    data.append(struct.pack('<B', 127+i))
+    data.append(struct.pack('<B', 127+i))
+
+    #SubSwitch comination with Swin[] SwOut[]
+    data.append(struct.pack('<B', 0)) # SubSwitch Write 128
+    data.append(struct.pack('<B', 255))
+    data.append(struct.pack('<B', 0))
+    data.append(struct.pack('<B', 0))
+
+    #data.append("\xf4")
+
+    #print( ["ArtAdress SEND:",data,(ip,port)] )
+    data2 = b""
+    for d in data:
+        #print(d,type(d))
+        if type(d) is str:
+            data2+=bytes(d,"utf-8")
+        elif type(d) is bytes:
+            data2+=d
+        else:
+            data2+=bytes(str(d),"ascii")
+    print(data2)
+    if raw:
+        return data2,(ip,port)
+    sock.sendto(data2 ,(ip,port))
+
+def set_ip4(cur_ip=(2,0,0,91),new_ip=(2,0,0,201),new_netmask=(255,0,0,0)):
+    sock = UDP_Socket()
+    
+    #send ip
+    port = 7600
+    
+    #print(ip)
+    data = []
+    #New ip
+    #_ip = [192, 168,   2,  91]
+    _ip = [  2,   0,  0, 181] # CLASS C NET
+    _ip = [  2,   0,  0, 101] # CLASS C NET
+    #_ip = [192, 168,  0,  91]
+    _ip = new_ip
+    
+    print("NEW NODE _ip:", _ip)
+    data.append(struct.pack('<B', _ip[0]))
+    data.append(struct.pack('<B', _ip[1]))
+    data.append(struct.pack('<B', _ip[2]))
+    data.append(struct.pack('<B', _ip[3]))
+
+    #_ip = [255, 255, 255, 255] # cange all nodes in Network to the same _ip ! DANGER !
+    #_ip = [002, 000, 000, 255] # cange all nodes in subnet to the same _ip ! DANGER !
+    _ip = [  2,   0,   0, 199]  # CLASS A NET
+    _ip = [192, 168,   0,  91]
+    #_ip = [  2,   0,  0, 191] # CLASS C NET
+    _ip = cur_ip
+    
+    print("OLD NODE _ip:", _ip)
+    #OLD _ip , Target Node to change
+    data.append(struct.pack('<B', _ip[0]))
+    data.append(struct.pack('<B', _ip[1]))
+    data.append(struct.pack('<B', _ip[2]))
+    data.append(struct.pack('<B', _ip[3]))
+    
+    ip = ".".join(str(x) for x in _ip)
+    #print("send to ip:", ip)
+    
+        
+    # NETMASK
+    MASK = []
+    netmask = [255, 255, 255 ,  0] #fast CLASS C funktioniert
+    #netmask = [255, 0, 0 ,  0]  #CLASS C funkioniert nicht
+    netmask = new_netmask
+    print("NEW NODE net:",netmask)
+    MASK.append(struct.pack('<B', netmask[0]))
+    MASK.append(struct.pack('<B', netmask[1]))
+    MASK.append(struct.pack('<B', netmask[2]))
+    MASK.append(struct.pack('<B', netmask[3]))
+    
+    data += MASK
+    data += [struct.pack('<B', 255)]*11 
+    
+    
+    print("------------------------------")
+    data = b'CMD IP '+ b"".join(data)
+    
+    print("SENDING TO ",(ip,port))
+    print([data]) #,    cur_ip=(2,0,0,91))
+        
+    #sock.sendto(data ,(ip,port))
+    sock.sendto(data ,(ip,port))
+
+
+def send_cmd(ip=(2,0,0,91),cmd=""):
+    sock = UDP_Socket()
+    node_nr = 1
+    port = 7600
+    
+    print(ip)
+    data = []
+    
+    _ip = [  2,   0,  0, 91] # CLASS C NET
+    
+    
+    print("NEW NODE _ip:", _ip)
+    data.append(struct.pack('<B', _ip[0]))
+    data.append(struct.pack('<B', _ip[1]))
+    data.append(struct.pack('<B', _ip[2]))
+    data.append(struct.pack('<B', _ip[3]))
+
+    #_ip = [255, 255, 255, 255] # cange all nodes in Network to the same _ip ! DANGER !
+    #_ip = [002, 000, 000, 255] # cange all nodes in subnet to the same _ip ! DANGER !
+    _ip = [  2,   0,   0, 199]  # CLASS A NET
+    _ip = [  2,   0,   0, 91]  # CLASS A NET
+    #_ip = [192, 168,   0,  91]
+    _ip = [  2,   0,  0, 255] # CLASS C NET
+    #_ip = [  2,   255,  255, 255] # CLASS C NET
+    
+    print("OLD NODE _ip:", _ip)
+    #OLD _ip , Target Node to change
+    data.append(struct.pack('<B', _ip[0]))
+    data.append(struct.pack('<B', _ip[1]))
+    data.append(struct.pack('<B', _ip[2]))
+    data.append(struct.pack('<B', _ip[3]))
+    
+    ip = ".".join(str(x) for x in ip)
+    print("send to ip:", ip)
+    
+        
+    # NETMASK
+    MASK = []
+    netmask = [255, 255, 255 ,  0] #fast CLASS C funktioniert
+    netmask = [255, 0, 0 ,  0]  #CLASS C funkioniert nicht
+    print("NEW NODE net:",netmask)
+    MASK.append(struct.pack('<B', netmask[0]))
+    MASK.append(struct.pack('<B', netmask[1]))
+    MASK.append(struct.pack('<B', netmask[2]))
+    MASK.append(struct.pack('<B', netmask[3]))
+    
+    data += MASK
+    data += [struct.pack('<B', 255)]*11 
+    print("------------------------------")
+    data = 'CMD '+cmd+' '+ "".join(data)
+    
+    print("SENDING TO ",(ip,port))
+    print([data]    )
+        
+    #sock.sendto(data ,(ip,port))
+    sock.sendto(data ,(ip,port))
+
+
+
 def get_mask(IP):
 
     print(sys._getframe().f_code.co_name)
@@ -398,23 +657,26 @@ def ArtPollReply(sock=None):
     
     print("send" ,[content])
 
-def main():
+def ArtNet_Server(verbose=0):
     print("start main()")
     sock = UDP_Socket(bind=True,ip='',port=6454)
-    print("-- loop --")
+    print(" -- loop --")
     while sock:
         data, addr = sock.recvfrom(300)
+        cprint(" <- ArtNet_Server rcv:",[addr],color="cyan")
+        ArtPollRawStore(data,addr)
+
         opcode=""
         if len(data) >= 10:
             opcode=convert_to_hex("<h",data[8:10])
         if opcode != '0x2100': #OpPollReplay
             continue
-        print("-",addr,len(data),opcode)
-        print()
+        print(" <-",addr,len(data),opcode)
 
-        nodes = ArtNet_decode_pollreplay(data)
-        for k,v in nodes.items():
-            print("-",[k,v])
+        if verbose:
+            nodes = ArtNet_decode_pollreplay(data)
+            for k,v in nodes.items():
+                print("-",[k,v])
     print("end main()")
 
 def print_help():
@@ -446,7 +708,12 @@ if __name__ == "__main__":
         print( get_mask("192.168.2.2/25"))
         print( get_mask("192.168.2.2/8"))
     elif "--main" in sys.argv:
-        main()
+        def loop():
+            while 1:
+                ArtPoll()
+                time.sleep(5)
+        thread.start_new_thread(loop,())
+        ArtNet_Server(verbose=1)
     else:
         print_help()