Realtime Serverless IoT Data Using Azure SignalR And Functions In Angular

Introduction

 
The data coming from the IoT devices must be shown (or used) in real-time. If we fail to do that, then there is no point in using IoT devices. Here in this article, we will see how we can show the real-time data from our IoT device in an Angular application using Azure SignalR Service and Azure Functions. Sound interesting?
 
The flow of data can be defined as
 
IoT device -> Azure IoT Hub -> Azure Function -> Azure SignalR Service -> Angular application.
 
Let’s start then. You can always read this article on my blog here.
 
Background
 
In our previous article, we have already created an Azure Function which pulls the data from our IoT Hub whenever there is any new message/event happening.
 
Source Code
 
Please feel free to fork/clone this project from GitHub here.
 
Real-time IoT Data Processing
 
We will be creating two solutions - one for Angular application and the other one for Azure Functions. We will also create a new Azure Signal R service in the Azure portal.
 
Azure SignalR Service
 
According to Microsoft, "Azure SignalR Service is an Azure managed PaaS service to simplify the development, deployment, and management of real-time web application using SignalR, with Azure supported SLA, scaling, performance, and security. The service provides API/SDK/CLI/UI, and the rich set of code samples, templates, and demo applications."
 
Core features for Azure SignalR Service,
  • Native ASP.NET Core SignalR development support
  • ASP.NET Core SignalR backend for improved performance and stability
  • Redis based backplane scaling
  • Web Socket, comet, and .NET Server-Sent-Event support
  • REST API support for server broadcast scenarios
  • Resource Provider support for ARM Template-based CLI
  • Dashboard for performance and connection monitoring
  • Token-based AUTH model
Let’s log in to our Azure portal and create a new Azure Signal R service. Click on the "+Create a resource" link and search for SignalR Service. Once you have created the service, go to the keys section and copy the connection string. We will be using the same in our Azure Function.
 
Azure Functions
 
As we discussed in my previous article, we will be creating an Azure Function with an IoTHubTrigger in it. You can refer to this article for the hints on how to create an Azure Function solution in Visual Studio. Please make sure that you had installed the required packages as mentioned in the image below.
 
Realtime Serverless IoT Data Using Azure SignalR And Functions In Angular
 
Required Packages
 
Once you have created a new Function in the solution, it is time to add some code.
  1. using Microsoft.Azure.EventHubs;    
  2. using Microsoft.Azure.WebJobs;    
  3. using Microsoft.Azure.WebJobs.Extensions.SignalRService;    
  4. using Microsoft.Extensions.Logging;    
  5. using Newtonsoft.Json;    
  6. using System;    
  7. using System.Text;    
  8. using System.Threading.Tasks;    
  9. using IoTHubTrigger = Microsoft.Azure.WebJobs.EventHubTriggerAttribute;    
  10. namespace AzureFunction {    
  11.     public static class SignalR {    
  12.         [FunctionName("SignalR")] public static async Task Run([IoTHubTrigger("messages/events", Connection = "IoTHubTriggerConnection", ConsumerGroup = "ml-iot-platform-func")] EventData message, [SignalR(HubName = "broadcast")] IAsyncCollector < SignalRMessage > signalRMessages, ILogger log) {    
  13.             var deviceData = JsonConvert.DeserializeObject < DeviceData > (Encoding.UTF8.GetString(message.Body.Array));    
  14.             deviceData.DeviceId = Convert.ToString(message.SystemProperties["iothub-connection-device-id"]);    
  15.             log.LogInformation($ "C# IoT Hub trigger function processed a message: {JsonConvert.SerializeObject(deviceData)}");    
  16.             await signalRMessages.AddAsync(new SignalRMessage() {    
  17.                 Target = "notify", Arguments = new [] {    
  18.                     JsonConvert.SerializeObject(deviceData)    
  19.                 }    
  20.             });    
  21.         }    
  22.     }    
  23. }  
As you can see, we are using Microsoft.Azure.WebJobs.EventHubTriggerAttribute for pulling data from our IoT Hub. Here, “messages/events” is our Event Hub Name and "Connection" is the IoT Hub connections string which is defined in the local.settings.json file and the ConsumerGroup is the group I have created for the Azure Function solution.
 
If you have noticed, we are using the HubName as “broadcast” in the SignalR attribute and “notify” as the SignalR message Target property. If you change the Target property, you may get a warning in your browser console as “Warning: No client method with the name ‘notify’ found.”. The @aspnet/signalr package is checking for the Target property ‘notify’ by default.
 
 
Notify not found error
 
 
HubConnection Js File Looks for Notify
 
