def initSensorDS18B20(self): if self.config.get('ENVIRONMENT') == 'production': try: self.app.logger.info('Init DS18B20 sensor %s', self.name) from w1thermsensor import W1ThermSensor self.sensor = W1ThermSensor( W1ThermSensor.THERM_SENSOR_DS18B20, self.config.get('TEMPERATURE_SENSOR_ADDRESS')) task = threading.Thread(target=self.runDS18B20) task.start() except Exception as e: self.app.logger.exception(e)
def __init__(self, input_dev, testing=False): super(InputModule, self).__init__(input_dev, testing=testing, name=__name__) if not testing: from w1thermsensor import W1ThermSensor self.location = input_dev.location self.resolution = input_dev.resolution self.sensor = W1ThermSensor( W1ThermSensor.THERM_SENSOR_DS1825, self.location) if self.resolution: self.sensor.set_resolution(self.resolution)
def PostOneWireData(sensor_id, MQTT_topic): try: sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, sensor_id) temperature_in_celsius = sensor.get_temperature() print("Sensor %s has temperature %.2f" % (sensor.id, temperature_in_celsius)) temperature_formated=str('{:0.1f}').format(temperature_in_celsius) client.publish(MQTT_topic+"Temp",temperature_formated) return 0 except Exception as inst: print("Can not retrieve or publish sensor :", sensor_id, MQTT_topic) print(inst) return -1
def readProbe(sensor_id): try: sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, sensor_id) temperature_c = sensor.get_temperature() print("The temperature is %s celsius" % temperature_c) temperature_f = temperature_c * 9.0 / 5.0 + 32.0 print("The temperature is %s f" % temperature_f) except: print("Sensor not found") temperature_f = 32 pass return (temperature_f)
def init(self): #Hardware configuration: try: # Create an DS18B20 instance. self.DS18B20 = W1ThermSensor() except Exception as e: print("DS18B20Config: Error initialising device - exit") print(str(e)) sys.exit(1) # provide configuration parameters self.ChanNams = ['DS18B20']
def __init__(self, pin, resolution, convert_to_unit=None, testing=False): super(DS1822Sensor, self).__init__() self._temperature = None self.pin = pin self.resolution = resolution self.convert_to_unit = convert_to_unit if not testing: self.sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS1822, self.pin) if self.resolution: self.sensor.set_precision(self.resolution)
def test_sensor_all_temperature_units(): _remove_w1_therm_sensors() # create DS18B20 sensor with 20 C degrees sensor_id = _create_w1_therm_sensor(W1ThermSensor.THERM_SENSOR_DS18B20, temperature=20) sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, sensor_id) sensor.id.should.be.equal(sensor_id) sensor.get_temperatures([ W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN ]).should.be.equal([20, 68, 293.15])
def test_sensor_type_name(): _remove_w1_therm_sensors() # create sensors of all types ds18s20_sensor_id = _create_w1_therm_sensor( W1ThermSensor.THERM_SENSOR_DS18S20) ds1822_sensor_id = _create_w1_therm_sensor( W1ThermSensor.THERM_SENSOR_DS1822) ds18b20_sensor_id = _create_w1_therm_sensor( W1ThermSensor.THERM_SENSOR_DS18B20) sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18S20, ds18s20_sensor_id) sensor.type_name.should.be.equal("DS18S20") sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS1822, ds1822_sensor_id) sensor.type_name.should.be.equal("DS1822") sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, ds18b20_sensor_id) sensor.type_name.should.be.equal("DS18B20")
def __init__(self): self.scheduler = BackgroundScheduler() self.db = DatabaseManager( '/home/pi/sfc1/SimpleFurnaceController/Common/database.db') self.sensor = W1ThermSensor() self.heater = Heater() self.checkFrequency() self.checkMinMaxTemperature() self.scheduler.start() self.initSchedulers()
def __init__(self, input_dev, testing=False): super(MAX31850KSensor, self).__init__() self.logger = logging.getLogger("mycodo.inputs.max31850k") self._temperature = None if not testing: self.logger = logging.getLogger( "mycodo.inputs.max31850k_{id}".format(id=input_dev.id)) self.location = input_dev.location self.convert_to_unit = input_dev.convert_to_unit self.sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_MAX31850K, self.location)
def start(self): LOGGER.debug('TempSensor start') self.sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, self.sensorID) self.tempC = self.sensor.get_temperature(W1ThermSensor.DEGREES_C) self.tempMinC24H = self.tempC self.tempMaxC24H = self.tempC self.tempMinC24HUpdated = False self.tempMaxC24HUpdated = False self.currentTime = datetime.datetime.now() self.updateInfo() LOGGER.debug(str(self.tempC) + ' TempSensor Reading')
def read_function(tsl = TSL2561(debug=True), temp_sensor = W1ThermSensor(), dht_sense = Adafruit_DHT.AM2302, gpio_ht = 11): date_time = datetime.datetime.now(pytz.timezone("US/Eastern")).strftime("%Y-%m-%d %H:%M:%S") h2o_temp = temp_sensor.get_temperature() #DS18B20 humidity, temperature = Adafruit_DHT.read_retry(dht_sense, gpio_ht) #AM2302 light = tsl.lux() #TSL2561 #Because this will be saved both to mLab remotely and locally in csv file #It was necessary to order the dictionary to ensure each appended observation is properly ordered #To align with the CSV file. sensor_observation = OrderedDict([('date_time',[date_time]),('water_temp',[round(h2o_temp, 2)]), ('air_temp',[round(temperature,2)]), ('humidity',[round(humidity,2)]), ('light_level',[light])]) return sensor_observation
def __init__(self, input_dev, testing=False): super(InputModule, self).__init__() self.logger = logging.getLogger("mycodo.inputs.max31850k") if not testing: from w1thermsensor import W1ThermSensor self.logger = logging.getLogger("mycodo.max31850k_{id}".format( id=input_dev.unique_id.split('-')[0])) self.location = input_dev.location self.sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_MAX31850K, self.location)
def __init__(self): # Create the I2C bus self.i2c = busio.I2C(board.SCL, board.SDA) # Analog to Digital Converter self.ads = ADS.ADS1015(self.i2c) self.ads.gain = 1 # +/- 4.096 # Thermal Sensor self.therm_sens = W1ThermSensor() self.setup_pins()
def main(): # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() # DS18B20 ds_sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, DS_SENSOR_ID) # DHT11 dht11_sensor_device = Adafruit_DHT.DHT11 # max31865 max_sensor = max31865.max31865(*MAX_PIN) # LCD lcd = lcd_init() data = {'ds18b20': 0, 'pt100': 0, 'dht11': 0, 'humi': 0} # inifinity loop while True: # DS18B20 data['ds18b20'] = ds_sensor.get_temperature() # PT100 max31865 data['pt100'] = max_sensor.readTemp() if DEBUG: print("ds: {} pt100: {}".format(data['ds18b20'], data['pt100'])) # DHT11 temp_dht11, humi_dht11 = Adafruit_DHT.read_retry( dht11_sensor_device, DHT11_PIN) if humi_dht11 is not None and temp_dht11 is not None: data['dht11'] = temp_dht11 data['humi'] = temp_dht11 # LCD line 1 lcd_line1 = "{:.1f}C {:.1f}C {:.0f}C" lcd.set_cursor(row=0) lcd.message( lcd_line1.format(data['ds18b20'], data['pt100'], data['dht11'])) # LCD line 2 lcd_line2 = "humidity:{:.1f}%" lcd.set_cursor(row=1) lcd.message(lcd_line2.format(data['humi'])) time.sleep(5) # 5 sec delay
def setup_ds_resolution(): """ Set DS Sensor resolution """ form_ds = forms_calibration.SetupDS18B20() inputs = Input.query.all() # Check if w1thermsensor library is installed dep_unmet, _ = return_dependencies('CALIBRATE_DS_TYPE') if dep_unmet: list_unmet_deps = [] for each_dep in dep_unmet: list_unmet_deps.append(each_dep[0]) flash( "The device you're trying to calibrate has unmet dependencies: {dep}" .format(dep=', '.join(list_unmet_deps))) return redirect( url_for('routes_admin.admin_dependencies', device='CALIBRATE_DS_TYPE')) # If DS18B20 inputs added, compile a list of detected inputs ds_inputs = [] try: from w1thermsensor import W1ThermSensor for each_input in W1ThermSensor.get_available_sensors(): ds_inputs.append(each_input.id) except OSError: flash( "Unable to detect DS18B20 Inputs in '/sys/bus/w1/devices'. " "Make 1-wire support is enabled with 'sudo raspi-config'.", "error") if form_ds.set_resolution.data and form_ds.device_id.data: try: from w1thermsensor import W1ThermSensor sensor = W1ThermSensor(input_id=form_ds.device_id.data) # sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "00000588806a") sensor.set_precision(form_ds.set_resolution.data, persist=True) flash( "Successfully set sensor {id} resolution to " "{bit}-bit".format(id=form_ds.device_id.data, bit=form_ds.set_resolution.data), "success") except Exception as msg: flash( "Error while setting resolution of sensor with ID {id}: " "{err}".format(id=form_ds.device_id.data, err=msg), "error") return render_template('tools/calibration_options/ds_resolution.html', ds_inputs=ds_inputs, form_ds=form_ds, inputs=inputs)
def thread2(): console_counter = 0 temperature = 0 sm = "idle" while True: try: sensor = W1ThermSensor() temperature = sensor.get_temperature( ) # beim Abziehen des Sensors kommt hier eine 0 (int) zurück except: # ein Abziehen des Sensors wird erst einige Zeit später bemerkt print("exception occoured") temperature = 0 # temperatur manuell auf 0 setzen now = time.localtime(time.time()) date_string = time.strftime("%Y-%m-%d", now) time_string = time.strftime("%H:%M:%S", now) if temperature == 0: # im Fehlerfall temperature = 100 # maximale Tempeartur => da springen sofort die Lüfter an temperature = round(temperature, 0) # nur runden console_counter += 1 print( str(console_counter) + "\t" + sm + "\t" + str(temperature) + "\t" + str(var_case_rear) + "\t" + str(var_cpu_rear) + "\t" + str(var_cpu_front) + "\t" + str(var_case_front)) if sm == "idle": if temperature >= 45: set_case_rear(40) set_cpu_rear(40) set_cpu_front(40) set_case_front(40) sm = "gaming" if sm == "gaming": if temperature <= 32: set_case_rear(0) set_cpu_rear(0) set_cpu_front(0) set_case_front(0) sm = "idle" time.sleep(1)
async def main(): try: if not sys.version >= "3.5.3": raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version) print("IoT Hub Client for Python") # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() IoTHubModuleClient.create_from_edge_environment() # conn_str = "HostName=AndrewPiProject.azure-devices.net;DeviceId=RPi4;SharedAccessKey=FoUWxLuoWLZxKWN/ytg6qMCk0dWHSiWaysIart2CD/s=" # module_client = IoTHubModuleClient.create_from_connection_string(conn_str) # connect the client. await module_client.connect() # Connect Sensor while True: try: sensor = W1ThermSensor() print("Sensor active") break except: pass data = {} data['temperature'] = 0 tempOld = 0 temp = "" # define behavior for receiving an input message on input1 while True: try: data['temperature'] = sensor.get_temperature() * 9 / 5 + 32 json_body = json.dumps(data) temp = json.loads(json_body) print(temp) except: time.sleep(.5) if temp != "" and tempOld != temp['temperature']: print(temp['temperature']) print("forwarding message to output1 at {0}".format( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) tempOld = temp['temperature'] await module_client.send_message_to_output( json_body, "output1") except Exception as e: print("Unexpected error %s " % e) raise
def connect(self): if self.pseudo: self.logger.info('Connected to pseudo sensor') return try: self.sensor = W1ThermSensor() if not self.sensor_is_connected: self.sensor_is_connected = True self.logger.info('Connected to sensor') except: if self.sensor_is_connected: self.sensor_is_connected = False self.logger.warning('Unable to connect to sensor')
def test_sensor_temperature_in_F(): _remove_w1_therm_sensors() # 20 C = 68 F # 26.55 C = 79.79 F # create DS18B20 sensor with 20 C degrees sensor_id = _create_w1_therm_sensor(W1ThermSensor.THERM_SENSOR_DS18B20, temperature=20) sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, sensor_id) sensor.id.should.be.equal(sensor_id) sensor.get_temperature(W1ThermSensor.DEGREES_F).should.be.equal(68.0)
def test_sensor_temperature_in_K(): _remove_w1_therm_sensors() # 20 C = 293.15 K # 26.55 C = 299.7 K # create DS18B20 sensor with 20 C degrees sensor_id = _create_w1_therm_sensor(W1ThermSensor.THERM_SENSOR_DS18B20, temperature=20) sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, sensor_id) sensor.id.should.be.equal(sensor_id) sensor.get_temperature(W1ThermSensor.KELVIN).should.be.equal(293.15) # FIXME: sure should support float comparisation # create DS18B20 sensor with 26.55 C degrees sensor_id = _create_w1_therm_sensor(W1ThermSensor.THERM_SENSOR_DS18B20, temperature=26.55) sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, sensor_id) sensor.id.should.be.equal(sensor_id) sensor.get_temperature(W1ThermSensor.KELVIN).should.be.equal(299.7)
def read(): sensor_type = DS18B20TemperatureSensor.sensor_type sensors = node.node_info['sensors'] found = [ sen['id'] for sen in sensors if sen['sensorType'] == sensor_type ] if not found: return None else: thermSensor = W1ThermSensor() temperature = thermSensor.get_temperature(W1ThermSensor.DEGREES_C) return ReadingBuilder.get(found[0], temperature)
def start(self): GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.switchPin, GPIO.OUT) GPIO.output(self.switchPin, 0) sensor = W1ThermSensor() while (True): self.temp = sensor.get_temperature(W1ThermSensor.DEGREES_F) self.switch() publish.single(self.pubName, self.json_encoding(), hostname=self.host) time.sleep(5)
def __init__(self, input_dev, testing=False): super(InputModule, self).__init__() self.logger = logging.getLogger("mycodo.inputs.ds18s20") self._temperature = None if not testing: from w1thermsensor import W1ThermSensor self.logger = logging.getLogger("mycodo.ds18s20_{id}".format( id=input_dev.unique_id.split('-')[0])) self.location = input_dev.location self.convert_to_unit = input_dev.convert_to_unit self.sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18S20, self.location)
def get_data(): """Get the data from the sensors, also get the date and time. Data recorded: time (str): the time of the record in HH:MM:SS format. date (str): the date of the record in DD-MM-YYYY format. air_temp (float): the ambient temperature in Celsius. air_pressure (float): the barometric pressure in Pascal. water_temp (float): the temperature of the water in Celsius. turb (int): the analog value of the turbidity (from 0 to 1024). Returns: dict: The data in the order of the fieldnames. """ global turbidity_sensor # Date (DD-MM-YYY) and time (HH:MM:SS) d = datetime.now() time = '{:%H:%M:%S}'.format(d) date = '{:%d-%m-%Y}'.format(d) # (DS18B) Water temperature try: w = W1ThermSensor() water_temp = str(w.get_temperature()) except: water_temp = '0' # (BMP180) Air temperature + pressure try: b = BMP085() air_temp = str(b.read_temperature()) air_pressure = str(b.read_pressure()) except: air_temp = '0' air_pressure = '0' # Turbidity of the water turb = turbidity_sensor.read_turbidity() if turb > 1023: turb = 0 return { 'time': time, 'date': date, 'air_temp': air_temp, 'air_pressure': air_pressure, 'water_temp': water_temp, 'turb': turb }
def GetTemps(): for sensor in W1ThermSensor.get_available_sensors(): sensor.set_precision( 10 ) # Read precision, not print precision - 9-12 are only acceptable values try: sand_1_id = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "041701f825ff") Sand_temp = sand_1_id.get_temperature(W1ThermSensor.DEGREES_F) except W1ThermSensorError( NoSensorFoundError ) as e: # not using e for anything at moment but might later Sand_temp = "NA" pass try: soil_2_id = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "031701d060ff") Soil_temp = soil_2_id.get_temperature(W1ThermSensor.DEGREES_F) except W1ThermSensorError as e: Soil_temp = "NA" pass try: air_3_id = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "0316c2d27eff") Air_temp = air_3_id.get_temperature(W1ThermSensor.DEGREES_F) except W1ThermSensorError as e: Air_temp = "NA" pass try: outside_4_id = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "0316c2d810ff") Outside_temp = outside_4_id.get_temperature( W1ThermSensor.DEGREES_F) except W1ThermSensorError as e: Outside_temp = "NA" pass return Sand_temp, Soil_temp, Air_temp, Outside_temp
def initSensor(self, config1): sensor1 = False while sensor1 is False: try: self.sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, config1['sysbus'][3:]) except: print( '%s inicializálása sikertelen 5 másodperc múlva újrapróbálom' % self.id) time.sleep(5) else: sensor1 = True time.sleep(2)
def start(self): LOGGER.debug('start - Temp Sensor controller') try: self.mySensors = W1ThermSensor() self.nbrSensors = len(self.mySensors.get_available_sensors()) LOGGER.info(str(self.nbrSensors) + ' Sensors detected') self.discover() self.setDriver('ST', 1) except: LOGGER.info('ERROR initializing w1thermSensors ') self.setDriver('ST', 0) self.stop() self.updateInfo() self.reportDrivers()
def get_sensor(): """Return the temperature from the DS18B20 sensor""" # Use the W1ThermSensor library to communicate with the DS18B20 sensor = W1ThermSensor() # get the temperature from the device file sensor_temp = sensor.get_temperature() if sensor_temp == None: # Sometimes reads fail on the first attempt # so we need to retry sensor_temp = sensor.get_temperature() return sensor_temp
def __init__(self): self.sensors = { 'temp_tank': W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "011447ba3caa"), #'temp_room': dht11.DHT11(pin=14) } self.led_loop = True self.cCancelled = False self.led_task = None self.event_loop = asyncio.new_event_loop() if not self.event_loop.is_running(): t = threading.Thread(target=lambda: self.event_loop.run_forever()) t.start() self.cal_status = ["Success", "Failed", "In Progress", "None"]