ArtNetProcessor.py 34 KB

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