古人智慧

Just Do it!
上士聞道,勤而行之;中士聞道,若存若亡;下士聞道,大笑之。不笑,不足以爲道。
~ 道德經 41

「實現夢想不是追逐成功,而是在於賦予生命意義,人生中的每個決定與聲音都有其重要含義。」"The key to realizing a dream is to focus not on success but on significance — and then even the small steps and little victories along your path will take on greater meaning."
電視名人-歐普拉·溫芙蕾(OPRAH WINFREY)

搜尋此網誌

Translation

2019年7月12日 星期五

[Home IoT] ESP8266 MQTT Client device (IoT 自動給水器)

IoT萬物聯網是個很大的發展空間,尤其是在家庭應用是最接近我們生活,提供智能互動提升生活水平。
為何做這個項目?
做這個項目主要目的是用一個價格便宜具備WiFi的MCU可以運行MQTT的協議,然後連結週邊的設備,例如貓咪的自動給水器。
另外在Instructables網站上也有細節分享
IoT Internet of Things is a big scope for development, especially in home applications providing intelligent and high quality life.
Why I built this project?
I am doing this because of using a cheaper WiFi-enabled MCU that can run the MQTT protocol and then use the peripheral devices, such as the cat’s automatic water feeder.
I am also share more detail instruction guide here

Project Specification and ID outlook

  1. Basic version(Open source):
    1. connect to a predefined Access-Point SSID and MQTT broker
    2. the relay turn-on/off 3mins periodically , the esp8266 will into deep sleep mode while relay turn-off.
    3. Remote control by MQTT protocol from mobile phone
  2. Advance version(charge by request):
    1. Can be config the turn-on/off timing with webpage(HTML)
    2. Save the setting to RTC memory.
    3. upload sketch by OTA
  3. perfectinal version(charge by request):
    1. Can be config the SSID and MQTT broker by webpage(HTML) dynamically
    2. Can be config the turn-on/off timing by webpage(HTML)
    3. Save those setting into SPIFFS

Step 0: System Block Diagram

Here is my MQTT system
MQTT Broker: Raspberry Pi 3B+ with mosquitto
Python: paho-mqtt
Mobile Phone Apps: IoT Controller v0.37 SNR Lab
MCU: ESP8266

Step 1: Electrics Parts Preparation

BOM list:

1 x ESP6266 12E
1 x 2P relay module
2 x S8050 transistor
2 x 100 ohm resistor
1 x 10uF capacitor
1 x 0.1uF capacitor
1 x LM1117 3.3v module
1 x HLK-PM01 230V AC to 5V/3W DC power module
1 x 5x7cm perfboard
1 x AC Electrical socket

Tools:

1 x 3D printer with PLA filament
1 x Soldering iron

Equipment

1 x Raspberry pi 3B+

Step 2: Make the Main-board and testing

Schematic:

Reference pictures:


Testing

The power supply was made by myself, it is also an open project in hereHandy Power Supply
Upload the sketch to this board by USB2Uart cable shown as the picture as below.
ESP-12F_UART
The testing video

Step 3: Upload the software to ESP8266

Download the sketch
Code: Download
/*
  Basic ESP8266 MQTT for relay controller

  Regis Hsu
  2019-07-10
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ESP8266mDNS.h>        // Include the mDNS library

#define BUILTIN_LED 2
#define RELAY1_PIN 5
#define RELAY2_PIN 4

#define AP_SSID "your-ssid"
#define AP_PASSWD "password"
#define MQTT_BROKER "xxx.xxx.xxx.xxx"

#define MQTT_PUB "Home/esp32_sub"
#define MQTT_SUB "Home/esp32_pub"

#define RELAY_1_ON  3
#define RELAY_1_OFF 3

WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi()
{
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(AP_SSID);
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(AP_SSID, AP_PASSWD);

  int i = 0;
  while ((WiFi.status() != WL_CONNECTED))
  {
    delay(500);
    Serial.print(".");
    digitalWrite(BUILTIN_LED, i % 2);
    i = i + 1;
  }

  //turn off the LED
  digitalWrite(BUILTIN_LED, HIGH);
  randomSeed(micros());
  //   we send our IP address on the WiFi network
  if (!MDNS.begin("esp8266")) {
    Serial.println("Error setting up MDNS responder!");
    while (1) {
      delay(1000);
    }
  }
  Serial.println("mDNS responder started");

  // Add service to MDNS-SD
  MDNS.addService("http", "tcp", 80);
}

void callback(char* topic, byte * payload, unsigned int length) {
  Serial.print(F("Message arrived ["));
  Serial.print(topic);
  Serial.print(F("] "));
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  client.publish(MQTT_PUB, (char *)payload);

  // Switch on the LED if an 1 was received as first character
  switch ((char)payload[0] - 48)
  {
    case 0:
      ESP.restart();
      break;
    case 1:
      digitalWrite(RELAY1_PIN, ((char)payload[1] - 48));
      break;
    case 2:
      digitalWrite(RELAY2_PIN, ((char)payload[1] - 48));
      break;
    default:
      Serial.println(F("Not a command!"));
      break;
  }
}

void reconnect() {
  // Loop until we're reconnected
  //while (!client.connected()) {
  Serial.print(F("Attempting MQTT connection..."));
  // Create a random client ID
  String clientId = "ESP8266-";
  clientId += String(random(0xffff), HEX);
  // Attempt to connect
  if (client.connect(clientId.c_str())) {
    Serial.println(F("connected"));
    // Once connected, publish an announcement...
    //client.publish("Home/esp32_pub", "hello world");
    // ... and resubscribe
    client.subscribe(MQTT_SUB);
  } else {
    Serial.print(F("failed, rc="));
    Serial.print(client.state());
    Serial.println(F(" try again in few seconds"));
    // Wait 5 seconds before retrying
    delay(5000);
    //delay(2000);
  }
  //}
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);    // Initialize the BUILTIN_LED pin as an output
  pinMode(RELAY1_PIN, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  pinMode(RELAY2_PIN, OUTPUT);

  Serial.begin(115200);
  delay(500);
  Serial.println();

  digitalWrite(RELAY1_PIN, HIGH);

  setup_wifi();
  client.setServer(MQTT_BROKER, 1883);
  client.setCallback(callback);
  if (!client.connected()) {
    reconnect();
  }
  client.publish(MQTT_PUB, "11");
}

void loop()
{
  if (!client.connected()) {
    reconnect();
  }
  else
    client.loop();

  long now = millis();

  if (now > (RELAY_1_ON * 60 * 1000)) { //ms
    client.publish(MQTT_PUB, "10");
    Serial.printf("Going into deep sleep for %d mins", RELAY_1_OFF);
    client.loop();
    delay(2000);
    ESP.deepSleep(RELAY_1_OFF * 60 * 1000000); //us
  }
}

Arduino IDE setting

Be noticed that reserve 1M SPIFFS at least.

Step 4: Setup the MQTT broker

Install MQTT broker and tools

sudo apt update
sudo apt upgrade
sudo apt autoremove
sudo apt autoclean
sudo apt-get install mosquitto mosquitto-clients

Check the broker status

service mosquitto status

Step 5: Download Mobile App and configure the MQTT

I am using this Apps.

I have tested several Apps, but why I suggest this one? Because of it seems easy for my stupid head, It is sure that you can use another one by your personal preference.
how to config the MQTT objects?
Set the MQTT broker server and switch button as well as the log.

Set 6: Verify the MQTT connection

A tool written by Python to verify the connection between ESP8266 and MQTT broker(RPI 3B+) through Wifi.

Here is the process

nano SubscriberTest.py

python SubscriberTest.py

Python code:

# SubscriberTest.py
import paho.mqtt.client as mqtt
import time

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("Home/esp32_sub")
    client.subscribe("Home/esp32_pub")

def on_message(client, userdata, msg):
    #print(msg.topic+" "+str(msg.payload))
    tt = time.localtime(time.time())
    print(str(tt.tm_hour)+":"+str(tt.tm_min)+" "+msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("xxx.xxx.xxx.xxx", 1883, 60)
client.loop_forever()

Running on RPI 3B+

Step 6: Building the Mechanical Parts

I am using Sketchup to build the 3D modeling, it is just for you reference and should do it by yourself.

Step 7: Web page setting (Charge by request)

WebPage for SSID/Password and MQTT Broker

OTA upload sketch

If you need extra request from me, it will be better that make some suitable donation to me: http://paypal.me/RegisHsu

沒有留言:

張貼留言