adding mqtt resources
This commit is contained in:
1 parent
54476f6d7b
commit
b683ed2b94
13 files changed
+351
-112
No files matched your search
@@ -1 +0,0 @@
|
|||||||
,timbot,timbot,22.10.2026 17:16,file:///home/timbot/.config/libreoffice/4;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
,timbot,timbot,22.10.2026 17:40,file:///home/timbot/.config/libreoffice/4;
|
|
||||||
Binary file not shown.
Binary file not shown.
+56
-54
@@ -1,82 +1,84 @@
|
|||||||
# 🌐 The Internet of Things (IoT)
|
# 🔩 Through-Hole vs. Surface-Mount Components in Electronics
|
||||||
|
|
||||||
## 📡 What Is IoT?
|
In electronics design and assembly, components generally fall into two categories based on how they are mounted to the circuit board:
|
||||||
|
|
||||||
The **Internet of Things (IoT)** refers to a network of **interconnected devices** that collect, exchange, and act on data via the Internet. These "things" can include sensors, smart appliances, wearables, and industrial machines — essentially any physical object embedded with electronics and network connectivity.
|
- **Through-Hole Technology (THT)**
|
||||||
|
- **Surface-Mount Technology (SMT)**
|
||||||
|
|
||||||
IoT enables real-time monitoring, automation, and control across various sectors, such as:
|
Both have unique advantages and are suited for different applications.
|
||||||
|
|
||||||
- Smart homes (e.g. smart thermostats, lighting)
|
|
||||||
- Industrial automation (IIoT)
|
|
||||||
- Agriculture (smart irrigation)
|
|
||||||
- Healthcare (wearable health monitors)
|
|
||||||
- Environmental sensing
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ⚙️ How Devices Fit Into the IoT Ecosystem
|
## 🧷 Through-Hole Components (THT)
|
||||||
|
|
||||||
### 🧠 Microcontrollers (MCUs)
|
### 🔍 Description:
|
||||||
|
Through-hole components have long metal leads that are inserted into **drilled holes** on the PCB and soldered on the opposite side.
|
||||||
|
|
||||||
Microcontrollers are **small, energy-efficient computers on a chip**. They are typically used to:
|
### ✅ Strengths:
|
||||||
|
- **Strong mechanical bonds** – Ideal for components that face physical stress (e.g., connectors, switches).
|
||||||
|
- **Easier to prototype and test** – Can be used with breadboards and perfboards.
|
||||||
|
- **Simpler for beginners** – Leads are easier to handle and solder by hand.
|
||||||
|
|
||||||
- **Read sensor data**
|
### ❌ Weaknesses:
|
||||||
- **Control actuators** (like motors, relays, LEDs)
|
- **Larger footprint** – Takes up more board space and limits component density.
|
||||||
- **Execute simple, real-time tasks**
|
- **Slower manufacturing** – Requires drilling, increasing production time and cost.
|
||||||
- **Communicate wirelessly** (if supported)
|
- **Not ideal for automation** – Less compatible with modern pick-and-place machines.
|
||||||
|
|
||||||
#### Common IoT Microcontrollers:
|
### 🧠 Use Cases:
|
||||||
| Device | Key Role in IoT |
|
- Prototyping and education
|
||||||
|-----------------|-------------------------------------------|
|
- High-reliability systems (e.g., aerospace, military)
|
||||||
| **Arduino Uno/Nano** | Basic sensors, automation, beginners |
|
- Components under physical load (e.g., large capacitors, connectors)
|
||||||
| **ESP32** | Advanced wireless control with Wi-Fi/BLE |
|
|
||||||
| **Arduino Nano** | Compact, breadboard-friendly microcontroller |
|
|
||||||
|
|
||||||
These devices often run standalone, programmed with simple C/C++ code, and interact directly with the physical world.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 💻 Single Board Computers (SBCs)
|
## 📎 Surface-Mount Components (SMT)
|
||||||
|
|
||||||
SBCs are **full-featured mini computers** capable of running operating systems like **Linux**. In IoT systems, they typically serve as **gateways**, **data processors**, or **user interfaces**.
|
### 🔍 Description:
|
||||||
|
Surface-mount components are soldered **directly onto the surface** of the PCB without the need for holes.
|
||||||
|
|
||||||
#### Popular SBC:
|
### ✅ Strengths:
|
||||||
| Device | Role in IoT |
|
- **Compact size** – Enables high-density, miniaturized designs.
|
||||||
|-------------------|-------------------------------------------|
|
- **Automated assembly** – Compatible with pick-and-place machines and reflow ovens.
|
||||||
| **Raspberry Pi** | Local servers, edge computing, dashboards |
|
- **Faster, cheaper production** – No drilling, more efficient assembly lines.
|
||||||
|
|
||||||
The **Raspberry Pi** is commonly used to:
|
### ❌ Weaknesses:
|
||||||
|
- **Harder to handle manually** – Tiny size makes hand-soldering more difficult.
|
||||||
|
- **Less durable mechanically** – Weaker than through-hole in high-stress applications.
|
||||||
|
- **Not breadboard-friendly** – Requires custom PCBs for prototyping.
|
||||||
|
|
||||||
- Act as a **hub** or **gateway** for a network of microcontrollers
|
### 🧠 Use Cases:
|
||||||
- Host local databases and dashboards
|
- Consumer electronics (phones, laptops, wearables)
|
||||||
- Communicate with cloud services (e.g., AWS IoT, Azure IoT)
|
- Mass-produced circuit boards
|
||||||
- Handle complex processing or image recognition tasks
|
- Space-constrained designs (IoT, embedded systems)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🔁 SBC + Microcontroller Collaboration
|
## ⚔️ Side-by-Side Comparison
|
||||||
|
|
||||||
In many IoT applications, SBCs and microcontrollers **work together**:
|
| Feature | Through-Hole (THT) | Surface-Mount (SMT) |
|
||||||
|
|--------------------------|------------------------------|------------------------------|
|
||||||
### Example Setup:
|
| Mounting Method | Leads through drilled holes | Mounted directly on surface |
|
||||||
- 🧭 **Arduino or ESP32** collects sensor data and controls devices
|
| Size | Larger | Smaller |
|
||||||
- 💬 Sends data to **Raspberry Pi** via serial, MQTT, or Wi-Fi
|
| Mechanical Strength | Stronger | Weaker under stress |
|
||||||
- 📊 **Raspberry Pi** logs the data, analyzes it, and uploads it to the cloud
|
| Manual Soldering | Easier | Harder (requires fine tools) |
|
||||||
|
| Breadboard Compatibility | Yes | No |
|
||||||
This hybrid approach combines:
|
| Automation Compatibility | Less suitable | Highly suitable |
|
||||||
- **Real-time, low-power responsiveness** of microcontrollers
|
| Typical Use | Prototyping, heavy-duty | Mass production, compact designs |
|
||||||
- With the **computational power and network versatility** of SBCs
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🧠 Summary
|
## 🧪 Which Should You Use?
|
||||||
|
|
||||||
| Component | Purpose in IoT |
|
- Choose **through-hole** for:
|
||||||
|--------------------|------------------------------------------|
|
- Learning and prototyping
|
||||||
| **Microcontroller**| Simple, real-time control and sensing |
|
- Mechanically stressed components
|
||||||
| **SBC (e.g., Pi)** | Processing, cloud communication, UI |
|
- Simple, low-volume builds
|
||||||
| **Together** | Full-stack edge IoT systems |
|
|
||||||
|
- Choose **surface-mount** for:
|
||||||
|
- Compact and high-density designs
|
||||||
|
- Automated manufacturing
|
||||||
|
- Professional or commercial projects
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
The IoT thrives on collaboration between simple embedded devices and smarter processing units — a perfect example of **hardware synergy** in the modern world. 🌍📶💡
|
Understanding the strengths of both THT and SMT helps you design smarter circuits, whether you're hand-soldering your first board or designing a commercial IoT product. 🔧⚡
|
||||||
+58
-56
@@ -1,84 +1,86 @@
|
|||||||
# 🔩 Through-Hole vs. Surface-Mount Components in Electronics
|
# 🌐 The Internet of Things (IoT)
|
||||||
|
|
||||||
In electronics design and assembly, components generally fall into two categories based on how they are mounted to the circuit board:
|
## 📡 What Is IoT?
|
||||||
|
|
||||||
- **Through-Hole Technology (THT)**
|
The **Internet of Things (IoT)** refers to a network of **interconnected devices** that collect, exchange, and act on data via the Internet. These "things" can include sensors, smart appliances, wearables, and industrial machines — essentially any physical object embedded with electronics and network connectivity.
|
||||||
- **Surface-Mount Technology (SMT)**
|
|
||||||
|
|
||||||
Both have unique advantages and are suited for different applications.
|
IoT enables real-time monitoring, automation, and control across various sectors, such as:
|
||||||
|
|
||||||
|
- Smart homes (e.g. smart thermostats, lighting)
|
||||||
|
- Industrial automation (IIoT)
|
||||||
|
- Agriculture (smart irrigation)
|
||||||
|
- Healthcare (wearable health monitors)
|
||||||
|
- Environmental sensing
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🧷 Through-Hole Components (THT)
|
## ⚙️ How Devices Fit Into the IoT Ecosystem
|
||||||
|
|
||||||
### 🔍 Description:
|
### 🧠 Microcontrollers (MCUs)
|
||||||
Through-hole components have long metal leads that are inserted into **drilled holes** on the PCB and soldered on the opposite side.
|
|
||||||
|
|
||||||
### ✅ Strengths:
|
Microcontrollers are **small, energy-efficient computers on a chip**. They are typically used to:
|
||||||
- **Strong mechanical bonds** – Ideal for components that face physical stress (e.g., connectors, switches).
|
|
||||||
- **Easier to prototype and test** – Can be used with breadboards and perfboards.
|
|
||||||
- **Simpler for beginners** – Leads are easier to handle and solder by hand.
|
|
||||||
|
|
||||||
### ❌ Weaknesses:
|
- **Read sensor data**
|
||||||
- **Larger footprint** – Takes up more board space and limits component density.
|
- **Control actuators** (like motors, relays, LEDs)
|
||||||
- **Slower manufacturing** – Requires drilling, increasing production time and cost.
|
- **Execute simple, real-time tasks**
|
||||||
- **Not ideal for automation** – Less compatible with modern pick-and-place machines.
|
- **Communicate wirelessly** (if supported)
|
||||||
|
|
||||||
### 🧠 Use Cases:
|
#### Common IoT Microcontrollers:
|
||||||
- Prototyping and education
|
| Device | Key Role in IoT |
|
||||||
- High-reliability systems (e.g., aerospace, military)
|
|-----------------|-------------------------------------------|
|
||||||
- Components under physical load (e.g., large capacitors, connectors)
|
| **Arduino Uno/Nano** | Basic sensors, automation, beginners |
|
||||||
|
| **ESP32** | Advanced wireless control with Wi-Fi/BLE |
|
||||||
|
| **Arduino Nano** | Compact, breadboard-friendly microcontroller |
|
||||||
|
|
||||||
|
These devices often run standalone, programmed with simple C/C++ code, and interact directly with the physical world.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📎 Surface-Mount Components (SMT)
|
### 💻 Single Board Computers (SBCs)
|
||||||
|
|
||||||
### 🔍 Description:
|
SBCs are **full-featured mini computers** capable of running operating systems like **Linux**. In IoT systems, they typically serve as **gateways**, **data processors**, or **user interfaces**.
|
||||||
Surface-mount components are soldered **directly onto the surface** of the PCB without the need for holes.
|
|
||||||
|
|
||||||
### ✅ Strengths:
|
#### Popular SBC:
|
||||||
- **Compact size** – Enables high-density, miniaturized designs.
|
| Device | Role in IoT |
|
||||||
- **Automated assembly** – Compatible with pick-and-place machines and reflow ovens.
|
|-------------------|-------------------------------------------|
|
||||||
- **Faster, cheaper production** – No drilling, more efficient assembly lines.
|
| **Raspberry Pi** | Local servers, edge computing, dashboards |
|
||||||
|
|
||||||
### ❌ Weaknesses:
|
The **Raspberry Pi** is commonly used to:
|
||||||
- **Harder to handle manually** – Tiny size makes hand-soldering more difficult.
|
|
||||||
- **Less durable mechanically** – Weaker than through-hole in high-stress applications.
|
|
||||||
- **Not breadboard-friendly** – Requires custom PCBs for prototyping.
|
|
||||||
|
|
||||||
### 🧠 Use Cases:
|
- Act as a **hub** or **gateway** for a network of microcontrollers
|
||||||
- Consumer electronics (phones, laptops, wearables)
|
- Host local databases and dashboards
|
||||||
- Mass-produced circuit boards
|
- Communicate with cloud services (e.g., AWS IoT, Azure IoT)
|
||||||
- Space-constrained designs (IoT, embedded systems)
|
- Handle complex processing or image recognition tasks
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ⚔️ Side-by-Side Comparison
|
## 🔁 SBC + Microcontroller Collaboration
|
||||||
|
|
||||||
| Feature | Through-Hole (THT) | Surface-Mount (SMT) |
|
In many IoT applications, SBCs and microcontrollers **work together**:
|
||||||
|--------------------------|------------------------------|------------------------------|
|
|
||||||
| Mounting Method | Leads through drilled holes | Mounted directly on surface |
|
### Example Setup:
|
||||||
| Size | Larger | Smaller |
|
- 🧭 **Arduino or ESP32** collects sensor data and controls devices
|
||||||
| Mechanical Strength | Stronger | Weaker under stress |
|
- 💬 Sends data to **Raspberry Pi** via serial, MQTT, or Wi-Fi
|
||||||
| Manual Soldering | Easier | Harder (requires fine tools) |
|
- 📊 **Raspberry Pi** logs the data, analyzes it, and uploads it to the cloud
|
||||||
| Breadboard Compatibility | Yes | No |
|
|
||||||
| Automation Compatibility | Less suitable | Highly suitable |
|
This hybrid approach combines:
|
||||||
| Typical Use | Prototyping, heavy-duty | Mass production, compact designs |
|
- **Real-time, low-power responsiveness** of microcontrollers
|
||||||
|
- With the **computational power and network versatility** of SBCs
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🧪 Which Should You Use?
|
## 🧠 Summary
|
||||||
|
|
||||||
- Choose **through-hole** for:
|
| Component | Purpose in IoT |
|
||||||
- Learning and prototyping
|
|--------------------|------------------------------------------|
|
||||||
- Mechanically stressed components
|
| **Microcontroller**| Simple, real-time control and sensing |
|
||||||
- Simple, low-volume builds
|
| **SBC (e.g., Pi)** | Processing, cloud communication, UI |
|
||||||
|
| **Together** | Full-stack edge IoT systems |
|
||||||
- Choose **surface-mount** for:
|
|
||||||
- Compact and high-density designs
|
|
||||||
- Automated manufacturing
|
|
||||||
- Professional or commercial projects
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
Understanding the strengths of both THT and SMT helps you design smarter circuits, whether you're hand-soldering your first board or designing a commercial IoT product. 🔧⚡
|
The IoT thrives on collaboration between simple embedded devices and smarter processing units — a perfect example of **hardware synergy** in the modern world. 🌍📶💡
|
||||||
|
|
||||||
|
-----------------------------------
|
||||||
|
|
||||||
|
|
||||||
Binary file not shown.
@@ -0,0 +1,115 @@
|
|||||||
|
# How MQTT Works:
|
||||||
|
|
||||||
|
## What is MQTT
|
||||||
|
MQTT (Message Queuing Telemetry Transport) is a lightweight, bidirectional messaging protocol designed for resource-constrained devices and low-bandwidth networks. It operates on a publish/subscribe architecture that decouples message senders from receivers, allowing for scalable and efficient machine-to-machine communication.
|
||||||
|
|
||||||
|
### Core Components and Workflow
|
||||||
|
|
||||||
|
* MQTT Broker: A central server that acts as the intermediary, receiving all messages, filtering them, and distributing them to the appropriate recipients.
|
||||||
|
* MQTT Clients: Any device or application (from microcontrollers to servers) that connects to the broker to either send or receive data.
|
||||||
|
* Topics: Hierarchical labels (similar to file paths) that clients use to organize and subscribe to specific streams of data.
|
||||||
|
|
||||||
|
The process functions as follows: Clients establish a persistent TCP/IP connection with the broker by exchanging CONNECT and CONNACK packets. Publishers send messages with a specific topic and payload to the broker, while subscribers send SUBSCRIBE requests to express interest in topics. The broker then forwards published messages to all clients subscribed to that topic, ensuring that publishers and subscribers never communicate directly.
|
||||||
|
|
||||||
|
### Key Features
|
||||||
|
|
||||||
|
* Quality of Service (QoS): MQTT offers three levels of delivery guarantee: QoS 0 (at most once/fire-and-forget), QoS 1 (at least once/acknowledged), and QoS 2 (exactly once/four-way handshake), allowing users to balance reliability against bandwidth usage.
|
||||||
|
* Efficiency: It uses a minimal 2-byte fixed header and binary encoding to minimize data transmission overhead.
|
||||||
|
* State Management: The broker can buffer messages for disconnected clients, support retained messages (the last known state of a topic), and utilize Last Will and Testament (LWT) to notify subscribers if a client disconnects unexpectedly.
|
||||||
|
|
||||||
|
---
|
||||||
|
## Installing an MQTT Broker
|
||||||
|
|
||||||
|
To install Mosquitto MQTT on Ubuntu, use the package manager for the stable version or add the official Personal Package Archive (PPA) for the latest release.
|
||||||
|
|
||||||
|
### Standard Installation (Stable Version)
|
||||||
|
|
||||||
|
For most Ubuntu versions (including 20.04, 22.04, and 24.04), Mosquitto is available in the default repositories.
|
||||||
|
|
||||||
|
1. Update package lists:
|
||||||
|
|
||||||
|
`sudo apt update`
|
||||||
|
|
||||||
|
2. Install the broker and client utilities:
|
||||||
|
|
||||||
|
`sudo apt install -y mosquitto mosquitto-clients`
|
||||||
|
|
||||||
|
By default in Ubuntu this will start the MQTT broker as a service using systemctl.
|
||||||
|
|
||||||
|
### Update Configuration
|
||||||
|
As of Mosquitto v2 remote access of the broker is turned off. If you are happy with your network security you can turn on anonymous clients, or you can secure it with a password.
|
||||||
|
|
||||||
|
`sudo nano /etc/mosquitto/mosquitto.conf`
|
||||||
|
|
||||||
|
Add the following to the configuration file:
|
||||||
|
|
||||||
|
```
|
||||||
|
# Bind MQTT to port 1883 on all available network interfaces
|
||||||
|
listener 1883 0.0.0.0
|
||||||
|
allow_anonymous true
|
||||||
|
```
|
||||||
|
|
||||||
|
Restart the service:
|
||||||
|
|
||||||
|
`sudo systemctl restart mosquitto`
|
||||||
|
|
||||||
|
You can also manually run the service in the command-line if you do not wish to have it auto-start. Stop the service, then run:
|
||||||
|
|
||||||
|
`sudo mosquitto -v -c /etc/mosquitto/mosquitto.conf`
|
||||||
|
|
||||||
|
To check what is listening on a particular port, in this case 1883, check using lsof:
|
||||||
|
|
||||||
|
`sudo lsof -i :1883`
|
||||||
|
|
||||||
|
If necessary you can kill the running application using the PID number.
|
||||||
|
|
||||||
|
### Verification
|
||||||
|
Test the installation by checking the service status and version:
|
||||||
|
```
|
||||||
|
sudo systemctl status mosquitto
|
||||||
|
mosquitto -v
|
||||||
|
```
|
||||||
|
|
||||||
|
### Uninstallation
|
||||||
|
To completely uninstall Mosquitto from Ubuntu, you should first stop the service, then remove the packages and configuration files using apt.
|
||||||
|
|
||||||
|
1. Stop the Service: Prevent conflicts during removal.
|
||||||
|
`sudo systemctl stop mosquitto`
|
||||||
|
2. Remove Packages and Configs: Use purge to delete the software and its configuration files, and --auto-remove to delete dependencies no longer needed.
|
||||||
|
|
||||||
|
`sudo apt-get purge --auto-remove mosquitto mosquitto-clients`
|
||||||
|
|
||||||
|
3. Remove Repository (Optional): If you added the official Mosquitto PPA, remove it to keep your package sources clean.
|
||||||
|
|
||||||
|
`sudo add-apt-repository --remove ppa:mosquitto-dev/mosquitto-ppa`
|
||||||
|
|
||||||
|
### Port Conflicts
|
||||||
|
If something is already using the port 1883 that Mosquitto wants to use you can kill the other process using the 'fuser' command.
|
||||||
|
|
||||||
|
`sudo fuser -k 1883/tcp`
|
||||||
|
|
||||||
|
### Installing Clients
|
||||||
|
|
||||||
|
There are a wide variety of clients available. These do not need the full functionality of the broker so they can be very lightweight.
|
||||||
|
|
||||||
|
If you device is network-enabled, such as a pico-w, there are arduino clients for MQTT.
|
||||||
|
|
||||||
|
If your device is connected to a computer, it can send messages through serial to an applciation that then uses a client to publish and subscribe to the broker.
|
||||||
|
|
||||||
|
Try setting up a virtual environment, and running the python application included here.
|
||||||
|
|
||||||
|
`python3 -m venv .venv`
|
||||||
|
|
||||||
|
Then activate the virtual environment:
|
||||||
|
|
||||||
|
`source .venv/bin/activate`
|
||||||
|
|
||||||
|
To deactivate the virtual environment:
|
||||||
|
|
||||||
|
`deactivate`
|
||||||
|
|
||||||
|
Now pip install the dependencies for the python based mqtt client:
|
||||||
|
|
||||||
|
`pip install paho-mqtt`
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import time
|
||||||
|
import signal
|
||||||
|
import paho.mqtt.client as mqtt
|
||||||
|
|
||||||
|
BROKER = "localhost"
|
||||||
|
PORT = 1883
|
||||||
|
TOPIC = "python/mqtt/test"
|
||||||
|
|
||||||
|
def on_connect(client, userdata, flags, reason_code, properties):
|
||||||
|
print(f"Connected (rc={reason_code})")
|
||||||
|
client.subscribe(TOPIC)
|
||||||
|
|
||||||
|
def on_message(client, userdata, msg):
|
||||||
|
print(f"[{msg.topic}] {msg.payload.decode()}")
|
||||||
|
|
||||||
|
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
|
||||||
|
client.on_connect = on_connect
|
||||||
|
client.on_message = on_message
|
||||||
|
|
||||||
|
client.connect(BROKER, PORT, 60)
|
||||||
|
client.loop_start()
|
||||||
|
|
||||||
|
# Publish one test message
|
||||||
|
time.sleep(2)
|
||||||
|
client.publish(TOPIC, "Hello from Paho MQTT!", qos=1)
|
||||||
|
print("Published. Listening... (Ctrl+C to exit)")
|
||||||
|
|
||||||
|
# Block forever until SIGINT
|
||||||
|
signal.pause()
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
#include <Arduino.h>
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
// Initialize serial communication at 9600 baud
|
||||||
|
Serial.begin(9600);
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
// Simulate a temperature reading (replace with actual sensor logic if needed)
|
||||||
|
float temperature = 25.5; // Example value in Celsius
|
||||||
|
|
||||||
|
// Print the temperature message to the serial monitor
|
||||||
|
Serial.print("Temperature: ");
|
||||||
|
Serial.print(temperature);
|
||||||
|
Serial.println(" °C");
|
||||||
|
|
||||||
|
// Wait for 5 seconds before sending the next message
|
||||||
|
delay(5000);
|
||||||
|
}
|
||||||
Whitespace-only changes.
@@ -0,0 +1,32 @@
|
|||||||
|
import serial
|
||||||
|
import time
|
||||||
|
|
||||||
|
# Configure the serial port
|
||||||
|
# Replace 'COM4' (Windows) or '/dev/ttyACM0' (Linux/Mac) with your Arduino's port
|
||||||
|
# Ensure the baud rate matches the one used in your Arduino sketch (e.g., Serial.begin(9600))
|
||||||
|
port = '/dev/ttyACM0'
|
||||||
|
baud_rate = 9600
|
||||||
|
timeout = 1
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Open the serial port
|
||||||
|
ser = serial.Serial(port, baud_rate, timeout=timeout)
|
||||||
|
time.sleep(2) # Wait for the connection to establish (Arduino reset delay)
|
||||||
|
|
||||||
|
print("Listening for messages...")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
# Check if data is available
|
||||||
|
if ser.in_waiting > 0:
|
||||||
|
# Read a line from the serial port
|
||||||
|
message = ser.readline().decode('utf-8').rstrip()
|
||||||
|
print(f"Received: {message}")
|
||||||
|
|
||||||
|
except serial.SerialException as e:
|
||||||
|
print(f"Error opening serial port: {e}")
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\nExiting...")
|
||||||
|
finally:
|
||||||
|
if 'ser' in locals() and ser.is_open:
|
||||||
|
ser.close()
|
||||||
|
print("Serial port closed.")
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import time
|
||||||
|
import paho.mqtt.client as mqtt
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
BROKER = "localhost" # Public test broker
|
||||||
|
PORT = 1883
|
||||||
|
TOPIC = "python/mqtt/test"
|
||||||
|
|
||||||
|
def on_connect(client, userdata, flags, reason_code, properties):
|
||||||
|
print(f"Connected with result code {reason_code}")
|
||||||
|
# Subscribe to the topic immediately upon connection
|
||||||
|
client.subscribe(TOPIC)
|
||||||
|
|
||||||
|
def on_message(client, userdata, msg):
|
||||||
|
print(f"Received message on {msg.topic}: {msg.payload.decode()}")
|
||||||
|
|
||||||
|
# Create client instance
|
||||||
|
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
|
||||||
|
client.on_connect = on_connect
|
||||||
|
client.on_message = on_message
|
||||||
|
|
||||||
|
# Connect to broker
|
||||||
|
try:
|
||||||
|
client.connect(BROKER, PORT, 60)
|
||||||
|
client.loop_start() # Start network loop in a background thread
|
||||||
|
|
||||||
|
# Publish a message
|
||||||
|
time.sleep(2) # Wait for subscription to settle
|
||||||
|
client.publish(TOPIC, "Hello from Paho MQTT!", qos=1)
|
||||||
|
print("Message published.")
|
||||||
|
|
||||||
|
# Keep running to receive messages
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error: {e}")
|
||||||
|
finally:
|
||||||
|
# how to disconnect
|
||||||
|
# client.loop_stop()
|
||||||
|
# client.disconnect()
|
||||||
|
print("Disconnected.")
|
||||||
|
|
||||||
Reference in new issue
Block a user