ArtNetProcessor.py 36 KB

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