Webifi.me

C# Library Documentation

 

Index

1. Introduction
2. Webifi
2.1 Properties
2.2 Methods
2.3 Events
3. WebifiControl
3.1 Control
3.2 Properties
3.3 Methods
3.4 Events
3.5 WPF Control: UserControlWebifi
4. WebifiDataToSend
5. Discovery message
6. SerialPortControl
6.1 Properties
6.2 Methods
6.3 Events
6.4 WPF Control: UserControlSerialPort

1. Introduction

To install the library in Visual Studio, open the Package Manager Console and type the following:

Install-Package webifiLib

If you already have this package installed and want to update to the latest version:

Update-Package webifiLib

If you would like the two visual controls to show in the Visual Studio toolbox, right click in the toolbox and select Choose Items… Under .NET Framework components, click the Browse button. Go to your project directory and then delve down into the packages directory until you can select Webifi.dll. This should add 2 controls:

  1. SerialPortControl
  2. WebifiControl

This document describes all the classes and components that make up the Webifi C# Library. There are 4 public classes available under the webifiLib namespace:

  1. Webifi
  2. WebifiControl
  3. WebifiDataToSend
  4. SerialPortControl

Each of the classes are explained in more detail below.

2. Webifi

Webifi is the base class used for communication using our service. WebifiControl uses this class but adds a lot of extra functionality. For most users we would recommend using WebifiControl. To create a new instance of Webifi you need the connect name, connect password and at least one network name. This is configured on www.webifi.me.
Below is an example:

string connectName = "webifi";
string connectPassword = "12345678";
List<string> networks = new List<string>();
networks.Add("network 1");
WebifiLib.Webifi webifi = new WebifiLib.Webifi(connectName, connectPassword, networks);

2.1 Properties

Property Description
connected This is a read only property, when it is true then you are connected to our service.
connectName A read only property of the connect name that was set when the object was instantiated. To change the connectName a new instance of Webifi has to be created.
connectPassword A read only property of the network password that was set when the object was instantiated. To change the network password a new instance of Webifi has to be created.
discoverable When this value is true and a discovery message is received then an automatic discovery response will be sent containing the name and session ID of this instance. The default value of this property is true.
downloadRequestTimeout The maximum amount of time a download request should wait if there is no data available. A smaller number uses more bandwidth and a large number will take a long time to recover when something goes wrong with the connection. The default value is 2 minutes and the maximum value is 10 minutes. Normally the user does not need to change this value. This is only used with Long Polling.
httpDownloadRequestCount Each time a download request is started this counter is incremented. This is useful for seeing how many download requests have been made since the service started. This property is read only and only used with Long Polling.
httpUploadRequestCount Each time data is uploaded this counter is incremented. This property is read only and only used with Long Polling.
name A user defined name for this instance of Webifi. This is the name other devices will see when they discover this instance.
networkNames A generic list of network names that this instance should listen to.
networkNamesString This property sets and returns the same values as networkNames except that the property type is string instead of a list. Each network name is separated by a new line character. That makes this property easier to work with in some cases than a generic list.
sessionId A read only property set to the address of this instance on the Webifi network. This property is important if you design more complex systems where you would like another device to only send data to you.
useEncryption When set to true all the data will be exchanged using SSL/TLS.
useWebSocket Set to true if you want all communication to use HTML 5 WebSocket. If false then long polling will be used for exchanging data.

2.2 Methods

Method Description
CloseConnection Call this function when you want to stop using our service, for example when you close the program that uses our library.
GetBufferedAmount This function returns the number of send packets (not the number of bytes) that is currently in the queue for sending.
GetErrorCodeDescription This is a handy function to get the meaning of an error code. For example, if the error code “8” is passed into this function then the value returned should be: “Invalid connect name or password”.
SendData This function is used to send data to your other devices connected to our service. It’s input parameter is a reference to a WebifiDataToSend class. This class is explained in more detail later in this document.
SendDiscovery Call this function to discover the names and session IDs of your other devices currently connected. There are two overloads for this function. The first takes no arguments and sends the discovery to this instance’s default networks. The second takes a generic list of network names to send the discovery message to. Discovery messages are explained in more detail later in this document.
SetNewNetworkNames It is important that the user can change the networks that the devices are part of at any time. This function takes a generic list of strings as an input. For example:

