65.9K
CodeProject is changing. Read more.
Home

Simple Connection Between Raspberry Pi 2 with Windows 10 IoT to PC using C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.14/5 (5 votes)

Feb 24, 2016

CPOL

2 min read

viewsIcon

60749

downloadIcon

1431

This project will show how send a simple string between Raspberry Pi 2 with Windows 10 IoT and PC using C# over networking TCP/IP, where Raspberry is a server and PC is the client.

Introduction

This project will show you how to send a simple string between Raspberry Pi 2 with Windows 10 IoT and PC with Windows 10 using C# and UWP(Universal Windows Platform) over TCP/IP network, where Raspberry is a server and PC is a client and PC sends a message to Raspberry.

Background

UWP - Universal Windows Platform

UWP is a new type of project from Microsoft which allows applications to run in any Windows platform (like Windows 8 or superior, Xbox, Windows phone, etc.) without any modification, and now you have a “Manifest”, if you don't give permission in manifest, your app won't work. For further information, access this link:

Windows 10 IoT Core

Windows 10 IoT Core is a version of Windows 10 that is optimized for small devices with or without display. When this article was written, Windows 10 IoT Core supported the following devices:

  • Raspberry Pi 2
  • Arrow DragonBoard 410c
  • MinnowBoard MAX.

You can use UWP to develop apps for Windows 10 IoT Core. For more information, access this link:

Project

For this project, one “Solution” with two projects were created, one using UWP(client) and the other using Background IoT(Server). To access the entire project, access this link:

Diagram

Receiving String (Server)

Here, I’m going to show how to bind some port and wait for a connection. For that, a SocketServer class was made.

Variables

private readonly int _port;
public int Port { get { return _port; } }

private StreamSocketListener listener;

public delegate void DataRecived(string data);
public event DataRecived OnDataRecived;


public delegate void Error(string message);
public event Error OnError;

Bind Port

public async void Star() 
{ 
    listener = new StreamSocketListener(); 
    listener.ConnectionReceived += Listener_ConnectionReceived; 
    await listener.BindServiceNameAsync(Port.ToString()); 
}

Wait Receive Message

private async void Listener_ConnectionReceived
(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{ 
    var reader = new DataReader(args.Socket.InputStream); 
    try 
    { 
        while (true) 
        { 
            uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); 
            //if disconnected 
            if (sizeFieldCount != sizeof(uint)) 
                return; 
            uint stringLenght = reader.ReadUInt32(); 
            uint actualStringLength = await reader.LoadAsync(stringLenght); 
            //if disconnected 
            if (stringLenght != actualStringLength) 
                return; 
            if (OnDataRecived != null) 
                OnDataRecived(reader.ReadString(actualStringLength)); 
            } 
    } 
    catch (Exception ex) 
    { 
        if (OnError != null) 
            OnError(ex.Message); 
    } 
}

Start Application

public void Run(IBackgroundTaskInstance taskInstance)
{
    ...
    taskInstance.GetDeferral();
    var socket = new SocketServer(9000);
    ThreadPool.RunAsync(x => {
        socket.Star();
        socket.OnError += socket_OnError;
        socket.OnDataRecived += Socket_OnDataRecived;
    });
}  

And don't forget to give the app the ability to be client and server, see the image below:

Send String (Client)

The client was tested in Windows 10 with UWP. To send strings, it created a SocketClient class:

Variable

private readonly string _ip;
private readonly int _port;
private StreamSocket _socket;
private DataWriter _writer;
private DataReader _reader;

public delegate void Error(string message);
public event Error OnError;

public delegate void DataRecived(string data);
public event DataRecived OnDataRecived;

public string Ip { get { return _ip; } }
public int Port { get { return _port; } }

Connect

For creating a connection, you need this code:

public async void Connect()
{
    try
    {
        var hostName = new HostName(Ip);
        _socket = new StreamSocket();
        await _socket.ConnectAsync(hostName, Port.ToString());
        _writer = new DataWriter(_socket.OutputStream);
        Read();
    }
    catch (Exception ex)
    {
        ..
    }
}

Send String

public async void Send(string message)
{
    _writer.WriteUInt32(_writer.MeasureString(message));
    _writer.WriteString(message);

    try
    {
        await _writer.StoreAsync();
        await _writer.FlushAsync();
    }
    catch (Exception ex)
    {
        ...
    }
}

Read

To read something, the code is the same code used in class ServerSocket.

Close

public void Close()
{
    _writer.DetachStream();
    _writer.Dispose();

    _reader.DetachStream();
    _reader.Dispose();

    _socket.Dispose();
}

Conclusion

To create a simple connection to send a string, you don't need a complex or a large code, and it's simple to use C# with UWP, and now it’s possible to grow some application and create something more complex. UWP is good, but you have many things to learn, because it's a new framework and it introduces a new concept about design and development, since most methods will be async.

Acknowledgements

I would like to thank my two friends, Guilherme Effenberger and Ricardo Petrére, for helping me to write and translate this text.