Category Archives: Microsoft Galileo

Galileo Smart Fan Example

We would use as a starting point the Smart Fan sample http://ms-iot.github.io/content/SmartFan.htm .
The target is to modify the application to:

  • Read the temperature
  • Send it to a server
  • Execute the server commands to start or stop the fan

We would remove the light sensor part.
How do we communicate with the server, and what server it is?
We open a web page (web server then) and through GET parameters we send the data

http://WebSite/SiteName/Temperatures.aspx?id=2&temp=30&fan=false

The parameters are:

  • id – the id of the device
  • temp – the temperature
  • fan – true if the fan is on otherwise false

The page responds with an invalid html page with 3 commands:

  • listen – do nothing
  • start – start the fan
  • stop – stop the fan

The page is invalid because contains no html markings, just the command text to reduce the bandwidth used. Somethimes you pay for data transfer, and the “dead”, no util information, as the markups are in our case, add up.

2. Developing the Galileo application

The hardware pin wise need to be the same. My colleagues (I do software Big Grin | :-D ) did a simplified version on a Arduino Proto Shield.

Electonics

Code wise some constants were changed:

 

// Convert the voltage
double voltage_to_celsius(double voltage) {
 //+1 for our schema
 return 100 * voltage + 1;
}
void toggle_motor(bool motor_is_on) {
 if (motor_is_on) {
  // Turn off motor
  motor_is_on = false;
  analogWrite(MOTOR_PIN, 0);
 }
 else {
  // Turn on motor
  motor_is_on = true;
  //for our schema
  analogWrite(MOTOR_PIN, 250);
  //The old code
  //delay(1);
  //analogWrite(MOTOR_PIN, 50);
 }
}

 

The code to open a web site is a pretty trivial Windows C++ open a page

int SendTempAndGetCommand(int deviceId, double temperature, bool fanRunning)
{
	char hostname[] = "169.254.178.34";

	WSADATA                WsaData;
	size_t                 socketResult;
	WSAStartup(0x0101, &WsaData);
	socketResult = socket(AF_INET, SOCK_STREAM, 0);
	if (socketResult == -1)
	{
		return -100;
	}

	struct addrinfo addrinfoHints;
	struct addrinfo *pAddrinfo = NULL;
	struct addrinfo *pAddrinfoResult = NULL;
	int result = -7;

	// Setup the addrinfoHints address info structure
	// which is passed to the getaddrinfo() function
	ZeroMemory(&addrinfoHints, sizeof(addrinfoHints));
	addrinfoHints.ai_family = AF_INET;

	DWORD  dwReturnValue = getaddrinfo(hostname, PORT, &addrinfoHints, &pAddrinfoResult);
	if (dwReturnValue != 0)
	{
		return -101;
	}

	// loop through all the results and connect to the first we can
	for (pAddrinfo = pAddrinfoResult; pAddrinfo != NULL; pAddrinfo = pAddrinfo->ai_next)
	{
		if ((socketResult = socket(pAddrinfo->ai_family, pAddrinfo->ai_socktype,
			pAddrinfo->ai_protocol)) == -1)
		{
			perror("client: socket");
			continue;
		}

		if (connect(socketResult, pAddrinfo->ai_addr, pAddrinfo->ai_addrlen) == -1) {
			perror("client: connect");
			DWORD lasterr = WSAGetLastError();
			continue;
		}

		break;
	}

	if (pAddrinfo == NULL)
	{
		return -102;
	}

	freeaddrinfo(pAddrinfoResult);

	char msg[500];
	sprintf_s(msg, "GET http://WebSite/SiteName/Temperatures.aspx?id=%d&temp=%f&fan=false rnrn ", deviceId, temperature);
	if (fanRunning)
		sprintf_s(msg, "GET http://WebSite/SiteName/Temperatures.aspx?id=%d&temp=%f&fan=true rnrn ", deviceId, temperature);

	send(socketResult, msg, (int)strlen(msg), 0);
	char buffer[10000];
	recv(socketResult, buffer, 10000, 0);

	char listen[] = "Listen";
	char start[] = "Start";
	char stop[] = "Stop";

	if (strstr(buffer, listen) != NULL)
	{
		result = -1;
	}
	else
		if (strstr(buffer, start) != NULL)
		{
			result = 1;
		}
		else
			if (strstr(buffer, stop) != NULL)
			{
				result = 0;
			}

	closesocket(socketResult);

	WSACleanup();

	return result;
}

And the motor is commanded using the result of this method

	int result = SendTempAndGetCommand(3, temp_in_c, motor_is_on);

	if (result==1) {
		if (!motor_is_on) //super sure
		{
			toggle_motor(motor_is_on);
			motor_is_on = true;
			Log(L"Motor Onrn");
		}
	}
	else if (result==0) {
		if (motor_is_on) //super sure
		{
			toggle_motor(motor_is_on);
			motor_is_on = false;
			Log(L"Motor Offrn");
		}
	}

The code is attached to the article, bear in mind that you need to adapt it to your specific hardware.

3. Developing the server applications

The server app is an ASP.Net web site but could be anything (this is why I do not put the full code for it in the article Smile | :) ).

The aspx is “empty”:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Temperatures.aspx.cs" Inherits="FanTemperature.Temperatures" %>

And on .cs on the Page_Load is all the code.
This is how the paramethers are read.

                int deviceId = 0;
                double curentTemperature = 0;
                bool fanRunning = false;
                int commandFanToRun = -1;

                if (this.Request["ID"] != null)
                {
                    deviceId = Convert.ToInt32(this.Request["ID"], CultureInfo.InvariantCulture);

                    if (this.Request["temp"] != null)
                    {
                        curentTemperature = Convert.ToDouble(this.Request["temp"], CultureInfo.InvariantCulture);
                    }
                    if (this.Request["fan"] != null)
                    {
                        fanRunning = Convert.ToBoolean(this.Request["fan"], CultureInfo.InvariantCulture);
                    }
                }

 

And to suppress the headers the adding of the markups, this is the code used, the result string is the command.

            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.Write(result);
            Response.ClearHeaders();

About the rest of the code could be a simple if,  switch or a decision workflow etc. Also the data could be written into the database, and get a report from it using Reporting Services for example.

3. Run all Smile | :)

Depending on the sensor temperature (by touching the sensor is enough to change it) the fan will start

Start

or stop

Stop

The temperature report is set to auto refresh each second.

Report

4. Security consideration

I would admit that we use this communication through GET parameters in our solutions for years, our company was in IoT before the term was coined. But because our clients are in manufacturing the networks we use with our apps and sensors are private.
My point, the GET method is not secure, bear this in mind, is a solution in the cases when data is not sensitive or the network is private. As a plus the traffic is very easy to debug.
So if security is a concern POST, https, Azure and so is something that you should think of.
And there are some interesting Azure offerings that could be used in this IoT scenarios (for sure you can connect from Windows Galileo since the C++ method surface is almost all of a “big” Windows)

And I’m naming just a few Azure offerings that could fit in an IoT solution.

5. Conclusions

I hope that I was able to fill the gaps of the Windows Developer Program for IoT (http://dev.windows.com/en-us/featured/windows-developer-program-for-iot) documentation and tutorials and show you that running Windows on Galileo is an option.

Also there (https://ms-iot.github.io/content/AdvancedUsage.htm) are answers to some advanced questions, how to do not use the USB network card, how to ensure that my application runs on the device without using Visual Studio debug, how to kill a Galileo task and so on.

What is Galileo

1.2 What is Galileo?  AKA FAQ

  1. So what is this Galileo? (It seems that we are not talking about that old Italian astronomer or the European GPS )
    The answer according to Wikipedia ((http://en.wikipedia.org/wiki/Intel_Galileo)) is:” Intel Galileo is the first in a line of Arduino-certified development boards based on Intel x86 architecture and is designed for the maker and education communities.” Full technical details you could find on Arduino site http://arduino.cc/en/ArduinoCertified/IntelGalileo
  2. What makes Galileo run (as operating system of sorts)?
    Again Wikipedia (http://en.wikipedia.org/wiki/Intel_Galileo) give us the answer: “The development board runs an open source Linux operating system with the Arduino software libraries, enabling re-use of existing software, called “sketches”.”
  3. So if I understand right this board can also run Windows?
    The short answer is yes.
  4. The next question is why to run Windows on an Arduino board?
    Well there are several answers to this question:
    – You have access to almost all libraries that can run on Windows, hardware permitting and making sense.
    – A familiar operating system (albeit command line).
    – Excellent tool chain, using Visual Studio is to create and debug your applications.
  5. What is the programming model?
    The programming model is wiring (http://wiring.org.co/) like Arduino (“standard Arduino Wiring API set, and a subset of Win32” http://ms-iot.github.io/content/WelcomeAndFAQ.htm).
  6. All Arduino Shields (http://arduino.cc/en/Main/ArduinoShields) will work on a Galileo running Windows?
    We are talking about shields compatible with the board, running at 3.3 or 5 Volts, voltages which are not operating system dependent. And it, well depends, if do not have additional libraries or if they have but those libraries do not go to lower lever accessing directly the hardware it would work. Generally speaking your chances to pick a shield and this to work are pretty good.

 

2.Getting Started – Prerequisites & setting up

In this part we will see what we need to have, to download, and to install and configure to be able to run and develop for a Windows running on the Galileo board.

2.1. Prerequisites

  1. General
  2. Software
    • Visual Studio 2013 Express or better (just 2013 is supported).
  3. Hardware
    1. An Intel Galileo board Gen 1 or 2 with the power supply.
    2. microSD card > 16 GB (and something to read/write it from PC)
    3. A network cable
    4. Recommended: an USB network adapter
    5. Depending on your ideas, LEDs, resistors, breadboards, fans, Arduino Proto Shield, solder etc…

2.2. Set up the PC and the board itself

Note: If you had already done this before December 2014, you should do them ALL (PC and board) again since a new version was released.The main visible change beside a NuGet package with another name and more functionalities in Galileo Watcher application (see Part 3 for what it is), is Lighting support.
From the Windows Developer Program for IoT web site (http://ms-iot.github.io/content/Lightning.htm ):
“These performance improvements, called Lightning, represent a re-architecture of the user mode/kernel driver model for pin hardware I/O in Windows via the Windows Developer Program for IoT. As a programmer you access the pins exactly the same. The response time is improved for you.All analog and digital pins are faster than without Lightning.”

2.2.1 The PC

  • If you have the Studio 2013 Express for Windows Desktops you need to install the NuGet package manager for Visual Studio 2013, I will not insist on how it’s done since now exist also the Visual Studio Community( http://www.visualstudio.com/products/visual-studio-community-vs ) essentially a free Professional version for individuals, small business etc.
    If you have another version of Visual Studio 2013 than Express (quote the Windows Developer Program for IoT web site http://ms-iot.github.io/content/SetupPC.htm ):
    “Please install the WindowsDeveloperProgramforIOT.msi
    (During the install process, you may be prompted twice by the User Account Control. Once for the MSI and once for VSIXInstaller. To properly install the needed components, you will need to click yes.)”
  • Would help to have the Windows Telnet client installed, check if in Programs and Features (Control Panel applet) at “Turn Windows Features on or off”, in the feature list, the “Telnet Client” is checked.
  • Set up the USB network card, depend on the model, usually is just plug in and wait Windows to install the drivers.

2.2.2 The Galileo board itself

If Gen 1 you need to update the firmware, since Gen 1 without updated firmware is becoming rare and since also Gen 2 is around I will not delve into details of how it’s done. In short you need the Arduino IDE for Galileo and the firmware update and from the IDE you will do it.
I did found a detailed tutorial https://learn.sparkfun.com/tutorials/galileo-getting-started-guide/software-downloadsetup  , you do all the steps including the firmware update. Afterwards for running Windows on Galileo you will not need these tools.

2.3. The microSD card

This is the “hard disk” with the operating system.
We need these (from Microsoft Connect):

Here the tutorial (http://ms-iot.github.io/content/SetupGalileo.htm ) was really spot on so I will quote him:“

  • Write Windows to the microSD card
  • Format the microSD card with the Fat32 file system.
  • Open an Administrative command prompt:
    • Open the Start screen
    • type cmd
    • right click or tap and hold on Command Prompt, then select Run as Administrator.
  • If you are running on Windows 7 please follow these instructions before proceeding.
  • In the command window, type the following: cd /d %USERPROFILE%Downloads apply-bootmedia.cmd -destination {YourSDCardDrive} -image {.wimFile downloaded above} -hostname mygalileo -password admin”

 

3. Ready to go & board watching

We are now ready (after the first 2 parts) to connect the board, boot it and use the Galileo Watcher tool. So how and what?

3.1. Connect and boot the Galileo

3.1.1 So let’s start the Galileo:

  • put the microSD (the one prepared in part 2)card in the Galileo
  • Connect the USB network card to the PC (you can use your PC network but you will need to alter the settings to get eventually in the same network as the Galileo, USB network card is the solution for lazy people ).
  • connect the USB network card with the Galileo using a network cable
  • connect the Galileo power supply

Now wait a bit to boot, and you have Windows on Galileo. About the a bit from Windows Developer Program for IoT web site (http://ms-iot.github.io/content/SetupGalileo.htm):
“NOTE: Windows on Galileo can take about 2 minutes to boot. During this time you will see the microSD activity LED flashing rapidly. Once it stops flashing for a few seconds, the Galileo is fully booted. ”

3.2 Board watching

On the PC now we discovered (is also on the system tray) a new application running (starts at system startup): Galileo Watcher

After the board boot up we will get more info in the application. Sometimes when Galileo is booting up the Watcher could crash, do not worry restart the app and eventually will work.( December update improved the stability and the info displayed).

The app advertises a “handy context menu”, let’s see what all is about

 

What the “handy” menu entries do:

  1. Copy MAC Address – copy in clipboard the MAC address of the Galileo board
  2. Copy IP Address – copy in clipboard the IP address of the Galileo board
  3. Telnet Here – start a telnet session to the board (is not the only way to telnet the board)

The connection parameters are:
Username: Administrator
Password: admin

Whats the use of this telnet?One sure use of it: Shutdown (hey is WindowsJ)
On telnet prompt (quote again fro here http://ms-iot.github.io/content/SetupGalileo.htm) :

“shutdown /s /t 0 After the microSD activity LED stops blinking, you may unplug the Galileo.”

If you do not do a proper shutdown at next boot will do a scan of the microSD card as any Windows which was not properly shutdown scan the disk with the operating system.

And of course the connected check box on the Galileo Watcher it will went uncheck is the board is shutdown, or disconnected.

  1. Web Browser here – let’s be curious what it does, besides telling us that Galileo is running MinWin so “real” Windows, and that it has a Web server
  2. task list – is pretty self explanatory, you recognize the “normal” Windows processes
  3. file list – on my board is crashing (again pretty much self explanatory)
  4. memory statistic – shows , as you guess it the memory composition

As  a small conclusion the Web Browser option is something like a remote Task Manager.

  1. Open Network Share – as any Windows the Windows on Galileo has a C$ share.

The connection parameters are:
Username:myGalileo Administrator
Password: admin

As you guess it the board name is myGalileo, and if it not recognized you should use the IP

Now you can access the Galileo file system from the explorer, like any Windows system when you use the c$ share.

4. “Hello World” application on Galileo (Windows)

If Galileo Watcher say in the previous part that we are connected, this was solved, so let’s do our “Hello World” application (this and more samples you can find on Windows on Devices sample gallery http://ms-iot.github.io/content/SampleApps.htm).

4.1. The hardware schema

To have a Galileo application running, you must set the hardware, use a breadboard and some parts, add a shield, etc. Opposed to .Net Gadgeteer (http://www.netmf.com/gadgeteer/ )  on the hardware part Visual Studio does not help you, you do not design this hardware in Visual Studio, do not look at this moment for this facility for Galileo in Visual Studio.

On the Galileo, we shut down him him first, and disconnect the power. The electronics we need set up is add a LED, the power pin connected to Galileo pin 13 and LED GND to GND. A resistor on power pin would prolong the LED life. The longer LED pin is the power.

 

You can set it directly (like I did)or use a breadboard. Power up the board and check on the Galileo Watcher that is connected.

4.2. Visual Studio solution

4.2.1 Open Visual Studio. Select File -> New Project and Select Templates -> Visual C++ -> Windows for IoT -> Galileo Wiring app

Yes you guess it the template has already the Arduino “Hello World”

You find explained all over the Internet, you set up the pin 13 as output and in the loop you turn it on an off.  Just play with it. There are some minor differences to the Arduino code, and include here a _tmain there  but the rest is highly recognizable.

4.2.2 Let’s run the application! So happy F5!
At first connection attempt you could be prompted for credentials.
Username: mygalileoAdministrator
Password: admin

And all should work, the LED to blink. And no, the LED is not blinking “Hello World” in Morse code . If does not blink check if is correctly set up Power to Power, GND to GND.

4.3. Upgrade solution (if needed)

The NuGet as always is lurking: in 2 December Microsoft released an update to Galileo C++ SDK called Microsoft IoT SDK (see part 2 of this tutorial about the upgrade steps).Because the package has a different name the package is not recognized as update so you need to uninstall the previous version and install the new one for older projects, by old I mean the one created before you install December 2014 updates.

4.3.1 Start the Manage NuGet Packages  for the solution

4.3.2 Uninstall Galileo C++ SDK

4.3.3 Search in Nuget.org packages for, and install Microsoft IoT C++ SDK

It should work, but if you get this kind of errors at debug:

First-chance exception at 0x76CF0F63 in Galileo Wiring App1.exe: Microsoft C++ exception: _arduino_fatal_error at memory location 0x0069F640.

Sketch Aborted! A fatal error has occurred:

Error setting mode: OUTPUT for pin: 13, Error: 0x0000070d

The program ‘[1840] Galileo Wiring App1.exe’ has exited with code 1 (0x1).

It means that the board microSD card is not updated, update it as shown in part 2 of this tutorial with the December 2014 bits and it should work.