Wemos (d4) WiFi sniffing

最近力を入れる所は、WiFi sniffingという技術。

WiFi sniffingとは

ーーーーここからは中国語ーーーー

那么什么是snffer呢?sniffer可以翻译为混杂模式,ESP8266可以进入该模式,接收空中的 IEEE802.11 包。SDK主要提供的接口有:

接口 说明
wifi_promiscuous_enable 开启混杂模式
wifi_promiscuous_set_mac 设置 sniffer 模式时的 MAC 地址过滤
wifi_set_promiscuous_rx_cb 注册混杂模式下的接收数据回调函数,每收到一包数据,都会进入注册的回调函数。
wifi_get_channel 获取信道号
wifi_set_channel 设置信道号,用于混杂模式

ーーーーここまでは中国語ーーーー

応用例として、Amazon bottonをIoT bottonに改造する。そのカギは、このWiFi sniffing技術。Amazon bottonから出るWiFi信号をキャッチし、botton押されたとわかった。

IoT-Cloud-Mobile Kitの対応

推進するIoT-Cloud-Mobile Kitもそれに対応すべく、しばらくsniffingとPOSTの共存、メモリの制限などと格闘して、何度も諦めかけて、遂に安定して動作するようになった。

 

(IoT-Cloud-Mobile Kit)ブレッドボード

プロトタイプボードで実装もした。

Wemosが周りのMAC addressとRSSIは取得でき、TinyWebDB-APIでクラウドに蓄積できた。

 

さらに室内位置情報

蓄積されたMAC addressとRSSIは、出席確認などに活用でき、室内位置情報(Indoor Positioning)のシステムも作りたいね。

 

参考

 

 

 

WeMos (d2) Home Automation

TinyWebDB-APIを利用した、Home Automationの例。

ハードウェア

“IoT-Cloud-Mobile Study Kit”を利用

データ送信

下記のは操作中、数分起き温度、気圧センサーのデータをTinyWebDB-APIテストサーバ(http://tinydb.ml/api/)へ送信する。

送信したデータは、http://tinydb.ml/status/で確認できる。

データ受信

スマートフォンからLED On/Off の指令は受信すると、ESP8266内蔵LEDは点/滅可能になった。

ソースコード

// Sample Arduino Json Web Client
// Downloads and parse http://jsonplaceholder.typicode.com/users/1
//
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!

#include <ArduinoJson.h>
#include <Arduino.h>

#include <Adafruit_BMP280.h>
#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11 
#define BMP_CS 10

Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
 
#define OLED_RESET 0  // GPIO0
Adafruit_SSD1306 OLED(OLED_RESET);

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#define USE_SERIAL Serial

WiFiClient client;

const char* resource = "http://tinywebdb.cf/api/"; // http resource
const unsigned long BAUD_RATE = 9600;      // serial connection speed
const unsigned long HTTP_TIMEOUT = 10000;  // max respone time from server
const size_t MAX_CONTENT_SIZE = 512;       // max size of the HTTP response

#include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager

void configModeCallback (WiFiManager *myWiFiManager) {
  OLED.println("Entered config mode");
  OLED.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  OLED.println(myWiFiManager->getConfigPortalSSID());
  OLED.display(); //output 'display buffer' to screen  
}

HTTPClient http;

void setup() {
    OLED.begin();
    OLED.clearDisplay();
   
    //Add stuff into the 'display buffer'
    OLED.setTextWrap(false);
    OLED.setTextSize(1);
    OLED.setTextColor(WHITE);
    OLED.setCursor(0,0);
    delay(10);

    USE_SERIAL.begin(115200);
   // USE_SERIAL.setDebugOutput(true);

    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    OLED.println("wifiManager autoConnect...");
    OLED.display(); //output 'display buffer' to screen  

    //WiFiManager
    //Local intialization. Once its business is done, there is no need to keep it around
    WiFiManager wifiManager;
    //reset settings - for testing
    //wifiManager.resetSettings();
  
    //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
    wifiManager.setAPCallback(configModeCallback);
  
    //fetches ssid and pass and tries to connect
    //if it does not connect it starts an access point with the specified name
    //here  "AutoConnectAP"
    //and goes into a blocking loop awaiting configuration
    if(!wifiManager.autoConnect()) {
      Serial.println("failed to connect and hit timeout");
      //reset and try again, or maybe put it to deep sleep
      ESP.reset();
      delay(1000);
    } 
  
    //if you get here you have connected to the WiFi
    Serial.println("connected...yeey :)");

    if (!bmp.begin(0x76)) 
    {
      OLED.println("Could not find BMP280");
      OLED.display(); //output 'display buffer' to screen  
      while (1) {}
    }
}

void OLED_show()
{

  OLED.clearDisplay();
  OLED.setCursor(0,0);
  // Print the IP address
  OLED.print("http://");
  OLED.print(WiFi.localIP());
  OLED.println("/");
  OLED.setCursor(0,8);
  OLED.print("Temp = ");
  OLED.print(bmp.readTemperature());
  OLED.println(" Celsius");
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  OLED.setCursor(0,16);
  OLED.print("Pres = ");
  OLED.print(bmp.readPressure());
  OLED.println(" Pascal ");

  OLED.display(); //output 'display buffer' to screen  
}


void loop() {
    OLED_show();
    get_TinyWebDB("Led1");
    delay(10000);
    sensor_TinyWebDB();
    delay(10000);
}

void sensor_TinyWebDB() {    
    int httpCode;
    char  tag[32];
    char  value[128];

    // read values from the sensor
    float pressure = bmp.readPressure();
    float temperature = bmp.readTemperature();

    const size_t bufferSize = JSON_ARRAY_SIZE(2) + JSON_OBJECT_SIZE(3);
    DynamicJsonBuffer jsonBuffer(bufferSize);
    
    JsonObject& root = jsonBuffer.createObject();
    root["sensor"] = "bmp280";
    root["temperature"] = String(temperature);
    root["pressure_hpa"] = String(pressure);
    root.printTo(value);

    USE_SERIAL.printf("[TinyWebDB] %s\n", value);
    USE_SERIAL.printf("ESP8266 Chip id = %08X\n", ESP.getChipId());
    sprintf(tag, "esp8266-%06x", ESP.getChipId());
    httpCode = TinyWebDBStoreValue(tag, value);
    // httpCode will be negative on error
    if(httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        USE_SERIAL.printf("[HTTP] POST... code: %d\n", httpCode);

        if(httpCode == HTTP_CODE_OK) {
            TinyWebDBValueStored();
        }
    } else {
        USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
        TinyWebDBWebServiceError(http.errorToString(httpCode).c_str());
    }

    http.end();

    delay(10000);
}

void get_TinyWebDB(const char* tag0) {    
    int httpCode;
    char  tag[32];
    char  value[128];

    httpCode = TinyWebDBGetValue(tag0);

    // httpCode will be negative on error
    if(httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

        if(httpCode == HTTP_CODE_OK) {
            String payload = http.getString();
            const char * msg = payload.c_str();
            USE_SERIAL.println(payload);
            if (TinyWebDBreadReponseContent(tag, value, msg)){
                TinyWebDBGotValue(tag, value);
            }
        }
    } else {
        USE_SERIAL.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
        TinyWebDBWebServiceError(http.errorToString(httpCode).c_str());
    }

    http.end();

    delay(10000);
}

int TinyWebDBWebServiceError(const char* message)
{
}

// ----------------------------------------------------------------------------------------
// Wp TinyWebDB API
// Action        URL                      Post Parameters  Response
// Get Value     {ServiceURL}/getvalue    tag              JSON: ["VALUE","{tag}", {value}]
// ----------------------------------------------------------------------------------------
int TinyWebDBGetValue(const char* tag)
{
    char url[64];

    sprintf(url, "%s%s?tag=%s", resource, "getvalue/", tag);

    USE_SERIAL.printf("[HTTP] %s\n", url);
    // configure targed server and url
    http.begin(url);
    
    USE_SERIAL.print("[HTTP] GET...\n");
    // start connection and send HTTP header
    int httpCode = http.GET();

    return httpCode;
}

int TinyWebDBGotValue(const char* tag, const char* value)
{
    USE_SERIAL.printf("[TinyWebDB] %s\n", tag);
    USE_SERIAL.printf("[TinyWebDB] %s\n", value);

    OLED.printf("[TinyWebDB] %s:%s\n", tag, value);
    OLED.display(); //output 'display buffer' to screen  
    
    return 0;   
}

// ----------------------------------------------------------------------------------------
// Wp TinyWebDB API
// Action        URL                      Post Parameters  Response
// Store A Value {ServiceURL}/storeavalue tag,value        JSON: ["STORED", "{tag}", {value}]
// ----------------------------------------------------------------------------------------
int TinyWebDBStoreValue(const char* tag, const char* value)
{
    char url[64];
  
    sprintf(url, "%s%s", resource, "storeavalue");
    USE_SERIAL.printf("[HTTP] %s\n", url);

    // POST パラメータ作る
    char params[128];
    sprintf(params, "tag=%s&value=%s", tag, value);
    USE_SERIAL.printf("[HTTP] POST %s\n", params);

    // configure targed server and url
    http.begin(url);

    // start connection and send HTTP header
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    int httpCode = http.POST(params);
    String payload = http.getString();                  //Get the response payload
    Serial.println(payload);    //Print request response payload

    http.end();
    return httpCode;
}

int TinyWebDBValueStored()
{
  
    return 0;   
}


// Parse the JSON from the input string and extract the interesting values
// Here is the JSON we need to parse
// [
//   "VALUE",
//   "LED1",
//   "on",
// ]
bool TinyWebDBreadReponseContent(char* tag, char* value, const char* payload) {
  // Compute optimal size of the JSON buffer according to what we need to parse.
  // See https://bblanchon.github.io/ArduinoJson/assistant/
  const size_t BUFFER_SIZE =
      JSON_OBJECT_SIZE(3)    // the root object has 3 elements
      + MAX_CONTENT_SIZE;    // additional space for strings

  // Allocate a temporary memory pool
  DynamicJsonBuffer jsonBuffer(BUFFER_SIZE);

  // JsonObject& root = jsonBuffer.parseObject(payload);
  JsonArray& root = jsonBuffer.parseArray(payload);
  JsonArray& root_ = root;

  if (!root.success()) {
    Serial.println("JSON parsing failed!");
    return false;
  }

  // Here were copy the strings we're interested in
  strcpy(tag, root_[1]);   // "led1"
  strcpy(value, root_[2]); // "on"

  return true;
}


// Pause for a 1 minute
void wait() {
  Serial.println("Wait 60 seconds");
  delay(60000);
}

 


参考:

  • TinyWebDB-API : https://wordpress.org/plugins/tinywebdb-api/
  • https://techtutorialsx.com/2016/07/21/esp8266-post-requests/

WeMos (c6) Thingspeak

数回JSON関連の実験をしたが、いざTinyWebDBのAPIの実験を始まると、また引っかかるところが多い。

色々と検索してところ、ThingspeakのAPIサンプルが見つかったので、ちょっと曲がり道して試すことに。

センサーの温度と気圧をThingspeakにアップして、動きを見て見る。

まずThingspeakのアカウントを申請して、THINGSPEAK_API_KEYを取得する。

https://thingspeak.com/users/sign_up

次はサンプルを見ながら、プログラミング。

#include <Adafruit_BMP280.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
 
#define OLED_RESET 0  // GPIO0
Adafruit_SSD1306 OLED(OLED_RESET);

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11 
#define BMP_CS 10

Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);


#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

/***************************
 * Begin Settings
 **************************/

const char* host = "http://api.thingspeak.com";
const char* THINGSPEAK_API_KEY = "***********";

// Update every 600 seconds = 10 minutes. Min with Thingspeak is ~20 seconds
const int UPDATE_INTERVAL_SECONDS = 600;

//needed for library
#include <DNSServer.h>
#include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager

void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
}

/***************************
 * End Settings
 **************************/
 
void setup() {
  OLED.begin();
  OLED.clearDisplay();
 
  //Add stuff into the 'display buffer'
  OLED.setTextWrap(false);
  OLED.setTextSize(1);
  OLED.setTextColor(WHITE);
  OLED.setCursor(0,0);
  delay(10);
  
  Serial.begin(115200);
  delay(10);

  // We start by connecting to a WiFi network

  // Connect to WiFi network
  OLED.println("wifiManager autoConnect...");
  OLED.display(); //output 'display buffer' to screen  
 
  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
  //reset settings - for testing
  //wifiManager.resetSettings();

  //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  wifiManager.setAPCallback(configModeCallback);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if(!wifiManager.autoConnect()) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  } 

  // Print the IP address
  OLED.print("http://");
  OLED.print(WiFi.localIP());
  OLED.println("/");
  OLED.println("WiFi connected");
  OLED.display(); //output 'display buffer' to screen  
  
  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");

  if (!bmp.begin(0x76)) 
  {
    OLED.println("Could not find BMP180 or BMP085 sensor at 0x77");
    OLED.display(); //output 'display buffer' to screen  
    while (1) {}
  }

}

void loop() {      
  // read values from the sensor
  float pressure = bmp.readPressure();
  float temperature = bmp.readTemperature();
  
  // We now create a URI for the request
  String url = host;
  url += "/update?api_key=";
  url += THINGSPEAK_API_KEY;
  url += "&field1=";
  url += String(temperature);
  url += "&field2=";
  url += String(pressure);
  
  Serial.print("Requesting URL: ");
  Serial.println(url);

  HTTPClient http;
  Serial.print("[HTTP] begin...\n");
  // configure targed server and url
  http.begin(url);
  
  Serial.print("[HTTP] GET...\n");
  // start connection and send HTTP header
  int httpCode = http.GET();

  if(httpCode == HTTP_CODE_OK) {
    String buffer = http.getString();
    Serial.println(buffer);
  }

  Serial.println("closing connection");

  // Go back to sleep. If your sensor is battery powered you might
  // want to use deep sleep here
  delay(1000 * UPDATE_INTERVAL_SECONDS);
}

 

こちら問題なくデータの蓄積ができた。

WeMos (c5) JSON exchange rate

WeMosをRESPのクライアントとして機能するため、JSONと、HTTPClientを検証する。

前回ArduinoJsonというライブラリを使用したので、ESP8266ならではのWiFi機能を使い、インターネットから情報を取得して表示させてみる。

JSON データ形式

為替レートの情報は、

Foreign exchange rates and currency conversion JSON API

から取得する。

ドル円レートの情報を取得する場合、URLはhttp://api.fixer.io/latest?base=USD&symbols=JPY

応答は下記の通り

HTTP/1.1 200 OK
Server: nginx/1.13.6
Date: Sat, 04 Nov 2017 13:40:46 GMT
Content-Type: application/json
Content-Length: 57
Connection: close
Cache-Control: public, must-revalidate, max-age=900
Last-Modified: Fri, 03 Nov 2017 00:00:00 GMT
Vary: Origin
X-Content-Type-Options: nosniff
{"base":"USD","date":"2017-11-03","rates":{"JPY":113.94}}

closing connection

プログラム

下記の処理をする

  1.  WiFiManagerでWiFi自動接続
  2. get_exchange_rate処理
    1. api.fixer.io JSONデータ取得
    2. parse json data
    3. OLEDへ表示
  3. 60秒待ち
  4. 2へ続き
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
 
#define OLED_RESET 0  // GPIO0
Adafruit_SSD1306 OLED(OLED_RESET);

const char* URL = "http://api.fixer.io/latest?base=USD&symbols=JPY";  // http resource
//sample json data used in this sketch
// {"base":"USD","date":"2017-11-03","rates":{"JPY":113.94}}

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager

void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
}

void setup() {
  OLED.begin();
  OLED.clearDisplay();
 
  //Add stuff into the 'display buffer'
  OLED.setTextWrap(false);
  OLED.setTextSize(1);
  OLED.setTextColor(WHITE);
  OLED.setCursor(0,0);
  delay(10);
  
  Serial.begin(115200);
  Serial.println("");
  delay(10);

  // Connect to WiFi network
  OLED.println("wifiManager autoConnect...");
  OLED.display(); //output 'display buffer' to screen  
 
  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
  //reset settings - for testing
  //wifiManager.resetSettings();

  //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  wifiManager.setAPCallback(configModeCallback);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if(!wifiManager.autoConnect()) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  } 

  // Print the IP address
  OLED.print("http://");
  OLED.print(WiFi.localIP());
  OLED.println("/");
  OLED.println("WiFi connected");
  OLED.display(); //output 'display buffer' to screen  
  
  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");
 
}

void get_exchange_rate() {
  const int BUFFER_SIZE = JSON_OBJECT_SIZE(4) + JSON_ARRAY_SIZE(1);
  StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
  HTTPClient http;

  Serial.print("[HTTP] begin...\n");
  // configure targed server and url
  http.begin(URL);
  
  Serial.print("[HTTP] GET...\n");
  // start connection and send HTTP header
  int httpCode = http.GET();

  if(httpCode != HTTP_CODE_OK) {
    return;
  }
  String buffer = http.getString();
  Serial.println(buffer);

  //parse json data
  char json[buffer.length() + 1];
  buffer.toCharArray(json, sizeof(json));
  Serial.println(json);
  JsonObject& root = jsonBuffer.parseObject(json);
  if (!root.success()) {
    Serial.println("parseObject() failed");
    return;
  }
  const char* date = root["date"];
  Serial.println(date);
  const char* base = root["base"];
  Serial.println(base);
  JsonObject& rates = root["rates"];
  rates.printTo(Serial);
  Serial.println();
  const char* rate = rates["JPY"];
  Serial.println(rate);
  Serial.println();
  
  Serial.println("closing connection");

  OLED.clearDisplay();
  OLED.setCursor(0,0);
  // Print the IP address
  OLED.print("http://");
  OLED.print(WiFi.localIP());
  OLED.println("/");

  OLED.setCursor(0, 16);
  OLED.print(date);
  OLED.setCursor(0, 24);
  OLED.print("JPY/");
  OLED.print(base);
  OLED.print(": ");
  OLED.print(rate);
  OLED.display(); //output 'display buffer' to screen  

}

void loop() {
  get_exchange_rate();
  delay(60000);
}

 

参考

  • http://blog.boochow.com/article/425016458.html — ESP8266版Arduinoでネットから情報を取ってきてLCDに表示する

WeMos (c4) JSON

WeMosをRESPのクライアントとして機能するため、JSONと、HTTPClientを検証する。

ライブラリの追加

JSONを扱うライブラリに「ArduinoJSON」というのがあるので、ライブラリの追加で、リストが出てくるので、JSONと入力し絞込。

(2018/7現在、5.x と6.x が共存して、6.xはまたベター版のため、エラーが発生する。5.xを利用する)

ArduinoJSONの動作、JsonBuffer size、Parsing program、Serializing programは、下記のURLで確認しながら進める方が便利でしょう。

https://bblanchon.github.io/ArduinoJson/assistant/

動作確認

公式のサンプルJsonParserExampleをそのまんま。

// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!

#include <ArduinoJson.h>

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    // wait serial port initialization
  }

  // Memory pool for JSON object tree.
  //
  // Inside the brackets, 200 is the size of the pool in bytes,
  // If the JSON object is more complex, you need to increase that value.
  // See https://bblanchon.github.io/ArduinoJson/assistant/
  StaticJsonBuffer<200> jsonBuffer;

  // StaticJsonBuffer allocates memory on the stack, it can be
  // replaced by DynamicJsonBuffer which allocates in the heap.
  //
  // DynamicJsonBuffer  jsonBuffer(200);

  // JSON input string.
  //
  // It's better to use a char[] as shown here.
  // If you use a const char* or a String, ArduinoJson will
  // have to make a copy of the input in the JsonBuffer.
  char json[] =
      "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";

  // Root of the object tree.
  //
  // It's a reference to the JsonObject, the actual bytes are inside the
  // JsonBuffer with all the other nodes of the object tree.
  // Memory is freed when jsonBuffer goes out of scope.
  JsonObject& root = jsonBuffer.parseObject(json);

  // Test if parsing succeeds.
  if (!root.success()) {
    Serial.println("parseObject() failed");
    return;
  }

  // Fetch values.
  //
  // Most of the time, you can rely on the implicit casts.
  // In other case, you can do root["time"].as<long>();
  const char* sensor = root["sensor"];
  long time = root["time"];
  double latitude = root["data"][0];
  double longitude = root["data"][1];

  // Print values.
  Serial.println(sensor);
  Serial.println(time);
  Serial.println(latitude, 6);
  Serial.println(longitude, 6);
}

