#! /usr/bin/python import sys import datetime import os import fcntl import time import psycopg2 query = """INSERT INTO sputnik.reader (id, sequence, strength, station, time, tags) VALUES (%s, %s, %s, %s, now(), %s)""" readers = [{'id': 1, 'filename': '/dev/ttyACM0', 'file': None},] print readers for reader in readers: reader['file'] = open(reader['filename'], 'r') flags = fcntl.fcntl(reader['file'].fileno(), fcntl.F_GETFL) fcntl.fcntl(reader['file'].fileno(), fcntl.F_SETFL, flags|os.O_NDELAY) connection = psycopg2.connect("dbname=tomus port=5432") try: while True: line = None c = connection.cursor() for reader in readers: try: line = reader['file'].readline() except IOError: continue if line != '\n': print line d = line[:-1].split(',') if len(d) == 4: id = int(d[0]) seq = int(d[1]) strength = int(d[2]) flags = int(d[3]) n = datetime.datetime.now() print 'ID: %d Seq: %d Strength: %d Flags: %d, Time: %s' % (id, seq, strength, flags, n) tags = None tt = [] if flags != 0: if flags&2 != 0: tt.append('button0') if (flags>>2)&7 != 0: tt.append(str((flags>>2)&7)) if flags&32 != 0: tt.append('ping') if len(tt) > 0: tags = '{'+tt[0] for i in tt[1:]: tags += ', '+i tags += '}' c.execute(query, (id, seq, strength, reader['id'], tags)) if line == None: time.sleep(0.001) connection.commit() c.close() c = None except KeyboardInterrupt: pass connection.close() connection = None for reader in readers: reader['file'].close() reader['file'] = None