#include "painlessMesh.h"
#define MESH_PREFIX "meshnt911"
#define MESH_PASSWORD "911pwmesh"
#define MESH_PORT 5555
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 4; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int currbtstate = 0; // current button state
// -------
// NETWORK
// -------
Scheduler userScheduler; // to control your personal task
painlessMesh mesh;
void sendMessage() ; // Prototype
Task taskSendMessage( TASK_SECOND * 1 , TASK_FOREVER, &sendMessage );
void sendMessage() {
String msg = "Hi from node1";
msg += mesh.getNodeId();
mesh.sendBroadcast( msg );
taskSendMessage.setInterval( random( TASK_SECOND * 1, TASK_SECOND * 5 ));
}
// Needed for painless library
void receivedCallback( uint32_t from, String &msg ) {
Serial.printf("startHere: Received from %u msg=%s\n", from, msg.c_str());
}
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 %u. Offset = %d\n", mesh.getNodeTime(),offset);
}
void setup() {
Serial.begin(115200);
Serial.println("Hello, ESP32!");
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
mesh.setDebugMsgTypes( ERROR | STARTUP );
mesh.init( MESH_PREFIX, MESH_PASSWORD, &userScheduler, MESH_PORT );
mesh.onReceive(&receivedCallback);
mesh.onNewConnection(&newConnectionCallback);
mesh.onChangedConnections(&changedConnectionCallback);
mesh.onNodeTimeAdjusted(&nodeTimeAdjustedCallback);
userScheduler.addTask( taskSendMessage );
taskSendMessage.enable();
}
void loop() {
mesh.update();
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
if (currbtstate == 0) {
// turn LED on:
digitalWrite(ledPin, HIGH);
Serial.println("LED ON");
currbtstate = 1;
}
} else {
if (currbtstate == 1) {
// turn LED off:
digitalWrite(ledPin, LOW);
Serial.println("LED OFF");
currbtstate = 0;
}
}
}