void loop() {
  // not used in this example
}

出力

gps
1351824120
48.756080
2.302038

参考

  • https://bblanchon.github.io/ArduinoJson/assistant/ — ArduinoJson Assistant
  • http://shuzo-kino.hateblo.jp/entry/2016/05/06/203603 — ArduinoでJSONを扱う「ArduinoJSON」
  • https://arduinojson.org/v5/assistant/ — How to use ArduinoJson?
    How to compute the JsonBuffer size?
    Paste your JSON in the box and you’ll know…

WeMos (c3) Home IoT Server

いよいよWiFiManagerを組み込み、理想のIoT-Cloud-Mobile Study Kit (IoT実験キット)の形ができた。

今回の実験はWeMosにhttpサーバを立ち上げて、ブラウザーから接続 を待機;接続するとBMP280センサー情報を返送する。

つまり、スマートフォンまたはPCから直接接続して利用する。この場合ローカル環境の利用に限られ、出かける時でも利用するため、クラウド(例えばTinyWebDB API)が必要だ。

WiFiManagerを組み込みだ、Home IoT Server。

/*
 * 
 */
#include <Wire.h> 
#include <Adafruit_BMP280.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
 
#define OLED_RESET 0  // GPIO0
Adafruit_SSD1306 OLED(OLED_RESET);

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11 
#define BMP_CS 10

Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> 
 
int ledPin = BUILTIN_LED;
WiFiServer server(80);
 
void setup() {
  OLED.begin();
  OLED.clearDisplay();
 
  //Add stuff into the 'display buffer'
  OLED.setTextWrap(false);
  OLED.setTextSize(1);
  OLED.setTextColor(WHITE);
  OLED.setCursor(0,0);
  delay(10);
 
 
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);
 
  // Connect to WiFi network
  OLED.println("wifiManager autoConnect...");
  OLED.display(); //output 'display buffer' to screen  
 
  WiFiManager wifiManager;
  wifiManager.autoConnect();

  OLED.println("WiFi connected");
  OLED.display(); //output 'display buffer' to screen  
 
  // Start the server
  server.begin();
  OLED.println("Server started");
  
  // Print the IP address
  OLED.print("http://");
  OLED.print(WiFi.localIP());
  OLED.println("/");
 
  OLED.display(); //output 'display buffer' to screen  
  // OLED.startscrollleft(0x00, 0x0F); //make display scroll 

  if (!bmp.begin(0x76)) 
  {
    OLED.println("Could not find BMP180 or BMP085 sensor at 0x77");
    OLED.display(); //output 'display buffer' to screen  
    while (1) {}
  }
}

void OLED_show()
{

  OLED.clearDisplay();
  OLED.setCursor(0,0);
  // Print the IP address
  OLED.print("http://");
  OLED.print(WiFi.localIP());
  OLED.println("/");
  OLED.setCursor(0,8);
  OLED.print("Temp = ");
  OLED.print(bmp.readTemperature());
  OLED.println(" Celsius");
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  OLED.setCursor(0,16);
  OLED.print("Pres = ");
  OLED.print(bmp.readPressure());
  OLED.println(" Pascal ");
  // print the number of seconds since reset:
  OLED.setCursor(0,24);
  OLED.print(millis() / 1000);

  OLED.display(); //output 'display buffer' to screen  
}

