.NetGadgeteer

Open source nature and community for bringing .Net Micro Framework to a new life !

Yesterday, the biggest manufacturer of .Net Gadgeteer devices announced a bad news to the community: they won’t produce the boards based on it anymore.

To be precise, they won’t abandoned the entire .Net Micro Framework development but “only” all the boards known for the simplicity of developing prototypes avoiding soldering but using simple socket instead.

Of course, I’m speaking about the GHI Electronics.

I have some of their great boards used in a lot of demos and examples on .Net Micro Framework development for the Internet of Things during my sessions around Italy. Today, I can understand their decision: .Net Gadgeteer was created by Microsoft but today there isn’t so much effort on it and the community isn’t so huge for bringing the framework to the next level. In the last years, GHI Electronics was alone in order to support this framework and having it alive. From my point of view, it’s a pity because using .Net Gadgeteer boards, the ideas become reality in a very short time: from the advantage of using socket connection for the hardware to the application development with C# and .Net Micro Framework. The way to a final product is very long … but as starting point it was good.

To this bad news, we can add the silence by SecretLabs about another well-known board in the .Net Micro Framework world: the Netduino.

Netduino was my first love starting from its first version (without Ethernet) to the latest WiFi board. I played a lot with it, learning .Net Micro Framework development, even without the simplicity of hardware connections because I like “flying wires”. Even SecretLabs tried to do something like .Net Gadgeteer with Netduino Go without so much luck (they used a completely different “standard” for that).

The bad news and the silence let me start thinking about the future of the .Net Micro Framework.

Of course, to be precise, the framework life isn’t related to the future of the maker platforms provided by GHI Electronics and SecretLabs, because some companies are designing their own boards for running it.

It was born in the Microsoft research laboratories as the SPOT (Smart Personal Objects Technology) framework presented in the 2002. It became .Net Micro Framework and after some years Microsoft decided to provide it as open source without focusing so much on its development. Developers started to use it but only for hobbystic projects; only few companies decided to start developing real world products.

With the new IoT business, a couple of years ago Microsoft re-started to focus on it showing a lot of demos all around the world (at Build as well) based on .Net Micro Framework devices connected to Azure services (even before IoT Hub but using Service Bus and Event Hub). It seems that today this strong support is ended … Microsoft wants to provide better Cloud experience (the “I” in the IoT business) for all kind of devices without any difference on the running operating system or framework.

It seems to be another bad news for developers who believe in the .Net Micro Framework but fortunately … it’s always open source and the community can change its destiny.

As an open source developers (you know, I work for Red Hat … the company leader on open source) I believe in community projects : I started to write a lot of open sourced code for .Net Micro Framework a bunch of years ago and the community helped me to improve my libraries.

Today, Microsoft is providing few “human” resources to the .Net Micro Framework project hosted on GitHub in order to make the big changes on it and coordinate the community: I agree on that … now the community has the framework in its hands. At same time I know the Microsoft guys who are supporting it … they are great guys … trust me !

I know a lot of great guys who are working on .Net Micro Framework for their commercial products and for this reason I’m confident in the future. I know that the community around it isn’t so huge and it could be a problem for having a platform used as primary choice for embedded development. It’s also true that embedded world (yes ! embedded … not IoT !) is so much heterogeneous and each developer has its preferences: there is space for all of them, from ARM mbed platform to the .Net Micro Framework itself for example.

In the last months the interest about .Net Micro Framework was revamped by the new LILIUM project; to be precise it’s not the new version of the framework which has its own roadmap but a new way to develop in C# and UWP on embedded devices with the power of pre-compiled native code !

In order to define the right way for the community effort, two interesting discussions were opened on GitHub and all the main protagonists are arguing on the objectives and the roadmap: this is the essence of “to be a community”.

The first one is focused on the future of the .Net Micro Framework and its version 5 (today we are at 4.4) and the other one on the differences with LILIUM project; it’s worth for you to follow them both.

Let’s see … the IoT business opened a lot of scenarios … no doors are closed … can the open source nature and the community bring embedded C# development to a new life ?

Azure SB Lite … finally on Nuget !

azure_sb_lite_nuget

Finally my Azure SB Lite library is online on Nuget but … it was a long story 🙂

The last month, I decided to put this library on Nuget for all people that don’t like to compile source code from CodePlex and want to use it immediately. When I tried to upload the package, I received the “package id alredy used” error ! What ? Why ? Who ? Is there another library with same name ?

After few minutes I found that Sebastian Brandes (Microsoft Evangelist from Denmark) already uploaded it on Nuget in June (of course, he set me as “author”) and it was downloaded by 45 people. I contacted him who explained me that the library was useful to his project (thanks!) and that the right place for all other people was on Nuget (for much friendly usage). Right ! However, we decided that I should be the owner of the package so after about one month (Sebastian was on vacation) and Nuget support … today I re-uploaded the library !

I have to thank Sebastian for all his effort to help me to get the ownership of the package and for using it in his “Internet of Things” demo at Tech Ready conference (only for all Microsoft employees). He promised me to write a blog post and upload demo source code on GitHub.

Finally, I’d like to remember that there are some usage examples on GitHub at following link !

Internet of Things “wrap up” : eventi, slides, librerie e … demo con tanto codice !!

Nell’ultimo mese ho sviluppato molto ed ho avuto il piacere di essere speaker a tre eventi nazionali ed uno internazionale in California (ma da remoto).

Sono stato notevolmente impegnato nello scrivere codice e contenuti che ho deciso di riassumere qualora possano tornarvi utili.

DSC_0389 iotday

Con le slide ho cercato di descrivere al meglio l’Azure Service Bus focalizzandomi sull’Event Hubs e sul suo utilizzo nell’ambito della telemetria IoT :

A queste slide sono legate delle demo nelle quali ho utilizzato la mia ultima libreria Azure SB Lite, grazie alla quale è possibile accedere al Microsoft Azure Service Bus utilizzando le stesse API dell’SDK “originale” ma sulle piattaforme embedded come .Net Micro Framework e .Net Compact Framework oltre che su Mono (quindi Linux) e WinRT (quindi Windows 8.1 e Windows 10). Essa è basata sulla libreria AMQP .Net Lite di cui nasconde i concetti sul protocollo AMQP.

overall

Per quanto riguarda le demo :

  • BLE2Azure : concept di un IoT gateway da dispositive BLE verso Azure (Event Hubs) realizzato con il .Net Micro Framework e le board FEZ Spider e Netduino 3 Wi-Fi
  • Azure SB Lite Examples : esempi di utilizzo della libreria Azure SB Lite che mi hanno permesso (in quel di Venezia) di spiegare come funziona realmente l’accesso al Service Bus attraverso il protocollo AMQP e scoprire cosa ci sia al di sotto delle semplici APIs.

 Ovviamente non mi fermo qui nonostante il meritato riposo !

🙂

.Net Micro Framework e regular expressions … “out of range exception” !

Sviluppando la mia libreria per l’acesso al Microsoft Azure Service Bus (event hubs, queues, topics/subscriptions) basata su AMQP (e sulla libreria AMQP .Net Lite) mi sono imbattuto in un bug nel codice delle regular expression nel .Net Micro Framework.

Il bug si è verificato per puro caso, quando mi sono ritrovato con una “connection string” all’interno della quale c’era il campo “SharedAccessSignature” che va valorizzato nel caso in cui utilizziamo la connessione AMQP con CBS (Claim Based Security) ossia quando pubblichiamo su event hubs verso un “publisher” endpoint e con sicurezza basata su un SAS token.

In questo caso, il campo suddetto assume un valore abbastanza lungo, basta vedere la “connection string” nella quale mi sono imbattuto :

"Endpoint=sb://ppatiernoeventhubs.servicebus.windows.net/;SharedAccessSignature=SharedAccessSignature sr=http%3a%2f%2fppatiernoeventhubs.servicebus.windows.net%2fnetmftesteventhub%2fPublishers%2fdevice1&sig=FttwMBQt0T1e1hPQIk0TbRSfuPohbTXAi5L8dPSQzbA%3d&se=1306887634&skn=EventSendKeyName;EntityPath=ppatiernoeventhub;Publisher=device1;TransportType=0";

Per estrarre i campi, ho scritto le seguenti righe di codice :

Regex regex = new Regex("([^=;]+)=([^;]+)");

IDictionary connectionStringParams = new Hashtable();

MatchCollection matches = regex.Matches(connectionString);
foreach (Match match in matches)
{
	connectionStringParams[match.Groups[1].Value] = match.Groups[2].Value;
}

Alla seconda iterazione ossia in corrispondenza del campo “SharedAccessSignature” mi sono ritrovato di fronte ad una OutOfRangeException … dovuta a cosa ?

 regex_netmf

Dallo screenshot si evince che il campo “Length” del match riscontrato ha un valore negativo pari a -80. Come mai ?

Ebbene, il valore del campo “SharedAccessSignature” (il SAS token) ha una lunghezza pari a 208 e facendo una semplice sottrazione 128 – 208 è proprio pari a -80.

Probabilmente nel .Net Micro Framework viene utilizzata una variabile del tipo “signed byte” per contenere tale valore che determina un ovvio overflow; la lunghezza massima di un valore in un match è stata probabilmente fissata a 128.

Purtroppo, fino alla correzione del bug che ho provveduto a segnalare, vi consiglio di evitare matching con valori più lunghi di 128 caratteri !

🙂

MQTT & Eclipse Paho : nuove versioni per il client M2Mqtt ed il broker GnatMQ !!

Finalmente la nuova versione M2Mqtt 4.1 è stata rilasciata !

Negli ultimi mesi, la mia libreria è stata messa sotto pressione grazie ai miei amici Olivier Vigliengo (Adeneo) e Nicolas Besson (Microsoft MVP su Windows Embedded, Adeneo). Essi hanno usato il client MQTT per i loro progetti hobbistici, stressandolo non poco !

Dopo un fitto scambio di email e letture di log traces, ho risolto una serie di bug ed aggiunto degli miglioramenti :

  • L’evento di “published” fornisce la flag IsPublished (nell’event args) grazie alla quale poter capire se il messaggio è stato realmente pubblicato oppure no a causa del timeout (l’evento viene sollevato lo stesso);
  • Alcuni cambi “interni” per la gestione degli eventi;
  • Fixato un bug su timeout negativo;
  • Migliorata la stabilità della libreria in condizioni di rete poco affidabile;
  • Fixato un bug sulla gestione delle sessioni;
  • Aggiunte le informazioni di trace sul “queueing” dei messaggi;

Ovviamente, questi cambiamenti hanno avuto il loro impatto anche sul broker GnatMQ che è ancora in Beta ma che mi piacerebbe rilasciare al più presto : spero che le persone che lo usino mi diano dei feedback (sembra che il team di XSocket lo stia usando per fornire il supporto MQTT alla loro piattaforma) 🙂

Come sempre potete trovare M2Mqtt nel progetto Eclipse Paho, su CodePlex e su Nuget. Il broker GnatMQ è disponibile solo su CodePlex. Infine, ho aggiornato anche il progetto M2Mqtt4CE (per Windows Embedded Compact 2013) su CodePlex.

Internet of Things : dal “cos’è” al “come” con le tecnologie Microsoft

IoT_dotnetcampania

Il nuovo portale della community DotNetCampania, di cui faccio parte, è online da qualche settimana e la sezione degli articoli si arricchisce ogni giorno di nuovi contenuti con gli argomenti più svariati, dallo sviluppo web e mobile all’ALM, dai patterns all’Internet Of Things.

Ovviamente, la sezione a cui partecipo più attivamente è quella relativa all’IoT per la quale ad oggi ho scritto i due seguenti articoli :

Nel primo, un’introduzione su cosa sia l’Internet of Things e come i sistemi embedded rientrano in questo nuovo business. Nel secondo, tutte quelle che sono le tecnologie che Microsoft mette a disposizione per la realizzazione di una soluzione IoT completa, dai device (le “cose”) al “Cloud”.

Buona lettura !

🙂

Una nuova casa per il .Net Micro Framework … GitHub !!

netmf_github

Il primo passo “visibile” del nuovo .Net Micro Framework è stato compiuto … finalmente il repository ufficiale delle future versioni è GitHub; viceversa le precedenti versioni del framework rimarrano su CodePlex così come il forum. Ogni bug/issue riportata su CodePlex verrà valutata ed inserita come “work item” in GitHub.

Ricordando la natura da “interprete” del runtime, il progetto è stato battezzato proprio “.Net Micro Framework Interpreter” ma contiene l’interprete, la BCL (Base Class Library) ed il codice nativo per il porting.

Dal punto di vista delle funzionalità, le principali novità della versione 4.4 (Beta) sono :

  • miglioramento della stack di rete con maggiore stabilità nelle connessioni;
  • miglioramenti nel deploy e nel debug (non passerà più un’eternità tra uno step e l’altro);

Per chi lo volesse provare, non è disponibile l’SDK pronto da scaricare ma è necessario ricompilare i sorgenti. Inoltre, non è nemmeno più necessario il Porting Kit (a parte) come nelle versioni precedenti.

Cosa si prospetta per il futuro ?

Si parla di supporto per Visual Studio 2015, introduzione delle API WinRT ed .. udite … udite … supporto per AllJoyn !!

Il meccanismo di “string interning” nel .Net Micro Framework

Consideriamo la seguente semplicissima applicazione console in C# …

 static void Main(string[] args)
 {
   string s1 = "Hello world";
   string s2 = "Hello world";

   Console.WriteLine(s1.Equals(s2));
   Console.WriteLine(ReferenceEquals(s1, s2));
   Console.WriteLine(s1 == s2);

   string s3 = String.Intern(Console.ReadLine());

   Console.WriteLine(s1.Equals(s3));
   Console.WriteLine(ReferenceEquals(s1, s3));
   Console.WriteLine(s1 == s3);

   Console.ReadKey();
 }

Il cui output è il seguente …

string_intern_net

Come sappiamo il metodo Equals() e l’operatore “==” verificano che se le due stringhe contengono lo stesso valore pur avendo un reference diverso (s1 ed s2), per cui è ovvio il risultato “True”. Ma come mai la ReferenceEquals() continua a fornire “True” e non “False” considerando che i due riferimenti sono diversi ?

Bene ! Essi non sono diversi in realtà !

Il .Net Framework fornisce un meccanismo di “string interning” ossia un pool all’interno del quale gestisce le stringhe che hanno il medesimo valore evitando di allocare inutilmente ulteriore memoria. Per questo motivo, s1 ed s2 sono in realtà il medesimo riferimento !

E’ ovvio che, quando una stringa viene acquisita dall’esterno ciò non accade ed è quindi necessario chiedere esplicitamente al framework di cercare la stringa acquisita prima nel pool interno ed eventualmente allocarne una nuova se essa non esiste … questo è l’obiettivo dell’istruzione String.Intern().

Proviamo ora ad eseguire il medesimo codice (a meno di alcune modifiche) sul .Net Micro Framework …

 public static void Main()
 {
    string s1 = "Hello world";
    string s2 = "Hello world";
 
    Debug.Print(s1.Equals(s2).ToString());
    Debug.Print(ReferenceEquals(s1, s2).ToString());
    Debug.Print((s1 == s2).ToString());

    string s3 = String.Intern("Hello world");
    
    Debug.Print(s1.Equals(s3).ToString());
    Debug.Print(ReferenceEquals(s1, s3).ToString());
    Debug.Print((s1 == s3).ToString());
 }

con il seguente risultato …

string_intern_netmf

In questo caso il ReferenceEquals() ci conferma che i due reference sono diversi nel primo caso ma anche utilizzando String.Intern() … come mai ?

Il motivo è semplice … il .Net Micro Framework non supporta il meccanismo di “string interning” e non fornisce un pool interno di stringhe e la risposta è come sempre nell’implementazione nativa. Guardando nel file String.cs, troviamo :

 public static String Intern(String str)
 {
   // We don't support "interning" of strings. So simply return the string.
   return str;
 }

 public static String IsInterned(String str)
 {
   // We don't support "interning" of strings. So simply return the string.
   return str;
 }

Un esplicito commento ci dice che questa funzionalità non è supportata !

Regex portabile fra .Net e .Net Micro Framework … fate attenzione !

Sviluppando su tutte le versioni del .Net Framework (full, compact e micro) mi capita sempre di dover affrontare il problema della portabilità, evitando di utilizzare metodi che non siano disponibili in uno dei tre framework oppure utilizzando le direttive di precompilazione.

Non mi è mai capitato, però, un caso in cui il metodo esista in tutti i framework ma i parametri abbiano un significato diverso … siano addirittura invertiti !!

Il metodo in questione è l’overload di Regex.Split(String, String, RegexOptions) !

La firma è praticamente la stessa confrontando il .Net Framework ed il .Net Micro Framework ma …. con una notevole differenza nei primi due parametri.

Dalla documentazione MSDN del .Net Framework si legge che il primo parametro è la stringa da splittare mentre il secondo è il pattern da applicare.

01

Viceversa, nella documentazione MSDN del .Net Micro Framework si legge che il primo è il pattern ed il secondo è la stringa di input !!

02

Per assicurarmi che l’errore non fosse nella documentazione, ho cercato il codice sorgente del .Net Micro Framework in cui è implementato questo metodo ma purtroppo è arrivata la conferma !

 /// <summary>
 /// Splits the input string at the positions defined by a specified regular expression pattern. Specified options modify the matching operation.
 /// </summary>
 /// <param name="pattern">The pattern to match against</param>
 /// <param name="split">The string to split</param>
 /// <param name="options">The options to utilize during matching</param>
 /// <returns>The result of splitting the input string against the pattern</returns>
 public static string[] Split(string pattern, string split, RegexOptions options)
 {
   return new Regex(pattern, options).Split(split);
 }

Assolutamente strano … anche questa volta ho deciso di aprire una issue sul sito ufficiale del .Net Micro Framework su CodePlex !

Codifica Base64 non standard nel .Net Micro Framework

Come sappiamo, per poter accedere ai servizi Azure, in molti casi è prevista la SAS (Shared Access Signature) Authentication mediante l’invio di un token attraverso il quale otteniamo i diritti per poter eseguire specifiche operazioni.

Tale token si ottiene mediante la costruzione di una stringa contenente una serie di informazioni tra cui l’URI a cui accedere e la scadenza (expiry time) sulla quale calcolare un HMAC (Hash Massage Authentication Code) con SHA256. Il risultato di questa operazione di hashing viene codificato in Base64 ed il risultato ottenuto viene inserito all’interno del token (Shared Access Signature) con un opportuno formato.

L’obiettivo di questo post non è quello di descrivere precisamente la procedura per la determinazione del token ma di mettere in guardia chi utilizza le funzioni di conversione in Base64 messe a disposizione dal .Net Micro Framework.

Eseguendo i miei test con una board FEZ Spider per la connessione al Service Bus, ho riscontrato molte volte la condizione di accesso non autorizzato a causa di un token non correttamente calcolato. Eseguendo la stessa procedura sul PC, tutto funzionava correttamente. Come mai ?

Inizialmente ho pensato ad un errore nel calcolo della firma (HMAC) e solo dopo ho capito che c’era qualcosa che non andava nella codifica Base64.

Sono finalmente riuscito ad estrarre un caso di errore a seguito della firma rappresentata attraverso i seguenti bytes :

byte[] hmac = { 0x16, 0x01, 0x70, 0x76, 0xec, 0xc8, 0xdb, 0x01, 0xf0, 0x6a, 0x60, 0x9a, 0x89, 0x68, 0x6f, 0xef, 0x68, 0x9a, 0xad, 0x10, 0xe7, 0x92, 0x9b, 0xef, 0xfa, 0x10, 0x86, 0x24, 0xf1, 0x72, 0xa6, 0x69 };

Se proviamo a codificare in Base64 l’array di bytes suddetto con il metodo  Convert.ToBase64String(hmac) su PC, il risultato è il seguente :

FgFwduzI2wHwamCaiWhv72iarRDnkpvv+hCGJPFypmk=

Se proviamo ad eseguire la medesima operazione con il .Net Micro Framework, la codifica è la seguente :

FgFwduzI2wHwamCaiWhv72iarRDnkpvv!hCGJPFypmk=

In rosso ed in grassetto ho evidenziato la differenza tra le due codifiche ma … qual’è il motivo ?

Come sempre, la risposta è nell’implementazione nativa del .Net Micro Framework e questa volta nel file Convert.cs all’interno del quale si evincono due “alfabeti” per la codifica Base64 : l’alfabeto standard RFC4648 ed un alfabeto non standard.

 /// <summary>
 /// Conversion array from 6 bit of value into base64 encoded character.
 /// </summary>
 static char[] s_rgchBase64EncodingDefault = new char[]
 {
 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', /* 12 */
 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', /* 24 */
 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', /* 36 */
 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', /* 48 */
 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 60 */
 '8', '9', '!', '*' /* 64 */
 };

 static char[] s_rgchBase64EncodingRFC4648 = new char[]
 {
 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', /* 12 */
 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', /* 24 */
 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', /* 36 */
 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', /* 48 */
 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 60 */
 '8', '9', '+', '/' /* 64 */
 };

 static char[] s_rgchBase64Encoding = s_rgchBase64EncodingDefault;

Questi due alfabeti differiscono per gli ultimi due caratteri che sono “+” e “/” nel primo ma “!” e “*” nel secondo. A quanto pare il carattere “!” è relativo alla codifica Base64 nelle regular expressions mentre “*” é relativo alla medesima codifica nel privacy-enhanced mail.

Dal codice si evince che l’alfabeto di default (s_rgchBase64Encoding) che viene utilzzato non è quello standard !!

Come è possibile risolvere il problema ?

Per fortuna, la classe Convert fornisce la proprietà statica UseRFC4648Encoding che va impostata a true e grazie alla quale viene utilizzato l’alfabeto standard RFC4648 per ogni codifica Base64.

La mia opinione è che sarebbe opportuno invertire la logica in modo che la codifica di default sia quella standard e per questo motivo ho già aperto una issue sul sito ufficiale del .Net Micro Framework su CodePlex.

Voi cosa ne pensate ?