示例#1
0
 def get_temp(self):
     try:
         sekarang = int(time.time())
         if(self.cache == -1000 or (sekarang - self.last_read) > self.update_interval):
             dev = TS(TS.THERM_SENSOR_DS18B20, self.uid)
             self.cache = dev.get_temperature()
             self.last_read = sekarang
             return self.cache
         else:
             return self.cache
     except Exception as err:
         logging.error('Device {} error or not found. Error: {}'.format(self.uid, err))
示例#2
0
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()
示例#3
0
    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
示例#4
0
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()]
示例#5
0
文件: lmf7.py 项目: kkdds/lmf_bk
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()
示例#6
0
    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
示例#7
0
	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))
示例#8
0
    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")
示例#9
0
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)
示例#10
0
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)
示例#11
0
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)
示例#12
0
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)
示例#13
0
 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))
示例#14
0
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.
示例#15
0
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))
示例#16
0
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()
示例#17
0
 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()
示例#18
0
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")
示例#19
0
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)
示例#20
0
# tempbodge: temp fetcher
# [email protected]

import os
from datetime import datetime
import requests
from w1thermsensor import W1ThermSensor
from dotenv import load_dotenv


# Load env vars from .env
load_dotenv()


# Define constants
TOKEN = os.getenv("SECRET")
ENTRYPOINT = os.getenv("HOST") + "/post"
SENSOR_IN = W1ThermSensor.get_available_sensors()[0]
SENSOR_OUT = W1ThermSensor.get_available_sensors()[1]


# Get current time and temperature reading from the GPIO
# and post to the server
curtime = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
temp_in = SENSOR_IN.get_temperature()
temp_out = SENSOR_OUT.get_temperature()

payload = {"timestamp": curtime, "temp": temp_in, "outdoors": temp_out, "secret": TOKEN}
req = requests.get(url = ENTRYPOINT, params = payload)
示例#21
0
文件: ftserver.py 项目: lmtr/fishtank
def readtemp( strID ):
    for sensor in W1ThermSensor.get_available_sensors():
        if sensor.id == strID:
            return sensor.get_temperature()
示例#22
0
 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")
示例#23
0
GPIO.setwarnings(False)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)

fan_L = GPIO.PWM(12, 500)
fan_R = GPIO.PWM(18, 500)
fan_L.start(fan_L_sp)
fan_R.start(fan_R_sp)

val = (1 << OE_1) | (1 << OE_2) | (1 << OE_3) | (0 << CLR) | (1 << CLK_EN)
i2c.write_byte(PCF_CTRL, val)
val = (1 << OE_1) | (1 << OE_2) | (1 << OE_3) | (1 << CLR) | (1 << CLK_EN)
i2c.write_byte(PCF_CTRL, val)

while True:
    sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, T_SENSOR_1)
    temp_1 = sensor.get_temperature()
    sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, T_SENSOR_2)
    temp_2 = sensor.get_temperature()

    left_fan = GetRPM(0)
    right_fan = GetRPM(1)

    u_psu = 0
    u_bat = 0
    i_bat = 0

    for i in range(1000):
        u_psu += adc.read(0)
        u_bat += adc.read(1)
        i_bat += adc.read(2) - adc.read(3)
示例#24
0
import datetime
import Adafruit_DHT
import gspread
from oauth2client.service_account import ServiceAccountCredentials
DHT_TYPE = Adafruit_DHT.DHT11

DHT_PIN = 24

GDOCS_OAUTH_JSON = 'sahil.json'

# Google Docs spreadsheet name.
GDOCS_SPREADSHEET_NAME = 'sahiliot'

FREQUENCY_SECONDS = 3

se = W1ThermSensor()


def login_open_sheet(oauth_key_file, spreadsheet):
    """Connect to Google Docs spreadsheet and return the first worksheet."""
    try:
        scope = [
            'https://spreadsheets.google.com/feeds',
            'https://www.googleapis.com/auth/drive'
        ]
        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            oauth_key_file, scope)
        gc = gspread.authorize(credentials)
        worksheet = gc.open(spreadsheet).sheet1
        return worksheet
    except Exception as ex:
