SlideShare una empresa de Scribd logo
1 de 23
Cross-Platform Azure IoT Device
With C# Source Code Generator and .NET 6.0
Alon Fliess
Chief Architect
alonf@codevalue.net
@alon_fliess
http://alonfliess.me
http://codevalue.net
Ingredients
 IoT Device (Raspberry Pi)
 .NET 6.0 + .NET IoT Libraries
 C# Source Code Generator
 Azure IoT Hub + Azure IoT Client SDK for C#
 VS Code
About Alon Fliess
3
 Chief Architect & Founder – CodeValue
 Microsoft Regional Director
 Microsoft Azure MVP
 alonf@codevalue.net
 @alon_fliess
 http://alonfliess.me
 http://codevalue.net
IoT 101
var sensorData = await _bmp180.GetSensorDataAsync(Bmp180.UltraHighResolution);
var messageString = JsonConvert.SerializeObject(sensorData);
var message = new
Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString));
await deviceClient.SendEventAsync(message);
.NET IoT Libraries
System.Device.Gpio
 Hardware + OS
 Raspberry Pi, BeagleBoard, HummingBoard, ODROID,
and other single-board-computers that are supported
by Linux and Windows 10 IoT Core OS
 Wraps hardware access libraries on both Windows
and Linux
 Provides API for:
 General-purpose I/O (GPIO)
 Inter-Integrated Circuit (I2C)
 Serial Peripheral Interface (SPI)
 Pulse Width Modulation (PWM)
 Serial port
Device Binding
 Built on top of System.Device.Gpio
 Cross-Platform hardware driver classes
 Sensors, Displays, HMI devices and anything else that
requires software to control
 Cross-targeting .NET Standard 2.0 and up
 Full Framework, 3.1, 5, 6, mono
5
The wonder of Azure IoT Hub
IoT Hub
Receive device-to-cloud messages
Send cloud-to-device messages
Receive delivery acks
Receive file notifications
Direct method invocation
Receive operations monitoring events
Module identity management
Module twin management
Job Management
Send device-to-cloud
messages
Receive cloud-to-device
messages
Initiates file
uploads
Retrieve and update
twin properties
Receive direct method
requests
Service
Per-Device
Configuration Management
Message Routing
Message Enrichment
Device identity management
Device twin management
IoT Edge Device IoT Edge Management
Device Twin
Tags
Properties
Desired
Reported
What is a source generator?
 It lets you generate source code
 What does “generate source” mean?
 Why isn’t he saying any of these bullet points?
 So “source” I guess means source code
 And “generate” means create
 Wait.. Are source generators going to take our jobs?!
Your .cs
files
The C# Compiler
Project.dll
Parse
Source
Generator
Compile Emit
CST
AST
CST
Compilation IL
Source
(string)
CST
Referencing and Defining a Source Generator
A Simplified Flow
 Initialize  Register for a syntax node notification
context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
 Syntax node notification  gather code generation information
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
//collect information
…
}
 Execute  Generate source files and add them to the compilation
10
Your Implementation
IoTHubClientGenerator
 Build an IoT Device client program in seconds
 Handle configuration in multiple ways
 Use IoT Device Connection String, or Device Provisioning Service
 Support most of Azure IoT Hub protocols and protocols’ security
 Support Device Twin, Sending Telemetry, Direct Method and Cloud to Device
messages
 Support device connection status changed notification
11
Demo
Show me an
example!
• Raspberry Pi
• .NET 6.0 + .NET IoT
Libraries
• C# Source Code
Generator
• Azure IoT Hub + Azure
IoT Client SDK for C#
• VS Code
Summary & Takeaways
 .NET IoT Libraries – cross platform IoT foundation
 Azure IoT Hub – cloud scale IoT Platform
 C# + Source generators (IoTHubClientGenerator) – The easiest way to
develop Azure connected IoT device
13
Q
A
14
Alon Fliess
Chief Architect & Founder
alonf@codevalue.net
@alon_fliess
http://alonfliess.me
http://codevalue.net
Appendix – Demo Code
1. using System;
2. using System.Device.I2c;
3. using System.Device.Gpio;
4. using System.Threading;
5. using Iot.Device.Tcs3472x;
6. using System.Threading.Tasks;
7. using IoTHubClientGeneratorSDK;
8. using Microsoft.Azure.Devices.Client;
9. using Microsoft.Azure.Devices.Client.Exceptions;
10. using Microsoft.Azure.Devices.Client.Transport.Mqtt;
11. using System.Text;
12.
Appendix – Demo Code
17
13. namespace DotnetConf
14. {
15. [IoTHub(GeneratedSendMethodName = "SendAsync")]
16. partial class DotNetDevice
17. {
18. [Reported("LastColorName")]
19. private string _lastColorName;
20.
[Desired]
21. private int ReportingIntervalInSeconds { get; set; } = 10;
22.
[Device(ConnectionString="[Configuration.IoTHubConnectionString]")]
23. DeviceClient MyClient {get;set;}
24.
Appendix – Demo Code
18
25. static async Task Main(string[] args)
26. {
27. var device = new DoteNetDevice();
28. await device.InitIoTHubClientAsync();
29.
30. I2cConnectionSettings i2cSettings = new(1, 0x29);
31. using I2cDevice i2cDevice =
32. I2cDevice.Create(i2cSettings);
33. using Tcs3472x tcs3472X = new(i2cDevice);
34. long i = 0;
35. device.InitGpioController();
36.
Appendix – Demo Code
19
37. while (!Console.KeyAvailable)
38. {
39. Console.WriteLine(
40. $"ID: {tcs3472X.ChipId} Gain: {tcs3472X.Gain} Time to wait: {tcs3472X.IsClearInterrupt}");
41. var col = tcs3472X.GetColor();
42. var color = $"{col.R},{col.G},{col.B}";
43. device.LastColorName = col.Name;
44.
Console.WriteLine($"Valid data: {tcs3472X.IsValidData} Clear Interrupt: {tcs3472X.IsClearInterrupt}");
45.
46. if (tcs3472X.IsValidData)
47. {
48. Console.WriteLine(
49. $"{device.ReportingIntervalInSeconds} seconds trigger, sending data, color: {color}");
50. await device.SendAsync($"{{"color":"{color}"}}", (++i).ToString(), new CancellationToken());
51. }
52. await Task.Delay(TimeSpan.FromSeconds(device.ReportingIntervalInSeconds));
53. }
54. }
Appendix – Demo Code
20
55. private GpioController _gpioController;
56.
57. private void InitGpioController()
58. {
59. _gpioController = new GpioController ();
60. // Sets the pin to output mode so we can switch something on
61. _gpioController.OpenPin(Configuration.GreenLedPin,
62. PinMode.Output);
63. }
64.
Appendix – Demo Code
21
65. [C2DMessage(AutoComplete = true)]
66. private void Cloud2DeviceMessage(Message receivedMessage)
67. {
68. string messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
69. Console.WriteLine($"Received message: [{messageData}]");
70. try
71. {
72. var colors = messageData.Split(",");
73. var red = int.Parse(colors[0]);
74. var green = int.Parse(colors[1]);
75. var blue = int.Parse(colors[2]);
76.
77. Console.WriteLine($"Color: red:{red}, green:{green}, blue:{blue}");
78.
Appendix – Demo Code
22
79. if (green > red && green > blue)
80. {
81. _gpioController.Write(Configuration.GreenLedPin, PinValue.High);
82. }
83. else
84. {
85. _gpioController.Write(Configuration.GreenLedPin, PinValue.Low);
86. }
87. }
88. catch (System.Exception e)
89. {
90.
Console.WriteLine(e);
91. }
92. }
Appendix – Demo Code
23
93. [ConnectionStatus]
94. private (ConnectionStatus Status, ConnectionStatusChangeReason Reason) DeviceConnectionStatus { get; set; }
95.
96. [IoTHubErrorHandler]
97. void IoTHubErrorHandler(string errorMessage, Exception exception)
98. {
99. Console.WriteLine($"{errorMessage}, Exception: {exception.Message}");
100. }
101. }
102.}

