ArtNetProcessor.py 34 KB

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