Raspberry Pi 3 wears a Display-O-Tron HAT

Two weeks ago I laid my hands on a Raspberry Pi 3. For sure I did not buy the 10.000.000th one. I ordered just a week before this milestone wich was a good excuse for discounts, but anyway, a Raspberry Pi is a nice and versatile thing to play with.

Since there are already a huge number of tutorials on how to set up and configure a Raspberry Pi I will spare the details. For this example of using the Display-O-Tron HAT on a Raspberry lets assume your Pi is already set up with a Linux distribution, knows Python and is connected to the internet.

dothat

An Idea

My idea is to use the Display-O-Tron HAT as display for several purposes. The Display-O-Tron HAT comes with a three line LCD display, a row of very bright LEDs on the right and 6 touch buttons. Each button can trigger the display of different information such as

  • system statistics
  • the number of unread emails, signaling incoming messages
  • process states (dead or alive?)
  • date and time
  • head lines of a news feed

The Sources

Based on the examples for the Display-O-Tron HAT on github I created a simple, straightforward, quick and dirty Python script.

On the push of a button the LCD display will be alighted for a couple of seconds in a different colour and the desired information will be retrieved and displayed. After a couple of seconds the backlight LEDs will be turned off. This is realized using threads that will finish after the desired time has passed.
The functionality that is implemented is a check for unread emails on googlemail’s IMAP servers, a simple date and time display, a quick internet connection and system status check and a status check of certain processes.
If unread emails were detected the LEDs on the (b)right side will blink three times in a row. Every minute the display will switch back to the default view: date and time.

#!/usr/bin/env python
print('''
Switch between different views using the Display-o-Tron HAT buttons

Main button: Display date and time
Right: Display number of unread emails
Left: Display system statistics
Down: Display process status
Up: TODO find something else to display

Press CTRL+C to exit.
''')

import dothat.touch as touch
import dothat.lcd as lcd
import dothat.backlight as backlight
import signal
import sys

import psutil
import urllib2
import subprocess
import imaplib
import time
from datetime import date
import calendar
import threading

'''

Captouch provides the @captouch.on() decorator
to make it super easy to attach handlers to each button.

The handler will receive 'channel'( corresponding to a particular
button ID ) and 'event' ( corresponding to press/release ) arguments.
'''

'''DISPLAY utilities'''
# store time of last button touch
# to be able to reset backlight LEDs
oldTime = time.time()
turnedOff = True

def resetBacklightLEDs():
    global oldTime
    oldTime = time.time()
    global turnedOff
    turnedOff = False

def clearDOT():
    lcd.clear()

def colorDOT(r, g, b):
    backlight.rgb(r, g, b)

def turnOnLEDsDOT():
    # turn on LEDs one by one in a row
    for led in range(6):
        backlight.graph_set_led_state(led, 1)
        time.sleep(0.1)
    pass

def turnOffDOT():
    colorDOT(0, 0, 0)  # backlight off
    backlight.off()
    backlight.graph_off()  # side LEDs off
    global turnedOff
    turnedOff = True

def dotClock():
    clearDOT()

    d = time.strftime("%d.%m.%Y")
    t = time.strftime("%H:%M")
    the_date = date.today()
    day = calendar.day_name[the_date.weekday()]
    print day + ", " + d + " / " + t

    lcd.set_cursor_position(3, 0)
    lcd.write(day)
    lcd.set_cursor_position(3, 1)
    lcd.write(d)
    lcd.set_cursor_position(5, 2)
    lcd.write(t)

def dotMails(login, password):
    nofUnreadEmails = check_googlemail(login, password)
    if nofUnreadEmails > 0:
        lcd.write("Unread Emails: " + str(nofUnreadEmails))
        showNewMessages(200, 0, 0)

    else:
        lcd.write("No new mail")

def dotSystemStats():
    lcd.set_cursor_position(0, 0)
    lcd.write(check_internet())

    lcd.set_cursor_position(0, 1)
    lcd.write("CPU: " + check_CPU())

    lcd.set_cursor_position(0, 2)
    lcd.write("Memory: " + check_memory())

def check_internet():
    try:
        # ping google to check whether internet connection works
        response = urllib2.urlopen('http://www.google.com', timeout=1)
        return "Internet: OK"
    except urllib2.URLError as err: pass
    return "Internet connection broken"

def check_CPU():
    cpu_usage = str(psutil.cpu_percent(interval=None)) + " %"
    print "CPU usage: " + cpu_usage
    return cpu_usage

def check_memory():
    mem = psutil.virtual_memory()
    # print "Memory: " + str(mem)
    memory_used = str(mem.percent) + " %"
    print "Memory used: " + memory_used
    THRESHOLD = 100 * 1024 * 1024  # 100MB
    if mem.available >= THRESHOLD:
        print("Warning, memory low")
        return "Warning, memory low"
    return memory_used

def get_pid(name):
    try:
        pids = subprocess.check_output(["pidof", name])
    except subprocess.CalledProcessError as pids:
        print "error code", pids.returncode, pids.output
        return ""
    return map(int, pids.split())

def get_single_pid(name):
    return int(check_output(["pidof", "-s", name]))

def check_process(name):
    PID = get_pid(name)
    if len(PID) == 1:
        print "PID " + name + ": " + str(PID[0])
        p = psutil.Process(PID[0])
        status = ""
        if p.status == psutil.STATUS_ZOMBIE:
            status = "Process " + name + " died"
            print status
        else:
            status = "Process " + name + " OK"
            print status
            return status
        return ""

def dotProcessStats():
    lcd.set_cursor_position(0, 0)     
    process1 = check_process('geany')
    if len(process1) > 1 :    
        lcd.write(process1)
    else:
        lcd.write("geany is dead.")

    lcd.set_cursor_position(0, 1)
    process2 = check_process('bash')
    if len(process2) > 1 :
        lcd.write(process2)
    else:
        lcd.write("bash is dead.")

    lcd.set_cursor_position(0, 2)
    process3 = check_process('firefox')
    if len(process3) > 1 :
        lcd.write(process3)
    else:
        lcd.write("firefox is dead.")

def check_googlemail(login, password):
    # if new mail return # emails
    obj = imaplib.IMAP4_SSL('imap.gmail.com', '993')
    obj.login(login, password)
    obj.select()
    nofUnreadMessages = len(obj.search(None, 'UnSeen')[1][0].split())
    print "Unread emails: " + str(nofUnreadMessages)
    return nofUnreadMessages

class ShowNewMessagesThread (threading.Thread):
    red, green, blue = 0, 0, 0  # static elements, it means, they belong to the class

    def run (self):
        colorDOT(self.red, self.green, self.blue)
        for i in range(0, 3):
            turnOnLEDsDOT()
            time.sleep(2)
            turnOffDOT()
            time.sleep(2)

            if i == 2:
                print "stop ShowNewMessagesThread"
                self.do_run = False  # stop thread
                break

snmt = ShowNewMessagesThread()
def showNewMessages(r, g, b):
    global snmt
    if snmt.is_alive():
        return
    snmt = ShowNewMessagesThread()
    snmt.red = r
    snmt.green = g
    snmt.blue = b
    snmt.daemon = True  # enable stop of thread along script with Ctrl+C
    snmt.start()

class AlightThread (threading.Thread):
    red, green, blue = 0, 0, 0  # static elements, it means, they belong to the class

    def run (self):
        colorDOT(self.red, self.green, self.blue)
        while True:
        if turnedOff == False:
            if time.time() - oldTime > 5:
                print "stop AlightThread"
                turnOffDOT()
                self.do_run = False  # stop thread
                break

at = AlightThread()
def alightDisplay(r, g, b):
    global at
    if at.is_alive():
        return
    at = AlightThread()
    at.red = r
    at.green = g
    at.blue = b
    at.daemon = True  # enable stop of thread along script with Ctrl+C
    at.start()

class ClockThread (threading.Thread):
    def run (self):
        print "run update clock thread " + str(self)
        dotClock()
        self.do_run = False  # stop thread

    def stopClockThread(self):
        self.do_run = False  # stop thread

ct = ClockThread()
def updateClock():
    global ct
    if ct.is_alive():
        print "Clock thread " + str(ct) + " is alive."
        ct.stopClockThread()
        return
    print "Launching clock thread " + str(ct)
    ct = ClockThread()
    ct.daemon = True  # enable stop of thread along script with Ctrl+C
    ct.start()

'''DOT touch button handler'''
@touch.on(touch.UP)
def handle_up(ch, evt):
    print("Up pressed: TODO find another useful display idea")
    clearDOT()
    alightDisplay(255, 0, 255)
    lcd.write("Up up and away: TODO")
    resetBacklightLEDs()

@touch.on(touch.DOWN)
def handle_down(ch, evt):
    print("Down pressed: display process states")
    clearDOT()
    alightDisplay(255, 0, 0)
    dotProcessStats()
    resetBacklightLEDs()

@touch.on(touch.LEFT)
def handle_left(ch, evt):
    print("Left pressed: display system statistics")
    clearDOT()
    alightDisplay(0, 100, 200)
    dotSystemStats()
    resetBacklightLEDs()

@touch.on(touch.RIGHT)
def handle_right(ch, evt):
    print("Right pressed, check for new email")
    clearDOT()
    alightDisplay(100, 200, 255)
    dotMails('email adress', 'password')
    resetBacklightLEDs()

@touch.on(touch.BUTTON)
def handle_button(ch, evt):
    print("Main button pressed: show date and time")
    clearDOT()
    alightDisplay(255, 255, 255)
    updateClock()
    resetBacklightLEDs()

@touch.on(touch.CANCEL)
def handle_cancel(ch, evt):
    print("Cancel pressed!")
    clearDOT()
    backlight.rgb(0, 0, 0)
    lcd.write("Cancel")
    resetBacklightLEDs()
    alightDisplay(20, 20, 20)

'''main'''
if __name__ == '__main__':
    try:
    while True:
        timeDiff = time.time() - oldTime
        # print "time diff: " + str(timeDiff)

        # update clock every minute
        if timeDiff > 59 or timeDiff < 0.5:
        oldTime = time.time()
        alightDisplay(255, 255, 255)
        updateClock()
        time.sleep(1)
    except KeyboardInterrupt:
        print "exit"
        clearDOT()
        turnOffDOT()
        sys.exit()

 

Links

Raspberry Pi 3 Model B

Display-O-Tron HAT

https://github.com/pimoroni/dot3k

https://www.python.org/

ESP8266: Get Date and Time from HTTP Header

Instead of sending NTP packets to remote time server as in a previous blog post the date and the time can also be extracted from any HTTP header returned after an HTTP GET request. Usually the HTTP header contains the date and the time from the router. This way the local network must not be left necessarily. For illustration purposes only a well-known URL is used in this example.

Components used

Adafruit Feather Huzzah
Monochrome OLED display

Wiring

Adafruit Feather Huzzah OLED Display
3,3 V 3,3 V
GND GND
SDA (4)  SDA
SCL (5)  SCL

Software

This Arduino sketch shows

  • how to connect to the WiFi network
  • how to perform an HTTP GET request on an URL (could be an IP address as well)
  • how to extract date and time from the HTTP response header
  • how to display date and time on an OLED display .

Code

#include <EEPROM.h>
#include <ESP8266WiFi.h>    // http://esp8266.github.io/Arduino/versions/2.0.0/doc/libraries.html
#include <WiFiClient.h>     // https://www.arduino.cc/en/Reference/WiFiClient

// OLED ESP_ssd1306_128x64_I2C
#include <ESP_SSD1306.h>    // Modification of Adafruit_SSD1306 for ESP8266 compatibility
#include <Adafruit_GFX.h>   // Needs a little change in original Adafruit library (See README.txt file)
#include <SPI.h>            // For SPI comm (needed for not getting compile error)
#include <Wire.h>           // For I2C comm, but needed for not getting compile error

boolean debug=true;

// WiFi connection data
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_WIFI_PASSWORD";

const char* server = "www.google.de"; 	// an example URL
const int serverPort = 80;		// a port number
const char* resource = "/";       	// http resource

const unsigned long BAUD_RATE = 115200;	// serial connection speed
const unsigned long HTTP_TIMEOUT = 10000;   // max respone time from server

