Python Scripts: Difference between revisions

Line 927:
 
= Weather Parcer =
*Need to register a account & get API Key from http://openweathermap.org
 
<syntaxhighlight lang="py>
import socket
Line 935 ⟶ 937:
 
s.connect(addr[0][4])
s.send(b'GET http://api.openweathermap.org/data/2.5/weather?q=Bangalore&appid={key}84d996853fcc4db149bc40acb09a3ef7_1 HTTP/1.0\r\n\r\n')
 
html = s.recv(1000)
Line 968 ⟶ 970:
print("Wind Speed =", speed, "Km/h?")
print("Wind Direction =", rnd2, "Degree")
</syntaxhighlight>
 
= Plot Temperature using Thingspeak =
*Need to register a account & get API Key from http://openweathermap.org
*Need to register a account & get API Key from http://thingspeak.com
 
<syntaxhighlight lang="py>
import socket
import json
from time import strftime,localtime,sleep
 
def temp():
# Fetch Temperature from openweathermap.org
s = socket.socket()
addr = socket.getaddrinfo('api.openweathermap.org', 80)
 
s.connect(addr[0][4])
s.send(b'GET http://api.openweathermap.org/data/2.5/weather?q=Bangalore&appid=84d996853fcc4db149bc40acb09a3ef7_1 HTTP/1.0\r\n\r\n')
 
html = s.recv(1000)
div = html.split(b'\r\n\r\n')[-1]
data = json.loads(div)
 
Cel = data['main']['temp'] - 273.15
rnd = int(round(Cel,2))
return rnd
 
def upload():
#Upload Temperature Data to thingspeak.com
rnd = temp()
 
s2 = socket.socket()
addr2 = socket.getaddrinfo('api.thingspeak.com', 80)
 
s2.connect(addr2[0][4])
s2.send(b'POST https://api.thingspeak.com/update?api_key=XB15HC17CZH6KYMV&field1_1=%d HTTP/1.0\r\n\r\n' % rnd)
html2 = s2.recv(1000)
div2 = html2.split(b' ')[1]
return int(div2)
 
 
while True:
upload()
 
currtime = strftime("%H:%M:%S %d-%b-%Y", localtime())
 
if upload() == 200:
print("Uploaded Data @", currtime,":", "Temp =", temp(), "\xb0C")
else:
print("HTTP Error:", int(div2))
 
# Wait for 10 minutes
sleep(600)
</syntaxhighlight>