ArtNetProcessor.py 20 KB

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