ArtNetProcessor.py 34 KB

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