65.9K
CodeProject 正在变化。 阅读更多。
Home

Intel® IoT 分析与 Intel® Edison 主板

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.83/5 (4投票s)

2015年9月15日

CPOL

5分钟阅读

viewsIcon

15308

在本文中,我将介绍其中一个:Intel® 物联网分析。下图说明了 Intel 物联网分析的工作架构。

获取新的 Intel® 物联网开发者套件,这是一个完整的硬件和软件解决方案,允许开发人员使用 Intel® Galileo 和 Intel® Edison 主板创建令人兴奋的新解决方案。请访问 Intel® 物联网开发者专区

如今,智能手机、平板电脑、笔记本电脑无处不在,让我们能够上网、收发邮件和与朋友聊天。但人们希望通过他们的设备做更多的事情——他们希望远程管理和监控其他计算机和设备。要做到这一点,他们需要能够通过互联网发送和接收物联网设备数据。有几种基于云的解决方案可以提供这种能力。在本文中,我将介绍其中一个:Intel® 物联网分析。下图说明了 Intel 物联网分析的工作架构。

Intel 物联网分析包含 Intel® 物联网开发者套件提供的传感器数据收集和分析资源。利用此服务,开发人员可以快速启动数据采集和分析,而无需投入大规模的存储和处理能力。下图显示了来自 Intel® Galileo 和 Intel® Edison 主板的传感器数据通过互联网发送到 Intel 物联网分析云进行分析,并在笔记本电脑上显示。这是物联网分析使用的一个基本模型。

Intel® Edison 主板通过传感器收集测量数据,并通过配置的物联网代理(IoT Agent)将数据发送到云端。要开始使用 Intel 物联网分析仪表板,请创建一个管理用户帐户,该帐户将允许您注册设备、管理警报、创建帐户以及在该网站上执行其他任务。在此处 访问 Intel 物联网分析仪表板

为了演示物联网设备和云之间的交互,我将使用我们上一篇文章《在 Intel® Edison 主板上使用微控制器》中的示例代码。在这篇文章中,我们使用了超声波测距模块 HC-SR04 来测量检测到的物体距离。测量结果显示在 LCD 显示屏上。我们在该示例中添加了一些脚本,以便自动将数据传输到云端。下图显示了连接了 HC-SR04 传感器的 Intel® Edison 主板,测量结果显示在 LCD 显示屏上。

首先,我们需要将距离传感器注册为云中的一个组件。为此,请填写所有必填字段。

接下来,有必要在主板上注册传感器。然后,我们使用主板上的以下命令注册传感器与 Intel® Edison 主板:

iotkit-admin register dist distance.v1.0

iotkit-admin catalog

现在,我们的传感器已注册并分配给此主板。

为了使用整数类型,我们将值范围定义为 -1(错误)到 100 厘米。

有几种方法可以将数据发送到云端。

在主板上执行以下命令:

iotkit-admin observation dist 10

但是,这不是将数据发送到云端最方便的方法。通常,此命令用于测试。

另外两种将数据传输到云端的方法:

要运行主板上的代理,请使用以下命令:

systemctl start iotkit-agent

