Based on China-based Internet IoT development — based on .NET SDK package

Recently, the concept of the Internet of Things is relatively popular. A large number of manufacturers are rushing to occupy the level of the Internet of Things, including Huawei Internet of Things, Alibaba Cloud Internet of Things, Tencent Internet of Things, AWS Internet of Things, and so on. To enumerate, the general Internet of Things includes device-side development, platform-side development, and application-side development. The three parts constitute a complete online and offline connection. Unlike our conventional WeChat application and Dingding application, the terminal of the Internet of Things is composed of various A combination of a variety of devices, these devices are connected to the IOT platform through various protocols (such as CoAP, LWM2M, MQTT), and these devices are low-energy devices that can send data in real time, and can also accept Various operating instructions issued from the IOT platform. This essay mainly introduces the application development based on Huawei Internet of Things IOT, realizes the encapsulation of the .net SDK, and facilitates later application integration.

1. Introduction to the Internet of Things

The Internet of Things is actually a bit similar to the access of some industry equipment that we have done before, but it is relatively generalized and can be connected to various The same type of equipment, more secure, low energy consumption, etc., we used to access many equipment, may need to use the TCP/UDP protocol, and then there is a Socket server for these equipment management in the back-end server, but compared with the Internet of Things, these They have been completely remodeled to adapt to more application scenarios, simplify development, and support more powerful functions.

Currently, the Internet of Things can collect some specific parameters for some sensors, such as light perception, temperature, humidity, pressure, voltage, current and other conventional information. It can also be extended to achieve voice, image, video and other aspects. Acquisition and processing, such as classic smart street lamp application scenarios.

The following is the architecture design of one of the applications, mainly for the management of these devices. The Internet of Things also provides a lot of complete application API interfaces, so that we can more simplify the management of the devices (without setting up Socket services ), more convenient to obtain the corresponding information through the API, saving more maintenance costs.

share picture

The Internet of Things platform supports a large number of devices to connect to the cloud, and the device and the cloud can achieve stable and reliable two-way communication.

  • Provide device-side SDK, driver, software Packages, etc. help different devices and gateways to easily access the IoT cloud.
  • Provide 2G/ 3G /4G, NB-IoT, LoRa, WiFi and other different network equipment access solutions to solve enterprise heterogeneous networks Pain points of device access management.
  • The device-side SDK that provides multiple protocols such as MQTT, CoAP, HTTP/S, etc., not only meets the real-time requirements of long connections, but also Meet the low power consumption requirements of short connections.
  • Open source code for devices on multiple platforms, provide cross-platform migration guidance, and empower enterprises to access devices based on multiple platforms.

General IoT platforms will include product management, device management, device group management, rule engine management, message push and message subscription, task management, device upgrades, etc., different things Networked cloud platforms are different.

Several protocols related to the Internet of Things:

MQTT (Message Queue Telemetry Transport)

MQTT is an Internet of Things transport The protocol, designed for lightweight publish/subscribe message transmission, aims to provide reliable network services for IoT devices in low-bandwidth and unstable network environments.

MQTTS refers to MQTT+SSL/TLS, and SSL/TLS protocol is used for encrypted transmission in MQTTS.

CoAP (Constrained Application Protocol)

Constrained Application Protocol (CoAP) is a software protocol designed to enable very simple electronic devices to Interactive communication on the Internet.

