Exemplo n.º 1
0
 def read(self):
     try:
         measurement = mh_z19.read()['co2']
         self.save_measurement(measurement)
     except TypeError:
         measurement = mh_z19.read_from_pwm()['co2']
         self.save_measurement(measurement)
Exemplo n.º 2
0
def setup_screen(screen):
    ssid = 'ERROR'

    hostapd_conf = open('/etc/hostapd/hostapd.conf', 'r')
    hostapd_conf_lines = hostapd_conf.readlines()

    for line in hostapd_conf_lines:
        if line.strip().startswith('ssid='):
            ssid = line.split('=')[1]
            break

    while True:
        new_reading = mh_z19.read()['co2']
        store_new_CO2_read(new_reading)

        new_reading_color_code = 7
        if new_reading <= 700 and new_reading < 1000:
            new_reading_color_code = 2
        elif new_reading >= 1000 and new_reading <= 1400:
            new_reading_color_code = 3
        elif new_reading > 1400:
            new_reading_color_code = 1

        screen.print_at(' WiFi:         ', 0, 1, 6, 2)
        screen.print_at('╔══════════════════╗', 0, 2, 7, 2)
        screen.print_at('  Red: ' + ssid, 0, 4, 2, 1)
        screen.print_at('╚══════════════════╝', 0, 6, 7, 2)
        screen.print_at(' Medición CO2:         ', 0, 9, 6, 2)
        screen.print_at('╔══════════════════╗', 0, 10, 7, 2)
        screen.print_at('  ' + str(new_reading) + ' PPM', 0, 12,
                        new_reading_color_code, 1)
        screen.print_at('╚══════════════════╝', 0, 14, 7, 2)
        screen.refresh()
        time.sleep(1)
Exemplo n.º 3
0
def main():

    TIME = getTime()
    SensorValueArr = [
        TIME, LPG, METAN, PROPAN, CO, HYDROGEN, SMOKE, CO2, TEMP, HUM, FAILURE
    ]
    db = Database()
    com = comm.Cummunication()
    port = com.connect()
    dht22_sensor = dht22.DHT22()
    while (True):

        msg = com.read_message(port)
        val, msgID = com.getValue(msg)
        print("value:", val)
        print("type:", msgID)
        if msgID != 0:
            SensorValueArr[7] = mh_z19.read()["co2"]
            SensorValueArr[8] = dht22_sensor.read_dht(False)
            SensorValueArr[9] = dht22_sensor.read_dht(True)
            SensorValueArr[msgID] = val
            if SensorValueArr[1] >= LPG_LIMIT and SensorValueArr[2] >= METAN_LIMIT and \
               SensorValueArr[3] >= PROPAN_LIMIT and SensorValueArr[4] >= CO_LIMIT and \
               SensorValueArr[5] >= HYDROGEN_LIMIT and SensorValueArr[6] >=SMOKE_LIMIT and \
               SensorValueArr[7] >= CO2_LIMIT and SensorValueArr[8] >= TEMP_LIMIT and SensorValueArr[9] >= HUM_LIMIT:
                SensorValueArr[10] = True

        if msgID == 6:
            msgID = 0
            SensorValueArr[0] = getTime()
            db.prepare_data(SensorValueArr)
            db.send_data()
            print("Data sent...")

        print(SensorValueArr)
Exemplo n.º 4
0
def main():


    TIME = getTime() # Initialize time value
    SensorValueArr = [TIME, LPG, SMOKE, CO, CO2, TEMP, HUM, FAILURE] # Sensor arr keep all sensor data, time and failure data to send cloud.
    db = Database()      
    com = comm.Cummunication()
    port = com.connect()
    dht22_sensor = dht22.DHT22()
    while(True):
        
        msg = com.read_message(port)
        val, msgID  = com.getValue(msg)
        print ("value:", val)
        print("type:", msgID)
        if msgID != 0: # if the mqsensor data was read, other sensor's data will read.
            SensorValueArr[4] = mh_z19.read()["co2"]
            SensorValueArr[5] = dht22_sensor.read_dht(False)
            SensorValueArr[6] = dht22_sensor.read_dht(True)
            SensorValueArr[msgID] = val
            if SensorValueArr[1] >= LPG_LIMIT and SensorValueArr[2] >= SMOKE_LIMIT and \    
               SensorValueArr[3] >= CO_LIMIT and SensorValueArr[4] >= CO2_LIMIT and \
               SensorValueArr[5] >= TEMP_LIMIT and SensorValueArr[6] >= HUM_LIMIT: # Check Sensor failure limits.
                
                SensorValueArr[7] = True
         
        if msgID == 3: # When All sensor data was read. The data will send cloud.  
            msgID = 0
            SensorValueArr[0] = getTime()
            db.prepare_data(SensorValueArr)
            db.send_data()
            print("Data sent...")
        
        print(SensorValueArr)