List<string> networks = new List<string>();
networks.Add("room 1");
networks.Add("kitchen");
networks.Add("back yard");
webifi.SetNewNetworkNames(networks);
StartService The function will start the service and create a connection to the Webifi server.

2.3 Events

Event Description
connectionStatusEvent This event is called each time the connection status changes, in other words when your device connects or disconnects from our service.
dataReceivedEvent When data is received from another device this event is called. There are three variables passed to this event:

  • data: A byte array with the data that was received
  • dataType: This optional field is a string that the sending device can use. This can be useful for implementing basic protocols.
  • fromSessionID: The session ID or address on the Webifi server that sent the message to this device. This is useful if you only want to send data to a specific device.
errorEvent When something goes wrong then the error event is called. The error code is passed into the event in the variable: errorCode.

Below is an example of how the events can be used:

private void Form1_Load(object sender, EventArgs e)
{
  //configure information needed for establishing connection
  string connectName = "webifi";
  string connectPassword = "12345678";
  List<string> networks = new List<string>();
  networks.Add("network 1");
  WebifiLib.Webifi webifi = new WebifiLib.Webifi(connectName, connectPassword, networks);

  //configure event functions to be called by webifi
  webifi.connectionStatusEvent += ConnectionStatusEvent;
  webifi.dataReceivedEvent += DataReceivedEvent;
  webifi.errorEvent += ErrorEvent;

  webifi.StartService();
}

private void ConnectionStatusEvent(object sender, bool connected)
{
  if (connected)
  {
    //service is running, you can start sending data
  }
  else
  {
    //service got disconnected
  }
}

private void DataReceivedEvent(object sender, byte[] data, string dataType, int fromSessionID)
{
  //new data received
}

private void ErrorEvent(object sender, string errorCode)
{
  //there was an error
}

3. WebifiControl

WebifiControl is a Windows Forms visual control with the Webifi class at its core which makes it is much easier to use. It has the following advantages:

  • It is much easier to configure the properties and events because this can be done in the Properties window of Visual Studio.
  • With the Webifi class all the events are triggered in a separate thread, which means you have to use a delegate to get the data in the same thread as the code used with your form. All this is already done for you when you use WebifiControl.

See our C# Tutorial for an example of how to use this control.

3.1 Control

The control can be configured in the following two ways:
When ShowControls is true:
WebifiControl when ShowControls is true
When ShowControls is false:
WebifiControl when ShowControls is false
This allows the user to choose between a minimal control where more of the functionality must be programmatically controlled or a full featured control where the user can enter most of the details. For the full featured control, when the user presses the “Set Network Names” button a window comes up that allows the user to set the networks:
Set network names window
When the user clicks on the Start button, after the control successfully connects to the Webifi server the red square will turn into a green tick mark. This gives a visual indication that everything is working.
Control with service running

3.2 Properties

Property Description
Connected This is a read only property, when it is true then you are connected to our service.
ConnectName The connect name chosen by the user on webifi.me. This value cannot be changed after the service started.
ConnectPassword The connect password for this user. This value cannot be changed after the service started.
Discoverable When this value is true and a discovery message is received then an automatic discovery response will be sent containing the name and session ID of this instance. The default value of this property is true.
DownloadRequestTimeout The maximum amount of time a download request should wait if there is no data available. A smaller number uses more bandwidth and a large number will take a long time to recover when something goes wrong with the connection. The default value is 2 minutes and the maximum value is 10 minutes. This value is only used with Long Polling, not applicable to WebSocket.
NetworkNames A list of network names that this instance should listen to.
SessionId A read only property set to the address of this instance on the Webifi network. This property is important if you design more complex systems where you would like another device to only send data to you.
ShowControls When this value is set to false then only the Start/Stop button and the connected icon is shown. When it is set to true then all the controls are shown
UseEncryption When set to true all the data will be exchanged using SSL/TLS.
UseWebSocket Set to true if you want all communication to use HTML 5 WebSocket. If false then Long Polling will be used for exchanging data.

