#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间:2021年3月30日23:19:03
# 作者:lishan
# 邮箱:lishan_xatu@163.com
# pip install prettytable
import json
import random
import time
import urllib.request as req
from datetime import datetime
from threading import Timer
class OneNet:
def __init__(self, deviced):
self.device_id = deviced[0]
self.api_key = deviced[1]
self.post_data = []
self.get_data = []
self.url = "https://api.heclouds.com/devices/" + self.device_id + '/datapoints'
self.headers = {'api-key': self.api_key}
# 显示获取数据
def show_get_data(self):
# noinspection PyBroadException
try:
# 使用表格美化显示数据
import prettytable as pt
tb = pt.PrettyTable()
tb.field_names = ["id", "time", "value"]
for index, element in enumerate(self.get_data):
ID = str(element.get('id', ''))
update_at = str(element.get('datapoints', '')[0]['at'])
current_value = str(element.get('datapoints', '')[0]['value'])
tb.add_row([ID, update_at, current_value])
print(tb)
except Exception:
# 直接显示数据
print("id", "\t\t\ttime\t\t", "value")
for index, element in enumerate(self.get_data):
ID = str(element.get('id', ''))
update_at = str(element.get('datapoints', '')[0]['at'])
current_value = str(element.get('datapoints', '')[0]['value'])
print(ID, update_at, current_value)
# 上传函数
def OneNet_post_data(self, data):
streams = []
for index, element in enumerate(data):
streams.append({"id": element[0], "datapoints": [{"value": element[1]}]})
pkg = json.dumps({"datastreams": streams}).encode("utf-8")
request = json.loads((req.urlopen(req.Request(self.url, pkg, headers=self.headers))).read())
return request
# 获取函数
def OneNet_get_data(self):
request = json.loads((req.urlopen(req.Request(self.url, headers=self.headers))).read())
data = request.pop('data').pop('datastreams')
return data, request
# 准备待上传数据
def prepare_post_data(self):
self.post_data = []
# 上传数据ph、温度、浊度......
self.post_data.append(["PH", str(random.randint(0, 7))])
self.post_data.append(["WD", str(random.randint(0, 85))])
self.post_data.append(["ZD", str(random.randint(0, 10))])
# 间隔时间上传数据函数
def interval_post_data(self, sec):
self.prepare_post_data()
self.OneNet_post_data(self.post_data)
t = Timer(sec, self.interval_post_data, (sec,))
t.start()
# 间隔时间获取数据函数
def interval_get_data(self, sec):
self.get_data, reply = self.OneNet_get_data()
# 显示获取数据
self.show_get_data()
t = Timer(sec, self.interval_get_data, (sec,))
t.start()
if __name__ == '__main__':
# 设备ID、Key
Device = ["545225476", "EvNvc4m******CPkdl46xCw0="]
onenet = OneNet(Device)
now_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(now_time, "开始上传数据,")
# 定时5s上传数据
onenet.interval_post_data(5)
# 定时5s获取数据
onenet.interval_get_data(5)
定时上传数据到OneNet
最新推荐文章于 2022-04-14 10:48:51 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)