CoAPS refers to CoAP over DTLS. In CoAPS, the DTLS protocol is used for encrypted transmission. [ (Including storage, power consumption, etc.) NB-IoT terminal

2, application-side development interface

The application-side development interface generally provides different cloud platforms Platform SDK, such as Alibaba Cloud Open Source provides Java SDK/C# SDK, etc.; while Huawei provides SDKs such as Java and PHP, but does not include the SDK of .net.

The application-side API interfaces of Alibaba IoT Cloud include:

Share pictures

Huawei IoT Cloud’s application-side API interface includes:

share picture

share picture

This article mainly introduces the most basic The packaging of the Internet of Things SDK to facilitate subsequent application development and integration. This essay is also mainly based on the encapsulation of Huawei’s application-side API, using C# language to realize all the encapsulation processing of the .net SDK.

For the above interface classification, we define different interface classes to handle them.

Share pictures

Basically all API access First, you need to obtain the access token through the authentication interface. The authentication interface is defined as follows.

share picture

And Huawei’s API interface requires X509 certificate processing, we can download the corresponding X509 certificate on the official website for integration test API.

In order to realize the .net SDK encapsulation of the API, we define some common system variables to facilitate the use in the interface.

share picture

According to the results returned by the authentication, we define a corresponding entity class to store these attribute information, as shown below.

 /// < /span>

/// Authentication result
///

public class AuthenticationResult: BaseJsonResult
{
///
/// The scope of application permissions, that is, the scope of the Internet of Things platform resources that the accessToken can access , The parameter value is fixed to default.
///

public string scope {get; set;}

///
/// The type of accessToken, the parameter value is fixed to Bearer.
///

public string tokenType {get; set;}

///
/// The valid time of accessToken, the parameter value is fixed at 3600 seconds
///

public int expiresIn {get; set;}

///
/// Authentication parameters, credentials for accessing the API interface of the Internet of Things platform.
///

public string accessToken {get; set;}

///
/// Authentication parameters, valid for 1 month, used for "refresh Token" interface.
/// When the accessToken is about to expire, you can click "Refresh Token "Interface to obtain a new accessToken.
///

public string refreshToken {get; set;}
}

Then according to the authentication definition, we realize the encapsulation of this interface.

 /// < /span>

/// IOT authentication interface implementation
///

public class AuthenticationApi: IAuthenticationApi
{
///
/// User authentication
/// When the application server accesses the open API of the IoT platform for the first time , Need to call this interface to complete access authentication;
/// After the application server’s certification of the IoT platform expires, You need to call this interface for re-authentication before you can continue to access the open API of the IoT platform.
///

public AuthenticationResult Authentication()
{
string postData = string.Format("appId={0}&secret={1}", Constants.AppId, Constants.Secret);
var url = Constants.AppBaseUrl + "/iocm/app/sec/v1.1.0/login";//The capitalization of the name cannot be wrong

HttpHelper helper
= new HttpHelper();
helper.ContentType
= "application/x-www-form-urlencoded ";
helper.ClientCertificates
= new X509CertificateCollection() {new X509Certificate2(Constants.CertFilePath, Constants.CertPassword) };

string content = helper.GetHtml(url, postData, true span>);
var result = JsonConvert.DeserializeObject(content);
return result;
}

For the refresh operation of Token, encapsulation is similar to the operation

 /// 

/// Refresh the token.
/// The accessToken obtained by the application server through the authentication interface is If there is a valid time, when the accessToken is about to expire,
/// The application server obtains a new accessToken by calling this interface .
///

///
/// refresh token to obtain a new accessToken. The refreshToken is obtained when the authentication interface is called or the token interface is refreshed.
///
///
public AuthenticationResult RefreshToken(string refreshToken)
{
string postData = new
{
appId
= Constants.AppId,
secret
= Constants.Secret,
refreshToken
= refreshToken
}.ToJson();
var url = Constants.AppBaseUrl + "/iocm/app/sec/v1.1.0/refreshToken";//The capitalization of the name cannot be wrong

var result = WeJsonHelper.ConvertJson(url, postData);
return result;
}

Some of the above are for the convenience of operation, and some public class libraries are defined to reduce code duplication.

Generally, all APIs except for authentication have similar processing methods. They all interact in application/json format and use POST, PUT, GET, and Delete operations to process data.

And they all need to have fixed request header information, we will introduce device registration as an example.

share picture

Generally, we can set the request information in the header of the interface through a function encapsulation, as shown below.

 /// < /span>

/// General access to header information
///

/// Interface access password
///
protected NameValueCollection GetHeader(string accessToken)
{
var header = new NameValueCollection();
header.Add(Constants.HEADER_APP_KEY, Constants.AppId);
header.Add(Constants.HEADER_APP_AUTH,
string.Format("< /span>Bearer {0}", accessToken));
return header;
}

Then define the entity class object corresponding to the requested JSON and the returned JSON, and encapsulate the corresponding API interface.

For example, the interface package of our registered device is shown below.

 /// < /span>

/// Device management interface implementation
///

public class DeviceApi: BaseCommon, IDeviceApi
{
///
/// Register the device (verification code method).
/// Before the device is connected to the IoT platform, the application server You need to call this interface to register the device on the IoT platform and set the unique identifier of the device (such as IMEI).
/// Only carry the device when the device is connected to the IoT platform Mark, complete the access authentication of the device.
///

///
///
///
public RegDeviceResult RegisterDevice(string accessToken, RegDeviceJson info)
{
var header = GetHeader(accessToken);

string postData = info.ToJson();
var url = Constants.AppBaseUrl + "/iocm/app/reg/v1.1.0/deviceCredentials";//The capitalization of the name cannot be wrong
url += string.Format("?appId={0}", Constants.AppId) ;

var result = WeJsonHelper.ConvertJson(url, postData, header);
return result;
}
......

The information requested here is RegDeviceJson, and the class of returned information is RegDeviceResult. We can implement the corresponding processing according to the API definition.

In order to facilitate processing, we can define the entity classes of these corresponding devices in a file, such as DeviceJson.cs, as shown below, which is very convenient for us to manage.

share picture

APIs in other business categories are also encapsulated in this way, so I won’t repeat them one by one.

When we test, we can create a separate Winform project to test the interface function, or we can write unit test code for testing by ourselves. Choose according to your proficiency.

For example, the authentication interface test code is as follows, we can look at the output to determine whether it is working properly.

 private void btnLogin_Click (object sender, EventArgs e)

{
var result = basicApi.Authentication();
Console.WriteLine(result
!= null? " accessToken:" + result.ToJson(): "Error getting results");

if (result != null)
{
var refreshResult = basicApi.RefreshToken(result.refreshToken);

Console.WriteLine(refreshResult
!= null? " accessToken:" + refreshResult.ToJson(): "Error getting results");
this.accessToken = refreshResult.accessToken;// Record for use
}
}

The functional test of device registration is shown below.

 private void btnRegDevice_Click (object sender, EventArgs e)

{
if (string.IsNullOrEmpty(accessToken))
{
MessageUtil.ShowTips(
"Please authenticate first to obtain AccessToken");
return;
}

var deviceApi = new DeviceApi();
var regDeviceInfo = new RegDeviceJson()
{
endUserId
= "64bf5869-b271-4007-8db8-fab185e19c10 span>",
nodeId
= "64bf5869-b271-4007-8db8-fab185e19c10 span>",
psk
= "12345678",
timeout
= 0,
verifyCode
= "",
deviceInfo
= new DeviceJson()
{
deviceType
= "Smoke",
manufacturerId
= "49ac78c99f3e453598c155870efe8bfc",
manufacturerName
= "iqidi",
//Compare with manufacturerId, manufacturerName, deviceType, model and protocolType series Choose one of two
//productId = "5d9bf49b6a018f02d04cae28",
model = "1001",
name
= "NBSimulator",
imsi
= "fafafasfasf",
mac
= "testetst",
isSecurity
= true.ToString().ToUpper(),
protocolType
= "LWM2M",
}
};

var regResult = deviceApi.RegisterDevice(accessToken, regDeviceInfo);
Console.WriteLine(regResult
!= null? regResult.ToJson(): "no regResult");
}

In addition, for event notifications, we generally perform corresponding processing passively on the application side, so we need to convert and process their messages.

share picture

For the above message notification, we need to define the corresponding message type, and then perform judgment processing.

We start a new project, and then define the corresponding event reception processing, as shown below is a unified entry processing.

share picture

With a general entry, after we convert the corresponding notification information into the corresponding entity, we can record or respond.

When we continue to develop application functions later, these corresponding interface APIs can be integrated into our system.

The above is the idea of ​​API packaging processing on the application side of the Huawei IoT platform, for your reference and communication.

 /// 

/// Authentication result
///

public class AuthenticationResult: BaseJsonResult
{
///
/// The scope of application permissions, that is, the scope of the Internet of Things platform resources that the accessToken can access , The parameter value is fixed to default.
///

public string scope {get; set;}

///
/// The type of accessToken, the parameter value is fixed to Bearer.
///

public string tokenType { get; set; }

///
/// accessToken的有效时间,参数值固定为3600秒
///

public int expiresIn { get; set; }

///
/// 鉴权参数,访问物联网平台API接口的凭证。
///

public string accessToken { get; set; }

///
/// 鉴权参数,有效时间为1个月,用于“刷新Token”接口。
/// 当accessToken即将过期时,可通过“刷新Token”接口来获取新的accessToken。
///

public string refreshToken { get; set; }
}

    /// 

/// IOT鉴权接口实现
///

public class AuthenticationApi : IAuthenticationApi
{
///
/// 用户鉴权
/// 应用服务器首次访问物联网平台的开放API时,需调用此接口完成接入认证;
/// 应用服务器在物联网平台的认证过期后,需调用此接口重新进行认证,才能继续访问物联网平台的开放API。
///

public AuthenticationResult Authentication()
{
string postData = string.Format("appId={0}&secret={1}", Constants.AppId, Constants.Secret);
var url = Constants.AppBaseUrl + "/iocm/app/sec/v1.1.0/login";//名称大小写不能错

HttpHelper helper
= new HttpHelper();
helper.ContentType
= "application/x-www-form-urlencoded";
helper.ClientCertificates
= new X509CertificateCollection() { new X509Certificate2(Constants.CertFilePath, Constants.CertPassword) };

string content = helper.GetHtml(url, postData, true);
var result = JsonConvert.DeserializeObject(content);
return result;
}

        /// 

/// 刷新token。
/// 应用服务器通过鉴权接口获取到的accessToken是有有效时间的,在accessToken快过期时,
/// 应用服务器通过调用此接口,获取新的accessToken。
///

///
/// 刷新token,用来获取一个新的accessToken。refreshToken在调用鉴权接口或刷新token接口时获得。
///
///
public AuthenticationResult RefreshToken(string refreshToken)
{
string postData = new
{
appId
= Constants.AppId,
secret
= Constants.Secret,
refreshToken
= refreshToken
}.ToJson();
var url = Constants.AppBaseUrl + "/iocm/app/sec/v1.1.0/refreshToken";//名称大小写不能错

var result = WeJsonHelper.ConvertJson(url, postData);
return result;
}

        /// 

/// 通用获取头部信息
///

/// 接口访问口令
///
protected NameValueCollection GetHeader(string accessToken)
{
var header = new NameValueCollection();
header.Add(Constants.HEADER_APP_KEY, Constants.AppId);
header.Add(Constants.HEADER_APP_AUTH,
string.Format("Bearer {0}", accessToken));
return header;
}

    /// 

/// 设备管理接口实现
///

public class DeviceApi : BaseCommon, IDeviceApi
{
///
/// 注册设备(验证码方式)。
/// 在设备接入物联网平台前,应用服务器需要调用此接口在物联网平台注册设备,并设置设备的唯一标识(如IMEI)。
/// 在设备接入物联网平台时携带设备唯一标识,完成设备的接入认证。
///

///
///
///
public RegDeviceResult RegisterDevice(string accessToken, RegDeviceJson info)
{
var header = GetHeader(accessToken);

string postData = info.ToJson();
var url = Constants.AppBaseUrl + "/iocm/app/reg/v1.1.0/deviceCredentials";//名称大小写不能错
url += string.Format("?appId={0}", Constants.AppId);

var result = WeJsonHelper.ConvertJson(url, postData, header);
return result;
}
......

        private void btnLogin_Click(object sender, EventArgs e)

{
var result = basicApi.Authentication();
Console.WriteLine(result
!= null ? "accessToken:" + result.ToJson() : "获取结果出错");

if (result != null)
{
var refreshResult = basicApi.RefreshToken(result.refreshToken);

Console.WriteLine(refreshResult
!= null ? "accessToken:" + refreshResult.ToJson() : "获取结果出错");
this.accessToken = refreshResult.accessToken;//记录待用
}
}

        private void btnRegDevice_Click(object sender, EventArgs e)

{
if (string.IsNullOrEmpty(accessToken))
{
MessageUtil.ShowTips(
"请先鉴权获取AccessToken");
return;
}

var deviceApi = new DeviceApi();
var regDeviceInfo = new RegDeviceJson()
{
endUserId
= "64bf5869-b271-4007-8db8-fab185e19c10",
nodeId
= "64bf5869-b271-4007-8db8-fab185e19c10",
psk
= "12345678",
timeout
= 0,
verifyCode
= "",
deviceInfo
= new DeviceJson()
{
deviceType
= "Smoke",
manufacturerId
= "49ac78c99f3e453598c155870efe8bfc",
manufacturerName
= "iqidi",
//与manufacturerId、manufacturerName、deviceType、model和protocolType系列参数二选一
//productId = "5d9bf49b6a018f02d04cae28",
model = "1001",
name
= "NBSimulator",
imsi
= "fafafasfasf",
mac
= "testetst",
isSecurity
= true.ToString().ToUpper(),
protocolType
= "LWM2M",
}
};

var regResult = deviceApi.RegisterDevice(accessToken, regDeviceInfo);
Console.WriteLine(regResult
!= null ? regResult.ToJson() : "no regResult");
}

Leave a Comment

Your email address will not be published.