def standalone():
    db = Session()
    while True:
        try:
            log.info("Opening serial port")
            ser = serial.Serial('/dev/ttyACM0', 115200, timeout=10)
            log.info("Serial port open")

            while True:
                line = ser.readline()
                if line:
                    (node_id, seq_no, reading_type, reading,
                     checksum_sent, checksum_calc) = line.split(" ")
                    r = Reading()
                    r.node_id = int(node_id)
                    r.seq_no = int(seq_no)
                    r.reading_type = reading_type
                    r.reading = float(reading)
                    r.checksum_sent = int(checksum_sent, 16)
                    r.checksum_calc = int(checksum_calc, 16)
                    db.add(r)
                    db.commit();
                    log.info("Read line: %r", line)
        except Exception:
            log.exception("Exception")
            time.sleep(20)
def standalone():
    db = Session()
    while True:
        try:
            log.info("Opening serial port")
            serial = pyserial.Serial('COM3', 115200, timeout=10) #/dev/ttyACM0
            log.info("Serial port open")

            while True:
                line = str(serial.readline(), 'ascii')
                if line:
                    (node_id, seq_no, reading_type, temperature,
                     checksum_sent, checksum_calc) = line.split(" ")
                    reading = Reading()
                    reading.node_id = int(node_id)
                    reading.seq_no = int(seq_no)
                    reading.reading_type = reading_type
                    reading.reading = float(temperature)
                    reading.checksum_sent = int(checksum_sent, 16)
                    reading.checksum_calc = int(checksum_calc, 16)
                    db.add(reading)
                    db.commit()
                    log.info("Read line: %r", line)         
                    
                    setpoint = db.query(Setpoint).filter(Setpoint.zone_id == reading.node_id).order_by(desc(Setpoint.created_at)).first()
                    if setpoint is not None:
                        log.info("actual temp %s desired temp %s" % (reading.reading, setpoint.temperature))
                        if setpoint.temperature > reading.reading:
                            serial.write(struct.pack('!B', (reading.node_id << 1))) # flip that zone to on
                            log.info("opening zone %s" % reading.node_id)
                        else:
                            serial.write(struct.pack('!B', (reading.node_id << 1) + 1)) # flip that zone to off
                            log.info("closing zone %s" % reading.node_id)


        except Exception:
            log.exception("Exception")
            time.sleep(20)