Más contenido relacionado

La actualidad más candente

Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
維佋 唐
 

La actualidad más candente (19)

Extending Retrofit for fun and profit
Extending Retrofit for fun and profitExtending Retrofit for fun and profit
Extending Retrofit for fun and profit
 
Durable functions
Durable functionsDurable functions
Durable functions
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage coding
 
SPIFFE Meetup Tokyo #2 - Attestation Internals in SPIRE - Shingo Omura
SPIFFE Meetup Tokyo #2 - Attestation Internals in SPIRE - Shingo OmuraSPIFFE Meetup Tokyo #2 - Attestation Internals in SPIRE - Shingo Omura
SPIFFE Meetup Tokyo #2 - Attestation Internals in SPIRE - Shingo Omura
 
HTTP Middlewares in PHP by Eugene Dounar
HTTP Middlewares in PHP by Eugene DounarHTTP Middlewares in PHP by Eugene Dounar
HTTP Middlewares in PHP by Eugene Dounar
 
2012: ql.io and Node.js
2012: ql.io and Node.js2012: ql.io and Node.js
2012: ql.io and Node.js
 
Network programming1
Network programming1Network programming1
Network programming1
 
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkHacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
Manage software dependencies with ioc and aop
Manage software dependencies with ioc and aopManage software dependencies with ioc and aop
Manage software dependencies with ioc and aop
 
Talk KVO with rac by Philippe Converset
Talk KVO with rac by Philippe ConversetTalk KVO with rac by Philippe Converset
Talk KVO with rac by Philippe Converset
 
I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...
 
Tech Webinar: AUMENTARE LA SCALABILITÀ DELLE WEB APP CON SERVLET 3.1 ASYNC I/O
Tech Webinar: AUMENTARE LA SCALABILITÀ DELLE WEB APP CON SERVLET 3.1 ASYNC I/OTech Webinar: AUMENTARE LA SCALABILITÀ DELLE WEB APP CON SERVLET 3.1 ASYNC I/O
Tech Webinar: AUMENTARE LA SCALABILITÀ DELLE WEB APP CON SERVLET 3.1 ASYNC I/O
 
Fidl analysis
Fidl analysisFidl analysis
Fidl analysis
 
Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Webエンジニアから見たiOS5
Webエンジニアから見たiOS5
 
ITK Tutorial Presentation Slides-944
ITK Tutorial Presentation Slides-944ITK Tutorial Presentation Slides-944
ITK Tutorial Presentation Slides-944
 
Retrofit
RetrofitRetrofit
Retrofit
 
All you need to know about Callbacks, Promises, Generators
All you need to know about Callbacks, Promises, GeneratorsAll you need to know about Callbacks, Promises, Generators
All you need to know about Callbacks, Promises, Generators
 

Similar a Generating cross platform .NET based azure IoTdevice

Use Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDEUse Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDE
Benjamin Cabé
 

Similar a Generating cross platform .NET based azure IoTdevice (20)

A serverless IoT story from design to production and monitoring
A serverless IoT story from design to production and monitoringA serverless IoT story from design to production and monitoring
A serverless IoT story from design to production and monitoring
 
A serverless IoT Story From Design to Production and Monitoring
A serverless IoT Story From Design to Production and MonitoringA serverless IoT Story From Design to Production and Monitoring
A serverless IoT Story From Design to Production and Monitoring
 
IoT on Raspberry Pi
IoT on Raspberry PiIoT on Raspberry Pi
IoT on Raspberry Pi
 
Can we build an Azure IoT controlled device in less than 40 minutes that cost...
Can we build an Azure IoT controlled device in less than 40 minutes that cost...Can we build an Azure IoT controlled device in less than 40 minutes that cost...
Can we build an Azure IoT controlled device in less than 40 minutes that cost...
 
