<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>IoT Hub Trigger &#8211; Sibeesh Passion</title>
	<atom:link href="https://mail.sibeeshpassion.com/tag/iot-hub-trigger/feed/" rel="self" type="application/rss+xml" />
	<link>https://mail.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Thu, 03 Jan 2019 12:24:50 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>IoT Hub Trigger &#8211; Sibeesh Passion</title>
	<link>https://mail.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Realtime IoT Data using Azure SignalR and Functions in Angular</title>
		<link>https://mail.sibeeshpassion.com/realtime-iot-data-using-azure-signalr-and-functions-in-angular/</link>
					<comments>https://mail.sibeeshpassion.com/realtime-iot-data-using-azure-signalr-and-functions-in-angular/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 31 Dec 2018 21:04:26 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[IoT]]></category>
		<category><![CDATA[Azure Function]]></category>
		<category><![CDATA[Azure IoT]]></category>
		<category><![CDATA[Http Trigger]]></category>
		<category><![CDATA[IoT Dev Kit]]></category>
		<category><![CDATA[IoT Hub]]></category>
		<category><![CDATA[IoT Hub Trigger]]></category>
		<category><![CDATA[MXChip]]></category>
		<category><![CDATA[Serverless]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=13498</guid>

					<description><![CDATA[[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 -&#62; Azure IoT Hub -&#62; Azure Function -&#62; Azure SignalR Service -&#62; Angular application. Sounds interesting? Let&#8217;s start then. Background In our previous article, we have already created [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>[toc]</p>



<h2 class="wp-block-heading">Introduction</h2>



<p>The data coming from the <a href="https://sibeeshpassion.com/category/iot/">IoT</a> 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 -&gt; Azure IoT Hub -&gt; Azure Function -&gt; Azure SignalR Service -&gt; Angular application. Sounds interesting? Let&#8217;s start then.</p>



<h2 class="wp-block-heading">Background</h2>



<p> In our previous article, we have already created an <a href="https://sibeeshpassion.com/iothubtrigger-azure-function-and-azure-iot-hub/">Azure Function which pulls the Data from our IoT Hub</a> whenever there is any new messages/events happening. If you have not read the same, please read it. </p>



<h2 class="wp-block-heading">Source Code</h2>



<p>Please feel free to fork, clone this project from GitHub here: <strong><a href="https://github.com/SibeeshVenu/Realtime-IoT-Device-Data-using-Azure-SignalR-and-Azure-Function-in-Angular">Realtime-IoT-Device-Data-using-Azure-SignalR-and-Azure-Function-in-Angular</a></strong></p>



<h2 class="wp-block-heading">Real-time IoT Data Processing</h2>



<p>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. </p>



<h3 class="wp-block-heading">Azure SignalR Service</h3>



<p>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 <g class="gr_ gr_5 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="5" data-gr-id="5">rich</g> set of code samples, templates, and demo applications.</p>



<p>Core features for Azure SignalR Service:</p>



<ul class="wp-block-list"><li>Native ASP.NET Core SignalR development support</li><li>ASP.NET Core SignalR backend for improved performance and stability</li><li>Redis based backplane scaling</li><li>Web Socket, comet, and .NET Server-Sent-Event support</li><li>REST API support for server broadcast scenarios</li><li>Resource Provider support for ARM Template based CLI</li><li>Dashboard for performance and connection monitoring</li><li>Token-based AUTH model</li></ul>



<p> Let&#8217;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.</p>



<h3 class="wp-block-heading">Azure Functions</h3>



<p>As we discussed in my previous article, we will be creating an Azure Function with an IoTHubTrigger in it. You can refer to <a href="https://sibeeshpassion.com/azure-function-as-output-job-topology-of-an-azure-stream-analytics-job/#creating-an-azure-function-solution-and-function">this article</a> 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.</p>



<figure class="wp-block-image"><img fetchpriority="high" decoding="async" width="650" height="390" src="https://sibeeshpassion.com/wp-content/uploads/2018/12/Required-Packages.jpg" alt="" class="wp-image-13507" srcset="/wp-content/uploads/2018/12/Required-Packages.jpg 650w, /wp-content/uploads/2018/12/Required-Packages-300x180.jpg 300w, /wp-content/uploads/2018/12/Required-Packages-400x240.jpg 400w" sizes="(max-width: 650px) 100vw, 650px" /><figcaption>Required Packages</figcaption></figure>



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



<pre class="wp-block-code"><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&lt;SignalRMessage> signalRMessages,
            ILogger log)
        {
            var deviceData = JsonConvert.DeserializeObject&lt;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) }
            });
        }
    }
}</code></pre>



