6 from bme280
import BME280
7 from pms5003
import PMS5003
, ReadTimeoutError
8 from subprocess
import PIPE
, Popen
, check_output
9 from PIL
import Image
, ImageDraw
, ImageFont
12 from smbus2
import SMBus
14 from smbus
import SMBus
19 format
='%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s',
21 datefmt
='%Y-%m-%d %H:%M:%S')
23 logging
.info("""luftdaten.py - Reads temperature, pressure, humidity,
24 PM2.5, and PM10 from Enviro plus and sends data to Luftdaten,
25 the citizen science air quality project.
27 Note: you'll need to register with Luftdaten at:
28 https://meine.luftdaten.info/ and enter your Raspberry Pi
29 serial number that's displayed on the Enviro plus LCD along
30 with the other details before the data appears on the
39 # Create BME280 instance
40 bme280
= BME280(i2c_dev
=bus
)
55 # Create PMS5003 instance
59 # Read values from BME280 and PMS5003 and return as dict
62 cpu_temp
= get_cpu_temperature()
63 raw_temp
= bme280
.get_temperature()
64 comp_temp
= raw_temp
- ((cpu_temp
- raw_temp
) / comp_factor
)
65 values
["temperature"] = "{:.2f}".format(comp_temp
)
66 values
["pressure"] = "{:.2f}".format(bme280
.get_pressure() * 100)
67 values
["humidity"] = "{:.2f}".format(bme280
.get_humidity())
69 pm_values
= pms5003
.read()
70 values
["P2"] = str(pm_values
.pm_ug_per_m3(2.5))
71 values
["P1"] = str(pm_values
.pm_ug_per_m3(10))
72 except ReadTimeoutError
:
74 pm_values
= pms5003
.read()
75 values
["P2"] = str(pm_values
.pm_ug_per_m3(2.5))
76 values
["P1"] = str(pm_values
.pm_ug_per_m3(10))
80 # Get CPU temperature to use for compensation
81 def get_cpu_temperature():
82 process
= Popen(['vcgencmd', 'measure_temp'], stdout
=PIPE
, universal_newlines
=True)
83 output
, _error
= process
.communicate()
84 return float(output
[output
.index('=') + 1:output
.rindex("'")])
87 # Get Raspberry Pi serial number to use as ID
88 def get_serial_number():
89 with
open('/proc/cpuinfo', 'r') as f
:
91 if line
[0:6] == 'Serial':
92 return line
.split(":")[1].strip()
95 # Check for Wi-Fi connection
97 if check_output(['hostname', '-I']):
103 # Display Raspberry Pi serial and Wi-Fi status on LCD
104 def display_status():
105 wifi_status
= "connected" if check_wifi() else "disconnected"
106 text_colour
= (255, 255, 255)
107 back_colour
= (0, 170, 170) if check_wifi() else (85, 15, 15)
108 id = get_serial_number()
109 message
= "{}\nWi-Fi: {}".format(id, wifi_status
)
110 img
= Image
.new('RGB', (WIDTH
, HEIGHT
), color
=(0, 0, 0))
111 draw
= ImageDraw
.Draw(img
)
112 size_x
, size_y
= draw
.textsize(message
, font
)
113 x
= (WIDTH
- size_x
) / 2
114 y
= (HEIGHT
/ 2) - (size_y
/ 2)
115 draw
.rectangle((0, 0, 160, 80), back_colour
)
116 draw
.text((x
, y
), message
, font
=font
, fill
=text_colour
)
120 def send_to_luftdaten(values
, id):
121 pm_values
= dict(i
for i
in values
.items() if i
[0].startswith("P"))
122 temp_values
= dict(i
for i
in values
.items() if not i
[0].startswith("P"))
124 resp_1
= requests
.post("https://api.luftdaten.info/v1/push-sensor-data/",
126 "software_version": "enviro-plus 0.0.1",
127 "sensordatavalues": [{"value_type": key
, "value": val
} for
128 key
, val
in pm_values
.items()]
133 "Content-Type": "application/json",
134 "cache-control": "no-cache"
138 resp_2
= requests
.post("https://api.luftdaten.info/v1/push-sensor-data/",
140 "software_version": "enviro-plus 0.0.1",
141 "sensordatavalues": [{"value_type": key
, "value": val
} for
142 key
, val
in temp_values
.items()]
147 "Content-Type": "application/json",
148 "cache-control": "no-cache"
152 if resp_1
.ok
and resp_2
.ok
:
158 # Compensation factor for temperature
161 # Raspberry Pi ID to send to Luftdaten
162 id = "raspi-" + get_serial_number()
164 # Width and height to calculate text position
170 font
= ImageFont
.truetype("fonts/Asap/Asap-Bold.ttf", font_size
)
172 # Display Raspberry Pi serial and Wi-Fi status
173 logging
.info("Raspberry Pi serial: {}".format(get_serial_number()))
174 logging
.info("Wi-Fi: {}\n".format("connected" if check_wifi() else "disconnected"))
176 time_since_update
= 0
177 update_time
= time
.time()
179 # Main loop to read data, display, and send to Luftdaten
182 time_since_update
= time
.time() - update_time
183 values
= read_values()
185 if time_since_update
> 145:
186 resp
= send_to_luftdaten(values
, id)
187 update_time
= time
.time()
188 logging
.info("Response: {}\n".format("ok" if resp
else "failed"))
190 except Exception as e
: