def main(): parser = argparse.ArgumentParser( description="Publish enviroplus values over mqtt" ) parser.add_argument( "--broker", default=DEFAULT_MQTT_BROKER_IP, type=str, help="mqtt broker IP", ) parser.add_argument( "--port", default=DEFAULT_MQTT_BROKER_PORT, type=int, help="mqtt broker port", ) parser.add_argument( "--topic", default=DEFAULT_MQTT_TOPIC, type=str, help="mqtt topic" ) parser.add_argument( "--interval", default=DEFAULT_READ_INTERVAL, type=int, help="the read interval in seconds", ) args = parser.parse_args() # Raspberry Pi ID device_serial_number = get_serial_number() device_id = "raspi-" + device_serial_number print( f"""mqtt-all.py - Reads Enviro plus data and sends over mqtt. broker: {args.broker} client_id: {device_id} port: {args.port} topic: {args.topic} Press Ctrl+C to exit! """ ) mqtt_client = mqtt.Client(client_id=device_id) mqtt_client.on_connect = on_connect mqtt_client.on_publish = on_publish mqtt_client.connect(args.broker, port=args.port) bus = SMBus(1) # Create BME280 instance bme280 = BME280(i2c_dev=bus) # Create LCD instance disp = ST7735.ST7735( port=0, cs=1, dc=9, backlight=12, rotation=270, spi_speed_hz=10000000 ) # Initialize display disp.begin() # Try to create PMS5003 instance HAS_PMS = False try: pms5003 = PMS5003() pm_values = pms5003.read() HAS_PMS = True print("PMS5003 sensor is connected") except SerialTimeoutError: print("No PMS5003 sensor connected") # Display Raspberry Pi serial and Wi-Fi status print("RPi serial: {}".format(device_serial_number)) print("Wi-Fi: {}\n".format("connected" if check_wifi() else "disconnected")) print("MQTT broker IP: {}".format(args.broker)) # Main loop to read data, display, and send over mqtt mqtt_client.loop_start() while True: try: values = read_bme280(bme280) if HAS_PMS: pms_values = read_pms5003(pms5003) values.update(pms_values) values["serial"] = device_serial_number print(values) mqtt_client.publish(args.topic, json.dumps(values)) display_status(disp, args.broker) time.sleep(args.interval) except Exception as e: print(e)
# Create LCD instance disp = ST7735.ST7735( port=0, cs=1, dc=9, backlight=12, rotation=270, spi_speed_hz=10000000 ) # Initialize display disp.begin() # Create PMS5003 instance pms5003 = PMS5003() # Read values from BME280 and PMS5003 and return as dict def read_values(): values = {} cpu_temp = get_cpu_temperature() raw_temp = bme280.get_temperature() comp_temp = raw_temp - ((cpu_temp - raw_temp) / comp_factor) values["temperature"] = "{:.2f}".format(comp_temp) values["pressure"] = "{:.2f}".format(bme280.get_pressure() * 100) values["humidity"] = "{:.2f}".format(bme280.get_humidity()) try: pm_values = pms5003.read() values["P2"] = str(pm_values.pm_ug_per_m3(2.5)) values["P1"] = str(pm_values.pm_ug_per_m3(10))
#!/usr/bin/env python3 import json import os import subprocess import time import re import paho.mqtt.client as mqtt from pms5003 import PMS5003 import config # Configure the PMS5003 pms5003 = PMS5003( device='/dev/ttyAMA0', baudrate=9600, pin_enable=config.ENABLE_PIN, pin_reset=config.RESET_PIN ) def on_connect(client, userdata, rc, *extra_params): # The callback for when the client receives a CONNACK response from the server. print('Connected with result code ' + str(rc)) def get_state(): try: data = pms5003.read() result = {} result['pm1'] = data.pm_ug_per_m3(1.0) result['pm2_5'] = data.pm_ug_per_m3(2.5)
import os import RPi.GPIO as IO import ST7735 from PIL import Image from PIL import ImageDraw from PIL import ImageFont try: from smbus2 import SMBus except ImportError: from smbus import SMBus bus = SMBus(1) bme280 = BME280(i2c_dev=bus) # BME280 temperature, humidity and pressure sensor pms5003 = PMS5003() # PMS5003 particulate sensor IO.setmode(IO.BCM) # Set pin numbering IO.setup(4,IO.OUT) # Fan controller on GPIO 4 pwm = IO.PWM(4,1000) # PWM frequency pwm.start(100) # Duty cycle # Create ST7735 LCD display class st7735 = ST7735.ST7735( port=0, cs=1, dc=9, backlight=12, rotation=270, spi_speed_hz=10000000 )
noise_measure = Noise() # This takes a little longer --- by default listens for 0.5 seconds def update_noise(): amp_low, amp_mid, amp_high, amp_total = noise_measure.get_noise_profile() noise.labels(level="low").set(amp_low) noise.labels(level="mid").set(amp_mid) noise.labels(level="high").set(amp_high) noise.labels(level="total").set(amp_total) # Particulates # # This sensor also allows for measuring a variant "atmospheric environment". # It's not clear to me what this means, so I'm sticking to the code as # used in the examples in the module Github repository. pms5003_measure = PMS5003() particulates = Gauge("particulates", "particulates in µg/m³", ["diameter"]) def update_particulates(): data = pms5003_measure.read() particulates.labels(diameter="1.0").set(data.pm_ug_per_m3(1.0)) particulates.labels(diameter="2.5").set(data.pm_ug_per_m3(2.5)) particulates.labels(diameter="10").set(data.pm_ug_per_m3(10)) @app.route("/metrics", methods=["GET"]) def return_metrics(): update_weather() update_light() update_noise() update_gas()
# used with https://github.com/adafruit/Adafruit_Python_GPIO and https://github.com/adafruit/Adafruit_Python_BME280 import requests import sys import time from Adafruit_BME280 import * from pms5003 import PMS5003 bme = BME280(t_mode=BME280_OSAMPLE_8, p_mode=BME280_OSAMPLE_8, h_mode=BME280_OSAMPLE_8) pms5003 = PMS5003(device='/dev/ttyAMA0', baudrate=9600) # post to wunderground PWS api_url = 'http://rtupdate.wunderground.com/weatherstation/updateweatherstation.php' wun_station = sys.argv[1] wun_key = sys.argv[2] elevation = float(sys.argv[3]) # elevation above sea level in meters try: pressure_cal = float( sys.argv[4] ) # pressure calibration in pascals. leave set to 0 unless a calibrated reference is used. except: pressure_cal = 0 try: pms5003_enable = int(sys.argv[5]) except: pms5003_enable = 0 def get_sensor_data():
aioKey_polLar = initializeFeed(aio, "EnviroPi-PollutionLarge") aioKey_polMed = initializeFeed(aio, "EnviroPi-PollutionMedium") aioKey_polSml = initializeFeed(aio, "EnviroPi-PollutionSmall") aioKey_humidity = initializeFeed(aio, "EnviroPi-Humidity") aioKey_pressure = initializeFeed(aio, "EnviroPi-Pressure") aioKey_light = initializeFeed(aio, "EnviroPi-Light") # NOTE: There are some bad practices here. Later in the script we'll call reportToAIO repeatedly so its # arguments must exist even if we're not using AIO. So if the user decides not to use AIO or if the # credentials file is missing then the value of "aio" and the values of these keys are assigned to # be an empty string. However, that will only happen if USE_AIO == False and so those variables will # never be used. This is bad practice but for such a small script I didn't bother doing it right. # Initializing the sensors # The gas sensor doesn't need initialized like this. BME280 = BME280(i2c_dev=SMBus(1)) PMS5003 = PMS5003() LTR559 = LTR559() # Initializing the LCD DISPLAY = ST7735.ST7735(port=0, cs=1, dc=9, backlight=12, rotation=90, spi_speed_hz=10000000) # Initializing the image to DISPLAY on the LCD WIDTH = DISPLAY.width HEIGHT = DISPLAY.height IMG = Image.new('RGB', (WIDTH, HEIGHT), color=(0, 0, 0)) DRAW = ImageDraw.Draw(IMG)
def __init__(self): self.bus = SMBus(1) self.bme280 = BME280(i2c_dev=self.bus) self.pms5003 = PMS5003() self.ltr559 = LTR559() self.comp_factor = _comp_factor
#!/usr/bin/env python from pms5003 import PMS5003 print("""specific.py - Continously print a specific data value. Press Ctrl+C to exit! """) # Configure the PMS5003 for Enviro+ pms5003 = PMS5003(device='/dev/ttyAMA0', baudrate=9600, pin_enable=22, pin_reset=27) try: while True: data = pms5003.read() print( "PM2.5 ug/m3 (combustion particles, organic compounds, metals): {}" .format(data.pm_ug_per_m3(2.5))) except KeyboardInterrupt: pass
def __init__(self): bus = SMBus(1) self.bme280 = BME280(i2c_dev=bus) self.pms5003 = PMS5003() time.sleep(1)
ertc.save_time() wlan.deinit() pycom.nvs_set('rtc_synced', 1) else: print('RTC synced: {}'.format(ertc.get_time())) lock.release() _thread.start_new_thread(th_func, (measurements, )) ###################### en = Pin('P4', mode=Pin.OUT, pull=Pin.PULL_DOWN) # MOSFET gate en(True) aq_sensor = PMS5003(Pin.module.P8, Pin.module.P10, Pin.module.P11, Pin.module.P9) aq_sensor.wake_up() frames = aq_sensor.read_frames(5) aq_sensor.idle() en.value(0) cpm25 = 0 cpm10 = 0 pm25 = 0 pm10 = 0 for data in frames: cpm25 += data.cpm25 cpm10 += data.cpm10 pm25 += data.pm25