-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSensorian_Client.py
2895 lines (2608 loc) · 113 KB
/
Sensorian_Client.py
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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
"""Sensorian_Client.py: Collects sensor data on given intervals and sends it to various services upon request.
Cab be run on its own or imported to other projects and run in the background.
"""
from __future__ import print_function
import ConfigParser
import os
import requests
import json
import time
import datetime
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import TFT as GLCD
import APDS9300 as LUX_SENSOR
import MPL3115A2 as ALTIBAR
import CAP1203 as CAP_TOUCH
import MCP79410RTCC as RT_CLOCK
import FXOS8700CQR1 as ACCEL_SENSOR
import threading
import socket
import fcntl
import struct
import subprocess
import RPi.GPIO as GPIO
from flask import Flask, abort, request
from flask_restful import Api, Resource, reqparse
from flask_httpauth import HTTPBasicAuth
from multiprocessing import Process
from sense_hat import SenseHat
__author__ = "Dylan Kauling"
__maintainer__ = "Dylan Kauling"
__status__ = "Development"
CapTouch = None
RTC = None
imuSensor = None
AltiBar = None
font = None
disp = None
sensehat = None
def sensorian_setup():
# Sensor initializations
# RTC excepts on first call on boot
# Loops until the RTC works
rtc_not_ready = True
global RTC
while rtc_not_ready:
try:
RTC = RT_CLOCK.MCP79410()
rtc_not_ready = False
except:
rtc_not_ready = True
global imuSensor
imuSensor = ACCEL_SENSOR.FXOS8700CQR1()
imuSensor.configureAccelerometer()
imuSensor.configureMagnetometer()
imuSensor.configureOrientation()
global AltiBar
AltiBar = ALTIBAR.MPL3115A2()
AltiBar.ActiveMode()
AltiBar.BarometerMode()
# print "Giving the Barometer 2 seconds or it won't work"
time.sleep(2)
global CapTouch
CapTouch = CAP_TOUCH.CAP1203()
# Prepare an object for drawing on the TFT LCD
global disp
disp = GLCD.TFT()
disp.initialize()
disp.clear()
global font
font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeSansBold.ttf', 14) # use a truetype font
# Set up the GPIO for the touch buttons and LED
GPIO.setup(CAP_PIN, GPIO.IN)
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.add_event_detect(CAP_PIN, GPIO.FALLING)
GPIO.add_event_callback(CAP_PIN, button_event_handler)
# Enable interrupts on the buttons
CapTouch.clearInterrupt()
CapTouch.enableInterrupt(0, 0, 0x07)
def sense_hat_setup():
global sensehat
sensehat = SenseHat()
# Thread sentinels - Threads stop looping when disabled
timeEnabled = True
ambientEnabled = True
lightEnabled = True
cpuEnabled = True
interfaceIPEnabled = True
publicIPEnabled = True
accelEnabled = True
pressureEnabled = True
buttonEnabled = True
sendEnabled = False
flaskEnabled = False
socketEnabled = False
magnetEnabled = True
# Global sensor/IP variables protected by locks below if required
currentDateTime = datetime.datetime(2000, 1, 1, 0, 0, 0)
cpuSerial = "0000000000000000"
light = -1
ambientTemp = -1
cpuTemp = -1
mode = -1
accelX = 0
accelY = 0
accelZ = 0
modeprevious = -1
ambientPressure = -1
watchedInterface = "eth0"
interfaceIP = "0.0.0.0"
publicIP = "0.0.0.0"
serverURL = "http://localhost/"
iftttEvent = "SensorianEvent"
iftttKey = "xxxxxxxxxxxxxxxxxxxxxx"
button = 0
displayEnabled = True
printEnabled = False
lockOrientation = False
hatEnabled = True
hatUsed = "Sensorian"
defaultOrientation = 0
sleepTime = 1
postInterval = 4
postTimeout = 5
ambientInterval = 5
lightInterval = 1
cpuTempInterval = 5
interfaceInterval = 5
publicInterval = 30
accelInterval = 1
inMenu = False
currentMenu = "Top"
menuElements = []
topMenuElements = ["Exit", "General", "UI", "Requests", "Accelerometer", "Light", "Ambient", "System"]
menuPosition = 0
parser = ConfigParser.SafeConfigParser()
threads = []
killWatch = False
magnetX = 0
magnetY = 0
magnetZ = 0
magnetInterval = 1
configUsername = 'configUsername'
configPassword = 'configPassword'
relayAddress = "0.0.0.0"
relayPort = 8000
# Board Pin Numbers
INT_PIN = 11 # Ambient Light Sensor Interrupt - BCM 17
LED_PIN = 12 # LED - BCM 18
CAP_PIN = 13 # Capacitive Touch Button Interrupt - BCM 27
GPIO.setmode(GPIO.BOARD)
# Lock to ensure one sensor used at a time
# Sensorian firmware not thread-safe without
I2CLock = threading.Lock()
# Sentinel Thread Locks - Make sure the thread and main program aren't
# accessing the thread sentinels at the same time
timeEnabledLock = threading.Lock()
ambientEnabledLock = threading.Lock()
lightEnabledLock = threading.Lock()
accelEnabledLock = threading.Lock()
interfaceIPEnabledLock = threading.Lock()
publicIPEnabledLock = threading.Lock()
cpuEnabledLock = threading.Lock()
pressureEnabledLock = threading.Lock()
buttonEnabledLock = threading.Lock()
sendEnabledLock = threading.Lock()
# Global Variable Thread Locks - Make sure the thread and main program aren't
# accessing the global sensor variables at the same time
serialLock = threading.Lock()
ambientTempLock = threading.Lock()
lightLock = threading.Lock()
modeLock = threading.Lock()
watchedInterfaceLock = threading.Lock()
interfaceIPLock = threading.Lock()
publicIPLock = threading.Lock()
cpuTempLock = threading.Lock()
ambientPressureLock = threading.Lock()
rtcLock = threading.Lock()
buttonLock = threading.Lock()
accelXLock = threading.Lock()
accelYLock = threading.Lock()
accelZLock = threading.Lock()
inMenuLock = threading.Lock()
currentMenuLock = threading.Lock()
menuElementsLock = threading.Lock()
menuPositionLock = threading.Lock()
defaultOrientationLock = threading.Lock()
lockOrientationLock = threading.Lock()
printEnabledLock = threading.Lock()
displayEnabledLock = threading.Lock()
sleepTimeLock = threading.Lock()
postTimeoutLock = threading.Lock()
killWatchLock = threading.Lock()
flaskEnabledLock = threading.Lock()
interfaceIntervalLock = threading.Lock()
publicIntervalLock = threading.Lock()
postIntervalLock = threading.Lock()
serverURLLock = threading.Lock()
iftttKeyLock = threading.Lock()
iftttEventLock = threading.Lock()
ambientIntervalLock = threading.Lock()
lightIntervalLock = threading.Lock()
accelIntervalLock = threading.Lock()
cpuTempIntervalLock = threading.Lock()
socketEnabledLock = threading.Lock()
magnetXLock = threading.Lock()
magnetYLock = threading.Lock()
magnetZLock = threading.Lock()
magnetIntervalLock = threading.Lock()
magnetEnabledLock = threading.Lock()
relayAddressLock = threading.Lock()
relayPortLock = threading.Lock()
configUsernameLock = threading.Lock()
configPasswordLock = threading.Lock()
hatEnabledLock = threading.Lock()
hatUsedLock = threading.Lock()
app = Flask(__name__)
api = Api(app)
auth = HTTPBasicAuth()
@auth.get_password
def get_password(username):
"""Used by Flask HTTP Auth to validate a username and password when requesting a secure page.
Accepts a single username and password from the config file.
"""
configUsernameLock.acquire()
temp_config_username = configUsername
configUsernameLock.release()
if username == temp_config_username:
configPasswordLock.acquire()
temp_config_password = configPassword
configPasswordLock.release()
return temp_config_password
return None
class ConfigListAPI(Resource):
"""Flask RESTful API for listing all current config values.
Execute a GET request to http://0.0.0.0/variables to retrieve the list.
"""
decorators = [auth.login_required]
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('name', type=str, location='json')
self.reqparse.add_argument('value', type=str, location='json')
super(ConfigListAPI, self).__init__()
def get(self):
config_list = get_all_config()
return {'variables': config_list}
class ConfigAPI(Resource):
"""Flask RESTful API for checking and updating specific config values.
Execute a GET or PUT request to http://0.0.0.0/variables/variablename to retrieve or set the item.
"""
decorators = [auth.login_required]
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('name', type=str, location='json')
self.reqparse.add_argument('value', type=str, location='json')
super(ConfigAPI, self).__init__()
def get(self, name):
config_temp = get_config_value(name)
if config_temp != "ConfigNotFound":
return {'name': name, 'value': config_temp}
else:
abort(404)
def put(self, name):
config_temp = get_config_value(name)
if config_temp != "ConfigNotFound":
args = self.reqparse.parse_args()
if args['value'] is not None:
set_temp = set_config_value(name, args['value'])
if set_temp:
return {'name': name, 'value': get_config_value(name)}
else:
abort(400, 'Invalid value received, please provide the correct type')
else:
abort(400, 'No value received, please provide a value in the JSON')
else:
abort(404)
api.add_resource(ConfigListAPI, '/variables', endpoint='variables')
api.add_resource(ConfigAPI, '/variables/<string:name>', endpoint='variable')
def run_flask():
"""Method called by the Flask Thread to start the Flask server.
Runs the Flask server in debug mode currently and binds to any interface.
Can be called directly as well if not already running.
"""
print("Running Flask")
app.run(debug=True, use_reloader=False, host='0.0.0.0')
def shutdown_server():
"""Method called by kill_flask() to shut down the Flask server if it is running.
Called on application close or upon POST request to /shutdown, should not be called directly!
"""
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
@app.route('/shutdown', methods=['POST'])
@auth.login_required
def shutdown_flask_api():
"""Flask API to shut down the Flask server.
This of course prevents future calls to the Flask API.
Requires Basic Authentication with config username and password.
"""
shutdown_server()
return 'Flask server shutting down...'
@app.route('/commands/kill', methods=['POST'])
@auth.login_required
def kill_client_api():
"""Flask API to kill the Sensorian Hub Client gracefully.
This of course prevents future calls to the Client.
Requires Basic Authentication with config username and password.
"""
kill_program()
return 'Sensorian Client shutting down...'
@app.route('/commands/shutdown', methods=['POST'])
@auth.login_required
def shutdown_pi_api():
"""Flask API to shutdown the Raspberry Pi.
This of course prevents future calls to the Client.
Requires Basic Authentication with config username and password.
"""
shutdown_pi()
return 'Raspberry Pi shutting down...'
@app.route('/commands/reboot', methods=['POST'])
@auth.login_required
def reboot_pi_api():
"""Flask API to shutdown the Raspberry Pi.
This of course prevents future calls to the Client until it is started again.
Requires Basic Authentication with config username and password.
"""
reboot_pi()
return 'Raspberry Pi rebooting...'
def kill_flask():
"""Method to shut down the Flask server.
Called on system shutdown by cleanup() but can be called directly as well.
This makes a POST to the shutdown URL authenticated with the config file username and password.
Needs to be called for shutdown_server() to work.
"""
url = 'http://127.0.0.1:5000/shutdown'
configUsernameLock.acquire()
temp_config_username = configUsername
configUsernameLock.release()
configPasswordLock.acquire()
temp_config_password = configPassword
configPasswordLock.release()
try:
requests.post(url, auth=(temp_config_username, temp_config_password))
except requests.exceptions.ConnectionError:
print("Flask server already shut down")
def update_serial():
"""Updates the global CPU serial variable by reading it from the cpuinfo file.
Really only needs to be called once when the Client is initialized. It's not going to change.
"""
global cpuSerial
temp_serial = "0000000000000000"
# Get serial from the file, if fails, return error serial
try:
f = open('/proc/cpuinfo', 'r')
try:
for line in f:
if line[0:6] == 'Serial':
temp_serial = line[10:26]
finally:
f.close()
except (IOError, OSError):
temp_serial = "ERROR000000000"
# Update the serial global variable when safe
finally:
serialLock.acquire()
cpuSerial = temp_serial
serialLock.release()
def get_serial():
"""Gets the CPU serial from the global variable when not locked.
:return: String of the CPU serial.
"""
serialLock.acquire()
temp_serial = cpuSerial
serialLock.release()
return temp_serial
class GeneralThread(threading.Thread):
"""General Thread class to repeatedly update a variable at a given interval
Takes an arbitrary int thread_id and string name to identify the thread.
Takes an integer or float interval for how long in seconds to wait between updating values.
Takes the string method which is the name of the method to call contained in the methods dictionary.
"""
# Initializes a thread upon creation
def __init__(self, thread_id, name, interval, method):
threading.Thread.__init__(self)
self.threadID = thread_id
self.name = name
if interval < 1:
self.interval = 1
else:
self.interval = interval
self.method = method
self.repeat = check_sentinel(self.method)
self.slept = 0
self.toSleep = 0
def run(self):
# Thread loops as long as the sentinel remains True
while self.repeat:
methods[self.method]()
self.slept = 0
# Keep sleeping until it's time to update again
while self.slept < self.interval:
# Check the global sentinel for this thread every second at most
self.repeat = check_sentinel(self.method)
# If the sentinel changed to false this second, kill the thread
if not self.repeat:
print("Killing " + self.name)
break
# If it did not, sleep for another second unless less than a
# second needs to pass to reach the end of the current loop
if self.interval - self.slept < 1:
self.toSleep = self.interval - self.slept
else:
self.toSleep = 1
time.sleep(self.toSleep)
self.slept += self.toSleep
class FlaskThread(threading.Thread):
"""A Thread class specifically to run a Flask server in the background.
Terminates when an authenticated POST to /shutdown is made or shutdown_server() is called.
"""
def __init__(self):
"""Initializes a Flask Thread with only a default ID and name.
"""
threading.Thread.__init__(self)
self.threadID = 99
self.name = "FlaskThread"
def run(self):
"""Runs a Flask server continuously until terminated.
Can be terminated by an authenticated POST to /shutdown or call of shutdown_server().
"""
run_flask()
print("Killing FlaskThread")
class SocketThread(threading.Thread):
"""A Thread class specifically to establish a socket with a Sensorian Hub Site relay server.
The socket code is kind of janky with no real schema yet, but allows for configuration behind NATs and firewalls.
"""
def __init__(self):
"""Initializes the Socket thread with the config values for address, port and defaults for timings and ID/name.
"""
threading.Thread.__init__(self)
self.threadID = 100
self.name = "SocketThread"
self.connected = False
self.host = get_config_value("relayaddress")
self.port = get_config_value("relayport")
self.repeat = check_sentinel("SocketSentinel")
self.slept = 0
self.keep_alive = 5
self.timeout = 5.0
def run(self):
"""Loops attempts to establish a socket and waits for commands from the server when one is established.
Can be terminated by setting the SocketSentinel to False.
"""
while self.repeat:
if not self.connected:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(self.timeout)
s.connect((self.host, self.port))
self.connected = True
except socket.timeout:
self.connected = False
if self.slept >= self.keep_alive:
s.send("KeepAlive")
message = s.recv(1024)
if message == "LIVE":
print("LIVE Received")
elif message == "PREPARE":
s.send("READY")
data = s.recv(1024)
if data == "CANCEL":
print("CANCEL Received")
elif data:
try:
colon = data.index(":")
config_temp = get_config_value(data[0:colon])
if config_temp != "ConfigNotFound":
set_temp = set_config_value(data[0:colon], data[colon + 1:len(data) + 1])
if set_temp:
print("Updated " + data[0:colon] + " to " + get_config_value(data[0:colon]))
else:
print("Did not update " + data[0:colon] + ", stays " + get_config_value(
data[0:colon]))
else:
print("Did not find variable named " + data[0:colon])
except ValueError:
print("Malformed data received from socket")
self.slept = 0
elif self.slept < self.keep_alive:
self.slept += 1
self.repeat = check_sentinel("SocketSentinel")
time.sleep(1)
s.close()
print("Killing SocketThread")
def update_light():
"""Updates the global light variable by reading the Lux value from the Sensorian ambient light sensor.
This is called by the Light Thread, but can be called directly as well.
"""
global light
if get_config_value("hatenabled") == "True":
if get_config_value("hatused") == "Sensorian":
temp_light = -1
I2CLock.acquire()
# Try to initialize and update the light value
# Sometimes it excepts, so catch it if it does
try:
ambient_light = LUX_SENSOR.APDS9300()
channel1 = ambient_light.readChannel(1)
channel2 = ambient_light.readChannel(0)
temp_light = ambient_light.getLuxLevel(channel1, channel2)
except:
print("EXCEPTION IN LIGHT UPDATE")
I2CLock.release()
# Update the global light level when safe
lightLock.acquire()
light = temp_light
lightLock.release()
elif get_config_value("hatused") == "Sense HAT":
lightLock.acquire()
light = -1
lightLock.release()
def get_light():
"""Gets the most recent update of the global light variable when not locked.
:return: Float of the last updated light value.
"""
lightLock.acquire()
try:
temp_light = light
finally:
lightLock.release()
return temp_light
def get_ambient_temp():
"""Gets the most recent update of the global ambient temperature variable when not locked.
:return: Float of the last updated ambient temperature.
"""
ambientTempLock.acquire()
return_temp = ambientTemp
ambientTempLock.release()
return return_temp
def get_ambient_pressure():
"""Gets the most recent update of the global barometric pressure variable when not locked.
:return: Float of the last updated barometric pressure.
"""
ambientPressureLock.acquire()
return_press = float(ambientPressure) / 1000
ambientPressureLock.release()
return return_press
def update_ambient():
"""Updates the global ambient temperature and pressure variables by using the Sensorian Altibar sensor.
This is called by the Ambient Thread, but can be called directly as well.
"""
global ambientTemp
global ambientPressure
if get_config_value("hatenabled") == "True":
if get_config_value("hatused") == "Sensorian":
# Sensor needs some wait time between calls
time.sleep(0.5)
# Update the ambient temperature global variable
I2CLock.acquire()
temp = AltiBar.ReadTemperature()
I2CLock.release()
time.sleep(0.5)
ambientTempLock.acquire()
ambientTemp = temp
ambientTempLock.release()
# Check to see if pressure is desired
pressureEnabledLock.acquire()
temp_enabled = pressureEnabled
pressureEnabledLock.release()
# If pressure is needed, update the global variable when safe
if temp_enabled:
I2CLock.acquire()
press = AltiBar.ReadBarometricPressure()
I2CLock.release()
ambientPressureLock.acquire()
ambientPressure = press
ambientPressureLock.release()
else:
print("NoPressureNeeded")
# Getting altitude as well would result in additional sleeps
# for the sensor, may calculate from location/pressure/temp
'''
altitudeEnabledLock.acquire()
temp_enabled = pressureEnabled
altitudeEnabledLock.release()
if (temp_enabled):
I2CLock.acquire()
alt = AltiBar.ReadBarometricPressure()
I2CLock.release()
ambientPressureLock.acquire()
ambientPressure = press
ambientPressureLock.release()
else:
print "NoAltitudeNeeded"
'''
elif get_config_value("hatused") == "Sense HAT":
# Update the ambient temperature global variable
I2CLock.acquire()
temp = sensehat.temperature
I2CLock.release()
ambientTempLock.acquire()
ambientTemp = temp
ambientTempLock.release()
# Check to see if pressure is desired
pressureEnabledLock.acquire()
temp_enabled = pressureEnabled
pressureEnabledLock.release()
# If pressure is needed, update the global variable when safe
if temp_enabled:
I2CLock.acquire()
press = sensehat.pressure
I2CLock.release()
ambientPressureLock.acquire()
ambientPressure = press
ambientPressureLock.release()
else:
print("NoPressureNeeded")
def update_date_time():
"""Updates the global RTC date/time object by polling the date and time from the Sensorian real-time clock.
This is called by the Time Thread, but can be called directly as well.
"""
global currentDateTime
if get_config_value("hatenabled") == "True":
if get_config_value("hatused") == "Sensorian":
I2CLock.acquire()
temp_date_time = RTC.GetTime()
I2CLock.release()
temp_date = datetime.date(2000 + temp_date_time.year, temp_date_time.month, temp_date_time.date)
temp_time = datetime.time(temp_date_time.hour, temp_date_time.min, temp_date_time.sec)
temp_datetime = datetime.datetime.combine(temp_date, temp_time)
rtcLock.acquire()
currentDateTime = temp_datetime
rtcLock.release()
elif get_config_value("hatused") == "Sense HAT":
rtcLock.acquire()
currentDateTime = datetime.datetime.now()
rtcLock.release()
else:
rtcLock.acquire()
currentDateTime = datetime.datetime.now()
rtcLock.release()
else:
rtcLock.acquire()
currentDateTime = datetime.datetime.now()
rtcLock.release()
def get_date_time():
"""Gets the most recent update of the global RTC date/time object when not locked.
:return: RTC date/time object containing the last updated date and time.
"""
rtcLock.acquire()
temp_date_time = currentDateTime
rtcLock.release()
return temp_date_time
def update_cpu_temp():
"""Updates the global CPU temperature variable by reading the value from the system temperature file.
This is called by the CPU Thread, but can be called directly as well.
"""
# Read the CPU temperature from the system file
global cpuTemp
temp_path = '/sys/class/thermal/thermal_zone0/temp'
temp_file = open(temp_path)
cpu = temp_file.read()
temp_file.close()
temp = (float(cpu) / 1000)
# Update the global variable when safe
cpuTempLock.acquire()
cpuTemp = temp
cpuTempLock.release()
def get_cpu_temp():
"""Gets the most recent update of the global CPU temperature variable when not locked.
:return: Float containing the last updated CPU temperature in Celcius.
"""
cpuTempLock.acquire()
temp = cpuTemp
cpuTempLock.release()
return temp
def update_watched_interface_ip():
"""Updates the global Watched Network Interface IP variable by calling get_interface_ip().
This is called by the Update Watched IP Thread, but can be called directly as well.
"""
global interfaceIP
watchedInterfaceLock.acquire()
temp_interface = watchedInterface
watchedInterfaceLock.release()
ipaddr = get_interface_ip(temp_interface)
interfaceIPLock.acquire()
interfaceIP = ipaddr
interfaceIPLock.release()
if get_config_value("hatenabled") == "True":
if get_config_value("hatused") == "Sense HAT":
sensehat.show_message("IP: " + ipaddr)
def get_watched_interface_ip():
"""Gets the most recent update of the global watched network interface IP variable when not locked.
:return: String of the watched network interface's IP from the last update.
"""
interfaceIPLock.acquire()
temp_ip = interfaceIP
interfaceIPLock.release()
return temp_ip
def get_interface_ip(interface):
"""Gets the IP of the network interface passed by establishing and reading on socket on that interface.
This is called by update_watched_interface_ip() with the watched interface, but can be called directly as well.
:param interface: String of the network interface to check, eg. eth0, wlan0, etc.
:return: String of the given network interface's IP, defaults to 0.0.0.0
"""
# Create a socket to use to query the interface
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Try to get the IP of the passed interface
try:
ipaddr = socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', interface[:15])
)[20:24])
# If it fails, return an empty IP address
except IOError:
ipaddr = "0.0.0.0"
# Close the socket whether an IP was found or not
finally:
s.close()
# Return the IP Address: Correct or Empty
return ipaddr
def update_public_ip():
"""Updates the global Public IP variable by calling curl on icanhazip.com
Called by Update Public IP Thread, but can be called directly as well.
Gets the IP from icanhazip.com. As with any Internet resource, please be respectful.
Ie. Don't update too frequently, that's not cool.
"""
global publicIP
# Initiate a subprocess to run a curl request for the public IP
proc = subprocess.Popen(["curl", "-s", "-4", "icanhazip.com"], stdout=subprocess.PIPE)
(out, err) = proc.communicate()
# Store the response of the request when safe
publicIPLock.acquire()
publicIP = out.rstrip()
publicIPLock.release()
def get_public_ip():
"""Gets the most recent update of the global public IP variable when not locked.
:return: String of the public IP of the Client from the last update.
"""
publicIPLock.acquire()
temp_ip = publicIP
publicIPLock.release()
return temp_ip
def update_accelerometer():
"""Updates all the various Accelerometer-related global variables by polling the Sensorian's Accelerometer.
This is called by the Accel Thread, but can be called directly as well.
"""
global mode, modeprevious, accelX, accelY, accelZ
if get_config_value("hatenabled") == "True":
if get_config_value("hatused") == "Sensorian":
I2CLock.acquire()
# If the accelerometer is ready, read the orientation and forces
if imuSensor.readStatusReg() & 0x80:
x, y, z = imuSensor.pollAccelerometer()
orienta = imuSensor.getOrientation()
I2CLock.release()
# Store the various global variables when safe
accelXLock.acquire()
accelX = x
accelXLock.release()
accelYLock.acquire()
accelY = y
accelYLock.release()
accelZLock.acquire()
accelZ = z
accelZLock.release()
modeLock.acquire()
mode = (orienta >> 1) & 0x03
modeLock.release()
if mode != modeprevious:
# Alert change in orientation if required
# print "Changed orientation"
modeprevious = get_mode()
else:
I2CLock.release()
elif get_config_value("hatused") == "Sense HAT":
I2CLock.acquire()
temp_accel = sensehat.accelerometer_raw
I2CLock.release()
x = temp_accel.get('x')
y = temp_accel.get('y')
z = temp_accel.get('z')
accelXLock.acquire()
accelX = x
accelXLock.release()
accelYLock.acquire()
accelY = y
accelYLock.release()
accelZLock.acquire()
accelZ = z
accelZLock.release()
def update_magnetometer():
"""Updates all the various Magnetometer-related global variables by polling the Sensorian's Magnetometer.
This is called by the Magnet Thread, but can be called directly as well.
"""
global magnetX, magnetY, magnetZ
if get_config_value("hatenabled") == "True":
if get_config_value("hatused") == "Sensorian":
I2CLock.acquire()
# If the magnetometer is ready, read the magnetic forces
if imuSensor.readStatusReg() & 0x80:
magnet_x, magnet_y, magnet_z = imuSensor.pollMagnetometer()
I2CLock.release()
# Store the various global variables when safe
magnetXLock.acquire()
magnetX = magnet_x
magnetXLock.release()
magnetYLock.acquire()
magnetY = magnet_y
magnetYLock.release()
magnetZLock.acquire()
magnetZ = magnet_z
magnetZLock.release()
else:
I2CLock.release()
elif get_config_value("hatused") == "Sense HAT":
I2CLock.acquire()
temp_mag = sensehat.compass_raw
I2CLock.release()
magnet_x = temp_mag.get('x')
magnet_y = temp_mag.get('y')
magnet_z = temp_mag.get('z')
magnetXLock.acquire()
magnetX = magnet_x
magnetXLock.release()
magnetYLock.acquire()
magnetY = magnet_y
magnetYLock.release()
magnetZLock.acquire()
magnetZ = magnet_z
magnetZLock.release()
def get_mag_x():
"""Gets the most recent update of the global magnetic force x variable when not locked.
:return: Integer of the last updated magnetic force in the X direction
"""
magnetXLock.acquire()
x = magnetX
magnetXLock.release()
return x
def get_mag_y():
"""Gets the most recent update of the global magnetic force y variable when not locked.
:return: Integer of the last updated magnetic force in the Y direction
"""
magnetYLock.acquire()
y = magnetY
magnetYLock.release()
return y
def get_mag_z():
"""Gets the most recent update of the global magnetic force z variable when not locked.
:return: Integer of the last updated magnetic force in the Z direction
"""
magnetZLock.acquire()
z = magnetZ
magnetZLock.release()
return z
def get_mode():
"""Gets the most recent update of the global orientation variable when not locked.
:return: Integer of the last updated orientation