ArtNetProcessor.py 34 KB

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