IoT on Raspberry PI v1.2
IoT on Raspberry PI v1.2IoT on Raspberry PI v1.2
IoT on Raspberry PI v1.2
 
Architecting IoT solutions with Microsoft Azure
Architecting IoT solutions with Microsoft AzureArchitecting IoT solutions with Microsoft Azure
Architecting IoT solutions with Microsoft Azure
 
Azure IoT hub
Azure IoT hubAzure IoT hub
Azure IoT hub
 
Essential Capabilities of an IoT Cloud Platform - April 2017 AWS Online Tech ...
Essential Capabilities of an IoT Cloud Platform - April 2017 AWS Online Tech ...Essential Capabilities of an IoT Cloud Platform - April 2017 AWS Online Tech ...
Essential Capabilities of an IoT Cloud Platform - April 2017 AWS Online Tech ...
 
Azure Internet of Things
Azure Internet of ThingsAzure Internet of Things
Azure Internet of Things
 
Essential Capabilities of an IoT Cloud Platform - AWS Online Tech Talks
Essential Capabilities of an IoT Cloud Platform - AWS Online Tech TalksEssential Capabilities of an IoT Cloud Platform - AWS Online Tech Talks
Essential Capabilities of an IoT Cloud Platform - AWS Online Tech Talks
 
Use Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDEUse Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDE
 
Azure Digital Twins.pdf
Azure Digital Twins.pdfAzure Digital Twins.pdf
Azure Digital Twins.pdf
 
IoT on azure
IoT on azureIoT on azure
IoT on azure
 
Programming IoT Gateways in JavaScript with macchina.io
Programming IoT Gateways in JavaScript with macchina.ioProgramming IoT Gateways in JavaScript with macchina.io
Programming IoT Gateways in JavaScript with macchina.io
 
Azure IoT suite - A look behind the curtain (Sam Vanhoutte @AZUG Event)
Azure IoT suite - A look behind the curtain (Sam Vanhoutte @AZUG Event)Azure IoT suite - A look behind the curtain (Sam Vanhoutte @AZUG Event)
Azure IoT suite - A look behind the curtain (Sam Vanhoutte @AZUG Event)
 
Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...
Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...
Athens IoT meetup #7 - Create the Internet of your Things - Laurent Ellerbach...
 
FIWARE Primer - Learn FIWARE in 60 Minutes
FIWARE Primer - Learn FIWARE in 60 MinutesFIWARE Primer - Learn FIWARE in 60 Minutes
FIWARE Primer - Learn FIWARE in 60 Minutes
 
Federico Michele Facca - FIWARE Primer - Learn FIWARE in 60 Minutes
Federico Michele Facca - FIWARE Primer - Learn FIWARE in 60 MinutesFederico Michele Facca - FIWARE Primer - Learn FIWARE in 60 Minutes
Federico Michele Facca - FIWARE Primer - Learn FIWARE in 60 Minutes
 
Create Your Own Serverless PKI with .NET & Azure Key Vault
Create Your Own Serverless PKI with .NET & Azure Key VaultCreate Your Own Serverless PKI with .NET & Azure Key Vault
Create Your Own Serverless PKI with .NET & Azure Key Vault
 
Microsoft Azure IoT Hub (Sam Vanhoutte @TechdaysNL 2017)
Microsoft Azure IoT Hub (Sam Vanhoutte @TechdaysNL 2017)Microsoft Azure IoT Hub (Sam Vanhoutte @TechdaysNL 2017)
Microsoft Azure IoT Hub (Sam Vanhoutte @TechdaysNL 2017)
 

Más de Alon Fliess

Más de Alon Fliess (9)

Generative AI in CSharp with Semantic Kernel.pptx
Generative AI in CSharp with Semantic Kernel.pptxGenerative AI in CSharp with Semantic Kernel.pptx
Generative AI in CSharp with Semantic Kernel.pptx
 
