5 from bme280
import BME280
6 from pms5003
import PMS5003
, ReadTimeoutError
7 from subprocess
import PIPE
, Popen
, check_output
8 from PIL
import Image
, ImageDraw
, ImageFont
11 from smbus2
import SMBus
13 from smbus
import SMBus
18 format
='%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s',
20 datefmt
='%Y-%m-%d %H:%M:%S')
22 logging
.info("""luftdaten.py - Reads temperature, pressure, humidity,
23 PM2.5, and PM10 from Enviro plus and sends data to Luftdaten,
24 the citizen science air quality project.
26 Note: you'll need to register with Luftdaten at:
27 https://meine.luftdaten.info/ and enter your Raspberry Pi
28 serial number that's displayed on the Enviro plus LCD along
29 with the other details before the data appears on the
38 # Create BME280 instance
39 bme280
= BME280(i2c_dev
=bus
)
54 # Create PMS5003 instance
58 # Read values from BME280 and PMS5003 and return as dict
61 cpu_temp
= get_cpu_temperature()
62 raw_temp
= bme280
.get_temperature()
63 comp_temp
= raw_temp
- ((cpu_temp
- raw_temp
) / comp_factor
)
64 values
["temperature"] = "{:.2f}".format(comp_temp
)
65 values
["pressure"] = "{:.2f}".format(bme280
.get_pressure() * 100)
66 values
["humidity"] = "{:.2f}".format(bme280
.get_humidity())
68 pm_values
= pms5003
.read()
69 values
["P2"] = str(pm_values
.pm_ug_per_m3(2.5))
70 values
["P1"] = str(pm_values
.pm_ug_per_m3(10))
71 except ReadTimeoutError
:
73 pm_values
= pms5003
.read()
74 values
["P2"] = str(pm_values
.pm_ug_per_m3(2.5))
75 values
["P1"] = str(pm_values
.pm_ug_per_m3(10))
79 # Get CPU temperature to use for compensation
80 def get_cpu_temperature():
81 process
= Popen(['vcgencmd', 'measure_temp'], stdout
=PIPE
, universal_newlines
=True)
82 output
, _error
= process
.communicate()
83 return float(output
[output
.index('=') + 1:output
.rindex("'")])
86 # Get Raspberry Pi serial number to use as ID
87 def get_serial_number():
88 with
open('/proc/cpuinfo', 'r') as f
:
90 if line
[0:6] == 'Serial':
91 return line
.split(":")[1].strip()
94 # Check for Wi-Fi connection
96 if check_output(['hostname', '-I']):
102 # Display Raspberry Pi serial and Wi-Fi status on LCD
103 def display_status():
104 wifi_status
= "connected" if check_wifi() else "disconnected"
105 text_colour
= (255, 255, 255)
106 back_colour
= (0, 170, 170) if check_wifi() else (85, 15, 15)
107 id = get_serial_number()
108 message
= "{}\nWi-Fi: {}".format(id, wifi_status
)
109 img
= Image
.new('RGB', (WIDTH
, HEIGHT
), color
=(0, 0, 0))
110 draw
= ImageDraw
.Draw(img
)
111 size_x
, size_y
= draw
.textsize(message
, font
)
112 x
= (WIDTH
- size_x
) / 2
113 y
= (HEIGHT
/ 2) - (size_y
/ 2)
114 draw
.rectangle((0, 0, 160, 80), back_colour
)
115 draw
.text((x
, y
), message
, font
=font
, fill
=text_colour
)
119 def send_to_luftdaten(values
, id):
120 pm_values
= dict(i
for i
in values
.items() if i
[0].startswith("P"))
121 temp_values
= dict(i
for i
in values
.items() if not i
[0].startswith("P"))
123 resp_1
= requests
.post("https://api.luftdaten.info/v1/push-sensor-data/",
125 "software_version": "enviro-plus 0.0.1",
126 "sensordatavalues": [{"value_type": key
, "value": val
} for
127 key
, val
in pm_values
.items()]
132 "Content-Type": "application/json",
133 "cache-control": "no-cache"
137 resp_2
= requests
.post("https://api.luftdaten.info/v1/push-sensor-data/",
139 "software_version": "enviro-plus 0.0.1",
140 "sensordatavalues": [{"value_type": key
, "value": val
} for
141 key
, val
in temp_values
.items()]
146 "Content-Type": "application/json",
147 "cache-control": "no-cache"
151 if resp_1
.ok
and resp_2
.ok
:
157 # Compensation factor for temperature
160 # Raspberry Pi ID to send to Luftdaten
161 id = "raspi-" + get_serial_number()
163 # Width and height to calculate text position
169 font
= ImageFont
.truetype("fonts/Asap/Asap-Bold.ttf", font_size
)
171 # Display Raspberry Pi serial and Wi-Fi status
172 logging
.info("Raspberry Pi serial: {}".format(get_serial_number()))
173 logging
.info("Wi-Fi: {}\n".format("connected" if check_wifi() else "disconnected"))
175 # Main loop to read data, display, and send to Luftdaten
178 values
= read_values()
180 resp
= send_to_luftdaten(values
, id)
181 logging
.info("Response: {}\n".format("ok" if resp
else "failed"))
183 except Exception as e
: