Location>code7788 >text

How the surging-based WoodenBoat platform accesses devices via HTTP web components

Popularity:634 ℃/2024-11-06 02:33:54

I. Overview

The previous article introduces the wooden boat how to upload the module hot deployment, then this article will introduce how to use HTTP network components to access the device, then some people will ask the wooden boat and what is it, what is the architecture for the basis, what can be done?

What is Kayak?

Kayak (Kayak) is based on .NET6.0 software environment surging microservices engine for development, the platform contains microservices and Internet of Things platform. Support for asynchronous and responsive programming development , features include object models , devices , products , network components of unified management and microservices platform under the registry , service routing , modules , intermediate services and other management. There are also multi-protocol adaptation (TCP, MQTT, UDP, CoAP, HTTP, Grpc, websocket, rtmp, httpflv, webservice, etc.), through a variety of flexible configurations adapted to access different manufacturers of different protocols and other equipment. And through the device alarms, message notification, data visualization and other functions. Enable you to quickly set up a microservice IoT platform system.

So here's how to go from creating components, protocols, and device gateways, devices to device gateway access, and then to device data reporting, putting the whole process through this article.

II. Network components

1. Edit the creation of HTTP protocol network components, you can choose to share the configuration and stand-alone configuration (stand-alone configuration is cluster mode), and then you can choose to open the swagger and webservice.

Once it's turned on successfully, you can see if swagger can access the

Or perhaps access to an intermediate service, as in the Testapi module uploaded in the previous article:

III. Customized protocols

  • How to create a custom protocol module

If the network programming and development, will inevitably be involved in the protocol message encoding and decoding processing, then the platform is also done to deal with the flexibility of the first is the protocol module to create, through the following code to see the protocol module can be added to the protocol description of the md document, identity authentication processing, HTTP routing, message encoding and decoding, metadata configuration. The following one by one on how to write

  public class Demo5ProtocolSupportProvider : ProtocolSupportProvider
    {
        public override IObservable<ProtocolSupport> Create(ProtocolContext context)
        {
    var support = new ComplexProtocolSupport();
    = "demo5";
= "Demo Protocol 5".
= "Demo Protocol 5". (,
"Document/"); (, new Demo5Authenticator()); (, new List<BasicMessageCodec>() { , , , , }.Select(p => () .GroupName(()) .HttpMethod(()) .Path() .ContentType(()) .Description(()) .Example(()) ).ToList()); (, () => (new HttpDeviceMessageCodec())); (, _httpConfig); return (support); } }

1. Add a protocol description document such as the following code. (, "Document/");, the document only supports the markdownfile, as follows

 

### Push device data using HTTP

Example of reported attributes.

POST/{productId}/{deviceId}/properties/report
Authorization:{Token configured in the product or device}
Content-Type: application/json

{
 "properties":{
   "temp":11.5
 }
}

Example of reported event.

POST/{productId}/{deviceId}/event/{eventId}
Authorization:{Token configured in the product or device}
Content-Type: application/json

{
 "data":{
   "createtime": ""
 }
}

 

2. Add authentication as follows. (, new Demo5Authenticator()) , custom authenticationDemo5Authenticator The code is as follows:

 

       public class Demo5Authenticator : IAuthenticator
       {
           public IObservable<AuthenticationResult> Authenticate(IAuthenticationRequest request, IDeviceOperator deviceOperator)
           {
               var result = <AuthenticationResult>(default);
               if (request is DefaultAuthRequest)
               {
                   var authRequest = request as DefaultAuthRequest;
                   (()==?"token": "key").Subscribe(  config =>
                   {
                       var password = <string>();
                       if ((password))
                       {
                           result= (());
                       }
                       else
                       {
                           result= ((StatusCode.CUSTOM_ERROR, "Authentication failed, wrong password"));
                       }
                   });
               }
               else
               result = <AuthenticationResult>((StatusCode.CUSTOM_ERROR, "Request parameter types are not supported"));
               return result;
           }

           public IObservable<AuthenticationResult> Authenticate(IAuthenticationRequest request, IDeviceRegistry registry)
           {
               var result = <AuthenticationResult>(default);
               var authRequest = request as DefaultAuthRequest;
               registry
                 .GetDevice()
                 .Subscribe(async p => {

                    var config=  await (() ==  ? "token" : "key");
                     var password= <string>();
                    if((password))
                     {
                         result= (());
                     }
                     else
                     {
                         result= ((StatusCode.CUSTOM_ERROR, "Authentication failed, wrong password"));
                     }
                 });
               return result;
           }
       }

 

3. Add Http routing code, so how to configure it, the code is as follows:

 

    public static BasicMessageCodec ReportProperty =>
 new BasicMessageCodec("/*/properties/report", typeof(ReadPropertyMessage), route => ("Attribute Reporting")
                     .HttpMethod("Post")
                     .Description("Reported object model attribute data")
                     .Example("{\\"properties\":{\"Property ID\":\"Property Value\"}}}"));

 

4. Add message encoding and decoding code (, () => (new HttpDeviceMessageCodec())), you can customize the codec.HttpDeviceMessageCodecThe code is as follows:

 

  public class HttpDeviceMessageCodec : DeviceMessageCodec
  {
      private readonly MessageTransport _transport;

      public HttpDeviceMessageCodec() : this()
      {
      }

      private static DefaultHttpResponseMessage Unauthorized(String msg)
      {
          return new DefaultHttpResponseMessage()
                  .ContentType()
                  .Body("{\"success\":false,\"code\":\"unauthorized\",\"message\":\"" + msg + "\"}")
                  .Status();
      }

      private static DefaultHttpResponseMessage BadRequest()
      {
          return new DefaultHttpResponseMessage()
                  .ContentType()
                  .Body("{\"success\":false,\"code\":\"bad_request\"}")
                  .Status();
      }

      public HttpDeviceMessageCodec(MessageTransport transport)
      {
          _transport = transport;
      }
      public override IObservable<IDeviceMessage> Decode(MessageDecodeContext context)
      {
          if (() is HttpRequestMessage)
          {
              return DecodeHttpRequestMessage(context);
          }
          return <IDeviceMessage>(default);
      }


      public override  IObservable<IEncodedMessage> Encode(MessageEncodeContext context)
      {
          return <IEncodedMessage>(default);
      }



      private IObservable<IDeviceMessage> DecodeHttpRequestMessage(MessageDecodeContext context)
      {
          var result = <IDeviceMessage>(default);
          var message = (HttpExchangeMessage)();

          Header? header = ("Authorization");
          if (header == null ||  == null ||  == 0)
          {
              message
                   .Response(Unauthorized("Authorization header is required")).ToObservable()
                   .Subscribe(p => result = (default));

              return result;
          }
          var httpToken = [0];

          var paths = ("/");
          if ( == 0)
          {
              (BadRequest()).ToObservable()
                 .Subscribe(p => result = (default));
              return result;
          }
          String deviceId = paths[1];
          (deviceId).Subscribe(async deviceOperator =>
          {
              var config = deviceOperator==null?null: await ("token");
              var token = config?.Convert<string>();
              if (token == null || !(token))
              {
                  await message
                       .Response(Unauthorized("Device not registered or authentication failed"));
              }
              else
              {
                  var deviceMessage = await DecodeBody(message, deviceId);
                  if (deviceMessage != null)
                  {
                      await ("{\"success\":true,\"code\":\"success\"}");
                      result = (deviceMessage);
                  }
                  else
                  {
                      await (BadRequest());
                  }
              }
          });
          return result;
      }

      private async Task<IDeviceMessage> DecodeBody(HttpExchangeMessage message,string deviceId)
      {

          byte[] body = new byte[];
          (body);
          var deviceMessage = await (, body);
           = deviceId;
          return deviceMessage;
      }
  }

 

5. Add metadata configuration code (, _httpConfig);  _httpConfigThe code is as follows

        private readonly DefaultConfigMetadata _httpConfig = new DefaultConfigMetadata(
        "Http Authentication Configuration"
        , "token is the http authentication token")
        .Add("token", "token", "http token", );
  • How to load the protocol module, the protocol module contains the protocol module support add reference to load and upload hot deployment to load.

Reference Load Module

Upload Heat Deployment Protocol Module

IV. Equipment gateways

Creating a Device Gateway

V. Product management

The following products are added.

Device Access

VI. Equipment management

Add Device

HTTP Authentication Configuration

Creating Alert Thresholds

VII. Testing

Tested with Postman, calling http://127.0.0.1:168/{productid}/{deviceid}/properties/report as an example, with Authorization set to: 123456

1. Normal data testing

 

 

2. If you choose to call the Get method, it will return an error because it cannot find the ServiceRoute.

3. Changing Authorization to 1111 returns an error.Device not registered or authentication failedThe data reporting process has failed.

The above uploaded data can be viewed in the Device Information - "Operation Status".

Alarm messages can be viewed in Supercritical Data

VII. Summary

The above is based on HTTP network components device access, the existing platform network components can support TCP, MQTT, UDP, CoAP, HTTP, Grpc, websocket, rtmp, httpflv, webservice, tcpclient, while the device access support for TCP, UDP, HTTP network components, the latter will be successively add support for all network components access, I will also introduce other network components device access, and then scheduled for November 20, released 1.0 beta platform. Please pay attention to the show.