ArtNetProcessor.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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(" 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. import fcntl #socket control
  490. import errno
  491. def toPrintable(nonprintable):
  492. out = ""
  493. for i in str(nonprintable):
  494. printable = string.ascii_letters + string.digits +"/()=?{[]}\;:,.-_ "
  495. if str(i) in printable :
  496. out += str(i)
  497. return out
  498. def unpack_art_dmx(data):
  499. dmx = []
  500. for i in range(len(data[18:]) ):
  501. x=data[18+i]
  502. #print("x",x)
  503. #print( "data",b'!B', data[18+i])
  504. #x=struct.unpack( b'!B',data[18+i])
  505. #print( "data",b'!B', data[18+i],x)
  506. #x=x[0]
  507. dmx += [x]
  508. return dmx
  509. class Socket():
  510. def __init__(self,bind='',port=6454):
  511. self.__port =port
  512. self.__bind =bind
  513. self.__poll = 0
  514. self.__data = []
  515. self.__addr = "NONE"
  516. self.open()
  517. def open(self):
  518. try:
  519. print("connecting to ArtNet bind:",self.__bind,"Port",self.__port)
  520. self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  521. self.sock.bind((self.__bind, self.__port))
  522. fcntl.fcntl(self.sock, fcntl.F_SETFL, os.O_NONBLOCK)
  523. #self.sock.setblocking(0)
  524. except socket.error as e:
  525. print("Socket ",self.__bind,self.__port, "ERR: {0} ".format(e.args))
  526. #raw_input()
  527. #sys.exit()
  528. def poll(self):
  529. if not self.__poll:
  530. try:
  531. self.__data, self.__addr = self.sock.recvfrom(self.__port)
  532. data, addr = (self.__data,self.__addr)
  533. self.host = addr[0]
  534. head = data[:18]
  535. rawdmx = data[18:]
  536. #print([head],addr)
  537. self.univ = -1
  538. try:
  539. self.head = struct.unpack("!8sHBBBBHBB" , head )
  540. except Exception as e:
  541. pass#print( "======E09823" , e)
  542. univ = self.head[6]/255 # /512 # * 512
  543. self.univ = int(univ)
  544. if self.host.startswith("127."): #allways recive localhost on port
  545. self.__poll = 1
  546. return 1
  547. elif not options.recive:
  548. self.__poll = 1
  549. return 1
  550. elif self.host.startswith(options.recive):
  551. self.__poll = 1
  552. return 1
  553. else:
  554. self.__poll = 0
  555. except socket.timeout as e:
  556. err = e.args[0]
  557. if err == 'timed out':
  558. sleep(1)
  559. print('recv timed out, retry later')
  560. else:
  561. print(e)
  562. except socket.error as e:
  563. pass
  564. def recive(self):
  565. if self.__poll:
  566. self.__poll = 0
  567. data, addr = (self.__data,self.__addr)
  568. #print( self.univ,self.head)
  569. self.dmx = unpack_art_dmx(data)
  570. return { "host":self.host,"dmx":self.dmx,"univ":self.univ,"head":self.head,"data":data,"addr":addr}
  571. # ============================================================
  572. # miniartnet4.py =============================================
  573. # ============================================================
  574. import time
  575. import socket
  576. import struct
  577. import random
  578. class ArtNetNode():
  579. """simple Object to generate ArtNet Network packages
  580. works in Python2 and Python3 2021-12-05
  581. """
  582. def __init__(self, to="10.10.10.255",univ=7,port=6454):
  583. try:
  584. univ = int(univ)
  585. except:
  586. print("errror univ",univ ,"is not int ... set to 7")
  587. univ = 7
  588. self.univ=univ
  589. self.sendto = to
  590. self.portto = port
  591. self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  592. self.s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  593. self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  594. self.stamp = time.time()
  595. self.test_stamp = time.time()
  596. self.dmx=[33]*512
  597. self.v=0
  598. self.d=1
  599. def head(self):
  600. self._header = []
  601. self._header.append(b"Art-Net\x00") # Name, 7byte + 0x00
  602. self._header.append(struct.pack('<H', 0x5000)) # OpCode ArtDMX -> 0x5000, Low Byte first
  603. self._header.append(struct.pack('>H', 14)) # Protocol Version 14, High Byte first
  604. self._header.append(b"\x00") # Order -> nope -> 0x00
  605. self._header.append(struct.pack('B',1)) # Eternity Port
  606. # Address
  607. #if 0 <= universe <= 15 and 0 <= net <= 127 and 0 <= subnet <= 15
  608. net, subnet, universe = (0,0,self.univ) #address
  609. self._header.append(struct.pack('<H', net << 8 | subnet << 4 | universe))
  610. self._header = b"".join(self._header)
  611. def send(self,dmx=None,port=''):
  612. if dmx is None:
  613. dmx = self.dmx
  614. else:
  615. self.dmx = dmx
  616. self.head()
  617. c=[self._header]
  618. c.append( struct.pack('>H', len(dmx) ) )
  619. #print([c])
  620. dmx_count = 0
  621. for v in dmx:
  622. if type(v) is not int:
  623. v=0
  624. elif v > 255: # max dmx value 255
  625. v = 255
  626. elif v < 0: # min dmx value 0
  627. v = 0
  628. dmx_count += 1
  629. c.append(struct.pack("B",v))
  630. c = b"".join(c)
  631. if port:
  632. self.s.sendto(c, (self.sendto, port)) # default 6454
  633. else:
  634. self.s.sendto(c, (self.sendto, self.portto)) # default 6454
  635. return c
  636. def _test_frame(self):
  637. if self.test_stamp+0.1 > time.time():
  638. return 0
  639. self.test_stamp = time.time()
  640. dmx = [0]*512
  641. dmx[420] = self.v
  642. self.dmx = dmx
  643. self.next()
  644. #self.send(dmx)
  645. #print( [x] )
  646. if self.v >= 255:
  647. self.d=0
  648. elif self.v <=0:
  649. self.d=1
  650. if self.d:
  651. self.v+=1
  652. else:
  653. self.v-=1
  654. #time.sleep(1/30.)
  655. def next(self):
  656. if self.stamp + (1/60) <= time.time():
  657. self.send()
  658. def artnet_test():
  659. artnet = ArtNetNode()
  660. artnet._tes_frame()
  661. # ============================================================
  662. # helper =====================================================
  663. # ============================================================
  664. class Pager(): #scroll thru list
  665. def __init__(self):
  666. self.data = []
  667. self.index = 0
  668. self.wrap = 0
  669. self.maxindex = 0
  670. def append(self,val):
  671. self.data.append(val)
  672. self.check()
  673. def set(self,nr):
  674. self.index = nr
  675. self.check()
  676. def get(self):
  677. self.check()
  678. if self.data:
  679. return self.data[self.index]
  680. def next(self):
  681. self.index += 1
  682. self.check(flag=1)
  683. def prev(self):
  684. self.index -= 1
  685. self.check(flag=1)
  686. def check(self,flag=0):
  687. if flag:
  688. if self.maxindex and self.maxindex <= len(self.data):
  689. max = self.maxindex
  690. else:
  691. max = len(self.data)
  692. else:
  693. max = len(self.data)
  694. if self.wrap:
  695. if self.index >= max:
  696. self.index = 0
  697. elif self.index < 0:
  698. self.index = max-1
  699. else:
  700. if self.index >= max:
  701. self.index = max-1
  702. elif self.index < 0:
  703. self.index = 0
  704. # ============================================================
  705. # main =======================================================
  706. # ============================================================
  707. class Main():
  708. def __init__(self):
  709. pass
  710. def loop(self):
  711. ohost = HostBuffer()
  712. screen=Manager()
  713. screen.exit()
  714. screen.ohost = ohost
  715. #artnet_out = ArtNetNode(to="10.0.25.255")
  716. artnet_out = ArtNetNode(to=options.sendto)
  717. #artnet_out._test_frame()
  718. if options.testuniv:
  719. artnet = ArtNetNode(univ=options.testuniv)
  720. artnet._test_frame()
  721. ysocket = Socket(bind='127.0.0.1' ,port=6555)
  722. xsocket = Socket()
  723. send_time = time.time()
  724. try:
  725. while 1:
  726. if options.testuniv:
  727. artnet._test_frame()
  728. #artnet_out._test_frame()
  729. if xsocket.poll():
  730. x = xsocket.recive()
  731. if x["host"] == options.recive:
  732. try:
  733. x["univ"] = int(options.inmap )
  734. except TypeError:
  735. pass
  736. ohost.update(x["host"],x["univ"],x["dmx"])
  737. if ysocket.poll():
  738. x = ysocket.recive()
  739. if x["host"] == options.recive:
  740. try:
  741. x["univ"] = int(options.inmap )
  742. except TypeError:
  743. pass
  744. ohost.update(x["host"],x["univ"],x["dmx"])
  745. screen.sel_univ.data = ohost.univs()
  746. screen.sel_host.data = ohost.hosts()
  747. if send_time +(1/30.) < time.time() and options.sendto:
  748. send_time = time.time()
  749. #x=ohost.get(univ=univ2)
  750. info=ohost.info()
  751. jinfo = ""
  752. for i in info:
  753. univ = i
  754. #print( [ univ])
  755. if str(univ) == "54":
  756. break
  757. xl = json.dumps(univ) + "======= " #XX
  758. ltp=ohost.get(univ=i)
  759. #print( xl )
  760. #print( len(ltp) ,ltp[:20])
  761. ltp[511] = int(univ)
  762. artnet_out.univ=int(univ)
  763. artnet_out.send(ltp)
  764. #for j in info[i]:
  765. # print( str(univ)+" " + json.dumps([j,""]) )
  766. # for k in info[i][j]:
  767. # print( str(univ)+ " "+str(k).ljust(5," ")+": " + json.dumps( info[i][j][k]) )
  768. screen.loop()
  769. time.sleep(.001)
  770. finally:
  771. screen.exit()
  772. #print(dir(curses))
  773. if __name__ == "__main__":
  774. main = Main()
  775. main.loop()