ArtNetProcessor.py 33 KB

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