示例#1
0
def warmup():
    print("mh-z19 sensor warmup started.")
    # read for 60seconds in 10s intervals
    for i in range(6):
        mh_z19.read_all()
        time.sleep(10)
    print("mh-z19 sensor warmup complete!")
示例#2
0
def main():
    print("Starting sensoring")
    if not os.getenv("NOWARMUP"):
        warmup()
    setup_mqtt()

    # define SIGTERM handler to close the connection gracefully when we get closed with C-c or systemctl stop co2
    signal.signal(signal.SIGTERM, handle_exit)

    while True:
        rs = mh_z19.read_all()
        ts = int(time.time())  # unix gmt timestamp
        mc.publish("hpi/bptf/co2",
                   str({
                       "type": "carbon",
                       "ts": ts,
                       "value": rs["co2"]
                   }), 1, True)
        mc.publish(
            "hpi/bptf/temp",
            str({
                "type": "temperature",
                "ts": ts,
                "value": rs["temperature"]
            }), 1, True)
        time.sleep(10)
示例#3
0
def read_monitor():
    """
    Uses co2monitor to read the current temperature and co2 level. The results are formated such
    that influxdb understands data.
    """

    try:
        time        = datetime.datetime.utcnow().isoformat()
        read        = mh_z19.read_all()
        co2         = read['co2']
        temperature = read['temperature']
        SS          = read['SS']
        TT          = read['TT']
        UhUl        = read['UhUl']
    except Exception:
        print(datetime.datetime.now(), "  Error reading co2 monitor. Passing dummy data.")
        time        = datetime.datetime.utcnow().isoformat()
        co2         = None
        temperature = None
        SS          = None
        TT          = None
        UhUl        = None

    data = [{'measurement': 'live logging',
             'tags': {'room': 'bed room', 'sensor': 'MH-Z19 CO2'},
             'time': time,
             'fields': {'co2': co2, 'temperature2': temperature, 'TT': TT, 'SS': SS, 'UhUl': UhUl}
            }]

    return data
示例#4
0
def fetch(now_str: str) -> str:
    data: Dict[str, int] = mh_z19.read_all()
    co2 = data.get("co2")
    if co2 is not None:
        need_notify = check_border(co2)
        if need_notify:
            notify(co2)
    return json.dumps({now_str: data})
示例#5
0
def get_sensor_data():

    for t in range(SAMPLING_ITI):
        data = mh_z19.read_all()
        time.sleep(2)

    logging.debug("Co2 Data: " + str(data))
    if data and data["co2"] and data["temperature"]:
        return data
    return None
示例#6
0
    def on_get(self, req, resp):
        # Pass serial_console_untouched as per instructions for running as non-root
        # as the library expects to be running on native raspberry pi and have access to systemctl.
        # See https://github.com/UedaTakeyuki/mh-z19/wiki/How-to-use-without-root-permission.
        # Note that not all of the info there is relevant, it's not describing how to run in docker!
        co2Sensor = mh_z19.read_all(True)

        sensors = {"co2": co2Sensor["co2"], "tempC": co2Sensor["temperature"]}

        resp.media = sensors
示例#7
0
def main():
    global mh_z19_latest_reading, last_change, last_ppm, current_ip
    while True:
        mh_z19_latest_reading = mh_z19.read_all()
        current_ip = subprocess.check_output("hostname -I | cut -d\' \' -f1",
                                             shell=True).decode("utf-8")
        current_ppm = mh_z19_latest_reading["co2"]
        if current_ppm != last_ppm:
            last_ppm = current_ppm
            last_change = time.time()
        time.sleep(0.1)
示例#8
0
    def run(self):

        if dev:
            self.row_data = {'temp': 21, 'co2': 1972}

        else:

            self.row_data = mh_z19.read_all()
            if self.row_data["co2"] == None:
                self.row_data["co2"] = getPwm()
                self.row_data["temperature"] = None
示例#9
0
def read_all():
    co2 = tem = hu = -1

    try:
        data = mh_z19.read_all()
        co2 = data["co2"]
        tem = data["temperature"]
        hu = data["TT"]
    except:
        pass

    return co2, tem, hu
def interval(prev_data: dict) -> (bool, dict):
    cur_data = mh_z19.read_all()
    if (cur_data == prev_data):
        return (False, cur_data)
    if (cur_data.get('co2') == prev_data.get('co2')):  # use only co2
        return (False, cur_data)

    try:
        post_value(cur_data)
    except Exception as ex:
        put_log(ex, True)

    return (True, cur_data)
示例#11
0
	def sense(self):
		val = {'co2': -1, 'temperature': -1}
		try:
			val = mh_z19.read_all()
			# check that both values we care about are there
			print(val)
			val['co2']
			val['temperature']
		except Exception as e:
			print("Could not read sensor", e)
			val = {'co2': -1, 'temperature': -1}
		print("Sensor: ", val)
		return val
    def log_co2(self) -> typ.Tuple[int, float]:
        """CO2を記録する.

        Returns:
            CO2濃度, 気温
        """
        d: typ.Dict = mh_z19.read_all(serial_console_untouched=True)
        self.sk.debug_print(f"MH_Z19: {d}")
        if "co2" in d:
            store: db_store.DBStore = db_store.DBStore(self.db_url)
            store.co2_log(d["co2"], d["temperature"], d["UhUl"], d["SS"])
            del store
            self.add_zabbix("co2", d["co2"])
            return (d["co2"], d["temperature"])
        return (0, 0)
示例#13
0
    def read(self):
        """
            Purpose: Read CO2 value from the sensor
            Inputs:  None
            Outputs: Return the CO2 value
        """

        try:

            self.Co2 = mh_z19.read_all()['co2']

        except:

            self.Co2 = 0
            pass

        return self.Co2
示例#14
0
文件: check_co2.py 项目: ferag/locco2
def main():
    while (True):
        try:
            output = mh_z19.read_all()
            co2 = int(output['co2'])
            temp = output['temperature']
            print("CO2: %s | Temp: %s" % (co2, temp))
            if (co2 < 400):
                whiteOff()
                time.sleep(0.3)
                blueOn()
            elif (co2 >= 400 and co2 < 700):
                whiteOff()
                time.sleep(0.3)
                cyanOn()
            elif (co2 >= 700 and co2 < 850):
                whiteOff()
                time.sleep(0.3)
                greenOn()
            elif (co2 >= 850 and co2 < 1500):
                whiteOff()
                time.sleep(0.3)
                yellowOn()
            elif (co2 >= 1500 and co2 < 1750):
                whiteOff()
                time.sleep(0.3)
                magentaOn()
            elif (co2 >= 1750 and co2 < 5500):
                whiteOff()
                time.sleep(0.3)
                redOn()
            ts = time.time()
            timestamp = datetime.datetime.fromtimestamp(ts).strftime(
                '%Y-%m-%d %H:%M:%S')
            insert_values(timestamp, co2, temp)
        except Exception as e:
            print("Exception: %s" % e)
        try:
            update_local()
        except Exception as e:
            print("Exception: %s" % e)
        time.sleep(60)
示例#15
0
	finally:
		x.close()
		conn.close()
	
mh_z19.abc_on()

DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 21


while True:
    sensorMS5611.read()
    tempC = sensorMS5611.getTempC()
    press = sensorMS5611.getPressureAdj()*0.75006375541921
    
    mhz19 = mh_z19.read_all()
    temp = read_temp()
    

    #--------humid----------
    am2302_humid, am2302_temp = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
    #--------arduino sensors-----------
   
    bytesToRead = ser.inWaiting()
    ard_data_str = ser.read(bytesToRead)

    ard_data_ar = ard_data_str.split('\r\n')
    
    mq_values = ard_data_ar[len(ard_data_ar)-1].split(' ')
	 #--------arduino sensors-----------
    
示例#16
0
from google.cloud import bigquery
import datetime
import json
import mh_z19
import slackweb

project = "urusy-1"
dataset = "co2"
table = "mh_z19"

CO2_THRESHOLD = 900

sensor_data = mh_z19.read_all()

bigquery_client = bigquery.Client()

query = "INSERT INTO `{0}.{1}.{2}` VALUES (TIMESTAMP('{3}'), {4}, {5}, {6}, {7}, {8})".format(
    project, dataset, table, datetime.datetime.now(datetime.timezone.utc),
    sensor_data["co2"], sensor_data["temperature"], sensor_data["TT"],
    sensor_data["SS"], sensor_data["UhUl"])

rows = bigquery_client.query(query).result()

# if over threshold co2 notification to slack
co2 = sensor_data["co2"]

with open('config.json', 'r') as config:
    json_dict = json.load(config)
    latest_file_name = json_dict['files']['latest']
    slack_url = json_dict['slack']['url']
示例#17
0
    service_id=uuid,
    service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
    profiles=[bluetooth.SERIAL_PORT_PROFILE],
    # protocols=[bluetooth.OBEX_UUID]
)

print("Waiting for connection on RFCOMM channel", port)

client_sock, client_info = server_sock.accept()
print("Accepted connection from", client_info)

try:
    while True:
        log = open('log.txt', 'a+')
        for i in range(0, 5):
            mh_z19.read_all()
            time.sleep(0.5)
            reading = mh_z19.read_all()
            timestamp = time.localtime()
            # log.write(str(timestamp.tm_hour) + '.' + str(timestamp.tm_min) + ": " + str(reading) + '\n')
            time.sleep(1)
            client_sock.send(str(reading['co2']))
            #data = client_sock.recv(1024)
        log.close()
except OSError:
    pass

print("Disconnected.")

client_sock.close()
server_sock.close()
示例#18
0
font = ImageFont.truetype('VCR_OSD_MONO_1.001.ttf', 16)
draw.text((x, top + 47), "    loading...", font=font, fill=255)

# Display image.
disp.image(image)
disp.display()

font = ImageFont.truetype('VCR_OSD_MONO_1.001.ttf', 15)

