_console.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  1. #! /usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. This file is part of LibreLight.
  5. LibreLight is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, version 2 of the License.
  8. LibreLight is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with LibreLight. If not, see <http://www.gnu.org/licenses/>.
  14. (c) 2012 micha@librelight.de
  15. """
  16. import sys
  17. import time
  18. import json
  19. import zlib
  20. rnd_id = ""
  21. rnd_id += " Beta 22.02 "
  22. import subprocess
  23. import tool.git as git
  24. rnd_id += git.get_all()
  25. import lib.binfs as binfs
  26. binfs.fname="/tmp/vmaster.bin"
  27. #binfs.data =[0]*1024
  28. #binfs.patch(self._v_master_id,vm)
  29. binfs.debug = 0
  30. binfs.loop()
  31. if "__file__" in dir():
  32. sys.stdout.write("\x1b]2;"+str(__file__)+" "+rnd_id+"\x07") # terminal title
  33. else:
  34. sys.stdout.write("\x1b]2;"+str("__file__")+" "+rnd_if+"\x07") # terminal title
  35. __run_main = 0
  36. if __name__ == "__main__":
  37. __run_main = 1
  38. else:
  39. import __main__
  40. print(dir())
  41. if "unittest" not in dir(__main__):
  42. __run_main = 1
  43. import time
  44. import socket
  45. import struct
  46. import sys
  47. import random
  48. import math
  49. from collections import OrderedDict
  50. import lib.zchat as chat
  51. import lib.ArtNetNode as ANN
  52. import _thread as thread
  53. #idmx = [0]*512 # incremental dmx
  54. dmx = [0]*512 # absolute dmx data
  55. gcolor = 1
  56. def cprint(*text,color="blue",space=" ",end="\n"):
  57. color = color.lower()
  58. #return 0 #disable print dbg
  59. if not gcolor:
  60. print(text)
  61. return 0
  62. if color == "green":
  63. txt = '\033[92m'
  64. elif color == "red":
  65. txt = '\033[0;31m\033[1m'
  66. elif color == "yellow":
  67. txt = '\033[93m\033[1m'
  68. elif color == "cyan":
  69. txt = '\033[96m'
  70. else:
  71. txt = '\033[94m'
  72. for t in text:
  73. txt += str(t ) +" "
  74. #HEADER = '\033[95m'
  75. #OKBLUE = '\033[94m'
  76. #OKCYAN = '\033[96m'
  77. #OKGREEN = '\033[92m'
  78. #WARNING = '\033[93m'
  79. #FAIL = '\033[91m'
  80. #ENDC = '\033[0m'
  81. #BOLD = '\033[1m'
  82. #UNDERLINE = '\033[4m'
  83. txt += '\033[0m'
  84. print(txt,end=end)
  85. #return txt
  86. def artnet_loop(single=0):
  87. #artnet = ANN.ArtNetNode(to="127.0.0.1",port=6555,univ=12)
  88. #artnet = ANN.ArtNetNode(to="127.0.0.1",port=6555,univ=0)
  89. artnet = ANN.ArtNetNode(to="10.10.10.255",univ=0)
  90. #artnet = ANN.ArtNetNode(to="2.0.0.255",univ=0)
  91. #artnet = ANN.ArtNetNode(to="10.10.10.255",univ=1)
  92. #dmx[205] = 255 #205 BLUE
  93. artnet.dmx= dmx #[0]*512
  94. artnet.send()
  95. while 1:
  96. #artnet._test_frame()
  97. artnet.next()
  98. time.sleep(0.001)
  99. if single:
  100. break
  101. class CLOCK():
  102. def __init__(self):
  103. self.__time = 0
  104. self.__start = time.time() # only for debugging
  105. self.__tick = 0.01 # incremental timer drift's on highe cpu load ?
  106. def time(self):
  107. return self.__time
  108. def get_drift(self):
  109. run_time = time.time() - self.__start
  110. tick_time = self.__time # * self.__tick
  111. print( "runtime:{:0.2f} tick_timer:{:0.2f} drift:{:0.2f}".format(run_time,tick_time,run_time-tick_time))
  112. def loop(self):
  113. while 1:
  114. self.__time +=self.__tick
  115. #if int(self.__time*100)/10. % 10 == 0:# self.__time % 2 == 0:
  116. # print( self.get_drift())
  117. #print(self.__time)
  118. #for i in range(10):
  119. time.sleep(self.__tick)
  120. class CLOCK_REAL():
  121. def __init__(self):
  122. self.__time = 0
  123. self.__start = time.time() # only for debugging
  124. self.__tick = 0.001 # incremental timer drift's on highe cpu load ?
  125. def time(self):
  126. self.__time = time.time()
  127. return self.__time
  128. def get_drift(self):
  129. run_time = time.time() - self.__start
  130. tick_time = self.__time # * self.__tick
  131. print( "runtime:{:0.2f} tick_timer:{:0.2f} drift:{:0.2f}".format(run_time,tick_time,run_time-tick_time))
  132. def loop(self):
  133. pass
  134. #clock = CLOCK()
  135. clock = CLOCK_REAL()
  136. if __run_main:
  137. thread.start_new_thread(clock.loop,())
  138. class Fade():
  139. def __init__(self,start,target,ftime,clock,delay=0):
  140. #print("init Fade ",start,target,ftime,clock)
  141. if delay < 0:
  142. delay = 0.0001
  143. if ftime <= 0:
  144. ftime = 0.0001
  145. clock += delay
  146. self.__delay = delay
  147. self.__clock = clock
  148. self.__clock_curr = clock
  149. self.__ftime = ftime
  150. self.__start = start
  151. self.__last = start
  152. self.__target = target
  153. self.abs = 0
  154. self.run = 1
  155. self.end = 0
  156. self.off = 0
  157. #print("INIT", str(self) )
  158. def __str__(self):
  159. return self.__repr__()
  160. def __repr__(self):
  161. return "<FADE Next:{:0.2f} from:{:0.2f} to:{:0.2f} ft:{:0.2f} Clock:{:0.2f} run:{} delay:{:0.2f}>".format(
  162. self.__last, self.__start,self.__target,self.__ftime,self.__clock_curr,self.run,self.__delay )
  163. def next(self,clock=None):
  164. if self.__ftime <= 0 and self.__delay <= 0:
  165. self.__last = self.__target
  166. self.end = 1
  167. self.run = 0
  168. if type(clock) is float or type(clock) is int:#not None:
  169. self.__clock_curr = clock
  170. if self.__target > self.__start:
  171. if self.__last >= self.__target:
  172. self.run = 0
  173. self.end = 1
  174. return self.__target
  175. else:
  176. if self.__last <= self.__target:
  177. self.run = 0
  178. self.end = 1
  179. return self.__target
  180. current = (self.__clock - self.__clock_curr) / self.__ftime
  181. length = self.__start - self.__target
  182. self.__last = self.__start+ length*current
  183. self.run = 1
  184. return self.__last
  185. def ctl(self,cmd="",value=None): # if x-fade cmd="%" value=50
  186. pass
  187. class _MASTER():
  188. def __init__(self,name="None"):
  189. self.__data = {}
  190. self.name = name
  191. def val(self,name,value=None):
  192. _value = 100 #%
  193. name = str(name)
  194. if name not in self.__data:
  195. self.__data[name] = 100
  196. _value = self.__data[name]
  197. if value is not None:
  198. if _value != value:
  199. print(self.name,"CHANGE MASTER:",name,"from:",_value,"to:",value)
  200. self.__data[name] = value
  201. _value = self.__data[name]
  202. return _value /100.
  203. exec_size_master = _MASTER("EXEC-SIZE")
  204. exec_speed_master = _MASTER("EXEC-SPEED")
  205. exec_offset_master = _MASTER("EXEC-OFFSET")
  206. size_master = _MASTER("SIZE")
  207. speed_master = _MASTER("SPEED")
  208. exe_master = []
  209. exe_master.append({"SIZE":100,"SPEED":100,"id":12,"link-ids":[2]})
  210. class MASTER_FX():
  211. def __init__(self):
  212. self.__data = []
  213. self.__ok = []
  214. self.i=0
  215. self.old_offsets = []
  216. self.offsets = []
  217. self.count = -1
  218. self.init = 10
  219. def add(self,fx):
  220. if fx not in self.__data:
  221. self.__data.append(fx)
  222. info = fx._get_info()
  223. offset = 0
  224. if "offset" in info:
  225. offset = info["offset"]
  226. self.old_offsets.append(offset)
  227. self.offsets.append(offset)
  228. if "xtype" in info:
  229. if info["xtype"] == "rnd":
  230. self._shuffle()
  231. def _shuffle(self):
  232. random.seed(1000)
  233. random.shuffle(self.old_offsets)
  234. def _init(self):
  235. self._shuffle()
  236. for i,_ in enumerate(self.old_offsets):
  237. offset = self.old_offsets[i]
  238. self.offsets[i] = offset
  239. self.init = 0
  240. def next(self,child):
  241. i = self.__data.index(child)
  242. offset = self.old_offsets[i]
  243. self.offsets[i] = offset
  244. return offset
  245. def get(self,child,count):
  246. offset = 0
  247. if child not in self.__data:
  248. return offset
  249. if self.init:
  250. self._init()
  251. idx = self.__data.index(child)
  252. if (self.count != count and idx == 0 ) or self.init == 0:
  253. self.init = 1
  254. self._shuffle()
  255. self.count=count
  256. idx = self.__data.index(child)
  257. offset = self.offsets[idx]
  258. return offset
  259. class FX():
  260. def __init__(self,xtype="sinus",size=10,speed=10,invert=0,width=100,start=0,offset=0,base="",clock=0,master=None,master_id=0):
  261. self.__xtype=xtype
  262. self.__size = size
  263. self.__start = start
  264. self.__master_id = master_id
  265. if width > 200:
  266. width = 200
  267. if width <= 0:
  268. width = 1
  269. self.__fade_in_master = 0
  270. self.__width = width
  271. self.__invert = invert
  272. self.__base = base
  273. self.__speed = speed
  274. self.__offset = offset
  275. self.__clock = clock
  276. self.__clock_curr = clock
  277. self.__clock_delta = 0
  278. self.__clock_old = self.__clock_curr
  279. self.out = 0
  280. self.old_v = -1
  281. self.run = 1
  282. self.count = -1
  283. self.abs = 0 # ABSOLUT
  284. self.__angel = self.__clock_curr*360%360
  285. if master is None:
  286. cprint(master, "MASTER_FX ERR",master,color="red")
  287. self.__master = MASTER_FX()
  288. self.__master.add(self)
  289. else:
  290. self.__master = master
  291. self.__master.add(self)
  292. if self.__xtype == "rnd":
  293. self.__offset = self.__master.get(self,-2)
  294. self.__offset = self.__master.next(self)#,count)
  295. self._exec_id = None
  296. self.next()
  297. def exec_id(self,_id=None):
  298. if type(_id) is not type(None):
  299. self._exec_id = str(_id)
  300. return self._exec_id
  301. def _get_info(self):
  302. return {"offset":self.__offset,"xtype":self.__xtype}
  303. def __str__(self):
  304. return self.__repr__()
  305. def __repr__(self):
  306. ABS = "INC"
  307. if self.abs:
  308. ABS = "ABS"
  309. return "<FX Next:{:0.2f} xtype:{} Size:{:0.2f} Speed:{:0.2f} ang:{:0.2f} base:{} Clock:{:0.2f} run:{} EXEC:{} :{}>".format(
  310. self.next(), self.__xtype, self.__size, self.__speed, self.__angel
  311. , self.__base, self.__clock_curr, self.run, self._exec_id,ABS )
  312. def _calc_fx(self,v,t,size,base):
  313. base = 0
  314. if self.__base == "-": # sub
  315. if self.__invert:
  316. v = 1-v
  317. size *=-1
  318. v *=-1
  319. elif self.__base == "+": # sub
  320. if self.__invert:
  321. v = v-1
  322. else:
  323. v = (t%1-0.5)
  324. return v
  325. def next(self,clock=None):
  326. if type(clock) is float or type(clock) is int:#not None:
  327. self.__clock_curr = clock
  328. d = (self.__clock_curr - self.__clock_old)
  329. m1 = ( speed_master.val(self.__master_id)) # global speed-master
  330. m2 = ( exec_speed_master.val(self._exec_id)) # exec start by 0
  331. shift = 0
  332. m = (m1 * m2) -1
  333. shift += d * m
  334. self.__clock_delta += shift
  335. self.__clock_old = self.__clock_curr
  336. t = self.__clock_curr
  337. t += self.__clock_delta
  338. t *= self.__speed / 60
  339. offset2 = self.__offset
  340. offset2 *= exec_offset_master.val(self._exec_id)
  341. t += offset2 / 100
  342. t += self.__start / 200 # 1024 #255
  343. tw = t%1
  344. count = t//1
  345. t = t * (100/self.__width)
  346. if tw > self.__width/100:
  347. t = 1
  348. self.__angel = t%1*360
  349. t = t%1
  350. rad = math.radians(self.__angel)
  351. self.abs = 0
  352. v=0
  353. out = 0
  354. base = 0
  355. size = self.__size
  356. if self.__base == "+": # add
  357. base = size/2
  358. elif self.__base == "-": # sub
  359. base = size/2*-1
  360. if self.__xtype == "sinus":
  361. v = math.sin( rad )
  362. v/=2
  363. elif self.__xtype == "cosinus":
  364. v = math.cos( rad )
  365. if self.__base == "+": # add
  366. size *= -1
  367. v/=2
  368. elif self.__xtype == "rnd":
  369. #base = 0
  370. if self.__angel > 90 and self.__angel <=270:
  371. v=1
  372. else:
  373. v=0
  374. #if count != self.count and v: # % 2 == 0:#!= self.count:
  375. # #self.__offset = random.randint(0,1024)# /1024
  376. # self.__master._shuffle()
  377. if count != self.count and v == 0: # and v: # % 2 == 0:#!= self.count:
  378. self.__master.next(self)#,count)
  379. #self.__master.next(self)#,count)
  380. self.__offset = self.__master.get(self,count)
  381. base = 0
  382. if self.__base == "-": # sub
  383. if self.__invert:
  384. v = 1-v
  385. #base = -size
  386. size *=-1
  387. v *=-1
  388. elif self.__base == "+": # sub
  389. if self.__invert:
  390. v = v-1
  391. else:
  392. v = (t%1-0.5)
  393. elif self.__xtype == "on":
  394. #base = 0
  395. #if self.__angel > 90 and self.__angel <=270:
  396. if self.__angel > 0 and self.__angel <=360:
  397. v=1
  398. else:
  399. v=0
  400. base = 0
  401. if self.__base == "-": # sub
  402. if self.__invert:
  403. v = 1-v
  404. #base = -size
  405. size *=-1
  406. v *=-1
  407. elif self.__base == "+": # sub
  408. if self.__invert:
  409. v = v-1
  410. else:
  411. v = (t%1-0.5)
  412. elif self.__xtype == "ramp" or self.__xtype == "bump":
  413. v = (t%1)
  414. base = 0
  415. if self.__base == "-": # sub
  416. if self.__invert:
  417. v = 1-v
  418. #base = -size
  419. size *=-1
  420. v *=-1
  421. elif self.__base == "+": # sub
  422. if self.__invert:
  423. v = v-1
  424. else:
  425. v = (t%1-0.5)
  426. elif self.__xtype == "ramp2" or self.__xtype == "bump2":
  427. v = (t%1)
  428. v = 1-v
  429. if v == 1:
  430. v=0
  431. base = 0
  432. if self.__base == "-": # sub
  433. if self.__invert:
  434. v = 1-v
  435. #base = -size
  436. size *=-1
  437. v *=-1
  438. elif self.__base == "+": # sub
  439. if self.__invert:
  440. v = v-1
  441. else:
  442. v = (t%1-0.5)
  443. elif self.__xtype == "static":
  444. self.abs = 1
  445. base = size #100
  446. v=0
  447. size=0
  448. elif self.__xtype == "fade":
  449. x = t * 2
  450. if x > 1:
  451. x = 2-x
  452. x -= 0.5
  453. v = x*2
  454. #base /= 2
  455. #base *=2
  456. if self.__base == "+": # add
  457. pass#base /= 2
  458. else:
  459. v *= -1
  460. v/=2
  461. if self.__invert:
  462. v *=-1
  463. #if self.__fade_in_master < 255:
  464. # self.__fade_in_master += v*size
  465. out = v *size +base
  466. self.out = out
  467. self.count = count
  468. out = out * size_master.val(self.__master_id) # master
  469. out = out * exec_size_master.val(self._exec_id) # master
  470. #* (self.__fade_in_master /255.)
  471. return out
  472. class DMXCH(object):
  473. def __init__(self,dmx=-1):
  474. self._base_value = 0
  475. self._fade = None
  476. self._fx = [None,None] # None
  477. self._fx_value = 0
  478. self.name = "<name>"
  479. self._dmx = dmx
  480. self._dmx_fine = 0
  481. self._fix_id = 0
  482. self._v_master_id=0
  483. self._last_val_raw=0
  484. self._flash = None
  485. self._flash_fx = None
  486. self._flash_fx_value = 0
  487. self._last_val = None
  488. self._exec_ids = [None,None,None,None] # go, go-fx, flash, flash-fx
  489. def fade(self,target,ftime=0,clock=0,delay=0):
  490. if target != self._base_value:
  491. try:
  492. target = float(target)
  493. self._fade = Fade(self._base_value,target,ftime=ftime,clock=clock,delay=delay)
  494. except Exception as e:
  495. print( "Except:fade",e,target,ftime,clock)
  496. self.next(clock)
  497. def fx(self,xtype="sinus",size=40,speed=40,invert=0,width=100,start=0,offset=0,base="", clock=0,master=None):
  498. self._fx[0] = self._fx[1]
  499. if str(xtype).lower() == "off":
  500. fx_value = self._fx_value
  501. if fx_value != 0:
  502. #cprint("???????______ FX OFF AS FADE",fx_value,0,255)
  503. if self._fx[1].abs:
  504. self._fx[1] = Fade(self._last_val_raw,0,ftime=0.5,clock=clock)
  505. else:
  506. self._fx[1] = Fade(fx_value,0,ftime=0.5,clock=clock)
  507. else:
  508. self._fx[1] = None
  509. self._fx_value = 0
  510. else:
  511. self._fx[1] = FX(xtype=xtype,size=size,speed=speed,invert=invert
  512. ,width=width,start=start,offset=offset,base=base
  513. ,clock=clock,master=master,master_id=1)
  514. self._fx[1].exec_id(self._exec_ids[1])
  515. self.next(clock)
  516. def flash(self,target,ftime=0,clock=0,delay=0):
  517. if str(target).lower() == "off":
  518. if self._flash:
  519. cur_val = self._flash.next()
  520. cur_tar = self._base_value
  521. self._flash = Fade(cur_val,cur_tar,ftime=ftime,clock=clock)
  522. self._flash.off = 1
  523. else:
  524. try:
  525. target = float(target)
  526. self._flash = Fade(self._last_val,target,ftime=ftime,clock=clock,delay=delay)
  527. self._flash = Fade(self._last_val,target,ftime=0,clock=clock,delay=delay)
  528. except Exception as e:
  529. print( "Except:flash",target,ftime,clock,__name__,e,)
  530. self.next(clock)
  531. def flash_fx(self,xtype="sinus",size=40,speed=40,invert=0,width=100,start=0,offset=0,base="",clock=0,master=None):
  532. if str(xtype).lower() == "off":
  533. self._flash_fx = None
  534. self._flash_fx_value = 0
  535. else:
  536. self._flash_fx = FX(xtype=xtype,size=size,speed=speed,invert=invert
  537. ,width=width,start=start,offset=offset,base=base
  538. ,clock=clock,master=master,master_id=0)
  539. self._flash_fx.exec_id(self._exec_ids[3])
  540. self.next(clock)
  541. #print("init flash_fx",self)
  542. def fx_ctl(self,cmd=""): #start,stop,off
  543. pass
  544. def __str__(self):
  545. return self.__repr__()
  546. def exec_ids(self,_id=None):
  547. #if type(_id) is not type(None):
  548. # #self._exec_id = _id
  549. # #print("set exec_id",_id)
  550. return self._exec_ids
  551. def __repr__(self):
  552. v = self._last_val
  553. if type(self._last_val) in [int,float]:
  554. v = round(self._last_val,2)
  555. return "<DMXCH {} DMX:{} FINE:{} VAL:{} EXEC:{}\n fd:{}\n fx:{}\n fx_flash:{}\n".format(
  556. self.name,
  557. self._dmx,self._dmx_fine
  558. ,v,str(self._exec_ids)
  559. ,self._fade
  560. ,self._fx
  561. ,self._flash_fx)
  562. def fade_ctl(self,cmd=""): #start,stop,backw,fwd,bounce
  563. pass
  564. def next(self,clock=0):
  565. try:
  566. self._next(clock)
  567. except Exception as e:
  568. cprint("Exception DMXCH.next()" ,e)
  569. out = self._last_val
  570. return out
  571. def _next(self,clock=0):
  572. value = self._base_value
  573. if self._last_val is None:
  574. self._last_val = value
  575. fx_value = self._fx_value
  576. fx_abs = 0
  577. if self._flash is not None:
  578. value = self._flash.next(clock)
  579. value = self._flash.next(clock) #flicker bug ?!
  580. if self._flash.end == 1 and self._flash.off == 1:
  581. self._flash = None
  582. fx_value = 0
  583. elif self._fade is not None: # is Fade: # is Fade:
  584. self._base_value = self._fade.next(clock)
  585. self._base_value = self._fade.next(clock) #flicker bug ?!
  586. value = self._base_value
  587. if self._flash_fx is not None:# is FX:
  588. fx_value = self._flash_fx.next(clock)
  589. fx_abs = self._flash_fx.abs
  590. else:
  591. self._fx_value = 0
  592. if self._fx[-1] is not None and self._flash is None:# is FX:
  593. self._fx_value += self._fx[-1].next(clock)
  594. fx_abs = self._fx[-1].abs
  595. fx_value = self._fx_value
  596. if fx_abs == 1:
  597. self._last_val = fx_value
  598. else:
  599. self._last_val = value + fx_value
  600. self._last_val_raw = self._last_val
  601. if self._v_master_id in V_MASTER:
  602. vm = V_MASTER[self._v_master_id].next(clock)
  603. #binfs.patch(self._v_master_id,int(vm))
  604. binfs.buffer(self._v_master_id,int(vm))
  605. vm = vm/256
  606. self._last_val *= vm
  607. out = self._last_val
  608. return out
  609. V_MASTER = {} #DMXCH
  610. Bdmx = []
  611. for i in range(512*7+1):
  612. xDMX = DMXCH(i)
  613. xDMX.name = "543"+str(i)
  614. Bdmx.append(xDMX)
  615. #print(type(dmx[i]))
  616. _id = 1
  617. def split_cmd(data):
  618. if "cmd" in data:
  619. cmd = data["cmd"]
  620. #print("cmd",cmd)
  621. if "," in cmd:
  622. cmds = cmd.split(",")
  623. else:
  624. cmds = [cmd]
  625. return cmds
  626. class VDMX():
  627. """functional implementation as class for namespace encapsulation
  628. """
  629. def __init__(self):
  630. self.data = OrderedDict()
  631. self.data[4] = {"DMX":[21,22,23],"VALUE":255, "LIMIT":255} #,"DMXCH":DMXCH("V4")}
  632. def _list_by_dmx(self,_dmx=0):
  633. data = OrderedDict()
  634. for i,link in self.data.items(): # enumerate(self.data):
  635. if _dmx in link["DMX"]:
  636. #print( "_list_by_dmx",i,link)
  637. data[i] = link
  638. return data
  639. def dmx_by_id(self,_id=0):
  640. #print("dmx by master-id:",_id)
  641. if _id in self.data:
  642. for i,link in self.data[_id].items():
  643. #print("dmx_by_id", i,link)
  644. return (i,link)
  645. return 0,{}
  646. def by_dmx(self,clock,dmx):
  647. #print("master of dmx:",dmx)
  648. val=0
  649. flag = 0
  650. data = self._list_by_dmx(dmx)
  651. for i,row in data.items():
  652. if "DMXCH" not in row:
  653. row["DMXCH"] = DMXCH("V{}".format(i))
  654. row["DMXCH"].fade(255,0)
  655. v = row["DMXCH"].next(clock)
  656. #row["DMXCH"].fade(200,20)
  657. if v >= val:
  658. val = v
  659. flag = 1
  660. out = 1.
  661. if val > 255:
  662. val = 255
  663. if flag:
  664. out = val/255.
  665. else:
  666. out = 1.
  667. return out
  668. vdmx = VDMX()
  669. class HTP_MASTER():
  670. """functional implementation as class for namespace encapsulation
  671. """
  672. def __init__(self):
  673. self.data = OrderedDict()
  674. #self.data[1] = {"DMX":[1,2,3],"VALUE":80, "LIMIT":255}
  675. #self.data[2] = {"DMX":[12,13,22],"VALUE":70, "LIMIT":255}
  676. #self.data[3] = {"DMX":[22,23,24],"VALUE":99, "LIMIT":255}
  677. self.data[4] = {"DMX":[22,23,24],"VALUE":99, "LIMIT":255,"DMXCH":DMXCH(4)}
  678. def _list_by_dmx(self,_dmx=0):
  679. data = OrderedDict()
  680. for i,link in self.data.items(): # enumerate(self.data):
  681. if _dmx in link["DMX"]:
  682. #print( "_list_by_dmx",i,link)
  683. data[i] = link
  684. return data
  685. def dmx_by_id(self,_id=0):
  686. #print("dmx by master-id:",_id)
  687. if _id in self.data:
  688. for i,link in self.data[_id].items():
  689. #print("dmx_by_id", i,link)
  690. return (i,link)
  691. return 0,{}
  692. def val_by_dmx(self,dmx=0):
  693. #print("master of dmx:",dmx)
  694. val=0
  695. flag = 0
  696. data = self._list_by_dmx(dmx)
  697. for _,link in data.items():
  698. #print("master_by_dmx", i,link)
  699. if link["VALUE"] > val:
  700. #print("master_by_dmx", i,link)
  701. val = link["VALUE"]
  702. flag=1
  703. out = 1.
  704. if flag:
  705. out = val/255.
  706. return out
  707. htp_master = HTP_MASTER()
  708. #htp_master.data[_id] = {"DMX":[1,2,3],"VALUE":80, "LIMIT":255,"DMXCH":DMXCH()}
  709. class Core():
  710. def __init__(self):
  711. self.artnet = {}
  712. self.fx = {} # key is dmx address
  713. self.lock = thread.allocate_lock()
  714. def _fine_loop(self,Bdmx,t):
  715. old_univ = -1
  716. xx = [0]*512
  717. for ii,dmxch in enumerate(Bdmx): #fine loop
  718. dmx_fine = dmxch._dmx_fine
  719. if dmx_fine > 0:
  720. i = ii%512
  721. univ = ii//512
  722. if univ != old_univ:
  723. artnet = self.artnet[str(univ)]
  724. xx = artnet.dmx# = xx
  725. v = dmxch.next(t)
  726. vv = vdmx.by_dmx(clock=i,dmx=ii+1)
  727. try:
  728. v = v*vv # disable v-master
  729. except Exception as e:
  730. cprint("Exception v*vv",[v,vv],e)
  731. continue
  732. dmx_fine = dmx_fine%512
  733. try:
  734. if v >= 255:
  735. xx[dmx_fine-1] = 255
  736. elif v < 0:
  737. xx[dmx_fine-1] = 0
  738. else:
  739. xx[dmx_fine-1] = int(v%1*255)
  740. except Exception as e:
  741. print("E dmx_fine",e,dmx_fine)
  742. def _coarse_loop(self,Bdmx,t):
  743. old_univ = -1
  744. xx = [0]*512
  745. for ii,dmxch in enumerate(Bdmx):
  746. i = ii%512
  747. univ = ii//512
  748. if univ != old_univ:
  749. old_univ = univ
  750. artnet = self.artnet[str(univ)]
  751. xx = artnet.dmx
  752. v = dmxch.next(t)
  753. xx[i] = int(v)
  754. def artnete_init(self,Bdmx):
  755. """Init artnet if not exist's
  756. """
  757. for ii,_ in enumerate(Bdmx):
  758. univ = ii//512
  759. if str(univ) not in self.artnet:
  760. print("add uiv",univ)
  761. self.artnet[str(univ)] = ANN.ArtNetNode(to="10.10.10.255",univ=univ)
  762. def calc_fps(self,stop_fps=50):
  763. self.fps += 1
  764. if self.fps >= stop_fps:
  765. fps_t = time.time()
  766. FPS = round(stop_fps/(fps_t-self.fps_start),2)
  767. print("{:0.0f} core/fps".format(FPS) )
  768. self.fps = 0
  769. self.fps_start = time.time()
  770. def loop(self):
  771. """ core artnet calculation loop
  772. """
  773. self.artnete_init(Bdmx)
  774. self.fps_start = time.time()
  775. self.fps = 0
  776. while 1:
  777. self.lock.acquire_lock()
  778. self.artnete_init(Bdmx)
  779. t = clock.time()
  780. self._coarse_loop(Bdmx,t)
  781. self._fine_loop(Bdmx,t)
  782. self.lock.release_lock()
  783. for _,artnet in self.artnet.items():
  784. artnet.next()
  785. time.sleep(1/30)
  786. self.calc_fps()
  787. core = Core()
  788. if __run_main:
  789. thread.start_new_thread(core.loop,())
  790. def _init_action(row):#Bdmx,out,DMX):
  791. Admx = row["DMXCH"]
  792. line_sub_count = 0
  793. if row["fx"]:
  794. x = row["fx"]
  795. Admx.fx(xtype=x["xtype"]
  796. ,size=x["size"]
  797. ,speed=x["speed"]
  798. ,invert=x["invert"]
  799. ,width=x["width"]
  800. ,start=x["start"]
  801. ,offset=x["offset"]
  802. ,base=x["base"]
  803. ,clock=x["clock"]
  804. ,master=x["master"])
  805. line_sub_count += 1
  806. if row["flash_fx"]:
  807. x = row["flash_fx"]
  808. Admx.flash_fx(xtype=x["xtype"]
  809. ,size=x["size"]
  810. ,speed=x["speed"]
  811. ,invert=x["invert"]
  812. ,width=x["width"]
  813. ,start=x["start"]
  814. ,offset=x["offset"]
  815. ,base=x["base"]
  816. ,clock=x["clock"]
  817. ,master=x["master"])
  818. line_sub_count += 1
  819. if row["flash"]:
  820. x = row["flash"]
  821. Admx.flash(target=x["target"]
  822. ,ftime=x["ftime"]
  823. ,clock=x["clock"]
  824. ,delay=x["delay"])
  825. line_sub_count += 1
  826. if row["fade"]:
  827. x = row["fade"]
  828. Admx.fade(target=x["target"]
  829. ,ftime=x["ftime"]
  830. ,clock=x["clock"]
  831. ,delay=x["delay"])
  832. line_sub_count += 1
  833. return line_sub_count
  834. def set_dmx_fine_ch(Admx,dmx_fine_nr):
  835. try:
  836. if int(dmx_fine_nr) > 0:
  837. Admx._dmx_fine = int(dmx_fine_nr)
  838. except Exception as e:
  839. cprint(x,color="red")
  840. cprint("except 3455",e,color="red")
  841. def _parse_fx2(x,fx2,clock):
  842. if type(fx2) is dict and fx2:
  843. pass
  844. else:
  845. return
  846. xtype="fade"
  847. size = 10
  848. speed = 10
  849. start = 0
  850. offset= 0
  851. width=100
  852. invert=0
  853. base = "-"
  854. if "TYPE" in fx2:
  855. xtype = fx2["TYPE"]
  856. if "SIZE" in fx2:
  857. size = fx2["SIZE"]
  858. if "SPEED" in fx2:
  859. speed = fx2["SPEED"]
  860. if "OFFSET" in fx2:
  861. offset = fx2["OFFSET"]
  862. if "BASE" in fx2:
  863. base = fx2["BASE"]
  864. if "INVERT" in fx2:
  865. invert = fx2["INVERT"]
  866. if "WIDTH" in fx2:
  867. width = fx2["WIDTH"]
  868. if "START" in fx2:
  869. start = fx2["START"]
  870. if "off" == x["VALUE"]: #fix fx flash off
  871. xtype= "off"
  872. if "alloff" == xtype.lower():
  873. for dmxch in Bdmx:
  874. if dmxch is not None:
  875. dmxch.flash_fx(xtype="off",clock=clock)
  876. dmxch.fx(xtype="off",clock=clock)
  877. for j in V_MASTER:
  878. dmxch = V_MASTER[j]
  879. if j is not None:
  880. dmxch.flash_fx(xtype="off",clock=clock)
  881. dmxch.fx(xtype="off",clock=clock)
  882. xout = {"xtype":xtype,"size":size,"speed":speed
  883. ,"invert":invert,"width":width,"start":start
  884. ,"offset":offset,"base":base,"clock":clock,"master":0
  885. }
  886. #,"offset":offset,"base":base,"clock":c,"master":master_fx
  887. mode="fx"
  888. if "FLASH" in x:
  889. mode = "flash_fx"
  890. return [mode,xout]
  891. def _parse_master(x):
  892. print("CMD:",x)
  893. if "EXEC-SPEED-MASTER" == x["CMD"]:
  894. exec_speed_master.val(x["NR"],x["VALUE"])
  895. if "EXEC-SIZE-MASTER" == x["CMD"]:
  896. exec_size_master.val(x["NR"],x["VALUE"])
  897. if "EXEC-OFFSET-MASTER" == x["CMD"]:
  898. exec_offset_master.val(x["NR"],x["VALUE"])
  899. if "SPEED-MASTER" == x["CMD"]:
  900. speed_master.val(x["NR"],x["VALUE"])
  901. if "SIZE-MASTER" == x["CMD"]:
  902. size_master.val(x["NR"],x["VALUE"])
  903. def _check_vmaster(DMX,attr):
  904. if DMX <= 0 and "DIM" == attr:
  905. return True
  906. def _get_vmaster(_fix_id,attr):
  907. if _fix_id not in V_MASTER:
  908. print(" VMASTER init",_fix_id)
  909. V_MASTER[_fix_id] = DMXCH()
  910. V_MASTER[_fix_id].name = "vmaster_"+str(_fix_id)
  911. Admx = V_MASTER[_fix_id]
  912. return Admx
  913. def _get_dmx(DMX,Bdmx):
  914. if DMX < len(Bdmx):
  915. Admx = Bdmx[DMX-1]
  916. else:
  917. Admx = DMXCH() #dummy
  918. Admx.name = "get-dmx-dummy"
  919. print("DMX ADDRESS too BIG",DMX)
  920. return Admx
  921. def _parse_cmds(cmds,clock=0):
  922. out = {}
  923. for cmd in cmds:
  924. try:
  925. _parse_cmd(out,cmd,clock=clock)
  926. except Exception as e:
  927. cprint("EXCEPTION JCB",e,color="red")
  928. cprint("----",str(cmds)[:150],"...",color="red")
  929. cprint("Error on line {}".format(sys.exc_info()[-1].tb_lineno),color="red")
  930. raise e
  931. return out
  932. def _check_cmd(cmd):
  933. err=0
  934. if not isinstance(cmd,dict):
  935. cprint("_check_cmd() ... cmd is not dict !",type(cmd),color="red")
  936. err=1
  937. #if "DMX" not in cmd:
  938. # cprint("_check_cmd() ... 'DMX' not in x!",color="red")
  939. # #err=1
  940. if "VALUE" not in cmd:
  941. cprint("_check_cmd() ... 'VALUE' not in x!",color="red")
  942. err=1
  943. if err:
  944. return
  945. return True
  946. def _parse_cmd(out,cmd,clock=0):
  947. if not isinstance(out,dict):
  948. cprint("_parse_cmd() ... out !",type(out),color="red")
  949. return
  950. if not _check_cmd(cmd):
  951. return
  952. if "CMD" in cmd:
  953. _parse_master(cmd)
  954. return
  955. master_fx = MASTER_FX()
  956. c=clock
  957. DMX = cmd.get("DMX",0)
  958. DMX = int(DMX)
  959. exec_id = cmd.get("EXEC",None)
  960. _fix_id = cmd.get("FIX",0)
  961. _attr = cmd.get("ATTR","")
  962. _clock = cmd.get("clock",0)
  963. _val = cmd.get("VALUE","")
  964. _inc = cmd.get("INC",0)
  965. fx = cmd.get("FX","")
  966. fx2 = cmd.get("FX2",{})
  967. ftime = cmd.get("FADE",0)
  968. delay = cmd.get("DELAY",0)
  969. #print("cmd",cmd)
  970. Admx = _get_dmx(DMX,Bdmx)
  971. if _check_vmaster(DMX,_attr):
  972. Admx = _get_vmaster(_fix_id,_attr)
  973. DMX = "FIX"+str(_fix_id)
  974. DMX_FINE = cmd.get("DMX-FINE",-1)
  975. if DMX_FINE > 0:
  976. set_dmx_fine_ch(Admx, DMX_FINE)
  977. ids = Admx.exec_ids()
  978. if _val != "off":
  979. if "FLASH" in cmd:
  980. if type(_val) is int:
  981. ids[2] = exec_id
  982. if fx2:
  983. ids[3] = exec_id
  984. #print(" ",[ids, exec_id],"FL")
  985. else: # GO or ON
  986. if type(_val) is int:
  987. ids[0] = exec_id
  988. if fx2:
  989. ids[1] = exec_id
  990. #print(" ",[ids, exec_id],"GO")
  991. if _val == "off":
  992. # flash bug if lot's of virtual dimmer are RELEASED-FROM-FLASH ("FLASH off")
  993. # the V-MASTER FLASH ist HANGING ... no ENCODER change possible !!! ???
  994. if 0: # "FLASH" in cmd:
  995. stop = 0
  996. #print(" ",[ids, exec_id])
  997. if ids[2] != exec_id:
  998. stop = 1
  999. else:
  1000. ids[2] = None
  1001. if fx2:
  1002. if ids[3] != exec_id:
  1003. stop = 1
  1004. else:
  1005. ids[3] = None
  1006. stop = 0
  1007. if stop:
  1008. # this FLASH cmd OFF/RELEASE is not valid anymore
  1009. return #continue
  1010. out[DMX] = {"flash":{},"fade":{},"fx":{},"flash_fx":{},"fix_id":_fix_id,"attr":_attr,"DMXCH":Admx}
  1011. if _val is not None:
  1012. Xval = {"target":_val,"ftime":ftime, "clock":c,"delay":delay,"DMXCH":Admx}
  1013. mode = "fade"
  1014. if "FLASH" in cmd:
  1015. mode = "flash"
  1016. out[DMX][mode] = Xval
  1017. # FX PARSE
  1018. _fx2 = _parse_fx2(cmd,fx2,clock=c)
  1019. if _fx2:
  1020. _key=_fx2[0] # fx, fx_flash
  1021. Xval=_fx2[1] # dict
  1022. Xval["master"] = master_fx
  1023. out[DMX][_key] = Xval
  1024. elif type(fx) is str and fx:
  1025. # old fx like sinus:200:12:244
  1026. ccm = str(DMX+1)+":"+fx
  1027. print("fx",ccm)
  1028. if "FLASH" in cmd:
  1029. pass #CB({"cmd":"fxf"+ccm})
  1030. else:
  1031. pass #CB({"cmd":"fx"+ccm})
  1032. def calc_jitter(jdatas,t_start):
  1033. for cmds in jdatas:
  1034. for line in cmds:
  1035. if "time" in line:
  1036. jt_start = line["time"]
  1037. latenz = round(t_start-jt_start,4)
  1038. if latenz > 0.5:
  1039. cprint("jitter 0.5 >",latenz,color="red")
  1040. break
  1041. def process_flash(jdatas):
  1042. for cmds in jdatas:
  1043. for line in cmds: # run first
  1044. if "FLASH" in line:
  1045. cprint("FLUSH",end=" ",color="CYAN")
  1046. if "VALUE" in line:
  1047. if line["VALUE"] == "off":
  1048. cprint("OFF",end=" ",color="red")
  1049. else:
  1050. cprint("ON",end=" ",color="green")
  1051. print("")
  1052. else:
  1053. cprint("FADE",color="CYAN")
  1054. break
  1055. def parse_json(data):
  1056. jdatas = []
  1057. l2 = 0
  1058. print("INPUT JCB =>",len(data),":",l2)
  1059. for line in data:
  1060. data2 = json.loads(line)
  1061. l2 += len(data2)
  1062. jdatas.append(data2) #["CMD"])
  1063. jdatas2 = []
  1064. for cmds in jdatas:
  1065. if not cmds:
  1066. continue
  1067. jdatas2.append(cmds)
  1068. return jdatas2
  1069. import hashlib
  1070. JCB_GLOB_BUF = {}
  1071. def JCB(data,sock=None): #json client input
  1072. t_start = time.time()
  1073. s = time.time()
  1074. e = time.time()
  1075. ct = int(e*100)/100
  1076. msg = "{} JCB START: {:0.02f} sizeof:{}"
  1077. msg = msg.format(ct,e-s,sys.getsizeof(data) )
  1078. jdatas = parse_json(data)
  1079. c = clock.time()
  1080. c = float(c)
  1081. process_flash(jdatas)
  1082. calc_jitter(jdatas,t_start)
  1083. out = {}
  1084. for cmds in jdatas:
  1085. #master_fx = MASTER_FX()
  1086. out = _parse_cmds(cmds,clock=c)
  1087. line_count = 0
  1088. line_count_sub = 0
  1089. line_size = 0
  1090. attr_count = {}
  1091. attr_count2 = 0
  1092. if not out:
  1093. return
  1094. try:
  1095. core.lock.acquire_lock()
  1096. for _id in out:
  1097. row = out[_id]
  1098. #print(" ",_id,[str(row)])
  1099. line_size += sys.getsizeof(row)
  1100. #print("_id",_id)
  1101. Admx = row.get("DMXCH",-44) #["DMXCH"]
  1102. if Admx == -44:
  1103. print("Admx",Admx)
  1104. if "attr" in row:
  1105. if row["attr"] not in attr_count:
  1106. attr_count[row["attr"]] = 0
  1107. attr_count[row["attr"]] += 1
  1108. attr_count2 +=1
  1109. if row["fix_id"]:
  1110. _fix_id = row["fix_id"]
  1111. Admx._fix_id = _fix_id
  1112. if "attr" in row:
  1113. if row["attr"] in ["RED","GREEN","BLUE","WHITE","AMBER"]: #CYAN,MAGENTA,YELLOW
  1114. Admx._v_master_id = _fix_id
  1115. #print("SET V_MASTER",row)
  1116. line_count_sub += _init_action(row)
  1117. line_count += 1
  1118. e = time.time()
  1119. print(" sub-JCB TIME:","{:0.02f}".format(e-s),int(e*100)/100)
  1120. #time.sleep(1/30)
  1121. except Exception as e:
  1122. cprint("EXCEPTION JCB",e,color="red")
  1123. cprint("----",str(cmds)[:150],"...",color="red")
  1124. cprint("Error on line {}".format(sys.exc_info()[-1].tb_lineno),color="red")
  1125. raise e
  1126. finally:
  1127. core.lock.release_lock()
  1128. #cprint(" ","{:0.04} sec.".format(time.time()-t_start),color="yellow")
  1129. print("attr_count:",attr_count)
  1130. #print(line_count,line_size)
  1131. e = time.time()
  1132. ct = int(e*100)/100
  1133. msg = "{} JCB: END {:0.02f} sizeof:{} fix-count:{} attr-count:{}"
  1134. msg = msg.format(ct,e-s,line_size,line_count,line_count_sub )
  1135. print(msg)
  1136. time.sleep(1/60)
  1137. def jcb_loop():
  1138. s = chat.Server(cb=JCB)
  1139. while 1:
  1140. s.poll()
  1141. time.sleep(0.001)
  1142. if __run_main:
  1143. jcb_loop()