ArtNetProcessor.py 32 KB

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