Sibeesh Passion

Top Menu

  • Home
  • Search
  • About
  • Privacy Policy

Main Menu

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Home
  • Search
  • About
  • Privacy Policy

logo

Sibeesh Passion

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment

  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins

  • Post Messages to Microsoft Teams Using Python

  • Get Azure Blob Storage Blob Metadata Using PowerShell

  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines

AzureIoT
Home›Azure›Realtime IoT Data using Azure SignalR and Functions in Angular

Realtime IoT Data using Azure SignalR and Functions in Angular

By SibeeshVenu
December 31, 2018
767
0
Share:
Serverless Realtime MXChip Data Angular

[toc]

Introduction

The data coming from the IoT devices are to be shown in real time, if we failed to do that, then there is no point in showing it. 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. Sounds interesting? So the flow of data can be defined as IoT device -> Azure IoT Hub -> Azure Function -> Azure SignalR Service -> Angular application. Sounds interesting? Let’s start then.

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 messages/events happening. If you have not read the same, please read it.

Source Code

Please feel free to fork, clone this project from GitHub here: Realtime-IoT-Device-Data-using-Azure-SignalR-and-Azure-Function-in-Angular

Real-time IoT Data Processing

We will be creating two solutions, one for Angular application and 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 and search 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.

Required Packages

Once you have created a new Function in the solution it is time to add some code.

using Microsoft.Azure.EventHubs;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Threading.Tasks;
using IoTHubTrigger = Microsoft.Azure.WebJobs.EventHubTriggerAttribute;

namespace AzureFunction
{
    public static class SignalR
    {
        [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)
        {
            var deviceData = JsonConvert.DeserializeObject<DeviceData>(Encoding.UTF8.GetString(message.Body.Array));
            deviceData.DeviceId = Convert.ToString(message.SystemProperties["iothub-connection-device-id"]);


            log.LogInformation($"C# IoT Hub trigger function processed a message: {JsonConvert.SerializeObject(deviceData)}");
            await signalRMessages.AddAsync(new SignalRMessage()
            {
                Target = "notify",
                Arguments = new[] { JsonConvert.SerializeObject(deviceData) }
            });
        }
    }
}

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.

Nofity 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.

 var deviceData = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(message.Body.Array));
             deviceData.DeviceId = Convert.ToString(message.SystemProperties["iothub-connection-device-id"]);

Below is my DeviceData class.

using Newtonsoft.Json;
using System;

namespace AzureFunction
{
    public class DeviceData
    {
        [JsonProperty("messageId")]
        public string MessageId { get; set; }

        [JsonProperty("deviceId")]
        public string DeviceId { get; set; }

        [JsonProperty("temperature")]
        public string Temperature { get; set; }

        [JsonProperty("humidity")]
        public string Humidity { get; set; }

        [JsonProperty("pressure")]
        public string pressure { get; set; }

        [JsonProperty("pointInfo")]
        public string PointInfo { get; set; }

        [JsonProperty("ioTHub")]
        public string IoTHub { get; set; }

        [JsonProperty("eventEnqueuedUtcTime")]
        public DateTime EventEnqueuedUtcTime { get; set; }

        [JsonProperty("eventProcessedUtcTime")]
        public DateTime EventProcessedUtcTime { get; set; }

        [JsonProperty("partitionId")]
        public string PartitionId { get; set; }
    }
}

When you work with any client like Angular application, it is important that we need 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.

using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
using Microsoft.Extensions.Logging;

namespace AzureFunction
{
    public static class SignalRConnection
    {
        [FunctionName("SignalRConnection")]
        public static SignalRConnectionInfo Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            [SignalRConnectionInfo(HubName = "broadcast")] SignalRConnectionInfo info,
            ILogger log) => info;
    }
}

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.

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "AzureSignalRConnectionString": "",
    "MSDEPLOY_RENAME_LOCKED_FILES": 1,
    "IoTHubTriggerConnection": ""
  },
  "Host": {
    "LocalHttpPort": 7071,
    "CORS": "*"
  }
}

Please be noted that this file if for local configuration and remember to change the connections 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.

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 home.component.ts file.