示例#25
0
from w1thermsensor import W1ThermSensor
import paho.mqtt.client as mqtt
import time

client = mqtt.Client()
client.connect("ankh-morpork.fritz.box")

sensor1 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "0317018a3bff")
sensor2 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "04170197f1ff")
sensor3 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "041701abebff")

client.loop_start()

while True:
#    for count, sensor in enumerate(W1ThermSensor.get_available_sensors()):
#        temperature = sensor.get_temperature()
#        print("Sensor %s has temperature %.2f" % (sensor.id, sensor.get_temperature()))
#        client.publish("/playground/temperature" + str(count), temperature)
    flow_temp = sensor1.get_temperature()
    boiler_temp = sensor2.get_temperature()
    return_temp = sensor3.get_temperature()
    client.publish("/places/our place/cellar/heatingroom/boiler/flow temperature", flow_temp)
    client.publish("/places/our place/cellar/heatingroom/boiler/temperature", boiler_temp)
    client.publish("/places/our place/cellar/heatingroom/boiler/return temperature", return_temp)
    time.sleep(30)
示例#26
0
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()))
示例#27
0
文件: rest.py 项目: gurkslask/modsol
 def get(self, sensor_id):
     # Get value of sensor by supplying sensor id
     return W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                          sensor_id).get_temperature()
示例#28
0
                except:
                    pass

                os.system(cmd)

            if variable_wifipass == "1" and variable_wifiid == "0":
                Reset_WiFi()

            if variable_wifipass == "1" and variable_wifiid == "1":
                Update_source()

            # ---------------------------???????????????How to replace sensor???????

            try:
                quantity_plugged = 0
                for sens in W1ThermSensor.get_available_sensors():
                    quantity_plugged += 1
                quantity_in_file = 0
                for i in range(quantity_temp_sens):
                    if sensors_in_system[i] != None:
                        quantity_in_file += 1
                if quantity_plugged > quantity_in_file:
                    Search_sens()
            except:
                pass

            if call_System_tick_1_sec.is_alive() == False:
                restart = 1
            # if call_System_tick_05_sec.is_alive() == False:
            #    restart = 1
            if call_Request_data_to_server.is_alive() == False:
示例#29
0
def get_temperature_celsius():
    sensor = W1ThermSensor()
    return sensor.get_temperature()
示例#30
0
文件: Temp.py 项目: csmotion/CC
def ReadAllSensors():
	for sensor in W1ThermSensor.get_available_sensors([W1ThermSensor.THERM_SENSOR_DS18B20]):
		print("%s: %.2f" % (sensor.id, sensor.get_temperature()))
示例#31
0
def temperatures():
    from w1thermsensor import W1ThermSensor
    for sensor in W1ThermSensor.get_available_sensors():
        data.append(sensor.get_temperature())
    return (data)
示例#32
0
def get_temp():
    sensor = W1ThermSensor()
    temperature = sensor.get_temperature(W1ThermSensor.DEGREES_F)
    return temperature
def get_therm_data():
    sensor_data = {}
    for sensor in W1ThermSensor.get_available_sensors():
        sensor_data[sensor.id] = sensor.get_temperature()
    return sensor_data
 def run_forever(self):
     while not self._quit:
         for sensor in W1ThermSensor.get_available_sensors():
             self._read_and_record_temperature(sensor)
         time.sleep(self._period)
     self._logger.info("quitting")
示例#35
0
import I2C_LCD_driver
import json
import threading
import os
import sys

config_file = os.path.join(sys.path[0], './config.json')
outsideTemp = 0
insideTemp = 0
fan_on = False

with open(config_file) as cf:
    config = json.load(cf)

lcd = I2C_LCD_driver.lcd()
outsideSensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                              config["outside_sensor_id"])
insideSensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                             config["inside_sensor_id"])

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
GPIO.output(17, GPIO.LOW)


def save_config():
    with open(config_file, 'w') as cf:
        json.dump(config, cf)


def turn_fan_on():
    GPIO.output(17, GPIO.HIGH)
示例#36
0
文件: main.py 项目: Faruk0/piquarium
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(tempg, GPIO.OUT)
    GPIO.setup(tempr, GPIO.OUT)
    GPIO.setup(tempb, GPIO.OUT)
    GPIO.setup(phg, GPIO.OUT)
    GPIO.setup(phr, GPIO.OUT)
    GPIO.setup(phb, GPIO.OUT)
    GPIO.output(tempr, 1)
    GPIO.output(tempg, 0)
    GPIO.output(tempb, 0)
    GPIO.output(phr, 1)
    GPIO.output(phg, 0)
    GPIO.output(phb, 0)
    i2cdevice_list = i2c.get_devices()
    i2cdevice = i2cdevice_list[0]
    i2cdevice.query("Import," + calibration)

    while True:
        temperatures = []
        for sensor in W1ThermSensor.get_available_sensors(
            [W1ThermSensor.THERM_SENSOR_DS18B20]):
            temperatures.append(sensor.get_temperature())

        settempled(temperatures[0])

        ph = float(i2cdevice.query("r"))

        setphled(ph)

        sleep(60)
示例#37
0
    '031633c2aaff': '1A',
    '04163374ccff': '1B',
    '031633926eff': '2A',
    '031623c2deff': '2B',
    '04163372d9ff': '3A',
    '031633bfdeff': '3B',
    '031633bfadff': '4A',
    '0316339341ff': '4B',
    '031633c324ff': '5A',
    '031633c305ff': '5B',
    '031623c24bff': '6A',
    '031633c235ff': '6B'
}
TIME_FORMAT = '%Y-%m-%d_%H:%M:%S'

sensors = [x for x in W1ThermSensor.get_available_sensors()]
sensors_result = {}

parser = argparse.ArgumentParser()
parser.add_argument('-t', '--time', help=u'指定测量温度的时间, 单位为分钟', type=int)
parser.add_argument('-s',
                    '--store-path',
                    help=u'结果存储路径,csv格式。当指定-t参数时才有效',
                    type=str)
args = parser.parse_args()


def init():
    for sensor in sensors:
        sensors_result[sensor.id] = []
from w1thermsensor import W1ThermSensor
from datadog import statsd
import time
import sys
import socket

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening

server_address = ('10.0.0.48', 10137)

id_to_name = ["000008290883", "Inside Temp"]

for sensor in W1ThermSensor.get_available_sensors():
    print("Sensor %s has temperature %.2f" %
          (sensor.id, sensor.get_temperature()))

while True:

    sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, id_to_name[0])
    temp = sensor.get_temperature(W1ThermSensor.DEGREES_F)
    #statsd.gauge(id_to_name[1], temp)
    print("Called statsd with: " + id_to_name[1] + " " + str(temp))
    try:
        # Create a TCP/IP socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print >> sys.stderr, 'connecting to %s port %s' % server_address
        sock.connect(server_address)
        sockpayload = id_to_name[1] + "," + str(int(
示例#39
0
import time
import datetime
from w1thermsensor import W1ThermSensor

sensor = W1ThermSensor()

while True:
    temp1 = sensor.get_temperature()
    now = datetime.datetime.now()
    print now.strftime("%y-%m-%d %H:%M:%S") + ";" + str(temp1)
    time.sleep(10)
示例#40
0
 def __init__(self, units=W1ThermSensor.DEGREES_F):
     self.units = units
     self.sensor = W1ThermSensor()
示例#41
0
    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)
示例#42
0
import time
import sys
from datetime import datetime
from w1thermsensor import W1ThermSensor
temp_sensor = W1ThermSensor()

if len(sys.argv) != 3:
    print "USAGE:"
    print sys.argv[0], " <interval-in-seconds> <output-file>"
    sys.exit(1)

interval = float(sys.argv[1])
f_out = open(sys.argv[2], 'a') 

while True:
  temp_celsius = temp_sensor.get_temperature()
  time_now_iso8601 = datetime.now().replace(microsecond=0).isoformat()
  f_out.write(time_now_iso8601 + ";" + str(temp_celsius) + "\n")
  f_out.flush()
  time.sleep(interval)
    

f_out.close()
示例#43
0
    adcArray.append(i)
    chVolt.append(i)
#get each channel value and convert to voltage
for ch in range(4):
    chVolt[ch] = volConv(ad.getChVal(ch))
    print("Volt of channel%s is :%05.3f" % (ch, chVolt[ch]))

#BLE portion
lookUpNearbyBluetoothDevices()

#temperature sensor DS18B20 test
GPIO.setup(TEMP_GPIO, GPIO.IN, GPIO.PUD_UP)
sensor_temp = 1
while (sensor_temp):
    try:
        sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                               "041702b228ff")
        temperature = sensor.get_temperature()
        print("The temperature is %s celsius" % temperature)
        sensor_temp = 0
    except:
        print("Check pin-BCM4 that is pulled up or not, wait for a minutes")
        time.sleep(1)

