示例#1
0
文件: app.py 项目: cbron/co2-metrics
def grab_data():
    mon = co2.CO2monitor()
    data = mon.read_data()  # 0 is time, 1 is co2, 2 is temp
    return {
        "co2": data[1],
        "temp": round(9 / 5 * data[2] + 32, 2),
    }
示例#2
0
 def _read(self):
     dt, co2_ppm, temp = self._co2.read_data()
     if co2_ppm is None and temp is None:
         self._bypass_decrypt = not self._bypass_decrypt
         logger.warning(
             f'Fallback to read with bypass_decrypt={self._bypass_decrypt}',
         )
         self._co2 = co2.CO2monitor(bypass_decrypt=self._bypass_decrypt)
         dt, co2_ppm, temp = self._co2.read_data()
     return dt, co2_ppm, temp
示例#3
0
    def __init__(self, mon=None, freq=FREQUENCY, monitoring=True, **kwargs):
        """ Initialize sensor:
              - call parent __init__
              - save references to characteristics
              - (optional) set up callbacks

            If monitor object is not passed, it will be created.
            freq defines interval in seconds between updating the values.
        """
        if not monitoring and mon is None:
            raise ValueError('For monitoring=False monitor object should be passed')
        self.monitor = co2.CO2monitor() if mon is None else mon
        self.frequency = freq
        self.monitoring = monitoring
        super(CO2Accessory, self).__init__(NAME, **kwargs)
示例#4
0
    def __init__(
        self,
        reconnection_interval: int = 10,
        loop: Optional[asyncio.AbstractEventLoop] = None,
    ) -> None:
        self._reconnection_interval = reconnection_interval
        self._loop = loop or asyncio.get_event_loop()
        self._client = aio_mqtt.Client(loop=self._loop)
        self._tasks = []

        self._bypass_decrypt = False
        self._co2 = co2.CO2monitor(bypass_decrypt=self._bypass_decrypt)
        self.device_name = \
            f'{self._co2.info["product_name"]}_' \
            f'{self._co2.info["serial_no"].replace(".", "_")}'

        self.mqtt_prefix = f'homeassistant/sensor/{self.device_name}'
示例#5
0
def read_co2_data():
    """ A small hack to read co2 data from monitor in order to account for case
        when monitor is not initialized yet
    """
    global mon
    if mon is None:
        # Try to initialize
        try:
            mon = co2.CO2monitor()
            # Sleep. If we read from device before it is calibrated, we'll
            # get wrong values
            time.sleep(_INIT_TIME)
        except OSError:
            return None
    try:
        return mon.read_data_raw(max_requests=1000)
    except OSError:
        # We kill the link and will require to initialize monitor again next time
        mon = None
        return None
示例#6
0
import datetime
import co2meter as co2
from influxdb import InfluxDBClient
import influxdb.exceptions as inexc

####################################################################################################
# Sensor Definition
####################################################################################################

sample_time = 30  # seconds

####################################################################################################
# Set up co2monitor
####################################################################################################

mon = co2.CO2monitor()

####################################################################################################
# Initialize connection to influxdb
####################################################################################################

# if influxdb server is up and accessible
# TDB: test connection

client = InfluxDBClient(host='localhost',
                        port=8086,
                        username='******',
                        password='******',
                        database='homeclimate')

####################################################################################################
示例#7
0
文件: co2.py 项目: nozma/home_logging
def get_co2():
  return(co2.CO2monitor().read_data())
示例#8
0
    ax_c.set_ylabel(r"($\circ\rm{C}$)")

    plt.tight_layout()

    if not os.path.isdir("webapp/static"):
        os.mkdir("webapp/static")
    fig.savefig("webapp/static/co2.png", dpi=100)
    plt.close()


if __name__ == "__main__":
    import co2meter

    while True:
        tb = time.time()
        mon = co2meter.CO2monitor()
        now = pandas.Timestamp.now()
        output_filename = "{}-{}-{}.csv".format(now.year, now.month, now.day)
        if not os.path.exists(output_filename):
            with open(output_filename, "w") as f:
                f.write("Time,Concentration,Temperature\n")
        data = mon.read_data()
        t = time.mktime(data.index[0].timetuple())
        row = t, np.float64(data["co2"]), np.float64(data["temp"])
        print("{}, {} PPM, {} °C".format(*row))
        with open(output_filename, "a") as f:
            writer = csv.writer(f)
            writer.writerow(row)
        make_plot()
        tsleep = 60 - (time.time() - tb)
        if tsleep > 0:
示例#9
0
def get_instance():
    return co2.CO2monitor()