3.3 Methods

Method Description
GetBufferedAmount This function returns the number of send packets (not the number of bytes) that is currently in the queue for sending.
GetErrorCodeDescription This is a handy function for getting a description of an error code.
GetCounters Return an instance of webifiCounters which contains the upload and download counters. The upload counter is incremented each time data is uploaded and the download counter is incremented each time a download request is started. Only applicable to Long Polling.
SendData Send data to your other devices connected to our network. It takes an instance of the WebifiDataToSend class as parameter. The WebifiDataToSend class is described in detail later in this document.
SendDiscovery Call this function to discover the names and session IDs of your other devices currently connected. There are two overloads for this function. The first takes no arguments and sends the discovery to this instance’s default networks. The second takes a generic list of network names to send the discovery message to. Discovery messages are explained in more detail later in this document.
Start Start the service and create a connection to the server.
Stop Stop the service and terminates any blocked download requests.

3.4 Events

Event Description
ConnectionStatus This event is called each time the connection status changes, in other words when your device connects or disconnects from our service.
DataReceived When data is received from another device this event is called. There are three variables passed to this event:

  • data: A byte array with the data that was received
  • dataType: This optional field is a string that the sending device can use. This can be useful for implementing basic protocols.
  • fromSessionID: The session ID or address on the Webifi server that sent the message to this device. This is useful if you only want to send data to a specific device.
Error When something goes wrong then the error event is called. The error code is passed into the event in the variable: errorCode.

3.5 WPF Control: UserControlWebifi

We also have a WPF control with the same properties, methods and events as the Windows Forms control. For an example on how this control is used, please have a look at: https://github.com/webifi-me/WpfExamples.
The only difference is that the control uses networkNamesStrings, which is a string instead of networkNames, which is a list of strings.

4. WebifiDataToSend

This class is used for holding all the variables when sending your data using this library. Both Webifi and WebifiControl uses this class as the variable for its SendData method. It contains the following variables:

Name Data Type Initialised As
dataForSending byte[] Not initialised
dataType string “”
toSessionIDs List<int> List<int>()
toNetworks List<string> List<string>()

The variables in this class are initialised in such a way that the user only has to populate the dataForSending field to send data if no special setting are needed. When only the dataForSending field is set then the data will be sent to all the devices that are on the same networks as this instance of the library. Each field is explained in more detail below:

Name Description
dataForSending Any data that will be sent must be converted to a byte array first. See the examples below for how a string will be sent.
dataType This optional field allows the user to add extra information to the data without adding your own protocol. For example, if the receiving device contains two serial ports then the data type field can be “Com 1” or “Com 2”. The receiving device can then easily send the data to the correct serial port without having to decode a protocol.
toSessionIDs Each device receives a session ID when it connects to the Webifi server. This ID can be used to send data to specific devices. You can use the SendDiscovery function to find the session IDs of your other connected devices. When you recieve a message it will always contain the session ID of the device that sent the message. This allows you to reply to this specific device by setting this field to the same value as the received message’s session ID.
toNetworks The user can choose to which of the networks the message must be sent. The library can send data to other networks than the one it is listening to, as long as the network belongs to the same connect name.

Examples (This assumes that the library instance is already connected):

//Send a string to your default networks:
WebifiLib.WebifiDataToSend dataToSend = new WebifiLib.WebifiDataToSend();
string sendStr = "This is my data";
dataToSend.dataForSending = System.Text.Encoding.UTF8.GetBytes(sendStr);
webifi.SendData(dataToSend);
//or
webifiControl1.SendData(dataToSend);

In the next example we want to send the data received from the Serial Port Control (this control is explained in more detail in the next section). Assume that two of your devices have addresses 40 and 68, you would like to send a message only to these two devices:

private void serialPortControl1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e, byte[] recData)
{
  WebifiLib.WebifiDataToSend dataToSend = new WebifiLib.WebifiDataToSend();
  dataToSend.dataForSending = recData;
  //if the data will be sent from more than one source then the data type 
  //field can be used to indicate the data meaning
  dataToSend.dataType = "SP1";  //data coming from Serial Port 1
  //here the numbers are statically added. The user program will need to know what the 
  //session IDs of the other devices are
  dataToSend.toSessionIDs.Add(40);
  dataToSend.toSessionIDs.Add(68);
  webifi.SendData(dataToSend);
}

The message can also be sent to any of the user networks configured on the Webifi website:

WebifiLib.WebifiDataToSend dataToSend = new WebifiLib.WebifiDataToSend();
//in this example we use a generic list to build a byte array. We add the ASCII numbers 0 to 9
List<byte> sendData = new List<byte>();
for (int i = 0; i < 10; i++)
{
  sendData.Add((byte)(i + 0x30));
}
dataToSend.dataForSending = sendData.ToArray();
dataToSend.toNetworks.Add("Home network");
dataToSend.toNetworks.Add("Office network");
webifi.SendData(dataToSend);

5. Discovery message

The session IDs are dynamically assigned to devices connecting to the Webifi server. If you need to send data to a specific device or devices then you need to know their session IDs. The discovery message is an easy way to find the session IDs of all your connected devices. When you call the Send Discovery function the following message will be sent:

  • Data type: Discovery
  • Data: ? (A question mark character needs to be sent)
  • To networks: When empty then the discovery message will be sent to the default networks the sending device is listening to. If a list of networks are specified then all the discoverable devices on these networks will respond.

There isn’t a special event handler for the discovery response, the responses will be received by the data received event. This gives the most flexibility for the user to process the discovery responses any way the user needs. The discovery response looks as follows:

  • Data type: Discovery Response
  • Data: User defined name on the responding device
  • From session ID: The session ID that was discovered. This needs to be stored by the device doing the discovery.

Below is an example of how the discovery can be implemented by the user:

private List<string> discoveredNames;
private List<int> discoveredSessionIDs;
private void buttonDiscover_Click(object sender, EventArgs e)
{
  //Button click event. Clear the discovered devices lists and send a new discovery message.
  discoveredNames = new List<string>();
  discoveredSessionIDs = new List<int>();
  webifiControl1.SendDiscovery();
}

private void webifiControl1_DataReceived(object sender, byte[] data, string dataType, int fromSessionID)
{
  if (dataType == "Discovery Response")
  {
    //The data received is a discovery response
    string discoveredName = WebifiLib.Webifi.ConvertByteArrayToString(data);  //convert byte array to string
    discoveredNames.Add(discoveredName);
    discoveredSessionIDs.Add(fromSessionID);
    //add more code here if you need to do more processing when a device is discovered
  }
  else
  {
    //A normal message was received from a device. Process the message here.
  }
}

6. SerialPortControl

The SerialPortControl is a visual control that encaptulates the Microsoft SerialPort class. Full documentation for the SerialPort class can be viewed at Microsoft SerialPort Class.
The control looks as follows:
WebifiSerialPort
When the refresh button is pressed the list of available serial ports in the combo box is updated. The Open/Close button will open and close the selected serial port. The SerialPortControl control instantiates an instance of the Microsoft SerialPort when it gets created. If the user prefers to access the underlying serial port or needs to access a property or method that is not brought out by the SerialPortControl then the underlying serial port can be accessed as follows:

//the serial port control name is serialPortControl1
serialPortControl1.serialPort.BaudRate = 115200;

6.1 Properties

The following properties are brought out from the SerialPortControl without any change:

  • BaudRate
  • DataBits
  • DiscardNull
  • DtrEnable
  • Handshake
  • Parity
  • ParityReplace
  • PortName
  • ReadBufferSize
  • ReadTimeout
  • ReceivedBytesThreshold
  • RtsEnable
  • StopBits
  • WriteBufferSize
  • WriteTimeout

All of these properties can be edited in the Properties window:
Serial port properties window
One of the big advantages of using this control is that the received data can immediately be processed and placed in a visual control. The Microsoft serial port is running in a separate thread. That means the data read directly from the Microsoft serial port cannot be placed directly in a visual control, a delegate must be used to get the data into the same thread as the visual components. Because the SerialPortControl runs in the same thread as the form it can take care of these details and then the user directly use the received data.

