ArtNetProcessor.py 33 KB

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