ArtNetProcessor.py 35 KB

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