BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el...

82
BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux DEGREE: Bachelor in Telematics Engineering AUTHOR: Gerard Solé i Castellví DIRECTOR: Juan López Rúbio DATE: February 7, 2014

Transcript of BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el...

Page 1: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

BACHELOR’S THESIS

TITLE : IOSharp: .NET Micro Framework on Linux

DEGREE: Bachelor in Telematics Engineering

AUTHOR: Gerard Solé i Castellví

DIRECTOR: Juan López Rúbio

DATE: February 7, 2014

Page 2: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites
Page 3: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Títol : IOSharp: .NET Micro Framework on Linux

Autor: Gerard Solé i Castellví

Director: Juan López Rúbio

Data: 7 de febrer de 2014

Resum

Cada vegada més l’Internet de les Coses està en auge impulsant tot tipus de dispositiusincrustats i sistemes operatius per aquests dispositius. L’objectiu d’aquest projecte de fide carrera és desenvolupar una llibreria capaç d’executar aplicacions desenvolupades pera .NET Micro Framework (màquina virtual per a dispositius incrustats) en dispositius quepuguin executar qualsevol versió de Linux. Això permetria executar aplicacions de .NETMicro Framework en ordinadors d’escriptori o en dispositius embeguts que executin Linux,com per exemple Raspberry Pi.

En aquest document es presenta el plantejament i el desenvolupament d’IOSharp quecorrespon a la implementació en C# del sistema comentat anteriorment. Un cop aquestaimplementació s’ha dut a terme, s’ha passat a la fase de proves amb les aplicacions exis-tents on s’ha pogut determinar que el rendiment de la llibreria no és òptim. En aquest puntés on hi ha hagut una de les altres contribucions principals en el projecte, s’ha participat enel desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites en .NET a C++, d’aquesta manera s’avaluarà la millora del rendiment de la llibreriaal traduir-la amb l’AlterNative.

Page 4: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites
Page 5: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Title : IOSharp: .NET Micro Framework on Linux

Author: Gerard Solé i Castellví

Director: Juan López Rúbio

Date: February 7, 2014

Overview

Increasingly, the Internet of Things is promoting all types of embedded devices and op-erating systems for these devices. The aim of this project is to develop library capableof running applications developed for .NET Micro Framework (virtual machine for embed-ded devices) on devices that can run any version of Linux. The idea is that using thislibrary a developer can execute any application developed for .NET Micro Framework inany desktop computer or embedded device running Linux, for example Raspberry Pi.

This thesis presents the approach and the development of IOSharp which is an implemen-tation in C# of the system discussed above. Once this implementation has been done,a test phase has been done with existing applications. In this case, it has been provedthat the performance of this library is not optimal compared with the original one. At thispoint is where started another of the main contributions to the project, participating in thedevelopment of a tool called AlterNative which is able to translate applications written in.NET to C++, In this way it has been possible to analyse the improvement of this libraryafter translating it with AlterNative.

Page 6: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites
Page 7: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Un gran agraïment als meus pares, germanes i avis. Sense el suport dels quals hauriaestat impossible tot el temps dedicat tant a la carrera com en el projecte.

També a Juan López, Alex Albalá i Carla Iriberri els quals han tingut la paciència suficientper a contribuir en el bon camí d’aquest treball.

A Adrián Galera, Alberto Toro, Jesús Alcober, Marc Bajet, Norbert Nebra, Santi Pérez,Toni Oller, juntament amb Juan López i Alex Albalá. Treballar amb tots vosaltres dona

gust.

Finalment a Pau Martínez, Marc Beltrán i Marta Jiménez pel gran suport en les últimesfases d’aquest projecte.

Page 8: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites
Page 9: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

CONTENTS

INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

CHAPTER 1. Project overview . . . . . . . . . . . . . . . . . . . . . . . . 3

1.1 HomeSense . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.2 AlterNative . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.3 Thesis Proposal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.3.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.4 Document Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

CHAPTER 2. State of the art . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.1 Embedded Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.1.1 Operating Systems Architectures . . . . . . . . . . . . . . . . . . . 7

2.1.2 Embedded Operating Systems . . . . . . . . . . . . . . . . . . . . 8

2.2 .NET Micro Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.2.1 Devices using Micro Framework . . . . . . . . . . . . . . . . . . . . 9

2.2.2 NETMF on Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.2.3 NETMF on RaspberryPi . . . . . . . . . . . . . . . . . . . . . . . . 10

2.3 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

CHAPTER 3. IOSharp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

3.1 Planning the development . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.1.1 Focused on Raspberry Pi . . . . . . . . . . . . . . . . . . . . . . . 13

3.1.2 Focused on Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

3.1.3 Chosen implementation . . . . . . . . . . . . . . . . . . . . . . . . 14

3.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.2.1 GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

3.2.2 Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

3.2.3 SPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

3.2.4 UART . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

3.3 Port Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273.3.1 HardwareProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Page 10: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

CHAPTER 4. Functional Tests . . . . . . . . . . . . . . . . . . . . . . . . 29

4.1 SPI. RFID and IOSharp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.1.1 Micro Framework version . . . . . . . . . . . . . . . . . . . . . . . 29

4.1.2 Migrating to Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

4.2 HomeSense . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314.2.1 Gateway . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

4.2.2 Deploying on Raspberry Pi . . . . . . . . . . . . . . . . . . . . . . 33

4.3 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

CHAPTER 5. AlterNative . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

5.1 Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

5.2 Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355.2.1 Decompilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

5.2.2 Translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

5.2.3 Recompilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

5.3 Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385.3.1 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

5.3.2 Cross-Platform in embedded systems . . . . . . . . . . . . . . . . . 38

5.4 Contributions to AlterNative . . . . . . . . . . . . . . . . . . . . . . . . . . 38

5.5 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

CHAPTER 6. Performance tests . . . . . . . . . . . . . . . . . . . . . . . 43

6.1 Compilation types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

6.2 GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446.2.1 200 Iterations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

6.2.2 10K Iterations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

6.3 Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

6.4 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

CHAPTER 7. Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

7.1 Project Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517.1.1 Achieved Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Page 11: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

7.2 Personal Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

7.3 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

7.4 Environmental Impact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

GLOSSARY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

REFERENCES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

APPENDIX A. Technical information. Libraries and Datasheets . . 1

A.1 Library Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

A.2 spidev.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

A.3 SPI Test. RFID Reader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4A.3.1 MFRC522 Datasheet . . . . . . . . . . . . . . . . . . . . . . . . . 4

A.3.2 RFID Reader program . . . . . . . . . . . . . . . . . . . . . . . . . 4

A.4 AlterNative System Library . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Page 12: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites
Page 13: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

LIST OF FIGURES

1.1 Sensor on the left and HomeSense gateway on the right . . . . . . . . . . . . 31.2 AlterNative interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2.1 SPOT watch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.2 Micro Framework devices. Netduino Plus on the left, Netduino Mini on the center

and Cerbuino on the right. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

3.1 Representation of IOSharp . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.2 UML Diagram of NETMF Port and its inheritance . . . . . . . . . . . . . . . . 173.3 UML Diagram of NETMF Interrupt Port . . . . . . . . . . . . . . . . . . . . . 183.4 Representation of the Interrupt Port flow . . . . . . . . . . . . . . . . . . . . . 203.5 SPI bus setup with one master and two slaves . . . . . . . . . . . . . . . . . 223.6 SPI modes are defined with the parameters "CPOL" and "CPHA" to the data

sampling acording to the System Clock (SCLK) state. . . . . . . . . . . . . . . 223.7 UML representation of the SPI Configuration Class (Left) and the SPI Port (Right)

243.8 UART communication schema . . . . . . . . . . . . . . . . . . . . . . . . . . 253.9 UML SerialPort representation of the original .NET Framework (Left) and .NET

Micro Framework (Right) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263.10Raspberry Pi pin mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

4.1 Data exchange using the SPI . . . . . . . . . . . . . . . . . . . . . . . . . . . 314.2 Sensor for a medicine cabinet . . . . . . . . . . . . . . . . . . . . . . . . . . 314.3 Diagram showing the protocols and devices used in HomeSense . . . . . . . . 324.4 Raspberry Pi with the modules needed to run HomeSense . . . . . . . . . . . 334.5 HomeSense dashboard. The aaaida logo on the left represents the Raspberry

Pi (gateway) whereas the door represents a sensor . . . . . . . . . . . . . . . 34

5.1 AlterNative process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355.2 AST representation of the main method in C# . . . . . . . . . . . . . . . . . . 365.3 AST representation of the main method in C++ . . . . . . . . . . . . . . . . . 375.4 Stack in the original .NET Micro Framework, the IOSharp implementation and

the AlterNative translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

6.1 200 Iterations using C# with optimizations . . . . . . . . . . . . . . . . . . . . 466.2 200 Iterations using C++ with optimizations . . . . . . . . . . . . . . . . . . . 466.3 Graph showing the elapsed time for the 200 iteration test. Blue is for C++ while

orange is C#. On the left is represented the non-optimized compilations and onthe right the optimized ones . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

6.4 10k Iterations using C# with optimizations . . . . . . . . . . . . . . . . . . . . 476.5 Graph showing the elapsed time for the 10k iteration test. Blue is for C++ while

orange is C#. On the left is represented the non-optimized compilations and onthe right the optimized ones . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

6.6 Response time of an interrupt in C# and Mono . . . . . . . . . . . . . . . . . . 496.7 Response time of an interrupt in C++ . . . . . . . . . . . . . . . . . . . . . . 49

Page 14: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

A.1 Tree dump of the C++ libraries of AlterNative currently implemented . . . . . . 6

Page 15: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

LIST OF TABLES

3.1 Interrupt Trigger Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

5.1 Representation in C# and C++ of the Main method of a program . . . . . . . . 36

Page 16: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites
Page 17: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

1

INTRODUCTION

Embedded systems have become more powerful over time passing from 8 bit controllersto 8 or 16 bit microprocessors or even 32 bit ARM microprocessors. Apart from the in-crease of the processing power, the memory included in this devices has also increased,from tens of Kilobytes to tens or hundreds of Megabytes. One of the reasons for thesechanges has been the price drop on production. These new embedded systems offer aperformance similar to the computers from the nineties and most of them implement op-erating systems which helps on reducing the difficulty to create embedded applications.With an operating system running over the bare metal of the chip, the developer will get allthe underlying hardware abstracted to different APIs and libraries and avoiding low levelinteraction with the hardware. They also offer interesting features such as memory con-trol and allocation, threading or dynamic program loading. For example, one of the topnotch devices nowadays is the Raspberry Pi which provides an ARMv6, 512MB of RAMand some I/O features such as GPIOs, SPI, UART. This hardware can be equivalent to anineties computer like a Pentium II so they are really powerful regarding the task that theymay do.One of the operating systems available for embedded devices is .NET Micro Framework(NETMF) developed by Microsoft. This system is the smallest version of .NET Frameworkand is oriented to resource-constrained devices for embedded applications. This systemoffers different communication protocols and methods like GPIO ports, SPI, UART andI2C. There is no official implementation or port of Micro Framework capable of runningon standard computers (a normal desktop), so any application written for this operatingsystem will not work on Linux or Windows. Although a minimal port of Micro Frameworkexists for a Linux board called Eddy, it does not offer all the hardware features that MicroFramework does.The aim of IOSharp is to solve this lack and get Micro Framework applications run on anyLinux machine that is capable of running applications using the .NET Framework (the com-plete stack designed by Microsoft). So this project instead of writing a complete port of theMicro Framework runtime to run on Linux, is an extension to the classes provided by the.NET Framework. Basically, IOSharp offers the I/O functions, methods and classes thatare missing on .NET Framework, and although the implementation of the classes is differ-ent in IOSharp than in Micro Framework, the namespaces, methods, class naming, etc isequal to the original one so this makes much easier to migrate between Micro Frameworkto .NET Framework with IOSharp.The origin of this project resides in the need of migrating the code of an existing WirelessSensor Network (WSN) gateway implemented on Micro Framework for a Netduino Miniboard. One of the problems that this platform has is that the actual device is getting outof system resources, so in order to keep the existing code, different solutions are beingresearched. In this case IOSharp intends to be one of those solutions achieving the de-ployment of this WSN gateway software on a Raspberry Pi which runs a Linux operatingsystem.

After achieving the first goal, there is a second step of this project which consists on ex-tending a code translation tool called AlterNative which is being developed by Alex Albaláand Juan López. This translator is capable to get the source code from a C# assemblyand then translate it to C++ trying to improve the performance. C++ theoretically performs

Page 18: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

2 IOSharp: .NET Micro Framework on Linux

better than C# applications, but normally are more platform oriented, so a Windows as-sembly will not work on a Linux system, but one of the interesting features of AlterNativeis the generation of a highly portable code that can be compiled on (and for) any operatingsystem, i.e. Windows, Linux, MacOSX, iOS, Android, etc. Another interesting point of thistool is that the generated code is similar to C# so a developer used to this language will beable to understand or even write programs using the translated code.

Page 19: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Project overview 3

CHAPTER 1. PROJECT OVERVIEW

This project was proposed by AlterAid, a company which is working on several ways tohelp in taking care of the health of our elderly, or in general, anyone that is relevant to ourlives.

This company is working on two different projects that combine together. The first one iscalled aaaida, which consists of a social network where people can stay alert about itsrelatives, upload information about its health or watch recommendations from doctors orother professionals. On the other side, and on a more hardware oriented development,they are creating a Wireless Sensor Network called HomeSense that once deployed in ahouse will be able to collect relevant information from those sensors in the home and allowother people to know if the daily life of the resident’s house is going normal, or somethingis happening.

1.1 HomeSense

HomeSense is a Wireless Healthcare Sensor Platform created with the aim of control andcare taking of elderly and relatives. Actually it uses a Netduino Mini board which makesthe function of the gateway which controls the sensor network, receiving all the data anduploading to aaaida platform through Internet.In the house, the communication is carried on using little sensors capable of fetching datain different situations (for example the opening of a drawer or a medicine cabinet). It isalso possible to install the sensors on doors in order to know if they are opened or closed,or in any place where is interesting to acquire information from the environment, house orresidents. These sensors make use of nRF24LE1 SoC with a low-power RF ISM band on2.4GHz from Nordic Semiconductor.The communication protocol designed for HomeSense is similar to a star network withmulti-hop transmissions so it becomes a tree-star topology. The nodes mainly send infor-mation to the gateway because this is on charge of upload the information to the Internet,but they are also able to communicate with other nodes. The gateway system has beenentirely developed using .NET Micro Framework and deployed on a Netduino Mini board.

Figure 1.1: Sensor on the left and HomeSense gateway on the right

Page 20: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

4 IOSharp: .NET Micro Framework on Linux

1.2 AlterNative

AlterNative is a language translating tool created by Alex Albalá and Juan López. It cantranslate a compiled (.NET) assembly or library to standard C++ code. Basically this pro-gram decompiles the file to be translated, then it sketches how the program works, whichare its classes, functions, nodes, etc and then start translating step-by-step all the pro-gram. After that, it links the necessary C++ libraries to work, ones are from boost library,and the other ones are self-written to behave like the original C# classes.It is interesting to emphasize that the main difference of this translator between the otherexisting ones is that it tries to generate a code practically identical to the original C# sourcecode. By doing this, the resulting C++ source is really easy to read for people not used toC++ syntax and language.

Figure 1.2: AlterNative interface

1.3 Thesis Proposal

After introducing HomeSense and AlterNative is time to explain the thesis proposal itselfbecause it is related to the applications mentioned above. The proposed project is to takethe code of the HomeSense gateway, which is written using Micro Framework, and makeit run in a Linux device instead of a Netduino Mini. The reason is that the Netduino Mini isgetting limited in terms of capabilities, performance and expansion for future characteris-tics.The idea is to take the gateway code and port it to other devices capable of use minimumGPIO, interrupts from this ports, the SPI communication protocol and UART because allof them are used in the HomeSense source code. It is important to point that the im-plemented classes must be similar to the Micro Framework code to avoid major changeson the HomeSense program. Minor changes such as port renaming and communication

Page 21: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Project overview 5

module name changing are acceptable, because they do not alter the original executionflow and design architecture. But not only this should be done on HomeSense, it is in-teresting to make portable between different hardware platforms any code that runs overMicro Framework.After accomplishing with this first goal, the second part of the thesis is to use AlterNativeto translate the IOSharp library to C++ in order to increase and analyse the performanceof IOSharp running on C++ instead of C#. To accomplish with this objective, some C++libraries must be written in order to translate IOSharp.

1.3.1 Objectives

The proposed objectives are listed below:

• IOSharp: to be accomplished during the first part of this thesis.

– GPIO: Simple I/O functions (Input, Output ports).

– Interrupts: enable interrupts through GPIOs.

– SPI: get a working SPI bus on the implementation.

– UART: do serial transmissions.

– HomeSense: deploy this WSN as a functional test to show the correct functionof this library.

• AlterNative: second part of the thesis involving the code translation tool.

– Cross-Platform: although one of the goals of AlterNative is produce a cross-platform source code, it only runs on Windows so Linux or MacOSX users areunable to use this tool. In this case, the code must be analysed and modified toproduce a compatible program with any operating system capable of run .NETcode.

– Library: write the necessary library methods to translate IOSharp.

– Tests: functional tests to determine the correct functionality of the above meth-ods.

– Performance analysis: do some performance analysis to check the perfor-mance increase when the code is translated.

– Translate HomeSense: do a complete translation of the WSN platform usingAlterNative.

1.4 Document Structure

This document is structured on seven chapters. The first one shows the project definition.Then a state of the art is used to show the current technologies or systems that are similarto this thesis goal. Another chapter sketches the how has been carried out the develop-ment. The functional test chapter wants to proofs that IOSharp implementation objectives

Page 22: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

6 IOSharp: .NET Micro Framework on Linux

are done. Then an introduction to AlterNative is done along with the performance testschapter which shows the results for the AlterNative part. Finally, the conclusions chaptersummarizes the thesis results.

Page 23: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

State of the art 7

CHAPTER 2. STATE OF THE ART

This chapter briefly sketches out the state of the art of the embedded operating systemsand its capabilities.

2.1 Embedded Systems

Embedded Systems nowadays are taking relevance again with the Internet of Things, envi-ronment sensing, Wireless Sensor Networks and all new coming technologies that requirelow power consumption, small size, mobility environments, etc.

In Embedded Systems or Resource Constrained Systems it is interesting to take a lookinto the Hardware platform and its capabilities, the differences between platforms, andalso which tools or unique features they offer to developers.

An operating system (OS) offers an interface with the hardware to make it independentfrom the applications that the device runs, making easy the interactions between hardwareand the programs running on the machine.Until now, most embedded devices did not make use of operating systems and they wheretotally oriented to the designated application but as it has been explained in the introduc-tion, the cost reduction in the production of systems has helped to increase the capacitiesso now is not unusual to embed a Linux system to simplify the manage of the resources.An OS is an important software that makes easy to develop applications, but it is impor-tant to maintain the features that the processor offers, avoiding performance or capabilitiesdegradation. This bachelor thesis is focused on constrained-resource devices, where theprocessing capabilities and memory resources are limited, is fundamental to respect theabove criteria.

2.1.1 Operating Systems Architectures

In general, there are three types of operating system architectures for embedded devices,which are based on how applications are executed or included into the OS.

• Monolithic: The OS and the applications are combined into a single program. Nor-mally in this situations the embedded device runs in the same process the OS andthe program written to it. This type of architecture makes difficult to include newfunctions without rewriting much of the code.

• Modular: The OS is running as a standalone program in the processor and has theability of loading programs as modules. In terms of the development, it’s possible todevelop applications without writing in the core of the OS. Normally using modulesdevelopers can expand the capabilities of its software.

Page 24: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

8 IOSharp: .NET Micro Framework on Linux

• Virtual-Machine: The virtual machine creates an abstraction layer of its underly-ing hardware. This abstracted layer is common in every device that implementsthat virtual-machine. Using this type of operating system provides a helpful tool toachieve the well known slogan write once, run anywhere. Although using virtual-machine devices simplifies the development on multiple devices, the performanceof the platform normally will be reduced and in Real Time environments it is notrecommended to use it. It is interesting to remark that embedded virtual machines,differently from VMs in desktop or server environments, run on the bare metal sothey also act as an operating system.

2.1.2 Embedded Operating Systems

There is a wide range of Embedded Operating Systems each of them has strengths andweaknesses. Below different OS are described and compared.

• TinyOS is a popular open source OS for wireless constrained devices, many ofthem used in wireless sensor networks. It provides software abstractions from theunderlying hardware. It is focused on wireless communications offering stacks for6LoWPAN and ZigBee. It also supports secure networking and implements a RPLtaking in mind the forthcoming routing protocol for low power and lossy networks.However, TinyOS changes how programs should be developed, it intended to usenon-blocking programming which means that it is not prepared for long processingfunctions. For example, when TinyOS called to send a message the function willreturn immediately and after a while the send will be processed and then, TinyOS willmake a callback to a function, for example send()’s callback will be sendDone().

• FreeRTOS is a free real-time OS that supports over 34 architectures and it is beingdeveloped by professionals under strict quality controls and robustness. It is usedfrom toys to aircraft navigation and it is interesting for its real-time qualities. It hasa very small memory footprint (RAM usage) and very fast execution, based on hardreal-time interrupts performed by queues and semaphores. Apart from this, thereare not constraints on the maximum number of tasks neither the priority levels thatcan be used on tasks.

• Contiki is similar to TinyOS in terms of portability between platforms and its codeis open source. It also offers features similar to standard operating systems likethreading, timers, file system and command line shell and uses modular architecture,loading or unloading programs from its kernel. Contiki is built on top of the InternetStandards supporting IPv4 and IPv6 and also the new low-power internet protocolswhich includes 6LoWPAN, RPL and CoAP.Contiki uses protothreads, which are designed for event-driven systems running ontop of constrained devices, which is the case of Contiki’s kernel. It provides blockingwithout having a real multi-threading system or a stack-switching.

• Micro Framework .NET is a solution provided by Microsoft for resource-constraineddevices which cannot execute the full .NET stack. It is Virtual-Machine based oper-ating system that has a small implementation of the CLR making available to execute

Page 25: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

State of the art 9

a small set of .NET classes. Its memory footprint is about 300KB and supports thecommon embedded peripherals like EEPROM, GPIO, SPI, UART, USB, ...One of its interesting features is that it offers the advantages of .NET language usingVisual Studio and it also offers real-time debugging directly on the device.

2.2 .NET Micro Framework

Micro Framework, also known as NETMF, has its roots in a project called Smart PersonalObjects Technology (SPOT). The first devices implementing the SPOT technology weresmart-watches from Fossil and Suunto in 2004, but after them, some other devices alsomade use of SPOT, like kettles, weather stations and even map updates in Garmin devices.Microsoft wanted to create a technology for everyday devices, so they launched togetherwith SPOT the MSN Direct, which was a set of network services capable of deliveringinformation to the SPOT devices using FM radio broadcast signals.In 2008 the production of SPOT watches was discontinued, and in 2009 Microsoft releasedthe source code of Micro Framework under Apache 2.0 license, making availably to thecommunity, and shortly after this release the MSN Direct services where ceased.

Figure 2.1: SPOT watch

2.2.1 Devices using Micro Framework

Since Microsoft released the Micro Framework source code, companies had created dif-ferent devices supporting .NET code and this stack.There are two major vendors producing chips and development kits for this software. Se-cret Labs produces the netduino family, which consists of the standard netduino, a netduinoplus which is an enriched version. This one has better processor and memory, it includesan ethernet port and uses micro sd cards to provide storage. One of the interesting thingsof this two boards is that the layout is compatible with the arduino shields. Secret Labs hasanother board called netduino go, which is similar to netduino plus but without storage andethernet, and it does not use the typical arduino layout, so a globus module is requiredto use arduino shields. They also have another board called netduino mini whose size issimilar to a rubber.GHI Electronics is another hardware manufacturer that has designed and released dif-ferent boards implementing Micro Framework or modules for which its target platform isMicro Framework. GHI has a very wide range of products, for example FEZ Cerbuino Beeand FEZ Cerbuino NET, which are similar to the netduino plus in terms of performance.

Page 26: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

10 IOSharp: .NET Micro Framework on Linux

An interesting thing of FEZ devices over netduino is the possibility of loading native code(C/Assembly) for real-time requirements. For example HomeSense could run its Meshdriver in C and perform better than it performs using C#.

In addition to the mentioned manufacturers, Microsoft Research in Cambridge has de-fined a hardware reference platform called .NET Gadgeteer, which defines how boardsand modules must be in order to allow rapid prototyping of projects. Gadgeteer boardsand modules share the same layout and connector schemes and are open to any com-pany that wants to build products using those schematics.

Figure 2.2: Micro Framework devices. Netduino Plus on the left, Netduino Mini on thecenter and Cerbuino on the right.

2.2.2 NETMF on Linux

After doing some research about implementations of Micro Framework on other devices,or running on top of other operating systems such as Linux, it was found a project thatis currently porting NETMF to Linux, but for a very specific device called Eddy. This is acomplete port of the virtual Machine so it has the original CLR interpreter.Eddy is an ARM embedded device board that uses Linux. The port named above hasbeen made as a demonstration of writing NETMF applications using a port on top of otheroperating systems. One of the majors problems of this port is that some drivers are notworking at all, for example UART, SPI and I2C which are 3 I/O protocols and ports used inHomeSense.Although this port is for the Eddy board, it can be ported to other devices using the ap-propriate cross-toolchain. Anyway it seems that there is a lack of possibilities to run MicroFramework code in other devices or operating systems.

2.2.3 NETMF on RaspberryPi

If it is hard to find an implementation of NETMF in Linux, it will be harder to find an imple-mentation for Raspberry Pi. In other words, people in GHI forums are asking for NETMFports for the Raspberry Pi but no one exists. At time of writing this thesis, a small portwas uploaded to Codeplex http://raspberrypinetmf.codeplex.com/ and uses thebcm2835 library to implement the Micro Framework functions.

Page 27: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

State of the art 11

Leaving aside the NETMF implementations for the Raspberry Pi, a search on existing li-braries to control the features of the board was done. There are existing libraries for manylanguages including C and C++, Python, Java, Ruby and .NET. The interesting ones arethe C and .NET implementations, the first one because can be used in conjunction with.NET code via Platform Invocation Services. The second one is interesting for how hasbeen done the implementation of the bcm2835 in this language, but after analysing it, theconclusion was that there is a lack of libraries written in .NET.

2.3 Conclusions

There is not any real implementation of .NET Micro Framework for Linux. If IOSharpsucceeds on implementing a library with the same methods of the framework it will becomethe first library to execute Micro Framework programs on any standard computer that runsLinux. In other words, this library will make easier the interaction between .NET programsand the underlying hardware and I/O ports.

Page 28: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

12 IOSharp: .NET Micro Framework on Linux

Page 29: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

IOSharp 13

CHAPTER 3. IOSHARP

In this chapter it will be explained how was defined and architected, designed and imple-mented the core of IOSharp, disaggregating the different parts and explaining each one.

First of all, it will be explained the project design evaluating the two options at projectdefinition, then the implementation is explained for the different I/O ports and protocolstandards used in this project. Finally, it is explained how has been done the port mappingto work between different boards and devices.

3.1 Planning the development

At the beginning of the project, the development was focused on a tiny Linux board calledRaspberry Pi. This device was designed by Raspberry Pi Foundation in England taking inmind the kids around the world introducing them in computer science. It is an interestingboard for its features like basic I/O through GPIOs, SPI for serial peripheral communica-tion, I2C and UART interface also for transmissions between external components and thedevice itself.In addition to the interfaces mentioned above, it also has some desktop interesting featureslike USB ports which, practically can accept any device that works on Linux (for instancea Wi-Fi, Bluetooth, ZigBee or any stick for wireless transmissions, HDMI for graphics andEthernet for network communications). Apart from this I/O characteristics, it also mountsan ARMv6 (CPU) running at 700MHz on stock frequency along with 512MB of RAM, that isenough for normal desktop usage (surfing, emailing and office) and for embedded projects.

After choosing the target device, two implementation options were suitable for this projectso each one was analysed. Each one has its own benefits and problems that are going tobe explained in the following sections. Some options have been considered, as the use ofa specific library designed for the Raspberry Pi which should provide high efficiency. Ordevelop the implementation in a way that could be executed in any device running a LinuxKernel which makes the project platform independent.

3.1.1 Focused on Raspberry Pi

Initially IOSharp was started focusing on the Raspberry Pi, so a search was done in orderto find useful libraries for this project and one of the results was a native C library. Thislibrary gives control over all the features provided by the microprocessor integrated on theboard which includes a wide range of GPIO pins, different protocol communications likeSPI and UART, and other features like PWM.This method is interesting when achieving high performance on the programs is important,so using the library the CPU features are used on a low-level way by using the CPU reg-isters. This normally let the programs run faster but the programs only work on platformsusing the same CPU, or in other words, is a specific hardware implementation.

Page 30: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

14 IOSharp: .NET Micro Framework on Linux

The library written for the BCM2835 is the one that should be used in the case that a pro-gram has high performance requirements. The idea is to make calls from C# to this libraryusing a specific call methodology that will be explained on future sections on this thesis.

3.1.2 Focused on Linux

Thinking on a more wider way it could be interesting to make IOSharp available to muchmore devices or even real computers. This implies more developers using this softwarewhich can provide useful feedback that is interesting for the improvement and evolution ofthe library. Any computer running some kind of Linux Kernel should be able to use thissoftware facilitating the usage of the the hardware features.The idea is to use C# combined with C to generate cross-platform assemblies, whichmaking use of Mono, can run practically on any Linux device, but this has a little drawbackrelated with the performance. Mono is a virtual machine which executes .NET code (C#),the implementation of this VM is not as good as the .NET framework on Windows sonormally the performance of the programs running on it show some degradation.

3.1.3 Chosen implementation

Finally the chosen strategy was to use the Linux approach because it offers the appropri-ate tools like the spidev.h to manage the SPI or even the GPIO mappings through theSYSFS. To use any of this features the only requirement is that the necessary modulesmust be loaded into the Kernel. Along with the C# implementation, a C library will be writ-ten to interact with the functions provided by the Linux Kernel to control the SPI and theGPIOs. Micro Framework natively offers the required classes to configure the port map-ping according to the pins and devices of the underlying hardware. In short, IOSharp willbe able to run in any platform that uses the standard Linux Kernel such as the RaspberryPi, a Cubieboard or even a standard desktop. This also has to be provided by IOSharp tomap the Kernel devices into the specific hardware pins.

3.2 Implementation

In the following sections it will be explained how has been carried out the implementa-tion of the IOSharp library. As a summary IOSharp works as Micro Framework but ona high level basis, so it is not a complete port of the original, instead of this it uses C#to implement the same functions which are exposed by the framework. In this case, theoriginal source code has been downloaded from http://netmf.codeplex.com/. Fromthe folder \Framework\Core\Native_Hardware can be obtained the necessary files toimplement at least the GPIO and the SPI port along with the files for port mapping or evenUART. The native files make use of internal implements, so when a method which does aninternal implement, is called the virtual machine will take the call and process the functioninternally. IOSharp instead of implementing the virtual machine implements the functionsas a normal method (opening and closing the brackets and inserting the code inside the

Page 31: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

IOSharp 15

method).

The final implementation of IOSharp should look like the figure 3.1. The board uses Linuxand then Mono is used to execute the Embedded Application. The application referencesIOSharp library which it currently has 4 features. The SYSFS is used by the GPIO to con-trol the different I/O ports. The interrupt system and the SPI uses a custom library namedIOSharp-C. Finally, the UART uses the SerialPort implementation from the Mono libraries.

Linux

Mono

Embedded Application

IOSharp

SYSFS

GPIO

IOSharp‐C

Interrupts SPI UART

Figure 3.1: Representation of IOSharp

3.2.1 GPIO

GPIO acronym stands for General Purpose Input Output which are Ports on systems thatare capable of generating an output or reading an input with a certain level of voltage.Normally embedded systems work at 3.3V, but low power devices can work at 2V.

3.2.1.1 Implementation Options

In order to implement the GPIO ports in Micro Framework, it will be used the IOPorts.csfile which contains the structure for Input, Output, Tristate and Interrupt ports. The firstthree ports will be explained in this section whereas the interrupt port will have a dedicatedone.The GPIOs in Linux can be controlled in several ways. The most common and simple isto use the SYSFS, which stands for a set of directories with readable and writeable filesrepresenting the ports of the CPU. On the other hand, the Linux kernel also provides aKernel API to control the pins.The decision must be done between these two systems. In order to use any of this solu-tions the GPIO module must be loaded into the kernel. Many desktop Linux distributionshave GPIOs disabled and that’s why the kernel must be recompiled enabling this feature.In case of Linux operating systems designated for embedded devices, for example theRaspberry Pi or CubieBoard, they will have the I/O Ports enabled by default.It is interesting to point that Android is capable to use GPIO ports. Although it cannot seem

Page 32: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

16 IOSharp: .NET Micro Framework on Linux

an interesting feature nowadays, android is everywhere and can run in many devices, sothis is another reason to try to fetch this sector in future versions of IOSharp.

3.2.1.2 Using GPIO from SYSFS

Since each solution can be used in this project and both are available in any Linux, it wasdecided to use the SYSFS access because it is much easier to use and test the imple-mentation. It only requires having read/write access to a certain set of files and directoriesand by reading or writing in these ones is possible to change the port states.

As it was said before, in SYSFS the control of the GPIOs is carried by several files anddirectories located under the /sys/class/gpio directory. In this directory there are twofiles which are called export and unexport. The first one is used to enable a GPIO whilethe second one disables it. After enabling a GPIO, a new folder is created representing theenabled port. For instance, if port 2 is enabled, a folder called gpio2 will be created. Insidethis new folder there are several files. The direction file describes how the port shouldwork, if the desired function is an input port an in must be written in the file whereas outis used for an output port. After setting the port direction the next relevant file is valuewhich is used to set the port state in case of an Output Port (write 0 for a state-low or a 1for a state-high) or in case of an Input Port it will read the incoming value through the port.

3.2.1.3 Implementing in NETMF

Keeping in mind that this implementation has to be done over the existing code extractedfrom the IOPorts.cs file, it is important to design it properly. In this case, a GPIOManagerhas been created using a singleton pattern. This class will restrict the number of instan-tiations that a port can have in order to avoid problems on the hardware. The instance ofthis singleton is shared across all the code. This manager will be in charge of enabling,disabling and operating the different I/O ports. The figure 3.2 shows the UML diagram ofthe IOPorts.cs file from Micro Framework. Each class uses the GPIOManager to controlthe read/write functions and port creation.

Page 33: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

IOSharp 17

Port

NativeEventDispatcherClass

Fields

m_flagsm_glitchFilterEnablem_initialStatem_interruptModem_portIdm_resistorMode

Properties

Id

Methods

DisposePort (+ 2 overloads)ReadReservePin

Nested Types

InputPort

PortClass

Properties

GlitchFilterResistor

Methods

InputPort (+ 2 overloads)

OutputPort

PortClass

Properties

InitialState

Methods

OutputPort (+ 1 overload)Write

TristatePort

OutputPortSealed Class

Fields

activefirstTimeOutput

Properties

ActiveGlitchFilterResistor

Methods

TristatePort

Figure 3.2: UML Diagram of NETMF Port and its inheritance

As it is shown in the figure, each port type inherits from the Port object which implementsthe methods to enable or disable a port. The Read method is used to obtain the currentstate of the port e.g read an input value or even know the configured state in an outputport. Finally the ReservePin method permits to reserve a pin for a future usage.The InputPort inherits from Port and it does not have any special method apart from itsconstructor which bases to the Port class.The OutputPort which also inherits Port implements a new Write method which is usedto write a state through the port (active-high or active-low).The TristatePort inherits from OutputPort. This port can change its functional workbetween an input or an output mode.

3.2.2 Interrupts

Interrupts are required in the HomeSense program when using the SPI. Although theBCM2835 supports native interrupts via IRQ, at the time this project was developed theRaspberry Pi did not support GPIO interrupts using IRQ, so an alternate mechanism wasdesigned.

Page 34: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

18 IOSharp: .NET Micro Framework on Linux

3.2.2.1 Designing the Interrupts

The interrupt system has been written in C in order to use a function called poll, which iscommonly used by developers that want to detect GPIO interrupts using the SYSFS. Thepoll function must be configured to block until certain events occur on a file descriptorcorresponding to a GPIO port enabled on the SYSFS. This function is configured to waitand block the program execution until a POLLPRI event on the file descriptor is detected.This event will be triggered by the OS when the file has urgent data to be read. The pollfunction will detect the event and then will proceed with the following instructions to readdifferent parameters from the port (i.e. the port state). Then, in C# a delegate patternwill be used to notify to the upper layers of the program that interrupts. The developerwill configure the function which acts as the delegate by passing it to the OnInterruptproperty in the Interrupt Port.

Port

NativeEventDispatcherClass

Fields

Properties

Id

Methods

Nested Types

ResistorModeEnum

InterruptModeEnum

InterruptNoneInterruptEdgeLowInterruptEdgeHighInterruptEdgeBothInterruptEdgeLevelHighInterruptEdgeLevelLow

InputPort

PortClass

Properties

GlitchFilterResistor

Methods

InputPort (+ 2 …

InterruptPort

InputPortSealed Class

Fields

Properties

Interrupt

Methods

ClearInterruptDisableInterruptEnableInterruptInterruptPortListenInterruptions

Events

OnInterrupt

Nested Types

ThreadHelperClass

Properties

CallbackPin

Figure 3.3: UML Diagram of NETMF Interrupt Port

3.2.2.2 Platform Invocation Services

In C# it is possible to invoke external libraries which are not written in the same languageby using a mechanism called P/Invoke. In this case, the library used for the interrupts iswritten in C and it will be compiled into a shared library making it available to any program,or in this case, IOSharp. Take a look at the appendix A.1 to know more about the differentlibrary types.

P/Invokes in .NET make use of dynamic loaded libraries in order to use the containedfunctions. The implementation difficulty of a P/Invoke increases on how complex is thefunction to be called regarding its parameters. For basic type parameters such as int,

Page 35: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

IOSharp 19

long, byte it is really simple to make a P/Invoke call, but when passing object parametersthings get much more difficult because this requires doing marshalling for these objects.Marshalling is similar to serializing but maintaining some information related to the object.The marshalling is used to pass from managed to unmanaged code and sometimes it isimpossible without using intermediate structs as interchange objects.

Below the important parts of the implementation of this library are shown together withhow P/Invoke is done in C#. This first block shows the function which is used to detect theinterrupts on the GPIOs. The interesting parts are commented explaining what they do orwhat some macros mean.

Listing 3.1: IOSharp.c - Polling functionuint64_t start_polling ( i n t pin ) {

s t r u c t pollfd fdset ;i n t nfds = 1;i n t gpio_fd , timeout , rc ;char * buf [ MAX_BUF ] , c ;i n t len , count , i ;long t ;

/ / Get the F i l e Desc r ip to r f o r the GPIO Por t . See f u n c t i o n on the L i b r a r y .gpio_fd = gpio_fd_open (pin ) ;

/ / Clear any i n i t i a l pending i n t e r r u p t sioctl (gpio_fd , FIONREAD , & count ) ;f o r (i = 0; i < count ; ++i )

read (gpio_fd , & c , 1) ;

/ / F i l l f d se t which i s a s t r u c t f o r p o l l f d which i s used to descr ibe the p o l l i n g system ./ / In t h i s case the F i l e Desc r ip to r f o r the GPIO po r t i s entered , and then the POLLPRI ( Data←↩

Urgent to Read ) i s conf igured as the event type .fdset . fd = gpio_fd ;fdset . events = POLLPRI ;

read (fdset . fd , & buf , 64) ;

/ / S t a r t p o l l i n g the F i l e Desc r ip to r . POLL_TIMEOUT v a r i a b l e conta ins (−1) which stands f o r ←↩i n f i n i t e b lock ing u n t i l event .

rc = poll ( & fdset , 1 , POLL_TIMEOUT ) ;

/ / Close the GPIO Por t . See f u n c t i o n on the L i b r a r y .gpio_fd_close (gpio_fd ) ;r e t u r n t ;

}

After writing the function this must be exposed using a header file which is shown below.

Listing 3.2: IOSharp.h - Header file for the library# i f n d e f IOSHARP_H_INCLUDED# def ine IOSHARP_H_INCLUDED

/ / Def ine the p o l l i n g f u n c t i o nuint64_t start_polling ( i n t pin ) ;

# end i f

And finally this block represents P/Invoke is done in a C# program. The function is exposedusing a public static extern and then an attribute is attached which corresponds tothe DllImport which specifies the shared library to call.

Page 36: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

20 IOSharp: .NET Micro Framework on Linux

Listing 3.3: GPIOManager.cs - P/Invoke section/ / The f u n c t i o n which c a l l s the ex te rna l f u n c t i o np r i v a t e vo id Listen ( ob jec t obj ) {

ThreadHelper th = (ThreadHelper ) obj ;wh i le ( t r ue ) {

i n t pin = ( i n t ) th . Pin ;/ / Ca l l the f u n c t i o n . See down .ulong cback = GPIOManager . start_polling (pin ) ;th . Callback (4 , ( u i n t ) 0 , DateTime . Now ) ;

}}

/ / Ex te rna l f u n c t i o n represents a f u n c t i o n on an ex te rna l l i b r a r y , i n t h i s case the l i b r a r y i s ←↩the l ib IOSharp−c . so . The f u n c t i o n naming and f un c t i on s parameters are equal to the o r i g i n a l ←↩f unc t i on , but t ak ing i n t o account t h a t a ulong i n C# i s a u in t64_ t on C.

[ DllImport ( " l ib IOSharp−c . so " , CallingConvention = CallingConvention . StdCall ) ]p u b l i c s t a t i c ex tern ulong start_polling ( i n t gpio ) ;

3.2.2.3 Final implementation

The program flow is shown on Figure 3.4 which represents the steps that IOSharp doesfor the interrupts system. The Interrupt Port inherits from Input Port as Figure 3.3 shows.

InterruptPort

Enable GPIO

Set Port Type

Configure triggering

On Interrupt

Start Thread

Call IOSharp Library in C

Call the Delegate

Disable GPIO

IOSharp C Library

Open File Descriptor for GPIO

Start Polling

Close File Descriptor

Clear previous events

Wait for incoming events

Read GPIO state

P/Invoke Call

Call return

Figure 3.4: Representation of the Interrupt Port flow

The idea is to do the exact same steps the other ports do. The port enabling is done bythe Port implementation which is the base class for the Interrupt Port. Then the port typeis set to be an Interrupt Port. After doing this, the triggering must be configured. MicroFramework boards usually support four kinds of interrupts whereas Linux supports a fewless. In the table 3.1 are shown the supported ones. It is important to know that the edges

Page 37: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

IOSharp 21

are the point where the read state changes from one level to the other one. The Level isused when the state is maintained several time without changing.

Trigger Type Micro Framework Linux

InterruptNone X XInterruptEdgeLow X XInterruptEdgeHigh X XInterruptEdgeBoth X X

InterruptEdgeLevelHigh XInterruptEdgeLevelLow X

Table 3.1: Interrupt Trigger Types

Like the GPIO, the triggering is configured on the SYSFS on a file called edge locatedinside of the enabled GPIO folder. This file can be configured on three different ways.EdgeLow interrupts require the word falling be written in that file, in case of EdgeHighrising is used and finally both is for EdgeBoth.The polling thread works as an infinite loop P/Invoking to C and waiting for the return call,when this occurs the delegated function is called and this indicates that an interrupt eventoccurred.

3.2.3 SPI

The SPI is one of the important features to be implemented on IOSharp. This protocol isused in embedded systems to communicate boards and components in a Master-Slaveway. It offers a full-duplex communication channel where the master and the slave canwrite and read at the same time. Normally this protocol accepts transmission frequenciesin the range of 10 kHz to 100 MHz and in order to operate the master configures its clockusing a frequency less or equal to the maximum frequency supported by the slave whichwants to communicate.Figure 3.5 shows how a SPI bus is. A master device can have several slaves attachedto its ports. The minimal system is composed by three ports which are the bus itself,the MOSI is the channel where the Master device writes and from where Slaves read thewritten information. The MISO is the channel where the Master reads the information thatthe Slave writes. The SCLK is used to set the clock of the system between the Master andthe Slave. Finally for each Slave it must be CS in order to select the slave that must activeduring the transmission.

Page 38: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

22 IOSharp: .NET Micro Framework on Linux

MOSIMISOSCLKCS1CS2

MOSIMISOSCLKCS

MOSIMISOSCLKCS

MASTER SLAVE #1

SLAVE #2

Figure 3.5: SPI bus setup with one master and two slaves

3.2.3.1 Designing the SPI

The SPI implementation has been carried out like the Interrupt Port explained in section3.2.2. In this case, the Linux Kernel has been used by using the <linux/spi/spidev.h>library which makes the control of a SPI device very easy.SPI devices are mapped under /dev/ directory with a naming like /dev/spidevX.Y theX is an integer and represents the device (a CPU can have multiple SPI devices so thisnumber will indicate the device number), then the Y, also an integer, enumerates the CS(SPI devices have multiple chip selects, so they can have more than one slave).

Before doing a transaction via the SPI this must be configured. First of all, we start bydefining the operational mode. Modes are defined with the parameters Clock Polarity(CPOL) and Clock Phase (CPHA). Both are related to the sampling edge according tothe clock (SCLK) used in the communication. The CPOL defines the polarity of the clockso the sampling will be done when the clock is in edge low or in edge high according tothe configured parameter, CPHA defines in which phase the sample must be done. Thisconcept is much easier to understand using the figure 3.6 which shows the different CPHAand CPOL options with the equivalent SPI modes required to be configured in the C library.

MODE 0 MODE 1

MODE 3MODE 2

Sample Sample

SampleSample

CPOL = 0

CPOL = 1

CPHA = 0 CPHA = 1

Clock Phase (CPHA)

Clock Po

larity (CPO

L)

Figure 3.6: SPI modes are defined with the parameters "CPOL" and "CPHA" to the datasampling acording to the System Clock (SCLK) state.

Page 39: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

IOSharp 23

These modes must be configured using the ioctl function passing the file descriptor of theSPI device and the desired CS. Then the preprocessor macro SPI_IOC_WR_MODE is usedto specify which parameter will be configured. In this case, it is the SPI mode that hasbeen explained before. The last parameter corresponds to another macro which definesthe operational mode. The figure 3.6 shows each mode and the macro that must bepassed to the ioctl function, this modes are SPI_MODE_0, SPI_MODE_1, SPI_MODE_2 andSPI_MODE_3.

Listing 3.4: IOSharp.c - SPI Mode configurationuint8_t mode ;

i n t ret ;

/ / The mode v a r i a b l e can be SPI_MODE_0, SPI_MODE_1, SPI_MODE_2 and SPI_MODE_3ret = ioctl (fd , SPI_IOC_WR_MODE , &mode ) ;i f (ret == −1)pabort ( " can ' t se t sp i mode" ) ;

Once the SPI mode has been configured, a struct defining the transaction must be filled.The struct type of is spi_ioc_transfer specified in the spidev.h library. This structcontains different variables. The tx_buf and rx_buf are configured with the write andread buffers. Apart from the buffers, the transmission length is configured using the vari-able len. Then the delay is configured, using the delay_usecs variable. This indicateshow many microseconds the SPI driver must wait before starting the transmission. This isimportant because some slaves take some time from when they are selected until they areable to communicate. Another parameter to configure is the clock by using speed_hz. Inorder to deselect a device before a transfer, the parameter cs_change must be true. Fi-nally, to configure or override the wordsize of a transmission the bits_per_word is used.

Listing 3.5: IOSharp.c - SPI struct configurations t r u c t spi_ioc_transfer tr = {

. tx_buf = ( unsigned long )writeBuffer ,

. rx_buf = ( unsigned long )readBuffer ,

. len = writeCount ,

. delay_usecs = spi . delay ,

. speed_hz = spi . speed ,

. cs_change = spi . cs_change ,

. bits_per_word = 8 ,} ;

Once the struct is configured, another ioctl call is done which makes the transfer itself. Inthis case, along with the File Descriptor corresponding to the SPI device, another prepro-cessor macro is passed as a parameter. This one is called SPI_IOC_MESSAGE and mustinclude the number of transfers that will be executed together. In case of IOSharp thereis only one transfer per call, so the parameter will look like SPI_IOC_MESSAGE(1). Finallythe struct commented above is included in the ioctl call.

Listing 3.6: IOSharp.c - SPI transfer/ / Pass the preprocessor macro and the s p i _ i o c _ t r a n s f e r s t r u c t .ioctl (fd , SPI_IOC_MESSAGE ( 1 ) , &tr ) ;

Page 40: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

24 IOSharp: .NET Micro Framework on Linux

3.2.3.2 Implementation in C#

After writing the library part in C it is time to modify IOSharp to add the necessary callsto this library. In this case, the calls will be done in a similar way as it has been done inthe interrupts (3.2.2). However, some data will need to be serialized in order to pass theconfiguration of the SPI from C# to C.Essentially the method will be doing a P/Invoke from C# in order to call the functions inthe C library. To facilitate the data exchange between the program and the library a structis used. This contains the basic information in order to do the configuration explained onthe previous section. This struct must be written in the header file of the library and alsomust be written in the C# code. The SPI implementation, in Micro Framework, is dividedinto two blocks. The first one represents the port configuration which is used to set thedifferent properties that can be used with the SPI (for example the clock rate, the setuptime of the slave, the SPI modes (CPHA and CPOL), etc). The second block, which is theSPI itself uses the configuration commented above to create an SPI instance, along withthe required pins for the MISO, MOSI, SCLK and CS.When the SPI instance is created, its methods will be able to be used. Basically, there aredifferent overloads of the Write and the WriteRead methods, but all of them end callingthe same internal function which will do the P/Invoke to the C library.

ConfigurationClass

Fields

BusyPinBusyPin_ActiveStateChipSelect_ActiveStateChipSelect_HoldTimeChipSelect_PortChipSelect_SetupTimeClock_EdgeClock_IdleStateClock_RateKHzSPI_mod

Methods

Configuration (+ 1 overload)

SPISealed Class

Fields

m_configm_csm_disposed

Properties

Config

Methods

~SPIDispose (+ 1 overload)InternalWriteReadByteInternalWriteReadShortSPIWrite (+ 1 overload)WriteRead (+ 5 overloads)

Figure 3.7: UML representation of the SPI Configuration Class (Left) and the SPI Port(Right)

In order to pass the configuration to the library, the configuration object is converted to astruct which its variables are the same as the struct from the header file of the library.The code shown below corresponds to the header file and represents the struct that willbe interchanged between the two languages.

Listing 3.7: IOSharp.h - spi_config structtypedef s t r u c t spi_config{

i n t mode ;uint32_t speed ;i n t cs_change ;

Page 41: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

IOSharp 25

uint16_t delay ;} SPI_CONFIG ;

The listing below represents the C# implementation of the C struct used for the pin config-uration. It contains the same parameters as the C version and also implements a construc-tor which simplifies the conversion between the Configuration class and this structure. It isimportant to note the attribute located over the method[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]. This at-tribute is used by the P/Invoke to know how the marshalling must be done when is passedto the C library.

Listing 3.8: SPI.cs - spi_config struct[ StructLayout (LayoutKind . Sequential , CharSet = CharSet . Unicode ) ]p u b l i c s t r u c t spi_config {

p u b l i c i n t mode ;p u b l i c u i n t speed ;p u b l i c i n t cs_change ;p u b l i c ushor t delay ;

p u b l i c spi_config (Configuration config ) {t h i s . cs_change = (config . ChipSelect_ActiveState ) ? 1 : 0 ;t h i s . delay = ( ushor t ) config . ChipSelect_HoldTime ;

i f (config . Clock_Edge && ! config . Clock_IdleState )t h i s . mode = 0;

e lse i f ( ! config . Clock_Edge && ! config . Clock_IdleState )t h i s . mode = 1;

e lse i f (config . Clock_Edge && config . Clock_IdleState )t h i s . mode = 2;

e lset h i s . mode = 3;

t h i s . speed = config . Clock_RateKHz * 1000;}

}

It is interesting to remark that the TX/RX buffers are not returned from C to C# , instead,their pointers are sent from C# to C, so the same memory is reused in both environments.

3.2.4 UART

UART is a really simple protocol that uses an asynchronous serial communication betweentwo devices. As figure 3.8 shows, each device have two ports which are the TX for trans-missions and RX for receptions. The transmission port must be connected to the receptionport on the other device. Both devices must share the ground.

TXRX

GND   Device 1

TXRXGND       Device 2

Figure 3.8: UART communication schema

Page 42: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

26 IOSharp: .NET Micro Framework on Linux

Unlike the above features which were not implemented on the standard .NET Framework,the UART (SerialPort) exists on that implementation with exactly the same name and in thenamespace. This is problematic in case of a class reimplementation is needed because itis impossible to maintain the original namespace (System.IO.Ports).First of all and trying to avoid a new implementation of a SerialPort, the classes fromthe Micro Framework and the .NET Framework were compared. After doing this, it wasrealised that the two classes were so similar that IOSharp did not require a new reimple-mentation. The are two reasons to avoid this reimplementation, the first one is that anyreuse of code is better rather than writing again the same feature, because .NET Frame-work is much more stable and tested than a code written from scratch. The other reasonis that, although the .NET Framework class is not exactly as the Micro Framework class, ithas all the required methods that are needed for HomeSense.

SerialPort

ComponentClass

Fields

Properties

Methods

CloseDiscardInBufferDiscardOutBufferDisposeGetPortNamesOpenRead (+ 1 overload)ReadByteReadCharReadExistingReadLineReadToSerialPort (+ 6 overloads)Write (+ 2 overloads)WriteLine

Events

DataReceivedErrorReceivedPinChanged

SerialPort

StreamClass

Fields

Properties

Methods

BytesInBufferCloseDataEventHandlerDiscardBufferDiscardInBufferDiscardOutBufferDisposeErrorEventHandlerFlushHandlePinReservationsInternalCloseInternalDisposeInternalOpenOpenReadSeekSerialPort (+ 4 overloads)SetLengthWrite

Events

DataReceivedErrorReceived

Nested Types

ConfigurationClass

.NET Implementation Micro Framework

Figure 3.9: UML SerialPort representation of the original .NET Framework (Left) and.NET Micro Framework (Right)

It is important to remark that IOSharp, in Linux, runs on the Mono implementation of .NETFramework classes, and in this case the SerialPort class has some disadvantages on theMono version, basically, it does not support the DataReceived or ErrorReceived eventsbecause that functions are not implemented on that virtual machine. But it is not a realproblem because HomeSense does not use that events.

Page 43: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

IOSharp 27

3.3 Port Mapping

Although IOSharp is a cross-platform library some features require a specific configurationwhen deploying on different boards. Every board has its own port mapping and naming,so it is necessary to have a specific library to describe that board. This is similar to theHAL and PAL concept:

• HAL: Hardware Abstraction Layer. In this case Linux acts as a HAL which offerssimple APIs to use features likes the kernel driven SPI device or the GPIO exposedin the SYSFS.

• PAL: Platform Abstraction Layer. It is the library that must be implemented in orderto exploit the HAL functionalities. In this case, the Raspberry Pi requires a library tomap the GPIO pins or the SPI devices to the appropriate names for the HAL.

3.3.1 HardwareProvider

In fact, the original Micro Framework supports a hardware descriptor which represents thePAL of the specific boards and is called HardwareProvider. Raspberry Pi is the targetplatform for this project so a hardware descriptor was written. Below are represented thepins of the Raspberry Pi, on the left the revision 1.0 and on the right the revision 2.0. Inthe image are also shown where are the different pins used for the SPI and the I2C.

Figure 3.10: Raspberry Pi pin mapping

Page 44: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

28 IOSharp: .NET Micro Framework on Linux

The mapping is divided into two different classes, the first one gives the Pin names thatmust be used on Linux to control the I/O ports. The second one, is related to the requiredpins to use a specific protocol. For example, it configures the pins for the SPI or theUART. In Linux the SPI and UART are known as devices so they are located under /dev/directory.

Page 45: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Functional Tests 29

CHAPTER 4. FUNCTIONAL TESTS

Simultaneously with the development of IOSharp some small tests were created so thedeveloped features could be tested to verify the properly operation of the implementation.Two functional test had been carried out in order to test the correct functioning of the library.The first one uses a Micro Framework project which consists of a RFID card reader. Thesecond one is mainly the deployment of HomeSense.

4.1 SPI. RFID and IOSharp

This was the first test to verify the SPI in a real environment using a RFID card reader con-nected through the SPI bus. This test derives from a proof of concept made for VR gymin Argentona under the Spanish project "Activat" from "Proyecto Impacto". This projectrequested to develop a method to authenticate and authorize users for a secure entranceon a complex by using a RFID card reader and different cards, tags and wristbands withan ID which can be associated with a certain user.The project was developed using a Netduino Plus which uses Micro Framework. The cardreader used in this test mounts a MFRC522 chip from NXP which can use different com-munication protocols like SPI, UART and I2C. But that chip is mounted on a MF522-ANboard from Mifare which only offers a SPI interface.An API was written in order to communicate the Netduino with the card reader, so theMFRC522 datasheet was used (see on Appendix A the section A.3.1). The program cre-ates an instance of this API and then starts the SPI configuration. Following this configu-ration a Timer is instantiated which triggers a function at the scheduled cycle. The calledfunction uses the API to communicate with the card reader so it can retrieve the card IDand then, with another tranmission, obtain the Serial Number located in the card. Finally itprints this data in the console.

4.1.1 Micro Framework version

The original example uses Micro Framework and the Secretlab classes for the NetduinoPlus so the resulting binary will only work on this board. The port configuration for thisexample is really simple, because it only uses a pin for the CS. The MOSI, MISO and SCLKare defined by the board schema so the pins will be selected and configured internally onthe virtual machine.

Listing 4.1: SPIApi.cs - Configuring SPI for the MFRC522 in Netduino Plusp u b l i c vo id ConfigureSPI ( ) {

SPI . Configuration xSPIConfig ;Cpu . Pin pin = Pins . GPIO_PIN_D9 ;

xSPIConfig = new SPI . Configuration (pin , / / Chip Selec t p infa l se , / / Chip Selec t Ac t i ve State50 , / / Chip Selec t Setup Time0 , / / Chip Selec t Hold Time

Page 46: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

30 IOSharp: .NET Micro Framework on Linux

f a l se , / / Clock I d l e Statet rue , / / Clock Edge1000 , / / Clock Rate ( kHz )SPI . SPI_module . SPI1 ) ; / / SPI Module

spiDevice = new SPI (xSPIConfig ) ;}

As it is shown above, the CS pin is the Pins.GPIO_PIN_D9 which corresponds to a digitalpin.

4.1.2 Migrating to Linux

To use IOSharp instead of Micro Framework there is not a big requirement, basically theproject must be converted to .NET Framework and then reference the IOSharp library.Beside this, the mapping classes according to the deployment platform must also be refer-enced. The next step is change the pin for the CS to the according one. Normally in Linuxeach SPI device have one or more CS pins but not every pin is suitable to work with thatSPI device, so it is important to check the appropriate pin.Taking in mind that using this test can also prove that IOSharp can work with the originalcode by doing a minimal set of changes, it was tried to use one of the features that theVisual Studio projects offers. Declaring two solution files (*.sln) which each one callstwo different project files (*.csproj) make possible to have one solution with the MicroFramework classes for the Netduino while the other one contains the references for theIOSharp and the .NET Framework. This will create two different projects from the samecode, one being able to run on Netduino and the other one in Linux.These were the major changes, and they cannot be considered real changes to the originalcode, because is possible to take the application program and create a new .NET Frame-work project with that code. This changes proves that is possible to maintain the samecode for different platform deployments.Using conditional compiling is possible to set the required pin for each board and eachsolution. In this case, the symbol used for the conditional compiling is MF which is presenton the Netduino version of the *.csproj whereas not in the Raspberry Pi. Taking a lookinto the above code, the Netduino uses Pins.GPIO_PIN_D9 whereas the Raspberry Piuses Cpu.Pin.GPIO_Pin9.

Listing 4.2: SPIApi.cs - Conditional compiling symbol for NETMF and IOSharpp u b l i c vo id ConfigureSPI ( ) {

SPI . Configuration xSPIConfig ;Cpu . Pin pin = Cpu . Pin . GPIO_NONE ;/ / In t h i s case , the c o n d i t i o n a l compi l ing symbol used i s MF, t r ue f o r Micro Framework or ←↩

f a l s e f o r IOSharp# i f MF

pin = Pins . GPIO_PIN_D9 ;#e lse

pin = Cpu . Pin . GPIO_Pin9 ;# end i f

xSPIConfig = new SPI . Configuration (pin , / / Chip Selec t p infa l se , / / Chip Selec t Ac t i ve State50 , / / Chip Selec t Setup Time0 , / / Chip Selec t Hold Timefa lse , / / Clock I d l e Statet rue , / / Clock Edge

Page 47: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Functional Tests 31

1000 , / / Clock Rate ( kHz )SPI . SPI_module . SPI1 ) ; / / SPI Module

spiDevice = new SPI (xSPIConfig ) ;/ / MFRC522Init ( ) ;

}

After doing this, this project can be opened as Micro Framework in order to deploy in aNetduino or open the Linux version. Deploying this application in any of these boards willresult in a working program like the figure 4.1 shows.

Figure 4.1: Data exchange using the SPI

4.2 HomeSense

HomeSense is a Wireless Healthcare Sensor Platform designed by AlterAid. The currentimplementation uses a Netduino Mini board which is the gateway. This board controlsthe sensor network, receiving all the data and uploading it to internet. Some sensorsare spread around the house which are used to fetch data. With all of those sensors,it is possible to acquire information from the environment and then send that informationto internet using the gateway. These sensors are programmed using C and all of themuse the SoC nRF24LE1 which mounts a low-power RF ISM band (2.4 GHz) from NordicSemiconductor.

Figure 4.2: Sensor for a medicine cabinet

Page 48: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

32 IOSharp: .NET Micro Framework on Linux

The communication protocol designed for HomeSense is similar to a star network withmulti-hop transmissions so it becomes a tree-start topology. The nodes try to fetch thegateway because this is on charge of upload the information to the internet.

4.2.1 Gateway

The program running on the gateway is coded using Micro Framework and is deployedon a Netduino Mini. Using IOSharp has been possible to deploy it on a Raspberry Pirunning Linux and Mono. The software running on the gateway controls the communicationhardware and also the mesh network using the designed protocol for this platform.As it uses all the features developed for the library it is a good functional test to try thewhole system.

• UART: the Serial Port is used to transmit data between the Wifly and the RaspberryPi. The Wifly is an XBee socket type module created by Roving Networks, and isused to connect to Wi-Fi networks. The communication between this module andthe board where is connected is carried out using UART with a protocol describedon the specification paper provided by the manufacturers.

• SPI: The Nordic nRF24L01+ is controlled using the SPI protocol. This chip is usedto create the physical meshed network which connects with the different nodes. Thechannel created using the Nordic is half-duplex so there is only one communicationat a time either transmission or reception.

• Interrupts: When the gateway’s Nordic receives information form other nodes itmust alert that new data is waiting to be read, to make this alert an interruption isused on a GPIO

Figure 4.3 summarizes the connections and devices used with the Raspberry Pi andHomeSense. On the left is shown the Nordic which uses the SPI protocol and it sendinterrupts to the Raspberry Pi. On the right, the Wifly uses the UART protocol to exchangedata.

Raspberry PiNordic(Mesh)

Wifly(WiFi)

UARTSPI

Interrupt

Figure 4.3: Diagram showing the protocols and devices used in HomeSense

With all of these devices attached to the shield used in the Raspberry Pi it will be possible totest all the functions working at the same time and how the system response is comparedto the original one.

Page 49: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Functional Tests 33

Figure 4.4: Raspberry Pi with the modules needed to run HomeSense

4.2.2 Deploying on Raspberry Pi

As IOSharp has implemented all the features required in HomeSense, it is possible tochange the project type from Micro Framework to .NET Framework and then referencethis library. Finally, the ports need to be remapped according to the shield used with theRaspberry Pi. The strategy to do this mapping is include the Hardware class of the Rasp-berry Pi and then rename the ports to the according ones. SerialPort device also must berenamed from COM1 to /dev/ttyAMA0. After changing the references and the port namesis possible to start testing the program. So it has been really easy to migrate from theNetduino Mini board to the Raspberry Pi.

HomeSense has a program which shows the network status, showing its gateway andthe different sensors connected to the network. On the following figure a connection isshown. The aaaida logo represents the gateway whereas the node is represented by adoor. In this case, both are linked as an arrow connects both of them. With this program ispossible to know the network addresses of both devices. Also it shows other informationlike battery state or the fetched information by any sensor located on a node.

Page 50: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

34 IOSharp: .NET Micro Framework on Linux

Figure 4.5: HomeSense dashboard. The aaaida logo on the left represents theRaspberry Pi (gateway) whereas the door represents a sensor

4.3 Conclusions

All the functional tests show that IOSharp has been successfully done. Each test works onthe Raspberry Pi with doing only minor changes on the code. With IOSharp working andbeing able to be used on existing Micro Framework projects it is possible to make them runon other platforms, so the development milestone has been done. But, after testing thedifferent parts of IOSharp and deploying HomeSense on the Raspberry Pi it was seen thatthe performance was not as good as it was expected. Raspberry Pi, need more time tosend the network events than the Netduino and this is probably related to the time neededto attend the interrupts on Mono. In this case the IOSharp with Mono needs two transmis-sions to send the same information that is sent with only one transmission in the Netduino.To try to solve these issues with the performance of the library, IOSharp will be trans-lated to C++ using a translating tool called AlterNative which is capable of translate .NETassemblies to C++ while maintaining a similar C# syntax.

Page 51: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

AlterNative 35

CHAPTER 5. ALTERNATIVE

This chapter is a walk-through AlterNative explaining its concept, how it can translate thecode, then an example using IOSharp with some use cases that can be applied to thistool.

5.1 Concept

The concept of AlterNative is to maximize the idea of Internet of Things by providing a toolto port applications from high-level languages (such as .NET) to native languages (suchas C++) easily. Most of the actual systems are C++ compatible, thus if the application isported to this language, it can be executed in several platforms (i.e. smartphones, tablets,embedded systems, computers with different operating systems).With this tool a developer can take the advantages of fast developing in a high-level lan-guages such as C# and then gain the advantage of performance related the low-levellanguages like C++. Apart from this, it also gives the chance to get native code capable ofworking in several systems, in other words, this philosophy is similar to the WORA (WriteOnce, Run Anywhere) slogan created by Sun Microsystems to illustrate the cross-platformbenefits of Java Virtual Machine. The difference is that AlterNative is focused on the finalperformance because it outputs the code in native language avoiding the dependence ofunderlying virtual machines.

5.2 Process

AlterNative process is divided in three steps: decompilation, translation and recompilation.To summarize the following sections the figure 5.1 shows the process that is done from theoriginal assembly, the decompilation, translation and finally the recompilation to an anotherassembly.

Figure 5.1: AlterNative process

To explain the AlterNative process will be used the Main method which both languagesmake use of it. In the following table is shown how this method looks like in each language.

Page 52: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

36 IOSharp: .NET Micro Framework on Linux

Language Method AST

C# void Main(string[] args){} Figure 5.2C++ void Main(string args[]){} Figure 5.3

Table 5.1: Representation in C# and C++ of the Main method of a program

5.2.1 Decompilation

First of all the assembly is passed through a decompiler in order to extract the source code.In this case, the original code is in C# and to decompile it is used a program called ILSpy(an open-source .NET assembly decompiler). Instead of extracting the code in text formatis extracted as an AST (Abstract Syntax Tree) that is an abstract representation with nodesand hierarchies of the original code. This representation is organized in a tree format fromthe top-level (assembly) until the low-level (instructions, types and constants).

The figure 5.2 shows how void Main(string[] args){} method would look like in ASTformat. The top node designates that the child nodes correspond to a method, then in thefirst row child is described the primitive type (what method returns) which in this case is avoid, the identifier which shows the method name (Main) and finally the parameter dec-laration which describes the parameters that the function takes. The example method hasone parameter corresponding to an array of strings. The parameter declaration node hastwo nodes defining it, the first one describes that string[] is a composed type which isalso defined by a string and an array specifier, the second node is the identifier name ofthe parameter, in this case, args.

MethodDeclaration

PrimitiveType: void Identifier: Main ParameterDeclaration

ComposedType Identifier: args

ArraySpecifierPrimitiveType: string

Figure 5.2: AST representation of the main method in C#

The translator will generate the C++ code from the AST representation of the original code.

5.2.2 Translation

To proceed with the translation, it is important to know how is the translated languagetyped, then in order to achieve that, some modifications need to be applied to the gener-ated AST in the decompilation step. After doing the pertinent AST modifications a second

Page 53: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

AlterNative 37

one will be obtained representing the source code of the desired language. After doing thisconversions, the following step is start writing the files containing the text representationof the tree. AlterNative translates the code to C++ so the AST changes must be done ina way that the resulting AST corresponds to that language. It is important to remark thatC++ is language that provides source and headers, so both need to be written to files.

Following the example explained in the previous section, now the AST will be trans-formed to an equivalent AST but for C++ language. In C# the choosen method lookslike void Main(string[] args){} but in C++ the syntax is different because the ar-ray specifier moves from the primitive type to the identifier. The figure 5.3 shows inred the changes done to the original tree in order to achieve an AST that looks likevoid Main(string args[]){} (C++ method). The original identifier changes to a com-posed identifier with two child nodes, the first one is the identifier args and the secondone is the array specifier which has been moved from the original composed type to thecomposed identifier in this case. As there is no composed type now the node is deletedand the parameter declaration is directly linked to the primitive type string.

MethodDeclaration

PrimitiveType: void Identifier: Main ParameterDeclaration

ComposedIdentifier

PrimitiveType: string ArraySpecifierIdentifier: args

Figure 5.3: AST representation of the main method in C++

5.2.3 Recompilation

The final step consists on compile the C++ code into a new assembly. This final assemblymaintains the same functionalities of the first one but taking the benefits of the performancethat gives native code. Although it could seem that this software is focused on the codetranslation it is not its real finality because its aim is to maintain all the features of theoriginal code like the garbage collector, specific expressions or even language syntax.Maintaining this characteristic on mind the programs translated using AlterNative will runmuch faster than the original because a virtual machine is not required to execute nativecode.As mentioned, AlterNative is able to provide most of the features of the original code to thefinal code using external open-source libraries like the boehm GC for the garbage collector,the boost library for implementing characteristics like threading and delegation and finallya proprietary library which implements all the System namespace of C#. With all of thisthe final assembly is fully compatible with any system like Windows, Linux, Android or anydevice capable of execute C++ assemblies.

Page 54: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

38 IOSharp: .NET Micro Framework on Linux

5.3 Use Cases

There are two clearly use cases of AlterNative together with IOSharp, the first one isperformance and the second one is cross-platform for embedded systems.

5.3.1 Performance

AlterNative gets the major advantage when it is applied to programs or libraries whichare very complex in a computational way (for example image processing, mathematics orcomplex algorithms) where languages running on virtual machines are not as fast as thedeveloper needs. The more complex the target is, the more benefit that can be obtained.Taking into account that the performance seen on IOSharp running on Mono is not asgood as it should be compared to the native Micro Framework running on a Netduino. Itis supposed that passing a program created with IOSharp through the translator a fasterbinary will be generated (the virtual machine is not longer needed). It is known that Monoimplementation is not as fast as .NET Framework (Windows).

5.3.2 Cross-Platform in embedded systems

Other advantage of the standard low level languages like C++ is that a high percentageof device processors can execute this code. And at this point is where it fits with theimplementation of IOSharp because translating the library with AlterNative a new one willbe obtained but instead of being written in C# it will be in C++. By doing this, the generatedsource can be compiled into a assembly, the unique requirement to execute the resultingcode is a Linux running on the deployment machine. The developer will get all the benefitsof Micro Framework with the speed of C++. The code will be written using the MicroFramework syntax which makes easy the development of embedded applications, andthen they could use AlterNative to gain performance or achieve more platforms.

5.4 Contributions to AlterNative

To achieve the translation (or partial translation) of IOSharp through AlterNative, somework was done on the proprietary implementation of System libraries which are the C++libraries that externally look like the C# ones but the methods are implemented using stan-dard C++ functions or third party libraries like boost or Boehm GC.

At the beginning, AlterNative only worked on Windows because some classes from theILSpy had mixed the view and the decompiler functions, so it was unable to run in Linux orMacOSX because of the non-compilable parts. In order to solve that, an AlterNative.Corewas created which could work in any system able to run C# programs. This core versionhas its own solution and csproj file but they are pointed to the same code files of the origi-nal program. In this way, AlterNative can run either on .NET Framework in Windows or on

Page 55: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

AlterNative 39

Mono in Linux and MacOSX.

The first attempt to translate IOSharp was unsuccessful, but it helped to determine hownear the translation was at being successful. There where several major features that Al-terNative was not able to translate like the threading, the delegates used in the interrupts,the P/Invokes or some functions like DateTime, Timer and file reading/writing. Many ofthose features where required to be implemented on the proprietary library because thisis the one that is linked to the translated program.

To implement this features, the C++ boost library has been used. This uses standardC++ functions so it can work practically in any device or operating system. The classescurrently implemented either totally or partially are shown in the Appendix A.4. Wheremarked in red are the libraries that where contributed to the AlterNative in order to trans-late IOSharp. Essentially the written ones are:

• DateTime: used for storing the time stamp of the interrupt.

• TimeSpan: to be used on the Timer.

• File: used to write or read values in the SYSFS in order to control the GPIO.

• Encoding: used to properly encode strings to UTF-8.

In the figure 5.4 is shown the differences between the original Micro Framework, the orig-inal IOSharp and the translated one. Each one includes some new layers on the stack,either to implement the functionalities of the Micro Framework as IOSharp layer does. Orto replace Mono as AlterNative System library does. The first one shows the original im-plementation which runs on the bare metal of the board as it has been explained on thestate of the art. The second column represents the IOSharp original implementation, inthis case, the underlying hardware has an operating system (Linux) and then it uses a vir-tual machine (Mono) to run the program that makes use of IOSharp. Finally, the translatedversion swaps Mono to AlterNative System classes and it also contains the C++ translationof IOSharp and the program, but it maintains the original IOSharp-C library.

IOSharpProgram

IOSharp‐C

IOSharp

Linux

Hardware

Mono

AlterNativeProgram

IOSharp‐C

IOSharp‐C++

Linux

Hardware

AlterNative

NETMFProgram

.NET Micro Framework

Hardware

Figure 5.4: Stack in the original .NET Micro Framework, the IOSharp implementation andthe AlterNative translation

Page 56: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

40 IOSharp: .NET Micro Framework on Linux

5.5 Example

The best example to show in this section will be some part of IOSharp translated to C++. Inthe moment of writing this thesis the only component being 100% translated automaticallywas the GPIO ports, which basically they make use of SYSFS and the interrupt port whichuses cross-language calls.

As a short example of this translation, the following pieces of code represents the InputPortin two different languages. This first one is the original implementation of IOSharp as it canbe downloaded from GitHub while the second one is the translated representation.

Listing 5.1: InputPort in C#using System ;using System . Collections . Generic ;using System . Linq ;using System . Text ;using Microsoft . SPOT . Hardware ;using IOSharp . NETMF . RaspberryPi . Hardware ;using System . Threading ;

namespace raspberrypi{

p u b l i c c lass InputPort : Port{

/ / As i t has been expla ined i n the IOSharp seccion , a l l the GPIO have an i n h e r i t a n c e wi th ←↩the Por t c lass , so a l l o f them base to Por t .

p u b l i c InputPort (Cpu . Pin portId , bool glitchFilter , ResistorMode resistor ): base (portId , glitchFilter , resistor , InterruptMode . InterruptNone )

{/ / In t h i s case , using the GPIOManager i s conf igured the po r t as an Inpu tPo r tGPIOManager . Instance . SetPortType (portId , PortType . INPUT ) ;

}

p ro tec ted InputPort (Cpu . Pin portId , bool glitchFilter , ResistorMode resistor , ←↩InterruptMode interruptMode ): base (portId , glitchFilter , resistor , interruptMode )

{GPIOManager . Instance . SetPortType (portId , PortType . INPUT ) ;

}

p ro tec ted InputPort (Cpu . Pin portId , bool initialState , bool glitchFilter , ResistorMode ←↩resistor ): base (portId , initialState , glitchFilter , resistor )

{GPIOManager . Instance . SetPortType (portId , PortType . INPUT ) ;

}

p u b l i c ResistorMode Resistor { get ; set ; }

p u b l i c bool GlitchFilter { get ; set ; }

}}

After translating the project the code is represented in C++ which uses header files, so thefollowing code represents the header for the InputPort.

Listing 5.2: Header file for the InterruptPort in C++#pragma once

Page 57: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

AlterNative 41

# inc lude " System / System . h "# inc lude " Por t . h "# inc lude "Cpu . h "# inc lude "GPIOManager . h "# inc lude " PortType . h "# inc lude " System / Except ion / SystemException / NotImplementedException . h "

using namespace Microsoft : : SPOT : : Manager ;using namespace System ;namespace Microsoft {

namespace SPOT {namespace Hardware {

c lass InputPort : p u b l i c v i r t u a l Port , p u b l i c v i r t u a l Object{

p u b l i c :Port : : ResistorMode getResistor ( ) ;

p u b l i c :vo id setResistor (Port : : ResistorMode value ) ;

p u b l i c :bool getGlitchFilter ( ) ;

p u b l i c :vo id setGlitchFilter ( bool value ) ;

p u b l i c :InputPort (Cpu : : Pin portId , bool glitchFilter , Port : : ResistorMode resistor ) ;

p ro tec ted :InputPort (Cpu : : Pin portId , bool glitchFilter , Port : : ResistorMode resistor , Port : :←↩

InterruptMode interruptMode ) ;p ro tec ted :InputPort (Cpu : : Pin portId , bool initialState , bool glitchFilter , Port : : ResistorMode ←↩

resistor ) ;

/ / The C# p r o p e r t i e s i n C++ are a u t o m a t i c a l l y converted to v a r i a b l e sp u b l i c :Port : : ResistorMode Resistor_var ;

p u b l i c :bool GlitchFilter_var ;

} ;}

}}

Finally this is the file containing the implementation of the header.

Listing 5.3: Implementation of the InterruptPort in C++# inc lude " Inpu tPo r t . h "namespace Microsoft {

namespace SPOT {namespace Hardware {

/ / So the converted v a r i a b l es need to be accessed using g e t t e r s and s e t t e r s . L ike i s shown←↩below

Port : : ResistorMode InputPort : : getResistor ( ) {r e t u r n Resistor_var ;

}vo id InputPort : : setResistor (Port : : ResistorMode value ){Resistor_var = value ;

}bool InputPort : : getGlitchFilter ( ){

r e t u r n GlitchFilter_var ;}vo id InputPort : : setGlitchFilter ( bool value ){GlitchFilter_var = value ;

}InputPort : : InputPort (Cpu : : Pin portId , bool glitchFilter , Port : : ResistorMode resistor ) : ←↩

Port (portId , glitchFilter , resistor , Port : : InterruptMode : : InterruptNone ){

Page 58: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

42 IOSharp: .NET Micro Framework on Linux

GlitchFilter_var = ( bool ) ( 0 ) ;Resistor_var = (Port : : ResistorMode ) ( 0 ) ;GPIOManager : : getInstance ( )−>SetPortType (portId , PortType : : INPUT ) ;

}InputPort : : InputPort (Cpu : : Pin portId , bool glitchFilter , Port : : ResistorMode resistor , Port←↩

: : InterruptMode interruptMode ) : Port (portId , glitchFilter , resistor , interruptMode ){GPIOManager : : getInstance ( )−>SetPortType (portId , PortType : : INPUT ) ;

}InputPort : : InputPort (Cpu : : Pin portId , bool initialState , bool glitchFilter , Port : :←↩

ResistorMode resistor ) : Port (portId , initialState , glitchFilter , resistor ){

throw new NotImplementedException ( ) ;}

}}

}

Some performance tests had been carried out to quantify how much faster is the translationcompared with the original one running on Mono. The explanation of the tests and itsresults are on the next chapter.

Page 59: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Performance tests 43

CHAPTER 6. PERFORMANCE TESTS

In this chapter are shown the performance results for two tests carried out on a RaspberryPi using the original implementation of IOSharp, and the C++ version, which is a directtranslation using AlterNative.Theoretically, C++ has a major performance compared to C# but this tests will be used todetermine how much gains C++ over C#.The Logic16 has been used to make the timing measurements. This is a channel analyserused to record, view, and measure digital signals.

6.1 Compilation types

When a compiler generates a binary from a source code normally tries to do some changesto optimize some attributes of the program. The most common requirement is to optimizethe time taken to execute that program, another one is optimize the amount of memory re-quired by the program. Also, some optimizations can be used to make a program consumeless power and this is interesting because nowadays the Internet of Things is growing andmany sensors have a small battery so reaching low-power consumption is great becauseit ensures a longest battery life or at least the sensor can operate more time. All of thisoptimizations are carried out by a sequence of optimizing transformations and algorithmswhich are applied by optimizing compilers.Normally compilers can generate programs optimized or non-optimized, depending on howis configured the build system. If the compiler uses optimizations the compile time will growbut the program will be much more optimized than if optimizations are not applied.

• Non-optimized or debug: this mode is used by developers who want to debugapplications in execution time. In this case the whole symbol information, whichis used by the debugger to stop at the break points (designated instructions), isattached to the generated assembly. For example the *.pdb files from Visual Studioare created by the compiler and have the information to debug the created assembly.On the other hand, the debug mode will not allow some optimizations because areincompatible with the debugging functionality.

• Optimized or release: this mode is used to generate an optimized assembly torun or perform much faster than the debug one. In this case, the compiler performsdifferent transformations to the original code, for example two typical optimizationsthat cannot be applied to a debug build are:

– Loop unrolling: the compiler analyses how many times the loop is executedand then it copies the inner code the same number of times. This helps avoid-ing the maintenance of the loop variables.

– Inlining: the compiler places the method on the place of the call avoiding thestack overhead produced by a method’s call.

Page 60: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

44 IOSharp: .NET Micro Framework on Linux

Listing 6.1: Inline examplei n l i n e i n t Max ( i n t x , i n t y ){

r e t u r n (x > y ) ? x : y ;}i n t main ( ){

i n t a = 100;i n t b = 1010;cout << "Max ( a , b ) : " << Max (a , b ) << endl ;r e t u r n 0 ;

}

/ * The Max( i n t , i n t ) f u n c t i o n i s i n l i n e d to the main Max c a l l i n the f o l l o w i n g way :←↩* /

i n t main ( ){

i n t a = 100;i n t b = 1010;cout << "Max ( a , b ) : " << (a>b ) ? a : b << endl ;r e t u r n 0 ;

}

6.2 GPIO

GPIO test consists on how much time takes the board to perform a certain number of iter-ations changing an output port between the high and low states. Two channels are usedin this test, the first one will activate the Logic16 to start sniffing the second channel whichwill be the one that performs the changes.

The following code shows the test using the C# implementation. This is the minimumtest to analyse the performance of Mono and C++ when I/O is involved using the origi-nal IOSharp and its translation. In this case, it is measured the whole time that systemrequires to change the state of an output port in a certain number of iterations.

Listing 6.2: GPIO Performance test in C#using System ;using System . Collections . Generic ;using System . Linq ;using System . Text ;using Microsoft . SPOT . Hardware ;using IOSharp . NETMF . RaspberryPi . Hardware ;using System . Threading ;

namespace raspberrypi{

c lass Program{

p u b l i c s t a t i c vo id Main ( ){

Debug . Print ( "START" ) ;OutputPort bar = new OutputPort (Pins . V2_GPIO17 , f a l s e ) ;bar . Write ( f a l s e ) ;bool foo = f a l s e ;OutputPort o = new OutputPort (Pins . V2_GPIO11 , f a l s e ) ;

bar . Write ( t r ue ) ;f o r ( i n t i = 0; i < 10000; i++){

Page 61: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Performance tests 45

foo = ! foo ;o . Write (foo ) ;

}bar . Write ( f a l s e ) ;Debug . Print ( "END" ) ;

}}

}

The following code corresponds to the C++ translation.

Listing 6.3: GPIO Performance translated to C++# inc lude " Program . h "namespace raspberrypi {

vo id Program : : Main ( ) {Program* p = new Program ( ) ;p−>Run ( ) ;

}

vo id Program : : Run ( ) {Debug : : Print (new String ( "START" ) ) ;OutputPort* bar = new OutputPort (Cpu : : Pin : : GPIO_Pin17 , f a l s e ) ;

bar−>Write ( f a l s e ) ;bool foo = f a l s e ;OutputPort* o = new OutputPort (Cpu : : Pin : : GPIO_Pin11 , f a l s e ) ;bar−>Write ( t r ue ) ;f o r ( i n t i = 0; i < 200; i += 1) {Debug : : Print (new String (i ) ) ;foo = ! foo ;o−>Write (foo ) ;

}bar−>Write ( f a l s e ) ;Debug : : Print (new String ( "END" ) ) ;

}}

This test has been executed varying the number of iterations between 200 and 10000.Each iteration swaps the port state between high and low. Apart from this iteration in-crease, the assembly is compiled using both compiling modes.

6.2.1 200 Iterations

The result produced by Mono with the optimized assembly shows an irregular patternconsisting of two small pulses followed by a wide pulse, and then two small pulses followedby a wide gap. In the figure 6.1 this pattern is coloured in blue and as it can be seen, itis regularly repeated across all the test. The wide pulses and gaps are supposed to becaused by the garbage collector and the thread round-robin that Mono does.The small pulses are around 1 ms and the wide gaps/pulses are 2 ms long. Each block isrepeated every 10 ms.

Page 62: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

46 IOSharp: .NET Micro Framework on Linux

Figure 6.1: 200 Iterations using C# with optimizations

The figure 6.1 represents this 200 changes in the output state. The required time to makethis iterations is the elapsed time between the marker 1 and the marker 2. The RaspberryPi with Mono needs 202 ms in order to do all the iterations.

After testing the performance in Mono it was time to try out the code generated by Alter-Native, which is also compiled in release mode. The resulting test is shown and explainedbelow.

Figure 6.2: 200 Iterations using C++ with optimizations

This above image uses the same scale as the figure 6.1 shows, so the magnitude of theelapsed time can be compared.

In the case of C++ test, it can be observed that the pulses are much more regular thanthe Mono test, but at certain point around the pulse 89 a big gap is observed probably dueto the lack of a garbage collector (AlterNative programs currently do not have a workinggarbage collector implemented). It is relevant to remark that C++ needs only 77 ms toperform the same test, and each pulse is 0.43 ms on average.

After doing some tests on debug and release mode in both languages a graphic couldbe sketched, the performance in 200 iterations on Mono using both compile types was thepractically the same, it took around 200 ms to complete all the test, however in C++ thetime varies a bit depending on the compilation type, without using optimizations it takes100 ms but when optimization is applied the time decreases to 78 ms.From the figure 6.3 can be concluded that the C++ version is a 62% faster than the Monoone.

Page 63: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Performance tests 47

0

50

100

150

200

250

Without optimizations With optimizations

Time elapsed (ms)

Performance 200 iterations

C++ mono

Figure 6.3: Graph showing the elapsed time for the 200 iteration test. Blue is for C++while orange is C#. On the left is represented the non-optimized compilations and on the

right the optimized ones

6.2.2 10K Iterations

After testing the 200 iterations another one was done, but increasing the number of iter-ations to 10000 or in a factor of fifty. In this magnitude the compiler optimizations shouldbe visible enough to observe some kind of improvement on the different compilation andlanguage types.In the figure 6.4 is represented the elapsed time for 10k iterations, the block on the left isthe Mono version and lasts 10 seconds while the second one is the C++ version and theiterations are done in approximately 3 seconds being approximately three times faster.

Figure 6.4: 10k Iterations using C# with optimizations

As it was done in the previous test a graph has been done comparing the different lan-guages and compilation types.

Page 64: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

48 IOSharp: .NET Micro Framework on Linux

0

2000

4000

6000

8000

10000

12000

Without optimizations With optimizations

Time elapsed (ms)

Performance 10k iterations

C++ mono

Figure 6.5: Graph showing the elapsed time for the 10k iteration test. Blue is for C++while orange is C#. On the left is represented the non-optimized compilations and on the

right the optimized ones

At this number of iterations, the C++ performs much better than C# and also it is alsopossible to see an improvement between the debug and release versions of C++ being theoptimized version 741 ms faster than the non-optimized one. And the difference betweenboth languages shows that the C++ is 72% faster than C#.

6.3 Interrupts

It was observed that in HomeSense the response time in the sensor events was poor,probably because of the time that Mono takes between the interrupt detection and theresponse. To analyse the elapsed time between the trigger and the response the followingtest will be polling events from a pin, when an event occurs another pin will be used inoutput mode with an active high state.Like the previous test, the C++ code has been generated using AlterNative so it also willbe used to test some special functionalities like the delegates, the thread and the timer.The program will start and then create a delegate which will be the called function whenan interrupt occurs.In the figure 6.6 is shown the triggering of the interrupt (the top channel with the fallingedge), after 1.326 ms the second channel is activated in state high which represents theinterrupt response.

Page 65: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Performance tests 49

Figure 6.6: Response time of an interrupt in C# and Mono

Then the same test is performed using the C++ version. The result is pretty good becausethe interrupt is attended only 0.879 ms after the triggering. This implies that C++ is 447 µsfaster than C#.

Figure 6.7: Response time of an interrupt in C++

It is important to remark that the interrupts in operating systems cannot be consideredreal-time interrupts, this implies that sometimes an event is attended at a certain time butin another moment, the time required can be much more different due to the non real-time kernel that usually Linux uses. If a hard real-time is needed it is recommended touse other platforms like FreeRTOS which is intended to do tasks that require controlledresponse times.

6.4 Conclusions

The iteration test is important because in embedded systems the highest speed that canachieve a board is related to the maximum rate that the board can interact with externaldevices. Whereas the interrupt test, which analyses the interrupt-response time, is use-ful to determine the response delay in front of an interrupt. Apart from this, these testscan certify that one of the use cases of AlterNative is real, because the performance isincreased as the 10K iteration example shows being 75% faster than the program runningin Mono.

Page 66: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

50 IOSharp: .NET Micro Framework on Linux

Page 67: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Conclusions 51

CHAPTER 7. CONCLUSIONS

7.1 Project Conclusions

An implementation of Micro Framework has been done with the necessary features tomake the existing software created for that platform work on it (HomeSense and the RFIDcard reader for example). Although it works well, the performance is not as good as theoriginal, probably because the Micro Framework runs on dedicated hardware and all theconsuming operations are implemented internally on the virtual machine in C. So this isprobably one of the reasons why HomeSense works better on the Netduino than on theRaspberry Pi although the second one is much more powerful.

Another goals was to create a portable implementation. IOSharp is implemented usingC# with some calls to Linux SYSFS or Kernel functions. By using this way the implemen-tation is architecture independent, so it is capable of running either on a standard desktopor on an ARMv6, like the Raspberry Pi. The only requirement is having an underlyingLinux with the Mono interpreter executing .NET code.

In order to try to improve the IOSharp performance, it was translated to C++ using Al-terNative which is a code translating tool. Currently, it can partially transform the originalcode to C++ but it still needs some work on its core because many classes are not imple-mented yet. The parts that AlterNative could not translate where fixed by hand, howeverthis the amount of time saved with this tool is bigger than the required time to implementthe same code from scratch. After all, once IOSharp is translated to C++, the performanceis increased as it is shown in the chapter 6. For example, in 10k iterations in the state of anOutput GPIO the C# version needs around 10 seconds to finish the task while the trans-lated one only takes around 3 seconds. This implies an increase of a 62% in performance.

And finally, the best of AlterNative is that the generated code is still cross platform be-cause it uses standard C++ or libraries which are also available on different platforms, soonce the source is generated it can be taken to an ARM Linux and then compile it to anexecutable assembly.

7.1.1 Achieved Objectives

On Chapter 1 (Project Overview) the objectives for this thesis where listed, above are listedthe results in terms of objective achievements.

• IOSharp: all objectives had been achieved.

– GPIO

– Interrupts

– SPI

Page 68: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

52 IOSharp: .NET Micro Framework on Linux

– UART

– HomeSense

• AlterNative: most of the objectives where achieved.

– Cross-Platform: now is possible to use this tool in any operating system ca-pable of run .NET programs.

– Library: the necessary methods for IOSharp translation are done.

– Tests: each implemented method has its own functional test.

– Performance analysis: shown in chapter 6.

– Translate HomeSense: although AlterNative translates IOSharp, HomeSenseis not completely translated.

7.2 Personal Conclusions

Beyond academic achievements, all the process involving this bachelor’s thesis has beenrewarding. This project has given me a real chance to start working with embedded strate-gies, protocols and it also has provided an introduction to C++ development.

This project has allowed me to get familiar with Micro Framework and Linux development,which represents the new paths for the embedded systems as it has been explained onthe introduction of this thesis. Then, on the AlterNative part of the project, an introductionto AST patterns was done to achieve the capability to transform a representational ASTin one language into another one. Also I was introduced to C++ development focused onmulti-platform environments.

There are many skills acquired or consolidated during this time: from the initial touch-down on Micro Framework, platform invocation services (cross-language calls), delegationpatterns, guidelines for application performance, etc.

I also have realized that the development of a project is a quite complex task and requireshard effort and dedication, but most of all a strict control of timings in order to accomplishwith the established work plan.

7.3 Future Work

The results of this bachelor’s thesis point to several interesting directions for future work.In case of IOSharp:

• Addition of new protocols: Currently IOSharp offers the simple GPIOs, UART andSPI but there are other common protocols or interfaces that could be developed toextend the features, such as the I2C bus protocol. It could also be nice to implementthe analogical ports or even PWM control in I/O ports.

Page 69: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Conclusions 53

• Performance optimization: The implementation in .NET is too much slow runningon Mono, probably related to the use of the SYSFS. It could be interesting to dosome performance tests using the SYSFS and the Kernel functions provided byLinux. Apart from this, the interrupts are not implemented using IRQ so using IRQinstead of polling interrupts could be a good improvement on performance althoughit could affect on the portability between boards, some distributions do not acceptIRQ interrupts from the GPIOs.

In the case of AlterNative translating tool:

• Garbage Collector: Although AlterNative has a garbage collector implemented us-ing the Boehm GC library, it does not get called periodically so programs with a bigfootprint in RAM can get out of memory easily. To solve this issue the Boehm GCcould be called to release unused RAM and make it available again to the programor the system.

• Continuous Integration: Changes on the core of AlterNative are very susceptibleto break some implemented functionalities, this is why regression tests were createdto test if the different functionalities are working well. The problem is that this testtakes a huge amount of time to finish so introducing continuous integration toolssuch as Jenkins or Hudson can provide an easy way to quickly test these changeson a server capable of detecting new commits to a git repository. After executing allthe test an inform could be mailed to know the results of it.

• Extend capabilities: It could be interesting to make IOSharp work with MAREA2which is a Middleware for distributed embedded systems in different areas such as:telecommunications, avionics, health-care, automotive, defense, etc. MAREA is asoftware specifically designed to fulfil Unmanned Aircraft Systems (UAS) communi-cations and their application to the design of complex distributed UAS avionics.

7.4 Environmental Impact

At last but not least it is relevant to talk about the environmental impact of the work de-scribed in this document. It can be seen from the present document, this project consistsin the design and development of a software application. This has not a direct environ-mental benefit, but IOSharp is an implementation on a high-level basis of .NET MicroFramework which is an operating system for embedded devices, so it makes easy to de-velop applications which helps control different kind of situations like home installations(i.e. lights, temperature or humidity) to applications capable of detect and analyse differentparameters from the environment (i.e. weather and wind stations).AlterNative also reduces the power consumption required to execute a program, by remov-ing the .NET virtual machine in which non-translated programs relay on. The translatedbinary runs directly on the operating system avoiding all the overhead that a virtual ma-chine implies.

Page 70: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

54 IOSharp: .NET Micro Framework on Linux

Page 71: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Glossary 55

GLOSSARY

BCM2835 ARMv6 CPU mounted on the RaspberryPi.

CS Chip Select.

File Descriptor file descriptor (FD) is an abstract indicator for accessing a file on POSIXsystems.

GPIO General Purpose Input Output.

HAL Hardware Abstraction Layer.

I2C Inter-Integrated Circuit is a multimaster serial single-ended computer bus.

ioctl Abbreviation of input/output control, system call used for device-specific input/outputoperations.

IRQ Interrupt Request.

ISM Industrial, Scientific and Medical.

MISO Master Input Slave Output.

MOSI Master Output Slave Input.

PAL Platform Abstraction Layer.

POSIX Portable Operating System Interface. X stands for Unix.

PWM Pulse-width modulation.

RPL IPv6 Routing Protocol for Low-Power and Lossy Networks.

RX Reception Channel.

SCLK Serial Clock.

SoC System on a Chip.

SPI Serial Peripheral Interface.

SYSFS Virtual file system provided by Linux. SYSFS exports information about devicesand drivers from the kernel device model to user space.

TX Transmission Channel.

UART Universal Asynchronous Receiver/Transmitter.

WSN Wireless Sensor Network.

Page 72: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

56 IOSharp: .NET Micro Framework on Linux

Page 73: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

REFERENCES 57

REFERENCES

[1] Weinberg, B., Uniting Mobile Linux Application Platforms, LinuxPundit.com, 2008. Alsoavailable at http://www.linuxpundit.com/cv/docs/Platforms_WP_LP.pdf

[2] Gómez, C., Paradells, J. and E. Caballero, J, "Operating Systems", Sensors Every-where. Wireless Network Technologies and Solutions, p.273-278, Fundación Voda-fone España, 2010. Also available at http://fundacion.vodafone.es/static/fichero/pre_ucm_mgmt_002618.pdf

[3] Kühner J., EXPERT .NET MICRO FRAMEWORK, Apress, United States of America,2010.

[4] Kiely, D., "Delegates Tutorial", The Microsoft Developer Network (MSDN). Available athttp://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx

[5] ILSpy homepage, http://ilspy.net/, 2013

[6] A. V. Aho, R. Sethi, J. D. Ullman, Compilers. Principles, Techniques, and Tools, BellTelephone Laboratories, United States of America, 1986.

[7] D. Grune, H. E. Bal, C. J.H. Jacobs, K. G. Langendoen, Modern Compiler Design, VrijeUniversiteit, Amsterdam and Delf University, John Wiley & Sons, Ltd, England, 2000

Page 74: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites
Page 75: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

APPENDICES

TITLE : IOSharp: .NET Micro Framework on Linux

DEGREE: Bachelor in Telematics Engineering

AUTHOR: Gerard Solé i Castellví

DIRECTOR: Juan López Rúbio

DATE: February 7, 2014

Page 76: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites
Page 77: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

Technical information. Libraries and Datasheets 1

APPENDIX A. TECHNICAL INFORMATION.LIBRARIES AND DATASHEETS

A.1 Library Types

Below there are explained the different types of libraries, its characteristics and the differentpros and cons of them.

• Static LibraryThis kind of library is the one that is imported while compiling, and when the sourcecode in the library is linked statically in the generated binary, the compiler takes thelibrary functions used along the program and then they are embedded statically tothe compiled binary. In this way, the functions are physically located with the pro-gram.For example, imagine that you create a library with has three functions, calledget_password(), generate_token() and hash(char[] plain()), but in thecurrent project you only use two of this functions, which are get_password() andget_token(). When the compiler builds the project, it code will only take the func-tions from the library that are currently used in the program and then insert them intothe binary. At this point, deleting that library won’t affect the generated binary, andit will be able to use it without any dependency problems related to missing libraries(dependencies).The typical files for this type is .lib for Windows and .a for UNIX systems.

• Dynamic LibraryIn order to avoid the replication of libraries that occurs in static ones, the dynamiclibraries were created. This type of libraries is normally used along the operatingsystems to let applications use the offered functions and APIs written from the OS.In this case, and instead of the functional behaviour of static libraries. It is importantto check that the dependencies are well satisfied when the binary is used, becausea missing dependency will break the execution.

The usual extension files are .dll for Windows and .so for UNIX. But .so files are alsoused in Windows, especially in web browsers, which use this types of library to loadbrowser plugins such us Flash.

There are two subtypes of dynamic libraries which are explained below:

– Dynamically LinkedThese libraries must be available at compiling/linking phase, because the com-piler will verify that the function exists and that it is used properly. The librarieswill be loaded at start time of the program. In this case, all the functions aremapped into the code.

– Dynamically LoadedInstead of the previous library, the dynamic loading is used by programs to loador unload libraries and use its functions at run time. When the program needs

Page 78: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

to use a function it loads the library, then it uses the required functions andfinally the library is unloaded again.

Pros and consThe main problem of using static libraries is that the compiled binary takes much morememory and the library is embedded in every program that needs some functions fromthat library. But, on the other hand, by using static libraries, the access to its functionsby programs is much faster than dynamic ones. Using them also avoids dependencyproblems, because the dependencies are embedded instead of being located in the filesystem as dynamic libraries do.Regarding the dynamic libraries, they help to avoid replications and memory consumption,and also help to maintain the library updated in all programs that use them. Although thiscan seem pretty good, it can generate two bad effects into the compiled program. First ofall, if the library is missing in the system, the program will not run or will crash in executiontime. Secondly, if the library is updated but some methods are changed, the programwill crash because the non-existing function, and it will be necessary to readjust the codeagain, recompile and redistribute it.

A.2 spidev.h

Source code of the library spidev.h used along this project. The different macros neededto configure the ioctl calls.

Listing A.1: linux/spi/spidev.h/ ** i nc lude / l i n u x / sp i / spidev . h

** Copyr ight (C) 2006 SWAPP

* Andrea Pa te rn ian i <a . paterniani@swapp−eng . i t >

** This program i s f ree sof tware ; you can r e d i s t r i b u t e i t and / or modify

* i t under the terms of the GNU General Pub l i c License as publ ished by

* the Free Software Foundation ; e i t h e r vers ion 2 of the License , or

* ( a t your op t ion ) any l a t e r vers ion .

** This program i s d i s t r i b u t e d i n the hope t h a t i t w i l l be usefu l ,

* but WITHOUT ANY WARRANTY; w i thou t even the imp l ied warranty o f

* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

* GNU General Pub l i c License f o r more d e t a i l s .

** You should have rece ived a copy of the GNU General Pub l i c License

* along wi th t h i s program ; i f not , w r i t e to the Free Software

* Foundation , Inc . , 675 Mass Ave , Cambridge , MA 02139 , USA.

* /

# i f n d e f SPIDEV_H# def ine SPIDEV_H

# inc lude < l i n u x / types . h>

/ * User space vers ions o f kerne l symbols f o r SPI c lock ing modes ,

* matching < l i n u x / sp i / sp i . h>

* /

# de f ine SPI_CPHA 0x01

Page 79: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

# def ine SPI_CPOL 0x02

# def ine SPI_MODE_0 ( 0 | 0 )# de f ine SPI_MODE_1 ( 0 | SPI_CPHA)# de f ine SPI_MODE_2 (SPI_CPOL | 0 )# de f ine SPI_MODE_3 (SPI_CPOL | SPI_CPHA)

# de f ine SPI_CS_HIGH 0x04# def ine SPI_LSB_FIRST 0x08# def ine SPI_3WIRE 0x10# def ine SPI_LOOP 0x20# def ine SPI_NO_CS 0x40# def ine SPI_READY 0x80

/ *−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−* /

/ * IOCTL commands * /

# de f ine SPI_IOC_MAGIC ' k '

s t r u c t spi_ioc_transfer {__u64 tx_buf ;__u64 rx_buf ;

__u32 len ;__u32 speed_hz ;

__u16 delay_usecs ;__u8 bits_per_word ;__u8 cs_change ;__u32 pad ;

/ * I f the contents o f ' s t r u c t s p i _ i o c _ t r a n s f e r ' ever change

* i ncompat ib ly , then the i o c t l number ( c u r r e n t l y 0) must change ;

* i o c t l s w i th constant s ize f i e l d s get a b i t more i n the way of

* e r r o r checking than ones ( l i k e t h i s ) where t h a t f i e l d va r i es .

** NOTE: s t r u c t l ayou t i s the same i n 64 b i t and 32 b i t userspace .

* /} ;

/ * not a l l p la t fo rms use <asm−gener ic / i o c t l . h> or _IOC_TYPECHECK( ) . . . * /# de f ine SPI_MSGSIZE(N) \

( ( ( ( N ) * ( s i z e o f ( s t r u c t spi_ioc_transfer ) ) ) < (1 << _IOC_SIZEBITS ) ) \? ( ( N ) * ( s i z e o f ( s t r u c t spi_ioc_transfer ) ) ) : 0)

# de f ine SPI_IOC_MESSAGE(N) _IOW(SPI_IOC_MAGIC , 0 , char [ SPI_MSGSIZE(N) ] )

/ * Read / Wr i te o f SPI mode (SPI_MODE_0 . . SPI_MODE_3) * /# de f ine SPI_IOC_RD_MODE _IOR (SPI_IOC_MAGIC , 1 , __u8 )# de f ine SPI_IOC_WR_MODE _IOW(SPI_IOC_MAGIC , 1 , __u8 )

/ * Read / Wr i te SPI b i t j u s t i f i c a t i o n * /# de f ine SPI_IOC_RD_LSB_FIRST _IOR (SPI_IOC_MAGIC , 2 , __u8 )# de f ine SPI_IOC_WR_LSB_FIRST _IOW(SPI_IOC_MAGIC , 2 , __u8 )

/ * Read / Wr i te SPI device word leng th ( 1 . .N) * /# de f ine SPI_IOC_RD_BITS_PER_WORD _IOR (SPI_IOC_MAGIC , 3 , __u8 )# de f ine SPI_IOC_WR_BITS_PER_WORD _IOW(SPI_IOC_MAGIC , 3 , __u8 )

/ * Read / Wr i te SPI device d e f a u l t max speed hz * /# de f ine SPI_IOC_RD_MAX_SPEED_HZ _IOR (SPI_IOC_MAGIC , 4 , __u32 )# de f ine SPI_IOC_WR_MAX_SPEED_HZ _IOW(SPI_IOC_MAGIC , 4 , __u32 )

# end i f / * SPIDEV_H * /

Page 80: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

A.3 SPI Test. RFID Reader

A.3.1 MFRC522 Datasheet

The datasheet of this card card reader can be find at the NXP website or in the followinglink http://www.nxp.com/documents/data_sheet/MFRC522.pdf.

A.3.2 RFID Reader program

Listing A.2: SPIExample.cs - RFID Reading intervalusing System ;using System . Runtime . CompilerServices ;using System . Threading ;using IOSharp . Utils ;using System . Net ;

namespace IOSharp . Exmples{

p u b l i c c lass SPIExample{

p r i v a t e MFRC522 . SPIApi mfrc522 = new MFRC522 . SPIApi ( ) ;p r i v a t e bool onUpdate = f a l s e ;p r i v a t e bool activated = f a l s e ;p r i v a t e Timer cardReader = n u l l ;

p u b l i c s t a t i c vo id Main ( ){

new SPIExample ( ) . Run ( ) ;}

p r i v a t e vo id Run ( ){

mfrc522 . ConfigureSPI ( ) ;StringUtils . PrintConsole ( "MF522−AN Version : "+StringUtils . ToHexString (mfrc522 .←↩

ReadReg_MFRC522 (mfrc522 . VersionReg ) ) ) ;ConfigureTimer ( ! activated ) ;Thread . Sleep(−1) ;

}

p r i v a t e vo id ConfigureTimer ( bool activate ){

i f (activate ){

Utils . StringUtils . PrintConsole ( " * * * * Card reader s t a r t e d * * * * " ) ;onUpdate = f a l s e ;mfrc522 . MFRC522Init ( ) ;cardReader = new Timer (StartMFRC522 , t h i s , 0 , 500) ;activated = t rue ;

}e lse{

Utils . StringUtils . PrintConsole ( " * * * * Card reader stoped * * * * " ) ;cardReader . Dispose ( ) ;mfrc522 . MFRC522Stop ( ) ;activated = f a l s e ;

}}

Page 81: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

p r i v a t e vo id StartMFRC522 (Object timerInput ){

i f ( ! onUpdate ){

onUpdate = t rue ;String cardType = mfrc522 . ReadTagTypeString (mfrc522 . PICC_REQALL ) ;i f ( ! cardType . Equals ( " * " ) ){

CardDetected (cardType , mfrc522 . ReadSerialNumberString ( ) ) ;}onUpdate = f a l s e ;

}}

p r i v a t e vo id CardDetected (String cardType , String serialNumber ){

/ * *Card type

* 0x4400 = M i f a r e _ U l t r a L i g h t

* 0x0400 = Mifare_One (S50 )

* 0x0200 = Mifare_One (S70 )

* 0x0800 = Mifare_Pro (X)

* 0x4403 = Mifare_DESFire

* /

cardType = cardType . Trim ( ) ;sw i tch (cardType ){

case " 44 00 " :cardType = " M i f a r e _ U l t r a L i g h t ( " + cardType + " ) " ;break ;

case " 04 00 " :cardType = " Mifare_One (S50 ) ( " + cardType + " ) " ;break ;

case " 02 00 " :cardType = " Mifare_One (S70 ) ( " + cardType + " ) " ;break ;

case " 08 00 " :cardType = " Mifare_Pro (X) ( " + cardType + " ) " ;break ;

case " 44 03 " :cardType = " Mifare_DESFire ( " + cardType + " ) " ;break ;

}StringUtils . PrintConsole ( " Card detected : " + cardType + "− S e r i a l : " + serialNumber )←↩

;}

}}

Page 82: BACHELOR’S THESIS · BACHELOR’S THESIS TITLE : IOSharp: .NET Micro Framework on Linux ... el desenvolupament d’una eina anomenada AlterNative capaç de traduir aplicacions es-crites

A.4 AlterNative System Library

Figure A.1: Tree dump of the C++ libraries of AlterNative currently implemented