ArtNetProcessor.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. #! /usr/bin/python
  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, either version 2 of the License, or
  11. (at your option) any later version.
  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.rathfelder@gmail.com
  19. """
  20. import sys
  21. sys.stdout.write("\x1b]2;DMX-SHEET 5\x07") # terminal title
  22. import string
  23. import time
  24. import os
  25. import json
  26. from collections import OrderedDict
  27. # ============================================================
  28. # Text Grafik Curses =========================================
  29. # ============================================================
  30. import curses
  31. class CursesDummy():
  32. def __init__(self):
  33. self.sel_host=Pager()
  34. self.sel_host.wrap=1
  35. self.sel_univ=Pager()
  36. self.sel_univ.wrap=1
  37. self.sel_mode=Pager()
  38. self.sel_mode.wrap=1
  39. pass
  40. def dir(self):
  41. pass
  42. def test(self):
  43. pass
  44. def init(self):
  45. pass
  46. def addstr(self,x,y,txt):
  47. pass
  48. def draw_lines(self,lines):
  49. pass
  50. def inp(self):
  51. return ""
  52. pass
  53. def read(self):
  54. pass
  55. def clear(self):
  56. pass
  57. def exit(self):
  58. pass
  59. class Curses():
  60. def __init__(self):
  61. self.myscreen = curses.initscr()
  62. print( dir(self.myscreen))
  63. print( self.myscreen.getmaxyx() )
  64. self._inp=""
  65. self.cmd = []
  66. self.mode="ltp"
  67. self.sel_host=Pager()
  68. self.sel_host.wrap=1
  69. self.sel_univ=Pager()
  70. self.sel_univ.wrap=1
  71. self.sel_mode=Pager()
  72. self.sel_mode.wrap=1
  73. self.sel_mode.data = ["dmx","ltp","mtx","main"] # mtx = matrix
  74. self.sel_mode.maxindex = len( self.sel_mode.data )-1
  75. self.ttime = time.time()
  76. self.univ2 = 0
  77. self.host =""
  78. self.ohost = Hosts() # as default
  79. def dir(self):
  80. return dir(self.myscreen)
  81. def test(self):
  82. self.init()
  83. #self.loop()
  84. self.draw_lines(["a","b","c"])
  85. try:
  86. time.sleep(10)
  87. finally:
  88. self.exit()
  89. def init(self):
  90. curses.savetty()
  91. curses.noecho()
  92. curses.cbreak()
  93. curses.noqiflush() #?
  94. curses.noraw() #?
  95. self.clear()
  96. curses.beep()
  97. frame = 10
  98. i = 0
  99. def addstr(self,x,y,txt):
  100. self.myscreen.addstr(x, y, txt ) #zeile,spalte,text
  101. def draw_lines(self,lines):
  102. self.clear()
  103. try:
  104. x,y= self.myscreen.getmaxyx()
  105. for i,l in enumerate(lines):
  106. #print(i,l)
  107. if i >= x-2:
  108. break
  109. self.myscreen.addstr(i+1, 1, l ) #zeile,spalte,text
  110. if i >= self.myscreen.getmaxyx()[0]-2:
  111. self.myscreen.addstr(i+1, 1, "..." ) #zeile,spalte,text
  112. self.myscreen.refresh()
  113. self.myscreen.resize(x-1,y-1) # to prevent slowdown..
  114. self.myscreen.resize(x,y)
  115. except KeyboardInterrupt as e:
  116. self.exit()
  117. print("KeyboardInterrupt")
  118. raise e
  119. #except Exception as e:
  120. # self.exit()
  121. # raise e
  122. def inp(self):
  123. x= self._inp
  124. self._inp=""
  125. return x
  126. def read(self):
  127. self.myscreen.nodelay(1)
  128. try:
  129. self._inp=self.myscreen.getkey()
  130. if not self._inp:
  131. self._inp = self.myscreen.getch()
  132. self.myscreen.addstr(0, 1, str(self._inp) ) #zeile,spalte,text
  133. self.myscreen.refresh()
  134. return self._inp
  135. except:
  136. pass#self._inp=""
  137. def clear(self):
  138. self.myscreen.clear()
  139. self.myscreen.border(0)
  140. curses.nocbreak();
  141. self.myscreen.keypad(0);
  142. #self.read()
  143. curses.echo()
  144. curses.resetty()
  145. #self.myscreen.addstr(10, 2, x ) #zeile,spalte,text
  146. def exit(self):
  147. self.clear()
  148. curses.endwin()
  149. print("ENDE")
  150. def keyread(self):
  151. #continue
  152. # input command buffer
  153. self.read()
  154. inp2=self.inp()
  155. if "q" == inp2:
  156. inp2=""
  157. self.exit()
  158. sys.exit()
  159. elif "?" == inp2:
  160. self.mode = "?"
  161. elif "," == inp2:
  162. self.sel_mode.next()
  163. inp2=""
  164. elif ";" == inp2:
  165. self.sel_mode.prev()
  166. inp2=""
  167. elif "." == inp2:
  168. self.sel_univ.next()
  169. inp2=""
  170. elif ":" == inp2:
  171. self.sel_univ.prev()
  172. inp2=""
  173. elif "-" == inp2:
  174. self.sel_host.next()
  175. inp2=""
  176. elif "_" == inp2:
  177. self.sel_host.prev()
  178. inp2=""
  179. elif "#" == inp2:
  180. if "main" in self.sel_mode.data:
  181. x = self.sel_mode.data.index( "main")
  182. self.sel_mode.index = x
  183. self.sel_mode.check()
  184. inp2=""
  185. if inp2 == "\n":
  186. cmd2 = "".join( self.cmd).split()
  187. self.cmd=[]
  188. if len(cmd2) < 2:
  189. pass
  190. elif "C^" in cmd2:
  191. screen.exit()
  192. sys.exit()
  193. elif "univ" in cmd2 or "u" == cmd2[0]:
  194. x=""
  195. if cmd2[1] in sel_univ.data:
  196. x = sel_univ.data.index( cmd2[1])
  197. sel_univ.index = x
  198. sel_univ.check()
  199. elif "mode" in cmd2 or "m" == cmd2[0]:
  200. if cmd2[1] in self.sel_mode.data:
  201. x = self.sel_mode.data.index( cmd2[1])
  202. self.sel_mode.index = x
  203. self.sel_mode.check()
  204. elif "host" in cmd2 or "h" == cmd2[0]:
  205. try:
  206. x=int(cmd2[1])
  207. self.sel_host.set(x)
  208. except:
  209. pass
  210. else:
  211. self.cmd.append(inp2)
  212. def loop(self):
  213. self.keyread()
  214. #print( "LOOP")
  215. host = self.sel_host.get()
  216. univ2 = self.sel_univ.get()
  217. self.mode = self.sel_mode.get()
  218. if time.time()-0.12 > self.ttime:
  219. lines = [ ]
  220. #print("cmd:",cmd)
  221. lines.append(" CMD:" + "".join(self.cmd) )
  222. if self.mode=="help" or self.mode=="?":
  223. lines.append("HILFE[h]: " )
  224. lines.append("MODE [m]: inp, in2 in1 " )
  225. lines.append("UNIV [u]: 0-16 " )
  226. lines.append(" " )
  227. lines.append("HILFE " )
  228. elif self.mode=="dmx" or self.mode == "DMX":
  229. self.ttime = time.time()
  230. dmx=self.ohost.get(host,univ=univ2)#univ=head_uni)
  231. info=self.ohost.info()
  232. #lines.append("frame "+str(info.keys()) )
  233. if univ2 in info:
  234. if host in info[univ2] :
  235. lines.append("frame "+str(info[univ2][host]["frame"]))
  236. x=""
  237. for i,v in enumerate(dmx):
  238. if v == 0:
  239. v = "+"
  240. x += str(v).rjust(4," ")
  241. if (i+1) % 20 == 0:# and i:
  242. lines.append(x)
  243. x=""
  244. if x:
  245. lines.append(x)
  246. lines.append(" ")
  247. lines.append(str(self.ttime))
  248. #screen.draw_lines(lines)
  249. elif self.mode=="mtx":
  250. self.ttime = time.time()
  251. dmx=self.ohost.get_mtx(host,univ=univ2)#univ=head_uni)
  252. info=self.ohost.info()
  253. #lines.append("frame "+str(info.keys()) )
  254. if univ2 in info:
  255. if host in info[univ2] :
  256. lines.append("frame "+str(info[univ2][host]["frame"]))
  257. x=""
  258. for i,v in enumerate(dmx):
  259. x += str(v).rjust(4," ")
  260. if (i+1) % 20 == 0:# and i:
  261. lines.append(x)
  262. x=""
  263. if x:
  264. lines.append(x)
  265. lines.append(" ")
  266. lines.append(str(self.ttime))
  267. #screen.draw_lines(lines)
  268. elif self.mode=="ltp" or self.mode=="LTP":
  269. self.ttime = time.time()
  270. dmx=self.ohost.get(univ=univ2)#head_uni)
  271. #univ2=""
  272. host=""
  273. info=self.ohost.info()
  274. lines.append("frame "+str(info.keys()) )
  275. x=""
  276. for i,v in enumerate(dmx):
  277. x += str(v).rjust(4," ")
  278. if (i+1) % 20 == 0:
  279. lines.append(x)
  280. x=""
  281. if x:
  282. lines.append(x)
  283. lines.append(" ")
  284. lines.append(str(self.ttime))
  285. #screen.draw_lines(lines)
  286. else:
  287. self.ttime = time.time()
  288. x=self.ohost.get(univ=head_uni)
  289. #lines = []
  290. host=""
  291. univ2=""
  292. info=self.ohost.info()
  293. jinfo = ""
  294. for i in info:
  295. xl = json.dumps(i) + "======= "
  296. lines.append( xl )
  297. for j in info[i]:
  298. lines.append( " " + json.dumps([j,""]) )
  299. if j not in self.sel_host.data:
  300. pass#sel_host.append(j)
  301. for k in info[i][j]:
  302. #lines.append( " " + json.dumps( info[i][j]) )
  303. lines.append( " "+str(k).ljust(5," ")+": " + json.dumps( info[i][j][k]) )
  304. lines.append(" ")
  305. lines.append(str(self.ttime))
  306. #screen.draw_lines(lines)
  307. tmp = ""
  308. tmp += " mode:"+(str(self.mode).ljust(10," "))
  309. tmp += " univ:"+str(self.sel_univ.index)+":"+(str(self.sel_univ.get()).ljust(10," "))
  310. tmp += " host:"+str(self.sel_host.index)+":"+(str(self.sel_host.get()).ljust(10," "))
  311. lines.insert(0,tmp)
  312. tmp = ""
  313. tmp += " univ:"+ (str(self.sel_univ.data))#.ljust(20," "))
  314. tmp += " list:"+ (str(self.sel_host.data))#.ljust(20," "))
  315. lines.insert(0,tmp)
  316. self.draw_lines(lines)
  317. class xUniversum():
  318. def __init__(self,univers_nr=0):
  319. """buffer and merge a universe from multiple sender
  320. """
  321. self.__hosts = []
  322. self.__universes_dmx = {}
  323. self.__universes_fps = {}
  324. self.__universes_frames = {}
  325. self.__universes_flag = {}
  326. self.__universes_x_frames = {}
  327. self.__universes_x_time = {}
  328. self.__universes_count = {}
  329. self.__universes_timer = {}
  330. self.__universes_matrix = ["."]*512
  331. self.__universes_info = {}
  332. self.__univers_nr = univers_nr
  333. self.__frame = 0
  334. def _add(self,host):
  335. if host not in self.__hosts:
  336. self.__hosts.append(host) #re-order hosts list for LTP
  337. #print( "ADDING HOST:",host,"UNIV:",self.__univers_nr)
  338. self.__universes_dmx[host] = [0]*512
  339. self.__universes_frames[host] = 0
  340. self.__universes_x_frames[host] = 0
  341. self.__universes_fps[host] = [""]*20
  342. self.__universes_flag[host] = [0]*20
  343. self.__universes_x_time[host] = time.time()
  344. self.__universes_timer[host] = [0]*512
  345. self.__universes_info[host] = {}
  346. def _next_frame(self,host):
  347. self.__frame += 1
  348. self.__universes_frames[host] += 1
  349. self.__universes_x_frames[host] += 1
  350. if self.__universes_x_time[host]+10 < time.time():
  351. sec = time.time()-self.__universes_x_time[host]
  352. fps = self.__universes_x_frames[host] /sec
  353. #fps = round(fps,1)
  354. fps = int(fps)
  355. self.__universes_fps[host].pop(0)
  356. self.__universes_fps[host].append(fps)
  357. self.__universes_x_time[host] = time.time()
  358. self.__universes_x_frames[host] = 0
  359. def update(self,host,dmxframe):
  360. if type(dmxframe) != list:
  361. #print( "update ERROR dmxframe is not a list", host )
  362. return
  363. self._add(host)
  364. update_matrix = [0]*512
  365. dmx=[0]*512
  366. update_flag = 0
  367. dmxframe_old = self.__universes_dmx[host]
  368. self._next_frame(host)
  369. if len(dmxframe) <= 512: #len(dmxframe_old):
  370. for i,v in enumerate(dmxframe):
  371. if dmxframe[i] != dmxframe_old[i]:
  372. update_flag += 1
  373. self.__universes_matrix[i] = self.__hosts.index(host)
  374. dmx[i] = v
  375. self.__universes_flag[host].pop(0)
  376. self.__universes_flag[host].append( update_flag )
  377. tmp = {}
  378. tmp["flag"] =update_flag
  379. tmp["flagx"] = self.__universes_flag[host]
  380. tmp["fpsx"] = int(self.__universes_x_frames[host] / (time.time()-self.__universes_x_time[host]))
  381. tmp["frame"] = self.__frame
  382. #tmp["hosts"] = self.__hosts
  383. tmp["uni"] = self.__univers_nr
  384. tmp["fps"] = self.__universes_fps[host]
  385. self.__universes_info[host] = tmp
  386. if update_flag:
  387. #print( "UPDATE HOST:",host, update_flag,"UNIV:",self.__univers_nr)
  388. self.__universes_dmx[host] = dmx # dmxframe
  389. self.__universes_timer[host] = update_matrix
  390. def get(self,host=""):
  391. if host and host in self.__hosts:
  392. return self.__universes_dmx[host]
  393. dmx = [":"]*512
  394. for i,v in enumerate(self.__universes_matrix):
  395. if type(v) is int:
  396. host = self.__hosts[v]
  397. v = self.__universes_dmx[host][i]
  398. dmx[i] = v
  399. return dmx
  400. def get_mtx(self,host=""):
  401. return self.__universes_matrix
  402. def info(self):
  403. return self.__universes_info
  404. def hosts(self):
  405. x = self.__universes_dmx.keys()
  406. x=list(x)
  407. x.sort()
  408. return x
  409. class Hosts():
  410. def __init__(self):
  411. """buffer hosts and route data into universes
  412. """
  413. self.__hosts = [] # LTP order
  414. self.__universes = OrderedDict() # {} # 192.168.0.1 = [0]*512
  415. #self.update(host="localhost",univ=0,dmxframe=[6]*512)
  416. dmxframe = [0]*512
  417. dmxframe[15] = 6
  418. #self.update(host="333.333.333.333",univ=8,dmxframe=dmxframe)
  419. def get_mtx(self,host="", univ=""):
  420. return self.__universes[str(univ)].get_mtx(host)
  421. def get(self,host="", univ=""):
  422. if str(univ) in self.__universes:
  423. return self.__universes[str(univ)].get(host)
  424. else:
  425. return [-8]*512
  426. def hosts(self):
  427. hosts = []
  428. for univ in self.__universes:
  429. x=self.__universes[univ].hosts()
  430. for y in x:
  431. #x=univ.hosts()
  432. if y not in hosts:
  433. hosts.append(y)
  434. hosts.sort()
  435. return hosts
  436. def univs(self):
  437. x=self.__universes.keys()
  438. x=list(x)
  439. #x.sort()
  440. return x
  441. def update(self,host,univ, dmxframe):
  442. #print( "update", host )
  443. if str(univ) not in self.__universes:
  444. self.__universes[str(univ)] = xUniversum(str(univ))
  445. self.__universes[str(univ)].update(host,dmxframe)
  446. def info(self,univ=0):
  447. out = {}
  448. #print self.__universes.keys()
  449. for univ in self.__universes.keys():
  450. #print("INFO:",univ)
  451. x=self.__universes[univ]
  452. out[univ] = x.info()
  453. return out
  454. # ============================================================
  455. # Network ====================================================
  456. # ============================================================
  457. import socket, struct
  458. import fcntl #socket control
  459. import errno
  460. def toPrintable(nonprintable):
  461. out = ""
  462. for i in str(nonprintable):
  463. printable = string.ascii_letters + string.digits +"/()=?{[]}\;:,.-_ "
  464. if str(i) in printable :
  465. out += str(i)
  466. return out
  467. def unpack_art_dmx(data):
  468. dmx = []
  469. for i in range(len(data[18:]) ):
  470. x=data[18+i]
  471. #print("x",x)
  472. #print( "data",b'!B', data[18+i])
  473. #x=struct.unpack( b'!B',data[18+i])
  474. #print( "data",b'!B', data[18+i],x)
  475. #x=x[0]
  476. dmx += [x]
  477. return dmx
  478. class Xsocket():
  479. def __init__(self):
  480. self.__poll = 0
  481. self.__data = []
  482. self.__addr = "NONE"
  483. pass
  484. def poll(self):
  485. if not self.__poll:
  486. try:
  487. self.__data, self.__addr = sock.recvfrom(6454)
  488. self.__poll = 1
  489. return 1
  490. except socket.timeout as e:
  491. err = e.args[0]
  492. if err == 'timed out':
  493. sleep(1)
  494. print('recv timed out, retry later')
  495. else:
  496. print(e)
  497. except socket.error as e:
  498. pass
  499. def recive(self):
  500. if self.__poll:
  501. self.__poll = 0
  502. return (self.__data,self.__addr)
  503. class Pager(): #scroll thru list
  504. def __init__(self):
  505. self.data = []
  506. self.index = 0
  507. self.wrap = 0
  508. self.maxindex = 0
  509. def append(self,val):
  510. self.data.append(val)
  511. self.check()
  512. def set(self,nr):
  513. self.index = nr
  514. self.check()
  515. def get(self):
  516. self.check()
  517. if self.data:
  518. return self.data[self.index]
  519. def next(self):
  520. self.index += 1
  521. self.check(flag=1)
  522. def prev(self):
  523. self.index -= 1
  524. self.check(flag=1)
  525. def check(self,flag=0):
  526. if flag:
  527. if self.maxindex and self.maxindex <= len(self.data):
  528. max = self.maxindex
  529. else:
  530. max = len(self.data)
  531. else:
  532. max = len(self.data)
  533. if self.wrap:
  534. if self.index >= max:
  535. self.index = 0
  536. elif self.index < 0:
  537. self.index = max-1
  538. else:
  539. if self.index >= max:
  540. self.index = max-1
  541. elif self.index < 0:
  542. self.index = 0
  543. if __name__ == "__main__":
  544. frames = [0]*10000
  545. print("frame",frames)
  546. ohost = Hosts()
  547. try:
  548. print("connecting to ArtNet Port 6454")
  549. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  550. sock.bind(('', 6454))
  551. fcntl.fcntl(sock, fcntl.F_SETFL, os.O_NONBLOCK)
  552. except socket.error as e:
  553. print("Socket 6454 ", "ERR: {0} ".format(e.args))
  554. #raw_input()
  555. #sys.exit()
  556. univers = None
  557. if len(sys.argv) >= 2+1 and sys.argv[1] == "-u":
  558. univers = sys.argv[2]
  559. inp = "q"
  560. univ2= "8"
  561. univers = 0# inp.read(univers)
  562. debug = 0# inp.debug()
  563. packets = 0
  564. #self.__myscreen.getch()
  565. dmx = [0] * 512
  566. fps = 0
  567. fpsi = 0
  568. fpst =int(time.time())
  569. head= "XXX"
  570. dmx_ch_buffer = []
  571. screen=Curses()
  572. #screen=CursesDummy()
  573. #screen.init()
  574. screen.exit()
  575. screen.ohost = ohost
  576. if 0: #testunivers
  577. while 1:
  578. screen.draw("head",list(range(1,512+1)))
  579. time.sleep(1)
  580. screen.draw("head",[0]*512)
  581. time.sleep(1)
  582. frame = 0
  583. xsocket = Xsocket()
  584. univ_dmx = [ ["x"]*512 ]*16
  585. univ_heads = [ ["none"]*2 ]*16
  586. counter = 0
  587. head_uni=""
  588. dmx = []
  589. headlines = ""
  590. try:
  591. while 1:
  592. dmx = univ_dmx[univers]
  593. headlines = univ_heads[univers]
  594. dmx = []
  595. text = ""
  596. if xsocket.poll():
  597. data, addr = xsocket.recive()
  598. head = [data[:18]]
  599. dmx = data[18:]
  600. try:
  601. head = struct.unpack("!8sHBBBBHBB" , head[0] )
  602. except:
  603. continue
  604. #print("\n=====", [addr,data],"\n======" )
  605. #sys.exit()
  606. head_uni = head[6]/255 # /512 # * 512
  607. head_uni = int(head_uni)
  608. #print("head_uni", head_uni)
  609. if head_uni < len(frames):# and len(data) == 530:
  610. frames[head_uni] += 1
  611. host = addr[0]
  612. dmx = unpack_art_dmx(data)
  613. ohost.update(host,head_uni,dmx)
  614. #screen.exit()
  615. if 0:# len(dmx):
  616. print( host)
  617. print( head_uni, data[:30] )#dmx[:10] )
  618. print( head_uni, dmx[:10] )
  619. #screen.ohost = ohost
  620. screen.sel_univ.data = ohost.univs()
  621. #screen.sel_univ.check()
  622. screen.sel_host.data = ohost.hosts()
  623. #screen.sel_host.check()
  624. screen.loop()
  625. time.sleep(.001)
  626. finally:
  627. screen.exit()
  628. print(dir(screen))
  629. print("###")
  630. print(screen.dir())
  631. print("###")
  632. print(dir(curses))
  633. #print( "finally",sel_host.index,sel_host.data)