def test_setup(): from sgp30 import SGP30 dev = MockI2CDev() assert dev._open is True sgp30 = SGP30(i2c_dev=dev, i2c_msg=MockI2CMsg()) del sgp30 assert dev._open is False
def __init__(self, config): SensorWrapper.__init__(self, config) # I2C bus self.bus = SMBus(1) # Create sensor object self.sensor = SGP30(self.bus) self.sensor.init_sgp()
def __init__(self, smbus, baseline_cache_path=None, baseline_storage_interval=1000): Thread.__init__(self) self._logger_thread = LoggerThread() self._bus = smbus self._chip = SGP30(smbus) self.last_sample = None self.warming_up = True self.baseline_cache_path = baseline_cache_path self.baseline_storage_interval = baseline_storage_interval self._samples_until_baseline_store = baseline_storage_interval self.terminate_asap = False self.__co2_baseline = self.__voc_baseline = None if self.baseline_cache_path: try: with open(baseline_cache_path) as f: self.__co2_baseline = int(f.readline()) self.__voc_baseline = int(f.readline()) except Exception as exc: print('Error loading baseline:', exc, file=stderr)
def main(): smbus = SMBus(1) # zero on some boards warming_up = True baseline_counter = 0 with SGP30(smbus) as chip: while True: measurement = chip.measure_air_quality() # Chip returns (400, 0) for the first ~15 seconds while it warms up if warming_up: if measurement.is_probably_warmup_value(): print('... warming up ...') sleep(1) continue else: warming_up = False print(measurement) # Don't take this as a complete example... read the spec sheet about how you're supposed to stash and restore the baseline, initial burn-in, humidity compensation, *and how you need to sample every second to maintain accurate results* baseline_counter = baseline_counter + 1 if baseline_counter % 100 == 0: baseline_counter = 0 baseline = chip.get_baseline() print('>> Baseline:', baseline) sleep(1)
def main(): smbus = SMBus(1) # zero on some boards warming_up = True baseline_counter = 0 initialise() with SGP30(smbus) as chip: while True: measurement = chip.measure_air_quality() # Chip returns (400, 0) for the first ~15 seconds while it warms up if warming_up: if measurement.is_probably_warmup_value(): print('... warming up ...') sleep(1) continue else: warming_up = False print(measurement.co2_ppm) print(measurement) client = InfluxDBClient(host, port, user, password, dbname) json_body = [{ "measurement": "data", "fields": { "co2": measurement.co2_ppm, "voc": measurement.voc_ppb, }, "tags": { "node": "server", "location": "salon", "sensor": "sgp30", }, }] client.write_points(json_body) # Don't take this as a complete example... read the spec sheet about how you're supposed to stash and restore the baseline, initial burn-in, humidity compensation, *and how you need to sample every second to maintain accurate results* baseline_counter = baseline_counter + 1 if baseline_counter % 100 == 0: sensor_config() baseline_counter = 0 baseline = chip.get_baseline() print('>> Baseline:', baseline) sleep(10)
def main(): smbus = SMBus(1) # zero on some boards warming_up = True baseline_counter = 0 with SGP30(smbus) as chip: while True: measurement = chip.measure_air_quality() # Chip returns (400, 0) for the first ~15 seconds while it warms up if warming_up: if measurement.is_probably_warmup_value(): print('... warming up ...') sleep(1) continue else: warming_up = False print(measurement) # Domoticz update script # CO2 update to Domoticz requests.get(DOMOTICZ_IP + "/json.htm?type=command¶m=udevice&idx=" + DEVICE_IDX_CO + "&nvalue=" + str(measurement[1])) # print(DOMOTICZ_IP + "/json.htm?type=command¶m=udevice&idx=" + DEVICE_IDX_CO + "&nvalue=" + str(measurement[1])) # VOC update to Domoticz requests.get(DOMOTICZ_IP + "/json.htm?type=command¶m=udevice&idx=" + DEVICE_IDX_VOC + "&nvalue=0&svalue=" + str(measurement[2])) # print(DOMOTICZ_IP + "/json.htm?type=command¶m=udevice&idx=" + DEVICE_IDX_VOC + "&nvalue=0&svalue=" + str(measurement[2])) # Don't take this as a complete example... read the spec sheet about how you're supposed to stash and restore the baseline, initial burn-in, humidity compensation, *and how you need to sample every second to maintain accurate results* baseline_counter = baseline_counter + 1 if baseline_counter % 100 == 0: baseline_counter = 0 baseline = chip.get_baseline() print('>> Baseline:', baseline) sleep(1)
async def sgp30_task(main_queue, config): sgp30 = SGP30(config['i2c']) lock = config['lock'] update_rate = config['update_rate'] if sgp30.init(): await main_queue.put(('sgp30_info', 'ok')) else: await main_queue.put(('sgp30_info', 'error')) return try: while True: sgp30.measure_air_quality() if sgp30.status[0] == 'error': print(sgp30.status[1]) await main_queue.put(('sgp30_info', 'error')) else: # TODO: create communication protocol (not substracting 400 from co2) await main_queue.put(('sgp30_data', {"co2": sgp30.eco2-400, "voc": sgp30.tvoc})) await asyncio.sleep(update_rate) except asyncio.CancelledError: return
def test_get_unique_id(): from sgp30 import SGP30 sgp30 = SGP30(i2c_dev=MockI2CDev(), i2c_msg=MockI2CMsg()) assert sgp30.get_unique_id() == 0xffffffffffff
def test_get_feature_set_version(): from sgp30 import SGP30 sgp30 = SGP30(i2c_dev=MockI2CDev(), i2c_msg=MockI2CMsg()) assert sgp30.get_feature_set_version() == (0xc, 0xfe)
def test_setup(): from sgp30 import SGP30 sgp30 = SGP30(i2c_dev=MockI2CDev(), i2c_msg=MockI2CMsg()) del sgp30
from smbus2 import SMBus from sgp30 import SGP30 if __name__ == "__main__": bus = SMBus(1) sensor = SGP30(bus) print(sensor.read_features()) print(sensor.read_serial()) sensor.init_sgp() for i in range(300): print(sensor.read_measurements()) time.sleep(0.1) sensor.store_baseline() bus.close()
from umqtt.simple import MQTTClient from ubinascii import b2a_base64 from sgp30 import SGP30 from config import * from restapi import RestApi sta_if = network.WLAN(network.STA_IF) epoch_offset = 946684800 ## sgp30 setup i2c = SoftI2C(scl=Pin(device_config['scl']), sda=Pin(device_config['sda']), freq=100000) sgp30 = SGP30(i2c) sgp30.initialise_indoor_air_quality() ## neopixel np = NeoPixel(Pin(device_config['led']), 1) if app_config['audio']: ## audio setup SAMPLES_PER_SECOND = 11025 audio_out = I2S(I2S.NUM0, bck=Pin(device_config['bck']), ws=Pin(device_config['ws']), sdout=Pin(device_config['sdout']), standard=I2S.PHILIPS, mode=I2S.MASTER_TX,
def main(config): try: client = connect_to_mqtt(config) except OSError: sleep(10) restart_and_reconnect() if display_present1: writer1 = Writer(oled1, Arial15) if display_present2: writer2 = Writer(oled2, Arial11) while True: light_sensor.init() light = light_sensor.getLux() if display_present1: oled1.fill(0) oled1.show() if display_present2: oled2.fill(0) oled2.show() pms_enable.value(1) # uart1 = UART(1) # uart1.init(baudrate=9600, rx=1, bits=8, parity=None, stop=1) # pms = Pms7003(uart1) # pms.read() pms_enable.value(0) uart2 = UART(2) uart2.init(baudrate=9600, tx=19, rx=18, bits=8, parity=None, stop=1) sensorCO2 = MHZ19BSensor(uart2) co2 = sensorCO2.measure() if bmx_present1: temp = float(sensor.temperature[:-3]) humid = float(sensor.humidity[:-3]) press = float(sensor.pressure[:-3]) if (display_present1 and light > 0): if bmx_present1: writer1.set_textpos(0, 0) writer1.printstring("Temp: %.0f °C" % temp) writer1.set_textpos(16, 0) writer1.printstring("Humid: %.0f %%" % humid) writer1.set_textpos(32, 0) writer1.printstring("%.0f hPa" % press) oled1.show() if (display_present2 and light > 0): if bmx_present1: writer2.set_textpos(0, 0) writer2.printstring("Temp: %.0f °C" % temp) writer2.set_textpos(12, 0) writer2.printstring("Humid: %.0f %%" % humid) writer2.set_textpos(24, 0) writer2.printstring("%.0f hPa" % press) writer2.set_textpos(36, 0) writer2.printstring("%.0f ppm" % co2) oled2.show() if bmx_present1: print("Temperature: %.0f °C" % temp) print("Humidity: %.0f %%" % humid) print("Pressure: %.0f hPa" % press) print("CO2: %.f ppm" % co2) try: if bmx_present1: client.publish(topic1, str("%.0f" % temp), qos=QOS) client.publish(topic2, str("%.0f" % humid), qos=QOS) client.publish(topic3, str("%.0f" % press), qos=QOS) except OSError: restart_and_reconnect() sleep(5) print("Light Intensity: %.4s lux" % light) if sgp30_present: airquality = SGP30(i2c) print("eCO2: %d ppm" % airquality.co2_equivalent) print("TVOC: %d ppb" % airquality.total_organic_compound) if (display_present1 and light > 0): oled1.fill(0) oled1.show() if bmx_present1: writer1.set_textpos(0, 0) writer1.printstring("Temp: %.0f °C" % temp) writer1.set_textpos(16, 0) writer1.printstring("Humid: %.0f %%" % humid) writer1.set_textpos(32, 0) writer1.printstring("%.0f hPa" % press) oled1.show() if (display_present2 and light > 0): oled2.fill(0) oled2.show() writer2.set_textpos(0, 0) writer2.printstring("light:%.4s lux" % light) if sgp30_present: writer2.set_textpos(24, 0) writer2.printstring("co2:%d ppm" % airquality.co2_equivalent) writer2.set_textpos(36, 0) writer2.printstring("Tvoc:%d ppb" % airquality.total_organic_compound) oled2.show() try: client.publish(topic4, str(light), qos=QOS) client.publish(topic5, str(co2), qos=QOS) if sgp30_present: client.publish(topic6, str(airquality.total_organic_compound), qos=QOS) except OSError: restart_and_reconnect() sleep(5) if display_present1: oled1.fill(0) oled1.show() if display_present2: oled2.fill(0) oled2.show() sleep(5)
###MH-Z16 try: mh = NDIR.Sensor(0x4D) mh.begin() except: print('mh not connected') logging.info('mh not conected') ###VL53L0X tof = VL53L0X.VL53L0X() tof.start_ranging(VL53L0X.VL53L0X_BETTER_ACCURACY_MODE) logging.info('Sensor setup done') with SGP30(smbus) as chip: while True: tim, lat, lon, alt, spe, T, H, W, L, N, C, V, D = (dt.datetime.now( tz=pytz.timezone("Europe/Berlin")), 'None', 'None', 'None', 'None', 0, 0, 0, 0, 0, 0, 0, 0) ###GPS try: if not session: session = gps.gps('localhost', '2947') session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) report = session.next() if report['class'] == 'TPV': if hasattr(report, 'lat'): lat = round(report.lat, 6) if hasattr(report, 'lon'): lon = round(report.lon, 6)
def __init__(self): # First, check to see if there is a BME680 on the I2C bus try: self.bus.write_byte(0x76, 0) except IOError: print('BME680 not found on 0x76, trying 0x77') else: self.readfrom = 'bme680primary' # If we didn't find it on 0x76, look on 0x77 if self.readfrom == 'unset': try: self.bus.write_byte(0x77, 0) except IOError: print('BME680 not found on 0x77') else: self.readfrom = 'bme680secondary' # If no BME680, is there a Sense HAT? if self.readfrom == 'unset': try: self.bus.write_byte(0x5F, 0) except: print('Sense HAT not found') else: self.readfrom = 'sense-hat' print('Using Sense HAT for readings (no gas measurements)') # Import the sense hat methods import sense_hat_air_quality from hts221 import HTS221 self.sense_hat_reading = lambda: sense_hat_air_quality.get_readings( HTS221()) else: print('Using BME680 for readings') # Import the BME680 methods self.sensor = BME680(self.readfrom) # Next, check if there is a 1-wire temperature sensor (e.g. DS18B20) if self.readfrom == 'unset': if os.environ.get('BALENASENSE_1WIRE_SENSOR_ID') != None: sensor_id = os.environ['BALENASENSE_1WIRE_SENSOR_ID'] else: sensor_id = None try: self.sensor = W1THERM(sensor_id) except: print('1-wire sensor not found') else: self.readfrom = '1-wire' print('Using 1-wire for readings (temperature only)') if self.readfrom == 'unset': try: self.sensor = SGP30() print("SGP30 serial #", self.sensor.get_id()) self.readfrom = 'sgp30' except: print('Failed to spin up sgp30 sensor') # If this is still unset, no sensors were found; quit! if self.readfrom == 'unset': print('No suitable sensors found! Exiting.') sys.exit()
def __init__(self): self._sgp30_sensor = SGP30() self._run = True if ENABLE_DHT22: self._dht22_sensor = adafruit_dht.DHT22( getattr(board, f"D{DHT22_PIN}"))
rotary_menu = [ {'label': 'Humidity', 'callback': lambda: round( dhts.humidity(), 1 ), 'u': '%', 'icon': ICONS['humidity']}, #{'label': 'Temperature', #'callback': lambda: round( (dhts.temperature() * 1.8) + 32, 1 ), 'u': 'F', #'icon': ICONS['therm']}, #{'label': 'Magnet', 'callback': lambda: esp32.hall_sensor(), 'u': 'm', #'icon': ICONS['magnet']}, ] bme = None sgp = None iaq = None try: sgp = SGP30( i2c ) iaq = sgp.indoor_air_quality rotary_menu.append( {'label': 'TVOC', 'callback': lambda: iaq[1], 'u': 'p', 'icon': ICONS['tvoc'] } ) rotary_menu.append( {'label': 'eCO2', 'callback': lambda: iaq[0], 'u': 'p', 'icon': ICONS['carbon']} ) except Exception as e: try: bme = BME680_I2C( i2c=i2c ) rotary_menu.append( {'label': 'Temp', 'u': 'F', 'icon': ICONS['therm'], 'callback': lambda: round( bme.temperature, 1 )} ) rotary_menu.append( {'label': 'Humidity', 'icon': ICONS['humidity'], 'u': '%',
from sgp30 import SGP30 import time import sys sgp30 = SGP30() # result = sgp30.command('set_baseline', (0xFECA, 0xBEBA)) # result = sgp30.command('get_baseline') # print(["{:02x}".format(n) for n in result]) print("Sensor warming up, please wait...") def crude_progress_bar(): sys.stdout.write('.') sys.stdout.flush() sgp30.start_measurement(crude_progress_bar) sys.stdout.write('\n') while True: result = sgp30.get_air_quality() print(result) time.sleep(1.0)
import smbus import time from sgp30 import SGP30 from gpiozero import LED import RPi.GPIO as GPIO #i2c bus #1 (#0 is only used for IDing on the pi) bus = smbus.SMBus(1) chip = SGP30(bus) chip.open() GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN) RED_LED = LED(4) GREEN_LED = LED(22) #SI7021 address temperatureAddress = 0x40 humidityAddress = 0x40 #SGP30 address airQualityAddress = 0x58 def RedLight(value): if value == 1: RED_LED.on() else: RED_LED.off()