Serialization | Iot framework ServerSuperIO tutorial-12. Service Interface Development and two-way interaction with the cloud, Iot cloud Management System

Source: Internet
Author: User

Serialization | Iot framework ServerSuperIO tutorial-12. Service Interface Development and two-way interaction with the cloud, Iot cloud Management System

1. C # Introduction to cross-platform Iot communication framework ServerSuperIO (SSIO)

Serialization | Iot framework ServerSuperIO tutorial 1.4 communication modes and mechanisms.

Serialization | Iot framework ServerSuperIO tutorial 2. service instance configuration parameters

Serialization | Iot framework ServerSuperIO tutorial-3. Device Driver Introduction

Serialization | Iot framework ServerSuperIO tutorial-4. For example, you can develop a device driver that supports both serial and network communication.

Serialization | Iot framework ServerSuperIO tutorial-5. Polling communication mode development and precautions.

Serialization | Iot framework ServerSuperIO tutorial-6. concurrent communication mode development and precautions

Serialization | Iot framework ServerSuperIO tutorial-7. Self-control communication mode development and precautions

Serialization | Iot framework ServerSuperIO tutorial-8. single-instance communication mode development and precautions

Serialization | Iot framework ServerSuperIO tutorial-9. protocol filter to solve multiple packet-related, sticky packet, and redundant data

Serialization | Iot framework ServerSuperIO tutorial-10. Two Methods for continuous transmission of large data streams (such as files)

Serialization | Iot framework ServerSuperIO tutorial-11. Implement device (driver) and device (driver) interaction and cascade control.

Contents

12. Service Interface Development and two-way interaction with the cloud... 2

12.1 Overview... 2

12.2 device linker... 2

12.3 service linker... 3

12.4 scenario hypothesis... 3

12.5 device driver development and precautions... 4

12.6 service instance development and precautions... 4

12.7 host program service instance configuration considerations... 8

12.8 running effect... 9

12. Service Interface Development and two-way interaction with the cloud
12.1 Overview

Service Interface IService is a special application scenario except the device driver interface IRunDevice. For example: SMS alarms, LED output, analog data collection, OPC server/client, cascading data forwarding, and other special applications. It is a powerful extension based on the device driver interface IRunDevice, making the framework more abundant and powerful.

This article mainly introduces data forwarding and control services. Other service development is similar to this. If the development based on the ServerSuperIO service interface has the data forwarding and control capabilities, then in the IOT construction, it will have the unlimited cascade transmission and control capabilities of data, using a set of frameworks to form a set of solutions. As follows:

 

12.2 device linker

The Device Driver Interface of IRunDevice inherits the IServiceConnectorDevice interface of the service. The device driver implements the RunServiceConnector interface function, which indicates that data information transmitted from the service instance can be received or run. The code is defined as follows:

