Community project

Solar Battery Home Dashboard

Photo of Solar Battery Home Dashboard

walkerleigh

Published November 16, 2026

This project builds a real-time home energy dashboard on a 480x480 display powered by an ESP32. It pulls data from solar inverters, battery systems, EV chargers, and weather services to show generation, consumption, storage, and grid flow at a glance.

The guide includes a complete wiring diagram for the display board and ESP32, a full parts list, step-by-step assembly instructions, and ready-to-use firmware. Configuration happens through a web-based entity settings page where users map their Home Assistant sensors to dashboard widgets.

Wiring diagram

Wiring diagram for Solar Battery Home Dashboard
Loading diagram…

Assemble it in 3 steps

1. Use the complete display board

The LCD and all control wiring are already built into the Waveshare 4B. No external parts or jumper wires are needed. Leave the battery socket and expansion pins unused.

2. Connect USB power

Connect the USB TO UART Type-C port to your computer with a data-capable USB cable. Keep the board on a dry, non-metal surface.

  • This display only reads Home Assistant. Do not connect it to mains, solar panels, inverter wiring or battery terminals.

3. Open the entity settings page

After Wi-Fi connects, briefly press BOOT. The current IP address appears in the top-right corner for 30 seconds. On a phone or computer on the same local network, open http:// followed by that address. Edit the Home Assistant entity names and press Save entity names within five minutes of pressing BOOT. A small countdown shows the remaining editing time. When it expires, the page reloads with a message to press BOOT again; unsaved edits are discarded. Settings survive power loss and restart. Press BOOT again to show the address and reopen the saving window.

  • Press BOOT only after startup. Holding it while powering on or resetting enters download mode.
  • Use this HTTP settings page only on a trusted local network. Do not expose it to the internet. The Home Assistant token is not shown or editable on the page.

Deploy the firmware

#include <Arduino.h>
#include <Wire.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <WebServer.h>
#include <Preferences.h>
#include <ArduinoJson.h>
#include <Arduino_GFX_Library.h>
#include <time.h>
#include "Roboto8.h"
#include "Roboto12.h"
#include "config.h"
#include "day_plugged.h"
#include "day_unplugged.h"
#include "night_plugged.h"
#include "night_unplugged.h"
#include "ChristmasTree.h"
Arduino_XCA9554SWSPI *expander = new Arduino_XCA9554SWSPI(7,0,2,1,&Wire,0x20);
Arduino_ESP32RGBPanel *panel = new Arduino_ESP32RGBPanel(
 17,3,46,9,10,11,12,13,14,21,8,18,45,38,39,40,41,42,2,1,
 1,10,8,50,1,10,8,20,
 0,12000000,false,0,0,480*10);
Arduino_RGB_Display *gfx = new Arduino_RGB_Display(480,480,panel,0,true,
 expander,GFX_NOT_DEFINED,st7701_type1_init_operations,sizeof(st7701_type1_init_operations));
String entities[] = {
 "sensor.foxess_modbus_foxess_modbus_pv_power_foxess_modbus",
 "sensor.foxess_modbus_grid_ct", "sensor.foxess_modbus_battery_soc",
 "sensor.foxess_modbus_load_power", "sensor.foxess_modbus_battery_charge",
 "sensor.foxess_modbus_battery_discharge", "binary_sensor.hypervolt_car_plugged",
 "sensor.hypervolt_ev_power", "sensor.byd_sealion_7_battery_level",
 "sensor.foxess_modbus_inverter_fault_code", "select.foxess_modbus_work_mode",
 "weather.bligh_park_weather", "sensor.sun_next_rising", "sensor.sun_next_setting"};
WebServer web(80);
Preferences settings;
const char *entityLabels[] = {"Solar power", "Grid power", "Battery SOC", "Home load",
 "Battery charge power", "Battery discharge power", "EV plugged", "EV power",
 "EV battery level", "Inverter fault", "Work mode", "Weather", "Next sunrise", "Next sunset"};
volatile bool bootPressed=false;
uint32_t ipUntil=0, editUntil=0;
String formNonce, ipCache;
String timeServer="10.1.1.204";
String timeZone="AEST-10AEDT,M10.1.0,M4.1.0/3";
void syncClock() { configTzTime(timeZone.c_str(),timeServer.c_str()); }
bool validTimeSetting(const String &value,bool zone=false) {
 if(!value.length() || value.length()>120) return false;
 for(unsigned int i=0;i<value.length();++i) {
  char c=value[i];
  if(!isalnum((unsigned char)c) && c!='.' && c!='-' && !(zone && (c=='+' || c==',' || c==':' || c=='/' || c=='<' || c=='>'))) return false;
 }
 return true;
}
void IRAM_ATTR bootISR() { bootPressed=true; }
String values[14], previous;
uint32_t lastGoodReading[14]={};
bool delayedReading[14]={};
String weatherTemperature, weatherUnit, weatherCache;
bool fullRedraw=true;
String boxCache[12];
int boxIndex=0;
bool plugged=false, plugKnown=false;
bool night=true;
time_t sunrise=0, sunset=0;
time_t parseSunTime(const String &value) {
 int y,m,d,h,minute; float sec;
 if(sscanf(value.c_str(),"%d-%d-%dT%d:%d:%f",&y,&m,&d,&h,&minute,&sec)!=6) return 0;
 struct tm t={}; t.tm_year=y-1900; t.tm_mon=m-1; t.tm_mday=d;
 t.tm_hour=h; t.tm_min=minute; t.tm_sec=int(sec);
 // Convert civil UTC without changing the device's local timezone.
 int yy=y-(m<=2); int era=(yy>=0?yy:yy-399)/400;
 unsigned yoe=unsigned(yy-era*400);
 unsigned doy=(153*(m+(m>2?-3:9))+2)/5+d-1;
 unsigned doe=yoe*365+yoe/4-yoe/100+doy;
 time_t stamp=time_t(era*146097+int(doe)-719468)*86400+h*3600+minute*60+int(sec);
 int offsetPos=value.indexOf('+',19);
 if(offsetPos<0) offsetPos=value.indexOf('-',19);
 if(offsetPos>=0) {
  int oh=0,om=0;
  if(sscanf(value.c_str()+offsetPos+1,"%d:%d",&oh,&om)!=2) return 0;
  stamp+=(value[offsetPos]=='+'?-1:1)*(oh*3600+om*60);
 } else if(!value.endsWith("Z")) return 0;
 return stamp;
}
void updateDaylight() {
 time_t now=time(nullptr);
 if(now<1700000000 || !sunrise || !sunset) return;
 if(sunrise<=now && sunset<=now) night=sunset>sunrise;
 else if(sunrise<=now) night=false;
 else if(sunset<=now) night=true;
 else night=sunrise<sunset;
}
const uint16_t *activeImage() {
 return night ? (plugged?NIGHT_PLUGGED_DATA:NIGHT_UNPLUGGED_DATA)
              : (plugged?DAY_PLUGGED_DATA:DAY_UNPLUGGED_DATA);
}
uint32_t nextPoll=0;
uint16_t row[480];
bool editUnlocked() { return editUntil && (int32_t)(editUntil-millis())>0; }
String htmlEscape(String text) {
 text.replace("&","&amp;"); text.replace("<","&lt;"); text.replace(">","&gt;");
 text.replace("\"","&quot;"); text.replace("'","&#39;"); return text;
}
bool validEntity(const String &id) {
 int dot=id.indexOf('.');
 if(dot<1 || dot==int(id.length())-1 || id.length()>160) return false;
 for(unsigned int i=0;i<id.length();++i) {
  char c=id[i];
  if(!((c>='a' && c<='z') || (c>='0' && c<='9') || c=='_' || (c=='.' && int(i)==dot))) return false;
 }
 return true;
}
void setupWeb() {
 settings.begin("ha-dashboard",false);
 String savedServer=settings.getString("ntp",timeServer);
 String savedZone=settings.getString("tz",timeZone);
 if(validTimeSetting(savedServer)) timeServer=savedServer;
 if(validTimeSetting(savedZone,true)) timeZone=savedZone;
 String stored=settings.isKey("entities") ? settings.getString("entities", "") : String("");
 JsonDocument doc;
 if(stored.length() && !deserializeJson(doc,stored)) {
  for(int i=0;i<14;++i) {
   String id=doc[i].as<String>(); if(validEntity(id)) entities[i]=id;
  }
 }
 formNonce=String((uint32_t)esp_random(),HEX)+String((uint32_t)esp_random(),HEX);
 web.on("/",HTTP_GET,[]() {
  String page="<!doctype html><html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>Home Energy settings</title><style>body{font:16px system-ui;max-width:700px;margin:24px auto;padding:0 16px;background:#17212b;color:white}label{display:block;margin-top:18px}input{box-sizing:border-box;width:100%;padding:10px;margin-top:5px}button{padding:12px;margin:24px 0}small{color:#ccc}</style></head><body><h1>Home Energy settings</h1><p>Device IP: ";
  page+=WiFi.localIP().toString();
  if(!editUnlocked()) {
   page+="</p><p>The settings window is closed. Press the display's BOOT button, then reload this page to edit entity names for five minutes.</p></body></html>";
   web.sendHeader("Cache-Control","no-store"); web.send(200,"text/html",page); return;
  }
  uint32_t remaining=editUntil-millis();
  page+="</p><small id='countdown' role='timer' aria-label='Time remaining to save'></small>";
  page+="<script>let deadline=performance.now()+"+String(remaining)+";function tick(){let seconds=Math.max(0,Math.ceil((deadline-performance.now())/1000));document.getElementById('countdown').textContent='Time remaining: '+Math.floor(seconds/60)+':'+String(seconds%60).padStart(2,'0');if(!seconds)location.reload();}setInterval(tick,250);tick();setInterval(async()=>{try{let r=await fetch('/edit-time',{cache:'no-store'});if(r.ok){let ms=Number(await r.text());if(ms<=0){location.reload();return;}deadline=performance.now()+ms;tick();}}catch(e){}},2000);document.addEventListener('visibilitychange',()=>{if(!document.hidden)tick();});</script>";
  page+="</p><p>Press the display's BOOT button to allow saving for five minutes. Names are saved across restarts. Power units and display behaviour stay unchanged.</p><form method='post' action='/save'><input type='hidden' name='nonce' value='"+formNonce+"'>";
  for(int i=0;i<14;++i) page+="<label>"+String(entityLabels[i])+"<input required maxlength='160' name='e"+String(i)+"' value='"+htmlEscape(entities[i])+"'></label>";
  page+="<label>Time server (NTP address)<input required maxlength='120' name='ntp' value='"+htmlEscape(timeServer)+"'></label><label>Time zone (POSIX rule)<input required maxlength='120' name='tz' value='"+htmlEscape(timeZone)+"'></label><small>Sydney: AEST-10AEDT,M10.1.0,M4.1.0/3. UTC: UTC0. The rule sets local time and daylight saving automatically.</small>";
  page+="<button type='submit'>Save settings</button></form><small>Local network only. Do not forward this device's web port to the internet. Home Assistant credentials are never included on this page.</small></body></html>";
  web.sendHeader("Cache-Control","no-store"); web.send(200,"text/html",page);
 });
 web.on("/edit-time",HTTP_GET,[]() {
  uint32_t remaining=editUnlocked()?editUntil-millis():0;
  web.sendHeader("Cache-Control","no-store");
  web.send(200,"text/plain",String(remaining));
 });
 web.on("/save",HTTP_POST,[]() {
  if(!editUnlocked() || web.arg("nonce")!=formNonce) {
   web.send(403,"text/plain","Press BOOT on the display, then reload the settings page and save within five minutes."); return;
  }
  String newServer=web.arg("ntp"), newZone=web.arg("tz");
  newServer.trim(); newZone.trim();
  if(!validTimeSetting(newServer) || !validTimeSetting(newZone,true)) {web.send(400,"text/plain","Invalid time server or time-zone rule."); return;}
  String updated[14]; JsonDocument doc;
  for(int i=0;i<14;++i) {
   updated[i]=web.arg("e"+String(i)); updated[i].trim();
   if(!validEntity(updated[i])) {web.send(400,"text/plain","Invalid entity name. Use lowercase domain.name with letters, numbers and underscores."); return;}
   doc.add(updated[i]);
  }
  String stored; serializeJson(doc,stored);
  if(!settings.putString("entities",stored)) {web.send(500,"text/plain","Could not save settings. Try again."); return;}
  if(!settings.putString("ntp",newServer) || !settings.putString("tz",newZone)) {web.send(500,"text/plain","Could not save time settings. Try again."); return;}
  timeServer=newServer; timeZone=newZone; syncClock(); ipCache="!";
  for(int i=0;i<14;++i) {entities[i]=updated[i]; values[i]="";}
  nextPoll=0;
  web.sendHeader("Location","/"); web.send(303,"text/plain","Saved");
 });
 web.begin();
}
// Seasonal decoration is part of the background, so partial redraws preserve it.
bool christmasVisible=false;
bool christmasSeason() {
 time_t now=time(nullptr);
 struct tm date;
 if(now<1700000000 || !localtime_r(&now,&date)) return false;
 return (date.tm_mon==10 && date.tm_mday>=15) || date.tm_mon==11 ||
        (date.tm_mon==0 && date.tm_mday==1);
}
uint16_t blendText(uint16_t fg,uint16_t bg,int alpha);
uint16_t backgroundPixel(const uint16_t *image,int x,int y) {
 uint16_t bg=pgm_read_word(image+y*480+x);
 // Use the uploaded tree in either garage-door variant, at night only.
 // Transparent silhouette preserves both original garage backgrounds.
 if(christmasVisible && night && x>=TREE_X && x<TREE_X+TREE_W &&
    y>=TREE_Y && y<TREE_Y+TREE_H) {
  int tx=x-TREE_X,ty=y-TREE_Y;
  // Tree mask is 0..255; blendText expects 0..16 (fully opaque).
  int alpha=(christmasTreeAlpha(tx,ty)*16+127)/255;
  uint16_t tree=pgm_read_word(CHRISTMAS_TREE_DATA+ty*TREE_W+tx);
  bg=blendText(tree,bg,alpha);
 }
 return bg;
}
void restore(int x,int y,int w,int h) {
 const uint16_t *image = activeImage();
 for(int yy=y; yy<y+h && yy<480; ++yy) {
  for(int xx=0;xx<w;xx++) row[xx]=backgroundPixel(image,x+xx,yy);
  // Write composed pixels directly: avoid the single-row bitmap fast path.
  gfx->startWrite();
  for(int xx=0;xx<w && x+xx<480;++xx) gfx->writePixel(x+xx,yy,row[xx]);
  gfx->endWrite();
 }
}
int textWidth(const String &text,const GFXfont *font);
void textAt(int x,int y,const String &text,const GFXfont *font,uint16_t color,bool heavy,int32_t solidBackground);
void serviceControls() {
 static uint32_t lastPress=0;
 if(bootPressed) {
  bootPressed=false;
  uint32_t now=millis();
  if(!lastPress || now-lastPress>250) {lastPress=now; ipUntil=now+30000; editUntil=now+300000;}
 }
 time_t nowTime=time(nullptr);
 struct tm local;
 String clockText="--:--";
 if(nowTime>1700000000 && localtime_r(&nowTime,&local)) {
  char formatted[6]; strftime(formatted,sizeof(formatted),"%H:%M",&local); clockText=formatted;
 }
 String ip=(ipUntil && (int32_t)(ipUntil-millis())>0)?
  (WiFi.status()==WL_CONNECTED?WiFi.localIP().toString():String("No Wi-Fi")):clockText;
 if(ip!=ipCache) {
  ipCache=ip;
  restore(290,0,190,18);
  restore(384,18,78,34);
  // Align the larger clock with the badge text, with matching edge padding.
  textAt(462-textWidth(clockText,&Roboto_Regular12pt7b),26,clockText,&Roboto_Regular12pt7b,0xFFFF,false,-1);
  if(ipUntil && (int32_t)(ipUntil-millis())>0)
   textAt(462-textWidth(ip,&Roboto_Regular8pt7b),1,ip,&Roboto_Regular8pt7b,0xFFFF,false,-1);
 }
 web.handleClient();
}
void background() { restore(0,0,480,480); gfx->flush(true); }
uint16_t blendText(uint16_t fg,uint16_t bg,int alpha);
// Local animation only: no extra Home Assistant requests.
struct FlowPoint { int16_t x,y; };
struct FlowPath { FlowPoint points[5]; uint8_t count; uint16_t color; };
// Traced from the user-marked 480x480 connection-lines.jpg.
// Follow both ground bends before fading past the garage; normal SOC green.
const FlowPath flowPaths[] = {
 {{{185,195},{185,270}},2,0x07E0}, // Apex down to inverter
 {{{185,306},{185,320}},2,0x07E0}, // Inverter down to battery
 {{{192,298},{253,313},{253,379},{177,405},{8,352}},5,0x07E0}, // Corner, ground, grid
 {{{192,298},{253,313},{300,300}},3,0x07E0} // Corner branch into home
};
// Do not draw OR erase a dot over a reading. Include the full 11x11
// restoration footprint, not just the dot centre, to protect font edges.
bool flowOverlapsText(int x,int y) {
 const int boxes[][4]={{0,0,480,110},{192,99,170,48},
  {24,413,174,65},{196,382,164,96},{362,413,118,65}};
 for(const auto &r:boxes)
  if(x+5>=r[0] && x-5<r[0]+r[2] && y+5>=r[1] && y-5<r[1]+r[3]) return true;
 if(plugged && x-5<184 && x+5>=18 && y+5>=142 && y-5<238) return true;
 return false;
}
struct FlowDot { int16_t x,y; bool visible; };
FlowDot flowDots[4][3]={};
int flowDirection[4]={};
uint32_t flowValidUntil=0;
void eraseFlowDots() {
 for(auto &path:flowDots) for(auto &dot:path) if(dot.visible) {
  restore(dot.x-5,dot.y-5,11,11); dot.visible=false;
 }
}
void updateFlows() {
 const double threshold=0.020; // 20 W dead band
 flowDirection[0]=values[0].length() && values[0].toDouble()>threshold?1:0;
 flowDirection[1]=0;
 if(values[4].length() && values[5].length()) {
  double net=fabs(values[4].toDouble())-fabs(values[5].toDouble());
  flowDirection[1]=net>threshold?1:net<-threshold?-1:0;
 }
 flowDirection[2]=values[1].length() && fabs(values[1].toDouble())>threshold?
  (values[1].toDouble()>0?1:-1):0;
 flowDirection[3]=values[3].length() && values[3].toDouble()>threshold?1:0;
 flowValidUntil=millis()+45000; // Never animate indefinitely on stale readings.
}
void animateFlows() {
 static uint32_t lastFrame=0;
 uint32_t now=millis();
 if(now-lastFrame<50) return;
 lastFrame=now;
 eraseFlowDots();
 if(WiFi.status()!=WL_CONNECTED || (int32_t)(flowValidUntil-now)<=0) return;
 for(int i=0;i<4;++i) {
  if(!flowDirection[i]) continue;
  const FlowPath &path=flowPaths[i];
  float lengths[4]={},total=0;
  for(int j=0;j<path.count-1;++j) {
   lengths[j]=hypotf(path.points[j+1].x-path.points[j].x,path.points[j+1].y-path.points[j].y);
   total+=lengths[j];
  }
  for(int d=0;d<3;++d) {
   float distance=fmodf(now*0.035f+d*total/3,total);
   if(flowDirection[i]<0) distance=total-distance;
   int segment=0;
   while(segment<path.count-2 && distance>lengths[segment]) distance-=lengths[segment++];
   float t=distance/lengths[segment];
   int x=lroundf(path.points[segment].x+t*(path.points[segment+1].x-path.points[segment].x));
   int y=lroundf(path.points[segment].y+t*(path.points[segment+1].y-path.points[segment].y));
   if(flowOverlapsText(x,y)) continue;
   flowDots[i][d]={(int16_t)x,(int16_t)y,true};
   const uint16_t *image=activeImage();
   for(int dy=-3;dy<=3;++dy) for(int dx=-3;dx<=3;++dx) {
    int radius=dx*dx+dy*dy;
    if(radius>10) continue;
    uint16_t bg=backgroundPixel(image,x+dx,y+dy);
    gfx->drawPixel(x+dx,y+dy,blendText(path.color,bg,(night?(radius<=2?10:radius<=5?6:3):(radius<=2?16:radius<=5?11:5))*(i==2 && segment==3 ? max(0,int(16*(1-t))) : 16)/16));
   }
  }
 }
}
String power(int index) {
 if(!values[index].length()) return "--";
 double watts=fabs(values[index].toDouble())*(index==7?1.0:1000.0);
 return watts<1000 ? String(watts,0)+"W" : String(watts/1000.0,2)+"kW";
}
String percent(int index) { return values[index].length()?values[index]+"%":String("--"); }
// Custom fonts use a baseline; measure ink bounds to position by top-left.
int textWidth(const String &text,const GFXfont *font) {
 gfx->setFont(font); gfx->setTextSize(1);
 int16_t bx,by; uint16_t bw,bh;
 gfx->getTextBounds(text.c_str(),0,0,&bx,&by,&bw,&bh);
 return bw;
}
// Blend softened bitmap edges with the image or the badge's solid colour.
uint16_t blendText(uint16_t fg,uint16_t bg,int alpha) {
 int r=(((fg>>11)&31)*alpha+((bg>>11)&31)*(16-alpha)+8)/16;
 int g=(((fg>>5)&63)*alpha+((bg>>5)&63)*(16-alpha)+8)/16;
 int b=((fg&31)*alpha+(bg&31)*(16-alpha)+8)/16;
 return (r<<11)|(g<<5)|b;
}
void textAt(int x,int y,const String &text,const GFXfont *font,uint16_t color,
            bool heavy=false,int32_t solidBackground=-1) {
 gfx->setFont(font); gfx->setTextSize(1); gfx->setTextWrap(false);
 int16_t bx,by; uint16_t bw,bh;
 gfx->getTextBounds(text.c_str(),0,0,&bx,&by,&bw,&bh);
 if(!bw || !bh) return;
 static uint8_t mask[480*40];
 int w=min(480,int(bw)+3+(heavy?1:0)), h=min(40,int(bh)+2);
 memset(mask,0,w*h);
 int cursor=1-bx;
 for(unsigned int i=0;i<text.length();++i) {
  unsigned char c=text[i];
  if(c<font->first || c>font->last) continue;
  const GFXglyph &g=font->glyph[c-font->first];
  for(int gy=0;gy<g.height;++gy) for(int gx=0;gx<g.width;++gx) {
   int bit=gy*g.width+gx;
   if(!(pgm_read_byte(font->bitmap+g.bitmapOffset+bit/8)&(0x80>>(bit%8)))) continue;
   int mx=cursor+g.xOffset+gx, my=1-by+g.yOffset+gy;
   if(mx>=0 && mx<w && my>=0 && my<h) mask[my*w+mx]=1;
   if(heavy && mx+1>=0 && mx+1<w && my>=0 && my<h) mask[my*w+mx+1]=1;
  }
  cursor+=g.xAdvance;
 }
 const uint16_t *image=activeImage();
 for(int my=0;my<h;++my) for(int mx=0;mx<w;++mx) {
  int alpha=12*mask[my*w+mx];
  if(mx>0) alpha+=mask[my*w+mx-1];
  if(mx+1<w) alpha+=mask[my*w+mx+1];
  if(my>0) alpha+=mask[(my-1)*w+mx];
  if(my+1<h) alpha+=mask[(my+1)*w+mx];
  int px=x+mx-1,py=y+my-1;
  if(!alpha || px<0 || px>=480 || py<0 || py>=480) continue;
  uint16_t bg=solidBackground>=0?uint16_t(solidBackground):
   backgroundPixel(image,px,py);
  gfx->drawPixel(px,py,blendText(color,bg,alpha));
 }
}
// Transparent MDI artwork; the field cache also tracks direction changes.
#include "GridIcons.h"
void gridIconAt(int x,int y,bool importing) {
 const uint8_t *mask=importing?gridImportIcon:gridExportIcon;
 const uint16_t *image=activeImage();
 for(int dy=0;dy<28;++dy) for(int dx=0;dx<28;++dx) {
  int alpha=pgm_read_byte(mask+dy*28+dx);
  if(!alpha) continue;
  int px=x+dx,py=y+dy;
  uint16_t bg=backgroundPixel(image,px,py);
  gfx->drawPixel(px,py,blendText(0xFFFF,bg,alpha));
 }
}
void field(int x,int y,int w,int h,const String &label,const String &value,
           uint16_t color=0xFFFF,const String &extra="",uint32_t valueColor=0x10000,int gridDirection=0) {
 int slot=boxIndex++;
 String key=label+"|"+value+"|"+extra+"|"+String(color)+"|"+String(valueColor)+"|"+String(gridDirection);
 if(!fullRedraw && boxCache[slot]==key) return;
 boxCache[slot]=key;
 restore(x,y,w,h);
 textAt(x+3,y+3,label,&Roboto_Regular8pt7b,color);
 textAt(x+3,y+19,value,&Roboto_Regular12pt7b,valueColor<=0xFFFF?uint16_t(valueColor):color,true);
 if(gridDirection) gridIconAt(x+textWidth(value,&Roboto_Regular12pt7b)+11,y+16,gridDirection<0);
 if(extra.length()) {
  textAt(x+3,y+43,extra,&Roboto_Regular12pt7b,color,true);
 }
}
void badge(int x,int w,const String &text,uint16_t bg,uint16_t fg,bool fitText=false) {
 int slot=boxIndex++;
 String key=text+String(bg)+"|"+String(x)+"|"+String(w);
 if(!fullRedraw && boxCache[slot]==key) return;
 boxCache[slot]=key;
 restore(x,18,w,34);
 const GFXfont *font=&Roboto_Regular12pt7b;
 if(textWidth(text,font)>w-12) font=&Roboto_Regular8pt7b;
 String shown=text;
 while(shown.length() && textWidth(shown,font)>w-12) shown.remove(shown.length()-1);
 int badgeWidth=fitText?min(w,textWidth(shown,font)+12):w;
 gfx->fillRoundRect(x,18,badgeWidth,34,6,bg);
 int16_t bx,by; uint16_t bw,bh;
 gfx->getTextBounds(shown.c_str(),0,0,&bx,&by,&bw,&bh);
 textAt(x+6,18+(34-bh)/2,shown,font,fg,false,bg);
}
// Small transparent weather graphics, embedded as drawing instructions.
void weatherDisc(int cx,int cy,int r,uint16_t color,bool crescent=false) {
 for(int dy=-r;dy<=r;++dy) for(int dx=-r;dx<=r;++dx) {
  if(dx*dx+dy*dy>r*r) continue;
  if(crescent && (dx-6)*(dx-6)+(dy+4)*(dy+4)<r*r) continue;
  gfx->drawPixel(cx+dx,cy+dy,color);
 }
}
void drawWeather() {
 String key=values[11]+"|"+weatherTemperature+"|"+weatherUnit;
 if(!fullRedraw && weatherCache==key) return;
 weatherCache=key;
 restore(18,60,166,50);
 const String &condition=values[11];
 const uint16_t yellow=0xFFE0, cloud=0xDEFB, blue=0x5DFF;
 if(condition=="sunny" || condition=="partlycloudy") {
  int cx=condition=="sunny"?42:35,cy=condition=="sunny"?82:75;
  weatherDisc(cx,cy,9,yellow);
  for(int i=0;i<8;++i) {
   float a=i*PI/4;
   for(int r=12;r<=16;++r) gfx->drawPixel(cx+int(round(cos(a)*r)),cy+int(round(sin(a)*r)),yellow);
  }
 }
 if(condition=="clear-night") weatherDisc(42,82,16,0xFFB0,true);
 bool cloudy=condition=="cloudy" || condition=="partlycloudy" || condition=="rainy" ||
  condition=="pouring" || condition=="lightning" || condition=="lightning-rainy" ||
  condition=="snowy" || condition=="snowy-rainy" || condition=="hail" || condition=="windy-variant";
 if(cloudy) {
  weatherDisc(32,82,8,cloud); weatherDisc(42,77,11,cloud); weatherDisc(53,83,8,cloud);
  gfx->fillRect(32,82,22,9,cloud);
 }
 if(condition=="rainy" || condition=="pouring" || condition=="lightning-rainy" || condition=="snowy-rainy") {
  for(int x=31;x<=55;x+=10) for(int d=0;d<7;++d) gfx->drawPixel(x-d/2,94+d,blue);
  if(condition=="pouring") for(int x=36;x<=56;x+=10) for(int d=0;d<6;++d) gfx->drawPixel(x-d/2,98+d,blue);
 }
 if(condition=="lightning" || condition=="lightning-rainy") {
  for(int y=88;y<104;++y) {int x=45-(y-88)/2+(y>=96?5:0); gfx->fillRect(x,y,4,1,yellow);}
 }
 if(condition=="snowy" || condition=="snowy-rainy" || condition=="hail") {
  for(int x=32;x<=56;x+=11) {
   weatherDisc(x,98,2,0xFFFF);
   if(condition!="hail") {gfx->fillRect(x-3,98,7,1,0xFFFF);gfx->fillRect(x,95,1,7,0xFFFF);}
  }
 }
 if(condition=="fog" || condition=="windy" || condition=="windy-variant") {
  for(int i=0;i<3;++i) gfx->fillRect(24+i*3,condition=="windy-variant"?94+i*5:73+i*8,32-i*3,2,cloud);
 }
 if(condition=="exceptional") textAt(35,73,"!",&Roboto_Regular12pt7b,0xF800,true);
 else if(!condition.length() || (!cloudy && condition!="sunny" && condition!="clear-night" && condition!="fog" && condition!="windy"))
  textAt(34,73,"?",&Roboto_Regular12pt7b,0xFFFF,true);
 String temp=weatherTemperature.length()?weatherTemperature:String("--");
 textAt(72,76,temp,&Roboto_Regular12pt7b,0xFFFF,true);
 if(weatherTemperature.length()) {
  int unitX=72+textWidth(temp,&Roboto_Regular12pt7b)+5;
  // Roboto's embedded ASCII subset lacks the degree glyph.
  for(int dy=-3;dy<=3;++dy) for(int dx=-3;dx<=3;++dx)
   if(dx*dx+dy*dy>=2 && dx*dx+dy*dy<=5) gfx->drawPixel(unitX+dx,78+dy,0xFFFF);
  textAt(unitX+5,76,weatherUnit,&Roboto_Regular12pt7b,0xFFFF);
 }
}
void render(const String &status) {
 updateDaylight();
 bool seasonalChange=christmasVisible!=christmasSeason();
 christmasVisible=christmasSeason();
 String signature=status+String(night)+String(plugged)+String(plugKnown)+String(christmasVisible)+weatherTemperature+"|"+weatherUnit;
 for(auto &v:values) signature+='|'+v;
 if(signature==previous) return;
 previous=signature;
 static bool first=true, lastPlugged=false, lastNight=true;
 static String lastStatus;
 String notice=status=="HOME ENERGY | Home Assistant connected"?String(""):status;
 // Status glyphs and their softened edges can extend into the badge area.
 // Repaint the background and fields on status transitions to remove all old ink.
 fullRedraw=first || seasonalChange || lastPlugged!=plugged || lastNight!=night || notice!=lastStatus;
 eraseFlowDots();
 boxIndex=0;
 if(fullRedraw) background();
 bool normal=values[9]=="None";
 String faultText=values[9].length()?(normal?String("Normal"):values[9]):String("Unavailable");
 int faultWidth=normal?min(148,textWidth(faultText,&Roboto_Regular12pt7b)+12):148;
 int modeX=18+faultWidth+6;
 // Clear both badges together when either changes, including their old positions.
 static String lastBadges;
 String badgesKey=faultText+"|"+values[10];
 if(fullRedraw || badgesKey!=lastBadges) {
  restore(18,18,444,34);
  ipCache="!";
  boxCache[0]=""; boxCache[1]="";
  lastBadges=badgesKey;
 }
 badge(18,148,faultText,normal?0x2528:0xF800,0xFFFF,normal);
 uint16_t modeColor=0xC618;
 if(values[10]=="Self Use") modeColor=0xFF50;
 else if(values[10]=="Feed-in First") modeColor=0xFC9F;
 else if(values[10]=="Back-up") modeColor=0x471A;
 else if(values[10]=="Force Charge") modeColor=0xF800;
 else if(values[10]=="Force Discharge") modeColor=0x001F;
 badge(modeX,378-modeX,values[10].length()?values[10]:String("Unavailable"),modeColor,(values[10]=="Force Charge" || values[10]=="Force Discharge")?0xFFFF:0x0000,true);
 drawWeather();
 field(192,99,170,48,"SOLAR",power(0),night?0xFFFF:0x0000);
 String gridLabel=values[1].length()?(values[1].toDouble()<0?"GRID IMPORTING":"GRID EXPORTING"):"GRID";
 bool importWarning=values[1].length() && values[1].toDouble()<-0.100 && values[10]!="Force Charge";
 field(24,413,174,65,gridLabel,power(1),0xFFFF,"",importWarning?0xF800:0xFFFF,values[1].length()?(values[1].toDouble()<0?-1:1):0);
 String batteryLabel="BATTERY", batteryPower="--";
 if(values[4].length() && values[5].length()) {
  if(fabs(values[4].toDouble())>0) {batteryLabel="CHARGING"; batteryPower=power(4);}
  else if(fabs(values[5].toDouble())>0) {batteryLabel="DISCHARGING"; batteryPower=power(5);}
  else batteryPower="0W";
 }
 uint16_t socColor=values[2].length() && values[2].toDouble()<20.0?0xF800:0x07E0;
 field(196,382,164,96,batteryLabel,percent(2),0xFFFF,batteryPower,socColor);
 field(362,413,118,65,"HOME",power(3));
 if(plugged) {
  field(18,142,166,45,"EV CHARGER",power(7),night?0xFFFF:0x0000);
  field(18,193,166,45,"EV BATTERY",percent(8),night?0xFFFF:0x0000);
 }
 if(fullRedraw || notice!=lastStatus) {
  restore(0,0,480,18);
  String shortNotice=notice;
  while(shortNotice.length() && textWidth(shortNotice,&Roboto_Regular8pt7b)>280) shortNotice.remove(shortNotice.length()-1);
  textAt(3,1,shortNotice,&Roboto_Regular8pt7b,0xFFFF);
  ipCache="!";
  lastStatus=notice;
 }
 if(fullRedraw || notice!=lastStatus) ipCache="!";
 first=false; lastPlugged=plugged; lastNight=night;
}
// Returns an empty value for unavailable/unknown/non-numeric readings.
String readEntity(int index, bool &requestFailed) {
 requestFailed=true;
 // Clients must outlive HTTPClient: its destructor may still call client->stop().
 WiFiClient plain; WiFiClientSecure tls; HTTPClient http;
 String base=HA_URL; while(base.endsWith("/")) base.remove(base.length()-1);
 bool secure=base.startsWith("https://");
 if(secure) {
  if(!strlen(HA_ROOT_CA) || time(nullptr)<1700000000) return "";
  tls.setCACert(HA_ROOT_CA);
 }
 String url=base+"/api/states/"+entities[index];
 if(!(secure ? http.begin(tls,url) : http.begin(plain,url))) return "";
 // Each poll owns its connection; do not leave a keep-alive socket behind.
 http.setReuse(false);
 http.setTimeout(2000); http.setConnectTimeout(2000);
 http.addHeader("Authorization",String("Bearer ")+HA_TOKEN);
 int code=http.GET();
 String result;
 if(code==200) {
  JsonDocument doc;
  if(!deserializeJson(doc,http.getString())) {
   requestFailed=false;
   if(index==11) {weatherTemperature=""; weatherUnit="";}
   String s=doc["state"].as<String>();
   if(index==11) {
    if(s.length() && s!="unknown" && s!="unavailable") {
     result=s;
     JsonVariant t=doc["attributes"]["temperature"];
     if(!t.isNull()) {
      String raw=t.as<String>(); char *end=nullptr;
      double n=strtod(raw.c_str(),&end);
      if(end!=raw.c_str() && *end=='\0' && isfinite(n)) weatherTemperature=String(n,1);
     }
     String u=doc["attributes"]["temperature_unit"].as<String>();
     weatherUnit=u.indexOf('F')>=0?"F":"C";
    }
   }
   else if(index>=12) { if(parseSunTime(s)) result=s; }
   else if(index==6) { if(s=="on"||s=="off") result=s; }
   else if(index==9 || index==10) {
    if(s.length() && s!="unknown" && s!="unavailable") result=s;
   } else {
    char *end=nullptr; double n=strtod(s.c_str(),&end);
    if(end!=s.c_str() && *end=='\0' && isfinite(n)) {
     String u=doc["attributes"]["unit_of_measurement"].as<String>();
     if(index==0||index==1||index==3||index==4||index==5) {
      if(u=="W") n/=1000.0;
     } else if(index==7 && u=="kW") n*=1000.0;
     result=String(n,(index==2||index==8)?0:3);
    }
   }
  }
 }
 http.end(); return result;
}
void setup() {
 Serial.begin(115200);
 pinMode(0,INPUT_PULLUP); // Official calibration example: GPIO0, falling edge.
 attachInterrupt(digitalPinToInterrupt(0),bootISR,FALLING);
 // Initialize the network stack before WebServer::begin creates its socket.
 WiFi.mode(WIFI_STA);
 setupWeb();
 Wire.begin(47,48);
 // Maker's startup sequence: hold touch INT low, pulse reset, then initialize LCD.
 expander->pinMode(5,OUTPUT); expander->pinMode(6,OUTPUT);
 expander->digitalWrite(6,LOW); delay(200);
 expander->digitalWrite(5,LOW); delay(200);
 expander->digitalWrite(5,HIGH); delay(200);
 if(!gfx->begin()) { Serial.println("LCD init failed"); while(true) delay(1000); }
 // Backlight and PMIC left at board defaults, as in maker's HelloWorld example.
 render("Configure include/config.h, then Deploy");
 if(String(WIFI_SSID)=="YOUR_WIFI_NAME" || String(HA_TOKEN)=="YOUR_LONG_LIVED_ACCESS_TOKEN") return;
 WiFi.setAutoReconnect(true); WiFi.begin(WIFI_SSID,WIFI_PASSWORD);
 syncClock();
}
void loop() {
 animateFlows();
 serviceControls();
 bool wasNight=night; updateDaylight();
 if(wasNight!=night || christmasVisible!=christmasSeason()) render("HOME ENERGY | Home Assistant connected");
 if(String(HA_TOKEN)=="YOUR_LONG_LIVED_ACCESS_TOKEN" || String(WIFI_SSID)=="YOUR_WIFI_NAME") {delay(100);return;}
 if(WiFi.status()!=WL_CONNECTED) {
  for(auto &v:values) v="";
  weatherTemperature=""; weatherUnit="";
  plugKnown=false; render("Wi-Fi disconnected - readings unavailable"); delay(250); return;
 }
 if((int32_t)(millis()-nextPoll)<0) {delay(20);return;}
 static int pollIndex=0;
 bool requestFailed=false;
 String fresh=readEntity(pollIndex,requestFailed);
 uint32_t now=millis();
 delayedReading[pollIndex]=requestFailed;
 if(!requestFailed) {
  values[pollIndex]=fresh;
  // Apply the garage state as soon as its request completes, not after the batch.
  if(pollIndex==6 && fresh.length()) {
   plugKnown=true; plugged=fresh=="on";
   render("HOME ENERGY | Home Assistant connected");
  }
  lastGoodReading[pollIndex]=fresh.length()?now:0;
 } else if(!lastGoodReading[pollIndex] || now-lastGoodReading[pollIndex]>45000) {
  values[pollIndex]="";
  if(pollIndex==11) {weatherTemperature=""; weatherUnit="";}
 }
 // Give Wi-Fi and the HA server breathing room between individual requests.
 nextPoll=millis()+150;
 if(pollIndex==12 && values[12].length()) sunrise=parseSunTime(values[12]);
 if(pollIndex==13 && values[13].length()) sunset=parseSunTime(values[13]);
 serviceControls();
 if(++pollIndex<14) return;
 pollIndex=0;
 bool all=true, delayed=false;
 for(auto &v:values) if(!v.length()) all=false;
 for(bool stale:delayedReading) if(stale) delayed=true;
 plugKnown=values[6].length();
 if(plugKnown) plugged=values[6]=="on";
 updateFlows();
 render(!all?"Some readings unavailable - check HA / token":delayed?"HA connection delayed - showing last readings":"HOME ENERGY | Home Assistant connected");
 nextPoll=millis()+10000;
}

Remix this project

Make it yours in one click

Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.

Open in Schematik