def loop():
    while(True):
        temp_data = dht.readDHT11()
        sleep(20)

        co2_data=mh_z19.read()
        if (co2_data["co2"] > 0):
            print("co2 ok")
            i = urllib2.urlopen(baseURL + fieldCO2 + str(co2_data["co2"])) #this command later opens a url. The "+" arguments are additions to the base url.
                                                                           #"fieldTemp" leads to the right graph, while the "str(...)" string is the actual data
            i.read()     #opening the stored function x
            i.close()    #closing the function
            sleep(20)    #the databse accepts new data every 15 seconds
        
        if (temp_data is dht.DHTLIB_OK):      #read DHT11 and get a return value. Then determine whether data read is normal according to the return value.
           print("DHTLIB_OK!!")
           x = urllib2.urlopen(baseURL + fieldTEMP + str(dht.temperature)) #this command later opens a url. The "+" arguments are additions to the base url.
                                                                           #"fieldTemp" leads to the right graph, while the "str(...)" string is the actual data
           x.read()     #opening the stored function x
           x.close()    #closing the function
           sleep(20)    #the databse accepts new data every 15 seconds
           if(dht.humidity < 100):
                y = urllib2.urlopen(baseURL + fieldHUM + str(dht.humidity))
                y.read()
                y.close()
        print("Humidity : %.2f, \t Temperature : %.2f, \t CO2: %.2f \n"%(dht.humidity,dht.temperature,co2_data["co2"]))
        sleep(10)
        if(co2_data["co2"]<1000):       #co2 < 1000ppm normal outdor level
              setColor(color_green)  
        elif(co2_data["co2"]<2000):  #co2: 1000-2000ppm level associated with complains of drowsiness and poor air 
                setColor(color_orange)  
        
        else:                           #co2: > 2000 level associated with headaches, sleepiness and poor concentration
                setColor(color_red)
                pwm_buzzer.ChangeDutyCycle(100)
Exemplo n.º 6
0
def get_data_points():
    opc_data = {}
    opc_data = alphasense.histogram()

    mhz19_data = mh_z19.read()

    # Get the five measurement values from the OPC sensor.
    pm1 = opc_data['PM_A']
    pm2_5 = opc_data['PM_B']
    pm10 = opc_data['PM_C']
    temperature = opc_data['Temperature']
    humidity = opc_data['Relative humidity']

    # Get the CO2 measurement value from the MHZ19 sensor.
    try:
        co2 = mhz19_data['co2']
    except:
        co2 = None
        print "ERROR: CO2 value could not be read"

    # Get a local timestamp
    timestamp = datetime.datetime.utcnow().isoformat()

    # Print out current readings to terminal
    print "****************************************"
    print "Timestamp: ", timestamp
    print "Temperature: {0}{1}C".format(round(temperature, 1),
                                        u'\u00b0'.encode('utf8'))
    print "Humidity: {0}%".format(round(humidity, 1))
    print "PM  1.0: {0}{1}g/m{2}".format(round(pm1,
                                               2), u'\u00B5'.encode('utf8'),
                                         u'\u00B3'.encode('utf8'))
    print "PM  2.5: {0}{1}g/m{2}".format(round(pm2_5,
                                               2), u'\u00B5'.encode('utf8'),
                                         u'\u00B3'.encode('utf8'))
    print "PM 10.0: {0}{1}g/m{2}".format(round(pm10,
                                               2), u'\u00B5'.encode('utf8'),
                                         u'\u00B3'.encode('utf8'))
    print "C0{0}: {1}ppm".format(u"\u2082".encode('utf8'), co2)
    print "****************************************"

    # Create InfluxDB datapoints
    datapoints = [{
        "measurement": session,
        "tags": {
            "run_num": run_num
        },
        "time": timestamp,
        "fields": {
            "temperaturevalue": temperature,
            "humidityvalue": humidity,
            "pm1value": pm1,
            "pm25value": pm2_5,
            "pm10value": pm10,
            "co2value": co2
        }
    }]
    return datapoints
Exemplo n.º 7
0
def getCo2():
    out = mh_z19.read()

    if not "co2" in out:
        print("Initializing mh_z19.......")
        time.sleep(10)

    co2 = out['co2']
    return co2
Exemplo n.º 8
0
def obtain_co2():
    try:
        val = mh_z19.read()
    except serial.SerialException as e:
        print("error", e)
    else:
        if val:
            CO2.set(val['co2'])
        else:
            failure_count.inc()
Exemplo n.º 9
0
def read():
    global ini
    try:
        if ini.get("mode", "run_mode") == "dummy":
            result = {"co2": 400}
        else:
            result = mh_z19.read()
        return result
    except:
        traceback.print_exc()
Exemplo n.º 10
0
def main():
    # DHT11 sensori
    dht11_sensor = Adafruit_DHT.DHT11
    dht11_gpio = 17

    sleep_time = 120

    file_name = get_meas_file_name()
    meas_time = raw_input("Anna mittauksen aika tunteina: ")

    # Time to stop measure
    timestamp_start = datetime.now()
    timestamp_end = timestamp_start + timedelta(hours=int(meas_time))

    # open file for results
    file = open(file_name, "w")
    file.write('date, time, temperature, humidity, co2\r\n')

    while True:

        # debug
        hum = 10
        temp = 20
        co2 = 400

        # read dht11 sensor
        hum, temp = Adafruit_DHT.read_retry(dht11_sensor, dht11_gpio)

        # read MH_Z19 sensor
        co2 = mh_z19.read()["co2"]

        timestamp_now = datetime.now()
        time_left = int((timestamp_end - timestamp_now).total_seconds() / 60.0)

        # print data to screen and file
        time = datetime.now().strftime('%Y-%m-%d %H:%M')
        print(
            '{3}  Temp={0:0.1f}*C  Humidity={1:0.1f}%  CO2={2}ppm  time left (minutes)={4}'
            .format(temp, hum, co2, time, time_left))
        time = datetime.now().strftime('%Y-%m-%d, %H:%M')

        #temp = int(temp)
        #hum = int(hum)
        file.write('{0},{1},{2},{3}\r\n'.format(time, int(temp), int(hum),
                                                co2))

        # Check if time to quit
        if (timestamp_now > timestamp_end):
            break

        # break before next round
        sleep(sleep_time)

    file.close
Exemplo n.º 11
0
def start_monitoring():
    # dht and hmt senors
    dht_hmt_sensor = Adafruit_DHT.DHT22
    humidity, temperature = Adafruit_DHT.read_retry(dht_hmt_sensor, 26)
    # co2 senors
    co2 = mh_z19.read()
    # timestamp
    current_milli_time = str(int(round(time.time() * 1000)))
    # lx senors
    bus.write_byte(__DEV_ADDR, __CMD_PWR_ON)
    bus.write_byte(__DEV_ADDR, __CMD_THRES2)
    time.sleep(0.2)
    res = bus.read_word_data(__DEV_ADDR, 0)
    res = ((res >> 8) & 0xff) | (res << 8) & 0xff00
    lx = round(res / (2 * 1.2), 2)

    # if every hardware is working
    if humidity is not None and temperature is not None and co2 != "9":
        data = {}
        data['date'] = time.strftime('%Y%m%d', time.localtime(time.time()))
        data['time'] = time.strftime('%H:%M', time.localtime(time.time()))
        data['tmp'] = format(temperature, ".1f")
        data['hmt'] = format(humidity, ".1f")
        data['ppm'] = str(co2['co2'])
        data['lx'] = str(lx)
        data['ld'] = str(GPIO.input(21))
        data['timestamp'] = current_milli_time
        # push to the sets
        current_sets.append(data)
        messages = {
            "time": data['time'],
            "tmp": data['tmp'],
            "hmt": data['hmt'],
            "ppm": data['ppm'],
            "lx": data['lx'],
            "ld": data['ld'],
            "date": data['date'],
            "timestamp": data['timestamp'],
            "device": str(DEVICE_ID),
        }
        print(messages)
        # save to local folder
        print(save_to_local_folder(data['date'], messages))

        # post to remote server
        try:
            print(post_to_server(messages))
        except:
            pass
    return
Exemplo n.º 12
0
def measure():
    global screenOn
    global lastPressed
    global oldLastPressed

    for i in range(6):
        now = datetime.now()
        co2 = mh_z19.read()
        measurements[now] = co2['co2']
        print(measurements[now])
        orderedMeasurements = collections.OrderedDict(
            sorted(measurements.items(), reverse=True)).values()

        minuteAgo = now - timedelta(minutes=1)
        recentMeasurements = {
            k: v
            for k, v in measurements.items() if k > minuteAgo
        }
        minuteAvg = sum(recentMeasurements.values()) / len(
            recentMeasurements.values())
        minuteStd = numpy.std(numpy.array(recentMeasurements.values()), axis=0)
        if lastPressed != oldLastPressed:
            screenOn = not screenOn
        oldLastPressed = lastPressed
        if screenOn:
            device.show()
            with canvas(device) as draw:
                draw.rectangle(device.bounding_box,
                               outline="white",
                               fill="black")
                draw.text((5, 5), (str(co2['co2'])), fill="white")
                draw.text((33, 5), ('avg ' + str(minuteAvg) + "(" +
                                    str(int(round(minuteStd, 0))) + ")"),
                          fill="white")
                draw.line((5, 20, 5, 55), fill="white")
                draw.line((5, 55, 120, 55), fill="white")

                for i, m in enumerate(orderedMeasurements[:115]):
                    height = 55 - m / 29
                    height = max(min(55, height), 20)
                    draw.point(((120 - i), height), fill="white")
        else:
            device.hide()
        time.sleep(10)

    with open('co2.csv', mode='w') as f:
        writer = csv.writer(f)
        for k, v in measurements.items():
            writer.writerow([k, v])
