当前,智能手机、平板电脑和笔记本电脑无处不在,支持我们网上冲浪、收发电子邮件,与朋友聊天。 但人们希望能够通过设备完成更多事情,比如远程管理和监控其他计算机和设备。 为此,他们需要能够通过互联网收发物联网设备的数据。 多款基于云的解决方案能够帮助你实现这项功能。 本文我们将介绍其中的一种: 英特尔® 物联网分析。 下图展示了英特尔® 物联网分析的工作原理。
<center><img src="http://intel.eetrend.com/files/filefield_paths/cloud.jpg" alt=""></center>
英特尔物联网分析包含各种资源,以便收集和分析英特尔® 物联网开发人员套件提供的传感器数据。 开发人员可借助这项服务直接进行数据采集和分析,无需投资大规模存储和处理容量。 下列示意图显示了英特尔® Galileo 和英特尔® Edison 开发板的传感器数据通过互联网发送至英特尔物联网分析云,进而在笔记本电脑上进行分析。 这是物联网分析使用的基本模式。
<center><img src="http://intel.eetrend.com/files/filefield_paths/iot-agent.png" alt=""></center>
英特尔® Edison 开发板通过传感器收集测量数据,并借助配置的物联网代理将数据发送至云。 开始使用英特尔物联网分析仪表板之前,需创建管理用户帐号,以便在网站上注册设备、管理告警,创建帐号和执行其他任务。 前往此处的英特尔物联网分析仪表板。
为验证物联网设备与云之间的互动,我将使用前文“使用英特尔开发板中的微控制器”中的示例代码。 在本文中,我们采用超声波测距模块 HC-SR04 测量物体之间的距离。 测量结果显示在 LCD 显示屏上。 我们将部分脚本添加至该示例,以自动将数据传输至云。 下图所示为连接 HC-SR04 传感器的英特尔® Edison 开发板,测量结果显示在 LCD 显示屏上。
<center><img src="http://intel.eetrend.com/files/filefield_paths/iot-hc-sr04-sensor.jpg&q…; alt=""></center>
首先,我们需要在云中以组件的形式注册距离传感器。 为此,需填写所有必填字段。
<center><img src="http://intel.eetrend.com/files/filefield_paths/my-account.jpg" alt=""></center>
<center><img src="http://intel.eetrend.com/files/filefield_paths/component.jpg" alt=""></center>
现在,需要在开发板上注册传感器。 接下来,我们使用开发板上的以下命令,通过英特尔® Edison 开发板注册传感器:
iotkit-admin register dist distance.v1.0
iotkit-admin catalog
现在,传感器已注册完成并分配至该开发板。
为使用整数类型,我们定义从 -1(错误)至 100 厘米的数值范围。
<center><img src="http://intel.eetrend.com/files/filefield_paths/device.jpg" alt=""></center>
将数据发送至云可以通过多种方法完成。
在开发板上执行以下命令:
iotkit-admin observation dist 10
但这并不是将数据发送至云的最佳方法。 该命令通常用于测试。
另外两种将数据传输至云的方法是:
配置客户端界面 REST(文档地址: https://github.com/enableiot/iotkit-api/wiki/Api-Home)
将 UPD 数据包发送至开发板的代理。 代理可将数据包转换成 REST 调用,并发送请求。
使用下面的指令在开发板上运行代理。
1 systemctl start iotkit-agent
可以通过UDP localhost 向41234端口发送消息 (UDP: // localhost: 41234)。为此,您必须创建一个JSON-file (JavaScript* 对象标记):
1 {"n": "<sensor name>", "v": "<value>" }
这里的 “n” 是量度名称(譬如距离或者温度),而 “v” 是数值。
例如:
1 { "n": "dist", "v": 17 }
2 { "n": "dist", "v": 24}
通过英特尔物联网分析 iotkit-agent 将数据发送至云的方法有多种。 您还可以使用编程语言(比如 C/C ++、JavaScript 或 Python*)发送数据。 我热衷于快速、便捷地进行编程,因此我使用钟爱的编程语言 Python 编写了一个小型示例。 该代码获取传感器数据,并自动将数据上传至物联网分析云。
001 import sys
002 import requests
003 import json
004 import uuid
005 import time
006 import random
007 import pyupm_i2clcd
008
009 host = "dashboard.us.enableiot.com"
010
011 proxies = {
012
013 }
014
015 username = "email@gmail.com"
016 password = "*********"
017 account_name = "account_name"
018
019 device_id = "***************************************"
020
021 observations_per_hour = 1
022 days_of_data = 1
023
024 verify = True
025
026 api_root = "/v1/api"
027 base_url = "https://{0}{1}".format(host, api_root)
028 device_name = "Device-{0}".format(device_id)
029
030 g_user_token = ""
031 g_device_token = ""
032
033 def main():
034 global g_user_token, g_device_token
035
036 g_user_token = get_token(username, password)
037
038 uid = get_user_id()
039 print "UserId: {0}".format(uid)
040
041 aid = get_account_id(uid, account_name)
042 print "AccountId: {0}".format(aid)
043
044 create_device(aid, device_id, device_name)
045
046 ac = generate_activation_code(aid)
047 print "Activation code: {0}".format(ac)
048
049 g_device_token = activate(aid, device_id, ac)
050
051 cid = create_component(aid, device_id, "Distance.v1.0", "Dist")
052 print "ComponentID (cid): {0}".format(cid)
053
054 lcd = pyupm_i2clcd.Jhd1313m1(6, 0x3E, 0x62)
055 with open('/dev/ttymcu0', 'w+t') as f:
056 while True:
057 f.write('get_distance\n')
058 f.flush()
059 line = f.readline()
060 value = int(line.strip('\n\r\t '))
061
062 create_observations(aid, device_id, cid, value)
063
064 o = get_observations(aid, device_id, cid)
065 print_observation_counts(o)
066
067 lcd.clear()
068 if value == -1:
069 lcd.setColor(255, 0, 0) # RED
070 lcd.write('ERROR')
071 else:
072 lcd.setColor(0, 255, 0) # GREEN
073 lcd.write('%d cm' % (value,))
074 time.sleep(1)
075
076 def get_user_headers():
077 headers = {
078 'Authorization': 'Bearer ' + g_user_token,
079 'content-type': 'application/json'
080 }
081 return headers
082
083
084 def get_device_headers():
085 headers = {
086 'Authorization': 'Bearer ' + g_device_token,
087 'content-type': 'application/json'
088 }
089 return headers
090
091
092 def check(resp, code):
093 if resp.status_code != code:
094 print "Expected {0}. Got {1} {2}".format(code, resp.status_code, resp.text)
095 sys.exit(1)
096
097 def get_token(username, password):
098 url = "{0}/auth/token".format(base_url)
099 headers = {'content-type': 'application/json'}
100 payload = {"username": username, "password": password}
101 data = json.dumps(payload)
102 resp = requests.post(url, data=data, headers=headers, proxies=proxies, verify=verify)
103 check(resp, 200)
104 js = resp.json()
105 token = js['token']
106 return token
107
108 def get_user_id():
109 url = "{0}/auth/tokenInfo".format(base_url)
110 resp = requests.get(url, headers=get_user_headers(), proxies=proxies, verify=verify)
111 check(resp, 200)
112 js = resp.json()
113 user_id = js["payload"]["sub"]
114 return user_id
115
116 def get_account_id(user_id, account_name):
117 url = "{0}/users/{1}".format(base_url, user_id)
118 resp = requests.get(url, headers=get_user_headers(), proxies=proxies, verify=verify)
119 check(resp, 200)
120 js = resp.json()
121 if 'accounts' in js:
122 accounts = js["accounts"]
123 for k, v in accounts.iteritems():
124 if 'name' in v and v["name"] == account_name:
125 return k
126 print "Account name {0} not found.".format(account_name)
127 print "Available accounts are: {0}".format([v["name"] for k, v in accounts.iteritems()])
128 return None
129
130 def create_device(account, device_id, device_name):
131 url = "{0}/accounts/{1}/devices".format(base_url, account)
132 device = {
133 "deviceId": str(device_id),
134 "gatewayId": str(device_id),
135 "name": device_name,
136 "tags": ["Russia", "Moscow", "RoadShow"],
137 "attributes": {
138 "vendor": "intel",
139 "platform": "x86",
140 "os": "linux"
141 }
142 }
143 data = json.dumps(device)
144 resp = requests.post(url, data=data, headers=get_user_headers(), proxies=proxies, verify=verify)
145 check(resp, 201)
146 return resp
147
148 def generate_activation_code(account_id):
149 url = "{0}/accounts/{1}/activationcode/refresh".format(base_url, account_id)
150 resp = requests.put(url, headers=get_user_headers(), proxies=proxies, verify=verify)
151 check(resp, 200)
152 js = resp.json()
153 activation_code = js["activationCode"]
154 return activation_code
155
156 def activate(account_id, device_id, activation_code):
157 url = "{0}/accounts/{1}/devices/{2}/activation".format(base_url, account_id, device_id)
158 activation = {
159 "activationCode": activation_code
160 }
161 data = json.dumps(activation)
162 resp = requests.put(url, data=data, headers=get_user_headers(), proxies=proxies, verify=verify)
163 check(resp, 200)
164 js = resp.json()
165 if "deviceToken" in js:
166 token = js["deviceToken"]
167 return token
168 else:
169 print js
170 sys.exit(1)
171
172 def create_component(account_id, device_id, component_type_name, name):
173 url = "{0}/accounts/{1}/devices/{2}/components".format(base_url, account_id, device_id)
174 component = {
175 "type": component_type_name,
176 "name": name,
177 "cid": str(uuid.uuid4())
178 }
179 data = json.dumps(component)
180 resp = requests.post(url, data=data, headers=get_device_headers(), proxies=proxies, verify=verify)
181 check(resp, 201)
182 js = resp.json()
183 return js["cid"]
184
185 def create_observations(account_id, device_id, cid, val):
186 url = "{0}/data/{1}".format(base_url, device_id)
187 body = {
188 "accountId": account_id,
189 "data": []
190 }
191 o = {
192 "componentId": cid,
193 "value": str(val),
194 "attributes": {
195 "i": i
196 }
197 }
198 body["data"].append(o)
199 data = json.dumps(body)
200 resp = requests.post(url, data=data, headers=get_device_headers(), proxies=proxies, verify=verify)
201 check(resp, 201)
202
203 def get_observations(account_id, device_id, component_id):
204 url = "{0}/accounts/{1}/data/search".format(base_url, account_id)
205 search = {
206 "from": 0,
207 "targetFilter": {
208 "deviceList": [device_id]
209 },
210 "metrics": [
211 {
212 "id": component_id
213 }
214 ]
215 }
216 data = json.dumps(search)
217 resp = requests.post(url, data=data, headers=get_user_headers(), proxies=proxies, verify=verify)
218 check(resp, 200)
219 js = resp.json()
220 return js
221
222 def print_observation_counts(js):
223 if 'series' in js:
224 series = js["series"]
225 series = sorted(series, key=lambda v: v["deviceName"])
226 for v in series:
227 print "Device: {0} Count: {1}".format(v["deviceName"], len(v["points"]))
228
229 if __name__ == "__main__":
230 main()
现在,我们来绘制有关测量数据的图表。 该图表展示了传感器在不同时间点测量的距离(单位:厘米)。
<center><img src="http://intel.eetrend.com/files/2016-03/wen_zhang_/100001241-1102-measur…; alt=""></center>
图表测量数据" typeof="foaf:Image">因此,通过绘制图表,我们借助物联网分析工具上传了距离测量数据。 现在,我们要使用物联网分析确定发送至云的最小和最大距离值 (cm),因此得出了下图。
<center><img src="http://intel.eetrend.com/files/2016-03/wen_zhang_/100001241-1103-iot-an…; alt=""></center>
总而言之,我们展示了英特尔物联网分析这款简单、方便的工具能够保存和分析传感器(连接至英特尔® Galileo 或英特尔® Edison 开发板)的数据。
文章来源:<a href="https://software.intel.com/zh-cn/articles/intel-iot-analytics-with-the-…;英特尔开发人员专区