#thread init
thread1 = myThread(1, "Threading-1", 3)
print(" thread1 :%s" % thread1)

page_init(3)
lcd.two_page_disp()
try:
    thread1.start()
示例#44
0
文件: rest.py 项目: gurkslask/modsol
 def get(self):
     # Get list of available sensors
     return [sensor.id for sensor in W1ThermSensor.get_available_sensors()]
示例#45
0
 def __init__(self, database_conn):
     super().__init__(database_conn)
     self.sensor = W1ThermSensor()
示例#46
0
def Read_temps():
    global write_error_thread_status, sensors_in_system
    global data_t1, error_t1, data_t2, error_t2, data_t3, error_t3, data_t4, error_t4, data_t5, error_t5, data_t6, error_t6, data_t7, error_t7, data_t8, error_t8
    temp1 = 0
    temp2 = 0
    temp3 = 0
    temp4 = 0
    temp5 = 0
    temp6 = 0
    temp7 = 0
    temp8 = 0
    sensor1_error = 1
    sensor2_error = 1
    sensor3_error = 1
    sensor4_error = 1
    sensor5_error = 1
    sensor6_error = 1
    sensor7_error = 1
    sensor8_error = 1
    sensor1_ready = False
    sensor2_ready = False
    sensor3_ready = False
    sensor4_ready = False
    sensor5_ready = False
    sensor6_ready = False
    sensor7_ready = False
    sensor8_ready = False
    while True:

        if sensors_in_system[0] != None and sensor1_ready == False:
            try:
                sensor1 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                                        sensors_in_system[0])
                sensor1_ready = True
            except Exception as e:
                pass
                # Print_error("sens1", e)

        if sensor1_ready == True:
            try:
                temp1 = sensor1.get_temperature()
                if temp1 < 75:
                    data_t1 = round(temp1 * 1.8 + 32)
                if sensor1_error == 0:
                    error_t1 = 0
                    sensor1_error = 1
                    write_error_thread_status = 0
                # print("S1 - %s" % sensor1.get_temperature())
            except BaseException:
                if sensor1_error == 1:
                    error_t1 = 1
                    sensor1_error = 0
                    write_error_thread_status = 0
                    data_t1 = None
                pass
                # print("Sensor %s not available" % sensors_in_system[0])
        # ------------------------------------------------------------------------------------------------
        if sensors_in_system[1] != None and sensor2_ready == False:
            try:
                sensor2 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                                        sensors_in_system[1])
                sensor2_ready = True
            except Exception as e:
                pass
                # Print_error("sens2", e)

        if sensor2_ready == True:
            try:
                temp2 = sensor2.get_temperature()
                if temp2 < 75:
                    data_t2 = round(temp2 * 1.8 + 32)
                if sensor2_error == 0:
                    error_t2 = 0
                    sensor2_error = 1
                    write_error_thread_status = 0
                # print("S2 - %s" % sensor2.get_temperature())
            except BaseException:
                if sensor2_error == 1:
                    error_t2 = 1
                    sensor2_error = 0
                    write_error_thread_status = 0
                    data_t2 = None
                pass
                # print("Sensor %s not available" % sensors_in_system[1])
        # ------------------------------------------------------------------------------------------------
        if sensors_in_system[2] != None and sensor3_ready == False:
            try:
                sensor3 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                                        sensors_in_system[2])
                sensor3_ready = True
            except Exception as e:
                pass
                # Print_error("sens3", e)

        if sensor3_ready == True:
            try:
                temp3 = sensor3.get_temperature()
                if temp3 < 75:
                    data_t3 = round(temp3 * 1.8 + 32)
                if sensor3_error == 0:
                    error_t3 = 0
                    sensor3_error = 1
                    write_error_thread_status = 0
                # print("S3 - %s" % data_t3)
            except BaseException:
                if sensor3_error == 1:
                    error_t3 = 1
                    sensor3_error = 0
                    write_error_thread_status = 0
                    data_t3 = None
                pass
                # print("Sensor %s not available" % sensors_in_system[2])
        # ------------------------------------------------------------------------------------------------
        if sensors_in_system[3] != None and sensor4_ready == False:
            try:
                sensor4 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                                        sensors_in_system[3])
                sensor4_ready = True
            except Exception as e:
                pass
                # Print_error("sens4", e)

        if sensor4_ready == True:
            try:
                temp4 = sensor4.get_temperature()
                if temp4 < 75:
                    data_t4 = round(temp4 * 1.8 + 32)
                if sensor4_error == 0:
                    error_t4 = 0
                    sensor4_error = 1
                    write_error_thread_status = 0
                # print("S4 - %s" % data_t4)
            except BaseException:
                if sensor4_error == 1:
                    error_t4 = 1
                    sensor4_error = 0
                    write_error_thread_status = 0
                    data_t4 = None
                pass
                # print("Sensor %s not available" % sensors_in_system[3])
        # ------------------------------------------------------------------------------------------------
        if sensors_in_system[4] != None and sensor5_ready == False:
            try:
                sensor5 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                                        sensors_in_system[4])
                sensor5_ready = True
            except Exception as e:
                pass
                # Print_error("sens5", e)

        if sensor5_ready == True:
            try:
                temp5 = sensor5.get_temperature()
                if temp5 < 75:
                    data_t5 = round(temp5 * 1.8 + 32)
                if sensor5_error == 0:
                    error_t5 = 0
                    sensor5_error = 1
                    write_error_thread_status = 0
                # print("S5 - %s" % data_t5)
            except BaseException:
                if sensor5_error == 1:
                    error_t5 = 1
                    sensor5_error = 0
                    write_error_thread_status = 0
                    data_t5 = None
                pass
                # print("Sensor %s not available" % sensors_in_system[4])
        # ------------------------------------------------------------------------------------------------
        if sensors_in_system[5] != None and sensor6_ready == False:
            try:
                sensor6 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                                        sensors_in_system[5])
                sensor6_ready = True
            except Exception as e:
                pass
                # Print_error("sens6", e)

        if sensor6_ready == True:
            try:
                temp6 = sensor6.get_temperature()
                if temp6 < 75:
                    data_t6 = round(temp6 * 1.8 + 32)
                if sensor6_error == 0:
                    error_t6 = 0
                    sensor6_error = 1
                    write_error_thread_status = 0
                # print("S6 - %s" % data_t6)
            except BaseException:
                if sensor6_error == 1:
                    error_t6 = 1
                    sensor6_error = 0
                    write_error_thread_status = 0
                    data_t6 = None
                pass
                # print("Sensor %s not available" % sensors_in_system[5])
        # ------------------------------------------------------------------------------------------------
        if sensors_in_system[6] != None and sensor7_ready == False:
            try:
                sensor7 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                                        sensors_in_system[6])
                sensor7_ready = True
            except Exception as e:
                pass
                # Print_error("sens7", e)

        if sensor7_ready == True:
            try:
                temp7 = sensor7.get_temperature()
                if temp7 < 75:
                    data_t7 = round(temp7 * 1.8 + 32)
                if sensor7_error == 0:
                    error_t7 = 0
                    sensor7_error = 1
                    write_error_thread_status = 0
                # print("S7 - %s" % data_t7)
            except BaseException:
                if sensor7_error == 1:
                    error_t7 = 1
                    sensor7_error = 0
                    write_error_thread_status = 0
                    data_t7 = None
                pass
                # print("Sensor %s not available" % sensors_in_system[6])

        if sensor8_ready == True:
            try:
                temp8 = sensor8.get_temperature()
                if temp8 < 75:
                    data_t8 = round(temp8 * 1.8 + 32)
                if sensor8_error == 0:
                    error_t8 = 0
                    sensor8_error = 1
                    write_error_thread_status = 0
                # print("S7 - %s" % data_t7)
            except BaseException:
                if sensor8_error == 1:
                    error_t8 = 1
                    sensor8_error = 0
                    write_error_thread_status = 0
                    data_t8 = None
                pass