Public interface IServiceConnectorDevice {// <summary> // sub-branch device connector /// </summary> /// <param name = "fromService"> </param> // /<param name = "toDevice"> </param> // <returns> </returns> object runserviceconne( IFromService fromService, IServiceToDevice toDevice );}
12.3 service linker

The IService interface is inherited from the iserviceconneservice linker, which represents that the service has two major functions: 1. send commands or information to the device driver. 2. Receive the result of the device driver processing command or information. The Code is as follows:

Public interface IServiceConnector {/// <summary> // callback function of the device connector, write the callback processing result /// </summary> /// <param name = "obj"> </param> void ServiceConnectorCallback (object obj ); /// <summary> /// if the operator encounters an exception, returns the result of this function /// </summary> /// <param name = "ex"> </param> void ServiceConnectorCallbackError (Exception ex ); /// <summary> // connector event, initiator // </summary> event ServiceConnectorHandler ServiceConnector; /// <summary> /// interface for event confirmation /// </summary> /// <param name = "fromService"> </param> /// <param name = "toDevice"> </param> void OnServiceConnector (IFromService fromService, IServiceToDevice toDevice );}
12.4 scenario hypothesis

The device driver collects sensor data in real time, transmits the data information to the UpdateDevice interface function of the service instance through the OnDeviceObjectChanged event interface, and then caches the data. Enable the service thread, connect to the cloud service, and regularly upload sensor data information. The cloud service sends the control command: control: 1 (Note: The command controls the No. 1 encoding device), the device driver sends the command to the sensor, and finally returns the result to the service instance.

12.5 device driver development and precautions

1. pass data information to the service instance through the OnDeviceObjectChanged event. The Code is as follows:

List<string> list = new List<string>();list.Add(_devicePara.DeviceCode);list.Add(_devicePara.DeviceName);list.Add(_deviceDyn.Dyn.Flow.ToString());list.Add(_deviceDyn.Dyn.Signal.ToString());OnDeviceObjectChanged(list.ToArray());

2. receive commands and information transmitted by the service instance. The Code is as follows:

Public override object RunServiceConnector (IFromService fromService, IServiceToDevice toDevice) {Console. writeLine (this. deviceParameter. deviceName + ", receives the cloud command:" + toDevice. text); return this. deviceParameter. deviceName + ", execution completed ";}
12.6 service instance development and precautions

The main functions of a service instance are to cache data, connect to the cloud service, regularly send data, receive cloud command information, and pass it to the device driver, and receive the result of the command execution by the driver.

Public override void UpdateDevice (string devCode, object obj) {lock (_ SyncObject) {if (obj! = Null) {if (obj is string []) {string [] arr = (string []) obj; // OnServiceLog (String. format ("service: {0} receives data from '{1}' >>{ 2}, {3}", ServiceName, arr [1], arr [2], arr [3]); if (arr. length> = 2) {if (this. _ Cache. containsKey (devCode) // judge ID {this. _ Cache [devCode] = arr;} else {this. _ Cache. add (devCode, arr );}}}}}}

2. Connect to the cloud service and regularly send data. The Code is as follows:

private void Target_Service()        {            while (_IsRun)            {                try                {                    if (_tcpClient != null)                    {                        lock (_SyncObject)                        {                            string content = String.Empty;                            foreach (KeyValuePair<string, string[]> kv in _Cache)                            {                                content += String.Join(",", kv.Value) + Environment.NewLine;                            }                            if (!String.IsNullOrEmpty(content))                            {                                byte[] data = System.Text.Encoding.ASCII.GetBytes(content);                                this.OnSend(data);                            }                        }                    }                    else                    {                        this.ConnectServer();                    }                }                catch (SocketException ex)                {                    this.CloseSocket();                    OnServiceLog(ex.Message);                }                catch (Exception ex)                {                    OnServiceLog(ex.Message);                }                finally                {                    System.Threading.Thread.Sleep(2000);                }            }        }

3. Receive cloud Command Information and pass it to the device driver

Private void export ecallback (IAsyncResult ar) {TcpClient socket = (TcpClient) ar. AsyncState; try {if (socket! = Null) {int read = socket. client. endReceive (ar); if (read> 0) {// process data ..................... notification device string text = System. text. encoding. ASCII. getString (_ Buffer, 0, read); OnServiceConnector (new FromService (this. serviceName, this. serviceKey), new ServiceToDevice ("1", text, null, null); OnReceive ();} else {this. closeSocket () ;}} catch (SocketException ex) {this. closeSocket (); this. onServiceLog (ex. message);} catch (Exception ex) {this. onServiceLog (ex. message );}}

4. Receive the command execution result of the driver.

Public override void ServiceConnectorCallback (object obj) {OnServiceLog (obj. ToString (); OnServiceLog ("the device has completed processing the command ");}
12.7 host program service instance configuration considerations
Static void Main (string [] args) {DeviceSelfDriver dev2 = new DeviceSelfDriver (); dev2.DeviceParameter. deviceName = "network device"; dev2.DeviceParameter. deviceAddr = 1; dev2.DeviceParameter. deviceID = "1"; dev2.DeviceDynamic. deviceID = "1"; dev2.DeviceParameter. deviceCode = "1"; dev2.DeviceParameter. NET. remoteIP = "127.0.0.1"; dev2.DeviceParameter. NET. remotePort = 9600; dev2.CommunicateType = CommunicateType. NET; dev2.Initialize ("1"); IServer server = new ServerManager (). createServer (new ServerConfig () {ServerName = "Service 1", ComReadTimeout = 1000, ComWriteTimeout = 1000, NetReceiveTimeout = 1000, NetSendTimeout = 1000, ControlMode = ControlMode. self, SocketMode = SocketMode. tcp, StartReceiveDataFliter = true, ClearSocketSession = false, StartCheckPackageLength = true, CheckSameSocketSession = false, DeliveryMode = DeliveryMode. deviceCode,}); server. addDeviceCompleted + = server_AddDeviceCompleted; server. deleteDeviceCompleted + = server_DeleteDeviceCompleted; server. start (); server. addDevice (dev2); TestService. service service = new TestService. service (); service. isAutoStart = true; server. addService (service); while ("exit" = Console. readLine () {server. stop ();}}
12.8 Running Effect

1. Images

 

 

1. [serialization] C # communication (Serial Port and network) Framework Design and Implementation

2. [Open Source] C # cross-platform Iot communication framework ServerSuperIO (SSIO) Introduction

2. Overall system construction solution using SuperIO and open-source cross-platform Iot framework ServerSuperIO

3. C # technical route of industrial IoT and integrated system solutions (data sources, data collection, data upload and receiving, ActiveMQ, Mongodb, WebApi, and mobile App)

5. ServerSuperIO Open Source Address: https://github.com/wxzz/ServerSuperIO

Internet of Things & integrated technology (. NET) QQ Group:54256083

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.