-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpclient.py
More file actions
107 lines (96 loc) · 2.93 KB
/
Copy pathhttpclient.py
File metadata and controls
107 lines (96 loc) · 2.93 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import socket
import requests
import time
import json
class HTTPClient(object):
url_report = "/api/report"
url_get_data = "/api/data"
url_push = "/api/push"
url_poll = "/api/poll"
def __init__(self, auth_id, auth_key, server_addr):
self.auth_id = auth_id
self.auth_key = auth_key
self.server_addr = server_addr
self.server_url = "http://{}".format(server_addr)
def report(self, device_id, data):
'''
device_id is an integer
data is a dictionary
'''
packet = {
"auth_id": self.auth_id,
"auth_key": self.auth_key,
"device_id": device_id,
"payload": data
}
try:
r = requests.post(self.server_url+self.url_report, json.dumps(packet))
except requests.RequestException as e:
print(e)
return False
print(r.status_code)
def get_data(self, device_id, limit=200):
try:
r = requests.get("{}{}?device_id={}&limit={}".format(self.server_url, self.url_get_data, device_id, limit))
except requests.RequestException as e:
print(e)
return
try:
data = json.loads(r.text)
except json.JSONDecodeError as e:
print(e)
return
if data['code'] == 0:
return data['data']
def push(self, device_id, data):
'''
data is a dictionary and should be something like
{ "name": "aircondition", "value": "open", "length": "4", "type": "string" }
'''
body = [data]
try:
r = requests.post("{}{}?device_id={}".format(self.server_url,
self.url_push, device_id), json.dumps(body))
print(r.status_code, r.text)
except requests.RequestException as e:
print(e)
def poll(self, device_id):
data = {
"auth_id": self.auth_id,
"auth_key": self.auth_key,
"device_id": device_id,
}
try:
r = requests.post(self.server_url+self.url_poll, json.dumps(data))
except requests.RequestException as e:
print(e)
return
if r.status_code != 200:
print(r.status_code)
return
try:
# print(r.text)
data = json.loads(r.text)
except ValueError as e:
print(e)
return
return data['data']
auth_id = 15
auth_key = "d7fe7b0a3c1dbde58e251d3aafc4954f"
def test_client():
c = HTTPClient(auth_id, auth_key, "nya.fatmou.se")
data = {
"pm2.5": 23,
"HCHO": 25,
"Temperature": 20,
"Humidity":71,
"CO":103,
"Detect People":2
}
'''test:report for AirMonitor'''
print(c.report(17, data))
#print(c.get_data(9))
#push_data = { "name": "set-temperature", "value": 28.50, "length": 4, "type": "float"}
#c.push(9, push_data)
if __name__=="__main__":
test_client()