ArtNetProcessor.py 36 KB

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