Exemplo n.º 13
0
    def payload(self, __payload):
        try:
            __payload["deviceTime"] = int(time.time())
            if (self.bme680 is not None):
                __payload["sensorType"] = "bme680"
                __payload["voc"] = "{0:.0f}".format(self.bme680.gas)
                __payload["temperature"] = "{0:.1f}".format(
                    self.bme680.temperature)
                __payload["humidity"] = "{0:.0f}".format(self.bme680.humidity)
                __payload["pressure"] = "{0:.0f}".format(self.bme680.pressure)
                __payload["altitude"] = "{0:.0f}".format(self.bme680.altitude)
                t = Temp(self.bme680.temperature, 'c')
                dewPoint = dew_point(temperature=t,
                                     humidity=self.bme680.humidity)
                __payload["dewPoint"] = "{0:.1f}".format(float(dewPoint))
            elif (self.bme280 is not None):
                print("payload for BME280")
                __payload["sensorType"] = "bme280"
                __payload["temperature"] = "{0:.1f}".format(
                    self.bme280.temperature)
                __payload["humidity"] = "{0:.0f}".format(self.bme280.humidity)
                __payload["pressure"] = "{0:.0f}".format(self.bme280.pressure)
                __payload["altitude"] = "{0:.0f}".format(self.bme280.altitude)
                t = Temp(self.bme280.temperature, 'c')
                dewPoint = dew_point(temperature=t,
                                     humidity=self.bme280.humidity)
                __payload["dewPoint"] = "{0:.1f}".format(float(dewPoint))
        except:
            pass

        try:
            if (self.tsl is not None):
                __payload["lux"] = "{0:.0f}".format(self.tsl.lux)
                __payload["infrared"] = "{0:d}".format(self.tsl.infrared)
                __payload["visible"] = "{0:d}".format(self.tsl.visible)
                __payload["full_spectrum"] = "{0:d}".format(
                    self.tsl.full_spectrum)
        except:
            pass

        try:
            drone.noSUDO()
            mhz19b = mh_z19.read()
            if mhz19b is not None:
                __payload["CO2"] = '{0:d}'.format(mhz19b['co2'])
        except:
            pass
Exemplo n.º 14
0
async def main() -> None:
    """
    Main loop
    :return:
    """
    while True:
        print("Loop through sensors")
        mhz19_data = mh_z19.read()
        humidity, temperature = Adafruit_DHT.read_retry(
            CONFIG["ADAFRUIT_SENSOR_TYPE"], CONFIG["ADAFRUIT_SENSOR_PIN"])
        print("Data received, packing")
        data = {
            "co2": mhz19_data["co2"],
            "temperature": temperature,
            "humidity": humidity,
            "time": datetime.datetime.now().timestamp(),
        }
        async with aiosqlite.connect(CONFIG["DB_PATH"]) as database:
            print("Writing to database")
            await database.execute(
                "INSERT INTO main.testimony VALUES (:co2,:temperature,:humidity,:time)",
                data,
            )
            await database.commit()

        try:
            print(data)
            await send_to_socket(data, CONFIG["URL"])
        except aiohttp.client_exceptions.ClientConnectorError:
            print("Socket not reachable")
            send_string = f"""CO2 level - {mhz19_data['co2']}.\
            Temperature - {temperature}.\
            Humidity - {humidity}"""
            print(send_string)
        print("Sleeping for {}".format(CONFIG["FREQUENCY"]))
        await asyncio.sleep(CONFIG["FREQUENCY"])
Exemplo n.º 15
0
 def measure(self):
     data = mh_z19.read(serial_console_untouched=True)
     return data
Exemplo n.º 16
0
	draw.text((180, 10),f"#: {len(rolling_co2_storage)}",(255,255,255),font=font_small)
	#draw.rectangle(((0, 40), (240, 42)), fill="white")

	if isinstance(ping('192.168.1.102'), float):
		draw.rectangle(((205,60), (230,85)), fill="green")
	else:
		draw.rectangle(((205,60), (230,85)), fill="red")

	sensor = Adafruit_DHT.DHT22
	#GPIO.setmode(GPIO.BOARD)
	GPIO.setup(16, GPIO.IN, pull_up_down = GPIO.PUD_UP)
	humidity, temperature = Adafruit_DHT.read_retry(sensor, 16)
	draw.text((0, 220), f"t:{round(temperature, 1)}°C",(255, 255, 255), font=font_small)
	draw.text((80, 220), f"h:{round(humidity, 1)}%", (255, 255, 255), font=font_small) 
	try:
		measurement = mh_z19.read()['co2']
		if measurement == 500 and len(rolling_co2_storage) == 0:
			pass
		else:
			rolling_co2_storage.append(measurement)
		draw.text((0, 46),str(measurement) + " ppm", (255, 255, 255), font=font_big)
		draw.text((180, 220),"serial",(255,255,255),font=font_small)
		#draw.rectangle(((200, 50), (240, 90)), fill=get_color_for_value(measurement))
	except TypeError:
		measurement = mh_z19.read_from_pwm()['co2']
		if measurement == 500 and len(rolling_co2_storage) == 0:
			pass
		else:
			rolling_co2_storage.append(measurement)
		draw.text((0, 46),str(measurement) + " ppm", (255, 255, 255), font=font_big)
		draw.text((180, 220),"pwm",(255,255,255),font=font_small)
Exemplo n.º 17
0
#!/usr/bin/python3

# pip3 install mh-z19
import mh_z19

print(mh_z19.read())
# not working because Bluetooth and serial have a conflict on Raspi3
Exemplo n.º 18
0
import requests

logging.basicConfig(filename='/tmp/venti-sensor2.log', level=logging.DEBUG)

