ESP-WROOM-02でTFTに画像を表示する

今日のニャンコ その3


電子日めくりカレンダーの3回目です、
@画像データをネットからダウンロードする。
A画像データを変換/整形する。
B画像データをESP8266にアップロードする。
C画像データをESP8266で表示する。

前回はBとCを紹介しましたが、ESP8266側のスケッチを書き換える必 要が有りました。
そこで、今回はBとCを自動的に行う方法を紹介します。

以下のスケッチをESP8266に書き込みます。
myIP(192, 168, 10, 99)の部分は、環境に合わせて変更してください。
起動時にimage.bmpが有ればイメージファイルを表示します。
その後、upload.txtのファイルを監視し、このファイルができたらイメージファイルを表示します。
イメージファイル表示中にyield()を呼び出すことでバックグラウンド動作を行うようにしています。
/*
 * SPIFFSにあるBMPファイルを表示する
 */
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266FtpServer.h>
#include <FS.h>
#include <SPI.h>
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"

IPAddress myIP(192, 168, 10, 99);
const char* ssid = "アクセスポイントのSSID";
const char* password = "アクセスポイントのパスワード";

//set #define FTP_DEBUG in ESP8266FtpServer.h to see ftp verbose on serial
FtpServer ftpSrv;

#define TFT_DC 15
#define TFT_CS 2
#define TFT_RST -1

Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);

long lastTime = 0;

void listDir() {
  char cwdName[2];

  strcpy(cwdName,"/");
  Dir dir=SPIFFS.openDir(cwdName);
  while( dir.next()) {
    String fn, fs;
    fn = dir.fileName();
    fn.remove(0, 1);
    fs = String(dir.fileSize());
    Serial.println("<" + fn + "> size=" + fs);
  } // end while
}

void setup(void){
  Serial.begin(9600);
  delay(500);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  // Set Fix IP
  WiFi.config(myIP, WiFi.gatewayIP(), WiFi.subnetMask());
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  tft.begin();
  tft.setRotation(3);

  if (SPIFFS.begin()) {
    Serial.println("SPIFFS opened!");
   
    // Show BMP file
    if (SPIFFS.exists("/image.bmp")) {
      Serial.println("BMP File found");
      // Show BMP file
      tft.fillScreen(ILI9341_BLUE);
      bmpDraw("/image.bmp", 45, 0);
    }
  } else {
    Serial.println("SPIFFS failed!");
  }  

  //FTP Setup, ensure SPIFFS is started before ftp;
  //username, password for ftp.  set ports in ESP8266FtpServer.h  (default 21, 50009 for PASV)
  ftpSrv.begin("esp8266","esp8266");

}

void loop(void){

  ftpSrv.handleFTP();
  long now = millis();
  if (now - lastTime > 1000) {
    lastTime = now;

    if (SPIFFS.exists("/upload.txt")) {
      Serial.println("upload.txt found");
      // Show BMP file
      tft.fillScreen(ILI9341_BLUE);
      bmpDraw("/image.bmp", 45, 0);
      SPIFFS.remove("/upload.txt");
    }
  }
}

// This function opens a Windows Bitmap (BMP) file and
// displays it at the given coordinates.  It's sped up
// by reading many pixels worth of data at a time
// (rather than pixel by pixel).  Increasing the buffer
// size takes more of the Arduino's precious RAM but
// makes loading a little faster.  20 pixels seems a
// good balance.

#define BUFFPIXEL 20

