古人智慧

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

2019年2月16日 星期六

貓抓板 Cat Scratching Pad

當兵時期在營區有養過幾隻狗,但在家裡我不是很喜歡養寵物,每次都剩下我來善後。。。
家裡已經有寵物鼠,最近又多了嬌嬌女-小虎~~
她很酷,不太愛理人。

迎接她,首先想到就是貓抓板
為什麼是貓抓板? 聽說貓很會亂抓傢俱,所以第一時間就想到這個。。。
網上搜尋不少資料,發現貓抓板大多使用瓦楞紙的材料,這也是大紙箱的基本材料。
是的,DIY魂發作!
用3個多小時,做出這個超強貓抓板,而且這嬌嬌女還很喜歡的說~~~~

分享DIY

美圖分享:

2019年1月1日 星期二

Node.js install on Raspbian/Raspberry Pi

最近正學習Google的FirebaseDialogFlow,裡面用到的language是Node.js。
每次學習新的language,安裝套件是最令人頭痛的部分。時常遇到安裝失敗、缺東缺西、版本與Module不合、不然執行會crash~~
我一開始是用
sudo apt install nodejs
後來用了npm安裝各種module都出現權限不足,時常要加上sudo,也搞到自己的code也無法write的權限,經過多方search,使用nvm是最恰當的的安裝方式。

安裝過程

1. 首先,安裝nvm

先到nvm的github - nvm link

https://github.com/creationix/nvm
下面有安裝說明,最重要就是這行,注意注意注意,有關於版號會與我不同,請用最新版本。

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
到這裡nvm安裝OK,最好是把樹莓派reboot。

2. 安裝NodeJs

因為Node一直快速升級,時常會發生不相容情況。
所以要找一個配合Firebase版本也讓我花了好多時間。
目前這樣搭配是最合適,nodejs@8.15.0 + firebase@5.7.2
安裝nodejs

nvm install v8.15.0
安裝OK後,測試一下

node -v
如果出現v8.15.0那就確定ok。

3. 安裝Firebase套件

Google Firebase有提供一組Node的套件,而沒有熱門的Python有點詭異。

npm install firebase
到這裡應該把Firebase套件裝起來。

4. Test code

在$HOME產生一個子目錄來放測試code

mkdir nodejs

cd nodejs
參考這些前人高手文章,建立Firebase database,然後樹莓派用Nodejs來連上Firebase,控制LED燈。

5. 其他用到的指令

nvm ls-remote
nvm ls
nvm alias default 8.15.0

npm list

參考文章