import { Component, OnInit, NgZone } from '@angular/core';
import { SignalRService } from 'src/app/services/signal-r.service';
import { StreamData } from 'src/app/models/stream.data';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  streamData: StreamData = new StreamData();

  constructor(private signalRService: SignalRService) {
  }

  ngOnInit() {
    this.signalRService.init();
    this.signalRService.mxChipData.subscribe(data => {
      this.streamData = JSON.parse(data);
      console.log(data);
    });
  }
}

home.component.html

We use Material card to show the Device data, so we can define our home.component.html file as preceding.

<div class="container">
  <div class="row">
    <mat-card class="example-card">
      <mat-card-header>
        <div mat-card-avatar class="example-header-image"></div>
        <mat-card-title>Real Time Values</mat-card-title>
        <mat-card-subtitle>The real time values of humidity, temprature etc...</mat-card-subtitle>
      </mat-card-header>
      <mat-card-content>
        <p>
          <label>DeviceId: </label>
          {{streamData?.deviceId}}
        </p>
        <p>
          <label>Temperature: </label>
          {{streamData?.temperature}}
        </p>
        <p>
          <label>Humidity: </label>
          {{streamData?.humidity}}
        </p>
      </mat-card-content>
    </mat-card>
  </div>
</div>

signal-r.service.ts

Now, we can create a new service which calls our Azure SignalR service.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject } from 'rxjs';
import { SignalRConnection } from '../models/signal-r-connection.model';
import { environment } from '../../environments/environment';
import * as SignalR from '@aspnet/signalr';

@Injectable({
  providedIn: 'root'
})

export class SignalRService {
  mxChipData: Subject<string> = new Subject();
  private hubConnection: SignalR.HubConnection;

  constructor(private http: HttpClient) {
  }

  private getSignalRConnection(): Observable<SignalRConnection> {
    return this.http.get<SignalRConnection>(`${environment.baseUrl}SignalRConnection`);
  }

  init() {
    this.getSignalRConnection().subscribe(con => {
      const options = {
        accessTokenFactory: () => con.accessToken
      };

      this.hubConnection = new SignalR.HubConnectionBuilder()
        .withUrl(con.url, options)
        .configureLogging(SignalR.LogLevel.Information)
        .build();

      this.hubConnection.start().catch(error => console.error(error));

      this.hubConnection.on('notify', data => {
        this.mxChipData.next(data);
      });
    });
  }
}

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

export class SignalRConnection {
   url: string;
   accessToken: string;
}

stream.data.ts

export class StreamData {
    messageId: string;
    deviceId: string;
    temperature: string;
    humidity: string;
    pressure: string;
    pointInfo: string;
    ioTHub: string;
    eventEnqueuedUtcTime: string;
    eventProcessedUtcTime: string;
    partitionId: string;
}

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 IoT Device Data
Serverless Realtime MXChip Data Angular
Serverless Realtime MXChip Data Angular

References

  1. Server less real-time messaging

Conclusion

Wow!. Now we have learned,

  • How to connect IoT Hub and Azure Function
  • What is Triggers 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 ready my IoT articles here.

Your turn. What do you think?

Thanks a lot for reading. Did I miss anything that you may think which is needed in this article? Could you find this post as useful? Kindly do not forget to share me your feedback.

Kindest Regards
Sibeesh Venu

TagsAzureAzure FunctionAzure IoTHttp TriggerIoTIoT Dev KitIoT HubIoT Hub TriggerMXChipServerless
Previous Article

IoTHubTrigger Azure Function and Azure IoT Hub

Next Article

MXChip Device with Pressure, Humidity, Temperature Info ...

0
Shares
  • 0
  • +
  • 0
  • 0
  • 0

SibeeshVenu

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer.

Related articles More from author

  • Azure

    Secure Serverless Azure Functions AppSetting Using Key Vault

    July 5, 2019
    By SibeeshVenu
  • Azure

    Show Recent Blog Posts in GitHub ReadMe using Azure Function

    July 20, 2020
    By SibeeshVenu
  • Run without debugging
    Azure

    Fix To: Bundles Are Not Working After Hosting To MVC Application

    April 24, 2016
    By SibeeshVenu
  • Azure

    Creating a Simple Windows Application Using Azure

    April 29, 2015
    By SibeeshVenu
  • Azure

    Build, Deploy, Configure CI &CD Your Static Website in 5 mins

    March 30, 2025
    By SibeeshVenu
  • Azure

    Validating Azure ARM Template Never Been Easier

    November 5, 2020
    By SibeeshVenu
0

My book

Asp Net Core and Azure with Raspberry Pi Sibeesh Venu

YouTube

MICROSOFT MVP (2016-2022)

profile for Sibeesh Venu - Microsoft MVP

Recent Posts

  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment
  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins
  • Easily move data from one COSMOS DB to another
  • .NET 8 New and Efficient Way to Check IP is in Given IP Range
  • Async Client IP safelist for Dot NET
  • Post Messages to Microsoft Teams Using Python
  • Get Azure Blob Storage Blob Metadata Using PowerShell
  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines
  • Integrate Azure App Insights in 1 Minute to .Net6 Application
  • Azure DevOps Service Connection with Multiple Azure Resource Group

Tags

Achievements (35) Angular (14) Angular 5 (7) Angular JS (15) article (10) Article Of The Day (13) Asp.Net (14) Azure (65) Azure DevOps (10) Azure Function (10) Azure IoT (7) C# (17) c-sharp corner (13) Career Advice (11) chart (11) CSharp (7) CSS (7) CSS3 (6) HighChart (10) How To (9) HTML5 (10) HTML5 Chart (11) Interview (6) IoT (11) Javascript (10) JQuery (82) jquery functions (9) JQWidgets (15) JQX Grid (17) Json (7) Microsoft (8) MVC (20) MVP (9) MXChip (7) News (18) Office 365 (7) Products (10) SQL (20) SQL Server (15) Visual Studio (10) Visual Studio 2017 (7) VS2017 (7) Web API (12) Windows 10 (7) Wordpress (9)
  • .NET
  • Achievements
  • ADO.NET
  • Android
  • Angular
  • Arduino
  • Article Of The Day
  • ASP.NET
  • Asp.Net Core
  • Automobile
  • Awards
  • Azure
  • Azure CDN
  • azure devops
  • Blockchain
  • Blog
  • Browser
  • C-Sharp Corner
  • C#
  • Career Advice
  • Code Snippets
  • CodeProject
  • Cognitive Services
  • Cosmos DB
  • CSS
  • CSS3
  • Data Factory
  • Database
  • Docker
  • Drawings
  • Drill Down Chart
  • English
  • Excel Programming
  • Exporting
  • Facebook
  • Fun
  • Gadgets
  • GitHub
  • GoPro
  • High Map
  • HighChart
  • How to
  • HTML
  • HTML5
  • Ignite UI
  • IIS
  • Interview
  • IoT
  • JavaScript
  • JQuery
  • jQuery UI
  • JQWidgets
  • JQX Grid
  • Json
  • Knockout JS
  • Linux
  • Machine Learning
  • Malayalam
  • Malayalam Poems
  • MDX Query
  • Microsoft
  • Microsoft ADOMD
  • Microsoft MVP
  • Microsoft Office
  • Microsoft Technologies
  • Microsoft Windows
  • Microsoft Windows Server
  • Mobile
  • MongoDB
  • Monthly Winners
  • MVC
  • MVC Grid
  • MySQL
  • News
  • Node JS
  • npm
  • Number Conversions
  • October 2015
  • Office 365
  • Office Development
  • One Plus
  • Outlook
  • Page
  • PHP
  • Poems
  • PowerShell
  • Products
  • Q&A
  • Raspberry PI
  • React
  • SEO
  • SharePoint
  • Skype
  • Social Media
  • Software
  • Spire.Doc
  • Spire.PDF
  • Spire.XLS
  • SQL
  • SQL Server
  • SSAS
  • SSMS
  • Storage In HTML5
  • Stories
  • Third Party Software Apps
  • Tips
  • Tools
  • Translator Text
  • Uncategorized
  • Unit Testing
  • UWP
  • VB.Net
  • Videos
  • Virtual Machine
  • Visual Studio
  • Visual Studio 2017
  • Wamp Server
  • Web API
  • Web Platform Installer
  • Webinars
  • WebMatrix
  • Windows 10
  • Windows 7
  • Windows 8.1
  • Wordpress
  • Writing

ABOUT ME

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer. If you would like to know more about me, you can read my story here.

Contact Me

  • info@sibeeshpassion.com

Pages

  • About
  • Search
  • Privacy Policy
  • About
  • Search
  • Privacy Policy
© Copyright Sibeesh Passion 2014-2025. All Rights Reserved.
Go to mobile version