ArtNetProcessor.py 28 KB

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