void loop() {
  delay(500);
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    OLED_show();
    delay(1);
    return;
  }
 
  // Wait until the client sends some data
  OLED.println("new client");
  // while(!client.available()){
  //   delay(1);
  // }
 
  // Read the first line of the request
  String request = client.readStringUntil('\r');
  OLED.println(request);
  OLED.display(); //output 'display buffer' to screen  
  client.flush();
 
  // Match the request
 
  int value = LOW;
  if (request.indexOf("/LED=ON") != -1) {
    digitalWrite(ledPin, LOW);
    value = HIGH;
  } 
  if (request.indexOf("/LED=OFF") != -1){
    digitalWrite(ledPin, HIGH);
    value = LOW;
  }
 
 
 
  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
 
  client.print("Temp = ");
  client.print(bmp.readTemperature());
  client.println(" Celsius <br>");
  client.print("Pres = ");
  client.print(bmp.readPressure());
  client.println(" Pascal <br>");

  client.print("Led pin is now: ");
 
  if(value == HIGH) {
    client.print("On");  
  } else {
    client.print("Off");
  }
  client.println("<br><br>");
  client.println("Click <a href=\"/LED=ON\">here</a> turn the LED ON<br>");
  client.println("Click <a href=\"/LED=OFF\">here</a> turn the LED OFF<br>");
  client.println("</html>");
 
  delay(1);
  OLED.println("Client disconnected");
  OLED.println("");
  OLED.display(); //output 'display buffer' to screen  
 
}

 

実験方法:

  1. プログラム検証
  2. WeMosにプログラムアップロード
  3. WeMosのWiFiManeger で接続、AP設定
  4. WeMosのOLEDでIP確認
  5. 自動的にhttpサーバを立ち上げ、ブラウザーから接続 を待機
  6. 接続するとBMP280センサー情報を返送する。

 

WeMos (c2) WiFiManager

WeMos のWiFiが、前回のようにSSIDとPASSWORDをコードに書き込む方法の他に、オンライン変更できるような方法もある。

WiFiManager というライブラリを使うと簡単にできる

https://github.com/tzapu/WiFiManager

このソースを参考に試してみる。

まず、ライブラリマネージャーから、WiFiManagerを検索して、インストールする。

ライブラリを使える状態にすると,下記のサンプルで、接続するだけで上のユースケースが満たされて大変便利だ…。標準でWebUIもついてる。

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager

void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  
  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
  //reset settings - for testing
  //wifiManager.resetSettings();

  //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  wifiManager.setAPCallback(configModeCallback);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if(!wifiManager.autoConnect()) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  } 

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");
 
}

void loop() {
  // put your main code here, to run repeatedly:

}

 

WiFiManager 動作の流れ

  1. 保存されている認証情報があれば、その情報を使ってAPに接続する
  2. 保存されている情報がないか、あっても接続できなければ、Wi-Fiをスキャンして接続候補となるAPを探し、ESP8266自身がアクセスポイントモードになり、認証情報の入力を待つ
  3. ユーザーがESP8266のAPに接続すると、ESP8266自身が立ち上げたWebサーバーに接続され、表示されているAP候補の中から接続したいAPを選択し、そのパスワードを入力する。
  4. ESP8266は指定されたSSIDとパスワードでAPに接続する

ESP8266アクセスポイントモード

保存されている情報がないか、あっても接続できなければ、Wi-Fiをスキャンして接続候補となるAPを探し、ESP8266自身がアクセスポイントモードになり、認証情報の入力を待つ。

まずスマートフォンの「設定」の中の「Wi-Fi」を開く。自宅のWi-Fiルーターの他に”AutoConnectAP”というAPが見つかります。これがESP8266なので、これを選択。

image

接続したいAPを選択

ユーザーがESP8266のAPに接続すると、ESP8266自身が立ち上げたWebサーバーに接続される。

自動的にブラウザーが立ち上がる場合もありますし、そうでない場合はブラウザーを起動します。するとESP8266のWebサーバーに接続され、次の画面が表示されます。

image

ここで「Configure WiFi」をタップすると、近くにあるWi-Fi APのリストが表示されます。表示されているAP候補の中から接続したいAPを選択し、そのパスワードを入力。するとESP8266は指定されたSSIDとパスワードでAPに接続する。

 

WeMos (7) I2C OLED SSD1306 (Adafruit)

仕様

[0.96 インチ 4Pin IIC I2C ブルー OLED ディスプレイ モジュール Arduino対応]を使ってみる。

主な仕様は次のようになっています。

  • I2C通信
  • ディスプレイコントローラ: SSD1306
  • 解像度: 128×64
  • 電圧: 3.3V-5V

ライブラリ

次の2つライブラリが必要

  1. Adafruit_GFX
  2. Adafruit_SSD1306

こちらを参考にして、すんなりできた。下記の2つライブラリもSSD1306対応だ。

  • ThingPulseのライブラリ(SSD1306, SH1106対応)
  • U8g2ライブラリ(多数OLED対応)

結線

I2Cの場合、デフォルトはSDA、SCLはD1、D2。

サンプルコード

デフォルトはSDA、SCLはD1、D2。変更する場合、 Wire.begin(4,5); // OLED:SDA,SCL 行を変更して対応できるらしい。

#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
 
#define OLED_RESET 0  // GPIO0
Adafruit_SSD1306 OLED(OLED_RESET);
 
void setup()   {
  //  Wire.begin(4,5);              // OLED:SDA,SCL
  OLED.begin();
  OLED.clearDisplay();
 
  //Add stuff into the 'display buffer'
  OLED.setTextWrap(false);
  OLED.setTextSize(1);
  OLED.setTextColor(WHITE);
  OLED.setCursor(0,0);
  OLED.println("automatedhome.party");
 
  OLED.display(); //output 'display buffer' to screen  
  OLED.startscrollleft(0x00, 0x0F); //make display scroll 
} 
 
void loop() {
}

これて、i2c 複数繋いて、いい感じ。

参考

WeMos (b3) BMP280 I2C

BMP280センサーの利用し、 I2Cで気圧温度を測って見る。

ライブラリの追加

“Adafruit Unified Sensor”ライブラリの追加

スクリーンショット 2017-09-04 15.24.15

センサーをライブラリ追加

BMP280センサーを利用する

ライブラリからBMP280を検索して、追加してください

測定プログラム

 

/***************************************************************************
  This is a library for the BMP280 humidity, temperature & pressure sensor
  Designed specifically to work with the Adafruit BMEP280 Breakout 
  ----> http://www.adafruit.com/products/2651
  These sensors use I2C or SPI to communicate, 2 or 4 pins are required 
  to interface.
  Adafruit invests time and resources providing this open source code,
  please support Adafruit andopen-source hardware by purchasing products
  from Adafruit!
  Written by Limor Fried & Kevin Townsend for Adafruit Industries.  
  BSD license, all text above must be included in any redistribution
 ***************************************************************************/

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11 
#define BMP_CS 10

Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

void setup() {
  Serial.begin(9600);
  Serial.println(F("BMP280 test"));
  
  if (!bmp.begin(0x76)) {  
    Serial.println(F("Could not find a valid BMP280 sensor, check wiring!"));
    while (1);
  }
}

void loop() {
    Serial.print(F("Temperature = "));
    Serial.print(bmp.readTemperature());
    Serial.println(" *C");
    
    Serial.print(F("Pressure = "));
    Serial.print(bmp.readPressure());
    Serial.println(" Pa");

    Serial.print(F("Approx altitude = "));
    Serial.print(bmp.readAltitude(1013.25)); // this should be adjusted to your local forcase
    Serial.println(" m");
    
    Serial.println();
    delay(2000);
}

 

WeMos (1) Blink

Blink

動作確認のため、まずLちか(Blink)をする。

ボードから、WeMosには「D1 Mini & D1 R2」を選択する。

通信ポートは、デバイスマネージャーから見えた、CH340に割り当てた通信ポート(COM3など)も設定して下さい。

「wemos windows config」の画像検索結果

MacOSの場合、次のように設定する。

スクリーンショット 2016-12-06 21.48.39.png

(LEDはGPIO 5 に接続)の場合のスケッチ。

WeMosの内蔵LEDを利用する場合、プリグラムは次のように

#define ESP8266_LED BUILTIN_LED

void setup() 
{
  pinMode(ESP8266_LED, OUTPUT);
}

void loop() 
{
  digitalWrite(ESP8266_LED, HIGH);
  delay(500);
  digitalWrite(ESP8266_LED, LOW);
  delay(500);
}

参考

  1. http://www.esp8266learning.com/
  2. https://www.baldengineer.com/esp8266-5-reasons-to-use-one.html