void bmpDraw(char *filename, uint8_t x, uint16_t y) {

  File     bmpFile;
  int      bmpWidth, bmpHeight;   // W+H in pixels
  uint8_t  bmpDepth;              // Bit depth (currently must be 24)
  uint32_t bmpImageoffset;        // Start of image data in file
  uint32_t rowSize;               // Not always = bmpWidth; may have padding
  uint8_t  sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel)
  uint8_t  buffidx = sizeof(sdbuffer); // Current position in sdbuffer
  boolean  goodBmp = false;       // Set to true on valid header parse
  boolean  flip    = true;        // BMP is stored bottom-to-top
  int      w, h, row, col;
  uint8_t  r, g, b;
  uint32_t pos = 0, startTime = millis();

  if((x >= tft.width()) || (y >= tft.height())) return;

  Serial.println();
  Serial.print(F("Loading image '"));
  Serial.print(filename);
  Serial.println('\'');

  // Open requested file on SD card
  ;
  if (!(bmpFile = SPIFFS.open(filename,"r"))) {
    Serial.print(F("File not found"));
    return;
  }

  // Parse BMP header
  if(read16(bmpFile) == 0x4D42) { // BMP signature
    Serial.print(F("File size: ")); Serial.println(read32(bmpFile));
    (void)read32(bmpFile); // Read & ignore creator bytes
    bmpImageoffset = read32(bmpFile); // Start of image data
    Serial.print(F("Image Offset: ")); Serial.println(bmpImageoffset, DEC);
    // Read DIB header
    Serial.print(F("Header size: ")); Serial.println(read32(bmpFile));
    bmpWidth  = read32(bmpFile);
    bmpHeight = read32(bmpFile);
    if(read16(bmpFile) == 1) { // # planes -- must be '1'
      bmpDepth = read16(bmpFile); // bits per pixel
      Serial.print(F("Bit Depth: ")); Serial.println(bmpDepth);
      if((bmpDepth == 24) && (read32(bmpFile) == 0)) { // 0 = uncompressed

        goodBmp = true; // Supported BMP format -- proceed!
        Serial.print(F("Image size: "));
        Serial.print(bmpWidth);
        Serial.print('x');
        Serial.println(bmpHeight);

        // BMP rows are padded (if needed) to 4-byte boundary
        rowSize = (bmpWidth * 3 + 3) & ~3;

        // If bmpHeight is negative, image is in top-down order.
        // This is not canon but has been observed in the wild.
        if(bmpHeight < 0) {
          bmpHeight = -bmpHeight;
          flip      = false;
        }

        // Crop area to be loaded
        w = bmpWidth;
        h = bmpHeight;
        if((x+w-1) >= tft.width())  w = tft.width()  - x;
        if((y+h-1) >= tft.height()) h = tft.height() - y;

        // Set TFT address window to clipped image bounds
        tft.setAddrWindow(x, y, x+w-1, y+h-1);

        for (row=0; row<h; row++) { // For each scanline...

          // Seek to start of scan line.  It might seem labor-
          // intensive to be doing this on every line, but this
          // method covers a lot of gritty details like cropping
          // and scanline padding.  Also, the seek only takes
          // place if the file position actually needs to change
          // (avoids a lot of cluster math in SD library).
          if(flip) // Bitmap is stored bottom-to-top order (normal BMP)
            pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize;
          else     // Bitmap is stored top-to-bottom
            pos = bmpImageoffset + row * rowSize;
          if(bmpFile.position() != pos) { // Need seek?
            bmpFile.seek(pos,SeekSet);
            buffidx = sizeof(sdbuffer); // Force buffer reload
          }

          for (col=0; col<w; col++) { // For each pixel...
            // Time to read more pixel data?
            if (buffidx >= sizeof(sdbuffer)) { // Indeed
              bmpFile.read(sdbuffer, sizeof(sdbuffer));
              buffidx = 0; // Set index to beginning
            }

            // Convert pixel from BMP to TFT format, push to display
            b = sdbuffer[buffidx++];
            g = sdbuffer[buffidx++];
            r = sdbuffer[buffidx++];
            tft.pushColor(tft.color565(r,g,b));

            yield();
           
          } // end pixel
        } // end scanline
        Serial.print(F("Loaded in "));
        Serial.print(millis() - startTime);
        Serial.println(" ms");
      } // end goodBmp
    }
  }

  bmpFile.close();
  if(!goodBmp) Serial.println(F("BMP format not recognized."));
}

// These read 16- and 32-bit types from the SD card file.
// BMP data is stored little-endian, Arduino is little-endian too.
// May need to reverse subscript order if porting elsewhere.

uint16_t read16(File &f) {
  uint16_t result;
  ((uint8_t *)&result)[0] = f.read(); // LSB
  ((uint8_t *)&result)[1] = f.read(); // MSB
  return result;
}

uint32_t read32(File &f) {
  uint32_t result;
  ((uint8_t *)&result)[0] = f.read(); // LSB
  ((uint8_t *)&result)[1] = f.read();
  ((uint8_t *)&result)[2] = f.read();
  ((uint8_t *)&result)[3] = f.read(); // MSB
  return result;
}

ESP8266へのスケッチの書き込みが終了したら、Raspberry側で以下のコマンドを実行します。
下線部分が入力です。パスワードは表示されません。
$ ftp -p
ftp> open 192.168.10.99
Connected to 192.168.10.99.
220--- Welcome to FTP for ESP8266 ---
220---   By David Paiva   ---
220 --   Version FTP-2016-01-14   --
Name (192.168.10.99:orangepi): esp8266
331 OK. Password required
Password: esp8266
230 OK.
ftp> binary
200 TYPE is now 8-bit binary
ftp> put /tmp/imageDst.bmp image.bmp
local: /tmp/imageDst.bmp remote: image.bmp
227 Entering Passive Mode (192,168,10,99,195,89).
150 Connected to port 50009
226-File successfully transferred
226 3898 ms, 42 kbytes/s
164298 bytes sent in 1.87 secs (86.0233 kB/s)
ftp> !touch /tmp/upload.txt
ftp> ascii
200 TYPE is now ASII
ftp> put /tmp/upload.txt upload.txt
local: /tmp/upload.txt remote: upload.txt
227 Entering Passive Mode (192,168,10,99,195,89).
150 Connected to port 50009
226 File successfully transferred
ftp> bye
221 Goodbye

これで、ESP8266のSPIFFS領域にimage.bmpとupload.txtがアップロードされます。
ESP8266のTFTに画像データが表示されれば成功です。

最後にRaspberry側に、ftpのコマンドファイル(ftp.cmd)とシェルスクリプト(show_esp8266.sh)を作ります。
【ftp.cmd】
open 192.168.10.99
user esp8266 esp8266
binary
put /tmp/imageDst.bmp image.bmp
ascii
put /tmp/upload.txt upload.txt
bye

【show_esp8266.sh】
#!/bin/bash
#
set -x
HomeDir="/home/orangepi"

#Imageのダウンロード
SrcFile="/tmp/imageSrc.jpg"
DstFile="/tmp/imageDst.bmp"
sudo python ${HomeDir}/neko/SaveImages.py ${SrcFile}
#identify ${SrcFile}

#BMPファイルに変換
convert ${SrcFile} -geometry 320x240 -compress none ${DstFile}
#identify ${DstFile}

#ESP8266にアップロード
touch /tmp/upload.txt
ftp -p -n < ${HomeDir}/ftp.cmd

このシェルスクリプト(show_esp8266.sh)を一日一回、cronで実行すれば電子日めくりカレンダーの完成と思いました が.....

続く...