while True:

    # Get Sensor Data
    humidity, temperature = tempsensor.read_retry(DHT_SENSOR, DHT_PIN)

    sample = mh_z19.read_all()
    Co2 = sample['co2']

    # Draw a black filled box to clear the image.
    draw.rectangle((0, 0, width, height), outline=0, fill=0)

    # Write text.
    if humidity is not None and temperature is not None:

        draw.text((x, top + 0),
                  "Co2 : " + str(Co2).rjust(4, ' ') + " PPM",
                  font=font,
                  fill=255)
        draw.text((x, top + 16),
                  "TEM : " + "{:.1f}".format(temperature) + " C",
                  font=font,
示例#19
0
def sample_mh_z19():
    sample = mh_z19.read_all()
    return sample['co2'], sample['temperature']
示例#20
0
def sample_mh_z19():
    sample = mh_z19.read_all()
    return sample['co2']
示例#21
0
文件: co2.py 项目: shurik2533/growbox
 def get_data():
     return mh_z19.read_all()
示例#22
0
# Draw a black filled box to clear the image.
draw.rectangle((0, 0, width, height), outline=0, fill=0)

# Draw some shapes.
# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height - padding
# Move left to right keeping track of the current x position for drawing shapes.
x = 0

# Load nice silkscreen font
font = ImageFont.truetype('/home/pi/slkscr.ttf', 8)

app = Flask(__name__)
mh_z19_latest_reading = mh_z19.read_all()
last_change = time.time()
last_ppm = 0
current_ip = subprocess.check_output("hostname -I | cut -d\' \' -f1",
                                     shell=True).decode("utf-8")

display_off_on_wifi = False

effects = [
    (0, "Normal background concentration in outdoor ambient air"),
    (350,
     "Concentrations typical of occupied indoor spaces with good air exchange"
     ),
    (1000, "Complaints of drowsiness and poor air."),
    (2000,
     "Headaches, sleepiness and stagnant, stale, stuffy air. Poor concentration, loss of attention, increased heart rate and slight nausea may also be present."
def interval() -> None:
    cur_data = mh_z19.read_all()
    try:
        post_value(cur_data)
    except Exception as ex:
        put_log(ex, True)
示例#24
0
def main():
  lumi_sensor = utils.LuminositySensor()
  cpu_temp = CPUTemperature()
  load_average = LoadAverage()
  
  cache = []
  
  last_luminosity = -1
  last_co2 = -1
  update_frequency = 30 # in s
  
  while True:
    with open ("config.json", "r") as f:
        config = json.loads(f.read())
  
    ping_router = PingServer(config["MQTT_SERVER"])
    online = ping_router.value
  
    luminosity = lumi_sensor.get_luminosity(keep_open=update_frequency < 31)
  
    sensor_values = mh_z19.read_all(True)
    sensor_values["time"] = datetime.now().astimezone().isoformat()
    sensor_values["online"] = online
    sensor_values["luminosity"] = luminosity
    sensor_values["cpu_temperature"] =  cpu_temp.temperature
    sensor_values["cpu_load_percent"] = load_average.load_average * 100
    sensor_values["mem_percent"] = psutil.virtual_memory().percent
  
    #print(sensor_values)
   
    # MQTT publish
    if online:
        try:
          publish.single(config["MQTT_PATH"], json.dumps(sensor_values), hostname=config["MQTT_SERVER"])
        except Exception as e:
            print(e)
            sensor_values["exception"] = str(e)
            online = False
  
    # if not online, write to cache
    if not online:
        cache += [sensor_values]
    if len(cache) > 59 or (online and len(cache) > 0):
      with open (f"""cache/sensors-{datetime.now().strftime("%Y%m%d-%H%M%S")}.json""", "w") as f:
        f.write(json.dumps(cache))
      cache = []
  
    # change off/online depending on luminosity
    if luminosity < config["DISABLE_WIFI_LUMINOSITY"]:
        if online:
            utils.disable_wifi()
        online = False
    else:
        if not online:
            utils.activate_wifi()
            for i in range(30):
                online = ping_router.value
                if not online:
                    time.sleep(1)
                    continue
                break
  
    if online:
        utils.turn_led_on()
        utils.upload_cache()
    else:
        utils.turn_led_off()
  
    delta_luminosity = luminosity - last_luminosity
    last_luminosity = luminosity
    delta_co2 = sensor_values["co2"] - last_co2 
    last_co2 = sensor_values["co2"]
  
    if abs(delta_luminosity) > 0.01 or abs(delta_co2) > 10:
        update_frequency = 30
    else:
        if luminosity > 0.1:
            update_frequency = 60
        else:
            update_frequency = 60 * 5

  
    utils.wait_for_next_run(seconds=update_frequency)
示例#25
0
font = ImageFont.truetype('VCR_OSD_MONO_1.001.ttf', 16)
draw.text((x, top + 47), "    loading...", font=font, fill=255)

# Display image.
disp.image(image)
disp.display()

font = ImageFont.truetype('VCR_OSD_MONO_1.001.ttf', 15)

try:
    while True:

        # Get Sensor Data

        humidity, temperature = tempsensor.read_retry(DHT_SENSOR, DHT_PIN)
        Co2 = mh_z19.read_all()['co2']

        # Draw a black filled box to clear the image.
        draw.rectangle((0, 0, width, height), outline=0, fill=0)

        # Write text.
        if humidity is not None and temperature is not None:

            draw.text((x, top + 0),
                      "Co2 : " + str(Co2).rjust(4, ' ') + " PPM",
                      font=font,
                      fill=255)
            draw.text((x, top + 16),
                      "TEM : " + "{:.1f}".format(temperature) + " C",
                      font=font,
                      fill=255)
示例#26
0
        json.dumps(payload), 1, True)

if detection_range == 5000:
    mh_z19.detection_range_5000(serial_console_untouched=True)
elif detection_range == 10000:
    mh_z19.detection_range_10000(serial_console_untouched=True)
elif detection_range == 2000:
    mh_z19.detection_range_2000(serial_console_untouched=True)
else:
    # Unknown detection range, setting to 5000
    mh_z19.detection_range_5000(serial_console_untouched=True)

# Sensor data retrieval and publication
while True:
    print_line('Retrieving data from MH-Z19 sensor...')
    data = mh_z19.read_all(serial_console_untouched=True)
    if len(data) == 0:
        print_line('Unable to get data form sensor.',
                   error=True,
                   sd_notify=True)
        print()
        continue
    else:
        print_line('Result: {}'.format(json.dumps(data)))
        if reporting_mode == 'homeassistant-mqtt':
            print_line('Publishing to MQTT topic "{}/sensor/{}/state"'.format(
                base_topic, sensor_name).lower())
            mqtt_client.publish(
                '{}/sensor/{}/state'.format(base_topic, sensor_name).lower(),
                json.dumps(data))
            sleep(
示例#27
0
def get_sensor_data():
    if model_loaded:
        return mh_z19.read_all()
    else:
        return {'co2': 561, 'temperature': 22.1}
示例#28
0
def getCO2():
    # root authority required
    dat = mh_z19.read_all()
    return dat['co2'], dat['temperature']