ArtNetProcessor.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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]-3:
  59. continue
  60. self.myscreen.addstr(i+1, 1, l ) #zeile,spalte,text
  61. self.myscreen.refresh()
  62. except KeyboardInterrupt as e:
  63. self.exit()
  64. print "KeyboardInterrupt"
  65. raise e
  66. #except Exception as e:
  67. # self.exit()
  68. # raise e
  69. def inp(self):
  70. x= self._inp
  71. self._inp=""
  72. return x
  73. def read(self):
  74. self.myscreen.nodelay(1)
  75. try:
  76. self._inp=self.myscreen.getkey()
  77. self.myscreen.addstr(0, 1, str(self._inp) ) #zeile,spalte,text
  78. self.myscreen.refresh()
  79. return self._inp
  80. except:
  81. pass#self._inp=""
  82. def clear(self):
  83. self.myscreen.clear()
  84. self.myscreen.border(0)
  85. curses.nocbreak();
  86. #self.myscreen.keypad(0);
  87. self.read()
  88. curses.echo()
  89. curses.resetty()
  90. #self.myscreen.addstr(10, 2, x ) #zeile,spalte,text
  91. def exit(self):
  92. self.clear()
  93. curses.endwin()
  94. print("ENDE")
  95. class xUniversum():
  96. def __init__(self,univers_nr=0):
  97. self.__hosts = []
  98. self.__universes_dmx = {}
  99. self.__universes_fps = {}
  100. self.__universes_frames = {}
  101. self.__universes_flag = {}
  102. self.__universes_x_frames = {}
  103. self.__universes_x_time = {}
  104. self.__universes_count = {}
  105. self.__universes_timer = {}
  106. self.__universes_info = {}
  107. self.__univers_nr = univers_nr
  108. self.__frame = 0
  109. def update(self,host,dmxframe):
  110. if type(dmxframe) != list:
  111. #print( "update ERROR dmxframe is not a list", host )
  112. return
  113. if host not in self.__hosts:
  114. #print( "ADDING HOST:",host,"UNIV:",self.__univers_nr)
  115. self.__universes_dmx[host] = [0]*512
  116. self.__universes_frames[host] = 0
  117. self.__universes_x_frames[host] = 0
  118. self.__universes_fps[host] = [99]*20
  119. self.__universes_flag[host] = [0]*20
  120. self.__universes_x_time[host] = time.time()
  121. self.__universes_timer[host] = [0]*512
  122. self.__universes_info[host] = {}
  123. while host in self.__hosts:
  124. self.__hosts.remove(host)
  125. self.__hosts.append(host) #re-order hosts list for LTP
  126. #print("U",host,self.__hosts)
  127. #print( len(dmxframe),len([0]*512), dmxframe[:10] )
  128. self.__frame += 1
  129. update_matrix = [0]*512
  130. dmx=[0]*512
  131. update_flag = 0
  132. dmxframe_old = self.__universes_dmx[host]
  133. self.__universes_frames[host] += 1
  134. self.__universes_x_frames[host] += 1
  135. if self.__universes_x_time[host]+10 < time.time():
  136. sec = time.time()-self.__universes_x_time[host]
  137. fps = self.__universes_x_frames[host] /sec
  138. #fps = round(fps,1)
  139. fps = int(fps)
  140. self.__universes_fps[host].pop(0)
  141. self.__universes_fps[host].append(fps)
  142. self.__universes_x_time[host] = time.time()
  143. self.__universes_x_frames[host] = 0
  144. if len(dmxframe) <= len(dmxframe_old):
  145. for i,v in enumerate(dmxframe):
  146. if dmxframe[i] != dmxframe_old[i]:
  147. #print( i,v, self.__frame)
  148. update_matrix[i] = self.__frame #LTP timing
  149. update_flag += 1
  150. dmx[i] = v
  151. self.__universes_flag[host].pop(0)
  152. self.__universes_flag[host].append( update_flag )
  153. if update_flag:
  154. tmp = {}
  155. tmp["flag"] =update_flag
  156. tmp["flagx"] = self.__universes_flag[host]
  157. tmp["fpsx"] = int(self.__universes_x_frames[host] / (time.time()-self.__universes_x_time[host]))
  158. tmp["frame"] = self.__frame
  159. #tmp["hosts"] = self.__hosts
  160. tmp["uni"] = self.__univers_nr
  161. tmp["fps"] = self.__universes_fps[host]
  162. self.__universes_info[host] = tmp
  163. #print( "UPDATE HOST:",host, update_flag,"UNIV:",self.__univers_nr)
  164. self.__universes_dmx[host] = dmxframe
  165. self.__universes_timer[host] = update_matrix
  166. def get(self,host=""):
  167. dmx = [-1]*512
  168. timer = [0]*512
  169. #print( "H",self.__hosts,self.__univers_nr )
  170. if host and host in self.__hosts:
  171. return self.__universes_dmx[host]
  172. for host in self.__hosts:
  173. #print( host )
  174. dmxA = self.__universes_dmx[host]
  175. timerA = self.__universes_timer[host]
  176. for i,t in enumerate(timerA):
  177. if timer[i] < t:
  178. timer[i] = timerA[i]
  179. dmx[i] = dmxA[i]
  180. return dmx
  181. def info(self):
  182. return self.__universes_info
  183. class Hosts():
  184. def __init__(self):
  185. self.__hosts = [] # LTP order
  186. self.__universes = {} # 192.168.0.1 = [0]*512
  187. #self.update(host="localhost",univ=0,dmxframe=[6]*512)
  188. #dmxframe = [0]*512
  189. #dmxframe[15] = 6
  190. #self.update(host="333.333.333.333",univ=8,dmxframe=dmxframe)
  191. def get(self,host="", univ=0):
  192. return self.__universes[str(univ)].get(host)
  193. def update(self,host,univ, dmxframe):
  194. #print( "update", host )
  195. if str(univ) not in self.__universes:
  196. self.__universes[str(univ)] = xUniversum(str(univ))
  197. self.__universes[str(univ)].update(host,dmxframe)
  198. def info(self,univ=0):
  199. out = {}
  200. #print self.__universes.keys()
  201. for univ in self.__universes.keys():
  202. #print("INFO:",univ)
  203. x=self.__universes[univ]
  204. out[univ] = x.info()
  205. return out
  206. def toPrintable(nonprintable):
  207. out = ""
  208. for i in str(nonprintable):
  209. printable = string.ascii_letters + string.digits +"/()=?{[]}\;:,.-_ "
  210. if str(i) in printable :
  211. out += str(i)
  212. return out
  213. class Xsocket():
  214. def __init__(self):
  215. self.__poll = 0
  216. self.__data = []
  217. self.__addr = "NONE"
  218. pass
  219. def poll(self):
  220. if not self.__poll:
  221. try:
  222. self.__data, self.__addr = sock.recvfrom(6454)
  223. self.__poll = 1
  224. return 1
  225. except socket.timeout, e:
  226. err = e.args[0]
  227. if err == 'timed out':
  228. sleep(1)
  229. print 'recv timed out, retry later'
  230. else:
  231. print e
  232. except socket.error, e:
  233. pass
  234. def recive(self):
  235. if self.__poll:
  236. self.__poll = 0
  237. return (self.__data,self.__addr)
  238. def unpack_art_dmx(data):
  239. dmx = []
  240. for i in range(len(data[18:]) ):
  241. #try:
  242. dmx += [struct.unpack('!B',data[18+i])[0]]
  243. #except:
  244. # pass
  245. return dmx
  246. if __name__ == "__main__":
  247. frames = [0]*10000
  248. print frames
  249. ohost = Hosts()
  250. try:
  251. print "connecting to ArtNet Port 6454"
  252. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  253. sock.bind(('', 6454))
  254. fcntl.fcntl(sock, fcntl.F_SETFL, os.O_NONBLOCK)
  255. except socket.error as e:
  256. print "Socket 6454 ", "ERR: {0} ".format(e.args)
  257. #raw_input()
  258. #sys.exit()
  259. univers = None
  260. if len(sys.argv) >= 2+1 and sys.argv[1] == "-u":
  261. univers = sys.argv[2]
  262. inp = "q"
  263. univ2= "8"
  264. univers = 0# inp.read(univers)
  265. debug = 0# inp.debug()
  266. packets = 0
  267. #self.__myscreen.getch()
  268. dmx = [0] * 512
  269. fps = 0
  270. fpsi = 0
  271. fpst =int(time.time())
  272. head= "XXX"
  273. screen=Curses()
  274. screen.init()
  275. if 0: #testunivers
  276. while 1:
  277. screen.draw("head",list(range(1,512+1)))
  278. time.sleep(1)
  279. screen.draw("head",[0]*512)
  280. time.sleep(1)
  281. frame = 0
  282. xsocket = Xsocket()
  283. univ_dmx = [ ["x"]*512 ]*16
  284. univ_heads = [ ["none"]*2 ]*16
  285. ttime = time.time()
  286. counter = 0
  287. oohosts=[]
  288. oshost="xxx"
  289. try:
  290. while 1:
  291. dmx = univ_dmx[univers]
  292. headlines = univ_heads[univers]
  293. dmx = []
  294. text = ""
  295. if xsocket.poll():
  296. data, addr = xsocket.recive()
  297. head = [data[:18]]
  298. dmx = data[18:]
  299. try:
  300. head = struct.unpack("!8sHBBBBHBB" , head[0] )
  301. except:
  302. continue
  303. head_uni = head[6]/255 # /512 # * 512
  304. if head_uni < len(frames):# and len(data) == 530:
  305. frames[head_uni] += 1
  306. host = addr[0]
  307. dmx = unpack_art_dmx(data)
  308. ohost.update(host,head_uni,dmx)
  309. if time.time()-0.2 > ttime:
  310. inp2=screen.inp()
  311. if inp2 in "0123456789" and inp2:
  312. univ2 = str(inp2)
  313. if inp2 in "asdfghjkl" and inp2:
  314. oshost = "asdfghjkl".index(inp2)
  315. if len(oohosts) > oshost:
  316. oshost = oohosts[oshost]
  317. elif inp2:
  318. inp=inp2
  319. lines = ["MENUE:"+str(inp)+" univ:"+str(univ2)+ " host:"+str(oshost)]
  320. a=inp
  321. if a=="q":
  322. ttime = time.time()
  323. x=ohost.get(univ=head_uni)
  324. #lines = []
  325. info=ohost.info()
  326. jinfo = ""
  327. for i in info:
  328. xl = json.dumps(i) + "======= "
  329. lines.append( xl )
  330. for j in info[i]:
  331. lines.append( " " + json.dumps([j,""]) )
  332. if j not in oohosts:
  333. oohosts.append(j)
  334. for k in info[i][j]:
  335. #lines.append( " " + json.dumps( info[i][j]) )
  336. lines.append( " "+str(k).ljust(5," ")+": " + json.dumps( info[i][j][k]) )
  337. lines.append(" ")
  338. lines.append(str(ttime))
  339. screen.draw_lines(lines)
  340. elif a=="w":
  341. ttime = time.time()
  342. host = oshost
  343. dmx=ohost.get(host,univ=head_uni)
  344. #lines = []
  345. info=ohost.info()
  346. lines.append("frame "+str(info.keys()) )
  347. # print( str(info.keys() ))
  348. if univ2 in info:
  349. if host in info[univ2] :
  350. lines.append("frame "+str(info[univ2][host]["frame"]))
  351. x=""
  352. for i,v in enumerate(dmx):
  353. x += str(v).rjust(4," ")
  354. if (i+1) % 20 == 0:# and i:
  355. lines.append(x)
  356. x=""
  357. if x:
  358. lines.append(x)
  359. lines.append(" ")
  360. lines.append(str(ttime))
  361. screen.draw_lines(lines)
  362. elif a=="e":
  363. ttime = time.time()
  364. host = "10.10.10.5"
  365. dmx=ohost.get(host,univ=head_uni)
  366. #lines = []
  367. info=ohost.info()
  368. lines.append("frame "+str(info.keys()) )
  369. #print( str(info.keys() ))
  370. if univ2 in info:
  371. if host in info[univ2] :
  372. lines.append("frame "+str(info[univ2][host]["frame"]))
  373. x=""
  374. for i,v in enumerate(dmx):
  375. x += str(v).rjust(4," ")
  376. if (i+1) % 20 == 0:# and i:
  377. lines.append(x)
  378. x=""
  379. if x:
  380. lines.append(x)
  381. lines.append(" ")
  382. lines.append(str(ttime))
  383. screen.draw_lines(lines)
  384. elif a=="r":
  385. ttime = time.time()
  386. host = "10.10.10.3"
  387. dmx=ohost.get(univ=head_uni)
  388. #lines = []
  389. info=ohost.info()
  390. lines.append("+++")
  391. lines.append("frame "+str(info.keys()) )
  392. #print( str(info.keys() ))
  393. if univ2 in info:
  394. if host in info[univ2] :
  395. lines.append("frame "+str(info[univ2][host]["frame"]))
  396. x=""
  397. for i,v in enumerate(dmx):
  398. x += str(v).rjust(4," ")
  399. if (i+1) % 20 == 0:
  400. lines.append(x)
  401. x=""
  402. if x:
  403. lines.append(x)
  404. lines.append(" ")
  405. lines.append(str(ttime))
  406. screen.draw_lines(lines)
  407. else:
  408. #lines = []
  409. lines.append(" NO MENUE SELECTED CHOOS 1-9 " )
  410. lines.append("time "+str(time.time() ) )
  411. screen.draw_lines(lines)
  412. time.sleep(.1)
  413. time.sleep(.001)
  414. finally:
  415. screen.exit()