Intel Edison Intel IoT Analytics Cloud: Sending SMS and RESTful Client on ASP.NET

  • Tutorial
Intel IoT Analytics
The final part of working with the Intel IoT Analytics Cloud . Adding sending SMS notifications using HTTP gateways and creating a simple RESTful client on ASP.NET. Summarizing.

Sending SMS notifications using an HTTP gateway
In a previous work by Intel Edison. Working with the Intel IoT Analytics cloud: creating rules and sending notifications; rules have been formed that allow you to send: an e-mail notification and manage the relay power. Sending SMS messages, add to these two rules created.
Rules:
  • Higth_temp_PowerOnRelay_and_send_to_web@devdotnet.org
  • Low_temp_PowerOffRelay_and_send_to_web@devdotnet.org

We will use smsc.ru SMS gateway . The API is available here .

To send an SMS message, it is enough to generate and send a GET request of the form:

smsc.ru/sys/send.php?login=&psw=&phones=&mes= , where:
login - Client's login
psw - Client's password or MD5 password hash in lower case.
phones - Number in international format without the sign "+"
mes - Text of the message to be sent.
There is no need to add Head headers, everything is very simple.

We will form two requests:
smsc.ru/sys/send.php?login=tele **** & psw = d46d70eb6 ****** & phones = 79232 ****** & mes = Relay_power_ON
smsc.ru/sys/send. php? login = tele**** & psw = d46d70eb6 ****** & phones = 79232 ****** & mes = Relay_power_OFF Go
to the Rules section , open the Higth_temp_PowerOnRelay_and_send_to_web@devdotnet.org rule .

Add Notifications type - HTTP Endpoint and enter the URL .
Intel IoT Analytics

Also, we will make Low_temp_PowerOffRelay_and_send_to_web@devdotnet.org for the second rule .

Received SMS on the phone
Intel IoT Analytics

From the minus of the function of sending SMS messages, it should be noted that there is no possibility of sending dynamic data, for example, you can not send the current sensor reading.

Simple RESTful client on ASP.NET Razor We will
form a page displaying the current sensor readings: temperature and pressure. On the page we will place the control part: turning on the relay and the LED. Cloud API is available here . Implementation on ASP.NET Razor netf 4.5. To work with JSON, the Newtonsoft.Json library is used. The Web.config file contains the login and password for accessing the cloud. The example is not a complete solution, but a simple demonstration of the use of the API.

As usual, we get the token, a section in the wiki Authorization :
The code
string GetNewToken()
            {
                //чтение login и pass
                string strLogin, strPass;
                strLogin = System.Configuration.ConfigurationManager.AppSettings["Login"];
                strPass = System.Configuration.ConfigurationManager.AppSettings["Pass"];
                //авторизация, получение токена.
                //https://github.com/enableiot/iotkit-api/wiki/Authorization
                //структура JSON
                var obj = new
                {
                    username = strLogin,
                    password = strPass
                };
                string postData = JsonConvert.SerializeObject(obj, Formatting.Indented);
                //HttpWebRequest
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("https://dashboard.us.enableiot.com/v1/api/auth/token");
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/json";
                //
                byte[] byte1 = System.Text.Encoding.UTF8.GetBytes(postData);
                httpWebRequest.ContentLength = byte1.Length;
                httpWebRequest.GetRequestStream().Write(byte1, 0, byte1.Length);
                httpWebRequest.GetRequestStream().Close();
                //
                StreamReader reader = new StreamReader(httpWebRequest.GetResponse().GetResponseStream());
                JObject objResponse = JObject.Parse(reader.ReadToEnd());
                return (string)objResponse["token"];
            }


Reading data, section in the wiki Data-API :
The code
void GetStateSensors(string strToken, Dictionary dicSensors)
            {
                //чтение данных
                //https://github.com/enableiot/iotkit-api/wiki/Data-API
                //структура JSON
                var obj = new
                {
                    from = -20,
                    targetFilter = new { deviceList = new[] { "9e-8d-22-0c-50-7b" } },
                    metrics = new[] { new {
						id="99fb5b73-a9e2-4ae0-8a0d-45e6a7cc0541",
						op="none"
					},
                    new {
						id="b3731f8a-4f31-414d-a072-b364b1792b5b",
						op="none"
					}
				}
                };
                string postData = JsonConvert.SerializeObject(obj, Formatting.Indented);
                //HttpWebRequest
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("https://dashboard.us.enableiot.com/v1/api/accounts/4c8c6b2e-c54f-4df5-8bbb-a5e59df85aaa/data/search");
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/json";
                //Headers
                httpWebRequest.Headers.Add("Authorization", "Bearer " + strToken);
                httpWebRequest.Headers.Add("accountId", "4c8c6b2e-c54f-4df5-8bbb-a5e59df85aaa");
                //
                byte[] byte1 = System.Text.Encoding.UTF8.GetBytes(postData);
                httpWebRequest.ContentLength = byte1.Length;
                httpWebRequest.GetRequestStream().Write(byte1, 0, byte1.Length);
                httpWebRequest.GetRequestStream().Close();
                //
                StreamReader reader = new StreamReader(httpWebRequest.GetResponse().GetResponseStream());
                JObject objResponse = JObject.Parse(reader.ReadToEnd());
                //add Dic
                string strValueSensor = (string)objResponse["series"][0]["points"][0]["value"];
                dicSensors.Add("pressure", strValueSensor);
                strValueSensor = (string)objResponse["series"][1]["points"][0]["value"];
                strValueSensor = Math.Round(decimal.Parse(strValueSensor, System.Globalization.CultureInfo.CreateSpecificCulture("en")), 2).ToString();
                dicSensors.Add("temperature", strValueSensor);
            }


Interface
Intel IoT Analytics

Summary
A cloud for data collection frees you from building your infrastructure, which reduces the cost of buying hardware and software. Configuring devices, sensors is very simple. The developed API allows not only receiving data and managing the device, but also creating its own administration panel. Data is transmitted without significant delays, requests are not lost. Two roles are available: administrator and user. To add a user, the administrator needs to specify a new email, and an invitation letter will be sent to this address. In the process of registering a new user, the user will be asked about accepting an invitation to access (invite). Thus, the user himself is in charge of managing his account, enable password changes. Of the flaws it is impossible to include sensor readings in the SMS message, only a pre-prepared template. For email, there are no templates, only a standard view with a sensor reading plate. Another feature was discovered, consisting in the sequence of processing rules. Sometimes a situation was observed with the relay turned off immediately after switching on. Moreover, according to the logic of the relay, it was supposed to turn off only after the temperature dropped below 28 C. The conditions of the logic of rules and the code on the device did not contain errors. The situation was resolved by viewing the alert log, new alerts are added to the end of the list. Sometimes a situation was observed with the relay turned off immediately after switching on. Moreover, according to the logic of the relay, it was supposed to turn off only after the temperature dropped below 28 C. The conditions of the logic of rules and the code on the device did not contain errors. The situation was resolved by viewing the alert log, new alerts are added to the end of the list. Sometimes a situation was observed with the relay turned off immediately after switching on. Moreover, according to the logic of the relay, it was supposed to turn off only after the temperature dropped below 28 C. The conditions of the logic of rules and the code on the device did not contain errors. The situation was resolved by viewing the alert log, new alerts are added to the end of the list.
Intel IoT Analytics
Event 39 was the last one to operate, although it preceded event 38 in time. The relay turned on for a second, and turned off, despite a further increase in temperature. Perhaps this is due to the service not yet completed. Currently, the Intel IoT Analytics cloud is in development (BETA status).

Application
Test working version of web.devdotnet.org .
The project is available here .
Source
web.config


index.cshtml
@using System.Net.Http
@using Newtonsoft.Json
@using Newtonsoft.Json.Linq
@{
    //Проверка токена в Session
    string strToken;
    strToken = (string)Session["Token"];
    if (strToken == null)
    {
        strToken = GetNewToken();
        Session["Token"] = strToken;
    }
    //Action
    if (Request["command"] != null)
    {
        string strCommand = (string)Request["command"];
        SetSateActuation(strToken,strCommand);
    }
    //Чтение данных Sensors
    Dictionary dicSensors = new Dictionary();
    GetStateSensors(strToken, dicSensors);
    //Чтение данных Actuation
    bool boolValueLED, boolValueRelay;
    GetStateActuations(strToken, out boolValueLED, out boolValueRelay);
}
        @functions {
            // Pass a user name to this method.
            string GetNewToken()
            {
                //чтение login и pass
                string strLogin, strPass;
                strLogin = System.Configuration.ConfigurationManager.AppSettings["Login"];
                strPass = System.Configuration.ConfigurationManager.AppSettings["Pass"];
                //авторизация, получение токена.
                //https://github.com/enableiot/iotkit-api/wiki/Authorization
                //структура JSON
                var obj = new
                {
                    username = strLogin,
                    password = strPass
                };
                string postData = JsonConvert.SerializeObject(obj, Formatting.Indented);
                //HttpWebRequest
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("https://dashboard.us.enableiot.com/v1/api/auth/token");
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/json";
                //
                byte[] byte1 = System.Text.Encoding.UTF8.GetBytes(postData);
                httpWebRequest.ContentLength = byte1.Length;
                httpWebRequest.GetRequestStream().Write(byte1, 0, byte1.Length);
                httpWebRequest.GetRequestStream().Close();
                //
                StreamReader reader = new StreamReader(httpWebRequest.GetResponse().GetResponseStream());
                JObject objResponse = JObject.Parse(reader.ReadToEnd());
                return (string)objResponse["token"];
            }
            void GetStateSensors(string strToken, Dictionary dicSensors)
            {
                //чтение данных
                //https://github.com/enableiot/iotkit-api/wiki/Data-API
                //структура JSON
                var obj = new
                {
                    from = -20,
                    targetFilter = new { deviceList = new[] { "9e-8d-22-0c-50-7b" } },
                    metrics = new[] { new {
						id="99fb5b73-a9e2-4ae0-8a0d-45e6a7cc0541",
						op="none"
					},
                    new {
						id="b3731f8a-4f31-414d-a072-b364b1792b5b",
						op="none"
					}
				}
                };
                string postData = JsonConvert.SerializeObject(obj, Formatting.Indented);
                //HttpWebRequest
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("https://dashboard.us.enableiot.com/v1/api/accounts/4c8c6b2e-c54f-4df5-8bbb-a5e59df85aaa/data/search");
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/json";
                //Headers
                httpWebRequest.Headers.Add("Authorization", "Bearer " + strToken);
                httpWebRequest.Headers.Add("accountId", "4c8c6b2e-c54f-4df5-8bbb-a5e59df85aaa");
                //
                byte[] byte1 = System.Text.Encoding.UTF8.GetBytes(postData);
                httpWebRequest.ContentLength = byte1.Length;
                httpWebRequest.GetRequestStream().Write(byte1, 0, byte1.Length);
                httpWebRequest.GetRequestStream().Close();
                //
                StreamReader reader = new StreamReader(httpWebRequest.GetResponse().GetResponseStream());
                JObject objResponse = JObject.Parse(reader.ReadToEnd());
                //add Dic
                string strValueSensor = (string)objResponse["series"][0]["points"][0]["value"];
                dicSensors.Add("pressure", strValueSensor);
                strValueSensor = (string)objResponse["series"][1]["points"][0]["value"];
                strValueSensor = Math.Round(decimal.Parse(strValueSensor, System.Globalization.CultureInfo.CreateSpecificCulture("en")), 2).ToString();
                dicSensors.Add("temperature", strValueSensor);
            }
            void GetStateActuations(string strToken, out bool boolValueLED, out bool boolValueRelay)
            {
                //чтение данных Actuation
                //https://github.com/enableiot/iotkit-api/wiki/Control-Device-API
                //HttpWebRequest
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("https://dashboard.us.enableiot.com/v1/api/accounts/4c8c6b2e-c54f-4df5-8bbb-a5e59df85aaa/control/devices/9e-8d-22-0c-50-7b?from=-60000");
                httpWebRequest.Method = "GET";
                //Headers
                httpWebRequest.Headers.Add("Authorization", "Bearer " + strToken);
                httpWebRequest.Headers.Add("accountId", "4c8c6b2e-c54f-4df5-8bbb-a5e59df85aaa");
                //
                StreamReader reader = new StreamReader(httpWebRequest.GetResponse().GetResponseStream());
                JArray jArr = (JArray)JsonConvert.DeserializeObject(reader.ReadToEnd());
                //Parse data
                Dictionary dicSensorLED = new Dictionary();
                Dictionary dicSensorRelay = new Dictionary();
                long longTicks;
                foreach (JObject item in jArr)
                {
                    longTicks = DateTime.Parse((string)item["created"]).Ticks;
                    if ((string)item["command"] == "LED.v1.0")
                    {
                        if (!dicSensorLED.ContainsKey(longTicks)) dicSensorLED.Add(longTicks, (string)item["params"][0]["value"]);
                    }
                    else
                    {
                        if (!dicSensorRelay.ContainsKey(longTicks)) dicSensorRelay.Add(longTicks, (string)item["params"][0]["value"]);
                    }
                }
                //find last value
                string strValueLED = dicSensorLED[dicSensorLED.Max(x => x.Key)];
                string strValueRelay = dicSensorRelay[dicSensorRelay.Max(x => x.Key)];
                //
                if (strValueLED == "0") boolValueLED = false; else boolValueLED = true;
                if (strValueRelay == "0") boolValueRelay = false; else boolValueRelay = true;
                }
            void SetSateActuation(string strToken, string strCommand)
            {
                //отправка команды Actuation
                //https://github.com/enableiot/iotkit-api/wiki/Control-Device-API
                //разбор команды
                string strComponentId, strName, strValue, strComplexCommands;
                switch (strCommand)
                {
                    case "led_on":
                        {
                            strComponentId="64dbdbee-e181-403f-8b51-0872e11a289e";
                            strName="LED";
                            strValue = "1";
                            strComplexCommands = "led1_ON";
                            break;
                        }
                    case "led_off":
                        {
                            strComponentId = "64dbdbee-e181-403f-8b51-0872e11a289e";
                            strName = "LED";
                            strValue = "0";
                            strComplexCommands = "led1_OFF";
                            break;
                        }
                    case "relay_on":
                        {
                            strComponentId = "5f72e39a-463a-4e57-bac7-9b32debfd865";
                            strName = "RELAY";
                            strValue = "1";
                            strComplexCommands = "relay1_ON";
                            break;
                        }
                    case "relay_off":
                        {
                            strComponentId = "5f72e39a-463a-4e57-bac7-9b32debfd865";
                            strName = "RELAY";
                            strValue = "0";
                            strComplexCommands = "relay1_OFF";
                            break;
                        }
                    default:
                        // You can use the default case.
                        return;
                }
                //структура JSON
                var obj = new
                {
                    commands = new[] { new {
                    componentId = strComponentId,
                    parameters= new[] { new
                                        {
                                            name=strName,
                                            value=strValue
                                        }
                    },
                    transport="ws"
                }
                },
                    complexCommands = new[] { strComplexCommands }
                };
                string postData = JsonConvert.SerializeObject(obj, Formatting.Indented);
                //HttpWebRequest
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("https://dashboard.us.enableiot.com/v1/api/accounts/4c8c6b2e-c54f-4df5-8bbb-a5e59df85aaa/control");
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/json";
                //Headers
                httpWebRequest.Headers.Add("Authorization", "Bearer " + strToken);
                httpWebRequest.Headers.Add("accountId", "4c8c6b2e-c54f-4df5-8bbb-a5e59df85aaa");
                //
                byte[] byte1 = System.Text.Encoding.UTF8.GetBytes(postData);
                httpWebRequest.ContentLength = byte1.Length;
                httpWebRequest.GetRequestStream().Write(byte1, 0, byte1.Length);
                httpWebRequest.GetRequestStream().Close();
                //
                httpWebRequest.GetResponse();
                }
            }
        }
        
        
            Пример RESTful клиента для Intel IoT Analytics на ASP.NET Razor

Пример RESTful клиента для Intel IoT Analytics на ASP.NET Razor

Сегодня: @DateTime.Now.ToString()

Пример демонстрирует использование api облака intel iot analytics.

Из функций API используется:

  1. Авторизация, получение токена
  2. Чтение данных с датчиков(sensor)
  3. Отправка управляющих команд (Actuation)

Состояние датчиков

Температура: @dicSensors["temperature"] *С

Давление: @dicSensors["pressure"] Па

@if (boolValueLED==false) {

LED: OFF

} else {

LED: ON

} @if (boolValueRelay == false) {

Реле: OFF

} else {

Реле: ON

}

Управление Actuation

LED:

Реле:



Table of contents
  1. Intel Edison First start
  2. Intel Edison Working with the Intel IoT Analytics Cloud: Logging and Sending Data
  3. Intel Edison Work with Intel IoT Analytics Cloud: Create Rules and Send Notifications
  4. Intel Edison Intel IoT Analytics Cloud: Sending SMS and RESTful Client on ASP.NET

Also popular now: