Let's dive into learning the painlessMesh library, a mesh network library designed for ESP8266 and ESP32 boards, facilitating wireless communication between multiple devices in a network. Here's a structured approach to learning this library:
Step 1: Understanding the Basics
What is a Mesh Network?
A mesh network is a local network topology in which the infrastructure nodes (i.e., bridges, switches, and other nodes) connect directly, dynamically, and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data to and from clients.
In the context of painlessMesh, it allows ESP devices to communicate with each other directly and dynamically, enabling features like multi-hop routing.
Key Features of painlessMesh:
Multi-hop Routing: Messages can be routed through intermediate nodes to reach the destination, extending the network range.
Auto-Discovery: Nodes can automatically discover each other.
Message Routing: Efficient routing of messages between nodes.
Callback Functions: For handling incoming messages and other events.
Step 2: Setting Up Your Environment
Hardware Requirements:
ESP8266 or ESP32 development boards (e.g., NodeMCU, ESP32 DevKitC).
USB cable for programming.
Computer with internet access.
Software Requirements:
Arduino IDE (or compatible alternatives like PlatformIO):
Install the Arduino IDE if you haven't already.
Add the ESP8266 or ESP32 board support via the Board Manager.
painlessMesh Library:
Install via the Arduino Library Manager (Search for "painlessMesh").
Alternatively, download from GitLab and manually install.
Step 3: Hands-On Learning
Example 1: Basic Setup and Communication
Connect Your ESP Boards:
Ensure at least two ESP boards are connected and recognized by your computer.
Upload Example Sketches:
Open the Arduino IDE, navigate to File > Examples > painlessMesh > simpleServer and simpleClient.
Upload simpleServer to one board and simpleClient to another.
Observe and Interact:
Use the Serial Monitor to observe the auto-discovery process and communication between the boards.
Experiment with sending messages from the client to the server.
Example 2: Exploring Multi-Hop and JSON Messages
Multi-Hop Setup:
Set up three ESP boards in a linear fashion (Board A -> Board B -> Board C) where Board A and Board C are out of direct range.
Upload a modified version of simpleServer to all boards, ensuring each has a unique ID.
Sending JSON Messages:
Modify the simpleClient sketch to send a JSON message to the server node (Board C) through the mesh network.
Observe how the message is routed through Board B to reach Board C.
Here's an example of how to send a JSON message:
cpp
#include <ArduinoJson.h>
#include "painlessMesh.h"
// Define the mesh
Scheduler userScheduler; // to control your personal task
painlessMesh mesh;
// User stub
void sendMessage() ; // Prototype so PlatformIO doesn't complain
void setup() {
Serial.begin(115200);
//mesh.setDebugMsgTypes( ERROR | MESH_STATUS | CONNECTION | SYNC | COMMUNICATION | GENERAL | MSG_TYPES | REMOTE ); // all types on
mesh.setDebugMsgTypes( ERROR | STARTUP ); // set before init() so that you can see startup messages
mesh.init( "meshBasic", "password123", &userScheduler, MESH_PORT );
mesh.onReceive(&receivedCallback);
mesh.onNewConnection(&newConnectionCallback);
mesh.onChangedConnections(&changedConnectionCallback);
mesh.onNodeTimeAdjusted(&nodeTimeAdjustedCallback);
userScheduler.addTask( sendMessage );
userScheduler.enableAll();
}
void loop() {
userScheduler.execute(); // it will run mesh scheduler as well
mesh.update();
}
void sendMessage() {
DynamicJsonDocument msg(2048);
msg["type"] = "testMessage";
msg["nodeId"] = mesh.getNodeId();
msg["value"] = 42;
mesh.sendBroadcast( msg );
userScheduler.addTask( sendMessage, TASK_SECOND * 10 ); // wait 10s before sending the next message
}
// Needed for painlessMesh library to work with json messages
void receivedCallback( uint32_t from, String &msg ) {
DynamicJsonDocument jsonDoc(2048);
jsonDoc.deserializeJson(msg);
jsonDoc.printTo(Serial);
if (jsonDoc.containsKey("type")) {
if (jsonDoc["type"] == "testMessage") {
Serial.printf("Got a message from node %u: value = %d\n", from, jsonDoc["value"].as<int>());
}
}
}
// -- Callbacks for events within the mesh --
void newConnectionCallback(uint32_t nodeId) {
Serial.printf("--> startHere: New Connection, nodeId = %u\n", nodeId);
}
void changedConnectionCallback() {
Serial.printf("Changed connections\n");
}
void nodeTimeAdjustedCallback(int32_t offset) {
Serial.printf("Adjusted time %d. Offset = %d\n", mesh.getNodeTime(),offset);
}
Step 4: Deep Dive and Advanced Topics
Customizing Node Behavior:
Learn to use callback functions for custom message handling.
Implement node-specific behaviors based on received messages.
Network Optimization:
Study the library's configuration options (e.g., message timeouts, routing algorithms).
Experiment with optimizing network settings for your specific use case.
Optimizing Multi-Hop Routing:
Adjust the MESH_SND_CHANNEL and MESH_RECV_CHANNEL to minimize interference.
Use mesh.setRoot(true) to designate a root node for more stable connections.
Improving JSON Message Efficiency:
Use DynamicJsonDocument efficiently to minimize memory usage.
Optimize JSON structure for smaller payloads.
Integrating with Other Libraries/Services:
Explore integrating painlessMesh with other IoT libraries (e.g., for sensor reading, actuator control) or cloud services.
Example: Integrating with DHT Sensor Library:
Use DHT library to read sensor data.
Send readings over the mesh network using JSON messages.
Step 5: Real-World Project Application
Conceptualize a Project:
Design a mesh network-enabled project, such as:
Smart Home Automation System.
Environmental Monitoring Network.
Interactive Art Installation.
Implement and Refine:
Apply the knowledge gained to implement your project.
Iterate based on performance, reliability, and user experience feedback.
Additional Tips for Mastery
Community Engagement:
Participate in the painlessMesh community (e.g., GitLab issues, forums) to learn from others and share your experiences.
Documentation and Source Code:
Frequently refer to the official documentation for detailed explanations and configuration options.
Explore the library's source code for in-depth understanding of its inner workings.
Troubleshooting Common Issues:
Connection Issues:
Check WiFi channels for interference.
Ensure consistent passwords across nodes.
Message Loss:
Adjust mesh.setRetryDelay() and mesh.setConnectionTimeout() for better reliability.
Monitor network stability using mesh.getNodeList().
By following these structured steps, you'll transition from a beginner to an advanced user of the painlessMesh library, capable of designing and implementing complex mesh network projects with ESP8266 and ESP32 devices.