Upload
hiang-meng-heng-marvin
View
74
Download
2
Embed Size (px)
Citation preview
How Mobile AppCan Communicate with IoT Devicesvia NetworkMarvin HengTwitter : @hmhengBlog : http://hmheng.azurewebsites.netGithub: https://github.com/hmheng
Pre-requisite• Installed Visual Studio 2017 for Windows with Xamarin
Cross-Platform component & all necessary platform-specific SDK. (Download a FREE Community Version here)
• Create a cross platform mobile app with .NETStandard 2.0(Learn to how to create one here)
Communicate between App & IoT Devices1. Launch your Visual Studio 2017 (VS2017), follow this tutorial to create a .NET Standard Cross Platform Mobile App.
2. Let’s delete the “Welcome to Xamarin.Forms!” label.3. Add in these lines to MainPage.xaml.
<?xml version="1.0" encoding="utf-8" ?><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"xmlns:local="clr-namespace:HmhengXamNet"x:Class="HmhengXamNet.MainPage">
<ContentPage.Content><StackLayout>
<Label Text="Welcome to Xamarin.Forms!"VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" />
<Entry x:Name="txtIPAddress" Text="192.168.0.103" /><Entry x:Name="txtPort" Text="7000" /><Entry x:Name="txtMessage" Text="Message" /><Button x:Name="btnConnect" Text=“Send" />
</StackLayout></ContentPage.Content>
</ContentPage>
Communicate between App & IoT Devices
3
2
4. Now, let’s create a SendUDP function that’ll eventually read the entered IP, Port Number & Message and perform a send.
public void ConnectUDP(object sender, EventArgs e){
UdpClient ucpClient = new UdpClient();IPAddress ipAddress = IPAddress.Parse(txtIPAddress.Text);IPEndPoint endPoint = new IPEndPoint(ipAddress,
Int32.Parse(txtPort.Text));
Byte[] data = Encoding.ASCII.GetBytes(txtMessage.Text);ucpClient.Send(data, data.Length, endPoint);
}
Communicate between App & IoT Devices
4
5. You may notice red underlined errors that can be resolved by adding reference to System.Net & System.Net.Sockets.
…using System.Net;using System.Net.Sockets;…
Communicate between App & IoT Devices
5
6. Last, but not least, we need to bind the btnConnect to the function of SendUDP.
public MainPage(){
InitializeComponent();btnConnect.Clicked += SendUDP;
}
Communicate between App & IoT Devices
6
7. Let’s compile, run and send some messages through network to an App that’s listening to same specified UDP port.
Communicate between App & IoT Devices
Congratulation!You’ve Created Your Very First Xamarin Cross-Platform App with VS2017!
How Mobile App Can Communicate with IoT Devices via NetworkMarvin HengTwitter : @hmhengBlog : http://hmheng.azurewebsites.netGithub: https://github.com/hmheng