Internet des Objets (IoT)

Cours Complet selon Referentiel BTS

Systemes Embarques Connectes | MQTT, Node-RED, Android

🌐 IoT 📬 MQTT 📱 Android ⏱️ 46h Cours + 12h TP
🌐

Chapitre 1 : Structure d'un Systeme IoT

Architecture et composants fondamentaux

🎯 Objectifs du chapitre

  • Definir l'Internet des Objets et ses caracteristiques
  • Comprendre l'architecture en couches d'un systeme IoT
  • Identifier les domaines d'application
  • Connaitre les flux de donnees typiques

1.1 Definition de l'Internet des Objets

📖
Definition IoT L'Internet des Objets (IoT - Internet of Things) designe l'interconnexion entre Internet et des objets physiques capables de collecter, transmettre et recevoir des donnees via des reseaux de communication. Ces objets "intelligents" peuvent interagir avec leur environnement et communiquer entre eux ou avec des systemes cloud.

Caracteristiques d'un objet connecte

  • Identifiable : Possede une identite unique (adresse IP, MAC, UUID)
  • Connecte : Communique via un reseau (WiFi, Bluetooth, LoRa...)
  • Intelligent : Embarque une capacite de traitement (microcontroleur)
  • Interactif : Percoit (capteurs) et agit (actionneurs) sur l'environnement
  • Autonome : Fonctionne de maniere independante, souvent sur batterie
📱

75 Mds

Objets connectes prevus en 2025

💰

1100 Mds $

Marche mondial IoT

🏭

40%

IoT industriel (IIoT)

🏠

25%

Smart Home

1.2 Architecture d'un Systeme IoT

┌─────────────────────────────────────────────────────────────────────────┐
│                    ARCHITECTURE IoT EN 4 COUCHES                         │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                          │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │              COUCHE APPLICATION                                  │    │
│  │  - Applications mobiles Android/iOS                              │    │
│  │  - Dashboards web (Node-RED, Grafana)                            │    │
│  │  - APIs REST, notifications, alertes                             │    │
│  └─────────────────────────────────────────────────────────────────┘    │
│                                   ▲                                      │
│                                   │ HTTP, WebSocket                      │
│                                   ▼                                      │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │              COUCHE TRAITEMENT (Cloud/Serveur)                   │    │
│  │  - Broker MQTT (Mosquitto)                                       │    │
│  │  - Bases de donnees (InfluxDB, MySQL)                            │    │
│  │  - Traitement Node-RED, regles, analytics                        │    │
│  └─────────────────────────────────────────────────────────────────┘    │
│                                   ▲                                      │
│                                   │ MQTT, HTTP                           │
│                                   ▼                                      │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │              COUCHE RESEAU (Communication)                       │    │
│  │  - WiFi (ESP32, ESP8266)                                         │    │
│  │  - Bluetooth / BLE (communication courte portee)                 │    │
│  │  - LoRa / LoRaWAN (longue portee, basse consommation)            │    │
│  └─────────────────────────────────────────────────────────────────┘    │
│                                   ▲                                      │
│                                   │ GPIO, I2C, SPI, UART                 │
│                                   ▼                                      │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │              COUCHE PERCEPTION (Dispositifs)                     │    │
│  │  - Capteurs : temperature, humidite, mouvement, lumiere...       │    │
│  │  - Actionneurs : relais, LEDs, moteurs, vannes...                │    │
│  │  - Controleurs : ESP32, Arduino, STM32, Raspberry Pi             │    │
│  └─────────────────────────────────────────────────────────────────┘    │
│                                                                          │
└─────────────────────────────────────────────────────────────────────────┘
                    

1.3 Composants d'un Dispositif IoT

🧠

Controleur

Microcontroleur (ESP32, Arduino, STM32) qui execute le programme

🌡️

Capteurs

Convertissent grandeurs physiques en signaux electriques

⚙️

Actionneurs

Agissent sur l'environnement (relais, moteurs, LEDs)

📡

Module Radio

WiFi, Bluetooth, LoRa pour la communication

🔋

Alimentation

Batterie, USB, secteur selon l'application

💾

Memoire

Flash, EEPROM pour stocker donnees et config

Flux de donnees typique

/* Flux de donnees dans un systeme IoT */

1. ACQUISITION
   Capteur DHT22 → Mesure temperature 25.5°C → Signal numerique

