ArtNetProcessor.py 38 KB

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