示例#1
0
def main():
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.cleanup()

    instance = dht11.DHT11(pin=int(os.getenv("TEMP_GPIO")))
    attempt = int(os.getenv("TEMP_ATTEMPT")) + 1

    print(f"Initializing {os.getenv('APP_NAME')}...")
    count = 0

    while True:
        for a in range(1, attempt):
            result = instance.read()
            now = datetime.datetime.now()
            if result.is_valid():
                count += 1
                print('[{0} | {1} | {2}] Temp={3:0.1f}ºC Humidity={4:0.1f}%'.
                      format(count, a, now.strftime("%Y-%m-%d %H:%M:%S"),
                             result.temperature, result.humidity))
                update_mqtt(f"{mqtt_host}/sensor/temperature",
                            result.temperature)
                update_mqtt(f"{mqtt_host}/sensor/humidity", result.humidity)
                break
            else:
                #print(f"Failed {a} to get reading. Try again!")
                if (a + 1) == attempt:
                    print(
                        '[{0} | {1} | {2}] Temp={3:0.1f}ºC Humidity={4:0.1f}%'.
                        format(count, a, now.strftime("%Y-%m-%d %H:%M:%S"), 0,
                               0))
            time.sleep(2)

        time.sleep(int(os.getenv("INTERVAL", 30)))
示例#2
0
def read_from_sensors():
    print("Start!")
    temp_results = []
    # initialize GPIO
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.cleanup()
    instance = dht11.DHT11(pin=4)  # read data from DHT11 sensor using pin 4
    schar = 0x4d42
    port = serial.Serial("/dev/ttyAMA0", baudrate=9600,
                         timeout=5.0)  # serial port for dust sensor

    while True:
        result = instance.read()
        pm25 = ''
        pm10 = ''
        """try:
            rcv = port.read(32)
            rlen = len(rcv)
            if rlen == 32:
                schar, flen, pm10, pm25, pm100, td1, td2, td3, ab3, ab5, ab10, ab25, ab50, ab100, td4, csum = \
                    unpack('>HHHHHHHHHHHHHHHH', rcv)
            # Check Bit for Data Sum, 16-byte 	Check Bit = Start Character 1 + Start Character 2 + ...all data
            cSum = 0
            for i in range(0, len(rcv) - 3):
                cSum = cSum + ord(rcv[i])
            # print('4=',hex(schar),hex(flen), hex(pm10), hex(pm25), hex(pm100), hex(td1), hex(td2), hex(td3), hex(ab3),
            # hex(ab5), hex(ab10), hex(ab25), hex(ab50), hex(ab100), hex(td4), hex(csum), hex(cSum))

            if (schar == 0x424d) and (cSum == csum):
                print("OK!", pm10, pm25)
            else:
                print('Byte order NOT OK')
                try:
                    port.read(31)
                except:
                    port.flushInput()
                    print("Read 1 error")
        except (KeyboardInterrupt, SystemExit):
            port.close()"""

        if result.is_valid():
            temp_results.append(
                [result.temperature, result.humidity, pm25, pm10])
            print("Last valid input: " + str(datetime.datetime.now()))

        # every minute average results from sensors and send data in separate thread
        if datetime.datetime.now().second == 0:
            """try:
                w_s = os.pipe()
                thread.start_new_thread(write_and_send, ("Thread-1", w_s,))
                threading.Thread(target=write_and_send, args=(temp_results,)).start()
            except:
                print("Error: unable to start thread")"""
            write_and_send(temp_results)
            temp_results = []
        time.sleep(1)
示例#3
0
def get_temp():

    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)

    instance = dht11.DHT11(pin=Temp_sensor)

    while True:
        #データ取得
        result = instance.read()
        return result.temperature, result.humidity
示例#4
0
 def GetTemp(self):  # 温湿度を取得
     instance = dht11.DHT11(pin=TEMP_SENSOR_PIN)
     retry_count = 0
     while True:  # MAX_RETRY回まで繰り返す
         retry_count += 1
         result = instance.read()
         if result.is_valid():  # 取得できたら温度と湿度を返す
             return result.humidity, result.temperature
         elif retry_count >= MAX_RETRY:
             return 99.9, 99.9  # MAX_RETRYを過ぎても取得できなかった時に温湿度99.9を返す
         sleep(RETRY_TIME)
示例#5
0
def get_actuator_dict():
    """
    get temperature and humidity from actuator.
    return OrderedDict
    {
        "temperature":
        "humidity":
        "location":
        "datetime":
    }
    """
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)

    instance = dht11.DHT11(pin=DHT_NUMBER)
    result = instance.read()
    read_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    if result.is_valid():
        output_json(read_datetime, result.temperature, result.humidity)
        output_csv(read_datetime, result.temperature, result.humidity)
    GPIO.cleanup()
    with open('./json/actuator.json', 'r', encoding='utf-8') as f:
        return json.load(f, object_pairs_hook=OrderedDict)
示例#6
0
def main(argv):

    table_name = 'envtable'
    dt_col = 'date_time'
    temp_col = 'temp'
    humidity_col = 'humidity'
    air_pollution_col = 'air_pollution'

    try:
        # Create a database
        db = sqlite3.connect('data/envdb')

        # Get a cursor object
        cursor = db.cursor()
        cursor.execute('CREATE TABLE IF NOT EXISTS \
                      {tn} ({dt} datetime, {t} REAL, {h} REAL, {a} REAL)'  \
                        .format(tn=table_name, dt=dt_col, t=temp_col, h=humidity_col, a=air_pollution_col))
        db.commit()
    except Exception as e:
        db.rollback()
        print('Failed to open or create table')
        raise e
    #finally:
    #db.close()

    # initialize GPIO
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.cleanup()
    # read data using pin 14

    # Initialize the ADS1115 ADC (16-bit) instance
    adc = Adafruit_ADS1x15.ADS1115()

    # Note you can change the I2C address from its default (0x48), and/or the I2C
    # bus by passing in these optional parameters:
    #adc = Adafruit_ADS1x15.ADS1015(address=0x49, busnum=1)

    # Choose a gain of 1 for reading voltages from 0 to 4.09V.
    # Or pick a different gain to change the range of voltages that are read:
    #  - 2/3 = +/-6.144V
    #  -   1 = +/-4.096V
    #  -   2 = +/-2.048V
    #  -   4 = +/-1.024V
    #  -   8 = +/-0.512V
    #  -  16 = +/-0.256V
    # See table 3 in the ADS1015/ADS1115 datasheet for more info on gain.
    GAIN = 1

    instance = dht11.DHT11(pin=17)

    DEFAULT_CONFIG_PATH = 'config/config.json'

    with open(DEFAULT_CONFIG_PATH, 'r') as config_file:
        config = json.load(config_file)['temperatureSensor']
    print(config)

    # Configure Oauth2 access_token for the client application.  Here we have used
    # the device token for the configuration
    artikcloud.configuration = artikcloud.Configuration()
    artikcloud.configuration.access_token = config['deviceToken']

    # We create an instance of the Message API class which provides
    # the send_message() and get_last_normalized_messages() api call
    # for our example
    api_instance = artikcloud.MessagesApi()

    # Device_message - data that is sent to your device
    device_message = {}

    # We send random values to the 'temp' field for this FireSensor.
    # Let's send a random value between 0 and 200 for this demo.
    #device_message['temp'] = random.randrange(0,200);
    result = instance.read()

    humidity = 0
    temp_value = 0
    if result.is_valid():
        temp_value = result.temperature * 1.8 + 32
        device_message['temp'] = temp_value
        humidity = result.humidity
        print("Last valid input: " + str(datetime.datetime.now()))
        print("Temperature: %d F" % temp_value)
        print("Humidity: %d %%" % result.humidity)

    time.sleep(1)

    # Set the 'device id' - value from your config.json file
    device_sdid = config['deviceId']
    send_message(api_instance, device_message, device_sdid)

    if (humidity > 0):
        device_message = {}
        device_message['humidity'] = humidity
        send_message(api_instance, device_message, device_sdid)

    #sensor = BMP085.BMP085()
    #pressure = sensor.read_pressure()
    #print('Pressure = {0:0.2f} Pa'.format(pressure))
    air_qa_value = adc.read_adc(0, gain=GAIN)
    print("Air quality: %f " % air_qa_value)

    if (air_qa_value > 0):
        device_message = {}
        device_message['air_quality'] = air_qa_value
        #if (pressure > 0):
        #   device_message = {}
        #   device_message['pressure'] = pressure
        send_message(api_instance, device_message, device_sdid)

    db.execute("INSERT INTO {tn}  VALUES ((CURRENT_TIMESTAMP), {t}, {h},{a})"\
         .format(tn=table_name, t = temp_value, h = humidity, a =air_qa_value))
    db.commit()
    db.close()
示例#7
0
import RPi.GPIO as GPIO
from DHT11_Python import dht11
import time
import datetime

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

# read data using pin 14
instance = dht11.DHT11(pin=5)

while True:
    result = instance.read()
    if result.is_valid():
        print("Last valid input: " + str(datetime.datetime.now()))
        print("Temperature: %d C" % result.temperature)
        print("Humidity: %d %%" % result.humidity)
    time.sleep(1)
示例#8
0
import RPi.GPIO as GPIO
import DHT11_Python.dht11 as dht11
from time import sleep

GPIO.setmode(GPIO.BCM)

dht = dht11.DHT11(pin=4)

try:
    while True:
        result = dht.read()

        if result.is_valid():
            print("T = %-3.1f C" % result.temperature)
            print("H = %-3.1f %%" % result.humidity)

        sleep(6)

except KeyboardInterrupt:
    GPIO.cleanup()
示例#9
0
文件: kisascode.py 项目: vely44/KISAS
import RPi.GPIO as GPIO
from DHT11_Python import dht11
import time
import datetime
from numpy import *
from matplotlib.pyplot import plot, show
import numpy as np

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(13, GPIO.OUT)  #pwm

# read data using pin 14
instance = dht11.DHT11(pin=14)  #DHT data line
pwm = GPIO.PWM(13, 100)
#Main Program
x = arange(0, 100, 1)
while True:
    for buffer in range(100):
        result = instance.read()
        if result.is_valid():
            print("Last valid input: " + str(datetime.datetime.now()))
            print("Temperature: %d C" % result.temperature)
            print("Humidity: %d %%" % result.humidity)
            y[buffer] = result.temperature
    time.sleep(1)
    #continue()

plot(x, y)
show()
示例#10
0
def temperature_read(adc, ch):
    buf = adc.xfer2([1, ((8 + ch) << 4), 0])  # read adc data
    adResult = ((buf[1] & 3) << 8) + buf[2]  # select data
    volt = adResult * 3.3 / 1024.0  # converte data to Voltage
    temperature = (volt * 1000.0 - 500.0) / 10.0  # convertr volt to temp
    return temperature


if __name__ == ("__main__"):

    # raspi gpio init
    gpio_init()

    # DHT11 init
    dht11_instance = dht11.DHT11(pin=conf.gpio_no)

    # GY30 init
    gy30_instance = gy30.GY30(conf.gy30_bus, conf.gy30_addr)

    # AWS IoT init
    aws_iot_msg_client = aws.AwsIotMessage()
    if aws_iot_msg_client.connect():
        print("connected.")
    else:
        print("connection error.")
        sys.exit(1)

    # raspi temperature read
    while (True):
示例#11
0
 def _dht11_reader(self):
   self.reader = dht11.DHT11(pin=self.pin)
   self.raw_data = self.reader.read()