2. TRAITEMENT LOCAL (ESP32)
   Lecture capteur → Formatage JSON → {"temp": 25.5, "hum": 60}

3. TRANSMISSION (WiFi + MQTT)
   ESP32 → Publish topic "maison/salon/capteur" → Broker Mosquitto

4. TRAITEMENT SERVEUR (Node-RED)
   Subscribe topic → Regles → Si temp > 30 → Alerte

5. STOCKAGE
   Node-RED → InfluxDB → Historique des mesures

6. VISUALISATION (Dashboard)
   Node-RED Dashboard → Graphiques temps reel → Navigateur/Mobile

7. ACTION (retour vers ESP32)
   Utilisateur clique "Ventilateur ON" → MQTT → ESP32 → Relais ON

1.4 Domaines d'Application

DomaineApplicationsExemples
Smart HomeDomotique, securite, confortThermostat Nest, eclairage Philips Hue
Industrie 4.0Maintenance predictive, suivi productionCapteurs vibration, OEE temps reel
AgricultureIrrigation, monitoring culturesCapteurs sol, stations meteo
SanteWearables, telemedecineMontres connectees, oxymetres
Smart CityEclairage, parking, dechetsLampadaires intelligents, capteurs niveau
TransportFlottes, vehicules connectesGPS trackers, OBD-II
📟

Chapitre 2 : Controleurs IoT

ESP32 et plateformes de developpement

🎯 Objectifs du chapitre

  • Connaitre les principaux controleurs IoT
  • Maitriser l'ESP32 et ses caracteristiques
  • Configurer l'environnement Arduino IDE
  • Programmer l'ESP32 pour l'IoT

2.1 Comparaison des Controleurs IoT

ControleurCPUWiFiBluetoothGPIOPrix
ESP32Dual-Core 240MHz✓ BLE34~5€
ESP8266Single 80MHz17~3€
Arduino UnoATmega328 16MHzShieldShield14~20€
Raspberry Pi Pico WDual-Core 133MHz26~8€
STM32 + ModuleARM Cortex-M 168MHzModuleModule80+~15€
💡
Choix recommande : ESP32 L'ESP32 est le controleur ideal pour l'IoT : WiFi + Bluetooth integres, puissant, economique, excellente documentation et communaute active.

2.2 Caracteristiques de l'ESP32

Dual-Core

Xtensa LX6 240 MHz

📶

WiFi

802.11 b/g/n 2.4GHz

📱

Bluetooth

Classic + BLE 4.2

💾

520 Ko SRAM

+ 4-16 Mo Flash

📍

34 GPIO

ADC, DAC, PWM, I2C, SPI

🔋

Deep Sleep

10 µA consommation

Brochage ESP32 DevKit

                         ESP32 DevKit V1 (30 pins)
                    ┌────────────────────────────────┐
                    │           ANTENNA              │
             EN ────┤ 1                        GND  ├──── GND
            VP ─────┤ 2   (ADC, input only)    23   ├──── GPIO23 (SPI MOSI)
            VN ─────┤ 3   (ADC, input only)    22   ├──── GPIO22 (I2C SCL)
          D34 ──────┤ 4   (input only)         TX   ├──── TX0
          D35 ──────┤ 5   (input only)         RX   ├──── RX0
          D32 ──────┤ 6   (ADC, Touch)         21   ├──── GPIO21 (I2C SDA)
          D33 ──────┤ 7   (ADC, Touch)         GND  ├──── GND
          D25 ──────┤ 8   (DAC1)               19   ├──── GPIO19 (SPI MISO)
          D26 ──────┤ 9   (DAC2)               18   ├──── GPIO18 (SPI SCK)
          D27 ──────┤ 10  (Touch)              5    ├──── GPIO5 (SPI CS)
          D14 ──────┤ 11  (Touch)              17   ├──── GPIO17 (UART2 TX)
          D12 ──────┤ 12  (Touch)              16   ├──── GPIO16 (UART2 RX)
          D13 ──────┤ 13  (Touch)              4    ├──── GPIO4
           GND ─────┤ 14                       0    ├──── GPIO0 (Boot)
           VIN ─────┤ 15  (5V input)           2    ├──── GPIO2 (LED integree)
                    │         ┌─────────┐    15   ├──── GPIO15
                    │         │  USB    │    3V3  ├──── 3.3V (sortie)
                    └─────────┴─────────┴────────┘
                    

2.3 Configuration Arduino IDE pour ESP32

/* Installation ESP32 dans Arduino IDE */

