WindowsForIoT

Azure IoT Hub : commands and feedback using AMQP .Net Lite

In the previous article, I described how it’s possibile to send telemetry data from a device and receive commands (sending feedback) from the cloud (to the device itself) using AMQP .Net Lite library connecting to the Azure IoT Hub. This approach is useful for some platforms that aren’t supported by the official SDKs like the .Net Micro Framework due to the Task and async/await programming model used in the C# implementation.

Covered the device side, it’s now time to see how we can use the same AMQP .Net Lite library on the service side. You could ask … “Why ?!! We have the great Microsoft.Azure.Devices Nuget package that provides the ServiceClient class to handle the connection, sending commands and receive feedback to/from devices !!”

You are right ! It’s true but … only if your service runs in a Web or a .Net Framework based application. If you try to install the above package in an UWP application you receive the following error !

nuget_uwp_error

As we can see, the official package uses some libraries that aren’t compatible with UAP like Microsoft.AspNet.WebApi.Core and Microsoft.Azure.Amqp. Tha latter sounds strange to me! It seems to be another AMQP stack implementation from Microsoft that can only run on .Net Framework. What are the differences with AMQP .Net Lite library? I’m sorry but I don’t know … the above stack isn’t open source and we can’t deep into it. However, there is a big and great difference that should be considered as a strength for AMQP .Net Lite : it works on all .Net platforms (micro, compact and full), on WinRT/UWP and Mono !

For this reason and using AMQP .Net Lite library we have a solution on developing an IoT Hub service inside a UWP application, a scenario that isn’t officially supported by Microsoft. As I love to say we can do that “knowing some AMQP protocol concepts and a bunch of IoT Hub node paths” !

IoT Hub service endpoints

Inside the IoT Hub architecture, the service has two endpoints to communicate with devices :

  • C2D (cloud to device) : the back end system can use this endpoint to send messages (for example commands) to the devices. This endpoint acts like a queue and each message has a TTL (Time To Live) so that it’s removed from the queue if the timeout expires (it’s useful to have commands executed in a short period of time and not executed too late when an offline device comes back online but the execution isn’t needed at that time because it could be harmful). The back end system can receive a confirmation message or delivery fault to understand if device has received command or not;
  • D2C (device to cloud) : it’s an Event Hubs compatible endpoint used by the back end system to retrieve messages from device (telemetry data) and feedback on command delivery (successful or not). “Event Hubs compatible” means that we can use an Event Hub client to receive messages from this endpoint (for example using an Event Processor Host implementation);

At AMQP level the endpoints are accessible from different entity paths; if you know Service Bus queues, topics/subscriptions and event hubs we can think them in the same way.

The entity path for sending command to devices is defined in the following way :

/messages/devicebound

while the entity path for receiving feedback (on commands sent) from devices is the following :

/messages/servicebound/feedback

As for the previous article, it means that after creating a connection and a session to our IoT Hub host we need to create two links to above entities (or nodes as defined in the AMQP spec). Using the programming model provided by AMQP .Net Lite library we have :

  • A SenderLink to the /messages/devicebound node;
  • A ReceiverLink to the /messages/servicebound/feedback node;

Authentication : sending the SAS token

The authentication mechanism is the same as device side. In this scenario, we need to send two SAS token on the two different AMQP nodes for sending command and receiving feedback.

The SAS token audience and resource URI for sending command are the same and defined in the following way :

string audience = Fx.Format("{0}/messages/devicebound", HOST);
string resourceUri = Fx.Format("{0}/messages/devicebound", HOST);

string sasToken = GetSharedAccessSignature(SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, resourceUri, new TimeSpan(1, 0, 0));
bool cbs = PutCbsToken(connection, HOST, sasToken, audience);

For receiving feedback, they are the following :

string audience = Fx.Format("{0}/messages/servicebound/feedback", HOST);
string resourceUri = Fx.Format("{0}/messages/servicebound/feedback", HOST);

string sasToken = GetSharedAccessSignature(SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, resourceUri, new TimeSpan(1, 0, 0));
bool cbs = PutCbsToken(connection, HOST, sasToken, audience);

Sending command

Using the SenderLink instance the device sends data calling the simple Send() method and passing it a Message class instance contains the data to send.

The sender link is created inside a new AMQP Session (using the related class of AMQP .Net Lite library) and the great news is that, thanks to the multiplexing feature of AMQP protocol, we can use the same session for both sender and receiver links all inside the same TCP connection.

The corresponding class in the official SDK is the ServiceClient class that provides the SendAsync() method. Regarding the original Message class (included into official SDK, not AMQP .Net Lite), it exposes the Ack property with following possible values :

  • none (default) : the service doesn’t want any feedback on command received by the device;
  • positive : the service receives a feedback message if the message was completed;
  • negative : the service receives a feedback message if the message expired (or max delivery count was reached) without being completed by the device;
  • full : the service receives both positive and negative feedbacks;

For more information you can refer to the previous article with a clear explanation of the message life cycle.

Using the AMQP .Net Lite library we don’t have an Ack property on the Message class but we need to use the application properties collection at AMQP level. The Ack property (at high level) is translated in an application property named “iothub-ack” (at AMQP level) which can have the above possible values. If we don’t set this application property, it means the same as “none” value so no feedback.

static private void SendCommand()
{
    string audience = Fx.Format("{0}/messages/devicebound", HOST);
    string resourceUri = Fx.Format("{0}/messages/devicebound", HOST);

    string sasToken = GetSharedAccessSignature(SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, resourceUri, new TimeSpan(1, 0, 0));
    bool cbs = PutCbsToken(connection, HOST, sasToken, audience);

    if (cbs)
    {
         string to = Fx.Format("/devices/{0}/messages/devicebound", DEVICE_ID);
         string entity = "/messages/devicebound";

         SenderLink senderLink = new SenderLink(session, "sender-link", entity);

         var messageValue = Encoding.UTF8.GetBytes("i am a command.");
         Message message = new Message()
         {
              BodySection = new Data() { Binary = messageValue }
         };
         message.Properties = new Properties();
         message.Properties.To = to;
         message.Properties.MessageId = Guid.NewGuid().ToString();
         message.ApplicationProperties = new ApplicationProperties();
         message.ApplicationProperties["iothub-ack"] = "full";

         senderLink.Send(message);
         senderLink.Close();
    }
}

As we can see, the sending path “/messages/devicebound” hasn’t any information about the target device. To do that, the service need to set the To AMQP system property to the following value :

/devices/<DEVICE_ID>/messages/devicebound

where <DEVICE_ID> is the id assigned to the device when we create it inside the identity registry.

Finally, it’s importat to notice that the C2D endpoint queue can hold at most 50 messages.

Receiving feedback

Using the ReceiverLink instance the service can receive feedback from the device calling the Receive() method.

static private void ReceiveFeedback()
{
     string audience = Fx.Format("{0}/messages/servicebound/feedback", HOST);
     string resourceUri = Fx.Format("{0}/messages/servicebound/feedback", HOST);

     string sasToken = GetSharedAccessSignature(SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, resourceUri, new TimeSpan(1, 0, 0));
     bool cbs = PutCbsToken(connection, HOST, sasToken, audience);

     if (cbs)
     {
          string entity = "/messages/servicebound/feedback";

          ReceiverLink receiveLink = new ReceiverLink(session, "receive-link", entity);

          Message received = receiveLink.Receive();
          if (received != null)
          {
               receiveLink.Accept(received);
               System.Diagnostics.Trace.WriteLine(Encoding.UTF8.GetString(received.GetBody<byte[]>()));
          }

          receiveLink.Close();
     }
}

The received message has a body in JSON format with an array of records (feedback from more different devices) each with following properties :

  • OriginalMessageId : it’s the MessageId of the original command (message) sent from the service to the device;
  • Description : description result that is related to the possible outcomes (success, message expired, maximum delivery count exceeded, message rejected);
  • DeviceGenerationId : device generation id related to the device that sent the feedback for a specific command;
  • DeviceId : device id related to the device that sent the feedback for a specific command;
  • EnqueuedTimeUtc : timestamp related to the outcome (it means when the feedback was enqueued);

For a single feedback, the JSON should be as following :

[{"originalMessageId":"5aac3169-af00-4536-acdb-cb9ea6b3980e","description":"Success","deviceGenerationId":"635794823643795743","deviceId":"<device_id>","enqueuedTimeUtc":"2015-10-29T07:59:00.9772497Z"}]

The full source code

As for all examples related to my blog posts, I update sample from previous article on GitHub. Now you can find a simple console application and a UWP application that are able to send command to a device and receive related feedback.

Conclusion

It’s clear that for a service running in a Web Application or .Net Framework based application, the best solution is to use the official Nuget package. With this article, I covered the NON officially supported possibility to use an UWP application to control devices through the IoT Hub thanks to the AMQP .Net Lite library and a bunch of AMQP paths.

If you consider the great portability of this AMQP stack implementation, you could control your devices using a .Net Compact Framework app (on Windows Embedded Compact 2013) or … another device based on .Net Micro Framework !

🙂

Advertisements

A new Internet of Things era starts today … the IoT Hub is finally here !

September 29th … what a day for Microsoft and related Internet of Things technologies !

Azure IoT Suite and IoT Hub are finally here ! The IoT Hub is available in public preview and ready to help you to develop your IoT solutions in a very simple manner !

Where you can find all useful information about them ?

First of all the “Azure IoT Suite now available” blog post on official Microsoft web site focused on Internet of Things.

On Microsoft Azure documentation section you can find the dedicated “Azure IoT Developer Center” that will guide you to create a new IoT Hub on the new Azure management portal and connect one or more devices to it.

iot_dev_center

Starting with IoT Hub is very simple if you follow the documentation page here. A lot of examples, how-to guides for sending data from device to cloud and command from cloud to device, handling devices and so on.

Devices are a very interesting story !

There is a certified IoT program with all current hardware platforms and silicon vendors certified for accessing to IoT Hub. Of course, not only Raspberry Pi and MinnowBoard (we know them with Windows IoT Core) but BeagleBoard and Dragon Board 410C too. As embedded developer I love Freescale FRDM-K64F and Texas Instruments CC3200 LaunchPad too. It’s possible for you to become a partner and certify your hardware platform !

iot_hub_partners

To simplify your life, you can follow the main steps at this page for :

  • Select a device (Raspberry Pi 2, MinnowBoard Max, Freescale FRDM-K64F and so on)
  • Select a platform (Linux, Windows, mbed , TI RTOS). The list is filtered based on above selected device
  • Select a language (C, C#, JavaScript, Java). Pay attention … it’s not filtered …but remember you can’t use C# on Freescale FRDM-K64F 😉
  • Configure your IoT Hub with all steps on the new Azure management portal
  • Connect your device with all steps to do it

Great news … all Azure IoT SDKs are open source and available on GitHub !

A great partnership I like too much is with the ARM mbed platform as discussed on the ARM official blog. Currently only the Freescale FRDM-K64F board is supported but it’s a great starting point. On the mbed web site you can find the official Azure IoT account with a lot of source code related to the IoT Hub client implementation and related examples. Of course the client uses AMQP protocol to communicate with IoT Hub and for this reason the Qpid Proton C porting on mbed is available there. Just think … it can be useful to you to access all Service Bus entities (queues, topics/subscriptions, event hubs, …) from mbed enabled boards like the Freescale one. Remember that the Microsoft Band has a Kinetis MCU from Freescale (here the Sparkfun teardown) ! 😉

Of course .Net Micro Framework support on the boards from GHI or Secret Labs aren’t available “out of box” but using the great AMQP .Net Lite library you can use them with IoT Hub. Don’t worry … my open source developer soul is just thinking to a new project library for it 😉 It’s the same for industrial Windows Embedded Compact 2013 devices.

Regarding Azure IoT Suite and all related services for storing messages and predictive analysis there is a dedicated web site you can start to create a full IoT solution from predefined scenarios (with provisioning and monitoring of course) you can customize.

What if you have MQTT based devices or you want to develop new devices using this protocol ? How you can connect them to the Azure IoT Hub ? Don’t worry, Microsoft provides you the “Azure IoT Protocol Gateway” that is a framework for protocol adaptation that supports MQTT v3.1.1. You can deploy it in the Cloud as a worker role or in on-premises environments such as field gateways.

If all above material isn’t enough for you, there are some great videos on Channel9 from AzureCon :

In conclusion, today starts a new IoT era … after people hub and all the other hubs on your Windows Phone … you have the IoT Hub in the Cloud with all your devices !

Windows IoT Core and M2Mqtt … a simple marriage !

“Hello, Windows IoT Core” as Steve Texeira wrote few days ago !

The last stable release of the new IoT (embedded ?) OS for makers (and professionals ?) is out but of course I couldn’t wait the last days to start using it so I already played with it in a lot of demos and sessions code.

Who follows me knows that other than interacting with real world using sensors from Raspberry Pi 2, my great love is share these data and send them to the Cloud ! I already spoke and coded about using Pi 2 to send data to the awesome Event Hubs service (in the Microsoft Azure Service Bus family) and you can find my material on GitHub and SlideShare related to my “Telemetry with Windows 10 IoT : from Raspberry Pi2 to Event Hubs” session.

Of course, who follows me knows that I’m currently developing and updating (since about 2 years) the M2Mqtt library as part of the Eclipse Paho project (starting from October 2014) as the main MQTT client implementation for all .Net platforms (full, compact and micro) and WinRT (Windows 8.1 and Windows Phone 8.1) but … what about Windows 10 and Windows IoT Core ?

Don’t worry guys ! The last stable release (4.2.0.0) in its WinRT version works great on the new awesome Microsoft OS from the PC to the Raspberry Pi 2 thanks to the UWP (Universal Windows Platform) programming model. You can use the last Nuget package for sending telemetry data from your embedded system, your PC or smartphone writing only one application !

In the next few lines, I’ll describe how to use this package to send simple temperature value from my home. I’d like only to show how simple is to use the library and give you the right tools to create you IoT solution MQTT based for a Windows IoT Core system !

The hardware : Raspberry Pi2 and TMP102

Of course, it’s possible to develop an Internet of Things solution without an embedded system. Yes, of course ! I’m not crazy but I don’t want to discuss about this scenario (IoT is very huge you could think) during this article that will be focused on using an embedded hardware like the Raspberry Pi 2 with latest release of Windows IoT Core. Online, you can find a lot of article and official documentation on how to setup your board so I can consider this step already done for you !

Regarding the telemetry scenario … what is the easiest data to send … a temperature value of course ! 🙂

For this, I chose a temperature sensor I already had … the TMP102 from Texas Instruments in the related breakout board from Sparkfun. The connections to the Pi2 are so simple because the sensor supports I2C protocol and referring to the Pi 2 pinout we have (left Pi 2 pin and right TMP102 pin) :

  • PIN 1 (3.3V PWR) –> V+ (power)
  • PIN 3 (I2C1 SDA) –> SDA (I2C data)
  • PIN 5 (I2C1 SCL) –> SCL (I2C clock)
  • PIN 6 (GND) –> GND (ground)
  • PIN 9 (GND) –> ADD0 (for I2C address selection)

You can leave the ALT pin of TMP102 not connected to Pi 2 because it’s for alert notifications from the sensor if temperature is higher or lower than a specific threshold. If you chose to use it, you need to connect it to a GPIO pin on the Pi 2 to receive an interrupt (Gpio Value Changed event) on alert.

Create UWP app and add the M2Mqtt package

Using Visual Studio 2015, it’s so simple to create a new UWP application from “File –> New Project –> Windows –> Universal” as showed in the following picture.

01_pi2mqtt

To develop on Raspberry Pi 2 and using all IoT features like Gpio pins, I2C and SPI devices, you need to add the Windows IoT Extensions for the UWP under references and selecting “Select Universal –> Windows –> Extensions”.

02_pi2mqtt

Now you are able to interact with all your Pi 2 pins and sensors you can connect to it but what about the M2Mqtt library for sending data to the Cloud using MQTT protocol. As I said, the library is available as Nuget package without need to recompile it from source code (it’s open source ! you can do it if you want !). Adding the package to your project is so simple under “References -> Manage NuGet Packages”, search for “M2Mqtt” and click on “Install”.

03_pi2mqtt

At the end of the installation you can find the package under the “Solution Explorer” window.

04_pi2mqtt

Time to code !

Now it’s time to code our application, reading from the temperature sensor and publish data to an MQTT broker. The first step is to interact with TMP102 sensor to get the temperature value. To do this I already wrote the driver you can find on GitHub here and include in your project.

To be much simpler as possible I wrote my code in the MainPage constructor to instantiate the TMP102 class and the MqttClient class from M2Mqtt library and to launch a task that reads the temperature and send it to the broker every 5 seconds. Of course, you have to write better code (for example using a Backgroud IoT Task instead of an UWP app) … but this sample is useful to show you how to integrate M2Mqtt in your project and how it’s simple to use it.

public sealed partial class MainPage : Page
{
    private TMP102 tmp102;
    private MqttClient client;

    public MainPage()
    {
         this.InitializeComponent();

         this.tmp102 = new TMP102();
         this.client = new MqttClient("test.mosquitto.org");

         this.client.Connect(Guid.NewGuid().ToString());

         Task.Run(async () =&gt;
         {
              bool isOpened = await this.tmp102.OpenAsync();

              while (true)
              {
                   float temperature = this.tmp102.Temperature();
                   string json = "{ temp : " + temperature + " }";

                   this.client.Publish("/pi2mqtt/temp", Encoding.UTF8.GetBytes(json));

                   await Task.Delay(5000);
              }
         });
    }
}

To simplify the solution I decided to use the publically available Mosquitto broker at this address : test.mosquitto.org

The above example is very simple. First you have to create TMP102 and MqttClient instances (for the last one you need to specify the broker host name). The second step is to connect to the MQTT broker and start the task for reading and sending data. Inside the task, every 5 seconds, the temperature value is read from the TMP102 instance and it’s published to the broker on the “/pi2mqtt/temp” topic in JSON format (as payload of the MQTT message).

Now that your project is sending value to the broker, the simplest way to see you are publishing data is to use another MQTT client, for example the mosquitto client and subscribe to the same topic to receive data. After installing mosquitto, you can start the mosquitto subscriber client in the following way :

mosquitto_sub -h test.mosquitto.org -t /pi2mqtt/temp -q 0 -d

Now … you should see data received from you Raspberry Pi 2 !

05_pi2mqtt

Conclusion

Of course, it isn’t an article to deep into Windows IoT Core, MQTT protocol, M2Mqtt library and so on. I’d like only to show how you have an “out of box” way (as the M2Mqtt library) to integrate your embedded system into a huge MQTT solution and you can develop it using Windows IoT Core as OS or in general your Windows 10 system !

Mobile Camp 2015 : telemetria da Windows 10 IoT Core all’Azure Event Hubs

mobile_camp_2015

Anche quest’anno ho avuto il piacere di essere speaker al Mobile Camp organizzato da Microsoft a Napoli; quest’anno l’evento era incentrato su Windows 10 e tutte le novità di Build 2015.

Da buon Microsoft MVP su Windows Embedded ed IoT, la mia sessione era ovviamente dedicata all’embedded ed all’Internet of Things ed in particolare alla Raspberry Pi 2 con Windows 10 IoT Core.

Ovviamente, in una soluzione IoT non può mancare il Cloud con i suoi servizi e nel mio caso non poteva mancare l’Azure Event Hubs come destinazione dei dati (temperatura) trasmessi dalla Raspberry Pi 2 (utilizzando la mia libreria Azure SB Lite).

Per chi fosse interessato, il materiale è disponibile su SlideShare (slide) e su GitHub (il codice sorgente della demo).

Esplora l’immagine “Windows for IoT” della Intel Galileo (Gen2) comodamente sul tuo PC !

Vi siete iscritti al Windows Developer Program for IoT e siete in attesa della board oppure avete ordinato una Intel Galileo (Gen2) sulla quale caricherete l’immagine di Windows messa a disposizione sul sito ufficiale ? Siete in attesa delle board ma siete curiosi di sapere quali siano i componenti inclusi nell’immagine di Windows for IoT ?

Una soluzione c’è !

Una volta scaricato il file WIM del sito, è possibile eseguirne il mounting attraverso il comando DISM nel modo seguente :

dism /Mount-Wim /WimFile:<path_wim_file> /Index:1 /MountDir:<path_dir_mount>

Ad esempio :

dism /Mount-Wim /WimFile:C:\Users\ppatierno\Downloads\9600.16384.x86fre.winblue_rtm_iotbuild.140925-1000_galileo_v2.wim /Index:1 /MountDir:C:\Galileo

Attenzione !! La cartella in cui montare va creata prima.

01

Al termine di tale operazione, attraverso esplora risorse potrete vedere comodamente sul vostro PC il contenuto dell’immagine di Windows per la vostra Intel Galileo !

02

Infine, per poter cancellare la cartella creata, è necessario in primo luogo eseguire l’unmounting con il seguente comando :

dism /Unmount-Wim /MountDir:<path_dir_mount> /Discard

03

🙂

Windows for IoT : MQTT sulla board Intel Galileo

Una delle principali caratteristiche di un oggetto nell’ambito dell’Internet of Things è la sua capacità di scambiare messaggi, inviando dati o ricevendo comandi, nel modo più efficace ed efficiente possibile. Esistono numerosi protocolli standard per questo scopo ma uno dei miei preferiti è MQTT.

Nel corso di questo articolo, vedremo come sia possibile utilizzare un client MQTT sulla board Intel Galileo con “Windows for IoT”, in modo da aggiungere a quest’ultima la potenzialità necessaria per poter essere riconosciuta come parte del mondo dell’Internet of Things.

Paho project : il client MQTT

Paho è un progetto open source della Eclipse Foundation che mette a disposizione una serie di client, sviluppati con differenti linguaggi di programmazione, per i principali protocolli utilizzati nell’ambito della M2M (Machine To Machine) communication e dell’IoT (Internet of Things). In particolare, la nostra attenzione è focalizzata sul client MQTT in linguaggio ANSI C che fornisce il supporto Posix/Windows e che espone due tipologie di APIs :

  • Sincrone : ogni chiamata è bloccante e ritorna il controllo al chiamante solo al termine dell’operazione richiesta;
  • Asincrone : l’operazione richiesta viene avviata in maniera asincrona restituendo immediatamente il controllo al chiamante e tutte le notifiche sono eseguite attraverso delle callback (molto utile nell’ambito di software con una UI);

Per poter compilare tale progetto utilizzando Visual Studio 2013, è necessario utilizzare GIT per eseguire il clone del corrispondente repository il cui URL è disponibile nella pagina principale della libreria nella sezione Downloads –> MQTT –> C/C++ –> C (Posix/Windows).

00

Nella sottocartella “Windows Build”, possiamo trovare la solution “Paho C MQTT APIs” i cui progetti sono i seguenti :

  • MQTTVersion : applicazione console che visualizza la versione corrente di una specifica libreria;
  • paho-mqtt3c, paho-mqtt3a : sono rispettivamente le librerie MQTT sincrone ed asincrone senza il supporto SSL;
  • paho-mqtt3cs, paho-mqttas : sono rispettivamente le librerie MQTT sincrone ed asincrone con il supporto SSL;
  • stdoutsub, stdoutsuba : applicazioni console che forniscono un subscriber in modalità sincrona ed asincrona;
  • test1, test3 : applicazioni console di test per la libreria sincrona rispettivamente senza e con SSL;
  • test4, test5 : applicazioni console di test per la libreria asincrona rispettivamente senza e con SSL;

01

La solution è ben strutturata ma purtroppo è necessario effettuare una serie di modifiche alle impostazioni per poter compilare i progetti su Windows, per poi passare all’esecuzione sulla Intel Galileo con “Windows for IoT”.

Compiliamo la libreria sincrona

Focalizziamo la nostra attenzione sulla libreria che fornisce l’implementazione sincrona (paho-mqtt3c) senza il supporto SSL nella configurazione di Debug. Essa compila senza alcun problema ma per l’esecuzione sulla Intel Galileo è necessario disabilitare le “enhanced instructions” a causa di un errore a runtime di “illegal instruction” sulla funzione difftime. Ciò è possibile attraverso le proprietà del progetto ed impostando “No Enhanced Instructions (/arch:IA32)” in C/C++ –> Code Generation –> Enable Enhanced Instruction Set.

02

Le modifiche principali vanno effettuate sul progetto test1 per la libreria suddetta, in quanto esso non compila immediatamente a causa di una serie di impostazioni errate.

In primo luogo fallisce l’inclusione del file MQTTClient.h (Cannot open include file: ‘MQTTClient.h: No such file or directory) che possiamo risolvere aggiungendo la corrispondente directory nelle proprietà del progetto; in particolare va aggiunto il path $(SolutionDir)\..\src in C/C++ –> General –> AdditionalIncludeDirectoris.

03

Inoltre, è necessario aggiungere le seguenti define in C/C++ –> Preprocessor –> Preprocessor Definitions :

  • _WINDOWS : utilizzata per evitare l’inclusione di alcuni header files legati a Linux e garantire l’inclusione degli header files relativi alle WinSock;
  • _CRT_SECURE_NO_WARNINGS : purtroppo la libreria fa uso di molte funzioni nella versione “unsafe” (es. strtok al posto di strtok_s);

04

05

A questo punto, il compilatore riesce a fare il proprio lavoro ma il Linker segnala una serie di “unresolved externals”, in quanto non è in grado di trovare i simboli relativi alla libreria WinSock e la libreria MQTT. Nel caso della libreria WinSock, va aggiunto il riferimento per il Linker alla libreria ws2_32.lib in Linker –> Input –> Additional Dependencies.

06

Per quanto riguarda la libreria MQTT, possiamo referenziare direttamente il progetto (visto che è nella medesima solution) in Common Properties –> References –> Add New Reference.

07

Con queste ultime modifiche la compilazione viene eseguita correttamente ma purtroppo se proviamo ad eseguire l’applicazione di test sul nostro PC, ci ritroviamo di fronte ad un errore di “stack corruption”. Ho prontamente segnalato il bug (potete trovare i dettagli qui) che con la versione corrente non è stato ancora messo a posto. La soluzione consiste semplicemente in una modifica nel file MQTTClient.c (funzione MQTTClient_deliverMessage) e nello spostare la seguente riga di codice :

ListRemove(m->c->messageQueue, m->c->messageQueue->first->content);

subito dopo #endif e la chiamata della funzione MQTTPersistence_unpersistQueueEntry.

Il primo test su PC

Prima di lanciare l’esecuzione dell’applicazione di test sulla Intel Galileo, possiamo accertarci che tutto funzioni correttamente eseguendola sul proprio PC. In primo luogo, dobbiamo scegliere un broker MQTT per poter eseguire i test (oppure utilizzare quello online di default). Io ho preferito utilizzare un broker molto leggero come Mosquitto che è possibile scaricare qui. Lanciamo il broker con l’opzione “-v” ossia in modalità “verbose” in modo da poter vedere tutti i messaggi di debug durante il test.

Prima di ricompilare e lanciare l’applicazione test1, è necessario modificare la struttura options che contiene, tra l’altro, l’indirizzo del broker a cui collegarci (nel mio caso, l’indirizzo IP del mio PC).

struct Options
{
    char* connection;         /**< connection to system under test. */
    char** haconnections;
    int hacount;
    int verbose;
    int test_no;
    int MQTTVersion;
    int iterations;
} options =
{
    "tcp://192.168.10.188:1883",
    NULL,
    0,
    0,
    0,
    MQTTVERSION_DEFAULT,
    1,
};

Se tutto è impostato nel modo corretto, l’applicazione di test verrà eseguita senza alcun problema.

08

MQTT con “Windows for IoT”

Una volta accertato il funzionamento sul PC, possiamo passare alla configurazione del remote debugging per eseguire l’applicazione sulla board Intel Galileo direttamente da Visual Studio; le impostazioni necessarie sono disponibili sul sito ufficiale di Windows On Devices.

09

Anche in questo caso, lanciando l’applicazione in debug dovremmo vedere tutti i messaggi nella console di Mosquitto che vengono scambiati con la board.

Abbiamo un client MQTT in esecuzione su di essa !

10

Se siamo curiosi di vedere anche l’output dell’applicazione di test, possiamo lanciarla attraverso una sessione Telnet direttamente dalla board. Al termine dell’esecuzione, viene visualizzato il report con tutti i test superati.

11

Ovviamente, tutte le modifiche apportati ai progetti relativi alla libreria sincrona, possono essere applicate anche ai progetti relativi alla libreria asincrona senza alcuna differenza con la garanzie di avere il medesimo risultato.

Windows for IoT : “cannot open include file arduino.h” ? Verifica la connessione ad Internet, hai bisogno del package Galileo C++ SDK su Nuget !

Ieri ho ricevuto il mio kit con la board Intel Galileo con la versione di “Windows for IoT” ed ovviamente, come un bambino che ha tra le mani il suo nuovo giocattolo, ho iniziato a giocare !

La cosa più semplice è quella di seguire la documentazione online, raggiungibile dal sito ufficiale Windows On Devices, che descrive passo passo come essere “up and running” in pochi minuti. La mia voglia di fare mi ha portato a commettere un “errore” che non mi ha permesso di concludere la procedura nel modo corretto. Cosa è successo ?

Dopo aver acceso la Galileo, averla collegata al PC e navigato tra le cartelle (sia con una sessione telnet che come “network shared”), ho deciso di sviluppare il primo esempio relativo al blinking del led. Apro Visual Studio 2013 e seleziono il template di progetto C++ relativo a Windows for IoT, avvio la compilazione ed …. ecco l’errore !!

0654.arduino_header_error_6768BD29

Non trova il file arduino.h ? Come mai ? Non viene installato insieme all’SDK che dobbiamo scaricare dal sito Microsoft Connect ? La risposta è no !

Tutti gli headers file con relativa implementazione sono nel Galileo C++ SDK che trovate su Nuget. Per questo motivo, ho dovuto manualmente scaricare tale package e referenziarlo nel mio progetto. A quel punto, tutto ha funzionato correttamente !

A quanto pare, però, sono stato l’unico ad avere questo problema e mi sono chiesto come mai ! Tutte le altre persone che hanno il kit hanno compilato il progetto di esempio senza alcun problema ma soprattutto senza dover scaricare manualmente il package Galileo C++ SDK da Nuget.

Ebbene non è proprio così ! Quel package è necessario ma il wizard lo scarica automaticamente al momento della generazione del progetto ed a quanto pare, in quel momento, il mio PC non era connesso ad Internet !!!

Se il PC non è connesso ad Internet, il wizard crea il file package.config vuoto :

<?xml version=”1.0” encoding=”utf-8”?>
<packages>
</packages>

Viceversa, esso contiene un riferimento al Galileo C++ SDK (Microsoft.IoT.Galileo.Arduino 1.0.0.0) nel momento in cui c’è connessione.

<?xml version=”1.0” encoding=”utf-8”?>
<packages>
 <package id="Microsoft.IoT.Galileo.Arduino" version="1.0.0.0" targetFramework="Native" />
</packages>

E’ ovvio che tale package è necessario se avete intenzione di sviluppare applicazioni Arduino-like (infatti il wizard specifica “Galileo Wiring app”) ma non nel caso di applicazioni Win32 standard.

Insomma … prima di partire con il Windows Developer Program for IoT assicuratevi di avere il PC connesso alla grande rete !