Displays the current weather, date, and time

Dependencies:   mbed MbedJSONValue mbed-rtos 4DGL-uLCD-SE ESP8266NodeMCUInterface

Welcome to the Smart Weather Clock, which uses WiFi and Bluetooth to give the user a clear date, time, and weather for the day.

This wiki serves to document

  • What components you'll need
  • How these components will be connected
  • How the code gets all the information it needs

Components

LCD Screen

Components / 4D Systems 128 by 128 Smart Color LCD uLCD-144-G2
128 by 128 Color Smart LCD with serial interface and SD card slot

The LCD screen is a 128x128 pixel full color LCD by 4D Systems. A wonderful introduction can be found here.

In the simplest case, we'll only use one screen, but we can (and perhaps should) augment the design to include two.

Import library4DGL-uLCD-SE

Fork of 4DGL lib for uLCD-144-G2. Different command values needed. See https://mbed.org/users/4180_1/notebook/ulcd-144-g2-128-by-128-color-lcd/ for instructions and demo code.

You can buy it from sparkfun.

5V Adapter

The adapter allows us to feed much more power to the MBED and, critically, decouples us from a computer. It's important to remember that on the barrel jack adapter (i.e., the part that goes in the breadboard), the pin closest to the jack is 5V, and the back pin is Ground.

You can get the adapter here, and the barrel jack adapter here

Bluetooth UART Module

This module allows us to interface with the mbed via bluetooth and the ever-helpful AdaFruit Bluetooth App. A great introduction can be found here.

We'll use it to allow the user to set some defaults and API keys. This is stored in persistent flash storage on the LPC 1768 (See the Local File System, but you'll need an SD card if you're using a different MBED device.

You can get the Bluetooth module here.

WiFi Module

The WiFi module is also from AdaFruit, like the Bluetooth module. This allows us to interface with different WiFi networks for internet connectivity. A nice introduction is here.

You can get the WiFi module here.

WiFi Interface!

The current WiFi interface (found here) has some major problems - we're using an augmented version in our code!

Connections

5V Input for MBED

Before you connect the MBED to 5V from the wall, Make sure you have connected it correctly! If you don't, you could brick the MBED.

Thankfully, this is easy to test - when you think you have hooked up the 5V Jack correctly, try lighting a single LED (with a 10K resistor in series). If it lights up - you're good!

Alternatively, you could just plug in the MBED via USB, and just not have the MBED run on the +5V. You'll still need the Wall Adapter, however.

WiFi Module

The WiFi Module has two Grounds - you must connect both!

MBED5V Barrel Jack
Vin+5V (back pin)
GndGnd (pin closest to jack)
MBEDuLCD Cable
5V5V
GndGnd
P09TX
P10RX
P11Reset
MBEDBluetooth UART
5VVin
GndGnd
GndCTS
P27TXO
P28RXI
MBEDWiFi Module
5VV+
GndGnd
GndGnd
P13RX
P14TX
P15Reset

Code

The code works in a fairly logical order:

  1. Connect to the given WiFi, and check that we have all of our API keys
  2. Get the current location via the IP API
  3. Get the current time via the TimeZoneDB
  4. Get the current weather via the OpenWeatherMap API
  5. Continually update the weather, once per minute

Some caveats:

  • Memory seems to be an issue. If I had to guess, it would be the MbedJSONValue JSON parser - instantiating a third one seems to always lead to an MBED OS Fault or an MBED Memory Allocation fault. More insight is needed here.
  • The off-the-shelf ESP8226 Interface doesn't handle receiving correctly - I had to augment the library with recv and recv2. It works in most simple practical use cases.
Revision:
1:0620ba35d2e8
Parent:
0:4ffa136585a2
Child:
2:f7d19812bdc5
diff -r 4ffa136585a2 -r 0620ba35d2e8 main.cpp
--- a/main.cpp	Mon Mar 25 23:19:58 2019 +0000
+++ b/main.cpp	Fri Mar 29 13:12:49 2019 +0000
@@ -1,12 +1,229 @@
 #include "mbed.h"
+#include "uLCD_4DGL.h"
+#include "ESP8266Interface.h"
+#include "TCPSocketConnection.h"
+#include "rtos.h"
+
+// We need this for being able to reset the MBED (similar to watch dogs)
+extern "C" void mbed_reset();
+
+// LCD Screen
+uLCD_4DGL uLCD(p9, p10, p11);
+Mutex lcd_lock;
+
+// File System
+LocalFileSystem fs("local");
+
+// Bluetooth
+RawSerial pc(USBTX, USBRX);
+RawSerial dev(p28,p27);
+Thread dev_thread;
+
+// Error LED
+DigitalOut err_led(LED1);
+
+// WiFi
+ESP8266Interface wifi(p13, p14, p15, 9600, 10000);
+
+// Time
+Thread time_thread;
+
+// Weather
+Thread weather_thread;
+char* forecast_link;
 
-DigitalOut myled(LED1);
+void time_updater() {
+    // We're not an interrupt, so take as much time as we need. Infinite loop
+    // but wait 1 second between each loop
+    struct tm* ltm;
+    time_t now;
+    
+    now = time(NULL);
+    ltm = localtime(&now);
+    
+    // Buffer for time string. Max length is 23:59 + \0
+    int max_time_len = 6;
+    char ftime[max_time_len];
+    
+    int min = -1;
+    
+    while (true) {
+        // if the minute has changed, update.
+        now = time(NULL);
+        ltm = localtime(&now);
+        if(ltm->tm_min != min) {
+            // Get the new time
+            strftime(ftime, max_time_len, "%H:%M", ltm); 
+            // Update time! Lock the lcd mutex
+            lcd_lock.lock();
+            uLCD.text_width(2);
+            uLCD.text_height(2);
+            uLCD.text_string(ftime, 0, 2, FONT_8X8, GREEN);
+            // Done updating - unlock!
+            lcd_lock.unlock();
+            min = ltm->tm_min;
+        }
+        // Wait 1 second
+        Thread::wait(1.0f);
+    }   
+}
+
+void weather_updater() {
+    // We can take as long as we want
+    while (true) {
+        // get the weather
+        // we'll always want to update the LCD - don't worry about the previous
+        // weather
+        int curr_temp = 0;
+        int high_temp = 0;
+        int low_temp = 0;
+        char buf[12];
+        sprintf(buf, "%d %d/%d", curr_temp, high_temp, low_temp);
+        // lock
+        lcd_lock.lock();
+        uLCD.text_width(2);
+        uLCD.text_height(2);
+        // include null!
+        uLCD.text_string(buf, 0, 5, FONT_7X8, WHITE);
+        // done! unlock
+        lcd_lock.unlock();
+        Thread::wait(3600);
+    }
+}
+
+void dev_recv() {
+    // Continually check if we have stuff...
+    char buf[1024];
+    int ind = 0;
+    while (true) {
+        while (true) {
+            // get stuff. If we encounter \r or \n, that's a complete command!
+            char tmp = dev.getc();
+            if (tmp == '\n' || tmp == '\r') {
+                break;
+            }
+            buf[ind++] = tmp;
+            Thread::wait(0.01);
+        }
+        buf[ind] = '\0';
+        // read command and respond
+        if (strcmp(buf, "reset") == 0) {
+            dev.printf("Are you sure? y/[n]\n");
+        }
+        buf[0] = '\0';
+        ind = 0;
+        //if (strcmp(buf, "reset") != 0) {
+        Thread::wait(0.01);
+    }
+}       
 
 int main() {
-    while(1) {
-        myled = 1;
-        wait(0.2);
-        myled = 0;
-        wait(0.2);
+    // Set up bluetooth
+    dev.baud(9600);
+    pc.baud(9600);
+    // Tell user we're initializing...
+    lcd_lock.lock();
+    uLCD.cls();
+    uLCD.text_height(2);
+    uLCD.text_string("PLEASE WAIT", 0, 2, FONT_7X8, WHITE);
+    lcd_lock.unlock();
+    // Need to get wifi settings. If we don't have local file, then ask!
+    FILE* fid = NULL;//fopen("/local/settings.txt", "r");
+    // TODO: Get username and password
+    char ssid[256];
+    char pass[256];
+    if (fid == NULL) {
+        
+        //fclose(fid);
+    } else {
+        lcd_lock.lock();
+        uLCD.cls();
+        uLCD.text_height(2);
+        uLCD.text_width(2);
+        uLCD.text_string("SEE", 0, 2, FONT_7X8, RED);
+        uLCD.text_string("DEVICE", 0, 5, FONT_7X8, RED);
+        lcd_lock.unlock();
+        // Ask!
+        dev.printf("Please provide the name of a WiFi Network\n");
+        // Wait for them to respond
+        while (!dev.readable()) {
+            wait(0.001);
+        }
+        int ind = 0;
+        // Read response
+        while (ind < 255) {
+            char tmp = dev.getc();
+            if (tmp == '\n' || tmp == '\r') {
+                break;
+            }
+            ssid[ind++] = tmp;
+            wait(0.01);
+        }
+        ssid[ind] = '\0';
+        
+        // flush device
+        while (dev.readable()) {
+            dev.getc();
+            wait(0.01);
+        }
+        
+        dev.printf("Please provide the password\n");
+        while (!dev.readable()) {
+            wait(0.001);
+        }
+        ind = 0;
+        while (ind < 255) {
+            char tmp = dev.getc();
+            if (tmp == '\n' || tmp == '\r') {
+                break;
+            }
+            pass[ind++] = tmp;
+            wait(0.01);
+        }
+        pass[ind] = '\0';
+        // Because this is a simple proof of concept, we store the password in 
+        // plaintext. It should be noted, however, that you **should never do 
+        // this in "real life"**
+        //fid = fopen("/local/settings.txt", "w");
+        //fprintf(fid, "ssid: %s\npass: %s\n", ssid, pass);
+        //fclose(fid);
+    }
+    
+    bool res = wifi.init();
+    //dev.printf("Reset: %d\n", res);
+    // Set up the WiFi Access Point
+    dev.printf("Connecting to WiFi %s with Password %s\n", ssid, pass);
+    res = wifi.connect("Alex's iPhone", "mbedlookhere");
+    //if (!res) {
+    //    dev.printf("Connection Failed... Resetting Device\n");
+        // mbed_reset();
+    //}
+    dev.printf("Is Connected: %d\n", wifi.is_connected());
+    dev.printf("IP Address: %s\n", wifi.getIPAddress());
+    TCPSocketConnection tcp;
+    int tcp_res = tcp.connect("13.58.105.158", 80);
+    dev.printf("Connection: %d\n", tcp_res);
+    // Where are we & What time is it?
+    // Create the TCP connection, request from ipstack. Get the request,
+    // and store the current time (FORMAT?)
+    set_time(1256729737);
+    // Now that we know what time it is, set up our Time Thread
+    time_thread.start(time_updater);
+    // Now, make a single request to nws and get the forecast link - we can 
+    // store this link for later!
+    lcd_lock.lock();
+    uLCD.cls();
+    lcd_lock.unlock();
+    
+    // Start up weather service!
+    weather_thread.start(weather_updater);
+    
+    //weather_ticker.attach(&weather_tick, 900000.0f);
+    // Listen on bluetooth.
+    dev_thread.start(dev_recv);
+    while(true) {
+        err_led = !err_led;
+        //dev.printf("Connection Status: %d\n", wifi.is_connected());
+        wait(0.5);
     }
 }