MQTT to rfSwitch Bridge

send rfSwitch codes via mqtt
This commit is contained in:
Arne Baeumler 2017-07-02 14:30:01 +02:00
parent b6ae6d93f5
commit f52eed2cde

View File

@ -0,0 +1,109 @@
/* Usage:
ESP will subscribe to mqtt topic "ssid/macAddress" waiting for tri State codes to be sent.
Where
- "ssid" is the ssid of the wifi, the esp will connect and
- "macAddress" is the hardware address of the esp itself
Upon mqtt connect the device will publish an "online" message to the same topic.
To send commands to the device use mosquitto_pub e.g.
mosquitto_pub -t myWifi/18fe349bde2c -m '0FF00FF0FFF0'
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <RCSwitch.h>
// Update these with values suitable for your network.
const char* ssid = "myWifi";
const char* password = "s3cr3t";
const char* mqtt_server = "mqtt.is.sexy";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient mqttClient(espClient);
RCSwitch rcSwitch = RCSwitch();
char mac[13];
char mqttTopic[65];
void setup() {
Serial.begin(115200);
setup_wifi();
setup_mqtt();
setup_rcSwitch();
}
void setup_rcSwitch() {
rcSwitch.enableTransmit(2);
}
void setup_mqtt() {
mqttClient.setServer(mqtt_server, mqtt_port);
mqttClient.setCallback(mqtt_recv);
snprintf (mqttTopic, 64, "%s/%s", ssid, mac);
}
void setup_wifi() {
Serial.println();
uint8_t mac_t[6];
WiFi.macAddress(mac_t);
sprintf(mac,"%02x%02x%02x%02x%02x%02x",mac_t[0],mac_t[1],mac_t[2],mac_t[3],mac_t[4],mac_t[5]);
Serial.println(sprintf("Client MAC Address: %s",mac));
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.print(" IP address: ");
Serial.println(WiFi.localIP());
}
void mqtt_recv(char* topic, byte* payload, unsigned int length) {
/*
Serial.print(topic);
Serial.print(": ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
*/
char *cmd = (char*)malloc(length + 2);
snprintf(cmd,length + 1,"%s",(char*)payload);
mqttClient.publish("esp8266/debug",cmd);
rcSwitch.sendTriState((char*)cmd);
delay(1000);
}
void mqtt_reconnect() {
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
if (mqttClient.connect("ESP8266Client")) {
Serial.println("connected");
mqttClient.publish(mqttTopic, "reconnected");
mqttClient.subscribe(mqttTopic);
} else {
Serial.print("failed, rc=");
Serial.print(mqttClient.state());
Serial.println();
delay(5000);
}
}
if(mqttClient.loop()) {
delay(200);
}
}
void loop() {
mqtt_reconnect();
}