Silverlight on the Netduino
Having been working with the Netduino Plus for a few week I wanted to look at the possibility of using the network to communicate with the board. Having browsed the forums on the Netduino home page I found a few discussions about using this board as a web server including using a WiFly board to hook up to a wireless network. The SDK also comes with several examples of network programming with the micro framework.
Objective
Allow the PC to send and receive data to the Netduino Plus over a wired network.
Main Program
The Netduino Plus board does not have the same resources available to the programmer you would normally find in a PC environment. This leaves the programmer with little to work with. The HTTP server supplied as a sample with the micro framework occupies a substantial amount of memory on the board.
One of the simpler examples provided with the framework implements a very simple server. A little bit of redesign and coding converted this into a very basic web server. The server is capable of serving a few file types (HTML, JPG, CSS, Javascript and XAP) to the client.
The main program is a simple affair. It contains a few definitions to support the file locations for the web files along with a small amount of code to offer “I am alive” feedback to the user.
For the “I am alive” feedback I have chosen to use the on board LED and button. The LED will flash twice when the user presses the on board button. A small power saving I know.
The final job of the main program is to instantiate the web server. This will start the server listening on the specified port.
private static OutputPort _onBoardLED;
private static InterruptPort _onBoardButton;
public static void Main()
{
_onBoardLED = new OutputPort(Pins.ONBOARD_LED, false);
_onBoardButton = new InterruptPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
_onBoardButton.OnInterrupt += new NativeEventHandler(onBoardButton_OnInterrupt);
_webServer = new WebServer(WEB_ROOT, WebServer.HTTP_PORT);
Thread.Sleep(Timeout.Infinite);
}
///
/// Flash the on board LED to let the user know we are still alive.
///
private static void onBoardButton_OnInterrupt(uint data1, uint data2, DateTime time)
{
if (data2 == 0)
{
_onBoardLED.Write(true);
Thread.Sleep(250);
_onBoardLED.Write(false);
Thread.Sleep(250);
_onBoardLED.Write(true);
Thread.Sleep(250);
_onBoardLED.Write(false);
}
}
The code for this can be found in SimpleWebServer.zip.
The files served provides a static web site to the client (a trip back to the 1990s).
Web Server
The web server class contains the methods to create a non blocking web server which will listen to the network on the specified socket and process the requests.
The constructor for the class sets up the local variables and creates a new thread to listen for requests:
public WebServer(string webFilesLocation, int portNumber)
{
_webRoot = webFilesLocation;
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind(new IPEndPoint(IPAddress.Any, portNumber));
_socket.Listen(int.MaxValue);
new Thread(Listen).Start();
}
The Listen method does the main work of listening to the socket, getting the request and converting it to a string which can be processed and finally closing the socket.
private void Listen()
{
while (true)
{
using (Socket client = _socket.Accept())
{
int requestSize;
byte[] buffer;
int amountRead;
string request;
requestSize = client.Available;
buffer = new byte[RECEIVE_BUFFER_SIZE];
Debug.Print("Request received from " + client.RemoteEndPoint.ToString() + " at " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss"));
amountRead = client.Receive(buffer, RECEIVE_BUFFER_SIZE, SocketFlags.None);
request = new string(Encoding.UTF8.GetChars(buffer));
Debug.Print(request);
ProcessRequest(client, request);
buffer = null;
request = null;
client.Close();
}
}
}
The method which processes the request is a simple method which is designed to check the first list of the request and verify that the web server can understand the protocol of the request. This server can only process HTTP 1.1 get requests. The first line of such a request should come through as something like the following:
GET filename.html HTTP/1.1
The ProcessRequest method looks something like the the following:
private void ProcessRequest(Socket client, string request)
{
string[] firstLine;
firstLine = request.Substring(0, request.IndexOf('n')).Split(' ');
if (firstLine[0].ToLower() != "get")
{
Send(client, HTTP_501_NOT_IMPLEMENTED);
}
else
{
if (firstLine[2].ToLower() != "http/1.1r")
{
Send(client, HTTP_505_HTTP_VERSION_NOT_SUPPORTED);
}
else
{
SendFile(client, firstLine[1]);
}
}
}
The constants in upper case contain response strings indicating that the web server has encountered an error.
The key work for sending the files and processing commands can be found in the SendFile method. The first thing this method does is to check on the file name to see if it is the “special command” file. If it is then the query string is passed to the command processor. All other requests are processed as request for files which should exist on the server. The system works out if it understands the file type and if it does then the file is sent to the client.
One design decision taken was to restrict the output to the client to 256 byte chunks. This decision was made in order to conserve memory.
Commands
The eventual aim is to connect sensors etc. to the Netduino and then read the data from them over the network. In order to test the theory a “dummy” sensor was added to the command processor. This simply returned the number of milliseconds from the current time divided by 100.
TimeSpan time;
tme = Utility.GetMachineTime();
Send(client, "Time " + time.Hours + ":" + time.Minutes + ":" + time.Seconds);
By using the command.html file and the QueryString we can test the system by making a simple request from the web browser. For instance:
http://192.168.10.100/Command.html?GetTemperature
could be interpreted as a request to read the temperature from a sensor attached to the board.
Silverlight Client
The next step was to look at dynamic content. The board is not powerful enough to support conventional technologies such as PHP or ASP. Silverlight offers the ability to move the dynamic content creation away from the web server and onto the client desk top. To demonstrate this, a simple Silverlight application was created to be served by the web server (hence the support for XAP files). The initial version simply said hello to the user.
So far, so good. The web server was serving HTML and Silverlight files to the client.
The next step was to flesh out the Silverlight client to hold sensor data and display this to the user. This part of the application is implemented in MVVM. For this I needed a class to hold a sensor reading and a class (TemperatureReading)to hold a collection of sensor readings (TemperatureViewModel).
public class TemperatureReading
{
///
/// Date and time the reading was recorded.
///
public DateTime When { get; set; }
///
/// Temperature.
///
public double Temperature { get; set; }
///
/// Constructor
///
/// <param name="when" />When was the reding taken
/// <param name="temperature" />Reading taken
public TemperatureReading(DateTime when, double temperature)
{
When = when;
Temperature = temperature;
}
}
public class TemperatureViewModel : INotifyPropertyChanged
{
#region Properties
///
/// Collection of temperature readings.
///
private ObservableCollection _readings;
public ObservableCollection Readings
{
get { return (_readings); }
set
{
_readings = value;
RaisePropertyChanged("Readings", "NumberOfReadings");
}
}
///
/// Number of readings in the collection of temperature readings.
///
public int NumberOfReadings
{
get { return (_readings.Count); }
}
#endregion
#region Constructor(s)
///
/// Default constructor
///
public TemperatureViewModel()
{
Readings = new ObservableCollection();
}
#endregion
#region INotifyPropertyChanged Members
///
/// Event used to notify any subscribers that the data in this class has changed.
///
public event PropertyChangedEventHandler PropertyChanged;
///
/// Let any subscribers know that some data has changed.
///
/// <param name="properties" />Array of name of the properties which have changed.
private void RaisePropertyChanged(params string[] properties)
{
if ((properties != null) && (PropertyChanged != null))
{
foreach (string property in properties)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
#endregion
#region Methods
///
/// Add a new reading to the collection.
///
/// <param name="reading" />Reading to be added.
public void Add(TemperatureReading reading)
{
Readings.Add(reading);
RaisePropertyChanged("Readings", "NumberOfReadings");
}
#endregion
}
Now we have somewhere to store the data we need to display the interface and then add a way of getting the data into the application.
The MainPage.xaml displays the data in a DataGrid and a chart. There is also a button for starting and stopping the collection of data. The DataGrid and the Chart are both bound to an instance of the TemperatureViewModel class.
The data for the class is collected periodically by using a web request from an instance of the WebClient class. This is then parsed and added to the collection of readings and the interface updated automatically through the magic of the RaiseProipertyChanged method of the TemperatureViewModel class.
The source can be found here: SilverlightOnNetduino.zip.
Building the Server
The web server code was modified to provide simulated readings from a temperature sensor. This is simply the current number of milliseconds divided by 100. The data is stored in a DataGrid and a presented to the user:
Adding the Silverlight Toolkit charting control to the application allowed the data to be plotted:
The next step is to tie this up to a real sensor and serve data to the users desktop.
Tags: Electronics, Netduino, Silverlight
Tuesday, February 1st, 2011 at 6:15 pm • Netduino, Silverlight, Software Development • RSS 2.0 feed Both comments and pings are currently closed.
Tried to get access to the code but to no avail …
Fixed the broken links.