Zionet Overview
Zionet OverviewZionet Overview
Zionet Overview
 
Observability and more architecture next 2020
Observability and more   architecture next 2020Observability and more   architecture next 2020
Observability and more architecture next 2020
 
C# Production Debugging Made Easy
 C# Production Debugging Made Easy C# Production Debugging Made Easy
C# Production Debugging Made Easy
 
We Make Debugging Sucks Less
We Make Debugging Sucks LessWe Make Debugging Sucks Less
We Make Debugging Sucks Less
 
Architecting io t solutions with microisoft azure ignite tour version
Architecting io t solutions with microisoft azure ignite tour versionArchitecting io t solutions with microisoft azure ignite tour version
Architecting io t solutions with microisoft azure ignite tour version
 
To microservice or not to microservice - ignite version
To microservice or not to microservice - ignite versionTo microservice or not to microservice - ignite version
To microservice or not to microservice - ignite version
 
Net core microservice development made easy with azure dev spaces
Net core microservice development made easy with azure dev spacesNet core microservice development made easy with azure dev spaces
Net core microservice development made easy with azure dev spaces
 
DWX2018 IoT lecture
DWX2018 IoT lectureDWX2018 IoT lecture
DWX2018 IoT lecture
 

Último

Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Último (20)

WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 

Generating cross platform .NET based azure IoTdevice

  • 1. Cross-Platform Azure IoT Device With C# Source Code Generator and .NET 6.0 Alon Fliess Chief Architect alonf@codevalue.net @alon_fliess http://alonfliess.me http://codevalue.net
  • 2. Ingredients  IoT Device (Raspberry Pi)  .NET 6.0 + .NET IoT Libraries  C# Source Code Generator  Azure IoT Hub + Azure IoT Client SDK for C#  VS Code
  • 3. About Alon Fliess 3  Chief Architect & Founder – CodeValue  Microsoft Regional Director  Microsoft Azure MVP  alonf@codevalue.net  @alon_fliess  http://alonfliess.me  http://codevalue.net
  • 4. IoT 101 var sensorData = await _bmp180.GetSensorDataAsync(Bmp180.UltraHighResolution); var messageString = JsonConvert.SerializeObject(sensorData); var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString)); await deviceClient.SendEventAsync(message);
  • 5. .NET IoT Libraries System.Device.Gpio  Hardware + OS  Raspberry Pi, BeagleBoard, HummingBoard, ODROID, and other single-board-computers that are supported by Linux and Windows 10 IoT Core OS  Wraps hardware access libraries on both Windows and Linux  Provides API for:  General-purpose I/O (GPIO)  Inter-Integrated Circuit (I2C)  Serial Peripheral Interface (SPI)  Pulse Width Modulation (PWM)  Serial port Device Binding  Built on top of System.Device.Gpio  Cross-Platform hardware driver classes  Sensors, Displays, HMI devices and anything else that requires software to control  Cross-targeting .NET Standard 2.0 and up  Full Framework, 3.1, 5, 6, mono 5
  • 6. The wonder of Azure IoT Hub IoT Hub Receive device-to-cloud messages Send cloud-to-device messages Receive delivery acks Receive file notifications Direct method invocation Receive operations monitoring events Module identity management Module twin management Job Management Send device-to-cloud messages Receive cloud-to-device messages Initiates file uploads Retrieve and update twin properties Receive direct method requests Service Per-Device Configuration Management Message Routing Message Enrichment Device identity management Device twin management IoT Edge Device IoT Edge Management Device Twin Tags Properties Desired Reported
  • 7. What is a source generator?  It lets you generate source code  What does “generate source” mean?  Why isn’t he saying any of these bullet points?  So “source” I guess means source code  And “generate” means create  Wait.. Are source generators going to take our jobs?!
  • 8. Your .cs files The C# Compiler Project.dll Parse Source Generator Compile Emit CST AST CST Compilation IL Source (string) CST
  • 9. Referencing and Defining a Source Generator
  • 10. A Simplified Flow  Initialize  Register for a syntax node notification context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());  Syntax node notification  gather code generation information public void OnVisitSyntaxNode(SyntaxNode syntaxNode) { //collect information … }  Execute  Generate source files and add them to the compilation 10 Your Implementation
  • 11. IoTHubClientGenerator  Build an IoT Device client program in seconds  Handle configuration in multiple ways  Use IoT Device Connection String, or Device Provisioning Service  Support most of Azure IoT Hub protocols and protocols’ security  Support Device Twin, Sending Telemetry, Direct Method and Cloud to Device messages  Support device connection status changed notification 11
  • 12. Demo Show me an example! • Raspberry Pi • .NET 6.0 + .NET IoT Libraries • C# Source Code Generator • Azure IoT Hub + Azure IoT Client SDK for C# • VS Code
  • 13. Summary & Takeaways  .NET IoT Libraries – cross platform IoT foundation  Azure IoT Hub – cloud scale IoT Platform  C# + Source generators (IoTHubClientGenerator) – The easiest way to develop Azure connected IoT device 13
  • 15. Alon Fliess Chief Architect & Founder alonf@codevalue.net @alon_fliess http://alonfliess.me http://codevalue.net
  • 16. Appendix – Demo Code 1. using System; 2. using System.Device.I2c; 3. using System.Device.Gpio; 4. using System.Threading; 5. using Iot.Device.Tcs3472x; 6. using System.Threading.Tasks; 7. using IoTHubClientGeneratorSDK; 8. using Microsoft.Azure.Devices.Client; 9. using Microsoft.Azure.Devices.Client.Exceptions; 10. using Microsoft.Azure.Devices.Client.Transport.Mqtt; 11. using System.Text; 12.
  • 17. Appendix – Demo Code 17 13. namespace DotnetConf 14. { 15. [IoTHub(GeneratedSendMethodName = "SendAsync")] 16. partial class DotNetDevice 17. { 18. [Reported("LastColorName")] 19. private string _lastColorName; 20. [Desired] 21. private int ReportingIntervalInSeconds { get; set; } = 10; 22. [Device(ConnectionString="[Configuration.IoTHubConnectionString]")] 23. DeviceClient MyClient {get;set;} 24.
  • 18. Appendix – Demo Code 18 25. static async Task Main(string[] args) 26. { 27. var device = new DoteNetDevice(); 28. await device.InitIoTHubClientAsync(); 29. 30. I2cConnectionSettings i2cSettings = new(1, 0x29); 31. using I2cDevice i2cDevice = 32. I2cDevice.Create(i2cSettings); 33. using Tcs3472x tcs3472X = new(i2cDevice); 34. long i = 0; 35. device.InitGpioController(); 36.
  • 19. Appendix – Demo Code 19 37. while (!Console.KeyAvailable) 38. { 39. Console.WriteLine( 40. $"ID: {tcs3472X.ChipId} Gain: {tcs3472X.Gain} Time to wait: {tcs3472X.IsClearInterrupt}"); 41. var col = tcs3472X.GetColor(); 42. var color = $"{col.R},{col.G},{col.B}"; 43. device.LastColorName = col.Name; 44. Console.WriteLine($"Valid data: {tcs3472X.IsValidData} Clear Interrupt: {tcs3472X.IsClearInterrupt}"); 45. 46. if (tcs3472X.IsValidData) 47. { 48. Console.WriteLine( 49. $"{device.ReportingIntervalInSeconds} seconds trigger, sending data, color: {color}"); 50. await device.SendAsync($"{{"color":"{color}"}}", (++i).ToString(), new CancellationToken()); 51. } 52. await Task.Delay(TimeSpan.FromSeconds(device.ReportingIntervalInSeconds)); 53. } 54. }
  • 20. Appendix – Demo Code 20 55. private GpioController _gpioController; 56. 57. private void InitGpioController() 58. { 59. _gpioController = new GpioController (); 60. // Sets the pin to output mode so we can switch something on 61. _gpioController.OpenPin(Configuration.GreenLedPin, 62. PinMode.Output); 63. } 64.
  • 21. Appendix – Demo Code 21 65. [C2DMessage(AutoComplete = true)] 66. private void Cloud2DeviceMessage(Message receivedMessage) 67. { 68. string messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); 69. Console.WriteLine($"Received message: [{messageData}]"); 70. try 71. { 72. var colors = messageData.Split(","); 73. var red = int.Parse(colors[0]); 74. var green = int.Parse(colors[1]); 75. var blue = int.Parse(colors[2]); 76. 77. Console.WriteLine($"Color: red:{red}, green:{green}, blue:{blue}"); 78.
  • 22. Appendix – Demo Code 22 79. if (green > red && green > blue) 80. { 81. _gpioController.Write(Configuration.GreenLedPin, PinValue.High); 82. } 83. else 84. { 85. _gpioController.Write(Configuration.GreenLedPin, PinValue.Low); 86. } 87. } 88. catch (System.Exception e) 89. { 90. Console.WriteLine(e); 91. } 92. }
  • 23. Appendix – Demo Code 23 93. [ConnectionStatus] 94. private (ConnectionStatus Status, ConnectionStatusChangeReason Reason) DeviceConnectionStatus { get; set; } 95. 96. [IoTHubErrorHandler] 97. void IoTHubErrorHandler(string errorMessage, Exception exception) 98. { 99. Console.WriteLine($"{errorMessage}, Exception: {exception.Message}"); 100. } 101. } 102.}

Notas del editor

  1. The System.Device.Gpio package supports general-purpose I/O (GPIO) pins, PWM, I2C, SPI and related interfaces for interacting with low level hardware pins to control hardware sensors, displays and input devices on single-board-computers; Raspberry Pi, BeagleBoard, HummingBoard, ODROID, and other single-board-computers that are supported by Linux and Windows 10 IoT Core OS can be used with .NET Core and System.Device.Gpio.  On Windows 10 IoT Core OS, the library wraps the Windows.Devices.Gpio.dll assembly.  On Linux, the library supports three driver modes: libgpiod for fast full-featured GPIO access on all Linux distros since version 4.8 of the Linux kernel; slower and limited-functionality GPIO access via the deprecated Sysfs interface (/sys/class/gpio) when running on older Linux distro versions with a Linux kernel older than version 4.8; and lastly board-specific Linux drivers that access GPIO addresses in /dev/mem for fasted performance at the trade-off of being able to run on very specific versions of single-board-computers.  In the future, the board-specific Linux drivers may be removed in favor of only supporting libgpiod and sysfs Linux interfaces.  In addition to System.Device.Gpio, the optional IoT.Device.Bindings NuGet package contains device bindings for many sensors, displays, and input devices that can be used with System.Device.Gpio.
  2. Microsoft Azure IoT Hub provides capabilities for securely connecting, provisioning, updating and sending commands to devices. IoT Hub enables companies to control millions of IoT assets running on a broad set of operating systems and protocols to jumpstart their Internet of Things projects. IoT Hub enables companies to: Establish reliable bi-directional communication with IoT assets, even if they are intermittently connected, so companies can analyze incoming telemetry data and send commands and notifications as needed. Enhance security of IoT solutions by leveraging per-device authentication to communicate with devices with the appropriate credentials. Revoke access rights to specific devices, if needed, to maintain the integrity of the system.
  3. A Source Generator is a .NET Standard 2.0
  4. CST- Concrete Syntax Tree https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/ A Source Generator is a new kind of component that C# developers can write that lets you do two major things: Retrieve a Compilation object that represents all user code that is being compiled. This object can be inspected and you can write code that works with the syntax and semantic models for the code being compiled, just like with analyzers today. Generate C# source files that can be added to a Compilation object during the course of compilation. In other words, you can provide additional source code as input to a compilation while the code is being compiled.
  5. Demonstrate using source code generator from NuGet