ArtNetProcessor.py 37 KB

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