1. Ouvrir Arduino IDE
2. Fichier → Preferences
3. Dans "URL de gestionnaire de cartes supplementaires", ajouter :
   https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json

4. Outils → Type de carte → Gestionnaire de cartes
5. Rechercher "esp32"
6. Installer "ESP32 by Espressif Systems"

7. Selectionner : Outils → Type de carte → ESP32 Dev Module
8. Selectionner le port COM (ex: COM3, /dev/ttyUSB0)
9. Upload Speed : 115200

Premier programme : Blink LED

/* Clignotement LED integree ESP32 */

#define LED_PIN 2  // LED integree sur GPIO2

void setup() {
    Serial.begin(115200);
    pinMode(LED_PIN, OUTPUT);
    Serial.println("ESP32 demarre!");
}

void loop() {
    digitalWrite(LED_PIN, HIGH);
    Serial.println("LED ON");
    delay(1000);
    
    digitalWrite(LED_PIN, LOW);
    Serial.println("LED OFF");
    delay(1000);
}

2.4 Lecture de Capteurs avec ESP32

/* Lecture capteur DHT22 (temperature + humidite) */

#include "DHT.h"

#define DHTPIN 4       // GPIO4
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

void setup() {
    Serial.begin(115200);
    dht.begin();
    Serial.println("Capteur DHT22 initialise");
}

void loop() {
    float humidity = dht.readHumidity();
    float temperature = dht.readTemperature();
    
    if (isnan(humidity) || isnan(temperature)) {
        Serial.println("Erreur lecture capteur!");
        return;
    }
    
    Serial.printf("Temperature: %.1f°C\n", temperature);
    Serial.printf("Humidite: %.1f%%\n", humidity);
    
    delay(2000);  // DHT22 necessite 2s entre lectures
}
📶

Chapitre 3 : Communication WiFi

Connexion sans fil 2.4 GHz

🎯 Objectifs du chapitre

  • Comprendre les modes WiFi (Station, AP)
  • Connecter l'ESP32 a un reseau WiFi
  • Creer un point d'acces WiFi
  • Gerer la reconnexion automatique

3.1 Modes WiFi ESP32

ModeDescriptionUsage
WIFI_STAStation : se connecte a un routeurAcces Internet, cloud, MQTT
WIFI_APAccess Point : cree son reseauConfiguration, reseau local isole
WIFI_AP_STALes deux simultanementRepeteur, config + cloud
    MODE STATION (STA)                    MODE ACCESS POINT (AP)
    
    ┌─────────────┐                       ┌─────────────┐
    │   ROUTER    │   Internet            │   ESP32     │
    │   WiFi      │◀──────────            │   AP Mode   │
    │ 192.168.1.1 │                       │ 192.168.4.1 │
    └──────┬──────┘                       └──────┬──────┘
           │                                     │
     ┌─────┴─────┐                         ┌─────┴─────┐
     │           │                         │           │
┌────┴───┐  ┌────┴───┐                ┌────┴───┐  ┌────┴───┐
│ ESP32  │  │  PC    │                │ Phone  │  │ Laptop │
│  STA   │  │        │                │        │  │        │
│.1.100  │  │ .1.50  │                │ .4.2   │  │ .4.3   │
└────────┘  └────────┘                └────────┘  └────────┘
                    

3.2 Connexion Mode Station

/* Connexion WiFi en mode Station */

#include <WiFi.h>

const char* ssid = "NomDuReseau";
const char* password = "MotDePasse";

void setup() {
    Serial.begin(115200);
    
    // Demarrer la connexion WiFi
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    
    Serial.print("Connexion a ");
    Serial.print(ssid);
    
    // Attendre la connexion
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    
    Serial.println("\nWiFi connecte!");
    Serial.print("Adresse IP: ");
    Serial.println(WiFi.localIP());
    Serial.print("Force signal (RSSI): ");
    Serial.print(WiFi.RSSI());
    Serial.println(" dBm");
}

void loop() {
    // Verifier la connexion
    if (WiFi.status() != WL_CONNECTED) {
        Serial.println("WiFi perdu! Reconnexion...");
        WiFi.reconnect();
    }
    delay(10000);
}

3.3 Mode Access Point

/* Creer un point d'acces WiFi */

#include <WiFi.h>

const char* ap_ssid = "ESP32_IoT";
const char* ap_password = "12345678";  // Min 8 caracteres

void setup() {
    Serial.begin(115200);
    
    // Configurer l'Access Point
    WiFi.mode(WIFI_AP);
    WiFi.softAP(ap_ssid, ap_password);
    
    Serial.println("Point d'acces cree!");
    Serial.print("SSID: ");
    Serial.println(ap_ssid);
    Serial.print("IP: ");
    Serial.println(WiFi.softAPIP());  // 192.168.4.1
}

void loop() {
    Serial.printf("Clients connectes: %d\n", 
                   WiFi.softAPgetStationNum());
    delay(5000);
}
📱

Chapitre 4 : Communication Bluetooth

Bluetooth Classic et BLE pour l'IoT

🎯 Objectifs du chapitre

  • Differencier Bluetooth Classic et BLE
  • Creer une communication serie Bluetooth
  • Comprendre l'architecture GATT du BLE
  • Communiquer avec une application Android

4.1 Bluetooth Classic vs BLE

CaracteristiqueBluetooth ClassicBluetooth Low Energy
Debit1-3 Mbps125 kbps - 2 Mbps
Consommation~30 mA< 15 mA (pics courts)
Portee~100 m~100 m (BLE 5: 400 m)
Latence~100 ms~6 ms
AppairageObligatoireOptionnel
UsageAudio, fichiersCapteurs IoT, beacons

4.2 Bluetooth Serial (SPP)

Le mode Bluetooth Serial emule une liaison serie RS232 via Bluetooth, permettant une communication simple avec un smartphone.

/* Bluetooth Serial avec ESP32 */

#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

void setup() {
    Serial.begin(115200);
    pinMode(2, OUTPUT);  // LED
    
    // Demarrer Bluetooth avec nom visible
    SerialBT.begin("ESP32_BT");
    Serial.println("Bluetooth demarre. Appairez votre telephone!");
}

void loop() {
    // Reception depuis smartphone
    if (SerialBT.available()) {
        char c = SerialBT.read();
        Serial.write(c);  // Afficher sur Serial
        
        // Commandes simples
        if (c == '1') {
            digitalWrite(2, HIGH);
            SerialBT.println("LED ON");
        } else if (c == '0') {
            digitalWrite(2, LOW);
            SerialBT.println("LED OFF");
        }
    }
    
    // Envoi depuis Serial vers smartphone
    if (Serial.available()) {
        SerialBT.write(Serial.read());
    }
}

4.3 Bluetooth Low Energy (BLE)

Le BLE utilise une architecture GATT (Generic Attribute Profile) avec des Services et Caracteristiques :

                    ARCHITECTURE GATT BLE
    
    ┌─────────────────────────────────────────┐
    │                 PROFIL                   │
    │            (ex: Sensor Profile)          │
    └────────────────────┬────────────────────┘
                         │
           ┌─────────────┴─────────────┐
           ▼                           ▼
    ┌─────────────────┐       ┌─────────────────┐
    │    SERVICE 1    │       │    SERVICE 2    │
    │ UUID: 0x180D    │       │ UUID: 0x180F    │
    │ (Temperature)   │       │ (Battery)       │
    └────────┬────────┘       └────────┬────────┘
             │                         │
    ┌────────┴────────┐       ┌────────┴────────┐
    ▼                 ▼       ▼                 
┌──────────┐   ┌──────────┐  ┌──────────┐
│ CHARACT. │   │ CHARACT. │  │ CHARACT. │
│  Temp    │   │ Humidity │  │ Level    │
│  Read    │   │  Notify  │  │  Read    │
└──────────┘   └──────────┘  └──────────┘
                    
/* Serveur BLE avec ESP32 */

#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"

BLECharacteristic* pCharacteristic;
bool deviceConnected = false;

class MyCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) { deviceConnected = true; }
    void onDisconnect(BLEServer* pServer) { deviceConnected = false; }
};

void setup() {
    BLEDevice::init("ESP32_BLE");
    BLEServer* pServer = BLEDevice::createServer();
    pServer->setCallbacks(new MyCallbacks());
    
    BLEService* pService = pServer->createService(SERVICE_UUID);
    pCharacteristic = pService->createCharacteristic(
        CHARACTERISTIC_UUID,
        BLECharacteristic::PROPERTY_READ | 
        BLECharacteristic::PROPERTY_NOTIFY
    );
    pCharacteristic->addDescriptor(new BLE2902());
    
    pService->start();
    pServer->getAdvertising()->start();
}

