ArtNetProcessor.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  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. # pylint: disable=redefined-outer-name,invalid-name,trailing-whitespace,missing-function-docstring
  7. """
  8. This file is part of librelight.
  9. librelight is free software: you can redistribute it and/or modify
  10. it under the terms of the GNU General Public License as published by
  11. the Free Software Foundation, version 2 of the License.
  12. librelight is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. GNU General Public License for more details.
  16. You should have received a copy of the GNU General Public License
  17. along with librelight. If not, see <http://www.gnu.org/licenses/>.
  18. (c) 2012 micha@uxsrv.de
  19. """
  20. import sys
  21. if sys.version_info.major <= 2:
  22. print("exit Python3 is needet")
  23. sys.exit()
  24. fn ="xx"
  25. sys.stdout.write("\x1b]2;"+str(fn)+"\x07") # terminal title
  26. if "__file__" in dir():
  27. fn = __file__
  28. if "/" in fn:
  29. fn = fn.split("/")[-1]
  30. sys.stdout.write("\x1b]2;"+str(fn)+" Beta 22.01"+"\x07") # terminal title
  31. else:
  32. sys.stdout.write("\x1b]2;"+str("__file__")+"\x07") # terminal title
  33. import json
  34. import os
  35. import string
  36. import time
  37. from optparse import OptionParser
  38. parser = OptionParser()
  39. parser.add_option("-r", "--recive", dest="recive",
  40. help="set recive ip like --recive 10.")
  41. parser.add_option("-s", "--sendto", dest="sendto",
  42. help="set sender ip like --sendto 2.255.255.255")
  43. parser.add_option("-t", "--test", dest="testuniv",
  44. help="set test univers like --test [0-16]")
  45. parser.add_option("", "--inmap", dest="inmap",
  46. help="set test univers like --test [0-16]")
  47. #parser.add_option("-q", "--quiet",
  48. # action="store_false", dest="verbose", default=True,
  49. # help="don't print status messages to stdout")
  50. (options, args) = parser.parse_args()
  51. print("option",options)
  52. print(options.sendto)
  53. cython = 0
  54. if cython:
  55. if " arm" in os.popen("uname -a").read():
  56. import cy.ArtNetProcessor_cy_pi as cy
  57. else:
  58. import cy.ArtNetProcessor_cy as cy
  59. from collections import OrderedDict
  60. from datetime import datetime
  61. #print(dir())
  62. #input()
  63. # ============================================================
  64. # memcach =========================================
  65. # ============================================================
  66. mc = None
  67. try:
  68. import memcache
  69. mc = memcache.Client(['127.0.0.1:11211'], debug=0)
  70. mc.set("dmx-1", [1]*512)
  71. except Exception as e:
  72. print("Exception",e)
  73. def memcachd_index_clear():
  74. _index = {}
  75. try:
  76. mc.set("index",_index)
  77. except Exception as e:
  78. print("memcach exception",e)
  79. memcachd_index_clear()
  80. def update_memcachd_index(key,active=-1): # val=""
  81. try:
  82. _index = mc.get("index")
  83. #print("A",_index)
  84. if type(_index) is type(None):
  85. _index = {}
  86. #print("A",_index)
  87. if key not in _index:
  88. _index[key] = [0,-33]
  89. _index[key][0] += 1
  90. _index[key][1] = active
  91. mc.set("index",_index)
  92. except Exception as e:
  93. print("memcach exception",e)
  94. if mc:
  95. INDEX="index-artpoll"
  96. mc.set(INDEX ,{})
  97. def update_mc_artpoll_index(key): #,val=""):
  98. try:
  99. INDEX="index-artpoll"
  100. _index = mc.get(INDEX)
  101. #print("A",_index)
  102. if type(_index) is type(None):
  103. _index = {}
  104. #print("A",_index)
  105. #now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
  106. now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  107. if key not in _index:
  108. _index[key] = [0,""]
  109. _index[key][0] += 1
  110. _index[key][1] = now #val
  111. mc.set(INDEX ,_index)
  112. except Exception as e:
  113. print("memcach exception",e)
  114. def count_active_dmx_ch(dmx):
  115. active = 0
  116. for _,v in enumerate(dmx):
  117. if type(v) is int and v>=1:
  118. #if active < 0:
  119. # active = 0
  120. active = max(active,0)
  121. active += 1
  122. return active
  123. # ============================================================
  124. # Text Grafik Curses =========================================
  125. # ============================================================
  126. import curses
  127. class CursesDummy():
  128. def __init__(self):
  129. self.sel_host=Pager()
  130. self.sel_host.wrap=1
  131. self.sel_univ=Pager()
  132. self.sel_univ.wrap=1
  133. self.sel_mode=Pager()
  134. self.sel_mode.wrap=1
  135. def dir(self):
  136. pass
  137. def test(self):
  138. pass
  139. def init(self):
  140. pass
  141. def addstr(self,x,y,txt):
  142. pass
  143. def draw_lines(self,lines):
  144. pass
  145. def inp(self):
  146. return ""
  147. def loop(self,**args):
  148. pass
  149. def read(self):
  150. pass
  151. def clear(self):
  152. pass
  153. def exit(self):
  154. pass
  155. class Window():
  156. def __init__(self):
  157. self.myscreen = curses.initscr()
  158. #print( dir(self.myscreen))
  159. #print( self.myscreen.getmaxyx() )
  160. self._inp=""
  161. self.cmd = []
  162. self.sel_host=Pager()
  163. self.sel_host.wrap=1
  164. self.sel_univ=Pager()
  165. self.sel_univ.wrap=1
  166. self.sel_mode=Pager()
  167. self.sel_mode.wrap=1
  168. self.mode="dmx"
  169. if options.sendto:
  170. self.sel_mode.data = ["stop","stop","ltp","dmx","mtx","main"] # mtx = matrix
  171. self.sel_mode.maxindex = len( self.sel_mode.data )-1
  172. self.mode="stop"
  173. #self.sel_mode.set(1) #stop
  174. #self.sel_mode.prev() #stop
  175. #self.sel_mode.prev() #stop
  176. #self.sel_mode.prev() #stop
  177. self.sel_mode.prev() #stop
  178. else:
  179. self.sel_mode.data = ["dmx","mtx","main"] # mtx = matrix
  180. self.sel_mode.maxindex = len( self.sel_mode.data )-1
  181. self.mode = self.sel_mode.get()
  182. self.ttime = time.time()
  183. self.univ2 = 0
  184. self.host =""
  185. self.ohost = HostBuffer() # as default
  186. self.ohost.update(host="Win-"+str(options.sendto),univ=0,dmxframe=[0]*512) # dummy input
  187. self.__reinit_time = time.time()
  188. def dir(self):
  189. return dir(self.myscreen)
  190. def test(self):
  191. self.init()
  192. #self.loop()
  193. self.draw_lines(["a","b","c"])
  194. try:
  195. time.sleep(10)
  196. finally:
  197. self.exit()
  198. def reinit(self):
  199. self.exit()
  200. print( "reinit",time.time())
  201. self.myscreen = curses.initscr()
  202. #time.sleep(5)
  203. #self.__init()
  204. self.init()
  205. self.__reinit_time = time.time()
  206. def init(self):
  207. curses.savetty()
  208. curses.noecho()
  209. curses.cbreak()
  210. curses.noqiflush() #?
  211. curses.noraw() #?
  212. self.clear()
  213. curses.beep()
  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 Exception as _:
  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 Exception as _:
  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 in ["help","?"]:
  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 in ["dmx","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 in ["ltp","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. for i in info:
  434. xl = json.dumps(i) + "=======X " # live
  435. lines.append( xl )
  436. for j in info[i]:
  437. lines2=[]
  438. lines.append( " " + json.dumps([j,""]) )
  439. for k in info[i][j]:
  440. if k in ["fpsx","uni","flag"]:
  441. lines2.append( " "+str(k).ljust(5," ")+": " + json.dumps( info[i][j][k]) )
  442. else:
  443. lines.append( " "+str(k).ljust(5," ")+": " + json.dumps( info[i][j][k]) )
  444. lines2 = "".join(lines2)
  445. lines.append(lines2)
  446. lines.append( " " + json.dumps([j,""]) )
  447. lines.append(" ")
  448. lines.append(str(self.ttime))
  449. #screen.draw_lines(lines)
  450. tmp = ""
  451. tmp += " mode:"+(str(self.mode).ljust(10," "))
  452. tmp += " univ:"+str(self.sel_univ.index)+":"+(str(self.sel_univ.get()).ljust(8," "))
  453. tmp += " host:"+str(self.sel_host.index)+":"+(str(self.sel_host.get()).ljust(8," "))
  454. tmp += " --recive:"+str(options.recive)
  455. tmp += " --sendto:"+str(options.sendto)
  456. lines.insert(0,tmp)
  457. tmp = ""
  458. #sel_univ_data = self.sel_univ.data
  459. #sel_univ_data.sort()
  460. tmp += " univ:"+ (str(self.sel_univ.data))#.ljust(20," "))
  461. tmp += " list:"+ (str(self.sel_host.data))#.ljust(20," "))
  462. lines.insert(0,tmp)
  463. self.draw_lines(lines)
  464. class UniversBuffer():
  465. def __init__(self,univers_nr=0):
  466. """buffer and merge a universe from multiple sender/hosts/ip's
  467. """
  468. self.__hosts = []
  469. self.__universes_dmx = {}
  470. self.__universes_fps = {}
  471. self.__universes_frames = {}
  472. self.__universes_flag = {}
  473. self.__universes_x_frames = {}
  474. self.__universes_x_time = {}
  475. #self.__universes_count = {}
  476. self.__universes_timer = {}
  477. self.__universes_matrix = ["."]*512
  478. self.__universes_info = {}
  479. self.__univers_nr = univers_nr
  480. self.__frame = 0
  481. def _add(self,host):
  482. if host not in self.__hosts:
  483. self.__hosts.append(host) #re-order hosts list for LTP
  484. #print( "ADDING HOST:",host,"UNIV:",self.__univers_nr)
  485. self.__universes_dmx[host] = [0]*512
  486. self.__universes_frames[host] = 0
  487. self.__universes_x_frames[host] = 0
  488. self.__universes_fps[host] = [""]*20
  489. self.__universes_flag[host] = [0]*20
  490. self.__universes_x_time[host] = time.time()
  491. self.__universes_timer[host] = [0]*512
  492. self.__universes_info[host] = {}
  493. def _next_frame(self,host):
  494. self.__frame += 1
  495. self.__universes_frames[host] += 1
  496. self.__universes_x_frames[host] += 1
  497. if self.__universes_x_time[host]+10 < time.time():
  498. sec = time.time()-self.__universes_x_time[host]
  499. fps = self.__universes_x_frames[host] /sec
  500. #fps = round(fps,1)
  501. fps = int(fps)
  502. self.__universes_fps[host].pop(0)
  503. self.__universes_fps[host].append(fps)
  504. self.__universes_x_time[host] = time.time()
  505. self.__universes_x_frames[host] = 0
  506. def update(self,host,dmxframe):
  507. if type(dmxframe) != list:
  508. #print( "update ERROR dmxframe is not a list", host )
  509. return
  510. self._add(host)
  511. update_matrix = [0]*512
  512. dmx=[0]*512
  513. update_flag = 0
  514. dmxframe_old = self.__universes_dmx[host]
  515. self._next_frame(host)
  516. #if len(dmxframe) <= 512: #len(dmxframe_old):
  517. if cython:# "cython":
  518. if len(dmxframe) <= 512: #len(dmxframe_old):
  519. dmxnew = dmxframe
  520. dmxold = dmxframe_old
  521. matrix = self.__universes_matrix
  522. hostid = self.__hosts.index(host)
  523. x= cy.merge(dmxold,dmxnew,matrix,hostid)
  524. dmx = list(x[0])
  525. self.__universes_matrix = list(x[1])
  526. update_flag = x[2]
  527. else:
  528. if len(dmxframe) <= 512: #len(dmxframe_old):
  529. for i,v in enumerate(dmxframe):
  530. if dmxframe[i] != dmxframe_old[i]:
  531. update_flag += 1
  532. self.__universes_matrix[i] = self.__hosts.index(host)
  533. dmx[i] = v
  534. self.__universes_flag[host].pop(0)
  535. self.__universes_flag[host].append( update_flag )
  536. tmp = {}
  537. tmp["flag"] =update_flag
  538. tmp["flagx"] = self.__universes_flag[host]
  539. tmp["fpsx"] = int(self.__universes_x_frames[host] / (time.time()-self.__universes_x_time[host]))
  540. tmp["frame"] = self.__frame
  541. #tmp["hosts"] = self.__hosts
  542. tmp["uni"] = self.__univers_nr
  543. tmp["fps"] = self.__universes_fps[host]
  544. tmp["active"] = count_active_dmx_ch(dmxframe)
  545. self.__universes_info[host] = tmp
  546. if update_flag:
  547. #print( "UPDATE HOST:",host, update_flag,"UNIV:",self.__univers_nr)
  548. self.__universes_dmx[host] = dmx # dmxframe
  549. self.__universes_timer[host] = update_matrix
  550. def get(self,host=""):
  551. if host and host in self.__hosts:
  552. return self.__universes_dmx[host]
  553. dmx = [":"]*512
  554. for i,v in enumerate(self.__universes_matrix):
  555. if type(v) is int:
  556. host = self.__hosts[v]
  557. v = self.__universes_dmx[host][i]
  558. dmx[i] = v
  559. return dmx
  560. def get_mtx(self):#,host=""):
  561. return self.__universes_matrix
  562. def info(self):
  563. return self.__universes_info
  564. def hosts(self):
  565. x = self.__universes_dmx.keys()
  566. x=list(x)
  567. x.sort()
  568. return x
  569. class HostBuffer():
  570. def __init__(self):
  571. """buffer hosts and route data into universes
  572. """
  573. #self.__hosts = [] # LTP order
  574. self.__universes = OrderedDict() # {} # 192.168.0.1 = [0]*512
  575. #self.update(host="localhost",univ=0,dmxframe=[6]*512)
  576. dmxframe = [0]*512
  577. dmxframe[15] = -6
  578. #self.update(host="333.333.333.333",univ=8,dmxframe=dmxframe)
  579. def get_mtx(self,host="", univ=""):
  580. return self.__universes[str(univ)].get_mtx(host)
  581. def get(self,host="", univ=""):
  582. if str(univ) in self.__universes:
  583. return self.__universes[str(univ)].get(host)
  584. return [-8]*512
  585. def hosts(self):
  586. hosts = []
  587. for univ in self.__universes:
  588. x=self.__universes[univ].hosts()
  589. for y in x:
  590. #x=univ.hosts()
  591. if y not in hosts:
  592. hosts.append(y)
  593. hosts.sort()
  594. return hosts
  595. def univs(self):
  596. x=self.__universes.keys()
  597. x=list(x)
  598. #x.sort()
  599. return x
  600. def update(self,host,univ, dmxframe):
  601. #print( "update", host )
  602. if str(univ) not in self.__universes:
  603. self.__universes[str(univ)] = UniversBuffer(str(univ))
  604. self.__universes[str(univ)].update(host,dmxframe)
  605. def info(self,univ=0):
  606. out = {}
  607. #print self.__universes.keys()
  608. for univ in self.__universes.keys():
  609. #print("INFO:",univ)
  610. x=self.__universes[univ]
  611. out[univ] = x.info()
  612. return out
  613. # ============================================================
  614. # Network ====================================================
  615. # ============================================================
  616. import socket
  617. import struct
  618. hostname = socket.gethostname()
  619. netns = "none"
  620. x = os.popen("ip netns identify $$")
  621. xx = x.read()
  622. if xx:
  623. netns = xx.strip()
  624. import fcntl # socket control
  625. def toPrintable(nonprintable):
  626. out = ""
  627. for i in str(nonprintable):
  628. printable = string.ascii_letters + string.digits +r"/()=?{[]}\;:,.-_ "
  629. if str(i) in printable :
  630. out += str(i)
  631. return out
  632. def unpack_art_dmx(data):
  633. dmx = []
  634. for i in range(len(data[18:]) ):
  635. x=data[18+i]
  636. #print("x",x)
  637. #print( "data",b'!B', data[18+i])
  638. #x=struct.unpack( b'!B',data[18+i])
  639. #print( "data",b'!B', data[18+i],x)
  640. #x=x[0]
  641. dmx += [x]
  642. return dmx
  643. def ArtPollCheck(data,addr):
  644. opcode=artnet_get_opcode(data)
  645. if "ArtPoll" in opcode or "ArtPollReplay" in opcode:
  646. #print("PKG3",addr, opcode,len(data))
  647. try:
  648. k = "{}:{}".format(addr[0],opcode[0])
  649. mc.set(k, data)
  650. update_mc_artpoll_index(k) #,val="")
  651. except Exception as e:
  652. print("ArtPollCheck err:",e)
  653. if mc:
  654. mc.set("artnet-pkg-count" ,{})
  655. class PKG_COUNT():
  656. def __init__(self,name="PKG_COUNT"):
  657. self.time = 0
  658. self.fps = 0
  659. self._count = 0
  660. self.fps_hitory = [0]*10
  661. self.fps_count = 0
  662. self.name = name
  663. self.start = time.time()
  664. def count(self):
  665. self.fps_count += 1
  666. def check(self):
  667. if time.time()-self.time > 10:
  668. self.reset()
  669. return True
  670. def reset(self,t=None):
  671. if t is None:
  672. self.time = time.time()
  673. else:
  674. self.time = t
  675. #print("reset",self.name, self.time)
  676. def info(self):
  677. self.fps = self.fps_count/10
  678. self.fps_count = 0
  679. #run_time=int((time.time()-self.start)/60)
  680. self.fps_hitory = self.fps_hitory[1:]
  681. self.fps_hitory.append(self.fps)
  682. self._count += 1
  683. return {self.name+"-fps":self.fps,self.name+"-hist":self.fps_hitory,self.name+"-count":self._count}
  684. def update_mc(self):
  685. data = {}
  686. x =mc.get("artnet-pkg-count")
  687. if x:
  688. data.update(x)
  689. data.update(self.info())
  690. mc.set("artnet-pkg-count" ,data)
  691. class IN_Socket():
  692. def __init__(self,bind='',port=6454):
  693. self.__port =port
  694. self.__bind =bind
  695. self.__poll = 0
  696. self.__data = []
  697. self.__addr = "NONE"
  698. #self.__hosts = {"host":{"9":[0]*512}}
  699. self.__hosts = {}
  700. self.hosts = self.__hosts
  701. self.open()
  702. self.start = time.time()
  703. self.pkg_in_count = PKG_COUNT(name="in")
  704. def open(self):
  705. try:
  706. print("connecting to ArtNet bind:",self.__bind,"Port",self.__port)
  707. self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  708. self.sock.bind((self.__bind, self.__port))
  709. fcntl.fcntl(self.sock, fcntl.F_SETFL, os.O_NONBLOCK)
  710. #self.sock.setblocking(0)
  711. except socket.error as e:
  712. print("Socket ",self.__bind,self.__port, "ERR: {0} ".format(e.args))
  713. #raw_input()
  714. #sys.exit()
  715. def poll(self):
  716. if not self.__poll:
  717. if mc:
  718. if self.pkg_in_count.check():
  719. self.pkg_in_count.reset()
  720. self.pkg_in_count.update_mc()
  721. try:
  722. self.__data, self.__addr = self.sock.recvfrom(self.__port)
  723. data, addr = (self.__data,self.__addr)
  724. self.pkg_in_count.count()
  725. ArtPollCheck(data,addr)
  726. opcode=artnet_get_opcode(data)
  727. if opcode[0] != "ArtDMX":
  728. return
  729. self.host = addr[0]
  730. head = data[:18]
  731. rawdmx = data[18:]
  732. #print([head],addr)
  733. self.univ = -1
  734. try:
  735. self.head = struct.unpack("!8sHBBBBHBB" , head )
  736. except Exception as _:
  737. pass#print( "======E09823" , e)
  738. univ = self.head[6]/255 # /512 # * 512
  739. self.univ = int(univ)
  740. #if "2.0.0.11" not in addr:
  741. # print("PKG3",addr,"univ:",self.univ, opcode,len(rawdmx))
  742. if self.host.startswith("127."): #allways recive localhost on port
  743. self.__poll = 1
  744. return 1
  745. if not options.recive:
  746. self.__poll = 1
  747. return 1
  748. if self.host.startswith(options.recive):
  749. self.__poll = 1
  750. return 1
  751. self.__poll = 0
  752. addr = str(addr)
  753. univ = str(univ)
  754. if self.__poll:
  755. if addr not in self.__hosts:
  756. self.__hosts[addr] = {}
  757. if univ not in self.__hosts[addr]:
  758. self.__hosts[addr][univ] = {}
  759. self.__hosts[addr][univ] = {"head":head,"addr":addr,"univ":univ,"dmx":rawdmx}
  760. self.hosts = self.__hosts
  761. except socket.timeout as e:
  762. err = e.args[0]
  763. if err == 'timed out':
  764. time.sleep(1)
  765. print('recv timed out, retry later')
  766. else:
  767. print(e)
  768. except Exception as _: # socket.error as e:
  769. pass
  770. def recive(self):
  771. if self.__poll:
  772. self.__poll = 0
  773. data, addr = (self.__data,self.__addr)
  774. #print("PKG", self.univ,self.head)
  775. self.dmx = unpack_art_dmx(data)
  776. return { "host":self.host,"dmx":self.dmx,"univ":self.univ,"head":self.head,"data":data,"addr":addr}
  777. # ============================================================
  778. # miniartnet4.py =============================================
  779. # ============================================================
  780. class ArtNetNode():
  781. """simple Object to generate raw ArtNet like Network packages
  782. works in Python2 and Python3 2021-12-05
  783. (only basic implementation)
  784. "Art-Net™ Designed by and Copyright Artistic Licence Holdings Ltd"
  785. https://art-net.org.uk/
  786. """
  787. def __init__(self, to="10.10.10.255",univ=7,port=6454):
  788. print("\n"+self.__doc__+"\n")
  789. try:
  790. univ = int(univ)
  791. except Exception as _:
  792. print("errror univ",univ ,"is not int ... set to 7")
  793. univ = 7
  794. self.univ=univ
  795. self.sendto = to
  796. self.portto = port
  797. self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  798. self.s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  799. self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  800. self.stamp = time.time()
  801. self.test_stamp = time.time()
  802. self.dmx=[33]*512
  803. self.v=0
  804. self.d=1
  805. #self.pkg_out_count = PKG_COUNT(name="out-"+str(univ))
  806. self.pkg_counter = {}
  807. def head(self):
  808. self._header = []
  809. self._header.append(b"Art-Net\x00") # Name, 7byte + 0x00
  810. self._header.append(struct.pack('<H', 0x5000)) # OpCode ArtDMX -> 0x5000, Low Byte first
  811. self._header.append(struct.pack('>H', 14)) # Protocol Version 14, High Byte first
  812. self._header.append(b"\x00") # Order -> nope -> 0x00
  813. self._header.append(struct.pack('B',1)) # Eternity Port
  814. # Address
  815. #if 0 <= universe <= 15 and 0 <= net <= 127 and 0 <= subnet <= 15
  816. net, subnet, universe = (0,0,self.univ) #address
  817. self._header.append(struct.pack('<H', net << 8 | subnet << 4 | universe))
  818. self._header = b"".join(self._header)
  819. def send(self,dmx=None,port=''):
  820. if dmx is None:
  821. dmx = self.dmx
  822. else:
  823. self.dmx = dmx
  824. self.head()
  825. c=[self._header]
  826. c.append( struct.pack('>H', len(dmx) ) )
  827. #print([c])
  828. dmx_count = 0
  829. for v in dmx:
  830. if type(v) is not int:
  831. v=0
  832. elif v > 255: # max dmx value 255
  833. v = 255
  834. elif v < 0: # min dmx value 0
  835. v = 0
  836. dmx_count += 1
  837. c.append(struct.pack("B",v))
  838. c = b"".join(c)
  839. if port:
  840. self.s.sendto(c, (self.sendto, port)) # default 6454
  841. else:
  842. self.s.sendto(c, (self.sendto, self.portto)) # default 6454
  843. # multicounter management !
  844. name = "out-"+str(self.univ)
  845. if name not in self.pkg_counter:
  846. self.pkg_counter[name] = PKG_COUNT(name=name)
  847. counter = self.pkg_counter[name]
  848. counter.count()
  849. if mc:
  850. if counter.check():
  851. counter.reset()
  852. counter.update_mc()
  853. return c
  854. def _test_frame(self):
  855. if self.test_stamp+0.1 > time.time():
  856. return 0
  857. self.test_stamp = time.time()
  858. dmx = [0]*512
  859. dmx[420] = self.v
  860. self.dmx = dmx
  861. self.next()
  862. #self.send(dmx)
  863. #print( [x] )
  864. if self.v >= 255:
  865. self.d=0
  866. elif self.v <=0:
  867. self.d=1
  868. if self.d:
  869. self.v+=1
  870. else:
  871. self.v-=1
  872. #time.sleep(1/30.)
  873. def next(self):
  874. if self.stamp + (1/60) <= time.time():
  875. self.send()
  876. def artnet_test():
  877. # pylint: disable=protected-access
  878. artnet = ArtNetNode()
  879. artnet._tes_frame()
  880. def artnet_get_opcode(head):
  881. #print([head]) #[9:10])
  882. opcode=0x0000
  883. name ="unkown"
  884. try:
  885. opcode=hex(struct.unpack('<h', head[8:10])[0])
  886. except Exception as _:
  887. print("opcode error",[head])
  888. if opcode == '0x5000':
  889. name = "ArtDMX"
  890. elif opcode == '0x2000':
  891. name = "ArtPoll"
  892. elif opcode == '0x2100':
  893. name = "ArtPollReplay"
  894. return (name,opcode)
  895. # ============================================================
  896. # helper =====================================================
  897. # ============================================================
  898. class Pager(): #scroll thru list
  899. def __init__(self):
  900. self.data = []
  901. self.index = 0
  902. self.wrap = 0
  903. self.maxindex = 0
  904. def append(self,val):
  905. self.data.append(val)
  906. self.check()
  907. def set(self,nr):
  908. self.index = nr
  909. self.check()
  910. def get(self):
  911. self.check()
  912. self.data.sort()
  913. if self.data:
  914. return self.data[self.index]
  915. def next(self):
  916. self.index += 1
  917. self.check(flag=1)
  918. return self.get()
  919. def prev(self):
  920. self.index -= 1
  921. self.check(flag=1)
  922. return self.get()
  923. def check(self,flag=0):
  924. if flag:
  925. if self.maxindex and self.maxindex <= len(self.data):
  926. _max = self.maxindex
  927. else:
  928. _max = len(self.data)
  929. else:
  930. _max = len(self.data)
  931. #_max = self.maxindex
  932. self.maxindex = _max
  933. if self.wrap:
  934. if self.index >= _max:
  935. self.index = 0
  936. elif self.index < 0:
  937. self.index = _max-1
  938. else:
  939. if self.index >= _max:
  940. self.index = _max-1
  941. elif self.index < 0:
  942. self.index = 0
  943. class Timer():
  944. def __init__(self,sec=1,start=None):
  945. if start is None:
  946. self.last = time.time()
  947. else:
  948. self.last = start
  949. self.sec = sec
  950. print( self,"init")
  951. def reset(self):
  952. self.last = time.time()
  953. def check(self):
  954. if self.last+self.sec < time.time():
  955. #print(self,"chk",time.time()+self.sec-time.time())
  956. self.reset()
  957. return 1
  958. # ============================================================
  959. # main =======================================================
  960. # ============================================================
  961. class Main():
  962. def __init__(self):
  963. pass
  964. def loop(self):
  965. ohost = HostBuffer()
  966. screen=Window()
  967. #screen=CursesDummy()
  968. screen.exit()
  969. screen.ohost = ohost
  970. #artnet_out = ArtNetNode(to="10.0.25.255")
  971. artnet_out = ArtNetNode(to=options.sendto)
  972. ohost.update(host="Main-"+str(options.sendto),univ=0,dmxframe=[0]*512) # dummy input
  973. #artnet_out._test_frame()
  974. if options.testuniv:
  975. artnet = ArtNetNode(univ=options.testuniv)
  976. # pylint: disable=protected-access
  977. artnet._test_frame()
  978. #ysocket = Socket(bind='127.0.0.1' ,port=6555)
  979. in_socket = IN_Socket()
  980. ohost_buf = {}
  981. ohost_timer = Timer(1/30.,start=0) # 0.03333
  982. send_timer = Timer(1/30.) # 0.03333
  983. try:
  984. screen.exit()
  985. while 1:
  986. poll_flag = 0
  987. if options.testuniv:
  988. # pylint: disable=protected-access
  989. artnet._test_frame()
  990. #artnet_out._test_frame()
  991. #if in_socket.poll():
  992. while in_socket.poll():
  993. poll_flag = 1
  994. x = in_socket.recive()
  995. if x["host"] == options.recive:
  996. try:
  997. x["univ"] = int(options.inmap )
  998. except TypeError:
  999. pass
  1000. if x["host"] not in ohost_buf:
  1001. ohost_buf[x["host"]] = {}
  1002. if x["univ"] not in ohost_buf[x["host"]]:
  1003. ohost_buf[x["host"]][x["univ"]] = {}
  1004. ohost_buf[x["host"]][x["univ"]] = x["dmx"] #write into buffer to prevent package latency encreasing
  1005. try:
  1006. k = "{}:{}".format(x["host"],x["univ"])
  1007. mc.set(k, x["dmx"]) # "dmx-{}".format(univ), ltp)
  1008. active = count_active_dmx_ch(x["dmx"])
  1009. update_memcachd_index(key=k,active=active)
  1010. except Exception as e:
  1011. print("exception:",e)
  1012. time.sleep(.1)
  1013. #ohost.update(x["host"],x["univ"],x["dmx"])
  1014. if 0:#ysocket.poll():
  1015. poll_flag = 1
  1016. x = ysocket.recive()
  1017. if x["host"] == options.recive:
  1018. try:
  1019. x["univ"] = int(options.inmap )
  1020. except TypeError:
  1021. pass
  1022. ohost.update(host=x["host"],univ=x["univ"],dmxframe=x["dmx"])
  1023. screen.sel_univ.data = ohost.univs()
  1024. screen.sel_host.data = ohost.hosts()
  1025. if ohost_timer.check():
  1026. for i in ohost_buf:
  1027. for j in ohost_buf[i]:
  1028. dmx=ohost_buf[i][j]
  1029. ohost.update(host=i,univ=j,dmxframe=dmx) # update univ_data from input buffer
  1030. ohost_buf = {} # clear package buffer
  1031. if send_timer.check() and options.sendto:
  1032. #x=ohost.get(univ=univ2)
  1033. info=ohost.info()
  1034. for i in info:
  1035. univ = i
  1036. if str(univ) == "54":
  1037. break
  1038. ltp=ohost.get(univ=i)
  1039. try:
  1040. k="ltp-out:{}".format(univ)
  1041. mc.set(k,ltp)
  1042. active = count_active_dmx_ch(ltp)
  1043. update_memcachd_index(key=k,active=active)
  1044. except Exception as e:
  1045. print("Exc memcachd_index1 ",e)
  1046. artnet_out.univ=int(univ)
  1047. artnet_out.send(ltp)
  1048. if not poll_flag:
  1049. time.sleep(.001)
  1050. screen.loop()
  1051. finally:
  1052. pass
  1053. #screen.exit()
  1054. #print(dir(curses))
  1055. if __name__ == "__main__":
  1056. print("main")
  1057. main = Main()
  1058. print("loop")
  1059. main.loop()