ArtNetProcessor.py 34 KB

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