ArtNetProcessor.py 28 KB

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