ArtNetProcessor.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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_info = {}
  111. self.__univers_nr = univers_nr
  112. self.__frame = 0
  113. def _add(self,host):
  114. if host not in self.__hosts:
  115. #print( "ADDING HOST:",host,"UNIV:",self.__univers_nr)
  116. self.__universes_dmx[host] = ["ini"]*512
  117. self.__universes_frames[host] = 0
  118. self.__universes_x_frames[host] = 0
  119. self.__universes_fps[host] = [99]*20
  120. self.__universes_flag[host] = [0]*20
  121. self.__universes_x_time[host] = time.time()
  122. self.__universes_timer[host] = [0]*512
  123. self.__universes_info[host] = {}
  124. def _next_frame(self):
  125. self.__frame += 1
  126. self.__universes_frames[host] += 1
  127. self.__universes_x_frames[host] += 1
  128. if self.__universes_x_time[host]+10 < time.time():
  129. sec = time.time()-self.__universes_x_time[host]
  130. fps = self.__universes_x_frames[host] /sec
  131. #fps = round(fps,1)
  132. fps = int(fps)
  133. self.__universes_fps[host].pop(0)
  134. self.__universes_fps[host].append(fps)
  135. self.__universes_x_time[host] = time.time()
  136. self.__universes_x_frames[host] = 0
  137. def update(self,host,dmxframe):
  138. if type(dmxframe) != list:
  139. #print( "update ERROR dmxframe is not a list", host )
  140. return
  141. self._add(host)
  142. while host in self.__hosts:
  143. self.__hosts.remove(host)
  144. self.__hosts.append(host) #re-order hosts list for LTP
  145. #print("U",host,self.__hosts)
  146. #print( len(dmxframe),len([0]*512), dmxframe[:10] )
  147. update_matrix = [0]*512
  148. dmx=["non"]*512
  149. update_flag = 0
  150. dmxframe_old = self.__universes_dmx[host]
  151. #for i in dmxframe_old:
  152. # dmx[i] = dmxframe_old[i]
  153. self._next_frame()
  154. if len(dmxframe) <= 512: #len(dmxframe_old):
  155. for i,v in enumerate(dmxframe):
  156. if dmxframe[i] != dmxframe_old[i]:
  157. #print( i,v, self.__frame)
  158. update_matrix[i] = self.__frame #LTP timing
  159. update_flag += 1
  160. dmx[i] = v
  161. self.__universes_flag[host].pop(0)
  162. self.__universes_flag[host].append( update_flag )
  163. tmp = {}
  164. tmp["flag"] =update_flag
  165. tmp["flagx"] = self.__universes_flag[host]
  166. tmp["fpsx"] = int(self.__universes_x_frames[host] / (time.time()-self.__universes_x_time[host]))
  167. tmp["frame"] = self.__frame
  168. #tmp["hosts"] = self.__hosts
  169. tmp["uni"] = self.__univers_nr
  170. tmp["fps"] = self.__universes_fps[host]
  171. self.__universes_info[host] = tmp
  172. if update_flag:
  173. #print( "UPDATE HOST:",host, update_flag,"UNIV:",self.__univers_nr)
  174. self.__universes_dmx[host] = dmx # dmxframe
  175. self.__universes_timer[host] = update_matrix
  176. def get(self,host=""):
  177. dmx = ["-"]*512
  178. timer = [0]*512
  179. #print( "H",self.__hosts,self.__univers_nr )
  180. if host and host in self.__hosts:
  181. return self.__universes_dmx[host]
  182. for host in self.__hosts: # <- LTP
  183. #print( host )
  184. dmxA = self.__universes_dmx[host]
  185. timerA = self.__universes_timer[host]
  186. for i,t in enumerate(timerA):
  187. if timer[i] < t:
  188. timer[i] = timerA[i]
  189. dmx[i] = dmxA[i]
  190. return dmx
  191. def get_mtx(self,host=""):
  192. dmx = ["--"]*512
  193. timer = [0]*512
  194. hosts = self.__hosts[:]
  195. hosts.sort()
  196. for x,host in enumerate(hosts): # <- LTP
  197. #print( host )
  198. dmxA = self.__universes_dmx[host]
  199. timerA = self.__universes_timer[host]
  200. for i,t in enumerate(timerA):
  201. if timer[i] < t:
  202. timer[i] = timerA[i]
  203. dmx[i] = x #dmxA[i]
  204. return dmx
  205. def info(self):
  206. return self.__universes_info
  207. def hosts(self):
  208. x = self.__universes_dmx.keys()
  209. x.sort()
  210. return x
  211. class Hosts():
  212. def __init__(self):
  213. self.__hosts = [] # LTP order
  214. self.__universes = {} # 192.168.0.1 = [0]*512
  215. #self.update(host="localhost",univ=0,dmxframe=[6]*512)
  216. #dmxframe = [0]*512
  217. #dmxframe[15] = 6
  218. #self.update(host="333.333.333.333",univ=8,dmxframe=dmxframe)
  219. def get_mtx(self,host="", univ=""):
  220. return self.__universes[str(univ)].get_mtx(host)
  221. def get(self,host="", univ=""):
  222. return self.__universes[str(univ)].get(host)
  223. def hosts(self):
  224. hosts = []
  225. for univ in self.__universes:
  226. x=self.__universes[univ].hosts()
  227. for y in x:
  228. #x=univ.hosts()
  229. if y not in hosts:
  230. hosts.append(y)
  231. hosts.sort()
  232. return hosts
  233. def univs(self):
  234. x=self.__universes.keys()
  235. x.sort()
  236. return x
  237. def update(self,host,univ, dmxframe):
  238. #print( "update", host )
  239. if str(univ) not in self.__universes:
  240. self.__universes[str(univ)] = xUniversum(str(univ))
  241. self.__universes[str(univ)].update(host,dmxframe)
  242. def info(self,univ=0):
  243. out = {}
  244. #print self.__universes.keys()
  245. for univ in self.__universes.keys():
  246. #print("INFO:",univ)
  247. x=self.__universes[univ]
  248. out[univ] = x.info()
  249. return out
  250. def toPrintable(nonprintable):
  251. out = ""
  252. for i in str(nonprintable):
  253. printable = string.ascii_letters + string.digits +"/()=?{[]}\;:,.-_ "
  254. if str(i) in printable :
  255. out += str(i)
  256. return out
  257. class Xsocket():
  258. def __init__(self):
  259. self.__poll = 0
  260. self.__data = []
  261. self.__addr = "NONE"
  262. pass
  263. def poll(self):
  264. if not self.__poll:
  265. try:
  266. self.__data, self.__addr = sock.recvfrom(6454)
  267. self.__poll = 1
  268. return 1
  269. except socket.timeout, e:
  270. err = e.args[0]
  271. if err == 'timed out':
  272. sleep(1)
  273. print 'recv timed out, retry later'
  274. else:
  275. print e
  276. except socket.error, e:
  277. pass
  278. def recive(self):
  279. if self.__poll:
  280. self.__poll = 0
  281. return (self.__data,self.__addr)
  282. def unpack_art_dmx(data):
  283. dmx = []
  284. for i in range(len(data[18:]) ):
  285. #try:
  286. dmx += [struct.unpack('!B',data[18+i])[0]]
  287. #except:
  288. # pass
  289. return dmx
  290. class Pager(): #scroll thru list
  291. def __init__(self):
  292. self.data = []
  293. self.index = 0
  294. self.wrap = 0
  295. self.maxindex = 0
  296. def append(self,val):
  297. self.data.append(val)
  298. self.check()
  299. def set(self,nr):
  300. self.index = nr
  301. self.check()
  302. def get(self):
  303. self.check()
  304. if self.data:
  305. return self.data[self.index]
  306. def next(self):
  307. self.index += 1
  308. self.check(flag=1)
  309. def prev(self):
  310. self.index -= 1
  311. self.check(flag=1)
  312. def check(self,flag=0):
  313. if flag:
  314. if self.maxindex and self.maxindex <= len(self.data):
  315. max = self.maxindex
  316. else:
  317. max = len(self.data)
  318. else:
  319. max = len(self.data)
  320. if self.wrap:
  321. if self.index >= max:
  322. self.index = 0
  323. elif self.index < 0:
  324. self.index = max-1
  325. else:
  326. if self.index >= max:
  327. self.index = max-1
  328. elif self.index < 0:
  329. self.index = 0
  330. if __name__ == "__main__":
  331. frames = [0]*10000
  332. print frames
  333. ohost = Hosts()
  334. try:
  335. print "connecting to ArtNet Port 6454"
  336. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  337. sock.bind(('', 6454))
  338. fcntl.fcntl(sock, fcntl.F_SETFL, os.O_NONBLOCK)
  339. except socket.error as e:
  340. print "Socket 6454 ", "ERR: {0} ".format(e.args)
  341. #raw_input()
  342. #sys.exit()
  343. univers = None
  344. if len(sys.argv) >= 2+1 and sys.argv[1] == "-u":
  345. univers = sys.argv[2]
  346. inp = "q"
  347. univ2= "8"
  348. univers = 0# inp.read(univers)
  349. debug = 0# inp.debug()
  350. packets = 0
  351. #self.__myscreen.getch()
  352. dmx = [0] * 512
  353. fps = 0
  354. fpsi = 0
  355. fpst =int(time.time())
  356. head= "XXX"
  357. dmx_ch_buffer = []
  358. screen=Curses()
  359. #screen.init()
  360. screen.exit()
  361. if 0: #testunivers
  362. while 1:
  363. screen.draw("head",list(range(1,512+1)))
  364. time.sleep(1)
  365. screen.draw("head",[0]*512)
  366. time.sleep(1)
  367. frame = 0
  368. xsocket = Xsocket()
  369. univ_dmx = [ ["x"]*512 ]*16
  370. univ_heads = [ ["none"]*2 ]*16
  371. ttime = time.time()
  372. counter = 0
  373. cmd=[]
  374. mode=""
  375. sel_host=Pager()
  376. sel_host.wrap=1
  377. sel_univ=Pager()
  378. sel_univ.wrap=1
  379. sel_mode=Pager()
  380. sel_mode.wrap=1
  381. sel_mode.data = ["dmx","ltp","mtx","main"] # mtx = matrix
  382. sel_mode.maxindex = len( sel_mode.data )-1
  383. try:
  384. while 1:
  385. dmx = univ_dmx[univers]
  386. headlines = univ_heads[univers]
  387. dmx = []
  388. text = ""
  389. if xsocket.poll():
  390. data, addr = xsocket.recive()
  391. head = [data[:18]]
  392. dmx = data[18:]
  393. try:
  394. head = struct.unpack("!8sHBBBBHBB" , head[0] )
  395. except:
  396. continue
  397. head_uni = head[6]/255 # /512 # * 512
  398. if head_uni < len(frames):# and len(data) == 530:
  399. frames[head_uni] += 1
  400. host = addr[0]
  401. dmx = unpack_art_dmx(data)
  402. ohost.update(host,head_uni,dmx)
  403. #screen.exit()
  404. if 0:# len(dmx):
  405. print( host)
  406. print( head_uni, data[:30] )#dmx[:10] )
  407. print( head_uni, dmx[:10] )
  408. #continue
  409. # input command buffer
  410. screen.read()
  411. inp2=screen.inp()
  412. if "q" == inp2:
  413. inp2=""
  414. screen.exit()
  415. sys.exit()
  416. elif "?" == inp2:
  417. mode = "?"
  418. elif "," == inp2:
  419. sel_mode.next()
  420. inp2=""
  421. elif ";" == inp2:
  422. sel_mode.prev()
  423. inp2=""
  424. elif "." == inp2:
  425. sel_univ.next()
  426. inp2=""
  427. elif ":" == inp2:
  428. sel_univ.prev()
  429. inp2=""
  430. elif "-" == inp2:
  431. sel_host.next()
  432. inp2=""
  433. elif "_" == inp2:
  434. sel_host.prev()
  435. inp2=""
  436. elif "#" == inp2:
  437. if "main" in sel_mode.data:
  438. x = sel_mode.data.index( "main")
  439. sel_mode.index = x
  440. sel_mode.check()
  441. inp2=""
  442. if inp2 == "\n":
  443. cmd2 = "".join( cmd).split()
  444. cmd=[]
  445. if len(cmd2) < 2:
  446. pass
  447. elif "C^" in cmd2:
  448. screen.exit()
  449. sys.exit()
  450. elif "univ" in cmd2 or "u" == cmd2[0]:
  451. x=""
  452. if cmd2[1] in sel_univ.data:
  453. x = sel_univ.data.index( cmd2[1])
  454. sel_univ.index = x
  455. sel_univ.check()
  456. elif "mode" in cmd2 or "m" == cmd2[0]:
  457. if cmd2[1] in sel_mode.data:
  458. x = sel_mode.data.index( cmd2[1])
  459. sel_mode.index = x
  460. sel_mode.check()
  461. elif "host" in cmd2 or "h" == cmd2[0]:
  462. try:
  463. x=int(cmd2[1])
  464. sel_host.set(x)
  465. except:
  466. pass
  467. else:
  468. cmd.append(inp2)
  469. sel_univ.data = ohost.univs()
  470. sel_univ.check()
  471. sel_host.data = ohost.hosts()
  472. sel_host.check()
  473. host = sel_host.get()
  474. univ2 = sel_univ.get()
  475. mode = sel_mode.get()
  476. if time.time()-0.2 > ttime:
  477. lines = [ ]
  478. lines.append(" CMD:" + "".join(cmd) )
  479. if mode=="help" or mode=="?":
  480. lines.append("HILFE[h]: " )
  481. lines.append("MODE [m]: inp, in2 in1 " )
  482. lines.append("UNIV [u]: 0-16 " )
  483. lines.append(" " )
  484. lines.append("HILFE " )
  485. elif mode=="dmx" or mode == "DMX":
  486. ttime = time.time()
  487. dmx=ohost.get(host,univ=univ2)#univ=head_uni)
  488. info=ohost.info()
  489. #lines.append("frame "+str(info.keys()) )
  490. if univ2 in info:
  491. if host in info[univ2] :
  492. lines.append("frame "+str(info[univ2][host]["frame"]))
  493. x=""
  494. for i,v in enumerate(dmx):
  495. if v == 0:
  496. v = "+"
  497. x += str(v).rjust(4," ")
  498. if (i+1) % 20 == 0:# and i:
  499. lines.append(x)
  500. x=""
  501. if x:
  502. lines.append(x)
  503. lines.append(" ")
  504. lines.append(str(ttime))
  505. #screen.draw_lines(lines)
  506. elif mode=="mtx":
  507. ttime = time.time()
  508. dmx=ohost.get_mtx(host,univ=univ2)#univ=head_uni)
  509. info=ohost.info()
  510. #lines.append("frame "+str(info.keys()) )
  511. if univ2 in info:
  512. if host in info[univ2] :
  513. lines.append("frame "+str(info[univ2][host]["frame"]))
  514. x=""
  515. for i,v in enumerate(dmx):
  516. x += str(v).rjust(4," ")
  517. if (i+1) % 20 == 0:# and i:
  518. lines.append(x)
  519. x=""
  520. if x:
  521. lines.append(x)
  522. lines.append(" ")
  523. lines.append(str(ttime))
  524. #screen.draw_lines(lines)
  525. elif mode=="ltp" or mode=="LTP":
  526. ttime = time.time()
  527. dmx=ohost.get(univ=univ2)#head_uni)
  528. #univ2=""
  529. host=""
  530. info=ohost.info()
  531. lines.append("frame "+str(info.keys()) )
  532. x=""
  533. for i,v in enumerate(dmx):
  534. x += str(v).rjust(4," ")
  535. if (i+1) % 20 == 0:
  536. lines.append(x)
  537. x=""
  538. if x:
  539. lines.append(x)
  540. lines.append(" ")
  541. lines.append(str(ttime))
  542. #screen.draw_lines(lines)
  543. else:
  544. ttime = time.time()
  545. x=ohost.get(univ=head_uni)
  546. #lines = []
  547. host=""
  548. univ2=""
  549. info=ohost.info()
  550. jinfo = ""
  551. for i in info:
  552. xl = json.dumps(i) + "======= "
  553. lines.append( xl )
  554. for j in info[i]:
  555. lines.append( " " + json.dumps([j,""]) )
  556. if j not in sel_host.data:
  557. pass#sel_host.append(j)
  558. for k in info[i][j]:
  559. #lines.append( " " + json.dumps( info[i][j]) )
  560. lines.append( " "+str(k).ljust(5," ")+": " + json.dumps( info[i][j][k]) )
  561. lines.append(" ")
  562. lines.append(str(ttime))
  563. #screen.draw_lines(lines)
  564. tmp = ""
  565. tmp += " mode:"+(str(mode).ljust(10," "))
  566. tmp += " univ:"+str(sel_univ.index)+":"+(str(univ2).ljust(10," "))
  567. tmp += " host:"+str(sel_host.index)+":"+(str(host).ljust(10," "))
  568. lines.insert(0,tmp)
  569. tmp = ""
  570. tmp += " univ:"+ (str(sel_univ.data))#.ljust(20," "))
  571. tmp += " list:"+ (str(sel_host.data))#.ljust(20," "))
  572. lines.insert(0,tmp)
  573. screen.draw_lines(lines)
  574. time.sleep(.001)
  575. finally:
  576. screen.exit()
  577. print( sel_host.index,sel_host.data)