可以通过 UDP 将消息发送到端口 41234 上的代理(UDP://:41234)。为此,您必须创建一个 JSON 文件(JavaScript* 对象表示法)。

{"n": "<sensor name>", "v": "<value>" }

其中“n”是测量名称(如距离或温度),“v”是值。

例如

{ "n": "dist", "v": 17 }
{ "n": "dist", "v": 24}

以上是通过 Intel 物联网分析 iotkit-agent 将数据发送到云端的几种方法。您还可以使用 C/C++、JavaScript 或 Python* 等编程语言发送数据。我喜欢快速、便捷编程的理念,因此我用我喜欢的编程语言 Python 编写了一个小型示例。此代码从传感器获取数据并自动将数据上传到物联网分析云。

import sys
import requests
import json
import uuid
import time
import random
import pyupm_i2clcd

host = "dashboard.us.enableiot.com"

proxies = {
     
}

username = "email@gmail.com"
password = "*********"
account_name = "account_name"

device_id = "***************************************"

observations_per_hour = 1
days_of_data = 1

verify = True

api_root = "/v1/api"
base_url = "https://{0}{1}".format(host, api_root)
device_name = "Device-{0}".format(device_id)

g_user_token = ""
g_device_token = ""

def main():
    global g_user_token, g_device_token

    g_user_token = get_token(username, password)

    uid = get_user_id()
    print "UserId: {0}".format(uid)

    aid = get_account_id(uid, account_name)
    print "AccountId: {0}".format(aid)

    create_device(aid, device_id, device_name)

    ac = generate_activation_code(aid)
    print "Activation code: {0}".format(ac)

    g_device_token = activate(aid, device_id, ac)

    cid = create_component(aid, device_id, "Distance.v1.0", "Dist")
    print "ComponentID (cid): {0}".format(cid)

    lcd = pyupm_i2clcd.Jhd1313m1(6, 0x3E, 0x62)
	with open('/dev/ttymcu0', 'w+t') as f:
		while True:
			f.write('get_distance\n')
			f.flush()
			line = f.readline() 
			value = int(line.strip('\n\r\t '))
                                                     
		                   create_observations(aid, device_id, cid, value)
                                                     
   			o = get_observations(aid, device_id, cid)
    			print_observation_counts(o)

			lcd.clear()
			if value == -1:
				lcd.setColor(255, 0, 0) # RED
				lcd.write('ERROR')
			else:
				lcd.setColor(0, 255, 0) # GREEN
				lcd.write('%d cm' % (value,))
			time.sleep(1)
 
def get_user_headers():
    headers = {
        'Authorization': 'Bearer ' + g_user_token,
        'content-type': 'application/json'
    }
    return headers


def get_device_headers():
    headers = {
        'Authorization': 'Bearer ' + g_device_token,
        'content-type': 'application/json'
    }
    return headers


def check(resp, code):
    if resp.status_code != code:
        print "Expected {0}. Got {1} {2}".format(code, resp.status_code, resp.text)
        sys.exit(1)

def get_token(username, password):
    url = "{0}/auth/token".format(base_url)
    headers = {'content-type': 'application/json'}
    payload = {"username": username, "password": password}
    data = json.dumps(payload)
    resp = requests.post(url, data=data, headers=headers, proxies=proxies, verify=verify)
    check(resp, 200)
    js = resp.json()
    token = js['token']
    return token

def get_user_id():
    url = "{0}/auth/tokenInfo".format(base_url)
    resp = requests.get(url, headers=get_user_headers(), proxies=proxies, verify=verify)
    check(resp, 200)
    js = resp.json()
    user_id = js["payload"]["sub"]
    return user_id

def get_account_id(user_id, account_name):
    url = "{0}/users/{1}".format(base_url, user_id)
    resp = requests.get(url, headers=get_user_headers(), proxies=proxies, verify=verify)
    check(resp, 200)
    js = resp.json()
    if 'accounts' in js:
        accounts = js["accounts"]
        for k, v in accounts.iteritems():
            if 'name' in v and v["name"] == account_name:
                return k
    print "Account name {0} not found.".format(account_name)
    print "Available accounts are: {0}".format([v["name"] for k, v in accounts.iteritems()])
    return None

def create_device(account, device_id, device_name):
    url = "{0}/accounts/{1}/devices".format(base_url, account)
    device = {
        "deviceId": str(device_id),
        "gatewayId": str(device_id),
        "name": device_name,
        "tags": ["Russia", "Moscow", "RoadShow"],
        "attributes": {
            "vendor": "intel",
            "platform": "x86",
            "os": "linux"
        }
    }
    data = json.dumps(device)
    resp = requests.post(url, data=data, headers=get_user_headers(), proxies=proxies, verify=verify)
    check(resp, 201)
    return resp

def generate_activation_code(account_id):
    url = "{0}/accounts/{1}/activationcode/refresh".format(base_url, account_id)
    resp = requests.put(url, headers=get_user_headers(), proxies=proxies, verify=verify)
    check(resp, 200)
    js = resp.json()
    activation_code = js["activationCode"]
    return activation_code

def activate(account_id, device_id, activation_code):
    url = "{0}/accounts/{1}/devices/{2}/activation".format(base_url, account_id, device_id)
    activation = {
        "activationCode": activation_code
    }
    data = json.dumps(activation)
    resp = requests.put(url, data=data, headers=get_user_headers(), proxies=proxies, verify=verify)
    check(resp, 200)
    js = resp.json()
    if "deviceToken" in js:
        token = js["deviceToken"]
        return token
    else:
        print js
        sys.exit(1)

def create_component(account_id, device_id, component_type_name, name):
    url = "{0}/accounts/{1}/devices/{2}/components".format(base_url, account_id, device_id)
    component = {
        "type": component_type_name,
        "name": name,
        "cid": str(uuid.uuid4())
    }
    data = json.dumps(component)
    resp = requests.post(url, data=data, headers=get_device_headers(), proxies=proxies, verify=verify)
    check(resp, 201)
    js = resp.json()
    return js["cid"]

def create_observations(account_id, device_id, cid, val):
    url = "{0}/data/{1}".format(base_url, device_id)
    body = {
        "accountId": account_id,
        "data": []
    }
        o = {
            "componentId": cid,
            "value": str(val),
            "attributes": {
                "i": i
            }
        }
        body["data"].append(o)
    data = json.dumps(body)
    resp = requests.post(url, data=data, headers=get_device_headers(), proxies=proxies, verify=verify)
    check(resp, 201)

def get_observations(account_id, device_id, component_id):
    url = "{0}/accounts/{1}/data/search".format(base_url, account_id)
    search = {
        "from": 0,
        "targetFilter": {
            "deviceList": [device_id]
        },
        "metrics": [
            {
                "id": component_id
            }
        ]
    }
    data = json.dumps(search)
    resp = requests.post(url, data=data, headers=get_user_headers(), proxies=proxies, verify=verify)
    check(resp, 200)
    js = resp.json()
    return js

def print_observation_counts(js): 
    if 'series' in js:
        series = js["series"]
        series = sorted(series, key=lambda v: v["deviceName"])
        for v in series:
            print "Device: {0} Count: {1}".format(v["deviceName"], len(v["points"]))

if __name__ == "__main__":
    main()

现在我们来绘制一些测量数据。图表显示了传感器在不同时间测量的距离(厘米)。

至此,我们已经完成了使用物联网分析工具绘制上传的测量距离数据。现在我们将使用物联网分析来确定发送到云端的最小和最大距离(厘米),并得到下图。

总之,我们已经证明 Intel 物联网分析是一个简单便捷的工具,用于存储和分析从连接到 Intel® Galileo 或 Intel® Edison 主板的传感器获得的数据。

相关文章与资源

关于作者

Vitaliy Kalinin 在 Intel 公司软件与服务集团工作。他是俄罗斯下诺夫哥罗德市洛巴切夫斯基国立大学的博士生。他拥有经济学与数学学士学位,以及应用经济学与信息学硕士学位。他的主要兴趣是移动技术和游戏开发。

Intel® 物联网开发者中心

立即开始创新!Intel® 物联网开发者计划提供知识、工具、套件以及专家社区,助您快速轻松地将您的创新想法转化为物联网解决方案。

Dream it, Build it,使用适用于 Intel® Edison 和 Intel® Galileo 平台的 Intel® 物联网开发者套件。这些套件功能强大、性能优化且完全集成的端到端物联网解决方案,支持各种编程环境、工具、安全、云连接和硬件。

如需更多资源并了解新的 Intel® 物联网开发者套件 v1.0 如何帮助您简化物联网项目

© . All rights reserved.