ArtNetProcessor.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  1. #! /usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #from __future__ import absolute_import, division, print_function
  4. #from builtins import str, open, range, dict
  5. #from builtins import *
  6. """
  7. This file is part of librelight.
  8. librelight is free software: you can redistribute it and/or modify
  9. it under the terms of the GNU General Public License as published by
  10. the Free Software Foundation, version 2 of the License.
  11. librelight is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. GNU General Public License for more details.
  15. You should have received a copy of the GNU General Public License
  16. along with librelight. If not, see <http://www.gnu.org/licenses/>.
  17. (c) 2012 micha@uxsrv.de
  18. """
  19. import sys
  20. if sys.version_info.major <= 2:
  21. print("exit Python3 is needet")
  22. sys.exit()
  23. fn ="xx"
  24. sys.stdout.write("\x1b]2;"+str(fn)+"\x07") # terminal title
  25. if "__file__" in dir():
  26. fn = __file__
  27. if "/" in fn:
  28. fn = fn.split("/")[-1]
  29. sys.stdout.write("\x1b]2;"+str(fn)+" Beta 22.01"+"\x07") # terminal title
  30. else:
  31. sys.stdout.write("\x1b]2;"+str("__file__")+"\x07") # terminal title
  32. import string
  33. import time
  34. import os
  35. import json
  36. from optparse import OptionParser
  37. parser = OptionParser()
  38. parser.add_option("-r", "--recive", dest="recive",
  39. help="set recive ip like --recive 10.")
  40. parser.add_option("-s", "--sendto", dest="sendto",
  41. help="set sender ip like --sendto 2.255.255.255")
  42. parser.add_option("-t", "--test", dest="testuniv",
  43. help="set test univers like --test [0-16]")
  44. parser.add_option("", "--inmap", dest="inmap",
  45. help="set test univers like --test [0-16]")
  46. #parser.add_option("-q", "--quiet",
  47. # action="store_false", dest="verbose", default=True,
  48. # help="don't print status messages to stdout")
  49. (options, args) = parser.parse_args()
  50. print("option",options)
  51. print(options.sendto)
  52. cython = 0
  53. if cython:
  54. if " arm" in os.popen("uname -a").read():
  55. import cy.ArtNetProcessor_cy_pi as cy
  56. else:
  57. import cy.ArtNetProcessor_cy as cy
  58. #print(dir())
  59. #input()
  60. # ============================================================
  61. # memcach =========================================
  62. # ============================================================
  63. mc = None
  64. try:
  65. import memcache
  66. mc = memcache.Client(['127.0.0.1:11211'], debug=0)
  67. mc.set("dmx-1", [1]*512)
  68. except Exception as e:
  69. print("Exception",e)
  70. from collections import OrderedDict
  71. # ============================================================
  72. # Text Grafik Curses =========================================
  73. # ============================================================
  74. import curses
  75. class CursesDummy():
  76. def __init__(self):
  77. self.sel_host=Pager()
  78. self.sel_host.wrap=1
  79. self.sel_univ=Pager()
  80. self.sel_univ.wrap=1
  81. self.sel_mode=Pager()
  82. self.sel_mode.wrap=1
  83. pass
  84. def dir(self):
  85. pass
  86. def test(self):
  87. pass
  88. def init(self):
  89. pass
  90. def addstr(self,x,y,txt):
  91. pass
  92. def draw_lines(self,lines):
  93. pass
  94. def inp(self):
  95. return ""
  96. pass
  97. def read(self):
  98. pass
  99. def clear(self):
  100. pass
  101. def exit(self):
  102. pass
  103. class Window():
  104. def __init__(self):
  105. self.myscreen = curses.initscr()
  106. #print( dir(self.myscreen))
  107. #print( self.myscreen.getmaxyx() )
  108. self._inp=""
  109. self.cmd = []
  110. self.sel_host=Pager()
  111. self.sel_host.wrap=1
  112. self.sel_univ=Pager()
  113. self.sel_univ.wrap=1
  114. self.sel_mode=Pager()
  115. self.sel_mode.wrap=1
  116. self.mode="dmx"
  117. if options.sendto:
  118. self.sel_mode.data = ["stop","stop","ltp","dmx","mtx","main"] # mtx = matrix
  119. self.sel_mode.maxindex = len( self.sel_mode.data )-1
  120. self.mode="stop"
  121. #self.sel_mode.set(1) #stop
  122. #self.sel_mode.prev() #stop
  123. #self.sel_mode.prev() #stop
  124. #self.sel_mode.prev() #stop
  125. self.sel_mode.prev() #stop
  126. else:
  127. self.sel_mode.data = ["dmx","mtx","main"] # mtx = matrix
  128. self.sel_mode.maxindex = len( self.sel_mode.data )-1
  129. self.mode = self.sel_mode.get()
  130. self.ttime = time.time()
  131. self.univ2 = 0
  132. self.host =""
  133. self.ohost = HostBuffer() # as default
  134. self.ohost.update(host="Win-"+str(options.sendto),univ=0,dmxframe=[0]*512) # dummy input
  135. self.__reinit_time = time.time()
  136. def dir(self):
  137. return dir(self.myscreen)
  138. def test(self):
  139. self.init()
  140. #self.loop()
  141. self.draw_lines(["a","b","c"])
  142. try:
  143. time.sleep(10)
  144. finally:
  145. self.exit()
  146. def reinit(self):
  147. self.exit()
  148. print( "reinit",time.time())
  149. self.myscreen = curses.initscr()
  150. #time.sleep(5)
  151. #self.__init()
  152. self.init()
  153. self.__reinit_time = time.time()
  154. def init(self):
  155. curses.savetty()
  156. curses.noecho()
  157. curses.cbreak()
  158. curses.noqiflush() #?
  159. curses.noraw() #?
  160. self.clear()
  161. curses.beep()
  162. frame = 10
  163. i = 0
  164. def addstr(self,x,y,txt):
  165. self.myscreen.addstr(x, y, txt ) #zeile,spalte,text
  166. def draw_lines(self,lines):
  167. self.clear()
  168. try:
  169. x,y= self.myscreen.getmaxyx()
  170. for i,l in enumerate(lines):
  171. #print(i,l)
  172. if i >= x-2:
  173. break
  174. self.myscreen.addstr(i+1, 1, l ) #zeile,spalte,text
  175. if i >= self.myscreen.getmaxyx()[0]-2:
  176. self.myscreen.addstr(i+1, 1, "..." ) #zeile,spalte,text
  177. self.myscreen.refresh()
  178. self.myscreen.resize(x-1,y-1) # to prevent slowdown..
  179. self.myscreen.resize(x,y)
  180. if self.__reinit_time+60 < time.time():
  181. self.reinit()
  182. except KeyboardInterrupt as e:
  183. self.exit()
  184. print("KeyboardInterrupt")
  185. raise e
  186. #except Exception as e:
  187. # self.exit()
  188. # raise e
  189. def inp(self):
  190. x= self._inp
  191. self._inp=""
  192. return x
  193. def read(self):
  194. self.myscreen.nodelay(1)
  195. try:
  196. self._inp=self.myscreen.getkey()
  197. if not self._inp:
  198. self._inp = self.myscreen.getch()
  199. self.myscreen.addstr(0, 1, str(self._inp) ) #zeile,spalte,text
  200. self.myscreen.refresh()
  201. return self._inp
  202. except:
  203. pass#self._inp=""
  204. def clear(self):
  205. self.myscreen.clear()
  206. self.myscreen.border(0)
  207. curses.nocbreak();
  208. self.myscreen.keypad(0);
  209. #self.read()
  210. curses.echo()
  211. curses.resetty()
  212. #self.myscreen.addstr(10, 2, x ) #zeile,spalte,text
  213. def exit(self):
  214. self.clear()
  215. curses.endwin()
  216. print("ENDE",self)
  217. def keyread(self):
  218. #continue
  219. # input command buffer
  220. self.read()
  221. inp2=self.inp()
  222. x=""
  223. if "q" == inp2:
  224. inp2=""
  225. self.exit()
  226. sys.exit()
  227. elif "?" == inp2:
  228. self.mode = "?"
  229. elif "," == inp2:
  230. x=self.sel_mode.next()
  231. self.ttime = time.time()-2
  232. inp2=""
  233. elif ";" == inp2:
  234. x=self.sel_mode.prev()
  235. self.ttime = time.time()-2
  236. inp2=""
  237. elif "." == inp2:
  238. x=self.sel_univ.next()
  239. self.ttime = time.time()-2
  240. inp2=""
  241. elif ":" == inp2:
  242. x=self.sel_univ.prev()
  243. self.ttime = time.time()-2
  244. inp2=""
  245. elif "-" == inp2:
  246. x=self.sel_host.next()
  247. self.ttime = time.time()-2
  248. inp2=""
  249. elif "_" == inp2:
  250. x=self.sel_host.prev()
  251. self.ttime = time.time()-2
  252. inp2=""
  253. elif "#" == inp2:
  254. if "main" in self.sel_mode.data:
  255. x = self.sel_mode.data.index( "main")
  256. self.sel_mode.index = x
  257. self.sel_mode.check()
  258. self.ttime = time.time()-2
  259. inp2=""
  260. if x:
  261. self.myscreen.addstr(0, 6,str(x) )
  262. if inp2 == "\n":
  263. cmd2 = "".join( self.cmd).split()
  264. self.cmd=[]
  265. if len(cmd2) < 2:
  266. pass
  267. elif "C^" in cmd2:
  268. screen.exit()
  269. sys.exit()
  270. elif "univ" in cmd2 or "u" == cmd2[0]:
  271. x=""
  272. if cmd2[1] in sel_univ.data:
  273. x = sel_univ.data.index( cmd2[1])
  274. sel_univ.index = x
  275. sel_univ.check()
  276. elif "mode" in cmd2 or "m" == cmd2[0]:
  277. if cmd2[1] in self.sel_mode.data:
  278. x = self.sel_mode.data.index( cmd2[1])
  279. self.sel_mode.index = x
  280. self.sel_mode.check()
  281. elif "host" in cmd2 or "h" == cmd2[0]:
  282. try:
  283. x=int(cmd2[1])
  284. self.sel_host.set(x)
  285. except:
  286. pass
  287. else:
  288. self.cmd.append(inp2)
  289. def loop(self):
  290. self.keyread()
  291. #print( "LOOP")
  292. host = self.sel_host.get()
  293. univ2 = self.sel_univ.get()
  294. #if type(univ2) is list:
  295. # univ2.sort()
  296. self.mode = self.sel_mode.get()
  297. if self.mode == "stop":
  298. if self.ttime+5 < time.time():
  299. self.ttime = time.time()
  300. self.draw_lines( ["STOP",str(time.time())] )
  301. #self.exit()
  302. #print( ["STOP",str(time.time())] )
  303. return
  304. if time.time()-0.12 > self.ttime:
  305. #if 1:
  306. lines = [ ]
  307. #print("cmd:",cmd)
  308. lines.append(" host:"+ hostname +":"+netns+" CMD:" + "".join(self.cmd) )
  309. if self.mode=="help" or self.mode=="?":
  310. lines.append("HILFE[h]: " )
  311. lines.append("MODE [m]: inp, in2 in1 " )
  312. lines.append("UNIV [u]: 0-16 " )
  313. lines.append(" " )
  314. lines.append("HILFE " )
  315. elif self.mode=="dmx" or self.mode == "DMX":
  316. self.ttime = time.time()
  317. dmx=self.ohost.get(host,univ=univ2)#univ=head_uni)
  318. info=self.ohost.info()
  319. #lines.append("frame "+str(info.keys()) )
  320. if univ2 in info:
  321. if host in info[univ2] :
  322. lines.append("frame "+str(info[univ2][host]["frame"]))
  323. x=""
  324. for i,v in enumerate(dmx):
  325. if v == 0:
  326. v = "+"
  327. x += str(v).rjust(4," ")
  328. #if (i+1) % 21 == 0:# and i:
  329. if (i+1) % 20 == 0:# and i:
  330. lines.append(x)
  331. x=""
  332. if x:
  333. lines.append(x)
  334. lines.append(" ")
  335. lines.append(str(self.ttime))
  336. #screen.draw_lines(lines)
  337. elif self.mode=="stop":
  338. return 0
  339. elif self.mode=="mtx":
  340. self.ttime = time.time()
  341. dmx=self.ohost.get_mtx(host,univ=univ2)#univ=head_uni)
  342. info=self.ohost.info()
  343. #lines.append("frame "+str(info.keys()) )
  344. if univ2 in info:
  345. if host in info[univ2] :
  346. lines.append("frame "+str(info[univ2][host]["frame"]))
  347. x=""
  348. for i,v in enumerate(dmx):
  349. x += str(v).rjust(4," ")
  350. if (i+1) % 20 == 0:# and i:
  351. lines.append(x)
  352. x=""
  353. if x:
  354. lines.append(x)
  355. lines.append(" ")
  356. lines.append(str(self.ttime))
  357. #screen.draw_lines(lines)
  358. elif self.mode=="ltp" or self.mode=="LTP":
  359. self.ttime = time.time()
  360. dmx=self.ohost.get(univ=univ2)#head_uni)
  361. #univ2=""
  362. host=""
  363. info=self.ohost.info()
  364. lines.append("frame "+str(info.keys()) )
  365. x=""
  366. for i,v in enumerate(dmx):
  367. x += str(v).rjust(4," ")
  368. if (i+1) % 20 == 0:
  369. lines.append(x)
  370. x=""
  371. if x:
  372. lines.append(x)
  373. lines.append(" ")
  374. lines.append(str(self.ttime))
  375. #screen.draw_lines(lines)
  376. else:
  377. self.ttime = time.time()
  378. x=self.ohost.get(univ=univ2)
  379. #lines = []
  380. host=""
  381. univ2=""
  382. info=self.ohost.info()
  383. jinfo = ""
  384. for i in info:
  385. xl = json.dumps(i) + "=======X " # live
  386. lines.append( xl )
  387. for j in info[i]:
  388. lines2=[]
  389. lines.append( " " + json.dumps([j,""]) )
  390. for k in info[i][j]:
  391. if k in ["fpsx","uni","flag"]:
  392. lines2.append( " "+str(k).ljust(5," ")+": " + json.dumps( info[i][j][k]) )
  393. else:
  394. lines.append( " "+str(k).ljust(5," ")+": " + json.dumps( info[i][j][k]) )
  395. lines2 = "".join(lines2)
  396. lines.append(lines2)
  397. lines.append( " " + json.dumps([j,""]) )
  398. lines.append(" ")
  399. lines.append(str(self.ttime))
  400. #screen.draw_lines(lines)
  401. tmp = ""
  402. tmp += " mode:"+(str(self.mode).ljust(10," "))
  403. tmp += " univ:"+str(self.sel_univ.index)+":"+(str(self.sel_univ.get()).ljust(8," "))
  404. tmp += " host:"+str(self.sel_host.index)+":"+(str(self.sel_host.get()).ljust(8," "))
  405. tmp += " --recive:"+str(options.recive)
  406. tmp += " --sendto:"+str(options.sendto)
  407. lines.insert(0,tmp)
  408. tmp = ""
  409. sel_univ_data = self.sel_univ.data
  410. #sel_univ_data.sort()
  411. tmp += " univ:"+ (str(self.sel_univ.data))#.ljust(20," "))
  412. tmp += " list:"+ (str(self.sel_host.data))#.ljust(20," "))
  413. lines.insert(0,tmp)
  414. self.draw_lines(lines)
  415. class UniversBuffer():
  416. def __init__(self,univers_nr=0):
  417. """buffer and merge a universe from multiple sender/hosts/ip's
  418. """
  419. self.__hosts = []
  420. self.__universes_dmx = {}
  421. self.__universes_fps = {}
  422. self.__universes_frames = {}
  423. self.__universes_flag = {}
  424. self.__universes_x_frames = {}
  425. self.__universes_x_time = {}
  426. self.__universes_count = {}
  427. self.__universes_timer = {}
  428. self.__universes_matrix = ["."]*512
  429. self.__universes_info = {}
  430. self.__univers_nr = univers_nr
  431. self.__frame = 0
  432. def _add(self,host):
  433. if host not in self.__hosts:
  434. self.__hosts.append(host) #re-order hosts list for LTP
  435. #print( "ADDING HOST:",host,"UNIV:",self.__univers_nr)
  436. self.__universes_dmx[host] = [0]*512
  437. self.__universes_frames[host] = 0
  438. self.__universes_x_frames[host] = 0
  439. self.__universes_fps[host] = [""]*20
  440. self.__universes_flag[host] = [0]*20
  441. self.__universes_x_time[host] = time.time()
  442. self.__universes_timer[host] = [0]*512
  443. self.__universes_info[host] = {}
  444. def _next_frame(self,host):
  445. self.__frame += 1
  446. self.__universes_frames[host] += 1
  447. self.__universes_x_frames[host] += 1
  448. if self.__universes_x_time[host]+10 < time.time():
  449. sec = time.time()-self.__universes_x_time[host]
  450. fps = self.__universes_x_frames[host] /sec
  451. #fps = round(fps,1)
  452. fps = int(fps)
  453. self.__universes_fps[host].pop(0)
  454. self.__universes_fps[host].append(fps)
  455. self.__universes_x_time[host] = time.time()
  456. self.__universes_x_frames[host] = 0
  457. def update(self,host,dmxframe):
  458. if type(dmxframe) != list:
  459. #print( "update ERROR dmxframe is not a list", host )
  460. return
  461. self._add(host)
  462. update_matrix = [0]*512
  463. dmx=[0]*512
  464. update_flag = 0
  465. dmxframe_old = self.__universes_dmx[host]
  466. self._next_frame(host)
  467. #if len(dmxframe) <= 512: #len(dmxframe_old):
  468. if cython:# "cython":
  469. if len(dmxframe) <= 512: #len(dmxframe_old):
  470. dmxnew = dmxframe
  471. dmxold = dmxframe_old
  472. matrix = self.__universes_matrix
  473. hostid = self.__hosts.index(host)
  474. x= cy.merge(dmxold,dmxnew,matrix,hostid)
  475. dmx = list(x[0])
  476. self.__universes_matrix = list(x[1])
  477. update_flag = x[2]
  478. else:
  479. if len(dmxframe) <= 512: #len(dmxframe_old):
  480. for i,v in enumerate(dmxframe):
  481. if dmxframe[i] != dmxframe_old[i]:
  482. update_flag += 1
  483. self.__universes_matrix[i] = self.__hosts.index(host)
  484. dmx[i] = v
  485. self.__universes_flag[host].pop(0)
  486. self.__universes_flag[host].append( update_flag )
  487. tmp = {}
  488. tmp["flag"] =update_flag
  489. tmp["flagx"] = self.__universes_flag[host]
  490. tmp["fpsx"] = int(self.__universes_x_frames[host] / (time.time()-self.__universes_x_time[host]))
  491. tmp["frame"] = self.__frame
  492. #tmp["hosts"] = self.__hosts
  493. tmp["uni"] = self.__univers_nr
  494. tmp["fps"] = self.__universes_fps[host]
  495. self.__universes_info[host] = tmp
  496. if update_flag:
  497. #print( "UPDATE HOST:",host, update_flag,"UNIV:",self.__univers_nr)
  498. self.__universes_dmx[host] = dmx # dmxframe
  499. self.__universes_timer[host] = update_matrix
  500. def get(self,host=""):
  501. if host and host in self.__hosts:
  502. return self.__universes_dmx[host]
  503. dmx = [":"]*512
  504. for i,v in enumerate(self.__universes_matrix):
  505. if type(v) is int:
  506. host = self.__hosts[v]
  507. v = self.__universes_dmx[host][i]
  508. dmx[i] = v
  509. return dmx
  510. def get_mtx(self,host=""):
  511. return self.__universes_matrix
  512. def info(self):
  513. return self.__universes_info
  514. def hosts(self):
  515. x = self.__universes_dmx.keys()
  516. x=list(x)
  517. x.sort()
  518. return x
  519. class HostBuffer():
  520. def __init__(self):
  521. """buffer hosts and route data into universes
  522. """
  523. self.__hosts = [] # LTP order
  524. self.__universes = OrderedDict() # {} # 192.168.0.1 = [0]*512
  525. #self.update(host="localhost",univ=0,dmxframe=[6]*512)
  526. dmxframe = [0]*512
  527. dmxframe[15] = -6
  528. #self.update(host="333.333.333.333",univ=8,dmxframe=dmxframe)
  529. def get_mtx(self,host="", univ=""):
  530. return self.__universes[str(univ)].get_mtx(host)
  531. def get(self,host="", univ=""):
  532. if str(univ) in self.__universes:
  533. return self.__universes[str(univ)].get(host)
  534. else:
  535. return [-8]*512
  536. def hosts(self):
  537. hosts = []
  538. for univ in self.__universes:
  539. x=self.__universes[univ].hosts()
  540. for y in x:
  541. #x=univ.hosts()
  542. if y not in hosts:
  543. hosts.append(y)
  544. hosts.sort()
  545. return hosts
  546. def univs(self):
  547. x=self.__universes.keys()
  548. x=list(x)
  549. #x.sort()
  550. return x
  551. def update(self,host,univ, dmxframe):
  552. #print( "update", host )
  553. if str(univ) not in self.__universes:
  554. self.__universes[str(univ)] = UniversBuffer(str(univ))
  555. self.__universes[str(univ)].update(host,dmxframe)
  556. def info(self,univ=0):
  557. out = {}
  558. #print self.__universes.keys()
  559. for univ in self.__universes.keys():
  560. #print("INFO:",univ)
  561. x=self.__universes[univ]
  562. out[univ] = x.info()
  563. return out
  564. # ============================================================
  565. # Network ====================================================
  566. # ============================================================
  567. import socket, struct
  568. hostname = socket.gethostname()
  569. netns = "none"
  570. x = os.popen("ip netns identify $$")
  571. xx = x.read()
  572. if xx:
  573. netns = xx.strip()
  574. import fcntl #socket control
  575. import errno
  576. def toPrintable(nonprintable):
  577. out = ""
  578. for i in str(nonprintable):
  579. printable = string.ascii_letters + string.digits +"/()=?{[]}\;:,.-_ "
  580. if str(i) in printable :
  581. out += str(i)
  582. return out
  583. def unpack_art_dmx(data):
  584. dmx = []
  585. for i in range(len(data[18:]) ):
  586. x=data[18+i]
  587. #print("x",x)
  588. #print( "data",b'!B', data[18+i])
  589. #x=struct.unpack( b'!B',data[18+i])
  590. #print( "data",b'!B', data[18+i],x)
  591. #x=x[0]
  592. dmx += [x]
  593. return dmx
  594. class Socket():
  595. def __init__(self,bind='',port=6454):
  596. self.__port =port
  597. self.__bind =bind
  598. self.__poll = 0
  599. self.__data = []
  600. self.__addr = "NONE"
  601. #self.__hosts = {"host":{"9":[0]*512}}
  602. self.__hosts = {}
  603. self.hosts = self.__hosts
  604. self.open()
  605. self._poll_clean_time = time.time()
  606. self._poll_clean_count = 0
  607. def open(self):
  608. try:
  609. print("connecting to ArtNet bind:",self.__bind,"Port",self.__port)
  610. self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  611. self.sock.bind((self.__bind, self.__port))
  612. fcntl.fcntl(self.sock, fcntl.F_SETFL, os.O_NONBLOCK)
  613. #self.sock.setblocking(0)
  614. except socket.error as e:
  615. print("Socket ",self.__bind,self.__port, "ERR: {0} ".format(e.args))
  616. #raw_input()
  617. #sys.exit()
  618. def poll_clean(self):
  619. if self._poll_clean_time+(1/25.) <= time.time():
  620. self._poll_clean_time = time.time()
  621. self._poll_clean()
  622. x = self._poll_clean_count
  623. self._poll_clean_count = 0
  624. return x
  625. def _poll_clean(self):
  626. while 1:
  627. try:
  628. self.__data, self.__addr = self.sock.recvfrom(self.__port)
  629. self._poll_clean_count += 1
  630. #return 1
  631. except socket.timeout as e:
  632. err = e.args[0]
  633. if err == 'timed out':
  634. time.sleep(1)
  635. print('recv timed out, retry later')
  636. else:
  637. print(e)
  638. break
  639. except socket.error as e:
  640. break
  641. def poll(self):
  642. if not self.__poll:
  643. try:
  644. self.__data, self.__addr = self.sock.recvfrom(self.__port)
  645. data, addr = (self.__data,self.__addr)
  646. self.host = addr[0]
  647. head = data[:18]
  648. rawdmx = data[18:]
  649. #print([head],addr)
  650. self.univ = -1
  651. try:
  652. self.head = struct.unpack("!8sHBBBBHBB" , head )
  653. except Exception as e:
  654. pass#print( "======E09823" , e)
  655. univ = self.head[6]/255 # /512 # * 512
  656. self.univ = int(univ)
  657. if self.host.startswith("127."): #allways recive localhost on port
  658. self.__poll = 1
  659. return 1
  660. elif not options.recive:
  661. self.__poll = 1
  662. return 1
  663. elif self.host.startswith(options.recive):
  664. self.__poll = 1
  665. return 1
  666. else:
  667. self.__poll = 0
  668. addr = str(addr)
  669. univ = str(univ)
  670. if self.__poll:
  671. if addr not in self.__hosts:
  672. self.__hosts[addr] = {}
  673. if univ not in self.__hosts[addr]:
  674. self.__hosts[addr][univ] = {}
  675. self.__hosts[addr][univ] = {"head":head,"addr":addr,"univ":univ,"dmx":rawdmx}
  676. self.hosts = self.__hosts
  677. except socket.timeout as e:
  678. err = e.args[0]
  679. if err == 'timed out':
  680. time.sleep(1)
  681. print('recv timed out, retry later')
  682. else:
  683. print(e)
  684. except socket.error as e:
  685. pass
  686. def recive(self):
  687. if self.__poll:
  688. self.__poll = 0
  689. data, addr = (self.__data,self.__addr)
  690. #print( self.univ,self.head)
  691. self.dmx = unpack_art_dmx(data)
  692. return { "host":self.host,"dmx":self.dmx,"univ":self.univ,"head":self.head,"data":data,"addr":addr}
  693. # ============================================================
  694. # miniartnet4.py =============================================
  695. # ============================================================
  696. import time
  697. import socket
  698. import struct
  699. import random
  700. class ArtNetNode():
  701. """simple Object to generate raw ArtNet like Network packages
  702. works in Python2 and Python3 2021-12-05
  703. (only basic implementation)
  704. "Art-Net™ Designed by and Copyright Artistic Licence Holdings Ltd"
  705. https://art-net.org.uk/
  706. """
  707. def __init__(self, to="10.10.10.255",univ=7,port=6454):
  708. try:
  709. univ = int(univ)
  710. except:
  711. print("errror univ",univ ,"is not int ... set to 7")
  712. univ = 7
  713. self.univ=univ
  714. self.sendto = to
  715. self.portto = port
  716. self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  717. self.s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  718. self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  719. self.stamp = time.time()
  720. self.test_stamp = time.time()
  721. self.dmx=[33]*512
  722. self.v=0
  723. self.d=1
  724. def head(self):
  725. self._header = []
  726. self._header.append(b"Art-Net\x00") # Name, 7byte + 0x00
  727. self._header.append(struct.pack('<H', 0x5000)) # OpCode ArtDMX -> 0x5000, Low Byte first
  728. self._header.append(struct.pack('>H', 14)) # Protocol Version 14, High Byte first
  729. self._header.append(b"\x00") # Order -> nope -> 0x00
  730. self._header.append(struct.pack('B',1)) # Eternity Port
  731. # Address
  732. #if 0 <= universe <= 15 and 0 <= net <= 127 and 0 <= subnet <= 15
  733. net, subnet, universe = (0,0,self.univ) #address
  734. self._header.append(struct.pack('<H', net << 8 | subnet << 4 | universe))
  735. self._header = b"".join(self._header)
  736. def send(self,dmx=None,port=''):
  737. if dmx is None:
  738. dmx = self.dmx
  739. else:
  740. self.dmx = dmx
  741. self.head()
  742. c=[self._header]
  743. c.append( struct.pack('>H', len(dmx) ) )
  744. #print([c])
  745. dmx_count = 0
  746. for v in dmx:
  747. if type(v) is not int:
  748. v=0
  749. elif v > 255: # max dmx value 255
  750. v = 255
  751. elif v < 0: # min dmx value 0
  752. v = 0
  753. dmx_count += 1
  754. c.append(struct.pack("B",v))
  755. c = b"".join(c)
  756. if port:
  757. self.s.sendto(c, (self.sendto, port)) # default 6454
  758. else:
  759. self.s.sendto(c, (self.sendto, self.portto)) # default 6454
  760. return c
  761. def _test_frame(self):
  762. if self.test_stamp+0.1 > time.time():
  763. return 0
  764. self.test_stamp = time.time()
  765. dmx = [0]*512
  766. dmx[420] = self.v
  767. self.dmx = dmx
  768. self.next()
  769. #self.send(dmx)
  770. #print( [x] )
  771. if self.v >= 255:
  772. self.d=0
  773. elif self.v <=0:
  774. self.d=1
  775. if self.d:
  776. self.v+=1
  777. else:
  778. self.v-=1
  779. #time.sleep(1/30.)
  780. def next(self):
  781. if self.stamp + (1/60) <= time.time():
  782. self.send()
  783. def artnet_test():
  784. artnet = ArtNetNode()
  785. artnet._tes_frame()
  786. # ============================================================
  787. # helper =====================================================
  788. # ============================================================
  789. class Pager(): #scroll thru list
  790. def __init__(self):
  791. self.data = []
  792. self.index = 0
  793. self.wrap = 0
  794. self.maxindex = 0
  795. def append(self,val):
  796. self.data.append(val)
  797. self.check()
  798. def set(self,nr):
  799. self.index = nr
  800. self.check()
  801. def get(self):
  802. self.check()
  803. self.data.sort()
  804. if self.data:
  805. return self.data[self.index]
  806. def next(self):
  807. self.index += 1
  808. self.check(flag=1)
  809. return self.get()
  810. def prev(self):
  811. self.index -= 1
  812. self.check(flag=1)
  813. return self.get()
  814. def check(self,flag=0):
  815. if flag:
  816. if self.maxindex and self.maxindex <= len(self.data):
  817. _max = self.maxindex
  818. else:
  819. _max = len(self.data)
  820. else:
  821. _max = len(self.data)
  822. #_max = self.maxindex
  823. self.maxindex = _max
  824. if self.wrap:
  825. if self.index >= _max:
  826. self.index = 0
  827. elif self.index < 0:
  828. self.index = _max-1
  829. else:
  830. if self.index >= _max:
  831. self.index = _max-1
  832. elif self.index < 0:
  833. self.index = 0
  834. class Timer():
  835. def __init__(self,sec=1,start=None):
  836. if start is None:
  837. self.last = time.time()
  838. else:
  839. self.last = start
  840. self.sec = sec
  841. print( self,"init")
  842. def reset(self):
  843. self.last = time.time()
  844. def check(self):
  845. if self.last+self.sec < time.time():
  846. #print(self,"chk",time.time()+self.sec-time.time())
  847. self.reset()
  848. return 1
  849. # ============================================================
  850. # main =======================================================
  851. # ============================================================
  852. class Main():
  853. def __init__(self):
  854. pass
  855. def loop(self):
  856. ohost = HostBuffer()
  857. screen=Window()
  858. screen.exit()
  859. screen.ohost = ohost
  860. #artnet_out = ArtNetNode(to="10.0.25.255")
  861. artnet_out = ArtNetNode(to=options.sendto)
  862. ohost.update(host="Main-"+str(options.sendto),univ=0,dmxframe=[0]*512) # dummy input
  863. #artnet_out._test_frame()
  864. if options.testuniv:
  865. artnet = ArtNetNode(univ=options.testuniv)
  866. artnet._test_frame()
  867. #ysocket = Socket(bind='127.0.0.1' ,port=6555)
  868. xsocket = Socket()
  869. xt = time.time()
  870. ohost_buf = {}
  871. ohost_timer = Timer(1/30.,start=0) # 0.03333
  872. send_timer = Timer(1/30.) # 0.03333
  873. try:
  874. screen.exit()
  875. while 1:
  876. poll_flag = 0
  877. if options.testuniv:
  878. artnet._test_frame()
  879. #artnet_out._test_frame()
  880. #if xsocket.poll():
  881. while xsocket.poll():
  882. xt = time.time()
  883. poll_flag = 1
  884. x = xsocket.recive()
  885. if x["host"] == options.recive:
  886. try:
  887. x["univ"] = int(options.inmap )
  888. except TypeError:
  889. pass
  890. if x["host"] not in ohost_buf:
  891. ohost_buf[x["host"]] = {}
  892. if x["univ"] not in ohost_buf[x["host"]]:
  893. ohost_buf[x["host"]][x["univ"]] = {}
  894. ohost_buf[x["host"]][x["univ"]] = x["dmx"] #write into buffer to prevent package latency encreasing
  895. #ohost.update(x["host"],x["univ"],x["dmx"])
  896. if 0:#ysocket.poll():
  897. poll_flag = 1
  898. x = ysocket.recive()
  899. if x["host"] == options.recive:
  900. try:
  901. x["univ"] = int(options.inmap )
  902. except TypeError:
  903. pass
  904. ohost.update(host=x["host"],univ=x["univ"],dmxframe=x["dmx"])
  905. screen.sel_univ.data = ohost.univs()
  906. screen.sel_host.data = ohost.hosts()
  907. #if x:
  908. # #screen.exit()
  909. # print( "poll_clean",x)
  910. if ohost_timer.check():
  911. for i in ohost_buf:
  912. for j in ohost_buf[i]:
  913. dmx=ohost_buf[i][j]
  914. ohost.update(host=i,univ=j,dmxframe=dmx) # update univ_data from input buffer
  915. ohost_buf = {} # clear package buffer
  916. if send_timer.check() and options.sendto:
  917. #x= xsocket.poll_clean()
  918. #x=ohost.get(univ=univ2)
  919. info=ohost.info()
  920. #print( info)
  921. jinfo = ""
  922. for i in info:
  923. univ = i
  924. #print( [ univ])
  925. if str(univ) == "54":
  926. break
  927. xl = json.dumps(univ) + "======= " #XX
  928. ltp=ohost.get(univ=i)
  929. #print( xl )
  930. #print( len(ltp) ,ltp[:20])
  931. #print( "univ", univ )
  932. try:
  933. mc.set("dmx-{}".format(univ), ltp)
  934. except Exception as e:
  935. pass#
  936. #print("Exception",e)
  937. ltp[511] = int(univ)
  938. artnet_out.univ=int(univ)
  939. artnet_out.send(ltp)
  940. #for j in info[i]:
  941. # print( str(univ)+" " + json.dumps([j,""]) )
  942. # for k in info[i][j]:
  943. # print( str(univ)+ " "+str(k).ljust(5," ")+": " + json.dumps( info[i][j][k]) )
  944. if not poll_flag:
  945. time.sleep(.001)
  946. screen.loop()
  947. finally:
  948. pass
  949. #screen.exit()
  950. #print(dir(curses))
  951. if __name__ == "__main__":
  952. print("main")
  953. main = Main()
  954. print("loop")
  955. main.loop()