Skip to content

Commit

Permalink
Refactor contentmanager (#112)
Browse files Browse the repository at this point in the history
* Start contentmanager cleanup

- Make destination constant
- Remove unneeded asignments
- Improve loops
- Move printHeap function into util

* Refactor contentmanager::drawNew

* Optimize contentManager::replaceVariables

* Fix missing const in prepareCancelPending

* Refactor drawDate

* Refactor drawWeather, drawForecast & getLocation

- Generalize http get json function

* Add util function for printing largest free block

* Reuse weather icons for both drawWeather & drawForecast

* Make httpGetJson timeout const

* Reafctor more functions

* Add few more const

* Fix spelling mistake

* Add util for debugging streams

- Add util for checking if strings are empty or contain null
- Fix file and string checks

* Remove leftover debug print
  • Loading branch information
enwi committed Aug 12, 2023
1 parent 98baa02 commit 6c91c78
Show file tree
Hide file tree
Showing 12 changed files with 483 additions and 364 deletions.
24 changes: 12 additions & 12 deletions ESP32_AP-Flasher/include/contentmanager.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@
struct contentTypes {
uint16_t id;
String name;
uint16_t tagTypes;
uint16_t tagTypes;
void (*functionname)();
String description;
String optionList;
String description;
String optionList;
};

void contentRunner();
void checkVars();
void drawNew(uint8_t mac[8], bool buttonPressed, tagRecord *&taginfo);
bool updateTagImage(String &filename, uint8_t *dst, uint16_t nextCheckin, tagRecord *&taginfo, imgParam &imageParams);
void drawNew(const uint8_t mac[8], const bool buttonPressed, tagRecord *&taginfo);
bool updateTagImage(String &filename, const uint8_t *dst, uint16_t nextCheckin, tagRecord *&taginfo, imgParam &imageParams);
void drawString(TFT_eSprite &spr, String content, int16_t posx, int16_t posy, String font, byte align = 0, uint16_t color = TFT_BLACK, uint16_t size = 30, uint16_t bgcolor = TFT_WHITE);
void initSprite(TFT_eSprite &spr, int w, int h, imgParam &imageParams);
void drawDate(String &filename, tagRecord *&taginfo, imgParam &imageParams);
Expand All @@ -35,14 +35,14 @@ int getJsonTemplateFile(String &filename, String jsonfile, tagRecord *&taginfo,
int getJsonTemplateUrl(String &filename, String URL, time_t fetched, String MAC, tagRecord *&taginfo, imgParam &imageParams);
void drawJsonStream(Stream &stream, String &filename, tagRecord *&taginfo, imgParam &imageParams);
void drawElement(const JsonObject &element, TFT_eSprite &spr);
uint16_t getColor(String color);
uint16_t getColor(const String &color);
char *formatHttpDate(time_t t);
String urlEncode(const char *msg);
int windSpeedToBeaufort(float windSpeed);
String windDirectionIcon(int degrees);
int windSpeedToBeaufort(const float windSpeed);
String windDirectionIcon(const int degrees);
void getLocation(JsonObject &cfgobj);
void prepareNFCReq(uint8_t* dst, const char* url);
void prepareLUTreq(uint8_t *dst, String input);
void prepareConfigFile(uint8_t *dst, JsonObject config);
void getTemplate(JsonDocument &json, uint8_t id, uint8_t hwtype);
void prepareNFCReq(const uint8_t *dst, const char *url);
void prepareLUTreq(const uint8_t *dst, const String &input);
void prepareConfigFile(const uint8_t *dst, const JsonObject &config);
void getTemplate(JsonDocument &json, const uint8_t id, const uint8_t hwtype);
void setU8G2Font(const String &title, U8g2_for_TFT_eSPI &u8f);
16 changes: 8 additions & 8 deletions ESP32_AP-Flasher/include/newproto.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,21 @@ extern void addCRC(void* p, uint8_t len);
extern bool checkCRC(void* p, uint8_t len);

extern void processBlockRequest(struct espBlockRequest* br);
extern void prepareCancelPending(uint8_t dst[8]);
extern void prepareIdleReq(uint8_t* dst, uint16_t nextCheckin);
extern void prepareDataAvail(uint8_t* data, uint16_t len, uint8_t dataType, uint8_t* dst);
extern bool prepareDataAvail(String* filename, uint8_t dataType, uint8_t* dst, uint16_t nextCheckin);
extern void prepareCancelPending(const uint8_t dst[8]);
extern void prepareIdleReq(const uint8_t* dst, uint16_t nextCheckin);
extern void prepareDataAvail(uint8_t* data, uint16_t len, uint8_t dataType, const uint8_t* dst);
extern bool prepareDataAvail(String* filename, uint8_t dataType, const uint8_t* dst, uint16_t nextCheckin);
extern void prepareExternalDataAvail(struct pendingData* pending, IPAddress remoteIP);
extern void processXferComplete(struct espXferComplete* xfc, bool local);
extern void processXferTimeout(struct espXferComplete* xfc, bool local);
extern void processDataReq(struct espAvailDataReq* adr, bool local);

extern bool sendTagCommand(uint8_t* dst, uint8_t cmd, bool local);
extern bool sendAPSegmentedData(uint8_t* dst, String data, uint16_t icons, bool inverted, bool local);
extern bool showAPSegmentedInfo(uint8_t* dst, bool local);
extern bool sendTagCommand(const uint8_t* dst, uint8_t cmd, bool local);
extern bool sendAPSegmentedData(const uint8_t* dst, String data, uint16_t icons, bool inverted, bool local);
extern bool showAPSegmentedInfo(const uint8_t* dst, bool local);
extern void updateTaginfoitem(struct TagInfo* taginfoitem);
bool checkMirror(struct tagRecord* taginfo, struct pendingData* pending);

void refreshAllPending();
void updateContent(uint8_t* dst);
void updateContent(const uint8_t* dst);
void setAPchannel();
13 changes: 6 additions & 7 deletions ESP32_AP-Flasher/include/tag_db.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@

class tagRecord {
public:
tagRecord() : mac{0}, alias(""), lastseen(0), nextupdate(0), contentMode(0), pending(false), md5{0}, md5pending{0}, expectedNextCheckin(0), modeConfigJson(""), LQI(0), RSSI(0), temperature(0), batteryMv(0), hwType(0), wakeupReason(0), capabilities(0), lastfullupdate(0), isExternal(false), pendingIdle(0), hasCustomLUT(false), rotate(0), lut(0), tagSoftwareVersion(0), currentChannel(0),
dataType(0), filename(""), data(nullptr), len(0) {}
tagRecord() : mac{0}, alias(""), lastseen(0), nextupdate(0), contentMode(0), pending(false), md5{0}, md5pending{0}, expectedNextCheckin(0), modeConfigJson(""), LQI(0), RSSI(0), temperature(0), batteryMv(0), hwType(0), wakeupReason(0), capabilities(0), lastfullupdate(0), isExternal(false), pendingIdle(0), hasCustomLUT(false), rotate(0), lut(0), tagSoftwareVersion(0), currentChannel(0), dataType(0), filename(""), data(nullptr), len(0) {}

uint8_t mac[8];
String alias;
Expand Down Expand Up @@ -53,7 +52,7 @@ class tagRecord {
uint8_t* data;
uint32_t len;

static tagRecord* findByMAC(uint8_t mac[8]);
static tagRecord* findByMAC(const uint8_t mac[8]);
};

struct Config {
Expand Down Expand Up @@ -87,15 +86,15 @@ extern std::vector<tagRecord*> tagDB;
extern std::unordered_map<int, HwType> hwtype;
extern std::unordered_map<std::string, varStruct> varDB;
extern DynamicJsonDocument APconfig;
String tagDBtoJson(uint8_t mac[8] = nullptr, uint8_t startPos = 0);
bool deleteRecord(uint8_t mac[8]);
void fillNode(JsonObject &tag, tagRecord* &taginfo);
String tagDBtoJson(const uint8_t mac[8] = nullptr, uint8_t startPos = 0);
bool deleteRecord(const uint8_t mac[8]);
void fillNode(JsonObject& tag, tagRecord*& taginfo);
void saveDB(String filename);
void loadDB(String filename);
void destroyDB();
uint32_t getTagCount();
uint32_t getTagCount(uint32_t& timeoutcount);
void mac2hex(uint8_t* mac, char* hexBuffer);
void mac2hex(const uint8_t* mac, char* hexBuffer);
bool hex2mac(const String& hexString, uint8_t* mac);
void clearPending(tagRecord* taginfo);
void initAPconfig();
Expand Down
102 changes: 102 additions & 0 deletions ESP32_AP-Flasher/include/util.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
#pragma once

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

#include "web.h"

namespace util {

/// @brief Can be used to wrap a stream and see what's going on
class DebugStream : public Stream {
public:
DebugStream(Stream &stream) : _stream(stream) {}

int available() override {
return _stream.available();
}

int read() override {
int data = _stream.read();
Serial.write(data);
return data;
}

int peek() override {
int data = _stream.peek();
Serial.print("Peek: ");
Serial.println(data);
return data;
}

void flush() override {
_stream.flush();
Serial.println("Flush");
}

size_t write(uint8_t data) override {
Serial.write(data);
return _stream.write(data);
}

size_t write(const uint8_t *buffer, size_t size) override {
for (size_t i = 0; i < size; i++) {
Serial.print("Write: ");
Serial.println(buffer[i]);
}
return _stream.write(buffer, size);
}

private:
Stream &_stream;
};

/// @brief Prints free heap, allocatbale heap and free stack
static void printHeap() {
const uint32_t freeStack = uxTaskGetStackHighWaterMark(NULL);
Serial.printf("Free heap: %d allocatable: %d stack: %d\n", ESP.getFreeHeap(), ESP.getMaxAllocHeap(), freeStack);
}

/// @brief Prints the maximum continuous heap space
static void printLargestFreeBlock() {
Serial.println("Maximum Continuous Heap Space: " + String(heap_caps_get_largest_free_block(MALLOC_CAP_DEFAULT)));
}

/// @brief Do a GET request to the given url and fill the given json with the response
/// @param url Request URL
/// @param json Json document to fill
/// @param timeout Request timeout
/// @param redirects Redirects handling
/// @return True on success, false on error (httpCode != 200 || deserialization error)
static bool httpGetJson(String &url, JsonDocument &json, const uint16_t timeout) //, const followRedirects_t redirects = followRedirects_t::HTTPC_DISABLE_FOLLOW_REDIRECTS)
{
HTTPClient http;
http.begin(url);
http.setTimeout(timeout);
// http.setFollowRedirects(redirects);
const int httpCode = http.GET();
if (httpCode != 200) {
http.end();
wsErr("http " + httpCode);
return false;
}

DeserializationError error = deserializeJson(json, http.getString());
http.end();
if (error) {
Serial.println(error.c_str());
return false;
}
return true;
}

/// @brief Check if the given string is empty or contains "null"
///
/// @param str String to check
/// @return True if empty or null, false if not
static inline bool isEmptyOrNull(const String &str) {
return str.isEmpty() || str == "null";
}

} // namespace util
4 changes: 2 additions & 2 deletions ESP32_AP-Flasher/include/web.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ void doJsonUpload(AsyncWebServerRequest *request);
extern void networkProcess(void *parameter);
void wsLog(String text);
void wsErr(String text);
void wsSendTaginfo(uint8_t *mac, uint8_t syncMode);
void wsSendTaginfo(const uint8_t *mac, uint8_t syncMode);
void wsSendSysteminfo();
void wsSendAPitem(struct APlist* apitem);
void wsSendAPitem(struct APlist *apitem);
void wsSerial(String text);
uint8_t wsClientCount();

Expand Down

0 comments on commit 6c91c78

Please sign in to comment.