应用背景:
Ubidots是一个物联网云平台,通过设备友好的API(可通过HTTP / MQTT / TCP / UDP协议访问)简单安全地将硬件和数字输入连接到Ubidots Cloud。它可以从任何启用互联网的设备将数据发送到云端,比如 Arduino、树莓派、Particle、Espressif、Onion,等等。此外,它还提供了多种类型的服务,比如设备连接管理以及数据可视化,开发人员可以基于实时数据和可视化工具配置操作和报警。RevPi作为工业级树莓派,与以太网进行连接,自然也可以与Ubidots云平台进行数据的通信。
解决方案:
RevPi Core具有定制的Raspbian系统可以通过运行python脚本随机生成压力、温度和湿度读数并将数据发送到Ubidots云平台。
首先通过RevPi Core终端使用nano编辑器创建Python脚本(可以通过putty远程连接,也可以外接显示屏,进入终端窗口):nano ubidots_revpi.py。
将以下代码粘贴到nano编辑器中,并将代码中的TOKEN替换成您自己的,获取方法见下图:
################################################################################
# This script simulates different sensors values using the random module and make
# a HTTP request to Ubidots Cloud (https://ubidots.com/)
#
# Author: M. Hernandez
################################################################################
import requests
import time
import random
from uuid import getnode as get_mac
# Assign your Ubidots TOKEN
TOKEN = “Assign_your_Ubidots_token”
# Set the delay desired to post the data
DELAY = 1
”’
This method build the JSON to be sent to the Ubidots Cloud
”’
def build_json(variable_1, value_1, variable_2, value_2, variable_3, value_3):
try:
data = {variable_1: value_1, variable_2: value_2, variable_3: value_3}
return data
except:
return None
”’
This method make the HTTP Request to the Ubidots Cloud
”’
def post_variable(device, value_1, value_2, value_3):
try:
url = “https://industrial.api.ubidots.com/api/v1.6/devices/” + device
headers = {“X-Auth-Token”: TOKEN, “Content-Type”: “application/json”}
data = build_json(“temperature”, value_1, “humidity”, value_2, “pressure”, value_3)
response = requests.post(url=url, headers=headers, json=data)
return response.json()
except:
pass
if __name__ == “__main__”:
while True:
mac = get_mac() # get the mac address of your device
device_mac = ‘:’.join((“%012X” % mac)[i:i+2] for i in range(0, 12, 2))
temp_value = random.randint(0,15)*2
hum_value = random.randint(20,50)
press_value = random.randint(2,50)*2
print post_variable(device_mac, temp_value, hum_value, press_value)
time.sleep(DELAY)