Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #-------------------------------------------------------------------------------
- # Name: module2
- # Purpose:
- #
- # Author: t3ahsa00
- #
- # Created: 19.11.2015
- # Copyright: (c) t3ahsa00 2015
- # Licence: <your licence>
- #-------------------------------------------------------------------------------
- import time
- import serial
- import mysql.connector
- connection = mysql.connector.connect( host = "127.0.0.1", # Database server address
- port = 3306, # Connection port
- db = "raspi", # Name of the database
- user = "root", # Username
- password = "spamtolkki!" # Password
- )
- ser = serial.Serial('/dev/ttyACM0', 9600)
- entrysql = "INSERT INTO `weather_data` ( `time` ) VALUES ( %s ) ON DUPLICATE KEY UPDATE time = time"
- queries = {
- 't': "INSERT INTO `temperatures` ( `weather_id`, `temperature`, `sensor_id` ) VALUES ( %s, %s, %s )",
- 'h': "INSERT INTO `humidities` ( `weather_id`, `humidity` ) VALUES ( %s, %s )"
- }
- delimiter = b':'
- keydelimiter = b'::'
- if connection.is_connected() and ser.isOpen():
- cur = connection.cursor()
- try:
- while True:
- if ser.inWaiting() > 0:
- data = ser.readline()
- if len(data) > 0:
- values = ()
- key, deli, data = data.partition(keydelimiter)
- key = list(key);
- data = data.replace("\r\n", '')
- for entry in data.split(delimiter):
- values = values + (entry.decode("utf-8"), )
- if len(values) == len(key):
- cur.execute(entrysql, [time.time()])
- entryid = cur.lastrowid
- x = 0
- if entryid != 0:
- while x < len(values):
- temp = []
- lastkey = ''
- while (len(key) > 0 and (lastkey == '' or lastkey == key[0]) and x < len(values)):
- lastkey = key[0]
- if lastkey == 't':
- temp.append((entryid, values[x], x + 1), )
- elif lastkey == 'h':
- temp.append((entryid, values[x]), )
- key.remove(key[0])
- x += 1
- if len(temp) > 0:
- cur.executemany(queries[lastkey], temp)
- connection.commit()
- else:
- time.sleep(5)
- except Exception as e:
- connection.close()
- print("Error")
- print(e)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement