Wednesday 25 November 2020

Azure SQL EDGE - Advantages

 

Introduction

Azure has introduced a new service called “Azure SQL Edge” which facilitates the containerized hot storage capability at EDGE itself. As per the documentation “Azure SQL Edge is an optimized relational database engine geared for IoT and IoT Edge deployments”. This tool is really enriching the concept of intelligent edge and distributed processing by proving a wonderful option to a store high-speed stream of data to a tabular shape. Azure-SQL-Edge is using the same engine of SQL server with streaming capability.

Ref: https://docs.microsoft.com/en-us/azure/azure-sql-edge/release-notes


 Major Storage Challenge

Using Azure IoT Edge architecture, we can develop any type of application, which can run in Linux and windows. This containerized architecture is capable to handle the remote management of modules. Even though we are able to utilize efficient programming capability, we need to depend on an internet connection to send and receive data from the cloud system. In the case of IoT, we are dealing with high-frequency data, processing can only be effective if we store the relevant data at EDGE. The file storage at EDGE was not effective from many perspectives.

 Microsoft SQL Server

Microsoft SQL Server is a popular relational database system developed by Microsoft. MS SQL Server is widely using in many heavy data centric application. It is possible to access MS SQL server instance, which is running on premise to read and write data from an IoT EDGE Module. In such case, the SQL instance need to be managed separately.

Implemented Use case

Need to read 10 OPC tags from an OPC Server, which are changing in the 100 millisecond frequency. These tags are required to store to an SQL database at EDGE (AzureSQLEdge). 10 messages are expecting per second. It is required to find the average value of these 10 tags for 10 seconds and that average values need to send to the cloud.

OPC Tags: 10 Tags

One Message (10 Tags): 2 KB

Expected Volume: One OPC Tag will be changing 20 times in a second.

For 10 tags, 200 messages per second.

Azure SQL EDGE – On Deployment



 

OPCServer

A Kepware OPC server is set up in an Azure VM to generate OPC data. 10 tags are configured with 100-millisecond data change frequency. Required port to communicate to this OPC server (Port 49320) is opened in windows firewall and Azure VM firewall. For this this trial I have not enabled the certificate based communication in Kepware. It is in “Non” state. In general, the opc server’s connection url will look like as below.

opc.tcp://<IP Address of VM>:<Port number>

 OPC Reader

I used the Microsoft “opcpublisher” 2.5.3 IoT Edge module as an OPC Reader. This is an IoT EDGE Module, which can interact with the OPC Server in “pub/sub” mode. The connection string and tag names need to add to this module’s configuration file. Container create option of “opcreader” module is as below

{

"Hostname": "opc-publisher",

"Cmd": [

"--pf=/<user folder>/pn.json",

"--tc=/<user folder>/telemetryconfiguration.json",

"--aa",

"--di=10",

"--si=0",

"--ms=0",

"--mq=24000"

],

"HostConfig": {

"Binds": [

"/var/iiotedge:/appdata"

],

"LogConfig": {

"Type": "json-file",

"Config": {

"max-size": "100k",

"max-file": 3

}

}

}

}

The output of this module is a flat json array of below structure

[{

"tag": "RCTR_TEMP",

"tagval": 124.25,

"tagtime": "2020-11-18T11:45:20.0000000Z"

}, {

"tag": "M1_FLWRATE",

"tagval": 108.00000000000003,

"tagtime": "2020-11-18T11:45:20.0000000Z"

}]

 AzureSQLEDGE



This is the Azure Market place module for Azure SQL EDGE. Please refer this link to get the direction to deploy this module from Azure Market Place. During deployment below details are required


Environment Variables



Variable Name

Value

ACCEPT_EULA

Y

MSSQL_SA_PASSWORD

<Password>

MSSQL_LCID

1033

MSSQL_COLLATION

SQL_Latin1_General_CP1_CI_AS



Container Create Option

{

"HostConfig": {

"CapAdd": [

"SYS_PTRACE"

],

"Binds": [

"sqlvolume:/sqlvolume"

],

"PortBindings": {

"1433/tcp": [

{

"HostPort": "1433"

}

]

},

"Mounts": [

{

"Type": "volume",

"Source": "sqlvolume",

"Target": "/var/opt/mssql"

}

]

},

"Env": [

"MSSQL_AGENT_ENABLED=TRUE",

"ClientTransportType=AMQP_TCP_Only",

"PlanId=asde-developer-on-iot-edge"

]

}

Based on deployment, EDGE will download the latest image from the Microsoft container registry and will create the module. By default, SQL is using port 1433 for establishing the connection.

 SQL Server Management Studio


https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver15

SQL Server Management Studio (SSMS) is an integrated environment for managing any SQL infrastructure, from SQL Server to Azure SQL Database. SSMS provides tools to configure, monitor, and administer instances of SQL Server and databases. Use SSMS to deploy, monitor, and upgrade the data-tier components used by your applications, and build queries and scripts.

In my case, I have used one another Windows VM and have installed the SSMS in that VM. After it is required to open the port 1433 port in windows firewall of windows VM. Network inbound and outbound port rules should be opened in a windows machine and EDGE VM.




The Azure SQL Edge is behaving similar to a local SQL Database instance and SSMS can provide a better development experience when we need to design the tables, but this is not a mandatory tool to set up the SQL EDGE.

Set Up SQL EDGE

There are few objects required to setup sequentially to create a streaming job. Once the streaming created, the streaming job can insert the input data to the SQL server tables. The objects required to create a streaming job is mentioned below.

  1. MASTER KEY ENCRYPTION

Query

CREATE MASTER KEY ENCRYPTION BY PASSWORD = '<Your Password>';

The database master key is a symmetric key used to protect the private keys of certificates and asymmetric keys that are present in the database. When it is created, the master key is encrypted by using the AES_256 algorithm and a user-supplied password.

  1. EXTERNAL FILE FORMAT

Query

If NOT Exists (select name from sys.external_file_formats where name = 'JSONFormat')

Begin

CREATE EXTERNAL FILE FORMAT [JSONFormat]

WITH ( FORMAT_TYPE = JSON)

End

  1. EXTERNAL DATA SOURCE

Query

If NOT Exists (select name from sys.external_data_sources where name = 'EdgeHub')

Begin

Create EXTERNAL DATA SOURCE [EdgeHub]

With(

LOCATION = N'edgehub://'

)

End

  1. External Stream - Input

Query

If NOT Exists (select name from sys.external_streams where name = 'opcInput')

Begin

CREATE EXTERNAL STREAM opcInput WITH

(

DATA_SOURCE = EdgeHub,

FILE_FORMAT = JSONFormat,

LOCATION = N'opcMeasures'

)

End



  1. DATABASE SCOPED CREDENTIAL

Query

If NOT Exists (select name from sys.database_scoped_credentials where name 'SQLCredential')

Begin

set @query = 'CREATE DATABASE SCOPED CREDENTIAL SQLCredential

WITH IDENTITY = ''sa'', SECRET = ''' + @SQL_SA_Password + ''''

Execute(@query)

End



  1. External Data Source

Query

If NOT Exists (select name from sys.external_data_sources where name = 'LocalSQLOutput')

Begin

CREATE EXTERNAL DATA SOURCE LocalSQLOutput WITH (

LOCATION = 'sqlserver://tcp:.,1433',CREDENTIAL = SQLCredential)

End

  1. External Stream – Output

Query

If NOT Exists (select name from sys.external_streams where name = 'opcOutput')

Begin

CREATE EXTERNAL STREAM opcOutput WITH

(

DATA_SOURCE = LocalSQLOutput,

LOCATION = N'pocdb.dbo.opcrawtelemetry'

)

End


  1. Create Stream Job

Query

EXEC sys.sp_create_streaming_job @name=N'opcdata',

@statement= N'Select i.tag as tag,i.tagval as tagval,i.tagtime as tagtime INTO opcOutput from opcInput i'


  1. Start Stream Job

Query

exec sys.sp_start_streaming_job @name=N'opcdata'

Once these steps are completed, we can route the message from the message generator to this SQLEdge module, and it is required to make sure the columns specified in the step 8 is available in the messages.

 Statistics

    EDGE Hardware

            Type: Azure VM

            OS: Ubuntu 18.04 LTS

            Spec: D2s V3

            RAM: 8 GB

            Vcpus : 2


    Data Used

            Number of OPC Tags used: 10 Tags

            Tag changing frequency: 100 millisecond

            Message size per Tag: 105 Byte

            Messages per Tag per second: 10 messages

            Total Number of messages per second: 100 messages

            Number of messages inserted to SQLEdge: Approximately 2million rows                      (1988976)

            Average latency during insert: 234 milliseconds

            Searching latency: xxxx <WIP>

            Data persistence: Yes in Docker volume. By default, it is configured to                 store the data files to the             physical location and removing and                 adding the SQLEdge module will not lead to data miss.                                       Volume mounting path should be same while re-deploying the module.

 Pricing of Azure SQL EDGE

        https://azure.microsoft.com/en-us/pricing/details/sql-edge/

PAY AS YOU GO

1 YEAR RESERVED

3 YEAR RESERVED

$10.001/device/month

$100/device/year

$60/device/year


 The Conclusion

 AzureSQLEdge is a promising feature providing by Azure. This can very well act as storage at EDGE side and can interact with various modules and other on premises applications. Along with the characteristics of SQL Server, this is having the capability to ingest high frequent data stream as well.

Thursday 8 August 2019

IoT EDGE simplified using Azure

IoT EDGE Simplified using Azure

Youtube video part 1 : https://youtu.be/e6Qo0fABPrc
Youtube video part 2 : https://youtu.be/IJ06JRosTMo
Youtube video part 3 : https://youtu.be/91_QPyKt6JI


Azure EDGE-First Version (Azure IoT devices)

Microsoft Azure is providing combination of cloud and “device-sdk” to develop EDGE side software, cloud side ingestion and processing services to develop IoT projects. Using the first version of sdk, we can design the EDGE software which can communicate to various sensors and real time data sources. The EDGE software would be a single application in which the different communication methods need to be programmed based on the nature of sensors/sources.


If there is any issue in the EDGE software, the software itself or its library files need to be updated. In IoT projects, the field gateways are not monitored physically on regular basis, which is not practically possible. Any manual operation on the field gateway are costly and time consuming. As the EDGE software is a single application, we may need to update the entire edge software in the case of minor issues.


So it is required to update the EDGE software remotely. Remotely means, the administrators who can monitor the gateway should be able to control the gateway, and using a command, the gateway should download the software from a cloud/external repository and it should update its-own similar to our mobile phone OS upgrade.


Have you done OS upgrades of your cell-phone? We would be facing suspicious minutes till we get our mobile phone’s home screen and its data  back when we are upgrading it right?

All these process of download and upgrade the software by its own is a risky activity and this is a real challenge. Any issue while upgrading the gateway software may lead to complete data loss or device software crash. If the device’s EDGE software is not in a state to respond to the commands from cloud system, a manual operation is required to set it back.


Azure EDGE-V2 (Azure IoT Edge)
In the second version, Azure is providing a better option which is known as IoT Edge. 
The EDGE software can be programmed and containerized. EDGE software need to be designed in ‘module’ wise. That means, rather than developing the EDGE software as a single program to communicate to all type of sensors or machines, we can develop one module for one type of sensors/data source. One module to communicate to one source of MODBUS registers (Slave).

Another module to communicate to one type serial temperature sensor. If we need to manage multiple MODBUS sensors, we need to use multiple instances of MODBUS modules in the gateway with different names. Here I am trying to elaborate a simple use case which is understandable to any readers. The end to end solution preparation is also trying to cover here and how can we develop an end to end solution which can be controlled from cloud. I am trying to list down the major challenges also here. Some portion of my code also provided for the technical readers.






Use Case Implementation

Smart plug

We are building a smart AC plug which can be used to power electrical equipment like table fan. This smart plug can be controlled from anywhere through internet. This can be monitored using an interface.

Expectation

One smart plug is considered as a single device. Each device is connected to a gateway. User can control and monitor each smart plug using an interface software. User need to know the health of gateway to device connection as well.

The design

We can use Azure IoT Edge module to manage the device from the gateway. NodeMCU can be used as a controller to control the AC flow to the smart plug. Gateway and NodeMCU can be connected using WiFi.
 The target to achieve ?
 Need a solution to control an electrical equipment like a table FAN remotely.
Expectations

User need to interact to the gateway using user interface. Based on the device management commands from cloud, the gateway should be able to control the device connected to it. The user should be able to know the health of gateway to device connection.

 The design / plan
We can use Azure IoT Edge module to manage the device from the gateway. NodeMCU is planned to use as a device. Gateway and NodeMCU can be connected using a common WiFi router.


 Module twin properties
Module twin desired properties would be used to communicate the device management commands to EDGE Module. All the device controls are passing using the device desired property. Module twin reported property is using to communicate all the device level status to the cloud. EDGE module would be updating the reported property of module twin when there is an update in the device status. This reported property can be read from cloud side.

Heart-beat to know gateway-device link

NodeMCU will be sending the heart beat with the device status in JSON format to gateway as an MQTT message to “Out-topic” topic. Gateway is keeping track on for the last heart beat time from a device, once received the heartbeat, gateway will update the last heartbeat received time. If the heartbeat from a device is not received till to a specific time, gateway will update the status in its reported property and then the cloud can read it.

 Setting up Azure
1. Create IoT hub in Azure portal under your subscription.
2. Create an IoT EDGE device with name “device1”


Setting up the gateway

1. Install Ubuntu 16 OS in gateway.
2. Install IoT EDGE run time in Gateway. (https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/iot-edge/how-to-install-iot-edge-linux.md)
3. Configure the /etc/iotedge/config.yaml file by adding the IoT device connection string from Azure portal.
4. Install Mosquitto broker in gateway.
http://www.steves-internet-guide.com/install-mosquitto-linux/
Test the gateway for mosquito installation with the below command.
Open a terminal and type
mosquitto_sub –t “test”
Open another terminal and type
mosquitto_pub –t “test” –m “testing message”
You can the messages in the subscribing screen, if the installation is proper.

Setting up NodeMCU
We can program the Node MCU using Arduino editor. Use the below link to install Node MCU board to Arduino editor. 
https://www.teachmemicro.com/intro-nodemcu-arduino/
Develop NodeMCU program
  1. One of output PIN (D2) of NodeMCU along with its inbuilt LED is using for this program.
  2. NodeMCU need to publish the heat beat to the gateway as an MQTT message in an
  3. interval of 2 seconds.
  4. The heart beat is a JSON message of the status of the inbuilt -LED.
  5. NodeMCU will be subscribing to the gateway on a topic “test1”.
  6. If the gateway is receiving the control command of the device(ON/OFF), the gateway
  7. will be publishing that to the topic test, which is subscribing by the NodeMCU.
A key name “SWITCH” is used to indicate the required status of the NodeMCU pin D2.
Eg: {SWITCH:0}
NodeMCU will be subscribing this message from the topic, and it will “low” the signal
on the pin D2, and inbuilt LED also indicate the status of D2 pin.
[Inbuilt LED will glow if signal is “low” and LED will off, if signal is “high”]

Controlling AC supply using NodeMCU

A relay circuit is using to control AC supply. This relay is controlled by the output pin
D2 of NodeMCU.
NodeMCU D2 pin ----------> IN pin of relay.
NodeMCU 3v3 pin ---------> VCC of relay.
NodeMCU GND pin --------> GND of relay.
AC Socket has to go through the relay, and preferably connect phase of AC.


Develop IoT Edge Module – Hot eye


Have used VS Code and Ubuntu 18 for this purpose.
The installation steps
https://docs.microsoft.com/en-us/azure/iot-edge/how-to-vs-code-develop-module


Below are the important methods implemented in this IoT EDGE module


1. static Task OnDesiredPropertiesUpdate(TwinCollection desiredProperties,object userContext) 
Static variables are used to store the desired property values fromThis is the method which is listening for any “Desiredproperty” changes. 
module twin using this method.

2. await
ioTHubModuleClient.UpdateReportedPropertiesAsync(reportedProperties);
This method is used to update the reported properties with the
connection status.

3. Publish message to topic “outtopic”
The topic name is passing through the desired properties, and the
commands to the NodeMCU is sending as message to the “outtopic”

4. Subscribe from topic “intopic”
The topic name is passing through the desired properties, and the
NodeMCU is sending the status as heartbeat to this topic.

5. RunAsync : This method will run continuously and the delay between two
consecutive heartbeat is mentioned in this.

Develop an Interface to manage

Developed an interface to manage all the operation on device. This windows application is developed in C#, using windows forms.
Below are the functionalities


Below are the functionalities


1. Deploy a module.
2. Un install all the modules.
3. Set configurations.
4. Control button to “SWITCH-ON and SWITCH-OFF” smart plug.
5. Know the status of “edgeHub”, “edgeAgent”
6. Know the status of “Hot-eye” module.

7. Know the status of gateway to device link.




The major Azure APIs and methods used




1. To deploy a new module to device Azure API 

https://<>/devices/edgedevice100/applyConfigurationContent?apiversion=2018-06-30 

2. To update Module twin https://IOT-Kochi3.azure-devices.net/twins/edgedevice100/modules/manumodule7?apiversion=2018-06-30 

3. RegistryManager.CreateFromConnectionString(connectionString); 

4. registryManager.CreateQuery("SELECT * FROM devices.modules where deviceId=xxx”,100); 5. await query.GetNextAsTwinAsync(); 

The user can click the “SWITCH” button and then this interface will update the moduletwin desired property “SWITCH” to 1. Azure will sync this desired property to the device. In device, the module will get a callback (OnDesiredPropertiesUpdate). This method will send a message to the outtopic in JSON format. {SWITCH:1}

The NodeMCU which is subscribing to this topic can get this message and NodeMCU will enable the D2 pin with high voltage, and after that Node MCU will send heartbeats to “intopic” in JSON {SWITCHDEVICESTATUS:1}. The relay circuit connected to the Node MCU will get closed and the AC power will flow to the AC socket of the smart plug.


Reference links

 https://docs.microsoft.com/bs-latn-ba/azure/iot-edge/iot-edge-runtime 
 https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/iot-edge/how-toinstall-iot-edge-linux.md 
 http://www.steves-internet-guide.com/install-mosquitto-linux/ 
 https://www.teachmemicro.com/intro-nodemcu-arduino/ 
 https://docs.microsoft.com/en-us/azure/iot-edge/how-to-vs-code-develop-module

Important Linux commands required during development and deployment


sudo systemctl restart iotedge 
sudo journalctl -f -u iotedge 
sudo iotedge list 
sudo iotedge check 
sudo iotedge logs <> -f