-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py.bak
executable file
·958 lines (853 loc) · 35.1 KB
/
server.py.bak
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
from __future__ import division
import socket
import threading
import time
import sys
import RPi.GPIO as GPIO
import json
import signal
import traceback
import paho.mqtt.client as mqtt
from apscheduler.schedulers.background import BackgroundScheduler
from rpi_ws281x import PixelStrip, Color
import code
from pytz import timezone
import datetime
import math
import telnetlib
import spotipy
import spotipy.util as util
from spotipy.oauth2 import SpotifyClientCredentials
from pwmPCA9685 import pwm as pwm
scope = 'user-modify-playback-state,user-read-currently-playing'
SPOTIPY_CLIENT_ID="49e4b4ca65ea409bb48295c0a2f3f5e7"
SPOTIPY_CLIENT_SECRET="ee5dc6e0676d42099c6e65ae9d4b276e"
SPOTIPY_REDIRECT_URI="http://localhost/"
def testCallback():
print "testCallback: ", time.time()
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("julian/redding/command");
client.subscribe("julian/redding/ampel");
client.subscribe("julian/redding/white");
client.subscribe("julian/redding/stopSunrise");
client.subscribe("julian/zoeRainbow");
client.subscribe("julian/zoeBrightness");
client.subscribe("julian/nightlight");
client.subscribe("julian/#");
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
if (msg.topic == "julian/redding/command"):
parse(msg.payload)
if (msg.topic == "julian/redding/ampel"):
data = json.dumps({"type":"mqtt","action":"ampelcolor","data":msg.payload[1:]})
# print data
parse(data)
if (msg.topic == "julian/redding/white"):
data = json.dumps({"type":"light","action":"white","data":msg.payload})
# print data
parse(data)
if (msg.topic == "julian/redding/stopSunrise"):
data = json.dumps({"type":"mqtt","action":"stopSunrise"})
# print data
parse(data)
if (msg.topic == "julian/zoeRainbow"):
if (msg.payload == "1"):
data = json.dumps({"type":"neopixel","action":"zoeStartRainbow"})
else:
data = json.dumps({"type":"neopixel","action":"zoeStopRainbow"})
print data
parse(data)
if (msg.topic == "julian/zoeBrightness"):
data = json.dumps({"type":"neopixel","action":"zoeBrightness","value":msg.payload})
print data
parse(data)
if (msg.topic == "julian/nightlight"):
nightlight.morphto(int(msg.payload))
if (msg.topic == "julian/nightlightChain"):
nightlightChain.morphto(int(msg.payload))
def alarm():
print "alarm";
alarmThread = threading.Thread(target=tmqtt.alarm)
alarmThread.setDaemon(True)
alarmThread.start()
# code.interact(local=dict(globals(), **locals()))
def calc(x):
#return 0.9784889413 * math.pow(1.021983957,x) - 1
#return 0.9784889413 * math.exp(0.0217457939 * x)
return x
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
alarmStop = threading.Event();
oldVol = 50
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
HOST = '127.0.0.1' # Symbolic name meaning the local host
PORT = 44148 # Arbitrary non-privileged port
def exit():
conn.close()
GPIO.cleanup()
print 'exit'
class whiteThread(threading.Thread):
def __init__(self, name="WhiteThread"):
threading.Thread.__init__(self, name=name)
self.w1 = pwm(1,100)
self.changeEvent = threading.Event()
self.value = 0
def run(self):
print "%s starts" % (self.getName())
old = 0
while True:
if self.changeEvent.isSet():
self.changeEvent.clear()
self.morph(old, self.value)
old = self.value
time.sleep(0.1)
def morph(self, old, new, speed = 1):
dVal = new - old
n = 100
for i in range(0,1+n):
newVal = old + dVal * i / n
self.w1.set(newVal)
time.sleep(float(speed)/n)
def set(self,val):
self.w1.set(val,100)
def changeWhite(self, value):
self.value = int(value)
self.changeEvent.set()
return '{"status":"success"}'
class lightthread(threading.Thread):
def __init__(self, color, name='LightThread'):
""" constructor, setting initial variables """
self._stopevent = threading.Event()
self.color = color
self.currcolor = 'new'
self.rainbowSpeed = 0.1
self.changeEvent = threading.Event()
self.rainbowEn = threading.Event()
self.rainbowBrightness = 255
threading.Thread.__init__(self, name=name)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
self.r1 = GPIO.PWM(15, 200)
self.g1 = GPIO.PWM(11, 200)
self.b1 = GPIO.PWM(13, 200)
self.r1.start(0)
self.g1.start(0)
self.b1.start(0)
def run(self):
""" main control loop """
print "%s starts" % (self.getName( ),)
old = [0,0,0]
while True:
if (self.changeEvent.isSet()):
self.changeEvent.clear()
# print self.changeEvent.isSet()
print 'change'
self.morphto(self.color,old)
old = self.color
print self.color
time.sleep(0.1)
if (self.rainbowEn.isSet()):
self.rainbow(self.rainbowSpeed, self.rainbowBrightness)
def startRainbow(self,data):
# self.changeEvent.set()
self.rainbowEn.clear()
self.rainbowBrightness = int(data['brightness'])
self.rainbowSpeed = float(data['speed'])
time.sleep(0.1)
self.rainbowEn.set()
return '{"status":"success"}'
def rainbow(self,speed, brightness):
i = 0
while self.rainbowEn.isSet():
color = self.wheel(i)
self.change(color, brightness)
i += [-255, 1][i < 255]
time.sleep(float(speed))
# print str(self.changeEvent.isSet()) + str(i)
# self.color = color
def wheel(self, pos):
"""Generate rainbow colors across 0-255 positions."""
if pos < 85:
return [pos * 3, 255 - pos * 3, 0]
elif pos < 170:
pos -= 85
return [255 - pos * 3, 0, pos * 3]
else:
pos -= 170
return [0, pos * 3, 255 - pos * 3]
def setcolor(self, color):
self.color = color
self.rainbowEn.clear()
self.changeEvent.set()
return '{"status":"success"}'
def morphto(self,color,start):
r1 = int(start[0]) # Anfangswerte
g1 = int(start[1])
b1 = int(start[2])
dr1 = int(color[0]) - r1 # Differenz Ende - Anfang
dg1 = int(color[1]) - g1
db1 = int(color[2]) - b1
n = 100
speed = 1
for counter in range(0, n + 1):
r1_end = r1 + (counter * dr1 / 100)
g1_end = g1 + (counter * dg1 / 100)
b1_end = b1 + (counter * db1 / 100)
self.change([r1_end,g1_end,b1_end])
time.sleep(float(speed)/n)
self.changeEvent.clear()
def change(self,color, brightness = 255):
self.r1.ChangeDutyCycle(color[0] * 100 / 255 * brightness / 255)
self.g1.ChangeDutyCycle(color[1] * 100 / 255 * brightness / 255)
self.b1.ChangeDutyCycle(color[2] * 100 / 255 * brightness / 255)
class neopixelThread(threading.Thread):
def __init__(self, name='NeopixelThread'):
""" constructor, setting initial variables """
threading.Thread.__init__(self, name=name)
self._stopevent = threading.Event()
self.zoeOldColor = [0,0,0]
self.zoeColor = [0,0,0]
self.zoeChangeEvent = threading.Event()
self.zoeRainbowEn = threading.Event()
self.zoePixels = 30
self.zoeBrightness = 255
# LED strip configuration:
LED_COUNT = 30 # Number of LED pixels.
# LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).
LED_PIN = 10 # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10 # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest
LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53
self.strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
# Intialize the library (must be called once before other functions).
self.strip.begin()
def run(self):
""" main control loop """
while True:
if (self.zoeChangeEvent.isSet()):
self.zoeChangeEvent.clear()
print 'changeZoeColor'
self.zoeMorphto(self.zoeColor,self.zoeOldColor)
self.zoeOldColor = self.zoeColor
if (self.zoeRainbowEn.isSet()):
self.zoeRainbow()
time.sleep(0.1)
def zoeStartRainbow(self):
self.zoeRainbowEn.set()
def zoeStopRainbow(self):
self.zoeRainbowEn.clear()
def zoeBrightness(self,value):
self.zoeBrightness = value
def zoeSetColor(self,color):
self.zoeColor = color
self.zoeRainbowEn.clear()
self.zoeChangeEvent.set()
def zoeRainbow(self, wait_ms=20, iterations=1):
"""Draw rainbow that uniformly distributes itself across all pixels."""
for j in range(256*iterations):
for i in range(self.zoePixels):
self.strip.setPixelColor(i, self.wheel((int(i * 256 / self.zoePixels) + j) & 255))
self.strip.show()
time.sleep(wait_ms/1000.0)
if not self.zoeRainbowEn.isSet():
self.zoeMorphto([0,0,0],[0,0,0],0,1)
break
def zoeMorphto(self,color,start,speed=1,n=100):
r1 = int(start[0]) # Anfangswerte
g1 = int(start[1])
b1 = int(start[2])
dr1 = int(color[0]) - r1 # Differenz Ende - Anfang
dg1 = int(color[1]) - g1
db1 = int(color[2]) - b1
n = 100
speed = 1 # 1 sec
for counter in range(0, n + 1):
r1_end = r1 + (counter * dr1 / 100)
g1_end = g1 + (counter * dg1 / 100)
b1_end = b1 + (counter * db1 / 100)
for i in range(self.zoePixels):
self.strip.setPixelColor(i, Color(int(r1_end),int(g1_end),int(b1_end)))
self.strip.show()
time.sleep(float(speed)/n)
self.zoeChangeEvent.clear()
def wheel(self,pos):
"""Generate rainbow colors across 0-255 positions."""
if pos < 85:
return Color(int(pos * 3 * float(self.zoeBrightness/255)), int((255 - pos * 3) * float(self.zoeBrightness/255)), 0)
elif pos < 170:
pos -= 85
return Color(int((255 - pos * 3) * float(self.zoeBrightness/255)), 0, int(pos * 3 * float(self.zoeBrightness/255)))
else:
pos -= 170
return Color(0, int(pos * 3 * float(self.zoeBrightness/255)), int((255 - pos * 3) * float(self.zoeBrightness/255)))
class mqttThread(threading.Thread):
def __init__(self, name='MQTTThread'):
threading.Thread.__init__(self, name=name)
client.connect("127.0.0.1", 1883, 60)
self.sunriseEn = threading.Event()
def run(self):
client.loop_forever()
def sunrise(self,data={"duration": 1800, "color": [100,53,30]}):
self.sunriseEn.set()
n = 100
timesleep = float(data['duration'] / n * 4)
print "duration: ",data['duration']
for i in range(1,n+1):
if not self.sunriseEn.isSet():
break
color = ""
color += "{:02x}".format(int(data['color'][0] * 2.55 * i / 100))
color += "{:02x}".format(int(data['color'][1] * 2.55 * i / 100))
color += "{:02x}".format(int(data['color'][2] * 2.55 * i / 100))
newData = {"type": "mqtt", "action": "roomLight", "data": color}
newData1 = {"type": "light", "action": "white", "data": i}
parse(json.dumps(newData))
parse(json.dumps(newData1))
if (i == 10):
timesleep = timesleep / 2.0
if (i == 17):
timesleep = timesleep / 2.0
if (i == 34):
timesleep = timesleep / 2.0
print "i",i
print "sleeping", timesleep
time.sleep(timesleep)
def stopSunrise(self):
self.sunriseEn.clear()
def alarm(self):
alarmStop.clear();
while not alarmStop.isSet():
tlight.change([255,0,0])
twhite.set(100)
client.publish("julian/redding/sonoff/cmnd/color","ff0000",1,False)
client.publish("julian/redding/clock/light",255<<16,1,False)
client.publish("julian/redding/room/light2","1",1,False)
time.sleep(1)
tlight.change([0,0,0])
twhite.set(0)
client.publish("julian/redding/sonoff/cmnd/color","000000",1,False)
client.publish("julian/redding/clock/light",0,1,False)
client.publish("julian/redding/room/light2","0",1,False)
time.sleep(1)
class spotifyThread(threading.Thread):
def __init__(self, name='SpotifyThread'):
threading.Thread.__init__(self, name=name)
def run(self):
global sp
while 1:
token = util.prompt_for_user_token('j.ullrich',scope,client_id=SPOTIPY_CLIENT_ID,client_secret=SPOTIPY_CLIENT_SECRET,redirect_uri=SPOTIPY_REDIRECT_URI)
sp = spotipy.client.Spotify(auth=token)
time.sleep(3500)
class nightlight():
def __init__(self, name='nightlight'):
""" constructor, setting initial variables """
self.inputPin = 22
GPIO.setup(self.inputPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
self.out = pwm(2)
self.currVal = 0 # 0-255
self.dimThreshold = 0.5
self.startThreshold = 0.05
self.rise = True
self.on = False
GPIO.add_event_detect(self.inputPin, GPIO.RISING, callback=self.dim)
print "nightlight started"
def dim(self,c):
# global storeValue, strip, on, rise, channel, start, number, dimThreshold, startThreshold
print "dim"
starttime = time.time()
while GPIO.input(self.inputPin):
time.sleep(0.02)
if time.time() - starttime >= 0.5:
break
endtime = time.time()
timediff = endtime-starttime
if timediff < self.startThreshold:
return 0
if timediff < self.dimThreshold:
if not self.on:
for i in range(0,101):
value = calc(self.currVal*i/100)
# print value
self.out.set(value)
time.sleep(0.005)
self.on = not self.on
else:
for i in range(0,101):
value = calc(self.currVal*(100-i)/100)
# print value
self.out.set(value)
time.sleep(0.005)
self.on = not self.on
else:
if not self.on:
self.currVal = 0
while GPIO.input(self.inputPin):
if self.rise:
if self.currVal < 255:
self.currVal += 1
else:
if self.currVal > 0:
self.currVal -= 1
value = calc(self.currVal)
# print value
self.out.set(value)
if self.currVal == 0:
self.on = False
self.currVal = 50
break
else:
self.on = True
time.sleep(0.015)
self.rise = not self.rise
def morphto(self,value):
print "morphing nightlight to",value
if (value == 0):
if not self.on:
return
else:
for i in range(0,101):
value = calc(self.currVal*(100-i)/100)
# print value
self.out.set(value)
time.sleep(0.005)
self.on = False
self.rise = True
return
else:
if not self.on:
self.currVal = value
for i in range(0,101):
value = calc(self.currVal*i/100)
# print value
self.out.set(value)
time.sleep(0.005)
self.on = True
return
if (value > 127):
self.rise = False
else:
self.rise = True
start = self.currVal
d1 = int(value) - start
n = 100
speed = 1
for counter in range(0, n + 1):
self.currVal = start + (counter * d1 / 100)
self.out.set(self.currVal)
time.sleep(float(speed)/n)
class nightlightChain():
def __init__(self, name='nightlightChain'):
""" constructor, setting initial variables """
self.inputPin = 7
GPIO.setup(self.inputPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
self.out = pwm(3)
self.currVal = 0 # 0-255
self.dimThreshold = 0.5
self.startThreshold = 0.05
self.rise = True
self.on = False
GPIO.add_event_detect(self.inputPin, GPIO.RISING, callback=self.dim)
print "nightlightChain started"
def dim(self,c):
# global storeValue, strip, on, rise, channel, start, number, dimThreshold, startThreshold
print "dim"
starttime = time.time()
while GPIO.input(self.inputPin):
time.sleep(0.02)
if time.time() - starttime >= 0.5:
break
endtime = time.time()
timediff = endtime-starttime
if timediff < self.startThreshold:
return 0
if timediff < self.dimThreshold:
if not self.on:
for i in range(0,101):
value = calc(self.currVal*i/100)
# print value
self.out.set(value)
time.sleep(0.005)
self.on = not self.on
else:
for i in range(0,101):
value = calc(self.currVal*(100-i)/100)
# print value
self.out.set(value)
time.sleep(0.005)
self.on = not self.on
else:
if not self.on:
self.currVal = 0
while GPIO.input(self.inputPin):
if self.rise:
if self.currVal < 255:
self.currVal += 1
else:
if self.currVal > 0:
self.currVal -= 1
value = calc(self.currVal)
# print value
self.out.set(value)
if self.currVal == 0:
self.on = False
self.currVal = 50
break
else:
self.on = True
time.sleep(0.015)
self.rise = not self.rise
def morphto(self,value):
print "morphing chain nightlight to",value
if (value == 0):
if not self.on:
return
else:
for i in range(0,101):
value = calc(self.currVal*(100-i)/100)
# print value
self.out.set(value)
time.sleep(0.005)
self.on = False
self.rise = True
return
else:
if not self.on:
self.currVal = value
for i in range(0,101):
value = calc(self.currVal*i/100)
# print value
self.out.set(value)
time.sleep(0.005)
self.on = True
return
if (value > 127):
self.rise = False
else:
self.rise = True
start = self.currVal
d1 = int(value) - start
n = 100
speed = 1
for counter in range(0, n + 1):
self.currVal = start + (counter * d1 / 100)
self.out.set(self.currVal)
time.sleep(float(speed)/n)
class EventEngine():
def __init__(self):
self.timezone = timezone("Europe/Berlin")
self.scheduler = BackgroundScheduler(timezone=self.timezone)
self.scheduler.add_jobstore('sqlalchemy', url='sqlite:///schedule.sqlite')
self.scheduler.start()
# job = self.scheduler.add_job(testCallback, 'interval', hours=2, id='2', replace_existing=True, name="intervaltest")
# job2 = self.scheduler.add_job(parse, 'cron', hour=5, minute=45, end_date='2019-05-08', id='1', replace_existing=True, name="wecker", args=['{"type":"mqtt","action":"sunrise","data":{"duration":1800,"color":[100,52,30]}}'])
# job3 = self.scheduler.add_job(testCallback, 'date', run_date='2019-11-17 20:30:0', id='3', replace_existing=True)
def getJobs(self):
jobArr = self.scheduler.get_jobs()
responseArr = []
for job in jobArr:
newJob = {}
newJob["id"] = job.id
newJob["name"] = job.name
newJob["args"] = job.args
newJob["running"] = False if (job.next_run_time == None) else True
if hasattr(job.trigger, 'interval'):
newJob['trigger'] = 'interval'
newJob['triggerargs'] = {}
newJob['triggerargs']['jitter'] = job.trigger.jitter
newJob['triggerargs']['start_date'] = str(job.trigger.start_date)
newJob['triggerargs']['end_date'] = str(job.trigger.end_date)
interval = job.trigger.interval_length
weeks = interval // (7*24*60*60)
days = (interval - weeks * (7*24*60*60)) // (24*60*60)
hours = (interval - weeks * (7*24*60*60) - days * (24*60*60)) // (60*60)
minutes = (interval - weeks * (7*24*60*60) - days * (24*60*60) - hours * (60*60)) // 60
seconds = (interval - weeks * (7*24*60*60) - days * (24*60*60) - hours * (60*60) - minutes * (60))
newJob['triggerargs']['weeks'] = weeks
newJob['triggerargs']['days'] = days
newJob['triggerargs']['hours'] = hours
newJob['triggerargs']['minutes'] = minutes
newJob['triggerargs']['seconds'] = seconds
if hasattr(job.trigger, 'fields'):
newJob['trigger'] = 'cron'
newJob['triggerargs'] = {}
newJob['triggerargs']['jitter'] = job.trigger.jitter
newJob['triggerargs']['start_date'] = str(job.trigger.start_date)
newJob['triggerargs']['end_date'] = str(job.trigger.end_date)
for field in job.trigger.fields:
newJob['triggerargs'][field.name] = str(field)
if hasattr(job.trigger, 'run_date'):
newJob['trigger'] = 'date'
newJob['triggerargs'] = {}
newJob['triggerargs']['run_date'] = str(job.trigger.run_date)
responseArr.append(newJob)
# print responseArr
responseJson = json.dumps(responseArr)
return responseJson
def newJob(self,jsondata):
data = jsondata
triggerargs = data['triggerargs']
# code.interact(local=locals())
self.scheduler.add_job(parse, data['trigger'], id=data['id'], replace_existing=True, name=data['name'], args=[data['args'][0]], **triggerargs)
# if (data['trigger'] == 'cron'):
# self.scheduler.add_job(parse, data['trigger'], id=data['id'], replace_existing=True, name=data['name'], args=[json.dumps(data['args'][0])], jitter=triggerargs['jitter'], year=triggerargs['year'], month=triggerargs['month'], week=triggerargs['week'], day=triggerargs['day'], day_of_week=triggerargs['day_of_week'], hour=triggerargs['hour'], minute=triggerargs['minute'], second=triggerargs['second'], start_date=triggerargs['start_date'], end_date=triggerargs['end_date'])
# if (data['trigger'] == 'interval'):
# self.scheduler.add_job(parse, data['trigger'], id=data['id'], replace_existing=True, name=data['name'], args=[json.dumps(data['args'][0])], jitter=triggerargs['jitter'], weeks=triggerargs['week'], days=triggerargs['day'], hours=triggerargs['hour'], minutes=triggerargs['minute'], seconds=triggerargs['second'], start_date=triggerargs['start_date'], end_date=triggerargs['end_date'])
# if (data['trigger'] == 'date'):
# self.scheduler.add_job(parse, data['trigger'], id=data['id'], replace_existing=True, name=data['name'], args=[json.dumps(data['args'][0])], run_date=triggerargs['run_date'])
def deleteJob(self,jobid):
self.scheduler.remove_job(jobid)
def toggleJob(self,jobId):
print "toggle"
if (self.scheduler.get_job(jobId).next_run_time == None):
#unpause job
self.scheduler.resume_job(jobId)
else:
#pause job
self.scheduler.pause_job(jobId)
def newTimer(self,data):
duration = data['time']
id = data['id']
run_date = datetime.datetime.fromtimestamp(math.floor(time.time() + int(duration)),self.timezone).isoformat()
self.scheduler.add_job(alarm, 'date', run_date=run_date, id=id, replace_existing=True, name="Clock_alarm")
def stopTimer(self,data):
id = data['id']
try:
self.scheduler.remove_job(id)
except Exception as e:
pass
alarmStop.set()
tlight = lightthread([0,0,0])
tlight.setDaemon(True)
tlight.start()
twhite = whiteThread()
twhite.setDaemon(True)
twhite.start()
tmqtt = mqttThread()
tmqtt.setDaemon(True)
tmqtt.start()
tneopixel = neopixelThread()
tneopixel.setDaemon(True)
tneopixel.start()
nightlight = nightlight();
nightlightChain = nightlightChain();
# tspot = spotifyThread()
# tspot.setDaemon(True)
# tspot.start()
s = None
conn = None
sp = None
def openSocket():
global s
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error, msg:
s = None
continue
try:
s.bind(sa)
s.listen(1)
except socket.error, msg:
s.close()
s = None
continue
break
if s is None:
print 'could not open socket'
sys.exit(1)
def parse(data,conn=None):
print "Parsing: ",data
jsonobj = json.loads(data)
response = ""
if 'type' not in jsonobj and 'entities' in jsonobj:
arr = {}
for index in jsonobj['entities']:
arr[index] = jsonobj['entities'][index][0]['value']
parse(json.dumps(arr))
return
if jsonobj['type'] == 'light':
if jsonobj['action'] == 'start':
response = tlight.setcolor(jsonobj['data'])
lightstate = 'on'
print 'start'
if jsonobj['action'] == 'rainbow':
response = tlight.startRainbow(jsonobj['data'])
lightstate = 'on'
print 'rainbow'
if jsonobj['action'] == 'white':
response = twhite.changeWhite(jsonobj['data'])
print 'white'
if jsonobj['action'] == 'kitchen':
response = twhite.changeWhite(jsonobj['value'])
print 'white'
if jsonobj['type'] == "mqtt":
if jsonobj['action'] == 'clockMode':
client.publish("julian/redding/clock/mode",jsonobj['data'],2,False)
response = '{"status":"success"}'
print 'clockMode'
if jsonobj['action'] == 'clockBright':
client.publish("julian/redding/clock/brightness",jsonobj['data'],2,False)
response = '{"status":"success"}'
print 'clockBright'
if jsonobj['action'] == 'roomLight':
client.publish("julian/redding/sonoff/cmnd/color",jsonobj['data'],1,False)
response = '{"status":"success"}'
print 'roomLight'
if jsonobj['action'] == "roomLightRGB":
client.publish("julian/redding/sonoff/cmnd/channel1",jsonobj['data'][0],1,False)
client.publish("julian/redding/sonoff/cmnd/channel2",jsonobj['data'][1],1,False)
client.publish("julian/redding/sonoff/cmnd/channel3",jsonobj['data'][2],1,False)
response = '{"status":"success"}'
print "roomlightRGB"
if jsonobj['action'] == "sunrise":
sunriseThread = threading.Thread(target=tmqtt.sunrise,kwargs={"data": jsonobj['data']})
sunriseThread.setDaemon(True)
response = '{"status":"success"}'
sunriseThread.start()
if jsonobj['action'] == "stopSunrise":
tmqtt.sunriseEn.clear()
response = '{"status":"success"}'
sunriseThread.start()
if jsonobj['action'] == "ampel":
print "ampel on"
client.publish("julian/redding/lichterkette1/farbe","[[0,255,0],[255,100,0],[255,0,0]]",1,False)
# client.publish("julian/redding/lichterkette2/farbe","[[0,255,0],[255,255,0],[255,0,0]]",1,False)
response = '{"status":"success"}'
if jsonobj['action'] == "ampeloff":
print "ampel off"
client.publish("julian/redding/lichterkette1/farbe","[[0,0,0],[0,0,0],[0,0,0]]",1,False)
# client.publish("julian/redding/lichterkette2/farbe","[[0,0,0],[0,0,0],[0,0,0]]",1,False)
response = '{"status":"success"}'
if jsonobj['action'] == "ampelcolor": #takes color as 888 value
print "ampel color"
print jsonobj['data']
try:
jsonobj['data'] = int(jsonobj['data'],16)
except Exception as e:
print(traceback.format_exc())
str = json.dumps([[(jsonobj['data'] >> 16) & 255,(jsonobj['data'] >> 8) & 255,jsonobj['data'] & 255],[(jsonobj['data'] >> 16) & 255,(jsonobj['data'] >> 8) & 255,jsonobj['data'] & 255],[(jsonobj['data'] >> 16) & 255,(jsonobj['data'] >> 8) & 255,jsonobj['data'] & 255]])
client.publish("julian/redding/lichterkette1/farbe",str,1,False)
print str
# client.publish("julian/redding/lichterkette2/farbe",json.dumps([(jsonobj['color'] >> 16) && 255,(jsonobj['color'] >> 8) && 255,jsonobj['color'] && 255]),1,False)
response = '{"status":"success"}'
if jsonobj['action'] == "roomMain":
print "roomMain"
client.publish("julian/redding/room/light1",jsonobj['data'],1,False)
# client.publish("julian/redding/lichterkette2/farbe","[[0,0,0],[0,0,0],[0,0,0]]",1,False)
response = '{"status":"success"}'
if jsonobj['action'] == "stringLight":
print "stringLight"
client.publish("julian/redding/room/light2",jsonobj['data'],1,False)
# client.publish("julian/redding/lichterkette2/farbe","[[0,0,0],[0,0,0],[0,0,0]]",1,False)
response = '{"status":"success"}'
if jsonobj['type'] == 'neopixel':
if jsonobj['action'] == 'zoeStartRainbow':
response = tneopixel.zoeStartRainbow()
print 'startRainbow'
if jsonobj['action'] == 'zoeStopRainbow':
response = tneopixel.zoeStopRainbow()
print 'stopRainbow'
if jsonobj['action'] == 'zoeBrightness':
response = tneopixel.zoeBrightness(jsonobj["value"])
print 'zoeBrightness'
if jsonobj['type'] == "schedule":
if jsonobj['action'] == "getJobs":
response = events.getJobs()
if jsonobj['action'] == "newJob":
events.newJob(jsonobj['data'])
response = '{"status":"success"}'
if jsonobj['action'] == "deleteJob":
events.deleteJob(jsonobj['data'])
response = '{"status":"success"}'
if jsonobj['action'] == "toggleJob":
events.toggleJob(jsonobj['data'])
response = '{"status":"success"}'
if jsonobj['action'] == "newTimer":
events.newTimer(jsonobj['data'])
response = '{"status":"success"}'
if jsonobj['action'] == "stopTimer":
events.stopTimer(jsonobj['data'])
response = '{"status":"success"}'
if jsonobj['type'] == "remote":
if jsonobj['action'] == "sendData":
print jsonobj['data']['payload']
tn = telnetlib.Telnet(jsonobj['data']['hostname'], jsonobj['data']['port'])
tn.write(jsonobj['data']['payload'].encode("utf-8"))
tn.close()
response = '{"status":"success"}'
if jsonobj['type'] == "spotify":
if jsonobj['action'] == "pause":
sp.pause_playback()
response = '{"status":"success"}'
if jsonobj['action'] == "play":
sp.start_playback()
response = '{"status":"success"}'
if jsonobj['action'] == "next":
sp.next_track()
response = '{"status":"success"}'
if jsonobj['action'] == "previous":
sp.previous_track()
response = '{"status":"success"}'
if jsonobj['action'] == "playTrack":
prefix = "track"
if 'searchprefix' in jsonobj:
prefix = jsonobj['searchprefix']
results = sp.search(q=jsonobj['trackname'], type=prefix)
items = results[prefix + "s"]['items']
if len(items) > 0:
play = items[0]
print (play['name'])
uri = play["uri"]
if prefix == "track":
sp.start_playback(uris=[uri])
else:
sp.start_playback(context_uri=uri)
response = '{"status":"success"}'
if jsonobj['action'] == "quieter":
oldVol = sp.current_playback()['device']['volume_percent']
sp.volume(oldVol - 10 if oldVol >= 10 else 0)
if jsonobj['action'] == "louder":
oldVol = sp.current_playback()['device']['volume_percent']
sp.volume(oldVol + 10 if oldVol <= 90 else 100)
if jsonobj['action'] == "volume":
sp.volume(int(jsonobj['value']))
if jsonobj['action'] == "speakStart":
global oldVol
print "speakstart"
oldVol = sp.current_playback()['device']['volume_percent']
print int(oldVol * 0.3)
sp.volume(int(oldVol * 0.3))
if jsonobj['action'] == "speakEnd":
global oldVol
sp.volume(oldVol)
# print response
if conn is not None:
conn.send(response)
if 'respId' in jsonobj:
# print jsonobj['respId']
client.publish("julian/redding/response/"+jsonobj['respId'],response,1,False)
def main():
global conn
openSocket()
lightstate = 'off'
# code.interact(local=locals())
while True:
conn, addr = s.accept()
print 'Connected by', addr
data = conn.recv(1024)
# print 'Socked date: ',data
try:
parse(data,conn)
except Exception:
print(traceback.format_exc())
# conn.send(data)
time.sleep(0.1)
events = EventEngine()
main()