url = 'https://frozen-reef-90562.herokuapp.com/'
#url='https://192.168.46.128:3000'
proxies = {
    'http': 'http://proxy.matsusaka.co.jp:12080',
    'https': 'http://proxy.matsusaka.co.jp:12080'
}
#proxies = {
#    'http': None,
#    'https': None
#}

logging.info("VentiSensor Start.[{}]".format(url))

logging.info("VentiSensor Initialized.")

while True:
    try:
        uploadData = mh_z19.read()
        print(uploadData)
        logging.info(uploadData)
        response = requests.post(url + '/addVentilation2/',
                                 json=uploadData,
                                 proxies=proxies)
    except Exception as e:
        logging.info(e)
    time.sleep(10)
Exemplo n.º 19
0
 def measure_co2(self):
     print("now, getting co2 by mh_z19")
     self.co2 = mh.read()
Exemplo n.º 20
0
from datetime import datetime, timedelta

from luma.core.interface.serial import i2c
from luma.core.render import canvas
from luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106

serial = i2c(port=1, address=0x3C)
device = ssd1306(serial, rotate=0)

measurements = {}

while True:
    for i in range(6):
        now = datetime.now()
        co2 = mh_z19.read()
        measurements[now] = co2['co2']
        orderedMeasurements = collections.OrderedDict(
            sorted(measurements.items(), reverse=True)).values()

        minuteAgo = now - timedelta(minutes=1)
        recentMeasurements = {
            k: v
            for k, v in measurements.items() if k > minuteAgo
        }
        try:
            minuteAvg = sum(recentMeasurements.values()) / len(
                recentMeasurements.values())
            minuteStd = numpy.std(numpy.array(recentMeasurements.values()),
                                  axis=0)
        except:
