Click here to Skip to main content
15,885,914 members
Articles / Internet of Things
Article

Intel® IoT Analytics with the Intel® Edison Board

Rate me:
Please Sign up or sign in to vote.
4.83/5 (4 votes)
15 Sep 2015CPOL5 min read 14.5K   6  
In this article I describe one of them: Intel® IoT Analytics. At the next picture illustrated the schema of working Intel IoT Analytics.

This article is for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers

Get access to the new Intel® IoT Developer Kit, a complete hardware and software solution that allows developers to create exciting new solutions with the Intel® Galileo and Intel® Edison boards. Visit the Intel® Developer Zone for IoT.

These days, smartphones, tablets, laptops are ubiquitous, allowing us to surf the Internet, check emails, and chat with friends. But people want to do more with their devices—they want to manage and monitor other computers and devices remotely. To do this, they need the ability to send and receive IoT device data via the Internet. There are several Cloud-based solutions you can use that provide this capability. In this article I describe one of them: Intel® IoT Analytics. At the next picture illustrated the schema of working Intel IoT Analytics.

Image 1

Intel IoT Analytics includes resources for the collection and analysis of sensor data that the Intel® IoT Developer Kit provides. Using this service, developers can jump­start data acquisition and analysis without having to invest in large-scale storage and processing capacity. The diagram below shows sensor data from Intel® Galileo and Intel® Edison boards being sent to the Intel IoT Analytics Cloud via the Internet for analysis on a laptop. It is a basic model of IoT Analytics use.

Image 2

Intel® Edison Board collects measurements with sensors and with configured IoT Agent send data into the cloud. To begin using the Intel IoT Analytics Dashboard, create an administrative user account that will give you the ability to register devices, manage alerts, create accounts, and perform other tasks on the site. Go to the Intel IoT Analytics Dashboard here.

To demonstrate the interaction between an IoT device and the Cloud, I’ll use the sample code from our previous article “Using microcontroller in the Intel® Edison Board”. In this article, we used the ultrasonic ranging module HC-SR04 to measure the distance to objects it detects. The resulting measurement is shown on an LCD display. We added some script to this sample to automatically transmit data to the Cloud. At the next picture there are Intel® Edison board with connected HC-SR04 sensor, the result of measurements is showed on LCD display.

Image 3

First of all, we need to register the distance sensor as a component into the cloud. To do this, fill in all required fields.

Image 4

Image 5

Now, it is necessary to register sensor on the board. Next, we register the sensor with the Intel® Edison board, using the following command on board:

iotkit-admin register dist distance.v1.0

iotkit-admin catalog

Now, our sensor is registered and assigned to this board.

To use the integer type, we define a range of values from -1 (error) to 100 centimeters.

Image 6

Sending data to the Cloud can be done one of several ways.

Perform the follow command on board:

iotkit-admin observation dist 10

But, this is not the most convenient way to send data to the Cloud. Typically, this command is used for testing.

The other two ways to transfer data to the Cloud:

To run the agent on the board use the following command:

C++
systemctl start iotkit-agent

It is possible to send messages via UDP localhost to port 41234 (UDP: // localhost: 41234). To do this, you must create a JSON-file (JavaScript* Object Notation):

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

where "n" is the name of the measurement (like distance or temperature), and "v" is the value.

For example:

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

These are some ways to send data to the Cloud via the Intel IoT Analytics iotkit-agent. You can also send data using programming languages such as C/C ++, JavaScript, or Python*. I like the concept of doing fast, convenient programming, so I wrote a small example using my favorite programming language, Python. This code gets data from sensor and automatically uploads data into IoT Analitics Cloud.

C++
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()

Now let’s chart some measurements. The chart shows the distances (in centimeters) the sensor measured at different times.

Image 7

Thus, charting uploaded data of measurement distance with IoT Analytics tool. Now we’ll use the IoT Analytics to determine the minimum and maximum distances (cm) sent to the Cloud, and we get this picture.

Image 8

In conclusion we’ve shown that the Intel IoT Analytics is a simple and convenient tool for storing and analyzing data obtained from sensors attached to Intel® Galileo or Intel® Edison boards.

Related Articles and Resources

About the Author

Vitaliy Kalinin works in the Software & Services Group at Intel Corporation. He is a PhD student at Lobachevsky State University in Nizhny Novgorod, Russia. He has a Bachelor’s degree in economics and mathematics and a Master’s degree in applied economics and informatics. His main interest is mobile technologies and game development.

Intel® Developer Zone for IoT

Start inventing today with the Intel® IoT Developer Program which offers knowledge, tools, kits and a community of experts to quickly and easily turn your innovative ideas into IoT Solutions.

Dream it, Build it with the Intel® IoT Developer Kit for Intel® Edison and Intel® Galileo platforms. These kits are versatile, performance-optimized and fully integrated end-to-end IoT solutions supporting a variety of programming environments, tools, security, cloud connectivity and hardware.

For more resources and to learn how the new Intel® IoT Developer Kit v1.0 can help streamline your IoT projects:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
You may know us for our processors. But we do so much more. Intel invents at the boundaries of technology to make amazing experiences possible for business and society, and for every person on Earth.

Harnessing the capability of the cloud, the ubiquity of the Internet of Things, the latest advances in memory and programmable solutions, and the promise of always-on 5G connectivity, Intel is disrupting industries and solving global challenges. Leading on policy, diversity, inclusion, education and sustainability, we create value for our stockholders, customers and society.
This is a Organisation

42 members

Comments and Discussions

 
-- There are no messages in this forum --