示例#47
0
#!/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
示例#48
0
def read_value(*args):
    sensor = W1ThermSensor()
    temperature_in_celsius = sensor.get_temperature()
    del sensor
    return temperature_in_celsius
示例#49
0
try:
    conn = pyodbc.connect(
        'DRIVER=FreeTDS;SERVER=topeni.database.windows.net;PORT=1433;DATABASE=topeni;UID=web;PWD=Laky85@@;TDS_Version=8.0;'
    )
    cursor = conn.cursor()
    sql = "INSERT INTO [dbo].[teploty] ([datum],[venku],[zona1],[zona2],[Z1top],[Z2top],[AKU1h],[AKU1p],[AKU1s],[AKU2h],[Bazen],[Kotel],[Solar],[Solarvrt],[rezerva],[TUV],[Z2poz],[solarOT])VALUES(GETDATE(),'" + venku + "','" + Z1 + "','" + Z2 + "','" + Ztop1 + "','" + Ztop2 + "','" + Aku1h + "','" + Aku1p + "','" + Aku1s + "','" + Aku2h + "','" + bazen + "','" + Solar1 + "','" + Solar2 + "','" + Solarvr + "','" + rezerva + "','" + predtuv + "','" + Z2a + "','" + solarOT + "')"
    print sql
    cursor.execute(sql)
    conn.commit()
    cursor.close()
    print "insert"
except:
    print "chyba T1"

try:
    tkomin = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                           "03177138a2ff").get_temperature()
    tkomin = str(tkomin)
    print tkomin
except:
    tkomin = 0
    print "chyba cidla tkomin"

try:
    tkotelna = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                             "00000608df3d").get_temperature()
    tkotelna = str(tkotelna)
    print float(tkotelna)
except:
    tkotelna = 0
    print "chyba cidla tkotelna"
示例#50
0
import time
import logging

logger = logging.getLogger(__name__)

# Initialize the GPIO Pins
#os.system('modprobe w1-gpio')  # Turns on the GPIO module
#os.system('modprobe w1-therm') # Turns on the Temperature module

DEG_FAHRENHEIT = 0
DEG_CELSIUS = 1
DEG_KELVIN = 2

# returns a jSON object containing the current values of all 28* one-wire devices on the bus
# sensors are scanned on module load for performance; if your bus changes frequently you can move into status()
sensors = W1ThermSensor.get_available_sensors()
logger.debug("Available sensors: " + str(sensors))


def available_sensors():
    return sensors


# send -1 for no rounding
def status(config={}, output="default"):
    logger.debug("generating status")
    result = {}
    dnames = {}

    # not an error if no sensors specified, you just won't get pretty names
    if "inputs" in config:
示例#51
0
def page_input():
    """ Display sensor settings """
    # TCA9548A I2C multiplexer
    multiplexer_addresses = [
        '0x70', '0x71', '0x72', '0x73', '0x74', '0x75', '0x76', '0x77'
    ]
    multiplexer_channels = list(range(0, 9))

    camera = Camera.query.all()
    lcd = LCD.query.all()
    pid = PID.query.all()
    relay = Relay.query.all()
    sensor = Sensor.query.all()
    user = User.query.all()

    conditional = Conditional.query.filter(
        Conditional.conditional_type == 'sensor').all()
    conditional_actions = ConditionalActions.query.all()

    display_order = csv_to_list_of_int(DisplayOrder.query.first().sensor)

    form_add_sensor = flaskforms.SensorAdd()
    form_mod_sensor = flaskforms.SensorMod()

    form_conditional = flaskforms.Conditional()
    form_conditional_actions = flaskforms.ConditionalActions()

    # If DS18B20 sensors added, compile a list of detected sensors
    ds18b20_sensors = []
    if Sensor.query.filter(Sensor.device == 'DS18B20').count():
        try:
            for each_sensor in W1ThermSensor.get_available_sensors():
                ds18b20_sensors.append(each_sensor.id)
        except OSError:
            flash("Unable to detect sensors in '/sys/bus/w1/devices'", "error")

    # Create list of file names from the input_options directory
    # Used in generating the correct options for each sensor/device
    sensor_templates = []
    sensor_path = os.path.join(
        INSTALL_DIRECTORY, 'mycodo/mycodo_flask/templates/pages/input_options')
    for (_, _, file_names) in os.walk(sensor_path):
        sensor_templates.extend(file_names)
        break

    if request.method == 'POST':
        if not flaskutils.user_has_permission('edit_controllers'):
            return redirect(url_for('page_routes.page_input'))

        if form_add_sensor.sensorAddSubmit.data:
            flaskutils.sensor_add(form_add_sensor)
        elif form_mod_sensor.modSensorSubmit.data:
            flaskutils.sensor_mod(form_mod_sensor)
        elif form_mod_sensor.delSensorSubmit.data:
            flaskutils.sensor_del(form_mod_sensor)
        elif form_mod_sensor.orderSensorUp.data:
            flaskutils.sensor_reorder(form_mod_sensor.modSensor_id.data,
                                      display_order, 'up')
        elif form_mod_sensor.orderSensorDown.data:
            flaskutils.sensor_reorder(form_mod_sensor.modSensor_id.data,
                                      display_order, 'down')
        elif form_mod_sensor.activateSensorSubmit.data:
            flaskutils.sensor_activate(form_mod_sensor)
        elif form_mod_sensor.deactivateSensorSubmit.data:
            flaskutils.sensor_deactivate(form_mod_sensor)

        elif form_conditional.deactivate_cond.data:
            flaskutils.conditional_deactivate(form_conditional)
        elif form_conditional.activate_cond.data:
            flaskutils.conditional_activate(form_conditional)
        elif form_mod_sensor.sensorCondAddSubmit.data:
            flaskutils.conditional_add(
                'sensor', 1, sensor_id=form_mod_sensor.modSensor_id.data)
        elif form_conditional.delete_cond.data:
            flaskutils.conditional_mod(form_conditional, 'delete')
        elif form_conditional.save_cond.data:
            flaskutils.conditional_mod(form_conditional, 'modify')
        elif form_conditional_actions.add_action.data:
            flaskutils.conditional_action_add(form_conditional_actions)
        elif form_conditional_actions.save_action.data:
            flaskutils.conditional_action_mod(form_conditional_actions,
                                              'modify')
        elif form_conditional_actions.delete_action.data:
            flaskutils.conditional_action_mod(form_conditional_actions,
                                              'delete')
        return redirect(url_for('page_routes.page_input'))

    return render_template('pages/input.html',
                           camera=camera,
                           conditional=conditional,
                           conditional_actions=conditional_actions,
                           conditional_actions_list=CONDITIONAL_ACTIONS,
                           displayOrder=display_order,
                           ds18b20_sensors=ds18b20_sensors,
                           form_add_sensor=form_add_sensor,
                           form_conditional=form_conditional,
                           form_conditional_actions=form_conditional_actions,
                           form_mod_sensor=form_mod_sensor,
                           lcd=lcd,
                           measurements=MEASUREMENTS,
                           multiplexer_addresses=multiplexer_addresses,
                           multiplexer_channels=multiplexer_channels,
                           pid=pid,
                           relay=relay,
                           sensor=sensor,
                           sensor_templates=sensor_templates,
                           units=MEASUREMENT_UNITS,
                           user=user)
