Skip to content

Instantly share code, notes, and snippets.

@mugifly
Last active March 17, 2019 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mugifly/8e5a0aa81ca4a2485b2c2b46e0968fc6 to your computer and use it in GitHub Desktop.
Save mugifly/8e5a0aa81ca4a2485b2c2b46e0968fc6 to your computer and use it in GitHub Desktop.
ESP8266 + DS18B20 One-Wire Temperature Sensor (Works with Hass.io)
// ESP8266 + DS18B20 One-Wire Temperature Sensor (Works with Hass.io)
// https://gist.github.com/mugifly/8e5a0aa81ca4a2485b2c2b46e0968fc6
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <timer.h>
// 設定 - Wi-Fi
#define WLAN_SSID "XXXXXX"
#define WLAN_KEY "XXXXXX"
// 設定 - Home Assistant (Hass.io)
#define HA_HOST "XXXXXX"
#define HA_HTTPS_PORT 443
#define HA_HTTPS_SHA1_FINGER_PRINT "" // 証明書チェックする場合は "XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX" のように指定
#define HA_ENTITY_ID "sensor.special_esp_temp_0"
#define HA_ACCESS_TOKEN "XXXXX"
// 設定 - 測定間隔 (ミリ秒)
#define SENSING_INTERVAL_MSEC 30000
// 設定 - 温度センサの接続ピン
#define ONE_WIRE_BUS 12
// ----
// 温度センサと通信するためのインスタンス
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
// タイマーのインスタンス
auto timer = timer_create_default();
void setup () {
Serial.begin(9600);
// 温度センサとの通信を開始
sensors.begin();
// Wi-Fi アクセスポイントへ接続
connectWiFi();
// 初回計測を実行
updateTemp(NULL);
// タイマーを設定
timer.every(SENSING_INTERVAL_MSEC, updateTemp);
}
void connectWiFi () {
// Wi-Fi アクセスポイントへ接続
Serial.print("Connecting to " + String(WLAN_SSID) + "...");
WiFi.mode(WIFI_STA);
WiFi.begin(WLAN_SSID, WLAN_KEY);
// 接続完了まで待機
int wait_counter = 0;
while (WiFi.status() != WL_CONNECTED) {
if (20 < wait_counter) { // 一定時間経過したときは
// 一旦スリープ状態へ移行させる
Serial.println("\nRetrying...");
wait_counter = 0;
ESP.deepSleep(5 * 1000 * 1000, WAKE_RF_DEFAULT);
delay(1000);
}
Serial.print(".");
wait_counter++;
delay(1000);
}
Serial.println("Done.");
// IPアドレスを表示
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
bool updateTemp (void *) {
// 温度センサから温度を取得
Serial.print("Getting temperature... ");
sensors.requestTemperatures();
float temp = sensors.getTempCByIndex(0);
Serial.println(temp);
// 送信するデータを生成
char post_body[128];
sprintf(post_body, "{\"state\": %.1f, \"attributes\": {\"unit_of_measurement\": \"°C\"}}", temp);
Serial.println(post_body);
// Wi-Fi の接続状態を確認
if (WiFi.status() != WL_CONNECTED) { // 接続済みでなければ
Serial.println("Disconnected from Wi-Fi.");
connectWiFi();
}
// 送信
Serial.print("Sending... ");
if (!postToHAServer(post_body)) {
Serial.println("Sending failed.");
} else {
Serial.println("Sent successfully.");
}
// タイマーを継続
return true;
}
bool postToHAServer (String post_body) {
// HTTPS通信のためのクライアントを初期化
WiFiClientSecure client;
// 証明書の検証方法を設定
if (HA_HTTPS_SHA1_FINGER_PRINT == "") {
client.setInsecure(); // 検証しない
} else {
client.setFingerprint(HA_HTTPS_SHA1_FINGER_PRINT); // SHA1 フィンガープリントで検証
}
// サーバへ接続
if (!client.connect(HA_HOST, HA_HTTPS_PORT)) {
return false;
}
// HTTPヘッダを送信
char url[128];
sprintf(url, "/api/states/%s", HA_ENTITY_ID);
client.println("POST " + String(url) + " HTTP/1.1");
client.println("Host: " + String(HA_HOST));
client.println("Authorization: Bearer " + String(HA_ACCESS_TOKEN));
client.println("Content-Type: application/json");
client.print("Content-Length: ");
client.println(post_body.length());
client.println();
// POSTボディを送信
client.println(post_body);
// レスポンスを待機
String response_code_line;
while (client.connected()) {
String response = client.readStringUntil('\n');
if (0 < response.length()) {
response_code_line = response;
break;
}
}
// レスポンスコードを確認
if (response_code_line.indexOf("200") == -1) { // レスポンスのステータスが 200 OK でなければ
Serial.print(response_code_line);
Serial.print("...");
return false;
}
Serial.print("200 OK...");
return true;
}
void loop() {
timer.tick();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment