def read_temperature(self): sensor_count = len(W1ThermSensor.get_available_sensors()) if sensor_count == 1: sensor = W1ThermSensor.get_available_sensors()[0] sensor_id, temperature = (sensor.id, sensor.get_temperature()) logging.info('Read temperature: {} from sensor id: {}.'.format(temperature, sensor_id)) self._temperature = temperature else: logging.error('There are "{}" sensors connected to the GPIO4. Expected: 1.'.format(sensor_count)) self._temperature = None
def get_temp(self): # gets the temperature of the sensor for readings found = False sensors = W1ThermSensor.get_available_sensors() for individual_sensor in W1ThermSensor.get_available_sensors(): if self.sensor4readings == individual_sensor.id: temp = individual_sensor.get_temperature() found = True else: print("Found other sensor code : ", individual_sensor.id, " please correct entry in config.cfg") if found: return temp else: return -100
def __init__(self, target_temp): self._target_temp = target_temp self._timestep = 0 self._MIN_VALID_TEMP = -5.0 self._MAX_VALID_TEMP = 30.0 self._READING_TICK = 5 self._DELTA_OVERSHOOT_TEMP = 2.0 self._SSR_PIN = 11 self._compressor_state = True self._sensors = {} self._sensors['000001efbab6'] = 'top' self._sensors['000001efd9ac'] = 'bottom' self._sensors['000001eff556'] = 'beer' self._sensor_readings = deque( maxlen=int(60/self._READING_TICK)*len(W1.get_available_sensors()) ) logging.config.dictConfig(app.config['LOG_CONFIG']) self.logger = logging.getLogger('agent') if not app.config['DEBUG']: GPIO.setmode(GPIO.BOARD) GPIO.setup(self._SSR_PIN, GPIO.OUT) uwsgi.register_signal(9000, 'worker', self.run) uwsgi.add_timer(9000, 5) atexit.register(lambda: self.cleanup()) if app.config['LOG_DEBUG']: self.logger.setLevel(logging.DEBUG) else: self.logger.setLevel(logging.WARN) self.logger.info("Agent started")
def run(self): while 1: try: if SIMULATION_MODE == 1: for sensor in self.sensors: timestamp = int(time()) lock.acquire() with open(self.csv_path, "a") as output_file: writer = csv.writer(output_file) row = sensor.id, sensor.name, sensor.get_temperature(), timestamp writer.writerow(row) lock.release() else: for sensor in W1ThermSensor.get_available_sensors(): # TODO: set a sensor name timestamp = int(time()) lock.acquire() with open(self.csv_path, "a") as output_file: writer = csv.writer(output_file) row = sensor.id, 'T', sensor.get_temperature(), timestamp writer.writerow(row) lock.release() sleep(self.sleep_time) finally: pass
def oneW(self,oneWlist): ticks = {} while True: time.sleep(0.1) try: for sensor in W1ThermSensor.get_available_sensors(): sid = sensor.id if sid in oneWlist: sk = oneWlist[sid]['sk'] if sk: offset = oneWlist[sid]['offset'] value = str(offset+sensor.get_temperature(Unit.KELVIN)) if not sid in ticks: ticks[sid] = time.time() rate = oneWlist[sid]['rate'] now = time.time() if now - ticks[sid] > rate: SignalK = '{"updates":[{"$source":"OpenPlotter.GPIO.1W.'+sid+'","values":[{"path":"'+sk+'","value":'+value+'}]}]}\n' try: if self.ws: self.ws.send(SignalK) ticks[sid] = time.time() else: return except: if self.ws: self.ws.close() self.ws = False return except Exception as e: if self.debug: print('Reading GPIO 1W error: '+str(e)) return
def read_temperatures(units=W1ThermSensor.DEGREES_F): '''Read temperatures from attached thermometers. Parameters units: int default=W1ThermSensor.DEGREES_F Temerature units (e.g., Fahrenheit, Celcius, Kelvin) as Returns array of dicts, each one containing sensor ID and temperature reading `[ { 'sensor_id': '80000002d2e0', 'sensor_type': 'DS18B20', 'temperature': 63.16160000000001 }, { 'sensor_id': '80000002d4c1', 'sensor_type': 'DS18B20', 'temperature': 20.8740000000001 } ]` ''' return [ dict(sensor_id=sensor.id, sensor_type=sensor.type_name, temperature=sensor.get_temperature(units)) for sensor in W1ThermSensor.get_available_sensors() ]
def read_humidity_and_temp(sensor_spec): """ Read an individual DHT11, DHT22, or DS18B20 sensor. If DS18B20 is passed for the sensor key, pin is ignored as it is assumed to be on the active single wire interface. Parameters ---------- sensor_spec Returns ------- humidity: float or NoneType temperature: float, list(float) or NoneType Temp or list of temps in the case of DS18B20 units in degrees celsius. """ sensor = SENSOR_MAP[sensor_spec['sensor']] pin = sensor_spec['pin'] if sensor in {Adafruit_DHT.DHT11, Adafruit_DHT.DHT22}: humidity, temperature = Adafruit_DHT.read_retry(sensor, pin, retries=5) return humidity, temperature elif sensor == 'DS18B20': temperatures = W1ThermSensor().get_temperatures(units=[ W1ThermSensor.DEGREES_C for _ in W1ThermSensor.get_available_sensors() ]) return None, temperatures else: raise ValueError('Sensor type %s not supported' % sensor)
def main(post=True): print 'running main...' responses = {} try: print 'Getting GPIO ready' GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setup(LIGHT, GPIO.OUT) _pin = RELAY # Setup sensors for sensor in W1ThermSensor.get_available_sensors(): print 'Detected sensor ', sensor.id _sid = '28-' + sensor.id if _sid in ID_TO_PIN: _pin = ID_TO_PIN[_sid] responses[_sid] = {'status': 'temper'} GPIO.setup(_pin, GPIO.OUT) print 'Success with one sensor' print 'Success with all sensors' except Exception, e: print 'EXCEPTION SETTING UP MAIN GPIO' print e GPIO.cleanup()
def collect_temp_readings(sc): clear_screen() if config.mqtt_enabled: mqtt_conn = mqtt.connect_mqtt(config.mqtt_ipaddress, config.mqtt_port, config.mqtt_username, config.mqtt_password) readings = [] for sensor in W1ThermSensor.get_available_sensors(): sensor_id = int(sensor.id, 16) temperature = sensor.get_temperature() readings.append({ 'sensorId': sensor_id, 'ambientTemperature': temperature }) if config.mqtt_enabled: mqtt.publish_temp(mqtt_conn, sensor_id, temperature) if config.mqtt_enabled: mqtt.disconnect_mqtt(mqtt_conn) if config.http_enabled and len(readings) > 0: send_to_server(list_to_json(readings)) if len(readings) == 0: print(time.strftime("%H:%M") + " No sensors found.") schedule.enter(config.poll_period_seconds, 1, collect_temp_readings, (sc, ))
def evaluate(self): sensor_readings = [] for sensor in W1.get_available_sensors(): sensor_readings.append(sensor.get_temperature()) average_temp = sum(sensor_readings)/len(sensor_readings) self.logger.debug("Average temp: " + str(average_temp) + ". Target temp: " + str(self.get_target_temp())) if average_temp > self.get_target_temp() + self._DELTA_OVERSHOOT_TEMP: self.logger.debug("Turn on compressor if needed") self._compressor_state = True if app.config['DEBUG']: return if not GPIO.input(self._SSR_PIN): self.logger.info("Turning on compressor") GPIO.output(self._SSR_PIN, True) if not GPIO.input(self._SSR_PIN): self.logger.error("Unable to turn on compressor!") self._compressor_state = False if average_temp <= self.get_target_temp(): self.logger.debug("Turn off compressor if needed") self._compressor_state = False if app.config['DEBUG']: return if GPIO.input(self._SSR_PIN): GPIO.output(self._SSR_PIN, False) self.logger.info("Turning off compressor") if GPIO.input(self._SSR_PIN): self.logger.error("Unable to turn off compressor!") self._compressor_state = True
def main(argv): print 'Number of arguments:', len(sys.argv), 'arguments.' print 'Argument List:', str(sys.argv) try: logger.info('Reading command line parameters') opts, args = getopt.getopt(argv, "h", []) except getopt.GetoptError: print 'python ' + str(sys.argv[0]) logger.error('python ' + str(sys.argv[0])) sys.exit(2) for opt, arg in opts: if opt == '-h': print str(sys.argv[0]) sys.exit() try: exciss_home = str(os.environ['EXCISS_HOME']) logger.info('Environment variable EXCISS_HOME=' + exciss_home) print('Environment variable EXCISS_HOME=' + exciss_home) except KeyError: logger.error('Environment variable EXCISS_HOME not set.') print('Environment variable EXCISS_HOME not set.') exit() # collect temperatures from all the connected sensors for sensor in W1ThermSensor.get_available_sensors(): print('Sensor %s has temperature %.2f' % (sensor.id, sensor.get_temperature())) # log temperatures to csv file writeCSVFile(exciss_home + '/' + CSV_FILENAME, sensor.id, sensor.get_temperature())
def graph_last_day(sensors): defs = [] lines = [] current_temps = ['COMMENT: \l'] for i, sensor in enumerate(sorted(W1ThermSensor.get_available_sensors(), key=lambda sensor: sensor.id)): color = COLORS[i % len(COLORS)]; defs.append('DEF:' + sensor.id + '=' + DATABASE_PATH + sensor.id + '.rrd:temp:AVERAGE') lines.append('LINE1:' + sensor.id + color + ':' + sensor_name(sensor.id)) current_temps.append('GPRINT:' + sensor.id + ':LAST:' + sensor_name(sensor.id) + '\: %4.2lf\l') params = [ LAST_DAY_GRAPH_FILE, '-a', 'PNG', '-w', '500', '-h', '250', '--start', '-86400', '--end', 'now', '--lower-limit', '18', '--upper-limit', '28', '--rigid', '--vertical-label', 'Temp, deg C'] + defs + lines + current_temps rrdtool.graph(*params)
def get_temp(): global tempeture_1 while True: yield from asyncio.sleep(1.5) #tempeture_1=SpiRead() for sensor in W1ThermSensor.get_available_sensors(): tempeture_1=sensor.get_temperature()
def get_temp(): global tempeture_1 while True: yield from asyncio.sleep(1.5) #tempeture_1=SpiRead() for sensor in W1ThermSensor.get_available_sensors(): tempeture_1 = sensor.get_temperature()
def read_temperatures(units=W1ThermSensor.DEGREES_F): '''Read temperatures from attached thermometers. Parameters units: int default=W1ThermSensor.DEGREES_F Temerature units (e.g., Fahrenheit, Celcius, Kelvin) as Returns array of dicts, each one containing sensor ID and temperature reading `[ { 'sensor_id': '80000002d2e0', 'sensor_type': 'DS18B20', 'temperature': 63.16160000000001 }, { 'sensor_id': '80000002d4c1', 'sensor_type': 'DS18B20', 'temperature': 20.8740000000001 } ]` ''' return [dict( sensor_id=sensor.id, sensor_type=sensor.type_name, temperature=sensor.get_temperature(units) ) for sensor in W1ThermSensor.get_available_sensors()]
def __init__(self,edit): wx.Dialog.__init__(self, None, title=_('Add DS18B20 sensor'), size=(330,290)) panel = wx.Panel(self) wx.StaticText(panel, label=_('name'), pos=(10, 10)) self.name = wx.TextCtrl(panel, size=(310, 30), pos=(10, 35)) wx.StaticText(panel, label=_('short name'), pos=(10, 70)) self.short = wx.TextCtrl(panel, size=(100, 30), pos=(10, 95)) list_units=['Celsius','Fahrenheit','Kelvin'] wx.StaticText(panel, label=_('unit'), pos=(120, 70)) self.unit_select= wx.ComboBox(panel, choices=list_units, style=wx.CB_READONLY, size=(200, 32), pos=(120, 95)) list_id=[] for sensor in W1ThermSensor.get_available_sensors(): list_id.append(sensor.id) wx.StaticText(panel, label=_('sensor ID'), pos=(10, 130)) self.id_select= wx.ComboBox(panel, choices=list_id, style=wx.CB_READONLY, size=(310, 32), pos=(10, 155)) if edit != 0: self.name.SetValue(edit[1]) self.short.SetValue(edit[2]) if edit[3]=='C': unit_selection='Celsius' if edit[3]=='F': unit_selection='Fahrenheit' if edit[3]=='K': unit_selection='Kelvin' self.unit_select.SetValue(unit_selection) self.id_select.SetValue(edit[4]) cancelBtn = wx.Button(panel, wx.ID_CANCEL, pos=(70, 205)) okBtn = wx.Button(panel, wx.ID_OK, pos=(180, 205))
def get_ds18b20_data(**kwargs): verbose = kwargs['verbose'] read_interval = kwargs['DS18B20_read_interval'] try: from w1thermsensor import W1ThermSensor from time import sleep while True: data = W1ThermSensor.get_available_sensors([ W1ThermSensor.THERM_SENSOR_DS18B20, W1ThermSensor.THERM_SENSOR_DS18S20 ]) for sensor in data: redis_db.sadd('DS18B20_sensors', sensor.id) redis_db.set(sensor.id, sensor.get_temperature()) sleep(1) redis_db.expire(sensor.id, read_interval * 2) if bool(verbose) is True: print( "Sensor %s temperature %.2f" % (sensor.id, sensor.get_temperature()), "\xb0C") print('') redis_db.expire('DS18B20_sensors', read_interval * 2) sleep(read_interval) except Exception as err: print(f'Problem with sensor DS18B20: {err}')
def job(): measurement_list = [] for sensor in W1ThermSensor.get_available_sensors(): measurement_value = sensor.get_temperature(W1ThermSensor.DEGREES_C) measurement_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') measurement = { "measurement": "temperature_sensor", "tags": { "id": sensor.id, # "prefix": sensor.slave_prefix, # "path": sensor.sensorpath, "device_name": sensor.type_name, "device_type": sensor.type, "location": SENSOR_LOCATIONS.get(sensor.id, SENSOR_LOCATIONS_NA), "unit": "C", }, "time": measurement_time, "fields": { "value": measurement_value, }, } print("Sensor %s has temperature %.2f at %s" % (sensor.id, measurement_value, measurement_time)) measurement_list.append(measurement) db_client = InfluxDBClient(INFLUXDB_HOST, INFLUXDB_PORT, INFLUXDB_NAME, INFLUXDB_PASSWD, INFLUXDB_DB) db_client.write_points(measurement_list)
def read_temperatures(self): sensors = W1ThermSensor.get_available_sensors() for sensor in sensors: print("Sensor " + sensor.id + " found: " + str(sensor.get_temperature())) self.s.enter(5, 1, self.read_temperatures) self.s.run()
def __init__(self, parent=None): super(App, self).__init__(parent) # define o tamanho da tela self.setFixedSize(1200, 800) ## cria janela principal self.mainbox = QtGui.QWidget() self.setCentralWidget(self.mainbox) ## cria um grid para os comandos self.grid = QGridLayout() self.grid.setSpacing(10) self.mainbox.setLayout(self.grid) # inicializa o painel de controle self._initialize_control_panel() # inicializa os paineis de gráficos self._initialize_charts() # inicializa os parâmetros para cálculo self._initialize_parameters() # variável para indicar se o controle está em execução self._started = False # inicializa os vetores dos graficos self.Y_var_controlada = [] self.Y_var_manipulada = [] self.Y_tanque_frio = [] self.Y_var_setpoint = [] self.X = [] # inicializa as variáveis self.sp = None self.kc = None self.ki = None self.kd = None self.pid = None # inicializa o sensor self.sensor_var_controlada = W1ThermSensor.get_available_sensors()[0] self.sensor_tanque_frio = W1ThermSensor.get_available_sensors()[1] # inicializa o controlador do motor self._initialize_motor()
def get_temperature(self): try: return [ sensor.get_temperature() for sensor in W1ThermSensor.get_available_sensors() ] except FileNotFoundError: return [1.11, 2.22, 3.33, 4.44]
def test_get_available_sensors(): _remove_w1_therm_sensors() _create_w1_therm_sensor(W1ThermSensor.THERM_SENSOR_DS18B20) sensors = W1ThermSensor.get_available_sensors() sensors.should.have.length_of(1) sensors[0].type.should.be.equal(W1ThermSensor.THERM_SENSOR_DS18B20) _create_w1_therm_sensor(W1ThermSensor.THERM_SENSOR_DS1822) _create_w1_therm_sensor(W1ThermSensor.THERM_SENSOR_DS18S20) sensors = W1ThermSensor.get_available_sensors() sensors.should.have.length_of(3) W1ThermSensor.THERM_SENSOR_DS1822.should.be.within(s.type for s in sensors) W1ThermSensor.THERM_SENSOR_DS18S20.should.be.within(s.type for s in sensors) W1ThermSensor.THERM_SENSOR_DS18B20.should.be.within(s.type for s in sensors)
def process_temperature(): """ a function to process the temperature """ """for mutliple Sensors""" for SENSOR in W1ThermSensor.get_available_sensors(): logging.info("Sensor %s has temperature %.2f" % (SENSOR.id, SENSOR.get_temperature())) G.labels("%s" % SENSOR.id).set("%.2f" % SENSOR.get_temperature())
def test_get_available_ds18s20_sensors(): _remove_w1_therm_sensors() # create 3 DS18S20 sensors _create_w1_therm_sensor(W1ThermSensor.THERM_SENSOR_DS18S20) _create_w1_therm_sensor(W1ThermSensor.THERM_SENSOR_DS18S20) _create_w1_therm_sensor(W1ThermSensor.THERM_SENSOR_DS18S20) sensors = W1ThermSensor.get_available_sensors([W1ThermSensor.THERM_SENSOR_DS18S20]) sensors.should.have.length_of(3) # create 2 DS18B20 sensors _create_w1_therm_sensor(W1ThermSensor.THERM_SENSOR_DS18B20) _create_w1_therm_sensor(W1ThermSensor.THERM_SENSOR_DS18B20) sensors = W1ThermSensor.get_available_sensors([W1ThermSensor.THERM_SENSOR_DS18S20]) sensors.should.have.length_of(3)
def setAllSensors(precision=9): for sensor in W1ThermSensor.get_available_sensors(): sty = sensor.type_name sid = sensor.id stp = sensor.get_temperature() print("Setting precision of sensor %s (%s) to %d" % (sid, sty, precision)) sensor.set_precision(precision, persist=True)
def handle(self, *args, **options): for sensor in W1ThermSensor.get_available_sensors(): if Thermometer.objects.filter(sensor_id=sensor.id).__len__() == 0: thermometer = Thermometer(sensor_id=sensor.id) thermometer.save() if thermometer.id is not None: self.stdout.write("Sensor o ID: %s dodany do bazy!" % (sensor.id)) else: self.stdout.write("Sensor o ID: %s juz istnieje w bazie!" % (sensor.id))
def temperatura(x, db, idmesura): modelSensor = "DS18B20" for sensor in W1ThermSensor.get_available_sensors(): print("Sensor %s has temperature %.2f" % (sensor.id, sensor.get_temperature())) query = "insert into temperatura (modelSensor, mesura, temperatura) values ('%s',%s,%s)" % ( modelSensor, idmesura, sensor.get_temperature()) x.execute(query) db.commit()
def flash_error(): # Shutoff all for sensor in W1ThermSensor.get_available_sensors(): pin = RELAY # Accomodate multiples if sensor.id in ID_TO_PIN: _sid = '28-' + sensor.id pin = ID_TO_PIN[_sid] GPIO.output(pin, False)
def setup_temp_sensors(self): # Get ID of DS18B20 sensor(s) THERM_ID = W1ThermSensor.get_available_sensors( [W1ThermSensor.THERM_SENSOR_DS18B20])[0].id # Create a W1ThermSensor object sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, THERM_ID) # Get temperatures in Celsius: sensor.get_temperature() # Get temperatures in Farenheit: sensor.get_temperature(W1ThermSensor.DEGREES_F) return sensor
def hello(): w1sensor = dict() for sensor in W1ThermSensor.get_available_sensors(): w1sensor[sensor.id] = sensor.get_temperature() if len(w1sensor) == 0: return "[NA]" else: return build_temp_str(w1sensor)
def w1TempList(ctx): sensor_names = { id: name for name, id in ctx.default_map["sensors"]["temperature"].items() } for sensor in W1ThermSensor.get_available_sensors(): click.echo("Sensor type: {} id: {} name: {}".format( sensor.type, sensor.id, sensor_names[sensor.id] if sensor.id in sensor_names else sensor.id))
def logged_in(*args, **kwargs): print 'Logged in: %s' % datetime.datetime.now().isoformat() print args print kwargs print 'Creating machines...' for sensor in W1ThermSensor.get_available_sensors(): client.call('getOrCreateMachine', sensor.id, callback=sensor_create_callback) for fakesensor in ['refiner1id', 'refiner12id']: client.call('getOrCreateMachine', fakesensor, callback=sensor_create_callback)
def temp_get_min(): temp_min = 1000000 for sensor in W1ThermSensor.get_available_sensors(): temp = sensor.get_temperature() almon_debug("Current temp, %s: %d" % (sensor_tbl[sensor.id], temp)) if temp < temp_min: temp_min = temp lowest_sensor = sensor_tbl[sensor.id] return temp_min, lowest_sensor
def __init__(self): self.tankSensors = [] self.outputSensors = [] for sensor in W1ThermSensor.get_available_sensors(): if sensor.id in tankSensorIds: self.tankSensors.append(sensor) elif sensor.id in outputSensorIds: self.outputSensors.append(sensor)
def getData(): out = {} for sensor in W1ThermSensor.get_available_sensors(): # print("Sensor {} has temperature {:.2f}".format(reverseSid[sensor.id], sensor.get_temperature())) tempC = sensor.get_temperature() out[reverseSid[sensor.id]] = "{0:.2f}".format(tempC) # out[reverseSid[sensor.id]] = f"{tempC:.2f}" return out
def run(self): """ Method that runs forever """ global currentTemp while True: # Do something print('Doing something imporant in the background') for sensor in W1ThermSensor.get_available_sensors(): self.w1sensor[sensor.id] = sensor.get_temperature() currentTemp = self.w1sensor time.sleep(self.interval)
def get_temperature(i): w1sensor = dict() for sensor in W1ThermSensor.get_available_sensors(): w1sensor[sensor.id] = sensor.get_temperature() print("Sensor %s has temperature %.2f" % (sensor.id, sensor.get_temperature())) # current_temperature(w1sensor) time.sleep(i)
def monitorTemps(): global sensor_current clearSensorAVG() lastminute=int(time.strftime("%M")) r = 0 count=0.0 while True: r += 1 count += 1.0 # Read the DS18B20s for sensor in W1ThermSensor.get_available_sensors(): temp=sensor.get_temperature(W1ThermSensor.DEGREES_F) # If the sensor is reading super high then something is wrong..try to read again while ( temp > 120 ): print("Sensor %s has high temp %.2f" % (sensor_name[sensor.id], temp)) time.sleep(0.2) temp=sensor.get_temperature(W1ThermSensor.DEGREES_F) if (DEBUG == 1): print("Sensor %s has temperature %.2f" % (sensor_name[sensor.id], temp)) sensor_avg[sensor_name[sensor.id]]+= temp time.sleep(0.2) if (DEBUG == 1): print("-") minute=int(time.strftime("%M")) if (minute != lastminute): # Minute just changed. Write a line to the CSV file f.write("{},{}".format(time.strftime("%Y/%m/%d %H:%M:%S"),r)) for sensorID,sensorName in sensor_name.iteritems(): f.write(",{:3.2f}".format(sensor_avg[sensorName]/count)) sensor_current[sensorName]=sensor_avg[sensorName]/count print "Setting sensor_current["+sensorName+"]="+str(sensor_current[sensorName]) f.write("\n") f.flush() clearSensorAVG() count=0 lastminute=minute time.sleep(3) # Overall INTERVAL second polling.
def get_sensor_data(): try: for sensor in W1ThermSensor.get_available_sensors(): #now = '{:%Y-%m-%d %H:%M}'.format(datetime.datetime.now()) room = clean_get(sensor.id, 'room') sensor_name = clean_get(sensor.id, 'name') result = room + " " + sensor_name + " " + str(sensor.type_name) + " " + sensor.id + " " + str(sensor.get_temperature(W1ThermSensor.DEGREES_F)) logging.info(result) except Exception, e: logging.error('Failed to get sensor information: '+ str(e))
def main(): log_path = path.join(PIDAS_DIR, 'logs') file_path = path.join(PIDAS_DIR, DATA_FILE) if not path.exists(log_path): makedirs(log_path) logging_level = logging.DEBUG logging.Formatter.converter = gmtime log_format = '%(asctime)-15s %(levelname)s:%(message)s' logging.basicConfig(format=log_format, datefmt='%Y/%m/%d %H:%M:%S UTC', level=logging_level, handlers=[logging.FileHandler(path.join(log_path, 'save_sensor_data.log')), logging.StreamHandler()]) logging.info('_____ Started _____') logging.info('saving in' + file_path) if not path.exists(file_path): with open(file_path, "w") as output_file: writer = csv.writer(output_file) writer.writerow(CSV_HEADER) client = InfluxDBClient(DATABASE['HOST'], DATABASE['PORT'], DATABASE['USER'], DATABASE['PASSWORD'], DATABASE['NAME']) sensors = [] if SIMULATION_MODE == 1: try: last_timestamp = client.query('select "timestamp" from temperatures order by desc limit 1;') if not last_timestamp: logging.info("Serie is empty, creating new sensors…") sensors = generate_temp_sensor(NB_SENSOR) logging.info("Sensors generated") else: try: logging.info("Getting sensors from database…") result_set = client.query('select distinct(sensorID) as sensorID from temperatures ') results = list(result_set.get_points(measurement='temperatures')) for result in results: s = FakeTempSensor() s.id = result['sensorID'] sensors.append(s) except requests.exceptions.ConnectionError: logging.error("Database connection lost !") except requests.exceptions.ConnectionError: logging.error("Database connection lost !") except exceptions.InfluxDBClientError as e: logging.error("{}".format(e.content)) else: sensors = W1ThermSensor.get_available_sensors() thread_local_save = ThreadLocalSave(file_path=file_path, sensors=sensors) thread_remote_save = ThreadRemoteSave(client, file_path=file_path) thread_local_save.start() thread_remote_save.start() # wait until threads terminates thread_local_save.join() thread_remote_save.join()
def save_reading(self): reading = Reading( target_temp=self.get_target_temp(), compressor_state=self.get_compressor_state() ) for w1sensor in W1.get_available_sensors(): sensor = Sensor( placement=self._sensors.get(w1sensor.id), value=w1sensor.get_temperature() ) db.session.add(sensor) reading.sensors.append(sensor) db.session.add(reading) db.session.commit()
def temp(downlink, tempLED): try: data_raw = [] data = [] for sensor in W1ThermSensor.get_available_sensors(): data_raw.append(sensor.get_temperature()) for i in range(len(data_raw)): data.append(data_raw[i]) #data.append(temp_cal[i] + data_raw[i]) if (not tempLED.is_set()) and tempCheck(data): # If the flag isn't set, and things are on fire. tempLED.set() downlink.put(["SE", "T%i" % (len(data)), cs_str(data)]) except: print("Temperature reading failed")
def t_temp(): while True: for sensor in W1ThermSensor.get_available_sensors(): lock.acquire() temps[sensor.id] = sensor.get_temperature(W1ThermSensor.DEGREES_F) temptimes[sensor.id] = time.time() print 'hwr>'+sensor.id+':'+str(temps[sensor.id]) lock.release() lock.acquire() todelete = [] expire = time.time() - 60 * 10 for t in temptimes: if temptimes[t] < expire: todelete.append(t) for t in todelete: temptimes.pop(t,None) temps.pop(t,None) print "del>"+t lock.release() time.sleep(120)
def get_w1_devices(self): log.debug('Scanning for 1W devices.') for sensor in W1ThermSensor.get_available_sensors(): self._w1_devices[sensor.id] = {'id': sensor.id, 'type': '1-Wire device'} return self._w1_devices
#!/usr/bin/python import sys import time from lib import BMP085 from lib import TSL2561 from w1thermsensor import W1ThermSensor import Adafruit_DHT bmp = BMP085.BMP085(0x77, 3) lux = TSL2561.TSL2561() dht = Adafruit_DHT.DHT22 temps = {} for sensor in W1ThermSensor.get_available_sensors(): temps[sensor.id] = sensor.get_temperature() bartemp = bmp.readTemperature() pressure = bmp.readPressure() / 100.0 light = lux.getAnyLux() humidity, humtemp = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 23) for id in temps.keys(): print "Temperature on %s: %.3f C" % (id, temps[id]) print "Barometer Temperature: %.1f C" % bartemp print "Hygrometer Temperature: %.1f C" % humtemp print "Pressure: %.2f hPa" % pressure print "Humidity: %.2f %%" % humidity print "Lightness: %.2f Lux" % light
logfile= r"logfile-" + period + ".txt" if ( os.path.exists(logfile) ): new_file[period] = False else: new_file[period] = True output[period] = open(logfile,"a") #logfile = file_timestamp + "-records_log.txt" logfile = "records_log.txt" if ( os.path.exists(logfile) ): new_file["records"] = False else: new_file["records"] = True output["records"] = open(logfile,"a") all_sensors = W1ThermSensor.get_available_sensors() record_count = {} last_reading = {} for sensor in all_sensors: match_sensor_to_loc(sensor) init_sensor_stats(sensor) for period in stats_periods.keys(): record_count[period] = 0 last_reading[period] = 0 if (new_file[period]): output[period].write("%20s |" % " ") for sensor in all_sensors: output[period].write("%23s |" % sensor.location)
detected_imu=imu.IMUName() if imu.getCompassCalibrationValid() and imu.getCompassCalibrationEllipsoidValid() and imu.getAccelCalibrationValid(): calibrated=1 SETTINGS_FILE2 = "RTIMULib2" s2 = RTIMU.Settings(SETTINGS_FILE2) pressure = RTIMU.RTPressure(s2) if pressure.pressureName()!='none': detected_pressure=pressure.pressureName() SETTINGS_FILE3 = "RTIMULib3" s3 = RTIMU.Settings(SETTINGS_FILE3) humidity = RTIMU.RTHumidity(s3) if humidity.humidityName()!='none': detected_humidity=humidity.humidityName() try: DS18B20=W1ThermSensor.get_available_sensors() except: pass if detected_imu: print detected_imu else: print 'none' if calibrated: print calibrated else: print '0' if detected_pressure: print detected_pressure else: print 'none' if detected_humidity: print detected_humidity else: print 'none'
def test_get_available_sensors_no_sensors(): _remove_w1_therm_sensors() sensors = W1ThermSensor.get_available_sensors() sensors.should.be.empty
def handle(self, *args, **options): for sensor in W1ThermSensor.get_available_sensors(): self.stdout.write("Sensor: %s, ID: %s" % (sensor.type_name, sensor.id)) if Thermometer.objects.filter(sensor_id=sensor.id).__len__() == 0: self.stdout.write("Podany senor nie wystepuje w bazie, prosze wykonac polecenie: addsensors")
def ReadAllSensors(): for sensor in W1ThermSensor.get_available_sensors([W1ThermSensor.THERM_SENSOR_DS18B20]): print("%s: %.2f" % (sensor.id, sensor.get_temperature()))
def list_w1_sensors(): from w1thermsensor import W1ThermSensor for sensor in W1ThermSensor.get_available_sensors(): print("Sensor %s has temperature %.2f" % (sensor.id, sensor.get_temperature()))
try: delay=config['sensors'][sensor]['delay'] except KeyError: delay=1 try: invert=config['sensors'][sensor]['invert'] except KeyError: invert=False try: offset=config['sensors'][sensor]['offset'] except KeyError: offset=0 if 'ds18b20' == type: logger.debug("Reading %s" % type) for count, w1 in enumerate(W1ThermSensor.get_available_sensors()): # Make sure a new reading will be fetched if w1.id not in last_change: last_change[w1.id]=time.time()-delay # Read from sensor #try: input = float("%.1f" % w1.get_temperature()) + offset #except W1ThermSensorError: # logger.error("Unable to read %s sensor on gpio %." % (type, gpio)) # continue if (input is None): logger.error("Sensor %s gave invalid data %s." % (w1.id, input)) state[w1.id] = input continue
def readtemp( strID ): for sensor in W1ThermSensor.get_available_sensors(): if sensor.id == strID: return sensor.get_temperature()