ArtNetProcessor.py 28 KB

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