So, I will keep the Target property as ‘notify’. By default, the message data doesn’t contain the device id value, so we will have to get the same from SystemProperties.
  1. var deviceData = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(message.Body.Array));    
  2. deviceData.DeviceId = Convert.ToString(message.SystemProperties["iothub-connection-device-id"]);   
Below is my DeviceData class.
  1. using Newtonsoft.Json;    
  2. using System;    
  3. namespace AzureFunction {    
  4.     public class DeviceData {    
  5.         [JsonProperty("messageId")] public string MessageId {    
  6.             get;    
  7.             set;    
  8.         } [JsonProperty("deviceId")] public string DeviceId {    
  9.             get;    
  10.             set;    
  11.         } [JsonProperty("temperature")] public string Temperature {    
  12.             get;    
  13.             set;    
  14.         } [JsonProperty("humidity")] public string Humidity {    
  15.             get;    
  16.             set;    
  17.         } [JsonProperty("pressure")] public string pressure {    
  18.             get;    
  19.             set;    
  20.         } [JsonProperty("pointInfo")] public string PointInfo {    
  21.             get;    
  22.             set;    
  23.         } [JsonProperty("ioTHub")] public string IoTHub {    
  24.             get;    
  25.             set;    
  26.         } [JsonProperty("eventEnqueuedUtcTime")] public DateTime EventEnqueuedUtcTime {    
  27.             get;    
  28.             set;    
  29.         } [JsonProperty("eventProcessedUtcTime")] public DateTime EventProcessedUtcTime {    
  30.             get;    
  31.             set;    
  32.         } [JsonProperty("partitionId")] public string PartitionId {    
  33.             get;    
  34.             set;    
  35.         }    
  36.     }    
  37. }   
When you work with any client like Angular application, it is important to get the token/connection from the server, so that the client can persist the connection with the server; hence the data can be pushed to the client from SignalR service. So, we will create a new Azure Function which will return the connection information with the URL and AccessToken.
  1. using Microsoft.AspNetCore.Http;    
  2. using Microsoft.Azure.WebJobs;    
  3. using Microsoft.Azure.WebJobs.Extensions.Http;    
  4. using Microsoft.Azure.WebJobs.Extensions.SignalRService;    
  5. using Microsoft.Extensions.Logging;    
  6. namespace AzureFunction {    
  7.     public static class SignalRConnection {    
  8.         [FunctionName("SignalRConnection")] public static SignalRConnectionInfo Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, [SignalRConnectionInfo(HubName = "broadcast")] SignalRConnectionInfo info, ILogger log) => info;    
  9.     }    
  10. }   
Please make sure that you have set AuthorizationLevel.Anonymous in HttpTrigger attribute and also to use the same HubName we have used for our other Azure Function, which is SignalR.
 
Now, we can customize our local.settings.json file.
  1. {    
  2.     "IsEncrypted": false,    
  3.     "Values": {    
  4.         "AzureWebJobsStorage": "UseDevelopmentStorage=true",    
  5.         "FUNCTIONS_WORKER_RUNTIME": "dotnet",    
  6.         "AzureSignalRConnectionString": "",    
  7.         "MSDEPLOY_RENAME_LOCKED_FILES": 1,    
  8.         "IoTHubTriggerConnection": ""    
  9.     },    
  10.     "Host": {    
  11.         "LocalHttpPort": 7071,    
  12.         "CORS": "*"    
  13.     }    
  14. }   
Please note that this file is for local configuration, and remember to change the connection strings here before you run the application. If you want to enable the CORS in the Azure Function in the Azure Portal, you can do that by following the steps mentioned in the image below.
 
Realtime Serverless IoT Data Using Azure SignalR And Functions In Angular
 
Enabling CORS in Azure Function
 
Angular Client
 
As we have already created our Azure Functions, now it is time to create our Angular client. Let’s use Angular CLI and create a new project. Now, we can add a new package @aspnet/signalr to our application which will help us to talk to our Azure SignalR service.
 
home.component.ts
 
Below is my code for the home.component.ts file.
  1. import {    
  2.     Component,    
  3.     OnInit,    
  4.     NgZone    
  5. } from '@angular/core';    
  6. import {    
  7.     SignalRService    
  8. } from 'src/app/services/signal-r.service';    
  9. import {    
  10.     StreamData    
  11. } from 'src/app/models/stream.data';    
  12. @Component({    
  13.     selector: 'app-home',    
  14.     templateUrl: './home.component.html',    
  15.     styleUrls: ['./home.component.css']    
  16. }) export class HomeComponent implements OnInit {    
  17.     streamData: StreamData = new StreamData();constructor(private signalRService: SignalRService) {}    
  18.     ngOnInit() {    
  19.         this.signalRService.init();    
  20.         this.signalRService.mxChipData.subscribe(data => {    
  21.             this.streamData = JSON.parse(data);    
  22.             console.log(data);    
  23.         });    
  24.     }    
  25. }   
home.component.html
 
We used a Material card to show the service data, so we can define our home.component.html file as preceding.
  1. <div class="container">    
  2.     <div class="row">    
  3.         <mat-card class="example-card">    
  4.             <mat-card-header>    
  5.                 <div mat-card-avatar class="example-header-image"></div>    
  6.                 <mat-card-title>Real Time Values</mat-card-title>    
  7.                 <mat-card-subtitle>The real time values of humidity, temprature etc...</mat-card-subtitle>    
  8.             </mat-card-header>    
  9.             <mat-card-content>    
  10.                 <p> <label>DeviceId: </label> {{streamData?.deviceId}} </p>    
  11.                 <p> <label>Temperature: </label> {{streamData?.temperature}} </p>    
  12.                 <p> <label>Humidity: </label> {{streamData?.humidity}} </p>    
  13.             </mat-card-content>    
  14.         </mat-card>    
  15.     </div>    
  16. </div>   
signal-r.service.ts
 
Now, we can create a new service which calls our Azure SignalR service.
  1. import {    
  2.     Injectable    
  3. } from '@angular/core';    
  4. import {    
  5.     HttpClient    
  6. } from '@angular/common/http';    
  7. import {    
  8.     Observable,    
  9.     Subject    
  10. } from 'rxjs';    
  11. import {    
  12.     SignalRConnection    
  13. } from '../models/signal-r-connection.model';    
  14. import {    
  15.     environment    
  16. } from '../../environments/environment';    
  17. import * as SignalR from '@aspnet/signalr';    
  18. @Injectable({    
  19.     providedIn: 'root'    
  20. }) export class SignalRService {    
  21.     mxChipData: Subject < string > = new Subject();    
  22.     private hubConnection: SignalR.HubConnection;    
  23.     constructor(private http: HttpClient) {}    
  24.     private getSignalRConnection(): Observable < SignalRConnection > {    
  25.         return this.http.get < SignalRConnection > (`${environment.baseUrl}SignalRConnection`);    
  26.     }    
  27.     init() {    
  28.         this.getSignalRConnection().subscribe(con => {    
  29.             const options = {    
  30.                 accessTokenFactory: () => con.accessToken    
  31.             };    
  32.             this.hubConnection = new SignalR.HubConnectionBuilder().withUrl(con.url, options).configureLogging(SignalR.LogLevel.Information).build();    
  33.             this.hubConnection.start().catch(error => console.error(error));    
  34.             this.hubConnection.on('notify', data => {    
  35.                 this.mxChipData.next(data);    
  36.             });    
  37.         });    
  38.     }    
  39. }   
As you can see, we are doing the following things in our service.
  1. Get the SignalR connection information which contains Url and Access token, by calling the SignalRConnection Azure Function.
  2. Create the Hub connection using SignalR.HubConnectionBuilder.
  3. Start the Hub connection
  4. Wire the ‘notify’ function, remember we have set this in our Azure Function SignalR.
signal-r-connection.model.ts
  1. export class SignalRConnection {    
  2.     url: string;    
  3.     accessToken: string;    
  4. }  
stream.data.ts
  1. export class StreamData {    
  2.     messageId: string;    
  3.     deviceId: string;    
  4.     temperature: string;    
  5.     humidity: string;    
  6.     pressure: string;    
  7.     pointInfo: string;    
  8.     ioTHub: string;    
  9.     eventEnqueuedUtcTime: string;    
  10.     eventProcessedUtcTime: string;    
  11.     partitionId: string;    
  12. }   
Output
 
Now, let’s just run our Angular application, Azure Function, and a simulated device. Please refer to this link for the information related to the simulated device. Please feel free to connect to your IoT device, if you haven’t configured the simulated device.
 
Realtime Serverless IoT Data Using Azure SignalR And Functions In Angular
 
Real-time IoT Device Data
 
References
  1. Serverless real-time messaging

Conclusion

 
Wow! Now we have learned,
  • How to connect IoT Hub and Azure Function
  • What Triggers are in Azure Function
  • How to connect Azure Function and Azure SignalR service
  • How to post data to Azure SignalR Service
  • How to connect Azure SignalR service from Angular client
  • How to show real-time data in Angular application from IoT device
You can always read my IoT articles here.
 
Your turn. What do you think?
 
Thanks a lot for reading. Did I miss anything that you may think is needed in this article? Did you find this post useful? Kindly do not forget to share your feedback with me.