Advertisement
Guest User

Untitled

a guest
Feb 18th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.94 KB | None | 0 0
  1. # python -m pip install pymysql
  2. # pymysql muss zunächst installiert werden
  3.  
  4. import pymysql
  5. import requests
  6. import json
  7. import datetime, time
  8.  
  9. # Liste mit den Arduino IP-Adressen
  10. arduino_list = ['192.168.1.112', '192.168.1.113']
  11.  
  12. # init DB Conncetion
  13. db = None
  14.  
  15. # Zeitverzögerung beim Abrufen
  16. seconds_to_sleep = 5
  17.  
  18. def connect_db():
  19.     global db
  20.     db = pymysql.Connect('localhost', 'user', 'password', 'MESSUNGEN')  # Datenbank Authentifizierungsparameter
  21.  
  22. def close_db():
  23.     db.close()
  24.  
  25. def create_table(arduino_ip):
  26.     cursor = db.cursor()
  27.     cursor.execute('''
  28.    CREATE TABLE IF NOT EXISTS '''+arduino_ip+'''(
  29.        ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  30.        SPANNUNG DOUBLE NOT NULL,
  31.        STROM DOUBLE NOT NULL,
  32.        LEISTUNG DOUBLE NOT NULL,
  33.        TIMESTAMP DATETIME NOT NULL
  34.    );''')
  35.     cursor.close()
  36.     db.commit()
  37.  
  38. def insert_entry(arduino_ip, spannung, strom):
  39.     ts = time.time()
  40.     timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
  41.     cursor = db.cursor()
  42.     cursor.execute('INSERT INTO ' + arduino_ip + ' VALUES (NULL, ' + str(spannung) + ', ' + str(strom) + ', ' + str(strom*spannung) + ', \'' + str(timestamp) + '\')')
  43.     db.commit()
  44.  
  45.  
  46.  
  47. if __name__ == '__main__':
  48.  
  49.     print('Intialisiere Messung')
  50.  
  51.     connect_db()
  52.  
  53.     # CREATE Tables
  54.     for arduino in arduino_list:
  55.         create_table(arduino)
  56.  
  57.     close_db()
  58.  
  59.     while True:
  60.         time.sleep(seconds_to_sleep)
  61.         print('GETTING DATA FROM ARDUINOS')
  62.         connect_db()
  63.  
  64.         for arduino in arduino_list:
  65.             result = requests.get('http://' + arduino)
  66.             result = result.content.strip()
  67.             result = json.loads(result)
  68.             if result['Strom'] != "0.00" and result['Spannung'] != "0.00": # Wenn werte vorhanden, schreibe es in die DB
  69.                 insert_entry(arduino, result['Strom'], result['Spannung'])
  70.  
  71.         close_db()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement