Retour sur le Meet'up "Linux et Android dans les systèmes embarqués et les objets connectés" qui s'est déroulé le 7 mars à Nantes.
Dans cette présentation, découvrez :
→ L'état de l'art "Android, Linux, et Tizen dans les systèmes embarqués et objets connectés"
→ 2 études de cas techniques :
1) La partie Android décrira comment accéder à un capteur de température (USB ou I²C) afin d'afficher la valeur mesurée dans une application écrite en Java. La cible utilisée sera une carte BeagleBone Black.
2) La partie Linux décrira comment réaliser un capteur de température (I²C) sur la base d'une carte Raspberry Pi zero sous Linux, la distribution adaptée étant produite avec l'outil Yocto.
2 experts de l'embarqué chez Smile sont intervenus :
• Pierre Ficheux, directeur technique Smile ECS, aussi enseignant et responsable de la spécialité Gistre (Génie informatique des systèmes temps réel et embarqués) de l’EPITA et auteur de l’ouvrage "Linux embarqué", ainsi que des livres blancs "Linux pour l'embarqué " et "Logiciel libre pour l'IoT " ;
• Cédric Ravalec, en charge de l'offre open source IoT de Smile, a cocréé et développé la société GENYMOBILE, dotée d’une très forte expertise autour d’Android, et de la société d'expertise Firefox Phoxygen. Il est aussi membre fondateur du Paris Android User Group.
3. 3
CHAINE DE VALEUR IoT
Hardware NETWORK Application
Cloud / Service
End Device
(sensor, …)
Gateway
Network
connectivit
y
Middleware
&
platform
Applicatio
n
DIGITAL / E-BUSINESS
BUSINESS INFORMATION SYSTEM
INFRASTRUCTURE
EMBEDDED &
CONNECTED SYSTEMS
6. 6
HISTORIQUE
• 1980 : RTOS (Real Time OS) génériques
• 2000 : OS libres, grand public
• Domaines historiques/industriels
● Militaire, spatial (RTOS/360, VRTX sur Hubble)
● Contrôle de processus industriel
● Transport : AUTOSAR/OSEK, ARINC 653
● Internet/Telecom : routeurs, PABX
• 2010 « Nouveaux » domaines orientés IoT
● Smart Home
● Smart Cities
● Industrie 4.0
● E-Santé
7. 7
OPEN SOURCE
Le logiciel libre est important dans le SI dans les année 2000
• Le logiciel libre a pris un part importante dans les systèmes
embarqués /mobiles
● OS (Linux, Android)
● Outils de base (compilateur, éditeur, débogueur, ...)
● « build systems » (Buildroot, Yocto/OE)
● IDE (Eclipse)
• La plupart des éditeurs ont au catalogue des composants basés
sur du logiciel libre (Wind River, Adacore, LynuxWorks, ...)
• Les plateforme IoT Open Source arrivent
8. 8
LINUX COMME OS EMBARQUE / IoT
Réservé aux systèmes complexes
● 32 bits minimum
● Gestion complexe de la mémoire
● Empreinte mémoire importante:
● Consommation mémoire vive et d’énergie
• Temps réel
● Problème de migration de anciens RTOS car Linux n’est pas TR
● Incompatible avec les systèmes critiques/certifiés
● Souvent utilisé pour les outils, les simulateurs et architectures « mixtes » (banc de
test)
• IoT
● N’est pas adapté pour des capteurs
● De plus en plus utilisé pour les objets intelligents / SmartHome
● Gateway entre les capteurs et la plate-forme IoT
● Prototypage
9. 9
OS OPEN SOURCE POUR L’IoT
Système d’exploitation léger et
flexible pour capteurs
miniatures en réseau
Consommation énergétique et
une empreinte mémoire
minimales Support IPv6 et
6LoWPAN
Portabilité
Léger
Contraintes de mémoire
Appareils à faible
consommation électrique
pour l'Internet des objets
10. 10
OS OPEN SOURCE POUR L’IoT
Système d'exploitation
temps réel (RTOS) faible
empreinte, portable,
préemptif et Open source
pour microcontrôleur
Porté sur 33 architectures
Créé en 2003
Parmi les plus utilisés dans
le marché des systèmes
d'exploitation temps réel.
Hébergé par Linux Foundation
RTOS évolutif et optimisé
optimisé pour les
périphériques à ressources
limitées,
Sonde Philae et Rosetta
11. 11
OUTILS
• Yocto/OpenEmbedded
● Moteur écrit en Python
● Très puissant mais lourd
● Basé sur des fichiers de configuration
• Buildroot
● Basé sur la commande « make »
● Au départ un démonstrateur pour uClibc
● Désormais un véritable outil, bien maintenu !
● Approche statique (pas de paquets)
12.
13. 13
ANDROID
Android = un système d'exploitation basé sur un noyau Linux
• Un « framework » fournissant des applications et permettant
d'en ajouter facilement
• Basé sur Dalvik (puis ART), une machine virtuelle Java optimisée
pour le mobile
• Navigateur web basé sur Webkit puis Chrome
• Graphique optimisé en 2D ou 3D basé sur OpenGL/ES
• Nouvel environnement de développement « Android Studio »
compatible avec Android « wear » et « things »
• Partiellement open source mais pas réellement du logiciel
libre...
14. 14
AVANTAGES POUR l’EMBARQUE
• Android a une interface utilisateur intuitive
• IHM plus facile à développer qu’avec QT ou EFL
• Possède un écosystème applicatif important et une forte
communauté
• Il est nativement mobile. Android a été conçu à partir de zéro
• Beaucoup de développeurs connaissent Android et Java
• Les APIs facilitent le développement des applications
• Les développeurs n'ont pas besoin de connaître l'architecture
sous-jacente Android, juste les API
15. 15
INCONVENIENTS POUR l’EMBARQUE
• Google a le contrôle total sur Android
• La nature monolithique d’Android rend difficile de réduire les
fonctionnalités sans casser les dépendances
• Demande beaucoup de ressource mémoire
• Il est plus difficile d'ajouter le support matériel
• Pas réellement un projet libre ni communautaire
• Inapproprié pour les périphériques avec des exigences en
temps réel
• Système de « build » statique assez rudimentaire par rapport à
ceux de Linux (Buildroot, OE)
16. 16
CONCLUSION
• Certains diront qu’Android devient une alternative viable à
Linux pour l’embarqué non TR parce qu'il normalise le
développement de logiciels pour de tels périphérique
• Utiliser Android quand :
● Le projet nécessite une IHM
● Le projet ne nécessite pas de TR dur (pour l’instant)
● L’utilisation de Java est un avantage
• Attention à la dépendance / Google
• Android ne peut remplacer GNU/Linux embarqué
● Développement communautaire
● Support matériel
● Système de construction bien plus avancé (Yocto)
17. 17
ANDROID THINGS
Pour créer des périphériques connectés pour une grande variété
d'applications grand public et industrielles.
• Android SDK et Android Studio
• Google Play Services & Google Cloud
• Flashable image + SDK (Developer Preview) Android Things
18. 18
CHANGEMENTS VIS A VIS D’ANDROID
• Android Things ne nécessite pas d’écran
• Prend en charge les interfaces utilisateur graphiques en utilisant
le même Toolkit qu’Android
• N'inclut pas la barre d'état système ou les boutons de
navigation
• Les paquets de base manquants (ContactsContract
MediaStore, Paramètres etc.)
• Sous-ensemble des services Google Play disponibles
• Pas d'autorisations d'exécution
• Pas de notifications Changements de comportement
• Pas de systeme de deploiement
22. 22
TIZEN PROJECT
Tizen es un système d’exploitation
• Principalement pour le SmartHome
● Toute la gamme Samsung d’ici 2018
● Arrive sur l’IoT
• Projet Open Source
• Samsung principal contributeur
• Basé sur GNU/Linux
• Hébergé par la Linux Foundation
24. 24
CASSER LES SILOTS AVEC IoTivity
• IoTivity est un framework
● communication entre objets
● C/C++ library (FLOSS : Apache 2.0)
• Implémentation des standards
● Open Connectivity Foundation (OCF)
• Supporté dans Tizen:3.0, Yocto, ...
• Cross Platform, multi profiles & protocol agnostic
● IP, Ethernet, WiFi, Bluetooth, BLE, Zigbee, LTE...
25. 25
MODULES POUR l’IoT ET LE CLOUD
• Cortex A Exynos5 CPU(s) et Cortex M MIPS
• Ethernet, WIFI, Bluetooth, BLE, Zigbee, SigFox...
27. 1Extension API Android
Support matériel et extension de l'API Android
Pierre Ficheux (pierre.ficheux@smile.fr)
Mars 2017
28. 2Extension API Android
Agenda
● Rappels démarrage Android
● Zygote, « System Server » et les « services »
● Support matériel GNU/Linux
● Support matériel Android
● Solution simplifiée
● Solution complète (Service + HAL + SDK)
● Test et exemple d'application
● Démonstrations
29. 3Extension API Android
Démarrage d'Android
● Le démarrage d'Android proche de celui d'un système
GNU/Linux
– Chargement du noyau statique par le bootloader
– Détection/initialisation du matériel par le noyau
– Exécution du programme init (PID = 1)
● La suite est spécifique à Android et contenue dans
system.img → /system
– Démarrage de la partie espace utilisateur par les
scripts init*.rc
– Démarrage Zygote, system_server puis la JVM
(Dalvik / ART)
31. 5Extension API Android
Zygote & Co
● Zygote est fils d'init
# ps | grep init
root 1 0 348 216 c017be04 0000e91c S /init
# ps | grep zygote
root 93 1 458472 35880 ffffffff 4006b0e4 S zygote
● Le system_server est démarré par Zygote
(startSystemServer() dans ZygoteInit.java)
system 490 93 541620 33972 ffffffff 4006afc0 S system_server
● Les applications (processus) sont filles de Zygote, chacune
utilisant une instance de JVM
radio 620 93 474592 22684 ffffffff 4006bebc S com.android.phone
u0_a16 638 93 484500 31860 ffffffff 4006bebc S com.android.launcher
u0_a10 964 93 466912 17492 ffffffff 4006bebc S com.android.musicfx
root 986 2 0 0 c019043c 00000000 S flush-179:0
root 1025 101 820 480 c004f6cc 400a694c S /system/bin/sh
32. 6Extension API Android
Service et « System server »
● Service = composant exécuté en tâche de fond (no GUI)
● System server démarre les services Android → audio,
power, activity, window, …
● Utilisation de la commande service
$ service list
Found 69 services:
0 phone: [com.android.internal.telephony.ITelephony]
1 iphonesubinfo: [com.android.internal.telephony.IPhoneSubInfo]
2 simphonebook: [com.android.internal.telephony.IIccPhoneBook]
3 isms: [com.android.internal.telephony.Isms]
...
31 statusbar: [com.android.internal.statusbar.IstatusBarService]
...
● Affichage/masquage de la barre d'état en utilisant les
méthodes exposées par Binder (et les codes 1 et 2)
$ service call statusbar 1
Result: Parcel(00000000 '....')
$ service call statusbar 2
33. 7Extension API Android
Architecture Android
/frameworks/base/services/java
/frameworks/base/services/jni
/hardware/libhardware/
/device/[MANUF.]/[DEVICE]
/sdk/emulator/
Noyau ou module
/frameworks/base/core/
AOSP-provided
ASL
Manuf.-provided
Manuf. license
Manuf.-provided
GPL-license
Schéma K. Yaghmour
Répertoires AOSP
1
2
3
4
5
6
35. 9Extension API Android
Support matériel GNU/Linux :-)
● Sous GNU/Linux le support matériel concerne
uniquement le noyau
● La plupart des périphériques récents sont supportés
– PCI
– USB
– I2C
– SPI
– Ethernet
– ...
● Certains bus sont accessibles par des API « user
space » (USB, I2C, SPI) → simplicité
● On peut aisément ajouter un pilote externe (.ko)
● Accès par un « démon » (= service), NTP + /dev/rtc
36. 10Extension API Android
Support matériel Android :-(
● Plus complexe que sous GNU/Linux (voir schéma)
● L'accès au matériel passe par « toujours » par un service
Android
● Il faut définir les points suivants :
– Module noyau (identique Linux)
– Bibliothèque HAL (Hardware Abstraction Layer)
– Service Java + interface JNI (vers la HAL)
– Exposer le nouveau service en langage AIDL
– Ajouter des classes de développement (SDK modifié)
● Très peu de documentation car développement « fermé »
37. 11Extension API Android
Approche simplifiée
● Une première approche pour un nouveau matériel consiste à :
– Écrire un pilote noyau (compatible Linux)
– Accéder au pilote depuis Java par JNI (pas de HAL)
● Exemple concret du capteur USB
– La température est disponible par "cat /dev/temper0"
– L'application Java affiche la valeur convertie en °C
– Autres exemples (I²C) en bibliographie
1
38. 12Extension API Android
Ajout de service « init »
● Un service correspond à une application ou un script exécutée
au démarrage
● Le code est à place dans les fichiers /init*.rc
service temper /system/bin/init_temper.sh
class main
oneshot
● Dans le cas présent
– détachement/attachement du device USB (HID)
– Chargement du pilote USB
● Trace de l'initialisation
# logcat -d | grep temper
I/INIT_TEMPER( 107): init_temper
● Syntaxe du init.rc dans system/core/init/readme.txt
n'est pas redémarré
39. 13Extension API Android
Bibliothèque JNI
#define FILE_PATH "/dev/temper0"
/* Java_<package name>_<class name>_<method name> */
jstring Java_com_example_temper_MainActivity_getTemp(JNIEnv* env, jobject thiz )
{
char buf[256];
// do something like "cat /dev/temper0"
FILE *fp = fopen (FILE_PATH, "r");
memset (buf, 0, sizeof(buf));
fread (buf, 1, sizeof(buf), fp);
fclose (fp);
return (*env)->NewStringUTF(env, buf);
}
nom de la fonction Java
2
40. 14Extension API Android
Application Java
● La bibliothèque est chargée dans la classe MainActivity
static {
System.loadLibrary("temper");
}
● La fonction update_temp() effectue la mise à jour
public native String getTemp();
...
void update_temp()
{
tv = (TextView)this.findViewById(R.id.textView2);
Float f = Float.parseFloat(getTemp());
// Convert driver data to °C
f = (f * 125) / 32000;
String s = String.format("%.1f °C", f);
tv.setText(s);
}
6
appel de la fonction
42. 16Extension API Android
Bibliothèque HAL
● Ajout arborescence à device/*
● Ajout de l'interface (.h) à hardware/libhardware/include
● Nouvelle bibliothèque conforme à la HAL
● Dans le cas de l'exemple la bibliothèque se limite aux actions
suivantes :
– Ouverture du fichier /dev/temper0
– Lecture de la température (fonction read())
– Fermeture du fichier
● La bibliothèque exécute les mêmes opérations qu'une
commande
$ cat /dev/temper0
2
43. 17Extension API Android
Définition du module
● Le type temperhw_device_t définit l'interface avec les
couches supérieures
struct temperhw_device_t {
struct hw_device_t common;
// device functions
int (*read)(char* buffer, int length); // read temperature
...
};
● Pointeur initialisé à l'ouverture
static int open_temperhw (const struct hw_module_t* module, char const *name, struct
hw_device_t** device)
{
struct temperhw_device_t *dev = malloc(sizeof(struct temperhw_device_t));
...
dev->read = temperhw__read;
...
return 0;
}
44. 18Extension API Android
Code de la fonction read()
int temperhw__read (char* buffer, int length)
{
int retval, fd;
// Just like "/dev/temper0"
fd = open("/dev/temper0", O_RDONLY);
if (fd < 0) {
ALOGI("Failed to open device!n");
return -1;
}
retval = read (fd, buffer, length);
close(fd);
return retval;
}
traces « info » (I) dans logcat
45. 19Extension API Android
Interface JNI
● L'ajout de service est dans frameworks/base
● Défini dans service/jni/com_android_server_TemperService.cpp
● La table ci-dessous définit les fonctions à enregistrer
static JNINativeMethod method_table[] = {
{ "init_native", "()I", (void*)init_native },
{ "finalize_native", "(I)V", (void*)finalize_native },
{ "read_native", "(I[B)I", (void*)read_native },
{ "test_native", "(II)I", (void*)test_native},
};
● Le 2ème paramètre code les types des paramètres de la
fonction (rouge) et le type de retour (bleu)
● (I[B)I → paramètres entier + tableau d'octets, retour entier
3
46. 20Extension API Android
Principales fonctions définies
● La fonction init_native() ouvre le module HAL (.so) par :
hw_get_module(TEMPERHW_HARDWARE_MODULE_ID, (hw_module_t const**)&module);
● La fonction finalize_native() libère le pointeur
alloué
● La fonction read_native() appelle la fonction read() de la
HAL
static int read_native(JNIEnv *env, jobject clazz, int ptr, jbyteArray
buffer) {
temperhw_device_t* dev = (temperhw_device_t*)ptr;
jbyte* real_byte_array;
int length;
real_byte_array = env->GetByteArrayElements(buffer, NULL);
...
length = dev->read((char*)real_byte_array, env->GetArrayLength(buffer));
env->ReleaseByteArrayElements(buffer, real_byte_array, 0);
return length ;
} fonction définie dans libtemper.so (dépend de la cible)
47. 21Extension API Android
Enregistrement
● Définition de la fonction d'enregistrement
int register_android_server_TemperService (JNIEnv * env) {
return jniRegisterNativeMethods (env,
"com/android/server/TemperService", method_table,
NELEM(method_table));
};
● L'appel à la fonction s'effectue dans JNI_OnLoad() du
fichier onload.cpp
48. 22Extension API Android
Code Java du service
● Localisé sur service/java/com/android/server/TemperService.java
● Le constructeur appelle init_native()
public class TemperService extends ITemperService.Stub {
...
public TemperService(Context context) {
super();
mContext = context;
mNativePointer = init_native();
}
};
● La fonction Java read() appelle read_native()
public String read(int maxLength) {
int length; byte[] buffer = new byte[maxLength];
length = read_native(mNativePointer, buffer);
return new String(buffer, 0, length);
}
● Ajout du nouveau service à la fonction run() de
SystemServer.java
4
49. 23Extension API Android
Exposition des fonctions (AIDL)
● AIDL = Android Interface Description Language
● Déclaration des fonctions du nouveau service pour
utilisation par Binder (IPC Android)
● Ajout du nouveau service par os/ItemperService.aidl
interface ItemperService {
/**
* {@hide}
*/
String read (int maxLength);
}
● Le code est produit par l'utilitaire aidl
50. 24Extension API Android
SDK
● Ajout des nouvelles classes au SDK
● Utilise un « manager » pour accéder au service (Power
Manager, Activity Manager, etc.)
– Interface dans content/Context.java
– Implémentation dans app/ContextImpl.java
● Accès par la fonction getSystemService()
mTemperManager = (TemperManager) this.getSystemService (Context.TEMPER_SERVICE);
5
51. 25Extension API Android
Compilation AOSP
● On doit compiler l'image cible et le SDK
● Pour l'image, résultat dans out/target/product
$ cd work_43
$ source build/envsetup.sh
$ lunch 18
$ make update-api
$ make
● Pour le SDK, résultat dans out/host/linux-x86/sdk
$ lunch sdk-eng
$ make
produit frameworks/base/api/current.txt
52. 26Extension API Android
Test du nouveau service
● Vérification de la présence du service
$ service list | grep temper
7 temper: [android.os.ITemperService]
● Création du fichier (simulation)
# echo 8888 > /dev/temper0 ; chmod 666 /dev/temper0
● Test de dialogue Binder avec la commande service
$ service call temper 1
Result: Parcel(00000000 00000000 00000000 '............')
● Traces « logcat »
$ adb logcat | grep temper
I/temperhw_bbb( 275): Temper HW - read() for 0 bytes called
I/temperhw_bbb( 275): Temper HW - read() = 0
53. 27Extension API Android
Application
● On déclare une variable de type TemperManager
import android.os.TemperManager; // Added class
public class HelloTemperInternalActivity extends Activity {
...
TemperManager mTemperManager;
}
● Nouvelle fonction update_temp()
void update_temp() {
Float f = 0.0f;
String s;
tv = (TextView)this.findViewById(R.id.textView2);
try {
f = Float.parseFloat (mTemperManager.read (20)); // Get temp from service
f = (f * 125) / 32000; // Convert to °C
s = String.format ("%.1f °C", f);
tv.setText(s); // update TextView
} catch (Exception e) { … }
}
6
54. 28Extension API Android
Conclusions
● Méthode utilisable pour toute extension matérielle...et plus →
A-Industrial-OSP ?
● Ajout d'un service « tâche périodique » pour un Android/RT
(noyau Xenomai)
import android.os.SquareSignalManager;
m = (SquareSignalManager)this.getSystemService(Context.SQUARESIGNAL_SERVICE);
m.send(frequency);
55. 29Extension API Android
Références
● http://www.opersys.com/blog/extending-android-hal
● http://www.vogella.com/tutorials/AndroidServices/article.html#service_overview
● http://fr.slideshare.net/opersys/understanding-the-android-system-server
● http://www.linuxembedded.fr/2014/12/investigation-android-temps-reel
● https://source.android.com/devices/sensors/hal-interface.html
● http://anatomyofandroid.com/?s=system+server
● http://fr.slideshare.net/opersys/understanding-the-android-system-server
● http://androidxref.com/4.3_r2.1/xref/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
● http://developer.android.com/guide/components/aidl.html
● http://elinux.org/Android_Binder
● http://www.2net.co.uk/tutorial/android-4.3-beaglebone-fastboot
● Article « Extension de l'API Android » dans OpenSilicium #14
● Article « AOSP pour BeagleBone Black » dans OpenSilicium #14
● http://www.possamai.it/android-i2c
● http://boundarydevices.com/i2c-tools-under-android
56. 1Prototyping IoT with Yocto
Prototyping IoT with
Pierre Ficheux (pierre.ficheux@smile.fr)
03/2017
57. 2Prototyping IoT with Yocto
$ whoami
● French embedded Linux developer, writer and teacher
● CTO @ Smile-ECS (Embedded & Connected Systems)
58. 3Prototyping IoT with Yocto
2 kinds of objects
● Basic one such as sensor
– MCU/µC (no MMU)
– Software is « bare metal » or light OS such as Contiki
or RIOT
● Advanced one (computer like)
– CPU with MMU (32 bits or more)
– OS such as Linux / Tizen / Android
Parrot flower power (µC)
Eccelenza touch (Yocto)
“Tesla car is a connected computer on wheels !”
59. 4Prototyping IoT with Yocto
Linux and IoT
● Not “the” universal OS for IoT but...
● According to “IoT developer Survey 2016”
– 73 % Linux
– 23 % « bare metal » (no OS)
– 12 % FreeRTOS
– 6 % Contiki
● Don't forget there are and
– Distribution (Debian, Ubuntu, etc.)
– « Build system » (Yocto, Buildroot, etc.)
● Today most of objects are computers
60. 5Prototyping IoT with Yocto
Linux distribution
● Most of developers use Linux distribution
● Well known, comfortable and portable environment but
– High footprint (Go)
– boot time (close to 1 mn)
– Development oriented → host but not a target
– No traceability (binaries)
– Limited target support (x86, ARM)
– Not for IoT at all !!
● Most distributions runs on ARM → easy to take a wrong
way
● Alternate – and right - way is « build system » !
61. 6Prototyping IoT with Yocto
What is a « build system » ?
● Not a distribution, just a tool to build one from sources
● Does not provide sources but “recipes”
● Provides binaries file to be installed on the target
– Bootloader
– Linux kernel and DT blobs
– Root-filesystem image + applications
● Provides additional information
– Licensing
– Dependencies graphs
● Much better footprint, boot time, etc.
● Android uses a dedicated – but open source - build
systems
62. 7Prototyping IoT with Yocto
Most famous build systems
● Yocto/OpenEmbedded
– Based on “BitBake” (Python)
– Very powerful, not that easy to learn
– Text oriented
● Buildroot
– Based on standard GNU Make
– Started as an internal tool for uClibc
– Static approach (no packages)
● OpenWrt
– Modified Buildroot
– Packaging support
– Used for WeIO (IoT device)
63. 8Prototyping IoT with Yocto
Buildroot
● Formerly internal tool for uClibc
● One version every 3 months since 2009.02
● Kernel like graphical configurator
● Fast and easy to use
● Result is not a distribution but a “Linux firmware”
64. 9Prototyping IoT with Yocto
OpenEmbedded
● A “cross compilation framework”
● Started Chris Larson, Michael Lauer et Holger Schuring
for “OpenZaurus” (2002)
● Zaurus (SHARP) was the “first” Linux/Qt PDA
65. 10Prototyping IoT with Yocto
OE principles
● Recipe is a .bb (for BitBake) file for every component
(from “Hello World” to whole distribution)
● OE uses classes (.bbclass), headers (.inc) and
configuration files (.conf)
● You can inherit from class with inherit
● “Deriving” a recipe is VERY useful → .bbappend
● Files are organized as “layers” → meta-*
● OE data flow is based on packages (RPM, IPK, DEB)
● Package management on target is optional
66. 11Prototyping IoT with Yocto
Yocto / OE
● Yocto (symbol y) is a unit prefix in the metric system
denoting a factor of 10-24
● Yocto project was started in 2010 by Linux foundation
● Sub-projects integration (OE, BitBake, Poky, etc.)
● Currently most of embedded companies and hardware
makers are members (Intel, Montavista, NXP, TI, etc.)
● Richard Purdie (Linux Foundation fellow) is the
architect
● Most of Linux BSP are provided as OE layers !
69. 14Prototyping IoT with Yocto
Yocto/Poky « in a nutshell »
● Installing Poky and BSP
$ git clone -b krogoth git://git.yoctoproject.org/poky
$ cd poky
$ git clone git://git.yoctoproject.org/meta-raspberrypi
● Creating working directory
$ source oe-init-build-env rpi-build
● Adding BSP layer to conf/bblayers.conf
$ bitbake-layers add-layer meta-raspberrypi
● Adding target name to conf/local.conf
MACHINE = "raspberrypi"
● Creating minimal image
$ bitbake core-image-minimal
● Testing on SD card
$ sudo dd if=<path>/core-image-minimal-raspberrypi.rpi-sdimg
of=/dev/sdb
70. 15Prototyping IoT with Yocto
Use case 1 : IoT sensor
● Building a demo sensor for Smile
– Raspberry Pi (zero)
– I²C temperature/pressure sensor (MPL115A2)
– Wi-Fi (USB)
– HTTP protocol
72. 17Prototyping IoT with Yocto
Building distribution
● Starting from smaller distro « core-image-minimal »
● Adding options and new recipes
– Package management
– Standard or “derivated” recipes
– New recipes (I²C sensor control)
● Put everything in a new layer → meta-iot
$ yocto-layer create iot
● Updating local.conf (for test only)
● Creating a new distro recipe → « rpi-iot-image »
73. 18Prototyping IoT with Yocto
Using .bbappend (derivation)
● One recipe (.bb) is defined in layer “A”
● We update recipe in a .bbappend located in layer “B”
● Currently
– Network configuration (Wi-Fi + HTTPd)
– I²C activation in config.txt
– Autoload of i2c-dev module
74. 19Prototyping IoT with Yocto
Wi-Fi + HTTPd
● Wi-Fi adapter is supported → wlan0
● We need some additional packages (Wi-Fi management +
HTTP server=
IMAGE_INSTALL_append += "iw wpa_supplicant lighttpd"
● Updating /etc/network/interfaces for wlan0
automatic configuration
● WPA authentication (manual procedure for test)
# wpa_passphrase <ESSID> <password> > /etc/wpa_supplicant.conf
# ifdown wlan0
# ifup wlan0
75. 20Prototyping IoT with Yocto
Sensor + I²C
● Updating config.txt
dtparam=i2c_arm=on
→ do_deploy_append()
● Adding packages to local.conf
IMAGE_INSTALL_append += "i2c-tools kernel-modules"
● Loading I²C support
KERNEL_MODULE_AUTOLOAD += "i2c-dev"
→ Kernel .bbappend
● New recipe for MPL115A2 control
– Adapting original program (C, based on WiringPi)
– Starting a “service”, reading sensor every 20 secs
→ using update-rc.d class
76. 21Prototyping IoT with Yocto
NTP support
● No RTC on Raspberry Pi
● NTP recipe provided by meta-openembedded layer
$ cd poky
$ git clone git://git.openembedded.org/meta-openembedded
$ git checkout <yocto-branch>
$ bitbake-layers add-layer ../meta-openembedded/meta-oe
$ bitbake-layers add-layer ../meta-openembedded/meta-python
$ bitbake-layers add-layer ../meta-openembedded/meta-networking
$ bitbake ntp tzdata
● Configuring timezone
# rm -f /etc/localtime
# ln -s /usr/share/zoneinfo/Europe/Paris /etc/localtime
# cat /etc/default/ntpdate
...
NTPSERVERS="pool.ntp.org"
77. 22Prototyping IoT with Yocto
Updading target
● SMART included by package management
● Creating packages index
$ bitbake package-index
● Creating HTTP channels on the target
# smart channel --add <channel> baseurl=http://<pkg-dir>
# smart update
# smart install ntpdate tzdata
78. 23Prototyping IoT with Yocto
Use case 2 : Border router (N. Aguirre)
● More complex demonstration based on sensorTag (TI)
● Raspberry Pi (Yocto 2.1 based) as “border router”
79. 24Prototyping IoT with Yocto
SensorTag
● Cortex M3 (48MHz, 128KB flash, 8KB RAM)
● 512KB external flash for OTA and/or storage
● Low-power (10 mA active, 100 uA sleeping)
● Radio802.15.4 + Bluetooth Low Energy (BLE)
● $ 30 from TI website
80. 25Prototyping IoT with Yocto
Raspberry Pi + 6LBR
● 6LBR est a board router software (between IoT/sensors
world and Internet world)
● Get data from SensorTags (6LoWPAN)
● Send data to the “cloud”
● MQTT broker
● Time Series (Influxdb) database
● MQTT / database connector (Telegraf)
● Web management and display (Grafana)