示例#52
0
    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
示例#53
0
 def __init__(self, read_interval):
     self.thread = threading.Thread(target=self._read_temp_thread)
     self.read_interval = read_interval
     self.sensor = W1ThermSensor()
     self.temperature = self.sensor.get_temperature()
     self.thread.start()
示例#54
0
def test_get_available_sensors_no_sensors():
    _remove_w1_therm_sensors()

    sensors = W1ThermSensor.get_available_sensors()
    sensors.should.be.empty
示例#55
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from w1thermsensor import W1ThermSensor, NoSensorFoundError

if __name__ == '__main__':
    try:
        sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20)
        temperature = sensor.get_temperature()
        print(temperature)
        print(sensor.sensorpath)
        print(sensor.id)
    except NoSensorFoundError as e:
        print(e)
    
示例#56
0
# Ensure /boot/config.txt has added GPIO14 instead of default Pin 4
# dtoverlay=w1-gpio,gpio=14

from sense_hat import SenseHat
from time import sleep
from w1thermsensor import W1ThermSensor

# set up the thermometer
thermometer = W1ThermSensor()

#set up SenseHat
sense = SenseHat()

# set up some colour variables to use
red = (100, 0, 0)
green = (0, 100, 0)
blue = (0, 0, 100)

# clear the screen
sense.clear()

while True:
    temperature = round(thermometer.get_temperature(W1ThermSensor.DEGREES_C),
                        1)

    print("Temperature is ", temperature, " Celsius")

    sense.show_message("Temperature is " + str(temperature) + " Celsius",
                       text_colour=red)

    sleep(5)
示例#57
0
		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'
示例#58
0
 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
示例#59
0
    def getReadingsEx(_self, leds, tf, cfg):

        tf.addTraceEntryInfo("Taking readings from temperature sensors ex")

        # Get a list of sensors to check form the config file
        sensorArray = cfg.getSensorDefinition()

        # Get the Ip address of the Mazi server in case we need to record any values to it
        maziIP = cfg.getMaziAddress()

        # And the readings will be held here
        sensorReadings = []

        # Turn LEDS on or off
        leds.activityOn()
        leds.warningOff()
        leds.errorOff()

        # Keep a track of the total values read from the sensors
        totalReadings = 0

        # And work through each sensor
        for current in sensorArray:

            try:

                if (current['enabled'].lower() == 'true'):

                    # Get a reference to the sensor
                    sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,
                                           current['id'])

                    # Add the lookup string (e.g. "12M-DEPTH" amd the temperatur reading to the list
                    reading = sensor.get_temperature()
                    totalReadings += reading
                    sensorReadings.append((current['description'], reading))

                    # And see if we need to record this value to the MAZI portal server
                    if (current['exportToMazi'].lower() != 'false'):
                        _self.reportToMaziPortal(tf, current['exportToMazi'],
                                                 maziIP)

            except:
                # Caught some sort of error. Log the details to the trce file
                tf.addTraceEntryError(
                    "Error while trying to read from sensor: " +
                    current['id'] + " " + current['description'])

                # And add the NA for this sensor reading
                sensorReadings.append((current['description'], "N/A"))

                # Switch on waring LED
                leds.warningOn()

        # If all the readings are zero, this looks highly suspicious. Turn on error LED
        if (totalReadings == 0):
            tf.addTraceEntryError(
                "Error, all sensors returned zero values. Please check conection to sensor array"
            )
            leds.errorOn()

        # Finished wih readings, urn off activity LED
        leds.activityOff()

        # And return the list of readings
        return sensorReadings