void loop() {
    if (deviceConnected) {
        float temp = 25.5;  // Lecture capteur
        char buf[8];
        sprintf(buf, "%.1f", temp);
        pCharacteristic->setValue(buf);
        pCharacteristic->notify();
    }
    delay(2000);
}
📡

Chapitre 5 : Communication LoRa

Longue portee, basse consommation (LPWAN)

🎯 Objectifs du chapitre

  • Comprendre la technologie LoRa et LPWAN
  • Connaitre les parametres de modulation
  • Configurer un module LoRa avec ESP32
  • Comparer LoRa avec WiFi et Bluetooth

5.1 Qu'est-ce que LoRa ?

📖
LoRa - Long Range Technologie de modulation radio developpee par Semtech, utilisant la modulation CSS (Chirp Spread Spectrum). Ideale pour l'IoT distant avec faible debit et tres longue autonomie.
📡

15+ km

Portee en zone rurale

🔋

10 ans

Autonomie sur pile

📊

50 kbps

Debit maximum

5.2 Comparaison des Technologies Sans Fil

TechnologiePorteeDebitConsommationUsage
WiFi~100 mJusqu'a GbpsEleveeInternet, streaming
Bluetooth~100 m1-3 MbpsMoyennePeripheriques, audio
BLE~100 m2 MbpsTres faibleCapteurs, wearables
LoRa15+ km50 kbpsTres faibleAgriculture, smart city
Zigbee~100 m250 kbpsFaibleDomotique, mesh

5.3 Communication LoRa Point-a-Point

/* Emetteur LoRa avec ESP32 + SX1276 */

#include <SPI.h>
#include <LoRa.h>

// Pins pour module LoRa
#define SS    18
#define RST   14
#define DIO0  26
#define BAND  868E6  // Frequence Europe (868 MHz)

void setup() {
    Serial.begin(115200);
    LoRa.setPins(SS, RST, DIO0);
    
    if (!LoRa.begin(BAND)) {
        Serial.println("Erreur initialisation LoRa!");
        while(1);
    }
    
    // Configuration
    LoRa.setSpreadingFactor(9);      // SF7-SF12
    LoRa.setSignalBandwidth(125E3);  // 125 kHz
    LoRa.setTxPower(14);             // 14 dBm
    
    Serial.println("LoRa initialise!");
}

void loop() {
    // Envoi d'un paquet
    LoRa.beginPacket();
    LoRa.print("Hello LoRa #");
    LoRa.print(millis());
    LoRa.endPacket();
    
    Serial.println("Paquet envoye");
    delay(5000);
}
📬

Chapitre 6 : Protocole MQTT

Messagerie legere pour l'IoT

🎯 Objectifs du chapitre

  • Comprendre l'architecture publish/subscribe
  • Maitriser les concepts MQTT (topics, QoS, retain)
  • Programmer un client MQTT sur ESP32
  • Publier et s'abonner a des topics

6.1 Architecture MQTT

📖
MQTT - Message Queuing Telemetry Transport Protocole de messagerie publish/subscribe leger, concu pour les reseaux a faible bande passante et les appareils a ressources limitees. Port standard : 1883 (8883 avec TLS).
                    ARCHITECTURE MQTT
    
                    ┌─────────────────┐
                    │     BROKER      │
                    │   (Mosquitto)   │
                    │   Port: 1883    │
                    └────────┬────────┘
                             │
          ┌──────────────────┼──────────────────┐
          │                  │                  │
          ▼                  ▼                  ▼
    ┌──────────┐       ┌──────────┐       ┌──────────┐
    │ PUBLISHER│       │SUBSCRIBER│       │ PUB+SUB  │
    │  ESP32   │       │  Phone   │       │ Node-RED │
    │ (Capteur)│       │   App    │       │          │
    └──────────┘       └──────────┘       └──────────┘
    
    Publish: sensors/temp ──────▶ Broker ──────▶ Subscribers
                "25.5"            (route)       (recoivent)
                    

6.2 Topics MQTT

Les topics sont des chemins hierarchiques utilises pour organiser les messages :

/* Structure des topics MQTT */

// Hierarchie avec "/"
maison/salon/temperature
maison/salon/humidite
maison/cuisine/lumiere
usine/machine1/vibration

/* Wildcards pour abonnements */

+ : Remplace UN niveau
    maison/+/temperature  → salon, cuisine, chambre...

# : Remplace TOUS les niveaux (fin uniquement)
    maison/#              → tout ce qui commence par maison/

Qualite de Service (QoS)

QoSGarantieUsage
0At most once (peut etre perdu)Donnees frequentes (temperature)
1At least once (doublons possibles)Donnees importantes
2Exactly onceCommandes critiques

6.3 Client MQTT ESP32

/* Client MQTT complet avec ESP32 */

#include <WiFi.h>
#include <PubSubClient.h>

// Configuration
const char* ssid = "VotreWiFi";
const char* password = "MotDePasse";
const char* mqtt_server = "192.168.1.100";  // IP du broker
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

// Callback reception messages
void callback(char* topic, byte* payload, unsigned int length) {
    Serial.printf("Message recu [%s]: ", topic);
    
    String message;
    for (int i = 0; i < length; i++) {
        message += (char)payload[i];
    }
    Serial.println(message);
    
    // Traiter les commandes
    if (String(topic) == "esp32/led") {
        if (message == "ON") digitalWrite(2, HIGH);
        if (message == "OFF") digitalWrite(2, LOW);
    }
}

void reconnect() {
    while (!client.connected()) {
        Serial.print("Connexion MQTT...");
        if (client.connect("ESP32Client")) {
            Serial.println("connecte!");
            client.subscribe("esp32/led");  // S'abonner
        } else {
            Serial.println(" echec, retry...");
            delay(5000);
        }
    }
}

void setup() {
    Serial.begin(115200);
    pinMode(2, OUTPUT);
    
    // Connexion WiFi
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) delay(500);
    Serial.println("WiFi OK");
    
    // Configuration MQTT
    client.setServer(mqtt_server, mqtt_port);
    client.setCallback(callback);
}

void loop() {
    if (!client.connected()) reconnect();
    client.loop();
    
    // Publier toutes les 10 secondes
    static unsigned long lastMsg = 0;
    if (millis() - lastMsg > 10000) {
        lastMsg = millis();
        
        float temp = 25.5;  // Lecture capteur
        char msg[10];
        sprintf(msg, "%.1f", temp);
        
        client.publish("esp32/temperature", msg);
        Serial.printf("Publie: %s\n", msg);
    }
}
🖥️

Chapitre 7 : Installation Broker Mosquitto

Mise en place du serveur MQTT

🎯 Objectifs du chapitre

  • Installer Mosquitto sur differentes plateformes
  • Configurer le broker MQTT
  • Tester avec mosquitto_pub et mosquitto_sub
  • Securiser le broker (authentification)

7.1 Installation de Mosquitto

# Installation sur Raspberry Pi / Ubuntu / Debian
sudo apt update
sudo apt install mosquitto mosquitto-clients -y

# Demarrer et activer au demarrage
sudo systemctl start mosquitto
sudo systemctl enable mosquitto

# Verifier le statut
sudo systemctl status mosquitto

# Installation sur Windows
# 1. Telecharger depuis: https://mosquitto.org/download/
# 2. Executer l'installeur .exe
# 3. Le service demarre automatiquement

7.2 Configuration Mosquitto

# Fichier: /etc/mosquitto/mosquitto.conf

# Ecouter sur toutes les interfaces
listener 1883

# Autoriser les connexions anonymes (dev uniquement)
allow_anonymous true

# --- Configuration avec authentification ---
# allow_anonymous false
# password_file /etc/mosquitto/passwd

# Creer un utilisateur :
sudo mosquitto_passwd -c /etc/mosquitto/passwd monuser
# Entrer le mot de passe quand demande

# Redemarrer apres modification
sudo systemctl restart mosquitto

7.3 Test en Ligne de Commande

# Terminal 1 : S'abonner a un topic
mosquitto_sub -h localhost -t "test/topic"

# Terminal 2 : Publier un message
mosquitto_pub -h localhost -t "test/topic" -m "Hello MQTT!"

# S'abonner a TOUS les topics (debug)
mosquitto_sub -h localhost -t "#" -v

# Avec authentification
mosquitto_pub -h localhost -u monuser -P motdepasse -t "test" -m "Secure!"

# Connexion a un broker distant
mosquitto_sub -h broker.hivemq.com -t "test/#"
💡
Brokers MQTT publics pour tests
  • broker.hivemq.com - Port 1883
  • test.mosquitto.org - Port 1883
  • broker.emqx.io - Port 1883
⚠️ Ne pas utiliser pour donnees sensibles !