-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParseUDPfromArduino2MySQL&ThingSpeak-Python3.6.py
65 lines (61 loc) · 2.32 KB
/
ParseUDPfromArduino2MySQL&ThingSpeak-Python3.6.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
#!/usr/bin/python
#code by IV LO w Czestochowie, Jan Konopka, Bartlomiej Meller, Milos Galas, Szymon Zycinski
import socket
import sys
from datetime import datetime
import MySQLdb
import urllib
import http.client
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to the port
server_address = ('Put IP address here', 5005)
print('starting up on %s port %s' % server_address)
sock.bind(server_address)
host = 'localhost'
login = 'MySQL login username'
password = 'MySQL database password'
database = 'MySQL DB Name'
table = 'MySQL Table Name'
API_key = 'THINGSPEAK API WRITE KEY'
while True:
print('waiting to receive message')
data, address = sock.recvfrom(1024)
print('received %s bytes from %s' % (len(data), address))
print(data)
print(datetime.now())
txt1, pm25, txt2, pm10, heater, RH, temp, txt3 = data.split(b':')
print('pm2.5= ', str(pm25, 'utf-8'))
print('pm10 = ', str(pm10, 'utf-8'))
print('heater = ', str(heater, 'utf-8'))
print('RH = ', str(RH, 'utf-8'))
print('Temp = ', str(temp, 'utf-8'))
strPm25 = str(pm25, 'utf-8')
strPm10 = str(pm10, 'utf-8')
strHeater = str(heater, 'utf-8')
strRH = str(RH, 'utf-8')
strTemp = str(temp, 'utf-8')
connection = MySQLdb.connect(host, login, password, database)
if (connection):
print("MySQL connect sucessfully")
else:
print("Could not connect to MySQL")
cursor = connection.cursor()
cursor.execute("insert into readings (pm25,pm10,heater,RH,temp) values (%s,%s,%s,%s,%s)",
(strPm25, strPm10, strHeater, strRH, strTemp))
print("affected rows = {}".format(cursor.rowcount))
connection.commit()
connection.close()
params = urllib.parse.urlencode(
{'field1': strPm25, 'field2': strPm10, 'field3': strRH, 'key': API_key})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = http.client.HTTPConnection("api.thingspeak.com:80")
try:
conn.request("POST", "/update", params, headers)
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print("Data uploaded OK")
conn.close()
except:
print("connection failed")