void initSerial();
void connectWiFi();
bool connect(const char* hostName, const int port);
void disconnect();
bool sendRequest(const char* host, const char* resource);
WiFiClient client;

#define OLED_RESET  16  // Pin 16 -RESET digital signal
ESP_SSD1306 display(OLED_RESET); // FOR I2C

void initOLEDDisplay();
void showDateAndTime();

bool findDateAndTimeInResponseHeaders();
String extractDayFromDateTimeString(String dateTime);
String extractMonthFromDateTimeString(String dateTime);
String extractYearFromDateTimeString(String dateTime);
String extractHourFromDateTimeString(String dateTime);
String extractMinuteFromDateTimeString(String dateTime);
String translateMonth(String monthStr);
String dateAndTime; // stores date and time from HTTP response header

unsigned long previousMillis = 0;
#define INTERVAL_MS 10000

void setup() {
  if( debug ) Serial.println("setup");
  initSerial();
  initOLEDDisplay();
  connectWiFi();
} // setup()

void loop() {

  unsigned long currentMillis = millis();
  // run every 10 seconds
  if (currentMillis - previousMillis >= INTERVAL_MS) {
    previousMillis = currentMillis;
	if( debug ) Serial.println("loop: get date and time");

	  if( connect(server, serverPort) ) {
		if( sendRequest(server, resource) ) {
		  if( findDateAndTimeInResponseHeaders() ) {
			if( debug ) {
			  Serial.print( "Date and Time from HTTP response header: " );
			  Serial.println( dateAndTime.c_str() );
			}
			showDateAndTime();
		  }
		}
		disconnect();
	  }
  }
} // loop()

// initialize serial port
void initSerial() {
  Serial.begin(BAUD_RATE);
  while (!Serial) {
    ;  // wait for serial port to initialize
  }
  if( debug ) Serial.println("Serial ready");
}

void initOLEDDisplay() {
  // SSD1306 Init
  display.begin(SSD1306_SWITCHCAPVCC);  // Switch OLED
  display.clearDisplay();
  // Show image buffer on the display hardware.
  // Since the buffer is intialized with an Adafruit splashscreen
  // internally, this will display the splashscreen.
  display.display();
  delay(2000);

  // Clear the buffer.
  display.clearDisplay();
}

// attempt to connect to WiFi
void connectWiFi() {
  WiFi.mode(WIFI_STA);
  // connect to the WiFi network
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    if( debug ) Serial.print(".");
  }
  if( debug ) {
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
  }
}

// Open connection to the HTTP server
bool connect(const char* hostName, const int port) {
  if( debug ) {
    Serial.print("Connect to ");
    Serial.println(hostName);
  }
  bool ok = client.connect(hostName, port);
  if( debug ) Serial.println(ok ? "Connected" : "Connection Failed!");
  return ok;
}
/* example  curl -vv http://www.google.de
* About to connect() to www.google.de port 80 (#0)
*   Trying 172.217.17.227...
* Connected to www.google.de (172.217.17.227) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: www.google.de
> Accept: * / *
*/
/* example response:
< HTTP/1.1 200 OK
< Date: Sun, 29 May 2016 10:00:14 GMT */ // Send the HTTP GET request to the server bool sendRequest(const char* host, const char* resource) {      if( debug ) {         Serial.print("GET ");         Serial.println(resource);     }     client.print("GET ");     client.print(resource);     client.println(" HTTP/1.1");     client.print("Host: ");     client.println(host);     client.println("Accept: */*");     client.println("Connection: close");     client.println();     return true;  }  bool findDateAndTimeInResponseHeaders() {     // date and time string starts with Date: and ends with GMT     // example: Date: Sun, 29 May 2016 10:00:14 GMT     client.setTimeout(HTTP_TIMEOUT);     char header[85];     size_t length = client.readBytes(header, 85);     header[length] = 0;     String headerString = String(header);     int ds = headerString.indexOf("Date: ");     int de = headerString.indexOf("GMT");     dateAndTime = headerString.substring(ds+6, de);     // date and time: Sun, 29 May 2016 10:00:14     if( debug ) {       Serial.print("HTTP response header ");       Serial.println(headerString.c_str());       Serial.print("index start date ");       Serial.println(ds);       Serial.print("index end time ");       Serial.println(de);       Serial.println(  );       Serial.print("date and time: ");       Serial.println(dateAndTime.c_str());     }    return dateAndTime.length()&amp;gt;15;
}

// Close the connection with the HTTP server
void disconnect() {
  if( debug ) Serial.println("Disconnect from HTTP server");
  client.stop();
}

//-------- time+date code ----------
// example: Sun, 29 May 2016 10:00:14
String extractDayFromDateTimeString(String dateTime) {
  uint8_t firstSpace = dateTime.indexOf(' ');
  String dayStr = dateTime.substring(firstSpace+1, firstSpace+3);
  if( debug ) {
    Serial.print("Day: ");
    Serial.println(dayStr.c_str());
  }
  return dayStr;
}

String extractMonthFromDateTimeString(String dateTime) {
  uint8_t firstSpace = dateTime.indexOf(' ', 7);
  String monthStr = dateTime.substring(firstSpace+1, firstSpace+4);
  if( debug ) {
    Serial.print("Month: ");
    Serial.println(monthStr.c_str());
  }
  return monthStr;
}

String extractYearFromDateTimeString(String dateTime) {
  uint8_t firstSpace = dateTime.indexOf(' ', 10);
  String yearStr = dateTime.substring(firstSpace+1, firstSpace+5);
  if( debug ) {
    Serial.print("Year: ");
    Serial.println(yearStr.c_str());
  }
  return yearStr;
}

String extractHourFromDateTimeString(String dateTime) {
  uint8_t firstColon = dateTime.indexOf(':');
  String hourStr = dateTime.substring(firstColon, firstColon-2);
  if( debug ) {
    Serial.print("Hour (GMT): ");
    Serial.println(hourStr.c_str());
  }
  // adjust GMT time
  int h = hourStr.toInt();
  h += 2; // summertime
  //h += 1; // wintertime
  if( debug ) {
    Serial.print("Hour (adjusted for summertime): ");
    Serial.println(h);
  }
  return String(h);
}

String extractMinuteFromDateTimeString(String dateTime) {
  uint8_t secondColon = dateTime.lastIndexOf(':');
  String minuteStr = dateTime.substring(secondColon, secondColon-2);
  if( debug ) {
    Serial.print("Minute: ");
    Serial.println(minuteStr.c_str());
  }
  return minuteStr;
}

String extractDayFromCalendarDate(String date) {
  String dateStr = String(date);
  uint8_t firstDot = dateStr.indexOf('.');
  String dayStr = dateStr.substring(1, firstDot);
  if( debug ) {
    Serial.print("Day: ");
    Serial.println(dayStr.c_str());
  }
  return dayStr;
}

String translateMonth(String monthStr) {
  if(monthStr.equals(String("Jan"))) return String("01");
  if(monthStr.equals(String("Feb"))) return String("02");
  if(monthStr.equals(String("Mar"))) return String("03");
  if(monthStr.equals(String("Apr"))) return String("04");
  if(monthStr.equals(String("May"))) return String("05");
  if(monthStr.equals(String("Jun"))) return String("06");
  if(monthStr.equals(String("Jul"))) return String("07");
  if(monthStr.equals(String("Aug"))) return String("08");
  if(monthStr.equals(String("Sep"))) return String("09");
  if(monthStr.equals(String("Oct"))) return String("10");
  if(monthStr.equals(String("Nov"))) return String("11");
  if(monthStr.equals(String("Dec"))) return String("12");
}

void showDateAndTime() {
  display.clearDisplay();

  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  String date = extractDayFromDateTimeString(dateAndTime);
  date += ".";
  date += translateMonth(extractMonthFromDateTimeString(dateAndTime));
  date += ".";
  date += extractYearFromDateTimeString(dateAndTime);
  display.println(date.c_str());
  String timeStr = extractHourFromDateTimeString(dateAndTime);
  timeStr += ":";
  timeStr += extractMinuteFromDateTimeString(dateAndTime);
  display.setCursor(30, 35);
  display.println(timeStr.c_str());

  display.display();
}

Results

oled_blog
Date and time extracted from HTTP response header on OLED display