def measurement(): try: # load settings settings = get_settings() # read configured sensors from settings.json ds18b20Sensors = get_sensors(settings, 0) bme680Sensors = get_sensors(settings, 1) weightSensors = get_sensors(settings, 2) dhtSensors = get_sensors(settings, 3) # if bme680 is configured if bme680Sensors and len(bme680Sensors) == 1: gas_baseline = None if initBME680FromMain(): # bme680 sensor must be burned in before use gas_baseline = burn_in_bme680(10) # if burning was canceled => exit if gas_baseline is None: print("gas_baseline can't be None") # dict with all fields and values which will be tranfered to ThingSpeak later ts_fields = {} # measure every sensor with type 0 for (sensorIndex, sensor) in enumerate(ds18b20Sensors): if 'ts_field' in sensor and 'device_id' in sensor: ts_field_ds18b20 = sensor["ts_field"] ds18b20_temperature = measure_temperature(sensor["device_id"]) ts_fields.update({ts_field_ds18b20: ds18b20_temperature}) else: print("DS18b20 missing param: ts_field or device_id") # measure BME680 (can only be once) [type 1] if bme680Sensors and len(bme680Sensors) == 1 and gas_baseline: bme680_values = measure_bme680(gas_baseline, bme680Sensors[0]) ts_fields.update(bme680_values) # disable warnings for HX711 GPIO.setwarnings(False) # measure every sensor with type 2 [HX711] for (i, sensor) in enumerate(weightSensors): weight = measure_weight(sensor) ts_fields.update(weight) # measure every sensor with type 3 [DHT11/DHT22] for (i, sensor) in enumerate(dhtSensors): tempAndHum = measure_dht(sensor) ts_fields.update(tempAndHum) return json.dumps(ts_fields) except Exception as e: print("Measurement: " + str(e))
def read_values(): records = 10 # after this many records we make a record values = [] while not event.is_set(): counter = 0 while counter < records and not event.is_set(): temperature = None try: temperature = get_temperature(get_sensors(0)[0]) print "temperature: " + str(temperature) except IOError: print "IOError occurred" except TypeError: print "TypeError occurred" if math.isnan(temperature) == False: values.append(temperature) counter += 1 sleep(1) lock.acquire() filtered_temperature.append(numpy.mean(filter_values([x for x in values]))) lock.release() values = []
def start_measurement(measurement_stop): try: global burn_in_time start_time = time.time() # load settings settings = get_settings() ts_channels = settings[ "ts_channels"] # ThingSpeak data (ts_channel_id, ts_write_key) ts_server_url = settings["ts_server_url"] debuglevel = settings["debuglevel"] if debuglevel <= 10: debug = True # flag to enable debug mode (HDMI output enabled and no rebooting) else: debug = False # flag to enable debug mode (HDMI output enabled and no rebooting) wittyPi = settings["wittyPi"] offline = settings["offline"] # flag to enable offline csv storage isLowVoltage = getStateFromStorage('isLowVoltage', False) if isLowVoltage == True: interval = wittyPi["low"]["interval"] shutdownAfterTransfer = wittyPi["low"]["shutdownAfterTransfer"] else: interval = wittyPi["normal"]["interval"] shutdownAfterTransfer = wittyPi["normal"]["shutdownAfterTransfer"] if debug: logger.info("The measurements have started.") # with process shared variables connectionErrors = Value('i', 0) measurementIsRunning = Value('i', 0) if interval and not isinstance(interval, int) or interval == 0: interval = 0 logger.info("Stop measurement because interval is null.") measurement_stop.set() # read configured sensors from settings.json ds18b20Sensors = get_sensors(settings, 0) bme680Sensors = get_sensors(settings, 1) weightSensors = get_sensors(settings, 2) dhtSensors = get_sensors(settings, 3) tcSensors = get_sensors(settings, 4) bme280Sensors = get_sensors(settings, 5) pcf8591Sensors = get_sensors(settings, 6) ee895Sensors = get_sensors(settings, 7) aht10Sensors = get_sensors(settings, 8) sht31Sensors = get_sensors(settings, 9) hdc1008Sensors = get_sensors(settings, 10) bme680Inits = [] # -- Run Pre Configuration -- # if bme680 is configured for (sensorIndex, bme680Sensor) in enumerate(bme680Sensors): bme680Init = {} if 'burn_in_time' in bme680Sensor: burn_in_time = bme680Sensor["burn_in_time"] sensor = initBME680FromMain(bme680Sensor) gas_baseline = burn_in_bme680(sensor, burn_in_time) bme680Init['sensor'] = sensor bme680Init['gas_baseline'] = gas_baseline bme680Inits.append(bme680Init) # if hx711 is set hxInits = [] for (i, sensor) in enumerate(weightSensors): _hx = init_hx711(sensor) hxInits.append(_hx) # PCF8591 if pcf8591Sensors and len(pcf8591Sensors) == 1: voltage = get_raw_voltage( pcf8591Sensors[0] ) # initial measurement as first measurement is always wrong # -- End Pre Configuration -- # start at -6 because we want to get 6 values before we can filter some out counter = -6 time_measured = 0 time_measured_Voltage = 0 # Main loop which checks every second while not measurement_stop.is_set(): counter += 1 time_now = time.time() for (sensorIndex, sensor) in enumerate(ds18b20Sensors): checkIfSensorExistsInArray(sensorIndex) if 'device_id' in sensor: read_unfiltered_temperatur_values(sensorIndex, sensor) time_measured_Voltage, interval, shutdownAfterTransfer, isLowVoltage = check_wittypi_voltage( time_measured_Voltage, wittyPi, pcf8591Sensors, isLowVoltage, interval, shutdownAfterTransfer) # wait seconds of interval before next check # free ThingSpeak account has an upload limit of 15 seconds isTimeToMeasure = ((time_now - time_measured >= interval) or (interval == 1)) and counter > 0 if isTimeToMeasure: now = time.strftime("%H:%M", time.localtime(time_now)) lastMeasurement = time.strftime("%H:%M", time.localtime(time_measured)) if time_measured == 0: print("First time measurement. Now: " + str(now)) else: print("Last measurement was at " + str(lastMeasurement)) print("Time over for a new measurement. Time is now: " + str(now)) time_measured = time.time() check_undervoltage('0x7') if measurementIsRunning.value == 0: q = Queue() p = Process(target=measure, args=(q, offline, debug, ts_channels, ts_server_url, filtered_temperature, ds18b20Sensors, bme680Sensors, bme680Inits, dhtSensors, aht10Sensors, sht31Sensors, hdc1008Sensors, tcSensors, bme280Sensors, pcf8591Sensors, ee895Sensors, weightSensors, hxInits, connectionErrors, measurementIsRunning)) p.start() p.join() else: logger.warning( "Forerun measurement is not finished yet. Consider increasing interval." ) # stop measurements after uploading once if interval == 1: print("Only one measurement was set => stop measurements.") measurement_stop.set() if shutdownAfterTransfer: isMaintenanceActive = getStateFromStorage( 'isMaintenanceActive', False) print("Wert isMaintenanceActive: " + str(isMaintenanceActive)) while isMaintenanceActive: isMaintenanceActive = getStateFromStorage( 'isMaintenanceActive', False) print( "Shutting down was set but Maintenance mode is active, delaying shutdown!" ) print("Wert isMaintenanceActive: " + str(isMaintenanceActive)) time.sleep(10) print( "Shutting down was set => Waiting 10seconds and then shutdown." ) tblink = threading.Thread(target=blink_led, args=(settings["led_pin"], 0.25)) tblink.start() time.sleep(10) shutdown() time.sleep(6) # wait 6 seconds before next measurement check end_time = time.time() time_taken = end_time - start_time # time_taken is in seconds time_taken_s = float( "{0:.2f}".format(time_taken)) # remove microseconds print("Measurement-Script runtime was " + str(time_taken_s) + " seconds.") except Exception as ex: logger.exception("Unhandled Exception in start_measurement") if not debug: time.sleep(10) reboot()
def measurement(): try: # load settings settings = get_settings() # read configured sensors from settings.json ds18b20Sensors = get_sensors(settings, 0) bme680Sensors = get_sensors(settings, 1) weightSensors = get_sensors(settings, 2) dhtSensors = get_sensors(settings, 3) tcSensors = get_sensors(settings, 4) bme280Sensors = get_sensors(settings, 5) # if bme680 is configured if bme680Sensors and len(bme680Sensors) == 1: bme680IsInitialized = initBME680FromMain(bme680Sensors) else: bme680IsInitialized = 0 # dict with all fields and values which will be tranfered to ThingSpeak later ts_fields = {} # measure every sensor with type 0 for (sensorIndex, sensor) in enumerate(ds18b20Sensors): if 'ts_field' in sensor and 'device_id' in sensor: ts_field_ds18b20 = sensor["ts_field"] ds18b20_temperature = measure_temperature(sensor["device_id"]) ts_fields.update({ts_field_ds18b20: ds18b20_temperature}) else: print("DS18b20 missing param: ts_field or device_id") # measure BME680 (can only be one) [type 1] if bme680Sensors and len(bme680Sensors) == 1 and bme680IsInitialized: bme680_values = measure_bme680(bme680Sensors[0], 10) ts_fields.update(bme680_values) # measure every sensor with type 3 [DHT11/DHT22] for (i, sensor) in enumerate(dhtSensors): tempAndHum = measure_dht(sensor) ts_fields.update(tempAndHum) # measure every sensor with type 4 [MAX6675] for (i, sensor) in enumerate(tcSensors): tc_temp = measure_tc(sensor) ts_fields.update(tc_temp) # measure BME280 (can only be one) [type 5] if bme280Sensors and len(bme280Sensors) == 1: bme280_values = measure_bme280(bme280Sensors[0]) ts_fields.update(bme280_values) start_single() # measure every sensor with type 2 [HX711] for (i, sensor) in enumerate(weightSensors): weight = measure_weight(sensor) weight = compensate_temperature(sensor, weight, ts_fields) ts_fields.update(weight) stop_single() return json.dumps(ts_fields) except Exception as e: print("Measurement: " + str(e)) # Error occured return {}
def measurement(): # dict with all fields and values which will be tranfered to ThingSpeak later ts_fields = {} try: # load settings settings = get_settings() # read configured sensors from settings.json ds18b20Sensors = get_sensors(settings, 0) bme680Sensors = get_sensors(settings, 1) weightSensors = get_sensors(settings, 2) dhtSensors = get_sensors(settings, 3) tcSensors = get_sensors(settings, 4) bme280Sensors = get_sensors(settings, 5) voltageSensors = get_sensors(settings, 6) ee895Sensors = get_sensors(settings, 7) aht10Sensors = get_sensors(settings, 8) sht31Sensors = get_sensors(settings, 9) hdc1008Sensors = get_sensors(settings, 10) bme680IsInitialized = {} # if bme680 is configured for (sensorIndex, bme680Sensor) in enumerate(bme680Sensors): bme680IsInitialized[sensorIndex] = 0 bme680IsInitialized[sensorIndex] = initBME680FromMain(bme680Sensor) ts_fields = measure_all_sensors(False, None, ds18b20Sensors, bme680Sensors, bme680IsInitialized, dhtSensors, aht10Sensors, sht31Sensors, hdc1008Sensors, tcSensors, bme280Sensors, voltageSensors, ee895Sensors, weightSensors, None) return json.dumps(ts_fields) except Exception as e: error_log(e, "Unhandled Exception in Measurement 2") # Error occured return {}
def start_measurement(measurement_stop): try: start_time = time.time() # load settings settings = get_settings() # ThingSpeak data channel_id = settings["ts_channel_id"] write_key = settings["ts_write_key"] interval = settings["interval"] debug = settings[ "debug"] # flag to enable debug mode (HDMI output enabled and no rebooting) shutdownAfterTransfer = settings["shutdownAfterTransfer"] offline = settings["offline"] # flag to enable offline csv storage if debug: print("Debug-Mode is enabled.") error_log("Info: The measurements have started.") # with process shared variables connectionErrors = Value('i', 0) measurementIsRunning = Value('i', 0) if interval and not isinstance( interval, int) or interval == 0 or not channel_id or not write_key: error_log( "Info: No measurement because ThingSpeak settings are not complete or measurement interval is null." ) measurement_stop.set() # read configured sensors from settings.json ds18b20Sensors = get_sensors(settings, 0) bme680Sensors = get_sensors(settings, 1) weightSensors = get_sensors(settings, 2) dhtSensors = get_sensors(settings, 3) tcSensors = get_sensors(settings, 4) bme280Sensors = get_sensors(settings, 5) # -- Run Pre Configuration -- # if bme680 is configured if bme680Sensors and len(bme680Sensors) == 1: bme680IsInitialized = initBME680FromMain() else: bme680IsInitialized = 0 # if hx711 is set hxInits = [] for (i, sensor) in enumerate(weightSensors): _hx = init_hx711(sensor, debug) hxInits.append(_hx) # ThingSpeak channel channel = thingspeak.Channel(id=channel_id, write_key=write_key) # start at -6 because we want to get 6 values before we can filter some out counter = -6 time_measured = 0 while not measurement_stop.is_set(): counter += 1 # read values from sensors every second for (sensorIndex, sensor) in enumerate(ds18b20Sensors): checkIfSensorExistsInArray(sensorIndex) if 'device_id' in sensor: read_unfiltered_temperatur_values(sensorIndex, sensor['device_id']) # wait seconds of interval before next check # free ThingSpeak account has an upload limit of 15 seconds time_now = time.time() isTimeToMeasure = (time_now - time_measured >= interval ) and counter > 0 # old: counter%interval == 0 if isTimeToMeasure or interval == 1: now = time.strftime("%H:%M", time.localtime(time_now)) lastMeasurement = time.strftime("%H:%M", time.localtime(time_measured)) if time_measured == 0: print("First time measurement. Now: " + str(now)) else: print("Last measurement was at " + str(lastMeasurement)) print("Time over for a new measurement. Time is now: " + str(now)) time_measured = time.time() if measurementIsRunning.value == 0: q = Queue() p = Process(target=measure, args=(offline, debug, channel, filtered_temperature, ds18b20Sensors, bme680Sensors, bme680IsInitialized, dhtSensors, tcSensors, bme280Sensors, weightSensors, hxInits, connectionErrors, measurementIsRunning)) p.start() p.join() else: error_log( "Warning: Forerun measurement is not finished yet. Consider increasing interval." ) # stop measurements after uploading once if interval == 1: print("Only one measurement was set => stop measurements.") measurement_stop.set() if shutdownAfterTransfer: print( "Shutting down was set => Waiting 10seconds and then shutdown." ) time.sleep(10) shutdown() time.sleep(6) # wait 6 seconds before next measurement check end_time = time.time() time_taken = end_time - start_time # time_taken is in seconds time_taken_s = float( "{0:.2f}".format(time_taken)) # remove microseconds print("Measurement-Script runtime was " + str(time_taken_s) + " seconds.") except Exception as e: error_log(e, "Unhandled Exception while Measurement") if not debug: time.sleep(10) reboot()
def measurement(): # dict with all fields and values which will be tranfered to ThingSpeak later ts_fields = {} global burn_in_time try: # read settings settings = get_settings() debuglevel = int(settings["debuglevel"]) debuglevel_logfile = int(settings["debuglevel_logfile"]) logger = logging.getLogger('HoneyPi.measurement') logger.setLevel(logging.DEBUG) fh = logging.FileHandler(logfile) fh.setLevel(logging.getLevelName(debuglevel_logfile)) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.getLevelName(debuglevel)) # create formatter and add it to the handlers formatter = logging.Formatter( '%(asctime)s | %(levelname)s | %(name)s | %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to the logger logger.addHandler(fh) logger.addHandler(ch) logger.info('Direct measurement started from webinterface.') # read configured sensors from settings.json ds18b20Sensors = get_sensors(settings, 0) bme680Sensors = get_sensors(settings, 1) weightSensors = get_sensors(settings, 2) dhtSensors = get_sensors(settings, 3) tcSensors = get_sensors(settings, 4) bme280Sensors = get_sensors(settings, 5) pcf8591Sensors = get_sensors(settings, 6) ee895Sensors = get_sensors(settings, 7) aht10Sensors = get_sensors(settings, 8) sht31Sensors = get_sensors(settings, 9) hdc1008Sensors = get_sensors(settings, 10) bme680Inits = [] # if bme680 is configured for (sensorIndex, bme680Sensor) in enumerate(bme680Sensors): bme680Init = {} if 'burn_in_time' in bme680Sensor: burn_in_time = bme680Sensor["burn_in_time"] sensor = initBME680FromMain(bme680Sensor) gas_baseline = burn_in_bme680(sensor, burn_in_time) bme680Init['sensor'] = sensor bme680Init['gas_baseline'] = gas_baseline bme680Inits.append(bme680Init) ts_fields, bme680Inits = measure_all_sensors( False, None, ds18b20Sensors, bme680Sensors, bme680Inits, dhtSensors, aht10Sensors, sht31Sensors, hdc1008Sensors, tcSensors, bme280Sensors, pcf8591Sensors, ee895Sensors, weightSensors, None) except Exception as ex: logger.exception("Unhandled Exception in direct measurement") return json.dumps(ts_fields)
#!/usr/bin/env python import time from pprint import pprint import bme680 from HX711 import HX711 from read_settings import get_settings, get_sensors settings = get_settings() # weight sensor pins pin_dt = get_sensors(2)[0]["pin_dt"] pin_sck = get_sensors(2)[0]["pin_sck"] reference_unit = get_sensors(2)[0]["reference_unit"] # setup weight sensor hx = HX711(pin_dt, pin_sck) hx.set_reading_format("LSB", "MSB") # HOW TO CALCULATE THE REFFERENCE UNIT # To set the reference unit to 1. Put 1kg on your sensor or anything you have and know exactly how much it weights. # In this case, 92 is 1 gram because, with 1 as a reference unit I got numbers near 0 without any weight # and I got numbers around 184000 when I added 2kg. So, according to the rule of thirds: # If 2000 grams is 184000 then 1000 grams is 184000 / 2000 = 92. # hx.set_reference_unit(113) hx.set_reference_unit(reference_unit) hx.reset() hx.tare()
#!/usr/bin/env python3 from pprint import pprint from read_settings import get_settings, get_sensors settings = get_settings() # liefert sensoren vom Type 0 (DS18b20) sensors = get_sensors(0) pprint(sensors)
def start_measurement(measurement_stop): try: print("The measurements have started.") start_time = time.time() # load settings settings = get_settings() # ThingSpeak data channel_id = settings["ts_channel_id"] write_key = settings["ts_write_key"] interval = settings["interval"] if interval and not isinstance( interval, int) or interval == 0 or not channel_id or not write_key: print("ThingSpeak settings are not complete or interval is 0") measurement_stop.set() # read configured sensors from settings.json ds18b20Sensors = get_sensors(settings, 0) bme680Sensors = get_sensors(settings, 1) weightSensors = get_sensors(settings, 2) dhtSensors = get_sensors(settings, 3) # if bme680 is configured if bme680Sensors and len(bme680Sensors) == 1: gas_baseline = None if initBME680FromMain(): # bme680 sensor must be burned in before use gas_baseline = burn_in_bme680(30) # if burning was canceled => exit if gas_baseline is None: print("gas_baseline can't be None") # ThingSpeak channel channel = thingspeak.Channel(id=channel_id, write_key=write_key) # counting connection Errors connectionErros = 0 # start at -6 because we want to get 6 values before we can filter some out counter = -6 while not measurement_stop.is_set(): # read values from sensors every second for (sensorIndex, sensor) in enumerate(ds18b20Sensors): checkIfSensorExistsInArray(sensorIndex) if 'device_id' in sensor: read_unfiltered_temperatur_values(sensorIndex, sensor['device_id']) # for testing: #try: # weight = measure_weight(weightSensors[0]) # print("weight: " + str(list(weight.values())[0])) #except IOError: # print "IOError occurred" #except TypeError: # print "TypeError occurred" #except IndexError: # print "IndexError occurred" # wait seconds of interval before next check # free ThingSpeak account has an upload limit of 15 seconds if counter % interval == 0: print("Time over for a new measurement.") # filter the values out for (sensorIndex, sensor) in enumerate(ds18b20Sensors): filter_temperatur_values(sensorIndex) # dict with all fields and values which will be tranfered to ThingSpeak later ts_fields = {} # measure every sensor with type 0 for (sensorIndex, sensor) in enumerate(ds18b20Sensors): # if we have at leat one filtered value we can upload if len(filtered_temperature[sensorIndex] ) > 0 and 'ts_field' in sensor: ds18b20_temperature = filtered_temperature[ sensorIndex].pop() # get last value from array ts_field_ds18b20 = sensor["ts_field"] if ts_field_ds18b20: ts_fields.update( {ts_field_ds18b20: ds18b20_temperature}) # measure BME680 (can only be once) [type 1] if bme680Sensors and len(bme680Sensors) == 1 and gas_baseline: bme680_values = measure_bme680(gas_baseline, bme680Sensors[0]) ts_fields.update(bme680_values) # measure every sensor with type 2 [HX711] for (i, sensor) in enumerate(weightSensors): weight = measure_weight(sensor) ts_fields.update(weight) # measure every sensor with type 3 [DHT11/DHT22] for (i, sensor) in enumerate(dhtSensors): tempAndHum = measure_dht(sensor) ts_fields.update(tempAndHum) # print measurement values for debug reasons for key, value in ts_fields.iteritems(): print key + ": " + str(value) try: # update ThingSpeak / transfer values if len(ts_fields) > 0: channel.update(ts_fields) # reset connectionErros because transfer succeded connectionErros = 0 except requests.exceptions.HTTPError as errh: error_log(errh, "Http Error") except requests.exceptions.ConnectionError as errc: error_log(errc, "Error Connecting") connectionErros += 1 # multiple connectionErrors in a row => Exception if connectionErros > 4: raise MyRebootException except requests.exceptions.Timeout as errt: error_log(errt, "Timeout Error") except requests.exceptions.RequestException as err: error_log(err, "Something Else") counter += 1 sleep(0.96) end_time = time.time() time_taken = end_time - start_time # time_taken is in seconds time_taken_s = float( "{0:.2f}".format(time_taken)) # remove microseconds print("Measurement-Script runtime was " + str(time_taken_s) + " seconds.") except MyRebootException as re: error_log(re, "Too many ConnectionErrors in a row => Rebooting") time.sleep(1) reboot() except Exception as e: error_log(e, "Unhandled Exception while Measurement") time.sleep(60) reboot()
def start_read_and_upload_all(measurement_stop): print("Messungen beginnen") # reset event flag in case thread is started again measurement_stop.clear() event.clear() # bme680 sensor must be burned in before use gas_baseline = burn_in_bme680() # if burning was canceled=> exit if gas_baseline is None: print "gas_baseline can't be None" stop_read_and_upload_all() # here we start the thread # we use a thread in order to gather/process the data separately from the printing process data_collector = threading.Thread(target=read_values) data_collector.start() # ThingSpeak channel channel = thingspeak.Channel(id=channel_id, write_key=write_key) counter = 0 while not event.is_set() and not measurement_stop.is_set(): # wait seconds of interval before next check # free ThingSpeak account has an upload limit of 15 seconds if counter%interval == 0: if len(filtered_temperature) > 0: # or we could have used filtered_humidity instead lock.acquire() # dict with all fields and values with will be tranfered later to ThingSpeak ts_fields = {} # here you can do whatever you want with the variables: print them, file them out, anything # measure sensor with type 0 ds18b20_temperature = filtered_temperature.pop() ts_field_ds18b20 = get_sensors(0)[0]["ts_field"] ts_fields.update({ts_field_ds18b20: ds18b20_temperature}) # measure BME680 (can only be once) bme680_values = measure_bme680(gas_baseline, get_sensors(1)[0]) ts_fields.update(bme680_values) # measure every sensor with type 2 for (i, sensor) in enumerate(get_sensors(2)): weight = measure_weight(sensor) ts_fields.update(weight) # print measurement values for debug reasons for key, value in ts_fields.iteritems(): print key + ": " + str(value) try: # update ThingSpeak / transfer values channel.update(ts_fields) except HTTPError: print "HTTPError occurred" lock.release() counter++ sleep(1) # wait until the thread is finished data_collector.join()