Exemplo n.º 21
0
    def main(self):

        """
        Configure the logger and record the types of
        sensors that have been detected by the controller.
        """

        self.logger.basicConfig = logging.basicConfig(format=self.format, filename='control.log',
                            level=logging.INFO)

        self.logger.info('SYSTEM ONLINE')
        
        # Initialize the logging string for future use
        logging_str = 'Average retrieved temperature: ' + repr(0.00)

        # Log the types of sensors we have detected in the system
        for sen in self.sensors:
            self.logger.info('Detected %s sensors', str(sen))

        # Calibrate current CO2 to 410ppm
        mh_z19.zero_point_calibration()

        while True:
            # Detect the sensors that are currently connected
            for i in range(0, len(self.sensors)):
                try:
                    self.sensors[i].detect()
                    self.num_sensors[i] = self.sensors[i].num_sensors
                except IOError:
                    self.logger.info('Error detecting %s sensors',
                                     str(self.sensors[i]))

            try:
                # Open the sensor readings file and write current timestamp.
                self.logger.info('Opening sensors file for records')
                self.sensor_readings = codecs.open('sensors.csv', 'a', 'utf-8')
                self.sensor_readings.write(time.strftime("%Y/%m/%d %H:%M:%S",
                                                         time.localtime()))

                # Read sensor data from all types of connected sensors.
                self.logger.info('Reading sensors from Pi')
                total_indoor = 0
                total_readings = ""
                error_flag = 0
                io_flag = 0
                for sen in self.sensors:
                    try:
                        self.indoor, readings = sen.read()
                        total_indoor += self.indoor
                        total_readings += readings
                    except (IOError, ZeroDivisionError):
                        self.logger.info('Error reading a sensor.')
                        error_flag += 1
                        io_flag = 1
                        # Read in error and reboot values for updates
                        self.io_errors = codecs.open('io_error', 'r', 'utf-8')
                        num_errors = int(self.io_errors.read())
                        self.io_errors.close()
                        self.reboots = codecs.open('reboots', 'r', 'utf-8')
                        num_reboots = int(self.reboots.read())
                        self.reboots.close()
                        # If maximum reboots not reached, then reboot
                        if (num_errors >= self.error_max and
                           num_reboots < self.reboot_max):
                            self.logger.info('Maximum I/O errors (%d);' +
                                             ' rebooting.', num_errors)
                            self.io_errors = codecs.open('io_error',
                                                         'w')
                            num_reboots += 1
                            self.io_errors.write('0')
                            self.io_errors.close()
                            self.reboots = codecs.open('reboots', 'w')
                            self.reboots.write((str(num_reboots)))
                            self.reboots.close()
                            self.sensor_readings.close()

                            proc = subprocess.Popen('reboot',
                                                    stdout=subprocess.PIPE,
                                                    shell=True)
                            out, err = proc.communicate()

                        # If maximum reboots reached, stay on
                        elif num_reboots >= self.reboot_max:
                            num_errors += 1
                            self.logger.info('Max reboots (%d) reached;' +
                                             ' I/O error #%d occurred',
                                             num_reboots, num_errors)
                            self.io_errors = codecs.open('io_error',
                                                         'w')
                            self.io_errors.write((str(num_errors)))
                            self.io_errors.close()

                        # If maximums not reached, record the error
                        elif (num_reboots < self.reboot_max and
                              num_errors < self.error_max):
                            num_errors += 1
                            self.logger.info('I/O Error #%d occurred',
                                             num_errors)
                            self.io_errors = codecs.open('io_error',
                                                         'w')
                            self.io_errors.write((str(num_errors)))
                            self.io_errors.close()

                # No I/O error detected this time -> reset counters
                if not io_flag:
                    self.logger.info('No I/O error detected; ' +
                                     'resetting number of errors and reboots')
                    self.io_errors = codecs.open('io_error', 'w')
                    self.io_errors.write('0')
                    self.io_errors.close()
                    self.reboots = codecs.open('reboots', 'w')
                    self.reboots.write('0')
                    self.reboots.close()

                self.logger.info('Detected indoor temp of %.2f',
                                 total_indoor / len(self.sensors))

                # Log the individual readings if we have any sensor data
                if error_flag != len(self.sensors):
                    self.sensor_readings.write(total_readings)

                self.logger.info('Reading CO2 data')
                try:
                    # Read CO2 sensor data and log to file
                    co2_val = mh_z19.read()['co2']
                    fmt_string = "," + str(co2_val) + "ppm"
                    self.logger.info('Logging %d ppm to file', co2_val)
                    self.sensor_readings.write(fmt_string)
                except TypeError:
                    self.logger.info('Unable to read CO2 data')

                # Write a new line for the next reading interval
                self.sensor_readings.write('\n')

                # Close the sensor readings file
                self.sensor_readings.close()

                # Average temperature readings for accuracy
                self.indoor = total_indoor / len(self.sensors)

                # Round to three decimal places
                self.indoor = round(self.indoor, 3)

                self.logger.info('Retrieving outdoor temp from control tent')
                # Retrieve outdoor temp from the control tent and parse it
                out_proc = subprocess.Popen('sudo scp -o ConnectTimeout=10 pi@' +
                                            self.control_ip + self.control_dir,
                                            stdout=subprocess.PIPE,
                                            shell=True)
                out, err = out_proc.communicate()

                try:
                    out_proc.terminate()
                except OSError:
                    pass

                # Open retrieved file, read the line, convert and round.
                outdoor_temps = codecs.open('outdoor', 'r')
                temps = outdoor_temps.read().split(',')
                outdoor_temps.close()
                out_vals = []

                # Initialize the logging string for future use
                # Remove any NULL characters received from the control tent
                # If any occur, remove them and still record that temperature
                for t in temps:
                    try:
                        out_vals.append(float(t))
                    except:
                        valid_parts = []
                        for char in t:
                            if char in string.printable:
                                valid_parts.append(char)
                        if len(valid_parts) > 0:
                            joined = "".join(v for v in valid_parts)
                            out_vals.append(float(joined))
                        
                # Convert the line to a list of floating point values
                out_list = list(map(float, out_vals))
                # Compute the average of the outdoor temperature for comparison
                # If an error occurred in parsing the outdoor, use the previous reading
                if len(out_list) > 0:
                    outdoor = sum(out_list) / len(out_list)
                else:
                    start_point = logging_str.find(':') + 1
                    prev_outdoor = float(logging_str[start_point:])
                    outdoor = prev_outdoor

                self.outdoor = round(outdoor, 3)
                logging_str = 'Average retrieved temperature: ' + repr(self.outdoor)
                self.logger.info(logging_str)

                if self.indoor == 0 and self.outdoor == 0:
                    # both sensors disconnected while running
                    raise RuntimeError

            except RuntimeError as ex:
                # Exception occurred with sensor: notify via GUI
                self.indoor = 90
                self.outdoor = 90
                self.heater = "SENSOR"

                # Record exception information
                self.logger.info('%s', repr(sys.exc_info()))
                print((str(ex)))

            # If indoor temperature is below differential then
            # engage Stage 2 since the purge period and Stage 1
            # won't be enough to maintain our differential
            if (self.indoor - self.outdoor < self.temperature_diff and
               self.indoor != 90 and self.outdoor != 90):
                self.heater = "ST2"
                GPIO.output(self.signal_pin, GPIO.HIGH)
                GPIO.output(self.stage_one_pin, GPIO.HIGH)
                GPIO.output(self.stage_two_pin, GPIO.HIGH)

            else:
                # Indoors >= outdoors -- turn off heater.
                if (self.indoor != 90 and self.outdoor != 90):
                    self.heater = "OFF"
                    GPIO.output(self.signal_pin, GPIO.LOW)
                    GPIO.output(self.stage_one_pin, GPIO.LOW)
                    GPIO.output(self.stage_two_pin, GPIO.LOW)

            self.logger.info('%.2f inside, %.2f outside, heater %s',
                             self.indoor, self.outdoor, self.heater)

            # Sleep system until the next check cycle.
            time.sleep(self.check_interval)
Exemplo n.º 22
0
 def co2Concentration(self):
     r = mh_z19.read()
     if r is not None and 'co2' in r.keys():
         return str(r['co2'])
     return None
Exemplo n.º 23
0
#!/usr/bin/env python3
import mh_z19
from influxdb import InfluxDBClient

homestats = InfluxDBClient(host='raspberrypi4bserver.local',
                           database='homestats')

points = [{
    'measurement': 'sensor',
    'tags': {
        'location': 'myRoom'
    },
    'fields': {
        'co2': mh_z19.read()['co2']
    }
}]
homestats.write_points(points)
Exemplo n.º 24
0
def getco2():
    out = mh_z19.read()
    V = getValue(str(out))
    return V
Exemplo n.º 25
0
def measure_data(sensor, pin):
    humidity, temperature = Adafruit_DHT.read(sensor, pin)
    co2 = mh_z19.read()["co2"]
    time = datetime.datetime.now()
    return {"humidity": humidity, "temperature": temperature, "co2": co2, "time": time}
Exemplo n.º 26
0
import mh_z19
co2=mh_z19.read()
print(mh_z19.read())
print(co2);
Exemplo n.º 27
0
    def start(self):
        print('## Sensing is Running ##')
        now_minute = datetime.datetime.now().minute
        start_minute = 0

        if now_minute < 30:
            start_minute = 30
        else:
            start_minute = 0

        while True:

            try:
                co2_value = co2.read()['co2']
                co_value = co.read()
                pm_values = pm.read()

                if self.fan_controller.is_auto_mode():
                    if self.fan_controller.is_on():
                        print('fan is on')
                        if shared_data.datas.co2_safe >= co2_value \
                        and shared_data.datas.co_safe >= co_value \
                        and shared_data.datas.pm25_safe >= pm_values['pm2.5'] \
                        and shared_data.datas.pm10_safe >= pm_values['pm10']:
                            print('@ try off')
                            self.fan_controller.off()
                            pass
                        pass

                    else:  # is off
                        print('fan is off')
                        if shared_data.datas.co2_limit <= co2_value \
                        or shared_data.datas.co_limit <= co_value \
                        or shared_data.datas.pm25_limit <= pm_values['pm2.5'] \
                        or shared_data.datas.pm10_limit <= pm_values['pm10']:
                            self.fan_controller.on()
                            pass
                        pass

                if self.fan_controller.is_auto_mode():
                    print('is auto mode')
                else:
                    print('is not auto mode')

                #test begin
                print('co2: {}'.format(co2_value))
                print('co: {}'.format(co_value))
                #print('pm1.0: {}'.format(pm_values['pm1.0']))
                print('pm2.5: {}'.format(pm_values['pm2.5']))
                print('pm10: {}'.format(pm_values['pm10']))
                print('')
                #test end

                shared_data.datas.set_sensing(pm_values['pm1.0'],
                                              pm_values['pm2.5'], co_value,
                                              co2_value)

                now_minute = datetime.datetime.now().minute
                if start_minute == now_minute:
                    if start_minute == 0:
                        start_minute = 30
                        pass
                    else:
                        start_minute = 0
                        pass

                    self.db_controller.insert_sensing \
                      (pm10=pm_values['pm10'], \
                       pm25=pm_values['pm2.5'], \
                       co=co_value, co2=co2_value, log='')
                    pass

            except:
                pass
Exemplo n.º 28
0
import mh_z19
import time
import paho.mqtt.client as mqtt

while __name__ == '__main__':
    value = mh_z19.read()
    client = mqtt.Client()
    client.username_pw_set(username="******", password="******")
    client.connect("mqtt_ip", 1883, 60)
    client.publish("home/livingroom/co2", value["co2"])
    time.sleep(60)
Exemplo n.º 29
0
                print("fine dust read success", flush=True)
                dust.save_data(buffer)
                dust_read_succeed = 1
                dust_fail_count = 0

                #print ("PM 2.5 : %s" % pm25_data, flush = True)
                #print ("PM 10.0 : %s" % pm10_data, flush = True)

            else:
                dust_read_succeed = 0
                dust_fail_count += 1
                print("finedust read fail", flush=True)

            #==============co2 sensor=====
            try:
                co2_data = mh_z19.read()['co2']
                print("co2 read success")
                #print("co2: ",co2_data)
                co2_read_succeed = 1
                co2_fail_count = 0

            except:
                print("co2 read fail")
                co2_read_succeed = 0
                co2_fail_count += 1

            #moving average filter
            pm25_datas.append(pm25_data)
            dust_pm25_mean = round(mean(pm25_datas))
            print("pm 2.5 average: ", dust_pm25_mean)
            dust_pm25_mean_list.append(dust_pm25_mean)
    def main(self):
        """
        Configure the logger and record the types of
        sensors that have been detected by the controller.
        """

        self.logger.basicConfig = logging.basicConfig(format=self.format,
                                                      filename='control.log',
                                                      level=logging.INFO)

        self.logger.info('SYSTEM ONLINE')

        # Log the types of sensors we have detected in the system
        for sen in self.sensors:
            self.logger.info('Detected %s sensors', str(sen))

        # Calibrate current CO2 to 410 ppm
        mh_z19.zero_point_calibration()

        while True:
            # Detect the sensors that are currently connected
            for i in range(0, len(self.sensors)):
                try:
                    self.sensors[i].detect()
                    self.num_sensors[i] = self.sensors[i].num_sensors
                except IOError:
                    self.logger.info('Error detecting %s sensors',
                                     str(self.sensors[i]))

            try:
                # Open the sensor readings file and write current timestamp.
                self.logger.info('Opening sensors file for records')
                self.sensor_readings = codecs.open('sensors.csv', 'a', 'utf-8')
                self.sensor_readings.write(
                    time.strftime("%Y/%m/%d %H:%M:%S", time.localtime()))

                # Read sensor data from all types of connected sensors.
                self.logger.info('Reading sensors from Pi')
                total_indoor = 0
                total_readings = ""
                error_flag = 0
                io_flag = 0
                for sen in self.sensors:
                    try:
                        self.indoor, readings = sen.read()
                        total_indoor += self.indoor
                        total_readings += readings
                    except (IOError, ZeroDivisionError):
                        self.logger.info('Error reading a sensor.')
                        error_flag += 1
                        io_flag = 1
                        # Read in error and reboot values for updates
                        self.io_errors = codecs.open('io_error', 'r', 'utf-8')
                        num_errors = int(self.io_errors.read())
                        self.io_errors.close()
                        self.reboots = codecs.open('reboots', 'r', 'utf-8')
                        num_reboots = int(self.reboots.read())
                        self.reboots.close()
                        # If maximum reboots not reached, then reboot
                        if (num_errors >= self.error_max
                                and num_reboots < self.reboot_max):
                            self.logger.info(
                                'Maximum I/O errors (%d);' + ' rebooting.',
                                num_errors)
                            self.io_errors = codecs.open('io_error', 'w')
                            num_reboots += 1
                            self.io_errors.write('0')
                            self.io_errors.close()
                            self.reboots = codecs.open('reboots', 'w')
                            self.reboots.write((str(num_reboots)))
                            self.reboots.close()
                            self.sensor_readings.close()
                            proc = subprocess.Popen('reboot',
                                                    stdout=subprocess.PIPE,
                                                    shell=True)
                            out, err = proc.communicate()

                        # If maximum reboots reached, stay on
                        elif num_reboots == self.reboot_max:
                            num_errors += 1
                            self.logger.info(
                                'Max reboots (%d) reached;' +
                                ' I/O error #%d occurred', num_reboots,
                                num_errors)
                            self.io_errors = codecs.open('io_error', 'w')
                            self.io_errors.write((str(num_errors)))
                            self.io_errors.close()

                        # If maximums not reached, record the error
                        elif (num_reboots < self.reboot_max
                              and num_errors < self.error_max):
                            num_errors += 1
                            self.logger.info('I/O Error #%d occurred',
                                             num_errors)
                            self.io_errors = codecs.open('io_error', 'w')
                            self.io_errors.write((str(num_errors)))
                            self.io_errors.close()

                # No I/O error detected this time -> reset counters
                if not io_flag:
                    self.logger.info('No I/O error detected; ' +
                                     'resetting number of errors and reboots')
                    self.io_errors = codecs.open('io_error', 'w')
                    self.io_errors.write('0')
                    self.io_errors.close()
                    self.reboots = codecs.open('reboots', 'w')
                    self.reboots.write('0')
                    self.reboots.close()

                    self.logger.info('Detected indoor temp of %.2f',
                                     total_indoor / len(self.sensors))

                # Log the individual readings if we have any sensor data
                if error_flag != len(self.sensors):
                    self.sensor_readings.write(total_readings)

                self.logger.info('Reading CO2 data')
                try:
                    # Read CO2 sensor data and log to file
                    co2_val = mh_z19.read()['co2']
                    fmt_string = "," + str(co2_val) + "ppm"
                    self.logger.info('Logging %d ppm to file', co2_val)
                    self.sensor_readings.write(fmt_string)
                except TypeError:
                    self.logger.info('Unable to read CO2 data')

                # Write a new line for the next reading interval
                self.sensor_readings.write('\n')

                # Close the sensor readings file
                self.sensor_readings.close()

                # Average temperature readings for accuracy
                self.indoor = total_indoor / len(self.sensors)

                # Round to three decimal places
                self.indoor = round(self.indoor, 3)

                if self.indoor == 0:
                    # sensors disconnected while running
                    raise RuntimeError

            except RuntimeError as ex:
                # Exception occurred with sensors
                self.indoor = 90
                self.heater = "SENSOR"

                # Record exception information
                self.logger.info('%s', repr(sys.exc_info()))
                print((str(ex)))

            # Immediately record outdoor temperature to file for control
            self.logger.info('Control: %d outside', self.indoor)

            self.logger.info('Recording temperature data to tent file %s',
                             self.data_file)

            # Remove non-printable characters (NULL, etc) and first comma
            outdoor_record = "".join(temp for temp in total_readings[1:]
                                     if temp in string.printable)
            if self.indoor != 90:
                self.output_file = codecs.open(self.data_file, 'w', 'utf-8')
                self.output_file.write(outdoor_record)
                self.output_file.close()
            else:
                self.logger.info('Cannot read sensors. No temperature data.')

            time.sleep(self.check_interval)