<p>As you can see we are using Microsoft.Azure.WebJobs.EventHubTriggerAttribute for pulling data from our IoT Hub. Here &#8220;messages/events&#8221; 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. </p>



<p>If you have noticed, we are using the HubName as &#8220;broadcast&#8221; in the SignalR attribute and &#8220;notify&#8221; as the SignalR message Target property. If you change the Target property, you may get a warning in your browser console as &#8220;Warning: No client method with the name &#8216;notify&#8217; found.&#8221;. The   @aspnet/<g class="gr_ gr_113 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="113" data-gr-id="113">signalr</g> package is checking for the Target property &#8216;notify&#8217; by default. </p>



<figure class="wp-block-image"><img decoding="async" width="650" height="202" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/Nofity-not-found-error.jpg" alt="" class="wp-image-13517" srcset="/wp-content/uploads/2019/01/Nofity-not-found-error.jpg 650w, /wp-content/uploads/2019/01/Nofity-not-found-error-300x93.jpg 300w, /wp-content/uploads/2019/01/Nofity-not-found-error-400x124.jpg 400w" sizes="(max-width: 650px) 100vw, 650px" /><figcaption>Nofity not found error</figcaption></figure>



<figure class="wp-block-image"><img decoding="async" width="650" height="255" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/HubConnection-Js-File-Looks-for-Notify.jpg" alt="" class="wp-image-13516" srcset="/wp-content/uploads/2019/01/HubConnection-Js-File-Looks-for-Notify.jpg 650w, /wp-content/uploads/2019/01/HubConnection-Js-File-Looks-for-Notify-300x118.jpg 300w, /wp-content/uploads/2019/01/HubConnection-Js-File-Looks-for-Notify-400x157.jpg 400w" sizes="(max-width: 650px) 100vw, 650px" /><figcaption>HubConnection Js File Looks for Notify</figcaption></figure>



<p>So, I will keep the Target property as &#8216;notify&#8217;. By default, the message data doesn&#8217;t contain the device id value, so we will have to get the same from SystemProperties.</p>



<pre class="wp-block-code"><code> var deviceData = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(message.Body.Array));
             deviceData.DeviceId = Convert.ToString(message.SystemProperties["iothub-connection-device-id"]);</code></pre>



<p>Below is my DeviceData class.</p>



<pre class="wp-block-code"><code>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; }
    }
}</code></pre>



<p>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 <g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="6" data-gr-id="6">server</g>, 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.</p>



<pre class="wp-block-code"><code>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;
    }
}</code></pre>



<p>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. </p>



<p>Now we can customize our local.settings.json file.</p>



<pre class="wp-block-code"><code>{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "AzureSignalRConnectionString": "",
    "MSDEPLOY_RENAME_LOCKED_FILES": 1,
    "IoTHubTriggerConnection": ""
  },
  "Host": {
    "LocalHttpPort": 7071,
    "CORS": "*"
  }
}</code></pre>



<p>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.</p>



<figure class="wp-block-image"><img decoding="async" width="649" height="227" src="https://sibeeshpassion.com/wp-content/uploads/2018/12/Enabling-CORS-in-Azure-Function.jpg" alt="" class="wp-image-13499" srcset="/wp-content/uploads/2018/12/Enabling-CORS-in-Azure-Function.jpg 649w, /wp-content/uploads/2018/12/Enabling-CORS-in-Azure-Function-300x105.jpg 300w, /wp-content/uploads/2018/12/Enabling-CORS-in-Azure-Function-400x140.jpg 400w" sizes="(max-width: 649px) 100vw, 649px" /><figcaption>Enabling CORS in Azure Function</figcaption></figure>



<h3 class="wp-block-heading">Angular Client</h3>



