ArtNetProcessor.py 33 KB

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