Ramon Fontes
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    2
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: iot --- # IoT Lab 2: MQTT with Python This lab aims to offer you an hands-on experience with MQTT. You will perform experiments that will allow you to learn how to “publish” data and “subscribe” to get data. ## Section 1: Basic MQTT **regarding the clients**: In this section you will work with MQTT using the MQTT Paho library for Python. The documentation of the MQTT Paho API is here. You have to first install it using: ` $ sudo python -m pip install paho-mqtt ` **regarding the broker:** In this session we will use a public broker. There are various public brokers (also called sandboxes) in the Internet. For example: * iot.eclipse.org (https://iot.eclipse.org/getting-started#sandboxes) * test.mosquitto.org (http://test.mosquitto.org/) * broker.hivemq.com (https://www.hivemq.com/public-mqtt-broker/) A more or less updated list is available here: https://github.com/mqtt/mqtt.github.io/wiki/public_brokers :::info BTW, it’s very easy to install one’s own broker (see for example https://mosquitto.org/download/). ::: **A simple subscriber** The code of the simplest subscriber is the one below. ```python= #!/usr/bin/env python # File: sisub.py import paho.mqtt.client as mqtt THE_BROKER = "test.mosquitto.org" THE_TOPIC = "$SYS/#" CLIENT_ID = "" # The callback for when the client receives a CONNACK # response from the server. def on_connect(client, userdata, flags, rc): print("Connected to ", client._host, "port: ", client._port) print("Flags: ", flags, "returned code: ", rc) client.subscribe(THE_TOPIC, qos=0) # The callback for when a message is received from the server. def on_message(client, userdata, msg): print("sisub: msg received with topic: {} and payload: {}".format(msg.topic, str(msg.payload))) client = mqtt.Client(client_id=CLIENT_ID, clean_session=True, userdata=None, protocol=mqtt.MQTTv311, transport="tcp") client.on_connect = on_connect client.on_message = on_message client.username_pw_set(None, password=None) client.connect(THE_BROKER, port=1883, keepalive=60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. client.loop_forever() ``` This code connects to the broker "test.mosquitto.org" and subscribes to topic "$SYS/#" :::info :question: 1. Execute o código acima e explique o resultado obtido. ::: **A simple producer** The code of the simplest producer is the one below. ```python= #!/usr/bin/env python # File: sipub.py import random import time import paho.mqtt.client as mqtt THE_BROKER = "test.mosquitto.org" THE_TOPIC = "ufrn/test" CLIENT_ID = "" # The callback for when the client receives a CONNACK # response from the server. def on_connect(client, userdata, flags, rc): print("Connected to ", client._host, "port: ", client._port) print("Flags: ", flags, "returned code: ", rc) # The callback for when a message is published. def on_publish(client, userdata, mid): print("sipub: msg published (mid={})".format(mid)) client = mqtt.Client(client_id=CLIENT_ID, clean_session=True, userdata=None, protocol=mqtt.MQTTv311, transport="tcp") client.on_connect = on_connect client.on_publish = on_publish client.username_pw_set(None, password=None) client.connect(THE_BROKER, port=1883, keepalive=60) client.loop_start() while True: msg_to_be_sent = random.randint(0, 100) client.publish(THE_TOPIC, payload=msg_to_be_sent, qos=0, retain=False) time.sleep(5) client.loop_stop() ``` This code connects to the broker `test.mosquitto.org` and periodically publishes random values to topic `ufrn/test` :::info :question: 2. Execute o código acima e explique o resultado obtido. :question: 3. Modifique `sisub.py` para obter os dados enviados por `sipub.py`. ::: ## Some basic test **one to many communication** MQTT is very useful when we have to distribute the same piece of information to various users… but we have to be careful with topics. For example, using the code from Question_3, set as `topic` for the `subscriber` the value `i/LOVE/Python` and execute it. Now modify the code of the `producer` so that it uses the same topic (i.e., `i/love/python`) and as the message use the text that you want. Execute the `producer` :::info :question: 4. Descreva o resultado obtido ::: **Retained messages:** Normally, if a publisher publishes a message to a topic, and no one is subscribed to that topic the message is simply discarded by the broker. If you want your broker to remember the last published message, you’ll have to use the `retained` option. Only one message is retained per topic. The next message published on that topic replaces the retained message for that topic. Modify the `loop_start/loop_stop` section of `sipub.py` like indicated below: ```python= #!/usr/bin/env python client.loop_start() msg_to_be_sent = "__whatevertextyouwant__" client.publish(THE_TOPIC, payload=msg_to_be_sent, qos=0, retain=False) client.loop_stop() ``` Try now the following cases, but **remember to always execute the “subscriber” AFTER the “producer**” in all cases: :::info :question: 5. Experimente os seguintes casos: * Poste uma mensagem com a opção retida definida como "Falso". O que o “assinante” recebe? * Publique uma mensagem com a opção retida definida como "True". O que o “assinante” recebe? * Publique várias mensagens (diferentes) com a opção de retidas em “True” antes de ativar o “assinante”. O que o “assinante” recebe? ::: Finally, how do you remove or delete a retained message? You have to publish a blank message with the retain flag set to true. Try it. :::info Exercício final… :question: 6.- Crie grupos de dois ou três membros. Crie um aplicativo de chat bem básico, onde todas as mensagens postadas de qualquer um dos membros são recebidas apenas pelos membros do mesmo grupo. ler texto do teclado em python pode ser feito com: name = input("Enter text: ") :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully