issue132:tutoriel1
Différences
Ci-dessous, les différences entre deux révisions de la page.
Les deux révisions précédentesRévision précédenteProchaine révision | Révision précédente | ||
issue132:tutoriel1 [2018/05/01 09:43] – d52fr | issue132:tutoriel1 [2018/05/07 17:52] (Version actuelle) – andre_domenech | ||
---|---|---|---|
Ligne 6: | Ligne 6: | ||
One of the best examples I found that helps to break it all down, was to compare it to a post office (https:// | One of the best examples I found that helps to break it all down, was to compare it to a post office (https:// | ||
+ | |||
+ | Salut à vous tous. Ça fait un bon moment que je n'ai pas été capable d' | ||
+ | |||
+ | MQTT est un protocole de réseau léger et facile d' | ||
+ | |||
+ | Et qu' | ||
+ | |||
+ | Un des meilleurs exemples que j'ai trouvé qui aide à le décortiquer, | ||
+ | |||
**The post office (broker or server) exists to route letters and packages (messages) from people and companies (publishers) to other people and companies (subscribers). If you want to send a message to someone, you create the message and send it to someone else through the post office. The post office receives your message and routes it to the recipient. However, the recipient needs to be known to the post office for them to be able to deliver it to them. | **The post office (broker or server) exists to route letters and packages (messages) from people and companies (publishers) to other people and companies (subscribers). If you want to send a message to someone, you create the message and send it to someone else through the post office. The post office receives your message and routes it to the recipient. However, the recipient needs to be known to the post office for them to be able to deliver it to them. | ||
In the above example, Mike wants to send a message to Sally. Mike (the publisher) sends the message to the post office and they know Sally' | In the above example, Mike wants to send a message to Sally. Mike (the publisher) sends the message to the post office and they know Sally' | ||
+ | |||
+ | Le bureau de poste (intermédiaire ou serveur) existe pour diriger les lettres et paquets (les messages) de gens et d' | ||
+ | |||
+ | Dans l' | ||
**In the real world, we have an application, | **In the real world, we have an application, | ||
I have been asked, what happens if one of the clients that are subscribed to a topic goes away for some reason. There are three Quality of Service (QoS) levels that can be set for any message being sent to the broker. When a client normally connects to the broker, it is in a non-persistent manner and the QoS level is set to 0, so any messages that arrive when a subscribing client is not connected are lost. If it is important that the subscribers get all messages, the publishing client must set up a persistent session and send the messages with a Quality of Service level higher than 0. We’ll deal with QoS and persistent sessions next month when we create our publishing client.** | I have been asked, what happens if one of the clients that are subscribed to a topic goes away for some reason. There are three Quality of Service (QoS) levels that can be set for any message being sent to the broker. When a client normally connects to the broker, it is in a non-persistent manner and the QoS level is set to 0, so any messages that arrive when a subscribing client is not connected are lost. If it is important that the subscribers get all messages, the publishing client must set up a persistent session and send the messages with a Quality of Service level higher than 0. We’ll deal with QoS and persistent sessions next month when we create our publishing client.** | ||
+ | |||
+ | Dans le monde réel, nous avons une application, | ||
+ | |||
+ | On m'a demandé ce qui se passe si l'un des clients qui est abonné au sujet part pour une raison quelconque. Il y a trois niveaux de Qualité de Service (QoS, Quality of Service) qui peuvent être réglés pour chaque message envoyé à l' | ||
**Let' | **Let' | ||
Ligne 20: | Ligne 37: | ||
For testing purposes, we’ll run the sensor, publishing program, broker and subscriber program all on the same Raspberry Pi. ** | For testing purposes, we’ll run the sensor, publishing program, broker and subscriber program all on the same Raspberry Pi. ** | ||
+ | |||
+ | Supposons qu'il y ait un Raspberry Pi 3 dans notre garage qui lit un capteur d' | ||
+ | |||
+ | Le RPi du garage peut utiliser une version modifiée du logiciel que nous avons utilisé dans le Full Circle Magazine n° 109, pour piloter le capteur et distribuer les messages à l' | ||
+ | |||
+ | Pour les besoins des tests, nous lancerons le capteur, le programme d' | ||
**The first thing we need to do is install Mosquitto and its two clients. From the Main Menu, go to Preferences | Add / Remove Software. In the search box, type ‘mosquitto’. You are looking for two packages. The first is the broker. It shows up as ‘MQTT version 3.1 / 3.1.1 compatible message broker mosquitto-1.4.15-0mosquitto1’. Select it, then, a few lines down from that, you want to find ‘Mosquitto command line MQTT clients mosquitto-clients-1.4.15-0mosquitto1’. Select this as well, then click the ‘Apply’ button. Once these are installed, you can dismiss the Software manager. Alternately, | **The first thing we need to do is install Mosquitto and its two clients. From the Main Menu, go to Preferences | Add / Remove Software. In the search box, type ‘mosquitto’. You are looking for two packages. The first is the broker. It shows up as ‘MQTT version 3.1 / 3.1.1 compatible message broker mosquitto-1.4.15-0mosquitto1’. Select it, then, a few lines down from that, you want to find ‘Mosquitto command line MQTT clients mosquitto-clients-1.4.15-0mosquitto1’. Select this as well, then click the ‘Apply’ button. Once these are installed, you can dismiss the Software manager. Alternately, | ||
Ligne 26: | Ligne 49: | ||
and they will be installed for you.** | and they will be installed for you.** | ||
+ | |||
+ | La première chose qu'il faut faire est d' | ||
+ | |||
+ | sudo apt-get install mosquitto mosquitto-clients | ||
+ | |||
+ | et ils s' | ||
**Once you have these programs installed, reboot the RPi and mosquitto will automatically be started. You won’t see anything, but it is running. Now we’ll make sure things are working correctly. | **Once you have these programs installed, reboot the RPi and mosquitto will automatically be started. You won’t see anything, but it is running. Now we’ll make sure things are working correctly. | ||
Ligne 36: | Ligne 65: | ||
The first part of the line we just typed was (of course) the command to run ‘mosquitto_sub’, | The first part of the line we just typed was (of course) the command to run ‘mosquitto_sub’, | ||
+ | |||
+ | Une fois que les programmes sont installés, redémarrez votre RPi et mosquitto sera automatiquement lancé. Vous ne voyez rien, mais il tourne. Maintenant, nous nous assurerons que tout tourne correctement. | ||
+ | |||
+ | Ouvrez deux fenêtres de terminal. Mettez-en une sur le côté gauche de l' | ||
+ | |||
+ | mosquitto_sub -h localhost -t test | ||
+ | |||
+ | Quand vous appuyez sur Entrée, vous ne voyez rien, mais vous avez créé votre premier abonnement à MQTT. Appuyons sur Pause pour un court instant et voyons ce que nous avons fait. | ||
+ | |||
+ | La première partie de la ligne que nous venons de taper était (bien sûr) la commande pour lancer « mosquitto-sub », le client d' | ||
**mosquitto_pub -h localhost -t test -m 'Hi There' | **mosquitto_pub -h localhost -t test -m 'Hi There' | ||
Ligne 46: | Ligne 85: | ||
The mosquitto broker (server) is running on our RPi and sits there by default listening on TCP/IP port 1883. You can change the port number to most any available TCP/IP port, however port 1883 is registered with IANA specifically for MQTT. TCP/IP port 8883 is also registered, for using MQTT over SSL. If you don’t want to run your own broker, there are many public brokers you can use, some of them are free. You can find a list of some of these and their conditions for use at https:// | The mosquitto broker (server) is running on our RPi and sits there by default listening on TCP/IP port 1883. You can change the port number to most any available TCP/IP port, however port 1883 is registered with IANA specifically for MQTT. TCP/IP port 8883 is also registered, for using MQTT over SSL. If you don’t want to run your own broker, there are many public brokers you can use, some of them are free. You can find a list of some of these and their conditions for use at https:// | ||
+ | |||
+ | mosquitto_pub -h localhost -t test -m 'Hi There' | ||
+ | |||
+ | Maintenant, regardez le terminal de gauche. Vous pouvez voir « Hi there » reproduit sur le terminal. | ||
+ | |||
+ | « mosquitto_pub » est le client d' | ||
+ | |||
+ | Alors que ceci semble très simple à première vue, pas mal de choses se passent. | ||
+ | |||
+ | L' | ||
**When a program wants to publish to a broker, it first needs to connect, then sends the topic and the message. It doesn’t have to be concerned who’s there, if anyone. A subscribing program also doesn’t have to care about much, other than subscribing to the proper topic that is being published on the broker. The key here is that if you accidentally subscribe to the wrong topic, nothing will ever come in. When we set up our two terminal window test above, we started the subscriber client before the first message ever came in. The broker didn’t know (or care) what the topic was that we were subscribing to. It assumed we knew what we were doing. In the same way, when we published our ‘Hi There’ message on the ‘test’ topic, the broker simply took it and sent it out to whatever clients out there that happened to be subscribed to the topic, if any.** | **When a program wants to publish to a broker, it first needs to connect, then sends the topic and the message. It doesn’t have to be concerned who’s there, if anyone. A subscribing program also doesn’t have to care about much, other than subscribing to the proper topic that is being published on the broker. The key here is that if you accidentally subscribe to the wrong topic, nothing will ever come in. When we set up our two terminal window test above, we started the subscriber client before the first message ever came in. The broker didn’t know (or care) what the topic was that we were subscribing to. It assumed we knew what we were doing. In the same way, when we published our ‘Hi There’ message on the ‘test’ topic, the broker simply took it and sent it out to whatever clients out there that happened to be subscribed to the topic, if any.** | ||
+ | |||
+ | Quand un programme veut émettre vers un intermédiaire, | ||
**The topic itself can be as simple as ‘test’ or extremely verbose. Some basic guidelines for topics are: | **The topic itself can be as simple as ‘test’ or extremely verbose. Some basic guidelines for topics are: | ||
Ligne 58: | Ligne 109: | ||
• Topics should not start with ‘$’, since those messages are for broker system messages. | • Topics should not start with ‘$’, since those messages are for broker system messages. | ||
• Topics should be specific in nature, not general.** | • Topics should be specific in nature, not general.** | ||
+ | |||
+ | Le sujet lui-même peut être aussi simple que « test » ou extrêmement verbeux. Certaines règles de base pour les sujets sont : | ||
+ | • Sensible à la casse. | ||
+ | • Doit être une chaîne en UTF-8. | ||
+ | • Doit consister en au moins un caractère pour être valide. | ||
+ | • Des jokers sont autorisés lors d'un abonnement à une hiérarchie de sujets, mais lors de l' | ||
+ | • Aucun sujet n'est créé par défaut par l' | ||
+ | • Les sujets sont créés par un client d' | ||
+ | • Les sujets ne doivent pas commencer par « $ », réservé pour les messages système de l' | ||
+ | • Les sujets doivent être spécifiques par nature, pas généraux. | ||
**Other than that, there are very little constraints on what a topic is or how it is constructed. Typically, if a client needs to publish more than a single type of message, the topics will be level based with each level separated by a forward slash (/). For example, in the program we will be writing to monitor and publish the DHT sensor values, we should use two different topics. One for the humidity value and one for the temperature value. We could combine the values into a string and only use one topic, but in this case, we will publish them separately. Making a very gross assumption, we will provide for a complete home solution, with multiple sensors of various types in multiple rooms of the house. We could then start our topic(s) with: | **Other than that, there are very little constraints on what a topic is or how it is constructed. Typically, if a client needs to publish more than a single type of message, the topics will be level based with each level separated by a forward slash (/). For example, in the program we will be writing to monitor and publish the DHT sensor values, we should use two different topics. One for the humidity value and one for the temperature value. We could combine the values into a string and only use one topic, but in this case, we will publish them separately. Making a very gross assumption, we will provide for a complete home solution, with multiple sensors of various types in multiple rooms of the house. We could then start our topic(s) with: | ||
housesensors/ | housesensors/ | ||
+ | |||
+ | En dehors de ça, il y a très peu de contraintes sur ce qu'est un sujet ou comment il est construit. Typiquement, | ||
+ | |||
+ | housesensors/ | ||
**This describes the topic to be one that will have sensor data specific to the house itself. This could include bedrooms, living areas and garden areas, but not something like a parking lot. The next level could possibly be floor based, as in first floor, basement and so on. | **This describes the topic to be one that will have sensor data specific to the house itself. This could include bedrooms, living areas and garden areas, but not something like a parking lot. The next level could possibly be floor based, as in first floor, basement and so on. | ||
Ligne 76: | Ligne 141: | ||
housesensors/ | housesensors/ | ||
+ | |||
+ | Il s'agit d'un sujet qui fournira des données de capteurs spécifiques à la maison elle-même. Cela peut comprendre les chambres, les zones de vie et les parties du jardin, mais pas un lieu comme un parking. Le prochain niveau pourrait être basé sur les étages, comme le premier étage, le rez-de-chaussée, | ||
+ | |||
+ | housesensors/ | ||
+ | |||
+ | Le suivant pourrait être la pièce ou la zone. | ||
+ | |||
+ | housesensors/ | ||
+ | |||
+ | Enfin, nous pourrions définir le sujet comme étant le type de valeur qui sera émise. | ||
+ | |||
+ | housesensors/ | ||
+ | |||
+ | housesensors/ | ||
**Notice that none of the topic strings have spaces in them. While spaces are not specifically prohibited, UTF-8 allows for many kinds of white space and could confuse things. You could also use mixed cases like ‘HouseSensors/ | **Notice that none of the topic strings have spaces in them. While spaces are not specifically prohibited, UTF-8 allows for many kinds of white space and could confuse things. You could also use mixed cases like ‘HouseSensors/ | ||
Ligne 88: | Ligne 167: | ||
Full documentation on the phao library can be found at https:// | Full documentation on the phao library can be found at https:// | ||
+ | |||
+ | Notez qu'il n'y a aucune espace dans les chaînes de sujet. Alors que les espaces ne sont pas spécifiquement interdits, UTF-8 autorise beaucoup de sortes d' | ||
+ | |||
+ | Pour que nos programmes en Python puissent communiquer avec MQTT, nous utiliserons la bibliothèque paho-mqtt. Vous pouvez l' | ||
+ | |||
+ | pip install --user paho-mqtt | ||
+ | |||
+ | Ou pour Python 3.x : | ||
+ | |||
+ | pip3 install --user paho-mqtt | ||
+ | |||
+ | Une documentation complète de la bibliothèque paho se trouve à https:// | ||
**As a sample program for you to test with, I’ll give you a short program that you can run and use the mosquitto_pub to send messages to it based on sample code from the eclipse site. I’ve made a couple of changes to make it work properly here. | **As a sample program for you to test with, I’ll give you a short program that you can run and use the mosquitto_pub to send messages to it based on sample code from the eclipse site. I’ve made a couple of changes to make it work properly here. | ||
Ligne 104: | Ligne 195: | ||
Now we instantiate the client and bind our callback functions to it.** | Now we instantiate the client and bind our callback functions to it.** | ||
+ | |||
+ | Comme exemple de programme pour que vous le testiez, je vous donnerai un programme court que vous pouvez lancer, puis utiliser mosquitto_pub pour lui envoyer des messages sur la base de l' | ||
+ | |||
+ | Bien sûr, il nous faut importer la bibliothèque pour démarrer. | ||
+ | |||
+ | import paho.mqtt.client as mqtt | ||
+ | |||
+ | Ensuite, nous créerons une fonction de rappel (ci-dessus à droite) qui tournera si un message est reçu de l' | ||
+ | |||
+ | def on_message(client, | ||
+ | |||
+ | print(msg.topic+" | ||
+ | |||
+ | Maintenant, nous instancions le client et lui lions nos fonctions de rappel. | ||
**client = mqtt.Client() | **client = mqtt.Client() | ||
Ligne 112: | Ligne 217: | ||
Next, we connect to the broker, located at localhost. The 60 at the end of the call specifies a ‘keepalive’ time of 60 seconds, where the client pings the broker every 60 seconds. | Next, we connect to the broker, located at localhost. The 60 at the end of the call specifies a ‘keepalive’ time of 60 seconds, where the client pings the broker every 60 seconds. | ||
+ | |||
client.connect(" | client.connect(" | ||
Ligne 120: | Ligne 226: | ||
# handles reconnecting.** | # handles reconnecting.** | ||
+ | |||
+ | client = mqtt.Client() | ||
+ | |||
+ | client.on_connect = on_connect | ||
+ | |||
+ | client.on_message = on_message | ||
+ | |||
+ | Ensuite, nous nous connectons à l' | ||
+ | |||
+ | client.connect(" | ||
+ | |||
+ | Enfin, nous disons au client de « loop_forever » (faire une boucle infinie). Utilisez l' | ||
+ | |||
+ | # Blocage de l' | ||
+ | |||
+ | # traite les reconnexions. | ||
**# Other loop*() functions are available that give a threaded interface and a | **# Other loop*() functions are available that give a threaded interface and a | ||
Ligne 135: | Ligne 257: | ||
Until then, have fun.** | Until then, have fun.** | ||
+ | # D' | ||
+ | |||
+ | # une interface manuelle. | ||
+ | |||
+ | client.loop_forever() | ||
+ | |||
+ | Maintenant, sauvegardez le programme sous « client1.py » et lancez-le. | ||
+ | |||
+ | Retournez au terminal qui exécute mosquitto_pub et renvoyez le message précédent au sujet « test ». Vous devriez le voir apparaître dans la fenêtre de terminal où notre programme Python tourne. J'ai placé le code sur Pastebin à https:// | ||
+ | |||
+ | Le mois prochain, nous mettrons à jour notre programme Python original du n° 109 du Full Circle Magazine pour qu'il supporte MQTT. | ||
+ | |||
+ | Jusque-là, amusez-vous bien. | ||
+ | |||
+ | |||
+ | Encart de la page 21, les deux lignes commençant par « # » | ||
+ | |||
+ | **# Subscribing in on_connect() means that if we lose the connection and | ||
+ | # reconnect then subscriptions will be renewed.** | ||
+ | |||
+ | # S' | ||
+ | # nous nous reconnectons, |
issue132/tutoriel1.1525160633.txt.gz · Dernière modification : 2018/05/01 09:43 de d52fr