Пример #1
0
def main():
    global log

    try:
        try:
            opts, args = getopt.getopt(sys.argv[1:], 'cdf:s:o:', [])
        except getopt.GetoptError:
            usage()
            sys.exit(2)

        try:
            # timeout=0 causes it to raise AlreadyLocked. Any timeout >0
            # causes LockTimeout
            global_lock.acquire(timeout=0)
        except lockfile.AlreadyLocked:
            log.error('Another copy of this program is running')
            sys.exit(1)

        atexit.register(cleanup)

        console = False
        debug_mode = False
        port = SERIAL_PORT;
        cfg_fname = CFG_FILE
        data_fname = DATA_FILE
        
        for o, a in opts:
            if o in ['-s']:
                port = a
            elif o in ['-f']:
                cfg_fname = a
            elif o in ['-o']:
                data_fname = a
            elif o in ['-c']:
                console = True
            elif o in ['-d']:
                debug_mode = True
            else:
                usage()
                sys.exit(1)

        log_format = '%(asctime)s %(process)d %(filename)s:%(lineno)d %(levelname)s %(message)s'
        if debug_mode:
            log_level=logging.DEBUG
        else:
            log_level=logging.INFO
        if console:
            logging.basicConfig(level=log_level, format=log_format)
        else:
            logging.basicConfig(level=log_level, format=log_format,
                                filename=MAIN_LOGFILE, filemode='a')
        log = logging.getLogger('default')

        try:
            cfg = read_config(cfg_fname)
        except Exception, ex:
            log.error("Error reading config file %s" % ex)
            sys.exit(1)

        log.info('Using serial port %s' % port)

        s = serial.serialposix.Serial(port=port,
                                      baudrate=9600, bytesize=8, parity='N', stopbits=1,
                                      timeout=120,
                                      rtscts=1)

        log.info("Starting collection")

        data_file = file(data_fname, 'a')

        pkt_reader = xbee_api.read_packet(s)
        while True:
            pkt = pkt_reader.next()

            try:

                sensor_address = str(pkt.address)
                try:
                    scfg = cfg[sensor_address]
                    vref = scfg["vref"]
                    battery_k = scfg["vccK"]
                except KeyError:
                    log.warning("No config for sensor '%s'. Using defaults" % sensor_address)
                    vref = VREF
                    battery_k = BATTERY_K
                    
                radc0 = pkt.get_adc(0)
                radc1 = pkt.get_adc(1)
                adc0 = float(get_adc_v(pkt,0,vref))
                adc1 = float(get_adc_v(pkt,1,vref))
                battery_V = get_battery_from_adc(adc1,battery_k)/1000.0
                temp_C = tmp36.get_t_from_adc(adc0)

                log.info('A={0} T={1:.1f}C V={2:.3f}V'.format(
                    pkt.address,
                    temp_C, battery_V))

                csv_report = '{0},{1},{2},{3},{4:.1f},{5:.3f}\n'.format(
                    time.time(), pkt.address, radc0, radc1, temp_C, battery_V*1000.0)

                if not debug_mode:
                    try:
                        data_file.write(csv_report)
                        data_file.flush()
                    except IOError, ex:
                        log.error("Error writing CSV file: %s" % ex)
                    
            except IndexError, e:
                # I get this from pkt.get_adc() when packet is broken
                log.error('Broken XBee packet: "{0}"'.format(pkt))
Пример #2
0
def main():
    global logger

    log_format = '%(asctime)s %(process)d %(filename)s:%(lineno)d %(levelname)s %(message)s'
    logging.basicConfig(level=logging.INFO,
                        format=log_format,
                        filename=MAIN_LOGFILE,
                        filemode='w')

    logger = logging.getLogger('default')

    try:

        try:
            opts, args = getopt.getopt(sys.argv[1:], 's:nc', [])

        except getopt.GetoptError:
            usage()
            sys.exit(2)

        try:
            # timeout=0 causes it to raise AlreadyLocked. Any timeout >0
            # causes LockTimeout
            global_lock.acquire(timeout=0)
        except lockfile.AlreadyLocked:
            logger.error('Another copy of this program is running')
            sys.exit(1)

        atexit.register(cleanup)

        serial_port= '/dev/ttyS0'
        send_to_data_logger = True
        console = False

        for o, a in opts:
            if o in ['-s']:
                serial_port = a
            elif o in ['-n']:
                send_to_data_logger = False
            elif o in ['-c']:
                console = True
            else:
                usage()
                sys.exit(1)

        print 'Using serial port %s' % serial_port
        print 'Sending to data_logger: %s' % send_to_data_logger

        s = serial.serialposix.Serial(port=serial_port,
                                      baudrate=9600, bytesize=8, parity='N', stopbits=1,
                                      timeout=120,
                                      rtscts=1)

        s.open()

        battery_file = file(BATTERY_DATA_FILE, 'a')

        data_logger_update_time = time.time()
        battery_log_time = time.time()

        pachube_feed = pachube.PachubeFeed(feed_id=PACHUBE_FEED_ID)

        pkt_reader = xbee_api.read_packet(s)
        while True:
            pkt = pkt_reader.next()

            try:
                adc0 = float(pkt.get_adc(0))
                adc1 = float(pkt.get_adc(1))
                temp_C = tmp36.get_t_from_adc(adc1)

                # res = thermistor.get_res_from_adc(adc1)
                # temp_C = thermistor.get_t(res)
                # temp_F = 32 + temp_C * 5 / 9

                # send to data_logger every 5 min
                time_now = time.time()
                if time_now >= data_logger_update_time:
                    if send_to_data_logger:
                        pachube_feed.datastream_update({'temp': temp_C, 'Vbatt': adc0})
                    data_logger_update_time += DATA_LOGGER_UPDATE_INTERVAL
                    if time_now > data_logger_update_time:
                        # this happens if we got stuck in pkt_reader.next() for a long time
                        # and data_logger_update_time is in the past
                        data_logger_update_time = time_now + DATA_LOGGER_UPDATE_INTERVAL

                if time_now >= battery_log_time:
                    record_battery_v(battery_file, adc0)
                    battery_log_time += BATTERY_LOG_INTERVAL
                    if time_now > battery_log_time:
                        battery_log_time = time_now + BATTERY_LOG_INTERVAL

                report = 'packet_size={0} adc0={1:.3f} mV adc1={2:.3f} mV T={3:.1f} C'.format(
                    pkt.packet_size, adc0, adc1, temp_C)

                if console:
                    print report
                else:
                    logger.info(report)
            except IndexError, e:
                # I get this from pkt.get_adc() when packet is broken
                logger.error('Broken XBee packet: "{0}"'.format(pkt))


    except serial.SerialException,e:
        print e