This repository has been archived by the owner on Aug 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
iot_serial.py
82 lines (48 loc) · 1.89 KB
/
iot_serial.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import pymysql as mdb
import csv
import serial
import datetime
import time
import logging
logging.basicConfig(level=logging.DEBUG,
format='[%(levelname)s] (%(threadName)-10s) %(message)s',
)
def insert_sql(database, table, str_columns, values, cursor, connection):
query = "INSERT INTO "+database+"."+table+" ("+str_columns+") "
query += "VALUES ("
for value in values:
if values.index(value) == 0:
query += "\'"+value+"\'"
else:
query += ",\'"+value+"\'"
query += ");"
print(query)
cursor.execute(query)
connection.commit()
def run_reading():
ser = serial.Serial('/dev/ttyUSB0', 9600)
con = mdb.connect(host='localhost',user='isa',password='demoisa',db='moisture')
cur = con.cursor()
columns = "time_stamp, id_plant, description, humidity_level"
logging.debug('Starting')
while(1):
now = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
reading = now+"," + ser.readline()[:-2].decode("utf-8")
logging.debug(reading)
logging.debug("READING SENSOR 1: "+reading)
insert_sql("moisture","plants",columns,reading.split(","), cur, con)
reading = now+"," + ser.readline()[:-2].decode("utf-8")
logging.debug(reading)
logging.debug("READING SENSOR 2: "+reading)
insert_sql("moisture","plants",columns,reading.split(","), cur, con)
reading = now+"," + ser.readline()[:-2].decode("utf-8")
logging.debug(reading)
logging.debug("READING SENSOR 3: "+reading)
insert_sql("moisture","plants",columns,reading.split(","), cur, con)
tempo = float(ser.readline())/1000
reading = reading[:len(reading)-2]
time.sleep(float(tempo))
# print(str(tempo))
logging.debug('Exiting')