11 from sqlalchemy import create_engine, exc
13 import MySQLdb.cursors
15 #May 27 21:32 /sys/bus/w1/devices/28-0416a1bab9ff
16 #May 27 21:33 /sys/bus/w1/devices/28-0416a1ac66ff
17 #May 27 21:35 /sys/bus/w1/devices/28-0516a207a4ff
18 #May 27 21:38 /sys/bus/w1/devices/28-0316a2193bff
19 #May 27 21:38 /sys/bus/w1/devices/28-0316a21383ff
22 # einen Sensor auslesen
25 class ReadsensorError(RuntimeError):
29 def readsensor(sensor_id):
30 sensorfile = "/sys/bus/w1/devices/28-{}/w1_slave".format(sensor_id)
31 file = open(sensorfile)
34 # 64 01 4b 46 7f ff 0c 10 01 : crc=01 YES
35 # 64 01 4b 46 7f ff 0c 10 01 t=22250
38 linecrc = file.readline()
39 match = re.search(": crc=[0-9a-f]{2} (YES|NO)",linecrc)
41 yesno = match.group(1)
43 raise ReadsensorError('Could not evaluate sensorfile "{}"'.format(sensorfile))
46 linetemp = file.readline()
47 match = re.search(" t=([-0-9]+)",linetemp)
49 temp_raw = match.group(1)
50 temp = float(temp_raw)/1000
53 jetzt = datetime.datetime.now()
55 return jetzt, temp_raw, temp
58 def writesensordatacsv(config, sensor_id, sensor_name, timestamp, value_type, value_raw, value):
59 # Schreiben des csv-files
60 with open(os.path.expanduser(config.get("csv", "filename")), "a", newline = "") as file:
61 writer = csv.writer(file, dialect = "excel")
62 writer.writerow([timestamp.strftime("%Y-%m-%d %H:%M"), sensor_id, sensor_name, "{:.1f}".format(value)])
65 def readcsvfile(csvfile):
66 with open(csvfile, "r", newline="") as file:
67 reader = csv.DictReader(file, dialect = "excel", fieldnames=("timestamp", "sensor_id", "sensor_name", "value"))
74 def writesensordatadb(config, sensor_id, sensor_name, timestamp, value_type, value_raw, value):
75 # Schreiben des db-files
76 user = config.get('database', 'user')
77 pwd = config.get('database','password')
78 host = config.get('database','hostname')
79 db = config.get('database','database')
81 engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db), echo=False)
82 conn = engine.connect()
83 with warnings.catch_warnings():
84 # ignore _mysql_exceptions.IntegrityError: (1062, "Duplicate entry '0316a2193bff-2018-08-29 14:30:00' for key 'sensorid_timestamp'")
85 # TODO: the following doesn't work
86 warnings.simplefilter("ignore", category=MySQLdb.cursors.Warning)
87 # TODO: this does but …?!
89 conn.execute("insert into sensors (sensor_id, sensor_name, value_type, value_raw, value, timestamp) values (%s,%s,%s,%s,%s,%s)", sensor_id, sensor_name, value_type, value_raw, value, timestamp)
90 except exc.IntegrityError as e:
98 def main(configfile, fromcsvfile):
99 config = configparser.ConfigParser()
100 config.read(configfile)
102 value_type = "Wassertemperatur"
103 for sensor_id, sensor_name in config.items('temperature'):
105 # "timestamp", "sensor_id", "sensor_name", "value"
106 for record in readcsvfile(fromcsvfile):
107 timestamp, sensor_id, sensor_name, value = (record["timestamp"], record["sensor_id"], record["sensor_name"], float(record["value"]))
109 writesensordatadb(config, sensor_id, sensor_name, timestamp, value_type, value_raw, value)
111 timestamp, value_raw, value = readsensor(sensor_id)
112 writesensordatacsv(config, sensor_id, sensor_name, timestamp, value_type, value_raw, value)
113 writesensordatadb(config, sensor_id, sensor_name, timestamp, value_type, value_raw, value)
114 logging.info('Sensor {}: {:.1f}°C'.format(sensor_id, value))
117 if __name__ == '__main__':
118 default_config_file = os.path.expanduser('~/seewasser.ini')
119 parser = argparse.ArgumentParser(description='Read sensor data')
120 parser.add_argument('--config', default=default_config_file, help='configuration file')
121 parser.add_argument('--fromcsvfile', help='write values from csv file to database')
122 args = parser.parse_args()
123 main(args.config, args.fromcsvfile)