<p>As we have already created our Azure Functions, now it is time to create our Angular client. Let&#8217;s use Angular CLI and create a new project. Now we can add a new package <em>@aspnet/</em><g class="gr_ gr_308 gr-alert gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling ins-del multiReplace" id="308" data-gr-id="308"><em class="">signalr</em></g> to our application which will help us to talk to our Azure SignalR service. </p>



<h4 class="wp-block-heading"> home.component.ts </h4>



<p>Below is my code for home.component.ts file.</p>



<pre class="wp-block-code"><code>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);
    });
  }
}</code></pre>



<h4 class="wp-block-heading"> home.component.html </h4>



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



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



<h4 class="wp-block-heading">signal-r.service.ts</h4>



<p>Now, we can create a new service which calls our Azure SignalR service. </p>



<pre class="wp-block-code"><code>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&lt;string> = new Subject();
  private hubConnection: SignalR.HubConnection;

  constructor(private http: HttpClient) {
  }

  private getSignalRConnection(): Observable&lt;SignalRConnection> {
    return this.http.get&lt;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);
      });
    });
  }
}</code></pre>



<p>As you can see, we are doing the following things in our service.</p>



<ol class="wp-block-list"><li>Get the SignalR connection information which contains Url and Access token, by calling the SignalRConnection Azure Function.</li><li>Create the Hub connection using SignalR.HubConnectionBuilder.</li><li>Start the Hub connection</li><li>Wire the &#8216;notify&#8217; function, remember we have set this in our Azure Function SignalR.</li></ol>



<h4 class="wp-block-heading">signal-r-connection.model.ts</h4>



<pre class="wp-block-code"><code>export class SignalRConnection {
   url: string;
   accessToken: string;
}</code></pre>



<h4 class="wp-block-heading">stream.data.ts</h4>



<pre class="wp-block-code"><code>export class StreamData {
    messageId: string;
    deviceId: string;
    temperature: string;
    humidity: string;
    pressure: string;
    pointInfo: string;
    ioTHub: string;
    eventEnqueuedUtcTime: string;
    eventProcessedUtcTime: string;
    partitionId: string;
}</code></pre>



<h2 class="wp-block-heading">Output</h2>



<p>Now, let&#8217;s just run our Angular application, Azure Function, and a simulated device. Please refer to <a href="https://sibeeshpassion.com/an-introduction-to-azure-stream-analytics-job/#run-the-stream-analytics-job-and-see-the-data-in-the-database">this link</a> for the information related to the Simulated device. Please feel free to connect to your IoT device, if you haven&#8217;t configured the simulated device. </p>



<figure class="wp-block-image"><img decoding="async" width="1280" height="720" src="https://sibeeshpassion.com/wp-content/uploads/2018/12/Realtime-IoT-Device-Data.gif" alt="" class="wp-image-13501"/><figcaption>Realtime IoT Device Data</figcaption></figure>



<figure class="wp-block-image"><img decoding="async" width="650" height="250" src="https://sibeeshpassion.com/wp-content/uploads/2018/12/Serverless-Realtime-MXChip-Data-Angular.gif" alt="Serverless Realtime MXChip Data Angular" class="wp-image-13512"/><figcaption>Serverless Realtime MXChip Data Angular</figcaption></figure>



<p>References</p>



<ol class="wp-block-list"><li><a href="https://medium.com/medialesson/serverless-real-time-messaging-with-azure-functions-and-azure-signalr-service-c70e781ff3c3">Server less real-time messaging</a></li></ol>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Wow!. Now we have learned,</p>



<ul class="wp-block-list"><li>How to connect IoT Hub and Azure Function </li><li>What is Triggers in Azure Function</li><li>How to connect Azure Function and Azure SignalR service</li><li>How to post data to Azure SignalR service</li><li>How to connect Azure SignalR service from Angular client</li><li>How to show <g class="gr_ gr_377 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="377" data-gr-id="377">real time</g> data in Angular application from IoT device</li></ul>



<p>You can always ready my IoT articles&nbsp;<a href="https://sibeeshpassion.com/category/iot/">here</a>.</p>



<h2 class="wp-block-heading">Your turn. What do you think?</h2>



<p>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.</p>



<p>Kindest Regards<br>Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/realtime-iot-data-using-azure-signalr-and-functions-in-angular/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
