-
Notifications
You must be signed in to change notification settings - Fork 0
/
pi-lightlevel
executable file
·74 lines (62 loc) · 1.87 KB
/
pi-lightlevel
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
#!/usr/bin/env python
import time
import picamera
from PIL import Image
import paho.mqtt.client
import mqtt_config
import json
import io
import fractions
#Test in test/, check http://spacehub.somakeit.org.uk
#for advice choosing a topic for production
TOPIC = "somakeit/space/main_room/lightlevel"
POLL_TIME = 300 #seconds
#Camera settings
AWB_GAINS = (fractions.Fraction(77, 64), fractions.Fraction(471, 256))
SHUTTER_SPEED = long(33164)
ISO = long(1600)
#Connect to a broker
mqtt = paho.mqtt.client.Client(client_id=mqtt_config.client_id, clean_session=True)
#Use real root certificates
mqtt.tls_set(("/etc/ssl/certs/ca-certificates.crt"))
mqtt.username_pw_set(mqtt_config.user_name, mqtt_config.password)
mqtt.loop_start()
while True:
try:
mqtt.connect(mqtt_config.server, port=mqtt_config.port)
break
except Exception as e:
print "failed to connecct: " + str(e)
time.sleep(60)
print "retrying.."
while True:
stream = io.BytesIO()
try:
camera = picamera.PiCamera()
camera.resolution = (320, 240)
camera.framerate = 30
# Fix everything
camera.shutter_speed = SHUTTER_SPEED
camera.exposure_mode = 'off'
camera.awb_mode = 'off'
camera.awb_gains = AWB_GAINS
camera.iso = ISO
#Capture a shot
camera.capture(stream, format='jpeg')
camera.close()
del(camera)
except Exception as e:
print "Failed to camera: " + str(e)
continue
#process the image
image = Image.open(stream)
bwimage = image.convert('L')
data = (bwimage.getdata())
light = 1.0*sum(data)/len(data)
del(stream)
del(image)
del(bwimage)
timestamp = time.time()
message = json.dumps({"timestamp": timestamp, "lumens": -1, "level": light})
mqtt.publish(TOPIC, payload=message, qos=0, retain=True)
time.sleep(POLL_TIME)