6.2 Methods

6.2.1 IsOpen

Method definition:
bool IsOpen(bool tryToOpen)

Variable Description
tryToOpen Set this to true if you would like to try to open the serial port if it is not already open.
Return value True if the serial port is open or was opened by this function.

The IsOpen method is handy when you want to check if it is open and if it is not open then try to open it. There are instances where the user forgets to press the open button and the correct serial port is selected in the SerialPortControl. Instead of showing an error message this will open the serial port and the application will give a much better user experience.

//the serial port control name is serialPortControl1
string dataForSending = "Test string 1 2 3";
if (serialPortControl1.IsOpen(true))
{
  serialPortControl1.Write(dataForSending);
}

6.2.2 RefreshSerialPorts

Method definition:
void RefreshSerialPorts()
This method refreshes the list of available serial ports in the Serial Ports combo box. This is the same function called by the Refresh button on the control.

6.2.3 Write

Method definitions:
void Write(string text)
void Write(byte[] buffer, int offset, int count)
void Write(char[] buffer, int offset, int count)
These three overloaded methods are exactly the same as the Write methods from the Microsoft SerialPort class. For full documentation about these methods please see the
Microsoft SerialPort Write help page.

6.3 Events

The following 4 events are available from the SerialPortControl:

  • SerialPortStatusChanged
  • ErrorReceived
  • PinChanged
  • DataReceived

6.3.1 SerialPortStatusChanged Event

Event definition:
public event serialPortStatusChangedDelegate SerialPortStatusChanged
public delegate void serialPortStatusChangedDelegate(bool portOpen);

This event is raised each time the serial port is opened or closed. When the user clicks the open button and the serial port was successfully opened then this event lets the user’s code know that it can start sending information. Otherwise the user code would have to poll the serial port continuously to see if it is open.

private void Form1_Load(object sender, EventArgs e)
{
  //if the user prefers to manually add the event handler to the serialPortControl event uncomment the line below
  //serialPortControl1.SerialPortStatusChanged += serialPortControl1_SerialPortStatusChanged;
}

//the serial port control name is serialPortControl1
private void serialPortControl1_SerialPortStatusChanged(bool portOpen)
{
  if (portOpen)
  {
    serialPort1.Write("Port is now open");
    //from now on the application can communicate with the serial port
    //RunCommsStateMachine();   
  }
}

6.3.2 DataReceived Event

Event definition:
public event DataReceivedDelegate DataReceived
public delegate void DataReceivedDelegate(object sender, SerialDataReceivedEventArgs e, byte[] recData)

This event is very similar to the event raised by the Microsoft serial port, its documentation is available at:
SerialPort.DataReceived Event Documentation.
The SerialPortControl DataReceived event has the received data (byte[] recData) as one of its variables. With the Microsoft serial port you have to manually read the received data from the serial port. The received data from our control can be processed immediately because the SerialPortControl uses a delegate to get the data into the same thread as the visual controls. The reading of the data is only done if you subscribed to the SerialPortControl’s DataReceived event. This means that you can still use the base serial port DataReceived event if you need functionality that is not taken care of in the SerialPortControl.

6.3.3 ErrorReceived Event

Event definition:
public event ErrorReceivedDelegate ErrorReceived
public delegate void ErrorReceivedDelegate(object sender, SerialErrorReceivedEventArgs e)

This event is exactly the same as the event raised by the Microsoft serial port, its documentation is available at:
SerialPort.ErrorReceived Event Documentation.

6.3.4 PinChanged Event

Event definition:
public event PinChangedDelegate PinChanged
public delegate void PinChangedDelegate(object sender, SerialPinChangedEventArgs e)

This event is exactly the same as the event raised by the Microsoft serial port, its documentation is available at:
SerialPort.PinChanged Event Documentation.

6.4 WPF Control: UserControlSerialPort

We also have a WPF control with the same properties, methods and events as the Windows Forms control. For an example on how this control is used, please have a look at: https://github.com/webifi-me/WpfExamples.