├── .github ├── act │ ├── tag.json │ ├── push.json │ └── pullrequest.json └── workflows │ ├── build_pio.yml │ └── build_arduino.yml ├── doc ├── .DS_Store └── images │ ├── .DS_Store │ ├── display.jpg │ ├── iobroker.png │ ├── partition.png │ ├── wifi_setup.png │ └── wifi_manager.png ├── .whitesource ├── Bluetti_ESP32 ├── utils.h ├── PowerStation.h ├── debug_custom.json ├── debug.cfg ├── BluettiConfig.h ├── PayloadParser.h ├── MQTT.h ├── BWifi.h ├── utils.cpp ├── Bluetti_ESP32.ino ├── display.h ├── BTooth.h ├── config.sample.h ├── Device_EP600.h ├── config.h ├── DeviceType.h ├── Device_AC500.h ├── Device_EP500.h ├── crc16.h ├── DEVICE_EB3A.h ├── Device_AC300.h ├── Device_AC200M.h ├── PayloadParser.cpp ├── index.h ├── DEVICE_EP500P.h ├── BTooth.cpp ├── BWifi.cpp ├── MQTT.cpp └── display.cpp ├── .gitignore ├── platformio.ini ├── scripts └── post_esp32.py ├── README.md └── LICENSE /.github/act/tag.json: -------------------------------------------------------------------------------- 1 | { 2 | "push": { 3 | "ref": "refs/master" 4 | } 5 | } -------------------------------------------------------------------------------- /.github/act/push.json: -------------------------------------------------------------------------------- 1 | { 2 | "push": { 3 | "ref": "refs/tags/v.0.2.0" 4 | } 5 | } -------------------------------------------------------------------------------- /doc/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mariolukas/Bluetti_ESP32_Bridge/HEAD/doc/.DS_Store -------------------------------------------------------------------------------- /doc/images/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mariolukas/Bluetti_ESP32_Bridge/HEAD/doc/images/.DS_Store -------------------------------------------------------------------------------- /doc/images/display.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mariolukas/Bluetti_ESP32_Bridge/HEAD/doc/images/display.jpg -------------------------------------------------------------------------------- /doc/images/iobroker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mariolukas/Bluetti_ESP32_Bridge/HEAD/doc/images/iobroker.png -------------------------------------------------------------------------------- /doc/images/partition.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mariolukas/Bluetti_ESP32_Bridge/HEAD/doc/images/partition.png -------------------------------------------------------------------------------- /doc/images/wifi_setup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mariolukas/Bluetti_ESP32_Bridge/HEAD/doc/images/wifi_setup.png -------------------------------------------------------------------------------- /doc/images/wifi_manager.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mariolukas/Bluetti_ESP32_Bridge/HEAD/doc/images/wifi_manager.png -------------------------------------------------------------------------------- /.github/act/pullrequest.json: -------------------------------------------------------------------------------- 1 | { 2 | "action": "opened", 3 | "number": 1, 4 | "pull_request": { 5 | "base": { 6 | "ref": "main" 7 | }, 8 | "head": { 9 | "ref": "feature-branch" 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /.whitesource: -------------------------------------------------------------------------------- 1 | { 2 | "scanSettings": { 3 | "baseBranches": [] 4 | }, 5 | "checkRunSettings": { 6 | "vulnerableCheckRunConclusionLevel": "failure", 7 | "displayMode": "diff", 8 | "useMendCheckNames": true 9 | }, 10 | "issueSettings": { 11 | "minSeverityLevel": "LOW", 12 | "issueType": "DEPENDENCY" 13 | } 14 | } -------------------------------------------------------------------------------- /Bluetti_ESP32/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef UTILS_H 2 | #define UTILS_H 3 | #include "Arduino.h" 4 | 5 | #define MAX 100 6 | 7 | typedef struct{ 8 | uint8_t myarr[MAX]; 9 | int mysize; 10 | } wrapper; 11 | 12 | extern uint16_t swap_bytes(uint16_t number); 13 | extern wrapper slice(const uint8_t* arr, int size, uint8_t include, uint8_t exclude); 14 | extern uint16_t modbus_crc(uint8_t buf[], int len); 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /Bluetti_ESP32/PowerStation.h: -------------------------------------------------------------------------------- 1 | #ifndef POWER_STATION_H 2 | #define POWER_STATION_H 3 | #include "Arduino.h" 4 | 5 | #define UNKNOWN_DEVICE -1 6 | #define AC300 1 7 | #define AC200M 2 8 | #define EP500 3 9 | #define EB3A 4 10 | #define EP500P 5 11 | #define AC500 6 12 | #define EP600 7 13 | 14 | #define POWER_STATION(type) (BLUETTI_TYPE==type) 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /Bluetti_ESP32/debug_custom.json: -------------------------------------------------------------------------------- 1 | { 2 | "name":"Arduino on ESP32", 3 | "toolchainPrefix":"xtensa-esp32-elf", 4 | "svdFile":"esp32.svd", 5 | "request":"attach", 6 | "postAttachCommands":[ 7 | "set remote hardware-watchpoint-limit 2", 8 | "monitor reset halt", 9 | "monitor gdb_sync", 10 | "thb setup", 11 | "c" 12 | ], 13 | "overrideRestartCommands":[ 14 | "monitor reset halt", 15 | "monitor gdb_sync", 16 | "thb setup", 17 | "c" 18 | ] 19 | } -------------------------------------------------------------------------------- /Bluetti_ESP32/debug.cfg: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: GPL-2.0-or-later 2 | # 3 | # Example OpenOCD configuration file for ESP32-WROVER-KIT board. 4 | # 5 | # For example, OpenOCD can be started for ESP32 debugging on 6 | # 7 | # openocd -f board/esp32-wrover-kit-3.3v.cfg 8 | # 9 | 10 | # Source the JTAG interface configuration file 11 | source [find interface/ftdi/esp32_devkitj_v1.cfg] 12 | set ESP32_FLASH_VOLTAGE 3.3 13 | # Source the ESP32 configuration file 14 | source [find target/esp32.cfg] 15 | -------------------------------------------------------------------------------- /Bluetti_ESP32/BluettiConfig.h: -------------------------------------------------------------------------------- 1 | #ifndef BLUETTI_CONFIG_H 2 | #define BLUETTI_CONFIG_H 3 | 4 | #include "DeviceType.h" 5 | #include "PowerStation.h" 6 | #include "config.h" 7 | 8 | #if POWER_STATION(AC300) 9 | #include "Device_AC300.h" 10 | #elif POWER_STATION(AC200M) 11 | #include "Device_AC200M.h" 12 | #elif POWER_STATION(EP500) 13 | #include "Device_EP500.h" 14 | #elif POWER_STATION(EB3A) 15 | #include "Device_EB3A.h" 16 | #elif POWER_STATION(EP500P) 17 | #include "Device_EP500P.h" 18 | #elif POWER_STATION(AC500) 19 | #include "Device_AC500.h" 20 | #elif POWER_STATION(EP600) 21 | #include "Device_EP600.h" 22 | #endif 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /Bluetti_ESP32/PayloadParser.h: -------------------------------------------------------------------------------- 1 | #ifndef PAYLOAD_PARSER_H 2 | #define PAYLOAD_PARSER_H 3 | #include "Arduino.h" 4 | #include "DeviceType.h" 5 | 6 | #define HEADER_SIZE 4 7 | #define CHECKSUM_SIZE 2 8 | 9 | uint16_t parse_uint_field(uint8_t data[]); 10 | bool parse_bool_field(uint8_t data[]); 11 | float parse_decimal_field(uint8_t data[], uint8_t scale); 12 | uint64_t parse_serial_field(uint8_t data[]); 13 | float parse_version_field(uint8_t data[]); 14 | String parse_string_field(uint8_t data[]); 15 | String parse_enum_field(uint8_t data[]); 16 | 17 | extern void parse_bluetooth_data(uint8_t page, uint8_t offset, uint8_t* pData, size_t length); 18 | 19 | #endif -------------------------------------------------------------------------------- /Bluetti_ESP32/MQTT.h: -------------------------------------------------------------------------------- 1 | #ifndef MQTT_H 2 | #define MQTT_H 3 | #include "Arduino.h" 4 | #include "DeviceType.h" 5 | 6 | extern void publishTopic(enum field_names field_name, String value); 7 | extern void publishHAConfig(); 8 | extern void publishDeviceState(); 9 | extern void publishDeviceStateStatus(); 10 | extern void deviceServoPress(int degree); 11 | extern void handleMQTT(); 12 | extern void initMQTT(); 13 | extern bool isMQTTconnected(); 14 | extern int getPublishErrorCount(); 15 | unsigned long getLastMQTTMessageTime(); 16 | unsigned long getLastMQTTDeviceStateMessageTime(); 17 | unsigned long getLastMQTTDeviceStateStatusMessageTime(); 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | # Platformio 35 | .pio 36 | build 37 | 38 | # Other files and folders 39 | .vscode/ 40 | .idea/ 41 | # OS generated files 42 | .DS_Store 43 | .DS_Store? 44 | ._* 45 | .Spotlight-V100 46 | .Trashes 47 | ehthumbs.db 48 | Thumbs.db 49 | Bluetti_ESP32/config.h -------------------------------------------------------------------------------- /platformio.ini: -------------------------------------------------------------------------------- 1 | [platformio] 2 | src_dir = Bluetti_ESP32 3 | 4 | [env] 5 | lib_deps = 6 | https://github.com/tzapu/WiFiManager/archive/refs/tags/v2.0.15-rc.1.zip 7 | PubSubClient@^2.8.0 8 | ElegantOTA@^3.1.4 9 | h2zero/NimBLE-Arduino @ ^1.4.1 10 | adafruit/Adafruit SSD1306@^2.5.7 11 | adafruit/Adafruit GFX Library @ ^1.11.5 12 | adafruit/Adafruit BusIO @ ^1.14.1 13 | Wire 14 | Spi 15 | extra_scripts = post:scripts/post_esp32.py 16 | 17 | [env:esp32dev] 18 | platform = espressif32@6.0.0 19 | framework = arduino 20 | board = esp32dev 21 | board_build.partitions = min_spiffs.csv 22 | monitor_speed = 115200 23 | build_flags=-DELEGANTOTA_USE_ASYNC_WEBSERVER=1 24 | lib_compat_mode = strict 25 | -------------------------------------------------------------------------------- /Bluetti_ESP32/BWifi.h: -------------------------------------------------------------------------------- 1 | #ifndef BWIFI_H 2 | #define BWIFI_H 3 | #include "Arduino.h" 4 | #include "config.h" 5 | 6 | typedef struct{ 7 | int salt = EEPROM_SALT; 8 | char mqtt_server[40] = "127.0.0.1"; 9 | char mqtt_port[6] = "1883"; 10 | char mqtt_username[40] = ""; 11 | char mqtt_password[40] = ""; 12 | char bluetti_device_id[40] = "Bluetti Blutetooth Id"; 13 | char ota_username[40] = ""; 14 | char ota_password[40] = ""; 15 | } ESPBluettiSettings; 16 | 17 | extern ESPBluettiSettings get_esp32_bluetti_settings(); 18 | extern void initBWifi(bool resetWifi); 19 | extern void handleWebserver(); 20 | String processorWebsiteUpdates(const String& var); 21 | extern void AddtoMsgView(String data); 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /Bluetti_ESP32/utils.cpp: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | #include "crc16.h" 3 | 4 | uint16_t swap_bytes(uint16_t number) { 5 | return (number << 8) | (number >> 8); 6 | } 7 | 8 | uint16_t modbus_crc(uint8_t buf[], int len){ 9 | unsigned int crc = 0xFFFF; 10 | for (unsigned int i = 0; i < len; i++) 11 | { 12 | crc = crc16_update(crc, buf[i]); 13 | } 14 | 15 | return crc; 16 | } 17 | 18 | wrapper slice(const uint8_t* arr, int size, uint8_t include, uint8_t exclude) { 19 | wrapper result = { .myarr = {0}, .mysize = 0 }; 20 | if (include >= 0 && exclude <= size) { 21 | int count = 0; 22 | for (int i = include; i < exclude; i++) { 23 | result.myarr[count] = arr[i]; 24 | count++; 25 | } 26 | result.mysize = exclude - include; 27 | return result; 28 | } 29 | else { 30 | printf("Array index out-of-bounds\n"); 31 | result.mysize = -1; 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Bluetti_ESP32/Bluetti_ESP32.ino: -------------------------------------------------------------------------------- 1 | #include "BWifi.h" 2 | #include "BTooth.h" 3 | #include "MQTT.h" 4 | #include "config.h" 5 | #include "display.h" 6 | 7 | unsigned long lastTime1 = 0; 8 | unsigned long timerDelay1 = 3000; 9 | 10 | void setup() { 11 | Serial.begin(115200); 12 | #ifdef RELAISMODE 13 | pinMode(RELAIS_PIN, OUTPUT); 14 | #ifdef DEBUG 15 | Serial.println(F("deactivate relais contact")); 16 | #endif 17 | digitalWrite(RELAIS_PIN, RELAIS_LOW); 18 | #endif 19 | #ifdef SLEEP_TIME_ON_BT_NOT_AVAIL 20 | esp_sleep_enable_timer_wakeup(SLEEP_TIME_ON_BT_NOT_AVAIL * 60 * 1000000ULL); 21 | #endif 22 | #ifdef DISPLAYSSD1306 23 | initDisplay(); 24 | #endif 25 | initBWifi(false); 26 | initBluetooth(); 27 | initMQTT(); 28 | #ifdef DISPLAYSSD1306 29 | wrDisp_Status("Running!"); 30 | #endif 31 | } 32 | 33 | void loop() { 34 | #ifdef DISPLAYSSD1306 35 | handleDisplay(); 36 | #endif 37 | handleBluetooth(); 38 | handleMQTT(); 39 | handleWebserver(); 40 | } 41 | -------------------------------------------------------------------------------- /Bluetti_ESP32/display.h: -------------------------------------------------------------------------------- 1 | #ifndef DISPLAY_H 2 | #define DISPLAY_H 3 | 4 | // for setup only 5 | void initDisplay(); 6 | void wrDisp_IP(String strIP="NoConf"); 7 | void wrDisp_Running(); 8 | void wrDisp_Status(String strStatus="boot.."); 9 | void drawProgressbar(int x,int y, int width,int height, int progress); 10 | void wrDisp_blueToothSignal(bool blConnected); 11 | void wrDisp_mqttConnected(bool blMqttConnected=false); 12 | void wrDisp_wifisignal_rewrite_static(); 13 | 14 | // can be used both is setup and in loop 15 | void wrDisp_wifisignal(int intMode=0, int intSignal=-100); 16 | void disp_setPrevStateIcon(byte bytePrevState); 17 | void disp_setBTPrevStateIcon(byte bytePrevState); 18 | 19 | // public usable on loops 20 | void handleDisplay(); 21 | 22 | void disp_setWifiMode(byte wMode); 23 | void disp_setBlueTooth(bool boolBtConn=false); 24 | void disp_setWifiSignal(int extWifMode=0, int extSignal=-100); 25 | void disp_setStatus(String strStatus); 26 | void disp_setIP(String strIP); 27 | void disp_setMqttStatus(bool blMqttconnected=false); 28 | #endif 29 | #include -------------------------------------------------------------------------------- /.github/workflows/build_pio.yml: -------------------------------------------------------------------------------- 1 | name: Build Bluetti ESP32 Bridge with PlatformIO 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | types: 9 | - opened 10 | workflow_run: 11 | workflows: ["Build with PlatformIO on PR Request"] 12 | types: 13 | - completed 14 | branches: 15 | - main # Change this to the branch you want to trigger the build on 16 | 17 | jobs: 18 | build: 19 | name: build with plattformIO 20 | runs-on: ubuntu-latest 21 | 22 | steps: 23 | - name: Checkout code 24 | uses: actions/checkout@v2 25 | 26 | - name: Set up Python 27 | uses: actions/setup-python@v2 28 | with: 29 | python-version: '3.x' # Set the desired Python version 30 | 31 | - name: Install PlatformIO 32 | run: | 33 | pip install -U platformio 34 | platformio platform install espressif32 35 | 36 | - name: Build ESP32 Program 37 | run: | 38 | platformio run 39 | 40 | # - name: Upload artifacts 41 | # uses: actions/upload-artifact@v2 42 | # with: 43 | # name: firmware # Set the name of the artifact directory 44 | # path: .pio/build/ # Replace with your PlatformIO environment name 45 | -------------------------------------------------------------------------------- /Bluetti_ESP32/BTooth.h: -------------------------------------------------------------------------------- 1 | #ifndef BTOOTH_H 2 | #define BTOOTH_H 3 | #include "Arduino.h" 4 | #include "NimBLEDevice.h" 5 | 6 | static boolean doConnect = false; 7 | static boolean connected = false; 8 | static boolean doScan = false; 9 | static BLERemoteCharacteristic* pRemoteWriteCharacteristic; 10 | static BLERemoteCharacteristic* pRemoteNotifyCharacteristic; 11 | static BLEAdvertisedDevice* bluettiDevice; 12 | 13 | typedef struct __attribute__ ((packed)) { 14 | uint8_t prefix; // 1 byte 15 | uint8_t field_update_cmd; // 1 byte 16 | uint8_t page; // 1 byte 17 | uint8_t offset; // 1 byte 18 | uint16_t len; // 2 bytes 19 | uint16_t check_sum; // 2 bytes 20 | } bt_command_t; 21 | 22 | 23 | // The remote Bluetti service we wish to connect to. 24 | static BLEUUID serviceUUID("0000ff00-0000-1000-8000-00805f9b34fb"); 25 | 26 | // The characteristics of Bluetti Devices 27 | static BLEUUID WRITE_UUID("0000ff02-0000-1000-8000-00805f9b34fb"); 28 | static BLEUUID NOTIFY_UUID("0000ff01-0000-1000-8000-00805f9b34fb"); 29 | 30 | void btResetStack(); 31 | extern void initBluetooth(); 32 | extern void handleBluetooth(); 33 | bool connectToServer(); 34 | extern void handleBTCommandQueue(); 35 | extern void sendBTCommand(bt_command_t command); 36 | extern bool isBTconnected(); 37 | extern unsigned long getLastBTMessageTime(); 38 | #endif 39 | -------------------------------------------------------------------------------- /Bluetti_ESP32/config.sample.h: -------------------------------------------------------------------------------- 1 | #ifndef CONFIG_H 2 | #define CONFIG_H 3 | #include "Arduino.h" 4 | 5 | #define DEBUG 1 6 | // Display config section, comment DISPLAYSSD1306 to disable display 7 | //#define DEBUGDISP 1 8 | //#define DISPLAYSSD1306 1 9 | #define DISPLAY_SCL_PORT 4 10 | #define DISPLAY_SDA_PORT 5 11 | //Uncomment to toggle display reset on start, required for displays like LoRa TTGO v1.0 12 | //#define DISPLAY_RST_PORT 16 13 | 14 | 15 | #define EEPROM_SALT 13374 16 | 17 | #define DEVICE_NAME "BLUETTI-MQTT" 18 | #define BLUETTI_TYPE AC300 19 | 20 | #define BLUETOOTH_QUERY_MESSAGE_DELAY 3000 21 | 22 | #define RELAISMODE 1 23 | #define RELAIS_PIN 22 24 | #define RELAIS_LOW LOW 25 | #define RELAIS_HIGH HIGH 26 | 27 | #define MAX_DISCONNECTED_TIME_UNTIL_REBOOT 5 //device will reboot when wlan/BT/MQTT is not connectet within x Minutes 28 | #define SLEEP_TIME_ON_BT_NOT_AVAIL 2 //device will sleep x minutes if restarted is triggered by bluetooth error 29 | //set to 0 to disable 30 | #define DEVICE_STATE_UPDATE 5 31 | #define MSG_VIEWER_DETAILS 0 //enable detailed BT/MQTT messages via WebUI by default, can be changed in WebUI 32 | #define DEVICE_STATE_STATUS_UPDATE 2.5 //Was 0.5 in original branc which is half the DEVICE_STATE_UPDATE value, kept the ratio 33 | #define MSG_VIEWER_ENTRY_COUNT 20 //number of lines for web message viewer 34 | #define MSG_VIEWER_REFRESH_CYCLE 5 //refresh time for website data in seconds 35 | 36 | 37 | #ifndef BLUETTI_TYPE 38 | #define BLUETTI_TYPE AC300 39 | #endif 40 | 41 | 42 | 43 | #endif 44 | -------------------------------------------------------------------------------- /Bluetti_ESP32/Device_EP600.h: -------------------------------------------------------------------------------- 1 | #ifndef DEVICE_EP600_H 2 | #define DEVICE_EP600_H 3 | #include "Arduino.h" 4 | 5 | // Based on https://doc.chromedshark.com/bluetti/ep600.html 6 | // and https://github.com/warhammerkid/bluetti_mqtt 7 | 8 | // { FIELD_NAME, PAGE, OFFSET, SIZE, SCALE (if scale is needed e.g. decimal value, defaults to 0) , ENUM (if data is enum, defaults to 0) , FIELD_TYPE } 9 | static device_field_data_t bluetti_device_state[] = { 10 | {TOTAL_BATTERY_PERCENT, 0x00, 0x66, 1, 0, 0, UINT_FIELD}, 11 | {DEVICE_TYPE, 0x00, 0x6E, 6, 0, 0, STRING_FIELD}, // TODO: swap string 12 | {SERIAL_NUMBER, 0x00, 0x74, 4, 0 ,0, SN_FIELD}, 13 | {POWER_GENERATION, 0x00, 0x90, 1, 3, 0, DECIMAL_FIELD}, 14 | 15 | {BATTERY_MIN_PERCENTAGE, 0x07, 0xE6, 1, 0, 0, UINT_FIELD}, 16 | {AC_CHARGE_MAX_PERCENTAGE, 0x07, 0xE7, 1, 0, 0, UINT_FIELD}, 17 | 18 | {AC_INPUT_POWER_MAX, 0x08, 0xA5, 1, 0, 0, UINT_FIELD}, 19 | {AC_INPUT_CURRENT_MAX, 0x08, 0xA6, 1, 0, 0, UINT_FIELD}, 20 | {AC_OUTPUT_POWER_MAX, 0x08, 0xA7, 1, 0, 0, UINT_FIELD}, 21 | {AC_OUTPUT_CURRENT_MAX, 0x08, 0xA8, 1, 0, 0, UINT_FIELD}, 22 | }; 23 | 24 | static device_field_data_t bluetti_device_command[] = {}; 25 | 26 | // {FIELD_NAME, PAGE, OFFSET, FIELDS_TO_READ, 0, 0, TYPE_UNDEFINED} 27 | static device_field_data_t bluetti_polling_command[] = { 28 | {FIELD_UNDEFINED, 0x00, 0x64, 0x3E, 0, 0, TYPE_UNDEFINED}, 29 | {FIELD_UNDEFINED, 0x07, 0xD0, 0x30, 0, 0, TYPE_UNDEFINED}, 30 | {FIELD_UNDEFINED, 0x08, 0x00, 0x29, 0, 0, TYPE_UNDEFINED}, 31 | }; 32 | 33 | #endif 34 | -------------------------------------------------------------------------------- /Bluetti_ESP32/config.h: -------------------------------------------------------------------------------- 1 | #ifndef CONFIG_H 2 | #define CONFIG_H 3 | #include "Arduino.h" 4 | 5 | #define DEBUG 1 6 | // Display config section, comment DISPLAYSSD1306 to disable display 7 | //#define DEBUGDISP 1 8 | //#define DISPLAYSSD1306 1 9 | #define DISPLAY_SCL_PORT 4 10 | #define DISPLAY_SDA_PORT 5 11 | //Uncomment to toggle display reset on start, required for displays like LoRa TTGO v1.0 12 | //#define DISPLAY_RST_PORT 16 13 | 14 | #define EEPROM_SALT 13374 15 | 16 | #define DEVICE_NAME "BLUETTI-MQTT" 17 | #define BLUETTI_TYPE AC300 18 | 19 | #define BLUETOOTH_QUERY_MESSAGE_DELAY 3000 20 | #define BLUETOOTH_MAX_RETRIES_BEFORE_REBOOT 10 21 | #define BLUETOOTH_SCAN_DURATION_IN_SECONDS 10 22 | #define BLUETOOTH_SCAN_INTERVAL_IN_SECONDS 10 23 | 24 | #define RELAISMODE 1 25 | #define RELAIS_PIN 22 26 | #define RELAIS_LOW LOW 27 | #define RELAIS_HIGH HIGH 28 | 29 | #define MAX_DISCONNECTED_TIME_UNTIL_REBOOT 5 //device will reboot when wlan/BT/MQTT is not connectet within x Minutes 30 | #define SLEEP_TIME_ON_BT_NOT_AVAIL 2 //device will sleep x minutes if restarted is triggered by bluetooth error 31 | //set to 0 to disable 32 | #define DEVICE_STATE_UPDATE 5 33 | #define MSG_VIEWER_DETAILS 0 //enable detailed BT/MQTT messages via WebUI by default, can be changed in WebUI 34 | #define DEVICE_STATE_STATUS_UPDATE 2.5 //Was 0.5 in original branc which is half the DEVICE_STATE_UPDATE value, kept the ratio 35 | #define MSG_VIEWER_ENTRY_COUNT 20 //number of lines for web message viewer 36 | #define MSG_VIEWER_REFRESH_CYCLE 5 //refresh time for website data in seconds 37 | 38 | 39 | #ifndef BLUETTI_TYPE 40 | #define BLUETTI_TYPE AC300 41 | #endif 42 | 43 | 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /.github/workflows/build_arduino.yml: -------------------------------------------------------------------------------- 1 | name: Build Bluetti ESP32 Bridge with Arduino IDE 2 | on: 3 | push: 4 | branches: 5 | - main 6 | pull_request: 7 | types: 8 | - opened 9 | workflow_run: 10 | workflows: ["Build with Arduino on PR Request"] 11 | types: 12 | - completed 13 | branches: 14 | - main # Change this to the branch you want to trigger the build on 15 | - 16 | jobs: 17 | build: 18 | name: build with Arduino CLI 19 | runs-on: ubuntu-latest 20 | 21 | steps: 22 | 23 | - name: 🏗 Install build dependencies 24 | run: sudo apt-get -qq update && sudo apt-get -y install build-essential curl python3-serial 25 | 26 | - name: ⬇ Checkout code 27 | uses: actions/checkout@v2 28 | with: 29 | fetch-depth: 0 30 | 31 | 32 | - name: Install Arduino CLI 33 | run: curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR=/usr/local/bin sh 34 | 35 | - name: Install platform 36 | run: | 37 | arduino-cli core update-index 38 | arduino-cli core install esp32:esp32 39 | 40 | - name: Install Platform 41 | run: | 42 | arduino-cli lib install WiFiManager 43 | arduino-cli lib install PubSubClient 44 | export ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=true && arduino-cli lib install --git-url https://github.com/me-no-dev/AsyncTCP.git 45 | export ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=true && arduino-cli lib install --git-url https://github.com/me-no-dev/ESPAsyncWebServer.git 46 | export ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=true && arduino-cli lib install --git-url https://github.com/h2zero/NimBLE-Arduino.git 47 | arduino-cli lib install AsyncElegantOTA 48 | arduino-cli lib install "Adafruit SSD1306" 49 | arduino-cli lib install "Adafruit GFX Library" 50 | arduino-cli lib install "Adafruit BusIO" 51 | 52 | - name: 🔨 Build Firmware 53 | run: | 54 | cd Bluetti_ESP32 55 | arduino-cli compile --fqbn esp32:esp32:esp32 Bluetti_ESP32.ino -------------------------------------------------------------------------------- /Bluetti_ESP32/DeviceType.h: -------------------------------------------------------------------------------- 1 | #ifndef __DEVICE_TYPE_H__ 2 | #define __DEVICE_TYPE_H__ 3 | #include "Arduino.h" 4 | 5 | enum field_types{ 6 | UINT_FIELD, 7 | BOOL_FIELD, 8 | ENUM_FIELD, 9 | STRING_FIELD, 10 | DECIMAL_ARRAY_FIELD, 11 | DECIMAL_FIELD, 12 | VERSION_FIELD, 13 | SN_FIELD, 14 | TYPE_UNDEFINED 15 | }; 16 | 17 | enum field_names { 18 | DC_OUTPUT_POWER, 19 | DC_OUTPUT_ON, 20 | AC_OUTPUT_POWER, 21 | AC_OUTPUT_ON, 22 | AC_OUTPUT_MODE, 23 | POWER_GENERATION, 24 | TOTAL_BATTERY_PERCENT, 25 | DC_INPUT_POWER, 26 | AC_INPUT_POWER, 27 | AC_INPUT_VOLTAGE, 28 | AC_INPUT_FREQUENCY, 29 | PACK_VOLTAGE, 30 | INTERNAL_PACK_VOLTAGE, 31 | SERIAL_NUMBER, 32 | ARM_VERSION, 33 | DSP_VERSION, 34 | DEVICE_TYPE, 35 | UPS_MODE, 36 | AUTO_SLEEP_MODE, 37 | GRID_CHARGE_ON, 38 | FIELD_UNDEFINED, 39 | INTERNAL_AC_VOLTAGE, 40 | INTERNAL_AC_FREQUENCY, 41 | INTERNAL_CURRENT_ONE, 42 | INTERNAL_POWER_ONE, 43 | INTERNAL_CURRENT_TWO, 44 | INTERNAL_POWER_TWO, 45 | INTERNAL_CURRENT_THREE, 46 | INTERNAL_POWER_THREE, 47 | INTERNAL_DC_INPUT_VOLTAGE, 48 | INTERNAL_DC_INPUT_POWER, 49 | INTERNAL_DC_INPUT_CURRENT, 50 | PACK_BATTERY_PERCENT, 51 | PACK_NUM, 52 | PACK_NUM_MAX, 53 | INTERNAL_CELL01_VOLTAGE, 54 | INTERNAL_CELL02_VOLTAGE, 55 | INTERNAL_CELL03_VOLTAGE, 56 | INTERNAL_CELL04_VOLTAGE, 57 | INTERNAL_CELL05_VOLTAGE, 58 | INTERNAL_CELL06_VOLTAGE, 59 | INTERNAL_CELL07_VOLTAGE, 60 | INTERNAL_CELL08_VOLTAGE, 61 | INTERNAL_CELL09_VOLTAGE, 62 | INTERNAL_CELL10_VOLTAGE, 63 | INTERNAL_CELL11_VOLTAGE, 64 | INTERNAL_CELL12_VOLTAGE, 65 | INTERNAL_CELL13_VOLTAGE, 66 | INTERNAL_CELL14_VOLTAGE, 67 | INTERNAL_CELL15_VOLTAGE, 68 | INTERNAL_CELL16_VOLTAGE, 69 | LED_MODE, 70 | POWER_OFF, 71 | ECO_ON, 72 | ECO_SHUTDOWN, 73 | CHARGING_MODE, 74 | POWER_LIFTING_ON, 75 | AC_INPUT_POWER_MAX, 76 | AC_INPUT_CURRENT_MAX, 77 | AC_OUTPUT_POWER_MAX, 78 | AC_OUTPUT_CURRENT_MAX, 79 | BATTERY_MIN_PERCENTAGE, // Discharge lower limit 80 | AC_CHARGE_MAX_PERCENTAGE // Percentage to which point battery will be charged with AC 81 | 82 | }; 83 | 84 | typedef struct device_field_data { 85 | enum field_names f_name; 86 | uint8_t f_page; 87 | uint8_t f_offset; 88 | int8_t f_size; 89 | int8_t f_scale; 90 | int8_t f_enum; 91 | enum field_types f_type; 92 | } device_field_data_t; 93 | 94 | #endif -------------------------------------------------------------------------------- /Bluetti_ESP32/Device_AC500.h: -------------------------------------------------------------------------------- 1 | #ifndef DEVICE_AC500_H 2 | #define DEVICE_AC500_H 3 | #include "Arduino.h" 4 | 5 | /* Not implemented yet 6 | enum output_mode { 7 | STOP = 0, 8 | INVERTER_OUTPUT = 1, 9 | BYPASS_OUTPUT_C = 2, 10 | BYPASS_OUTPUT_D = 3, 11 | LOAD_MATCHING = 4 12 | }; 13 | 14 | enum ups_mode { 15 | CUSTOMIZED = 1, 16 | PV_PRIORITY = 2, 17 | STANDARD = 3, 18 | TIME_CONTROl = 4 19 | }; 20 | 21 | enum auto_sleep_mode { 22 | THIRTY_SECONDS = 2, 23 | ONE_MINNUTE = 3, 24 | FIVE_MINUTES = 4, 25 | NEVER = 5 26 | }; 27 | */ 28 | 29 | // { FIELD_NAME, PAGE, OFFSET, SIZE, SCALE (if scale is needed e.g. decimal value, defaults to 0) , ENUM (if data is enum, defaults to 0) , FIELD_TYPE } 30 | static device_field_data_t bluetti_device_state[] = { 31 | /*Page 0x00 Core */ 32 | {DEVICE_TYPE, 0x00, 0x0A, 7, 0, 0, STRING_FIELD}, 33 | {SERIAL_NUMBER, 0x00, 0x11, 4, 0 ,0, SN_FIELD}, 34 | {ARM_VERSION, 0x00, 0x17, 2, 0, 0, VERSION_FIELD}, 35 | {DSP_VERSION, 0x00, 0x19, 2, 0, 0, VERSION_FIELD}, 36 | {DC_INPUT_POWER, 0x00, 0x24, 1, 0, 0, UINT_FIELD}, 37 | {AC_INPUT_POWER, 0x00, 0x25, 1, 0, 0, UINT_FIELD}, 38 | {AC_OUTPUT_POWER, 0x00, 0x26, 1, 0, 0, UINT_FIELD}, 39 | {DC_OUTPUT_POWER, 0x00, 0x27, 1, 0, 0, UINT_FIELD}, 40 | {POWER_GENERATION, 0x00, 0x29, 1, 1, 0, DECIMAL_FIELD}, 41 | {TOTAL_BATTERY_PERCENT, 0x00, 0x2B, 1,0,0, UINT_FIELD}, 42 | {AC_OUTPUT_ON, 0x00, 0x30, 1, 0, 0, BOOL_FIELD}, 43 | {DC_OUTPUT_ON, 0x00, 0x31, 1, 0, 0, BOOL_FIELD}, 44 | 45 | /*Page 0x00 Details 46 | {INTERNAL_AC_VOLTAGE, 0x00, 0x47, 1, 1, 0, DECIMAL_FIELD}, 47 | {INTERNAL_CURRENT_ONE, 0x00, 0x48, 1, 1, 0, DECIMAL_FIELD}, 48 | 49 | //Page 0x00 Battery Details 50 | {PACK_NUM_MAX, 0x00, 0x5B, 1, 0, 0, UINT_FIELD }, 51 | 52 | //Page 0x00 Battery Data 53 | {PACK_VOLTAGE, 0x00, 0x62, 1, 2 ,0 ,DECIMAL_FIELD}, 54 | */ 55 | 56 | }; 57 | 58 | static device_field_data_t bluetti_device_command[] = { 59 | /*Page 0x00 Core */ 60 | {AC_OUTPUT_ON, 0x0B, 0xBF, 1, 0, 0, BOOL_FIELD}, 61 | {DC_OUTPUT_ON, 0x0B, 0xC0, 1, 0, 0, BOOL_FIELD} 62 | }; 63 | 64 | static device_field_data_t bluetti_polling_command[] = { 65 | {FIELD_UNDEFINED, 0x00, 0x0A, 0x28 ,0 , 0, TYPE_UNDEFINED}, 66 | {FIELD_UNDEFINED, 0x00, 0x46, 0x15 ,0 , 0, TYPE_UNDEFINED}, 67 | {FIELD_UNDEFINED, 0x0B, 0xB9, 0x3D ,0 , 0, TYPE_UNDEFINED} 68 | }; 69 | 70 | #endif 71 | -------------------------------------------------------------------------------- /Bluetti_ESP32/Device_EP500.h: -------------------------------------------------------------------------------- 1 | #ifndef DEVICE_EP500_H 2 | #define DEVICE_EP500_H 3 | #include "Arduino.h" 4 | 5 | /* Not implemented yet 6 | enum output_mode { 7 | STOP = 0, 8 | INVERTER_OUTPUT = 1, 9 | BYPASS_OUTPUT_C = 2, 10 | BYPASS_OUTPUT_D = 3, 11 | LOAD_MATCHING = 4 12 | }; 13 | 14 | enum ups_mode { 15 | CUSTOMIZED = 1, 16 | PV_PRIORITY = 2, 17 | STANDARD = 3, 18 | TIME_CONTROl = 4 19 | }; 20 | 21 | enum auto_sleep_mode { 22 | THIRTY_SECONDS = 2, 23 | ONE_MINNUTE = 3, 24 | FIVE_MINUTES = 4, 25 | NEVER = 5 26 | }; 27 | */ 28 | 29 | // { FIELD_NAME, PAGE, OFFSET, SIZE, SCALE (if scale is needed e.g. decimal value, defaults to 0) , ENUM (if data is enum, defaults to 0) , FIELD_TYPE } 30 | static device_field_data_t bluetti_device_state[] = { 31 | /*Page 0x00 Core */ 32 | {DEVICE_TYPE, 0x00, 0x0A, 7, 0, 0, STRING_FIELD}, 33 | {SERIAL_NUMBER, 0x00, 0x11, 4, 0 ,0, SN_FIELD}, 34 | {ARM_VERSION, 0x00, 0x17, 2, 0, 0, VERSION_FIELD}, 35 | {DSP_VERSION, 0x00, 0x19, 2, 0, 0, VERSION_FIELD}, 36 | {DC_INPUT_POWER, 0x00, 0x24, 1, 0, 0, UINT_FIELD}, 37 | {AC_INPUT_POWER, 0x00, 0x25, 1, 0, 0, UINT_FIELD}, 38 | {AC_OUTPUT_POWER, 0x00, 0x26, 1, 0, 0, UINT_FIELD}, 39 | {DC_OUTPUT_POWER, 0x00, 0x27, 1, 0, 0, UINT_FIELD}, 40 | {POWER_GENERATION, 0x00, 0x29, 1, 1, 0, DECIMAL_FIELD}, 41 | {TOTAL_BATTERY_PERCENT, 0x00, 0x2B, 1,0,0, UINT_FIELD}, 42 | {AC_OUTPUT_ON, 0x00, 0x30, 1, 0, 0, BOOL_FIELD}, 43 | {DC_OUTPUT_ON, 0x00, 0x31, 1, 0, 0, BOOL_FIELD}, 44 | 45 | /*Page 0x00 Details 46 | {INTERNAL_AC_VOLTAGE, 0x00, 0x47, 1, 1, 0, DECIMAL_FIELD}, 47 | {INTERNAL_CURRENT_ONE, 0x00, 0x48, 1, 1, 0, DECIMAL_FIELD}, 48 | 49 | //Page 0x00 Battery Details 50 | {PACK_NUM_MAX, 0x00, 0x5B, 1, 0, 0, UINT_FIELD }, 51 | 52 | //Page 0x00 Battery Data 53 | {PACK_VOLTAGE, 0x00, 0x62, 1, 2 ,0 ,DECIMAL_FIELD}, 54 | */ 55 | 56 | }; 57 | 58 | static device_field_data_t bluetti_device_command[] = { 59 | /*Page 0x00 Core */ 60 | {AC_OUTPUT_ON, 0x0B, 0xBF, 1, 0, 0, BOOL_FIELD}, 61 | {DC_OUTPUT_ON, 0x0B, 0xC0, 1, 0, 0, BOOL_FIELD}, 62 | }; 63 | 64 | static device_field_data_t bluetti_polling_command[] = { 65 | {FIELD_UNDEFINED, 0x00, 0x0A, 0x28 ,0 , 0, TYPE_UNDEFINED}, 66 | {FIELD_UNDEFINED, 0x00, 0x46, 0x15 ,0 , 0, TYPE_UNDEFINED}, 67 | {FIELD_UNDEFINED, 0x0B, 0xB9, 0x3D ,0 , 0, TYPE_UNDEFINED} 68 | }; 69 | 70 | #endif 71 | -------------------------------------------------------------------------------- /Bluetti_ESP32/crc16.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2002, 2003, 2004 Marek Michalkiewicz 2 | Copyright (c) 2005, 2007 Joerg Wunsch 3 | All rights reserved. 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | * Redistributions of source code must retain the above copyright 7 | notice, this list of conditions and the following disclaimer. 8 | * Redistributions in binary form must reproduce the above copyright 9 | notice, this list of conditions and the following disclaimer in 10 | the documentation and/or other materials provided with the 11 | distribution. 12 | * Neither the name of the copyright holders nor the names of 13 | contributors may be used to endorse or promote products derived 14 | from this software without specific prior written permission. 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 16 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 18 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 19 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 20 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 21 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 22 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 23 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 24 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 25 | POSSIBILITY OF SUCH DAMAGE. */ 26 | 27 | // Port to Energia / MPS430 by Yannick DEVOS XV4Y - (c) 2013 28 | // http://xv4y.radioclub.asia/ 29 | // 30 | 31 | /* $Id: crc16.h 2136 2010-06-08 12:03:38Z joerg_wunsch $ */ 32 | 33 | #ifndef _UTIL_CRC16_H_ 34 | #define _UTIL_CRC16_H_ 35 | 36 | #include 37 | 38 | #define lo8(x) ((x)&0xff) 39 | #define hi8(x) ((x)>>8) 40 | 41 | uint16_t crc16_update(uint16_t crc, uint8_t a) 42 | { 43 | int i; 44 | 45 | crc ^= a; 46 | for (i = 0; i < 8; ++i) 47 | { 48 | if (crc & 1) 49 | crc = (crc >> 1) ^ 0xA001; 50 | else 51 | crc = (crc >> 1); 52 | } 53 | 54 | return crc; 55 | } 56 | 57 | uint16_t crc_xmodem_update (uint16_t crc, uint8_t data) 58 | { 59 | int i; 60 | 61 | crc = crc ^ ((uint16_t)data << 8); 62 | for (i=0; i<8; i++) 63 | { 64 | if (crc & 0x8000) 65 | crc = (crc << 1) ^ 0x1021; 66 | else 67 | crc <<= 1; 68 | } 69 | 70 | return crc; 71 | } 72 | uint16_t _crc_ccitt_update (uint16_t crc, uint8_t data) 73 | { 74 | data ^= lo8 (crc); 75 | data ^= data << 4; 76 | 77 | return ((((uint16_t)data << 8) | hi8 (crc)) ^ (uint8_t)(data >> 4) 78 | ^ ((uint16_t)data << 3)); 79 | } 80 | 81 | uint8_t _crc_ibutton_update(uint8_t crc, uint8_t data) 82 | { 83 | uint8_t i; 84 | 85 | crc = crc ^ data; 86 | for (i = 0; i < 8; i++) 87 | { 88 | if (crc & 0x01) 89 | crc = (crc >> 1) ^ 0x8C; 90 | else 91 | crc >>= 1; 92 | } 93 | 94 | return crc; 95 | } 96 | 97 | 98 | #endif /* _UTIL_CRC16_H_ */ 99 | -------------------------------------------------------------------------------- /scripts/post_esp32.py: -------------------------------------------------------------------------------- 1 | # Part of ESPEasy build toolchain. 2 | # Modified version of: https://raw.githubusercontent.com/letscontrolit/ESPEasy/mega/tools/pio/post_esp32.py 3 | # 4 | # Combines separate bin files with their respective offsets into a single file 5 | # This single file must then be flashed to an ESP32 node with 0 offset. 6 | # 7 | # Original implementation: Bartłomiej Zimoń (@uzi18) 8 | # Maintainer: Gijs Noorlander (@TD-er) 9 | # 10 | # Special thanks to @Jason2866 (Tasmota) for helping debug flashing to >4MB flash 11 | # Thanks @jesserockz (esphome) for adapting to use esptool.py with merge_bin 12 | # 13 | # Typical layout of the generated file: 14 | # Offset | File 15 | # - 0x1000 | ~\.platformio\packages\framework-arduinoespressif32\tools\sdk\esp32\bin\bootloader_dout_40m.bin 16 | # - 0x8000 | ~\ESPEasy\.pio\build\\partitions.bin 17 | # - 0xe000 | ~\.platformio\packages\framework-arduinoespressif32\tools\partitions\boot_app0.bin 18 | # - 0x10000 | ~\ESPEasy\.pio\build\/.bin 19 | 20 | Import("env") 21 | 22 | platform = env.PioPlatform() 23 | 24 | import sys 25 | from os.path import join 26 | from os import makedirs 27 | from shutil import copyfile 28 | 29 | sys.path.append(join(platform.get_package_dir("tool-esptoolpy"))) 30 | import esptool 31 | 32 | def esp32_create_combined_bin(source, target, env): 33 | print("Generating combined binary for serial flashing") 34 | 35 | # The offset from begin of the file where the app0 partition starts 36 | # This is defined in the partition .csv file 37 | app_offset = 0x10000 38 | 39 | build_dir = "build" 40 | bin_name = "Bluetti_ESP32_Bridge" 41 | 42 | makedirs(build_dir, exist_ok=True) 43 | new_file_name = env.subst(f"{build_dir}/{bin_name}.factory.bin") 44 | sections = env.subst(env.get("FLASH_EXTRA_IMAGES")) 45 | firmware_name = env.subst("$BUILD_DIR/${PROGNAME}.bin") 46 | chip = env.get("BOARD_MCU") 47 | flash_size = env.BoardConfig().get("upload.flash_size") 48 | flash_freq = env.BoardConfig().get("build.f_flash", '40m') 49 | flash_freq = flash_freq.replace('000000L', 'm') 50 | flash_mode = env.BoardConfig().get("build.flash_mode", "dio") 51 | memory_type = env.BoardConfig().get("build.arduino.memory_type", "qio_qspi") 52 | if flash_mode == "qio" or flash_mode == "qout": 53 | flash_mode = "dio" 54 | if memory_type == "opi_opi" or memory_type == "opi_qspi": 55 | flash_mode = "dout" 56 | cmd = [ 57 | "--chip", 58 | chip, 59 | "merge_bin", 60 | "-o", 61 | new_file_name, 62 | "--flash_mode", 63 | flash_mode, 64 | "--flash_freq", 65 | flash_freq, 66 | "--flash_size", 67 | flash_size, 68 | ] 69 | 70 | print(" Offset | File") 71 | for section in sections: 72 | sect_adr, sect_file = section.split(" ", 1) 73 | print(f" - {sect_adr} | {sect_file}") 74 | cmd += [sect_adr, sect_file] 75 | 76 | print(f" - {hex(app_offset)} | {firmware_name}") 77 | cmd += [hex(app_offset), firmware_name] 78 | 79 | 80 | 81 | print('Using esptool.py arguments: %s' % ' '.join(cmd)) 82 | 83 | esptool.main(cmd) 84 | copyfile(firmware_name, f"{build_dir}/{bin_name}.ota.bin") 85 | 86 | 87 | env.AddPostAction("$BUILD_DIR/${PROGNAME}.bin", esp32_create_combined_bin) 88 | 89 | -------------------------------------------------------------------------------- /Bluetti_ESP32/DEVICE_EB3A.h: -------------------------------------------------------------------------------- 1 | #ifndef DEVICE_EB3A_H 2 | #define DEVICE_EB3A_H 3 | #include "Arduino.h" 4 | 5 | /* Not implemented yet 6 | //Need to check which additional functions on EB3A are supported 7 | enum output_mode { 8 | STOP = 0, 9 | INVERTER_OUTPUT = 1, 10 | BYPASS_OUTPUT_C = 2, 11 | BYPASS_OUTPUT_D = 3, 12 | LOAD_MATCHING = 4 13 | }; 14 | 15 | enum ups_mode { 16 | CUSTOMIZED = 1, 17 | PV_PRIORITY = 2, 18 | STANDARD = 3, 19 | TIME_CONTROl = 4 20 | }; 21 | 22 | enum auto_sleep_mode { 23 | THIRTY_SECONDS = 2, 24 | ONE_MINNUTE = 3, 25 | FIVE_MINUTES = 4, 26 | NEVER = 5 27 | }; 28 | */ 29 | 30 | enum LedMode { 31 | LED_LOW = 1, 32 | LED_HIGH = 2, 33 | LED_SOS = 3, 34 | LED_OFF = 4 35 | }; 36 | 37 | enum EcoShutdown { 38 | ONE_HOUR = 1, 39 | TWO_HOURS = 2, 40 | THREE_HOURS = 3, 41 | FOUR_HOURS = 4 42 | }; 43 | 44 | enum ChargingMode { 45 | STANDARD = 0, 46 | SILENT = 1, 47 | TURBO = 2 48 | }; 49 | 50 | // { FIELD_NAME, PAGE, OFFSET, SIZE, SCALE (if scale is needed e.g. decimal value, defaults to 0) , ENUM (if data is enum, defaults to 0) , FIELD_TYPE } 51 | static device_field_data_t bluetti_device_state[] = { 52 | /*Page 0x00 Core */ 53 | {DEVICE_TYPE, 0x00, 0x0A, 7, 0, 0, STRING_FIELD}, 54 | {SERIAL_NUMBER, 0x00, 0x11, 4, 0 ,0, SN_FIELD}, 55 | {ARM_VERSION, 0x00, 0x17, 2, 0, 0, VERSION_FIELD}, 56 | {DSP_VERSION, 0x00, 0x19, 2, 0, 0, VERSION_FIELD}, 57 | {DC_INPUT_POWER, 0x00, 0x24, 1, 0, 0, UINT_FIELD}, 58 | {AC_INPUT_POWER, 0x00, 0x25, 1, 0, 0, UINT_FIELD}, 59 | {AC_OUTPUT_POWER, 0x00, 0x26, 1, 0, 0, UINT_FIELD}, 60 | {DC_OUTPUT_POWER, 0x00, 0x27, 1, 0, 0, UINT_FIELD}, 61 | {POWER_GENERATION, 0x00, 0x29, 1, 1, 0, DECIMAL_FIELD}, 62 | {TOTAL_BATTERY_PERCENT, 0x00, 0x2B, 1,0,0, UINT_FIELD}, 63 | {AC_OUTPUT_ON, 0x00, 0x30, 1, 0, 0, BOOL_FIELD}, 64 | {DC_OUTPUT_ON, 0x00, 0x31, 1, 0, 0, BOOL_FIELD}, 65 | 66 | //Page 0x00 Details 67 | //{INTERNAL_AC_VOLTAGE, 0x00, 0x47, 1, 1, 0, DECIMAL_FIELD}, 68 | //{INTERNAL_CURRENT_ONE, 0x00, 0x48, 1, 1, 0, DECIMAL_FIELD}, 69 | {AC_INPUT_VOLTAGE, 0x00, 0x4D, 1, 1, 0, DECIMAL_FIELD}, 70 | {INTERNAL_DC_INPUT_VOLTAGE, 0x00, 0x56, 1, 1, 0, DECIMAL_FIELD}, 71 | 72 | //Page 0x00 Battery Details 73 | {PACK_NUM_MAX, 0x00, 0x5B, 1, 0, 0, UINT_FIELD }, 74 | 75 | //Page 0x00 Battery Data 76 | //{PACK_VOLTAGE, 0x00, 0x62, 1, 2 ,0 ,DECIMAL_FIELD}, 77 | 78 | }; 79 | 80 | static device_field_data_t bluetti_device_command[] = { 81 | /*Page 0x00 Core */ 82 | {AC_OUTPUT_ON, 0x0B, 0xBF, 1, 0, 0, BOOL_FIELD}, 83 | {DC_OUTPUT_ON, 0x0B, 0xC0, 1, 0, 0, BOOL_FIELD}, 84 | {LED_MODE, 0x0B, 0xDA, 1, 0, 0, ENUM_FIELD}, 85 | {POWER_OFF, 0x0B, 0xF4, 1, 0, 0, BOOL_FIELD}, 86 | {ECO_ON, 0x0B, 0xF7, 1, 0, 0, BOOL_FIELD}, 87 | {ECO_SHUTDOWN, 0x0B, 0xF8, 1, 0, 0, ENUM_FIELD}, 88 | {CHARGING_MODE, 0x0B, 0xF9, 1, 0, 0, ENUM_FIELD}, 89 | {POWER_LIFTING_ON, 0x0B, 0xFA, 1, 0, 0, BOOL_FIELD}, 90 | }; 91 | 92 | static device_field_data_t bluetti_polling_command[] = { 93 | {FIELD_UNDEFINED, 0x00, 0x0A, 0x28 ,0 , 0, TYPE_UNDEFINED}, 94 | {FIELD_UNDEFINED, 0x00, 0x46, 0x15 ,0 , 0, TYPE_UNDEFINED}, 95 | {FIELD_UNDEFINED, 0x0B, 0xDA, 0x01 ,0 , 0, TYPE_UNDEFINED}, 96 | {FIELD_UNDEFINED, 0x0B, 0xF4, 0x07 ,0 , 0, TYPE_UNDEFINED}, 97 | }; 98 | 99 | static device_field_data_t bluetti_logging_command[] = { 100 | {FIELD_UNDEFINED, 0x00, 0x0A, 0x35 ,0 , 0, TYPE_UNDEFINED}, 101 | {FIELD_UNDEFINED, 0x00, 0x46, 0x42 ,0 , 0, TYPE_UNDEFINED}, 102 | {FIELD_UNDEFINED, 0x00, 0x88, 0x4A ,0 , 0, TYPE_UNDEFINED}, 103 | {FIELD_UNDEFINED, 0x0B, 0xB8, 0x43 ,0 , 0, TYPE_UNDEFINED} 104 | 105 | }; 106 | 107 | #endif -------------------------------------------------------------------------------- /Bluetti_ESP32/Device_AC300.h: -------------------------------------------------------------------------------- 1 | #ifndef DEVICE_AC300_H 2 | #define DEVICE_AC300_H 3 | #include "Arduino.h" 4 | 5 | /* Not implemented yet 6 | enum output_mode { 7 | STOP = 0, 8 | INVERTER_OUTPUT = 1, 9 | BYPASS_OUTPUT_C = 2, 10 | BYPASS_OUTPUT_D = 3, 11 | LOAD_MATCHING = 4 12 | }; 13 | 14 | enum ups_mode { 15 | CUSTOMIZED = 1, 16 | PV_PRIORITY = 2, 17 | STANDARD = 3, 18 | TIME_CONTROl = 4 19 | }; 20 | 21 | enum auto_sleep_mode { 22 | THIRTY_SECONDS = 2, 23 | ONE_MINNUTE = 3, 24 | FIVE_MINUTES = 4, 25 | NEVER = 5 26 | }; 27 | */ 28 | 29 | enum auto_sleep_mode { 30 | THIRTY_SECONDS = 2, 31 | ONE_MINNUTE = 3, 32 | FIVE_MINUTES = 4, 33 | NEVER = 5 34 | }; 35 | 36 | enum LedMode { 37 | LED_LOW = 1, 38 | LED_HIGH = 2, 39 | LED_SOS = 3, 40 | LED_OFF = 4 41 | }; 42 | 43 | enum EcoShutdown { 44 | ONE_HOUR = 1, 45 | TWO_HOURS = 2, 46 | THREE_HOURS = 3, 47 | FOUR_HOURS = 4 48 | }; 49 | 50 | enum ChargingMode { 51 | STANDARD = 0, 52 | SILENT = 1, 53 | TURBO = 2 54 | }; 55 | 56 | // { FIELD_NAME, PAGE, OFFSET, SIZE, SCALE (if scale is needed e.g. decimal value, defaults to 0) , ENUM (if data is enum, defaults to 0) , FIELD_TYPE } 57 | static device_field_data_t bluetti_device_state[] = { 58 | /*Page 0x00 Core */ 59 | {DEVICE_TYPE, 0x00, 0x0A, 7, 0, 0, STRING_FIELD}, 60 | {SERIAL_NUMBER, 0x00, 0x11, 4, 0 ,0, SN_FIELD}, 61 | {ARM_VERSION, 0x00, 0x17, 2, 0, 0, VERSION_FIELD}, 62 | {DSP_VERSION, 0x00, 0x19, 2, 0, 0, VERSION_FIELD}, 63 | {DC_INPUT_POWER, 0x00, 0x24, 1, 0, 0, UINT_FIELD}, 64 | {AC_INPUT_POWER, 0x00, 0x25, 1, 0, 0, UINT_FIELD}, 65 | {AC_OUTPUT_POWER, 0x00, 0x26, 1, 0, 0, UINT_FIELD}, 66 | {DC_OUTPUT_POWER, 0x00, 0x27, 1, 0, 0, UINT_FIELD}, 67 | {POWER_GENERATION, 0x00, 0x29, 1, 1, 0, DECIMAL_FIELD}, 68 | {TOTAL_BATTERY_PERCENT, 0x00, 0x2B, 1,0,0, UINT_FIELD}, 69 | {AC_OUTPUT_ON, 0x00, 0x30, 1, 0, 0, BOOL_FIELD}, 70 | {DC_OUTPUT_ON, 0x00, 0x31, 1, 0, 0, BOOL_FIELD}, 71 | {AC_OUTPUT_MODE, 0x00, 0x46, 1, 0, 0, UINT_FIELD}, 72 | 73 | {INTERNAL_AC_VOLTAGE, 0x00, 0x47, 1, 1, 0, DECIMAL_FIELD}, 74 | //INTERNAL_POWER_ONE AC Output usage 75 | {INTERNAL_CURRENT_ONE, 0x00, 0x48, 1, 1, 0, DECIMAL_FIELD}, 76 | {INTERNAL_POWER_ONE, 0x00, 0x49, 1, 0, 0, UINT_FIELD}, 77 | {INTERNAL_AC_FREQUENCY, 0x00, 0x4A, 1, 2, 0, DECIMAL_FIELD}, 78 | //INTERNAL_POWER_TWO AC Internal usage? 79 | {INTERNAL_CURRENT_TWO, 0x00, 0x4B, 1, 1, 0, DECIMAL_FIELD}, 80 | {INTERNAL_POWER_TWO, 0x00, 0x4C, 1, 0, 0, UINT_FIELD}, 81 | {AC_INPUT_VOLTAGE, 0x00, 0x4D, 1, 1, 0, DECIMAL_FIELD}, 82 | //INTERNAL_POWER_THREE AC Load from grid 83 | {INTERNAL_CURRENT_THREE, 0x00, 0x4E, 1, 1, 0, DECIMAL_FIELD}, 84 | {INTERNAL_POWER_THREE, 0x00, 0x4F, 1, 0, 0, UINT_FIELD}, 85 | 86 | 87 | {AC_INPUT_FREQUENCY, 0x00, 0x50, 1, 2, 0, DECIMAL_FIELD}, 88 | {INTERNAL_DC_INPUT_VOLTAGE, 0x00, 0x56, 1, 1, 0, DECIMAL_FIELD}, 89 | {INTERNAL_DC_INPUT_POWER, 0x00, 0x57, 1, 0, 0, UINT_FIELD}, 90 | {INTERNAL_DC_INPUT_CURRENT, 0x00, 0x58, 1, 1, 0, DECIMAL_FIELD}, 91 | {PACK_NUM_MAX, 0x00, 0x5B, 1, 0, 0, UINT_FIELD }, 92 | 93 | {INTERNAL_PACK_VOLTAGE, 0x00, 0x5C, 1, 1 ,0, DECIMAL_FIELD}, 94 | {PACK_BATTERY_PERCENT, 0x00, 0x63, 1, 0, 0, UINT_FIELD}, 95 | 96 | {PACK_NUM, 0x00, 0x60, 1, 0, 0, UINT_FIELD}, 97 | 98 | {UPS_MODE, 0x0B, 0xB9, 1, 0, 0, UINT_FIELD}, 99 | //{PACK_NUM, 0x0B, 0xBE, 1, 0, 0, UINT_FIELD}, 100 | {GRID_CHARGE_ON, 0x0B, 0xC3, 1, 0, 0, BOOL_FIELD}, 101 | {AUTO_SLEEP_MODE, 0x0B, 0xF5, 1, 0, 0, UINT_FIELD} 102 | 103 | 104 | }; 105 | 106 | static device_field_data_t bluetti_device_command[] = { 107 | /*Page 0x00 Core */ 108 | {AC_OUTPUT_ON, 0x0B, 0xBF, 1, 0, 0, BOOL_FIELD}, 109 | {DC_OUTPUT_ON, 0x0B, 0xC0, 1, 0, 0, BOOL_FIELD} 110 | }; 111 | 112 | static device_field_data_t bluetti_polling_command[] = { 113 | {FIELD_UNDEFINED, 0x00, 0x0A, 0x28 ,0 , 0, TYPE_UNDEFINED}, 114 | {FIELD_UNDEFINED, 0x00, 0x46, 0x15 ,0 , 0, TYPE_UNDEFINED}, 115 | // {FIELD_UNDEFINED, 0x0B, 0xB9, 0x3D ,0 , 0, TYPE_UNDEFINED} 116 | 117 | {FIELD_UNDEFINED, 0x0B, 0xDA, 0x01 ,0 , 0, TYPE_UNDEFINED}, 118 | {FIELD_UNDEFINED, 0x0B, 0xF5, 0x07 ,0 , 0, TYPE_UNDEFINED}, 119 | //Pack Polling 120 | {FIELD_UNDEFINED, 0x00, 0x5B, 0x25 ,0 , 0, TYPE_UNDEFINED} 121 | }; 122 | 123 | #endif 124 | -------------------------------------------------------------------------------- /Bluetti_ESP32/Device_AC200M.h: -------------------------------------------------------------------------------- 1 | #ifndef DEVICE_AC200M_H 2 | #define DEVICE_AC200M_H 3 | #include "Arduino.h" 4 | 5 | 6 | enum auto_sleep_mode { 7 | THIRTY_SECONDS = 2, 8 | ONE_MINNUTE = 3, 9 | FIVE_MINUTES = 4, 10 | NEVER = 5 11 | }; 12 | 13 | 14 | // { FIELD_NAME, PAGE, OFFSET, SIZE, SCALE (if scale is needed e.g. decimal value, defaults to 0) , ENUM (if data is enum, defaults to 0) , FIELD_TYPE } 15 | static device_field_data_t bluetti_device_state[] = { 16 | 17 | 18 | /*Page 0x00 Core */ 19 | {DEVICE_TYPE, 0x00, 0x0A, 7, 0, 0, STRING_FIELD}, 20 | {SERIAL_NUMBER, 0x00, 0x11, 4, 0 ,0, SN_FIELD}, 21 | {ARM_VERSION, 0x00, 0x17, 2, 0, 0, VERSION_FIELD}, 22 | {DSP_VERSION, 0x00, 0x19, 2, 0, 0, VERSION_FIELD}, 23 | {DC_INPUT_POWER, 0x00, 0x24, 1, 0, 0, UINT_FIELD}, 24 | {AC_INPUT_POWER, 0x00, 0x25, 1, 0, 0, UINT_FIELD}, 25 | {AC_OUTPUT_POWER, 0x00, 0x26, 1, 0, 0, UINT_FIELD}, 26 | {DC_OUTPUT_POWER, 0x00, 0x27, 1, 0, 0, UINT_FIELD}, 27 | {POWER_GENERATION, 0x00, 0x29, 1, 1, 0, DECIMAL_FIELD}, 28 | {TOTAL_BATTERY_PERCENT, 0x00, 0x2B, 1, 0, 0, UINT_FIELD}, 29 | {AC_OUTPUT_ON, 0x00, 0x30, 1, 0, 0, BOOL_FIELD}, 30 | {DC_OUTPUT_ON, 0x00, 0x31, 1, 0, 0, BOOL_FIELD}, 31 | 32 | {INTERNAL_AC_VOLTAGE, 0x00, 0x47, 1, 0, 0, DECIMAL_FIELD}, 33 | {INTERNAL_AC_FREQUENCY, 0x00, 0x4A, 2, 1, 0, DECIMAL_FIELD}, 34 | 35 | {AC_INPUT_VOLTAGE, 0x00, 0x4D, 1, 1, 0, DECIMAL_FIELD}, 36 | {INTERNAL_DC_INPUT_VOLTAGE, 0x00, 0x56, 1, 1, 0, DECIMAL_FIELD}, 37 | 38 | 39 | //Page 0x00 Battery Details 40 | //constant value, number off possible battery packs, 3 on AC200M, one internal and two external 41 | {PACK_NUM_MAX, 0x00, 0x5B, 1, 0, 0, UINT_FIELD }, 42 | 43 | 44 | //Page 0x00 Battery Data 45 | {INTERNAL_PACK_VOLTAGE, 0x00, 0x5C, 1, 2 ,0, DECIMAL_FIELD}, 46 | {INTERNAL_CELL01_VOLTAGE, 0x00, 0x69, 1, 2 ,0, DECIMAL_FIELD}, 47 | {INTERNAL_CELL02_VOLTAGE, 0x00, 0x6A, 1, 2 ,0, DECIMAL_FIELD}, 48 | {INTERNAL_CELL03_VOLTAGE, 0x00, 0x6B, 1, 2 ,0, DECIMAL_FIELD}, 49 | {INTERNAL_CELL04_VOLTAGE, 0x00, 0x6C, 1, 2 ,0, DECIMAL_FIELD}, 50 | {INTERNAL_CELL05_VOLTAGE, 0x00, 0x6D, 1, 2 ,0, DECIMAL_FIELD}, 51 | {INTERNAL_CELL06_VOLTAGE, 0x00, 0x6E, 1, 2 ,0, DECIMAL_FIELD}, 52 | {INTERNAL_CELL07_VOLTAGE, 0x00, 0x6F, 1, 2 ,0, DECIMAL_FIELD}, 53 | {INTERNAL_CELL08_VOLTAGE, 0x00, 0x70, 1, 2 ,0, DECIMAL_FIELD}, 54 | {INTERNAL_CELL09_VOLTAGE, 0x00, 0x71, 1, 2 ,0, DECIMAL_FIELD}, 55 | {INTERNAL_CELL10_VOLTAGE, 0x00, 0x72, 1, 2 ,0, DECIMAL_FIELD}, 56 | {INTERNAL_CELL11_VOLTAGE, 0x00, 0x73, 1, 2 ,0, DECIMAL_FIELD}, 57 | {INTERNAL_CELL12_VOLTAGE, 0x00, 0x74, 1, 2 ,0, DECIMAL_FIELD}, 58 | {INTERNAL_CELL13_VOLTAGE, 0x00, 0x75, 1, 2 ,0, DECIMAL_FIELD}, 59 | {INTERNAL_CELL14_VOLTAGE, 0x00, 0x76, 1, 2 ,0, DECIMAL_FIELD}, 60 | {INTERNAL_CELL15_VOLTAGE, 0x00, 0x77, 1, 2 ,0, DECIMAL_FIELD}, 61 | {INTERNAL_CELL16_VOLTAGE, 0x00, 0x78, 1, 2 ,0, DECIMAL_FIELD}, 62 | 63 | //Page 0x0B Controls 64 | // Time after the display switches off -> READ 65 | {AUTO_SLEEP_MODE, 0x0B, 0xF5, 1, 0, 0, UINT_FIELD}, 66 | 67 | }; 68 | 69 | // parameters that can be set via mqtt. 70 | // Hint: In the case topics not appearing automatically on the mqtt server they need to be created manually. 71 | // This can be done with MqttExplorer for instance 72 | static device_field_data_t bluetti_device_command[] = { 73 | /*Page 0x0B Core */ 74 | {DC_OUTPUT_ON, 0x0B, 0xC0, 1, 0, 0, BOOL_FIELD}, 75 | {AC_OUTPUT_ON, 0x0B, 0xBF, 1, 0, 0, BOOL_FIELD}, 76 | 77 | // Time after the display switches off -> WRITE 78 | // Caution: there is no check on the device, if the value is within the list of alowed values. 79 | // for allowed values see above, use of other values seems to confuse the HMI. 80 | // The possibility to set this parameter on the HMI (Diplay) disappears. 81 | // But by writing an allowed value it turns back to normality. 82 | // I guess this is true for all "enum type" settings 83 | {AUTO_SLEEP_MODE, 0x0B, 0xF5, 1, 0, 0, UINT_FIELD}, 84 | {POWER_OFF, 0x0B, 0xF4, 1, 0, 0, BOOL_FIELD}, 85 | 86 | }; 87 | 88 | static device_field_data_t bluetti_polling_command[] = { 89 | // Status 90 | // changed to only one page 0 request (a portion of 7F bytes) 91 | {FIELD_UNDEFINED, 0x00, 0x0A, 0x7F, 0, 0, TYPE_UNDEFINED}, 92 | // Settings 93 | {FIELD_UNDEFINED, 0x0B, 0xB9, 0x3F, 0, 0, TYPE_UNDEFINED} 94 | }; 95 | 96 | #endif 97 | -------------------------------------------------------------------------------- /Bluetti_ESP32/PayloadParser.cpp: -------------------------------------------------------------------------------- 1 | #include "BluettiConfig.h" 2 | #include "MQTT.h" 3 | #include "PayloadParser.h" 4 | #include "BWifi.h" 5 | 6 | 7 | uint16_t parse_uint_field(uint8_t data[]) { 8 | return ((uint16_t)data[0] << 8) | (uint16_t)data[1]; 9 | } 10 | 11 | bool parse_bool_field(uint8_t data[]) { 12 | return (data[1]) == 1; 13 | } 14 | 15 | float parse_decimal_field(uint8_t data[], uint8_t scale) { 16 | uint16_t raw_value = ((uint16_t)data[0] << 8) | (uint16_t)data[1]; 17 | return (raw_value) / pow(10, scale); 18 | } 19 | 20 | float parse_version_field(uint8_t data[]) { 21 | 22 | uint16_t low = ((uint16_t)data[0] << 8) | (uint16_t)data[1]; 23 | uint16_t high = ((uint16_t)data[2] << 8) | (uint16_t)data[3]; 24 | long val = (low) | (high << 16); 25 | 26 | return (float)val / 100; 27 | } 28 | 29 | uint64_t parse_serial_field(uint8_t data[]) { 30 | 31 | uint16_t val1 = ((uint16_t)data[0] << 8) | (uint16_t)data[1]; 32 | uint16_t val2 = ((uint16_t)data[2] << 8) | (uint16_t)data[3]; 33 | uint16_t val3 = ((uint16_t)data[4] << 8) | (uint16_t)data[5]; 34 | uint16_t val4 = ((uint16_t)data[6] << 8) | (uint16_t)data[7]; 35 | 36 | uint64_t sn = ((((uint64_t)val1) | ((uint64_t)val2 << 16)) | ((uint64_t)val3 << 32)) | ((uint64_t)val4 << 48); 37 | 38 | return sn; 39 | } 40 | 41 | String parse_string_field(uint8_t data[]) { 42 | return String((char*)data); 43 | } 44 | 45 | // not implemented yet, leads to nothing 46 | String parse_enum_field(uint8_t data[]){ 47 | return ""; 48 | } 49 | 50 | void parse_bluetooth_data(uint8_t page, uint8_t offset, uint8_t* pData, size_t length){ 51 | char Byte_In_Hex_offset[3]; 52 | char Byte_In_Hex_page[3]; 53 | sprintf(Byte_In_Hex_offset, "%x", offset); 54 | sprintf(Byte_In_Hex_page, "%x", page); 55 | 56 | switch(pData[1]){ 57 | // range request 58 | 59 | case 0x03: 60 | 61 | for (int i = 0; i < sizeof(bluetti_device_state) / sizeof(device_field_data_t); i++) { 62 | 63 | 64 | // filter fields not in range, reworked by https://github.com/AlexBurghardt 65 | // the original code didn't work completely and skipped some fields to be published 66 | if( 67 | // it's the correct page 68 | bluetti_device_state[i].f_page == page && 69 | // data offset greater than or equal to page offset 70 | bluetti_device_state[i].f_offset >= offset && 71 | // local offset does not exceed the page length, likely not needed because of the last condition check 72 | ((2* ((int)bluetti_device_state[i].f_offset - (int)offset)) + HEADER_SIZE) <= length && 73 | // local offset + data size do not exceed the page length 74 | ((2* ((int)bluetti_device_state[i].f_offset - (int)offset + bluetti_device_state[i].f_size)) + HEADER_SIZE) <= length 75 | ){ 76 | 77 | uint8_t data_start = (2* ((int)bluetti_device_state[i].f_offset - (int)offset)) + HEADER_SIZE; 78 | uint8_t data_end = (data_start + 2 * bluetti_device_state[i].f_size); 79 | uint8_t data_payload_field[data_end - data_start]; 80 | 81 | int p_index = 0; 82 | for (int i=data_start; i<= data_end; i++){ 83 | data_payload_field[p_index] = pData[i-1]; 84 | p_index++; 85 | } 86 | 87 | switch (bluetti_device_state[i].f_type){ 88 | 89 | case UINT_FIELD: 90 | publishTopic(bluetti_device_state[i].f_name, String(parse_uint_field(data_payload_field))); 91 | break; 92 | 93 | case BOOL_FIELD: 94 | publishTopic(bluetti_device_state[i].f_name, String((int)parse_bool_field(data_payload_field))); 95 | break; 96 | 97 | case DECIMAL_FIELD: 98 | publishTopic(bluetti_device_state[i].f_name, String(parse_decimal_field(data_payload_field, bluetti_device_state[i].f_scale ), 2) ); 99 | break; 100 | 101 | case SN_FIELD: 102 | char sn[16]; 103 | sprintf(sn, "%lld", parse_serial_field(data_payload_field)); 104 | publishTopic(bluetti_device_state[i].f_name, String(sn)); 105 | break; 106 | 107 | case VERSION_FIELD: 108 | publishTopic(bluetti_device_state[i].f_name, String(parse_version_field(data_payload_field),2) ); 109 | break; 110 | 111 | case STRING_FIELD: 112 | publishTopic(bluetti_device_state[i].f_name, parse_string_field(data_payload_field)); 113 | break; 114 | // doesn't work yet, not implemented further 115 | case ENUM_FIELD: 116 | publishTopic(bluetti_device_state[i].f_name, parse_enum_field(data_payload_field)); 117 | break; 118 | default: 119 | break; 120 | 121 | } 122 | 123 | } 124 | else{ 125 | /* causes way too many messages, for debugging only 126 | //AddtoMsgView(String(millis()) + ": skip filtered field: "+ Byte_In_Hex_page + " offset: " + Byte_In_Hex_offset); 127 | */ 128 | } 129 | } 130 | 131 | break; 132 | case 0x06: 133 | AddtoMsgView(String(millis()) + ":skip 0x06 request! page: " + Byte_In_Hex_page + " offset: " + Byte_In_Hex_offset); 134 | break; 135 | default: 136 | AddtoMsgView(String(millis()) + ":skip unknow request! page: " + Byte_In_Hex_page + " offset: " + Byte_In_Hex_offset); 137 | break; 138 | 139 | } 140 | 141 | } 142 | -------------------------------------------------------------------------------- /Bluetti_ESP32/index.h: -------------------------------------------------------------------------------- 1 | const char index_html[] PROGMEM = R"rawliteral( 2 | 3 | 4 | Bluetti MQTT Bridge 5 | 6 | 17 | 18 | 19 |
20 |

Bluetti MQTT Bridge web server

21 |
22 | Firmware Version: 0.1.1 (Update) 23 |
24 |
25 |
26 |
27 |
28 |

System

29 |

30 |

IP: %IP% reboot

31 |

MAC: %MAC%

32 |

SSID: %SSID% reset

33 |

RSSI: %RSSI%

34 |

35 |
36 |
37 |

Runtime

38 |

39 |

%RUNTIME% ms

40 |

%RUNTIME_H% h

41 |

%RUNTIME_D% d

42 |

43 |
44 |
45 |

MQTT

46 |

47 |

server: %MQTT_IP%

48 |

port: %MQTT_PORT%

49 |

connected: %MQTT_CONNECTED%

50 |

last msg time: %LAST_MQTT_MSG_TIME%

51 |

52 |
53 |
54 |

Bluetooth

55 |

56 |

Bluetti device id: %DEVICE_ID%

57 |

connected: %BT_CONNECTED%

58 |

last msg time: %LAST_BT_MSG_TIME%

59 |

publish errors: %BT_ERROR%

60 |

61 |
62 |
63 |
64 |

switch logging mode

65 |

last messages (time / value):

66 |

67 |

%LAST_MSG%

68 |

69 |
70 |
71 | 72 | 73 | 159 | 160 | )rawliteral"; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## About 2 | This is an ESP32 based Bluetooth to MQTT Bride for BLUETTI power stations. The project is based on https://github.com/warhammerkid/bluetti_mqtt 3 | The code is tested on a AC300. Other Powerstations should also work but are untested yet. The discussion on https://diysolarforum.com/threads/monitoring-bluetti-systems.37870/ was a great help for understanding the protocol. 4 | 5 | ## Community 6 | Join the Discord Server https://discord.gg/fWDSBTCVmB 7 | 8 | ## Features 9 | 10 | * easy configuration with WiFi manager 11 | * display support OLED 128x64 12 | * tested ESP32 WROOM with display: https://github.com/LilyGO/TTGO-T2-ESP32 13 | * mqtt support 14 | * support for BLUETTI power stations 15 | * AC300 (tested) 16 | * AC200 (tested) 17 | * EB3A (tested) 18 | * EP500 (untested) 19 | * EP500P (tested) 20 | * EP600 (some values still missing) 21 | * supported BLUETTI functions 22 | * commands 23 | * ac output on/off 24 | * dc output on/off 25 | * states 26 | * ac input power 27 | * dc input power 28 | * ac output power 29 | * dc output power 30 | * dsp firmware version 31 | * arm firmware version 32 | * serial number 33 | * device type 34 | * power generation 35 | * total battery percent 36 | 37 | ## Getting Started 38 | 39 | ### Configuration 40 | 41 | Create a copy of config.sample.h and name it config.h 42 | Change at least the device type to fit your Bluetti device. 43 | 44 | ### Compiling and Flashing to ESP32 45 | 46 | #### Arduino IDE 47 | 48 | You will need to install a board support package for your ESP32. Additionally the following libraries are needed: 49 | 50 | * https://github.com/tzapu/WiFiManager 51 | * https://github.com/knolleary/pubsubclient 52 | * https://github.com/ayushsharma82/ElegantOTA 53 | * https://github.com/me-no-dev/ESPAsyncWebServer 54 | * https://github.com/me-no-dev/AsyncTCP/archive 55 | 56 | Change the partition scheme with Tools -> Partition Scheme to 57 | 58 | * Minimal SPIFFS (1.9 MB App with OTA/ 190KB SPIFFS) 59 | 60 | ![Wifi Manager start menu](doc/images/partition.png) 61 | 62 | This setting is required because the Bluetooth stack already uses a lot of the ESP32 memory. 63 | 64 | Optional: Do changes in config.h file. The device can be set by changing 'BLUETTI_TYPE'. 65 | 66 | Finally upload the Sketch to your ESP32. 67 | 68 | *INFO*: Until now only BLUETTI_AC300, BLUETTI_EP500P was tested. If you own one of the supported devices please let me know if it works. 69 | 70 | #### PlatformIO 71 | 72 | Compiling 73 | ``` 74 | $ pio run 75 | ``` 76 | 77 | Flashing Factory Image 78 | ``` 79 | $ esptool.py write_flash 0x0 build/Bluetti_ESP32_Bridge.factory.bin 80 | ``` 81 | 82 | Updating only App (don't delete settings) 83 | ``` 84 | # Write Partition A 85 | $ esptool.py write_flash 0x10000 build/Bluetti_ESP32_Bridge.ota.bin 86 | ... 87 | # Write Partition B 88 | $ esptool.py write_flash 0x1F0000 build/Bluetti_ESP32_Bridge.ota.bin 89 | ``` 90 | 91 | The configuration interface also offers OTA updates. You can flash also `build/Bluetti_ESP32_Bridge.ota.bin` there. If you already configured your device you can use `http:///command 122 | * ac_output_on 123 | * dc_output_on 124 | 125 | #### State 126 | States are published to 127 | * /bluetti//state 128 | * ac_output_on 129 | * dc_output_on 130 | * dc_input_power 131 | * ac_input_power 132 | * ac_output_power 133 | * dc_output_power 134 | * serial 135 | * dsp_version 136 | * arm_version 137 | * power_generation 138 | * total_battery_percent 139 | 140 | ## Display 141 | Config Display: 142 | * By default, display is disabled. 143 | * Configurations (customize of file Bluetti_ESP32/config.h): 144 | * Enable display: uncomment #define DISPLAYSSD1306 1 145 | * Enable reset of display on init: uncomment DISPLAY_RST_PORT 146 | * Known needed for LoRa TTGO v1.0 147 | * set SCL & SDA ports: default ports are set to SCL=4 & SDA5, to change update DISPLAY_SCL_PORT and DISPLAY_SDA_PORT 148 | 149 | Display functionality: 150 | * Show current assiged IP address (AP mode or normal) 151 | * Show different wifi connection logo, depending on the mode its in and wifi Strength in normal mode (4 bars) 152 | * Show the running time of the device in the format "11d12h15m" Currently max until 49 days as this is the time millis() is reset. 153 | * Show status message, currently shows the init and running status, also BLEscan when scanning 154 | * a progressbar is available but currently not used anywhere. (to see where it can be used) 155 | * Show bluetooth icon status. Connected is static, blinking is trying to connect, together with message in case of scanning. 156 | * Show MQTT icon status. Connected is static, blinking is trying to connect. 157 | 158 | Example display screen: 159 | ![DisplayImage](doc/images/display.jpg) 160 | 161 | 162 | ## TODO 163 | 164 | * add full feature set to device files 165 | * adding support for SD-Card reader, for writing csv data to an sd-card 166 | * adding logging poll commands 167 | 168 | ## Disclaimer 169 | 170 | The code within this repository comes with no guarantee, use it on your own risk. 171 | 172 | Don't touch these firmwares if you don't know how to put the device in the programming mode if something goes wrong. 173 | As per the GPL v3 license, I assume no liability for any damage to you or any other person or equipment. 174 | -------------------------------------------------------------------------------- /Bluetti_ESP32/DEVICE_EP500P.h: -------------------------------------------------------------------------------- 1 | #ifndef DEVICE_EP500P_H 2 | #define DEVICE_EP500P_H 3 | #include "Arduino.h" 4 | 5 | /* Not implemented yet 6 | enum output_mode { 7 | STOP = 0, 8 | INVERTER_OUTPUT = 1, 9 | BYPASS_OUTPUT_C = 2, 10 | BYPASS_OUTPUT_D = 3, 11 | LOAD_MATCHING = 4 12 | }; 13 | 14 | enum ups_mode { 15 | CUSTOMIZED = 1, 16 | PV_PRIORITY = 2, 17 | STANDARD = 3, 18 | TIME_CONTROl = 4 19 | }; 20 | */ 21 | enum auto_sleep_mode { 22 | THIRTY_SECONDS = 2, 23 | ONE_MINNUTE = 3, 24 | FIVE_MINUTES = 4, 25 | NEVER = 5 26 | }; 27 | 28 | 29 | // { FIELD_NAME, PAGE, OFFSET, SIZE, SCALE (if scale is needed e.g. decimal value, defaults to 0) , ENUM (if data is enum, defaults to 0) , FIELD_TYPE } 30 | static device_field_data_t bluetti_device_state[] = { 31 | /*Page 0x00 Core */ 32 | {DEVICE_TYPE, 0x00, 0x0A, 7, 0, 0, STRING_FIELD}, 33 | {SERIAL_NUMBER, 0x00, 0x11, 4, 0 ,0, SN_FIELD}, 34 | {ARM_VERSION, 0x00, 0x17, 2, 0, 0, VERSION_FIELD}, 35 | {DSP_VERSION, 0x00, 0x19, 2, 0, 0, VERSION_FIELD}, 36 | {DC_INPUT_POWER, 0x00, 0x24, 1, 0, 0, UINT_FIELD}, 37 | {AC_INPUT_POWER, 0x00, 0x25, 1, 0, 0, UINT_FIELD}, 38 | {AC_OUTPUT_POWER, 0x00, 0x26, 1, 0, 0, UINT_FIELD}, 39 | {DC_OUTPUT_POWER, 0x00, 0x27, 1, 0, 0, UINT_FIELD}, 40 | {POWER_GENERATION, 0x00, 0x29, 1, 1, 0, DECIMAL_FIELD}, 41 | {TOTAL_BATTERY_PERCENT, 0x00, 0x2B, 1, 0, 0, UINT_FIELD}, 42 | {AC_OUTPUT_ON, 0x00, 0x30, 1, 0, 0, BOOL_FIELD}, 43 | {DC_OUTPUT_ON, 0x00, 0x31, 1, 0, 0, BOOL_FIELD}, 44 | {AC_OUTPUT_MODE, 0x00, 0x46, 1, 0, 0, UINT_FIELD}, 45 | 46 | {INTERNAL_AC_VOLTAGE, 0x00, 0x47, 1, 1, 0, DECIMAL_FIELD}, 47 | //INTERNAL_POWER_ONE AC Output usage 48 | {INTERNAL_CURRENT_ONE, 0x00, 0x48, 1, 1, 0, DECIMAL_FIELD}, 49 | {INTERNAL_POWER_ONE, 0x00, 0x49, 1, 0, 0, UINT_FIELD}, 50 | {INTERNAL_AC_FREQUENCY, 0x00, 0x4A, 1, 2, 0, DECIMAL_FIELD}, 51 | //INTERNAL_POWER_TWO AC Internal usage? 52 | {INTERNAL_CURRENT_TWO, 0x00, 0x4B, 1, 1, 0, DECIMAL_FIELD}, 53 | {INTERNAL_POWER_TWO, 0x00, 0x4C, 1, 0, 0, UINT_FIELD}, 54 | {AC_INPUT_VOLTAGE, 0x00, 0x4D, 1, 1, 0, DECIMAL_FIELD}, 55 | //INTERNAL_POWER_THREE AC Load from grid 56 | {INTERNAL_CURRENT_THREE, 0x00, 0x4E, 1, 1, 0, DECIMAL_FIELD}, 57 | {INTERNAL_POWER_THREE, 0x00, 0x4F, 1, 0, 0, UINT_FIELD}, 58 | 59 | {AC_INPUT_FREQUENCY, 0x00, 0x50, 1, 2, 0, DECIMAL_FIELD}, 60 | {INTERNAL_DC_INPUT_VOLTAGE, 0x00, 0x56, 1, 1, 0, DECIMAL_FIELD}, 61 | {INTERNAL_DC_INPUT_POWER, 0x00, 0x57, 1, 0, 0, UINT_FIELD}, 62 | {INTERNAL_DC_INPUT_CURRENT, 0x00, 0x58, 1, 1, 0, DECIMAL_FIELD}, 63 | {PACK_NUM_MAX, 0x00, 0x5B, 1, 0, 0, UINT_FIELD }, 64 | 65 | {INTERNAL_PACK_VOLTAGE, 0x00, 0x5C, 1, 1 ,0, DECIMAL_FIELD}, 66 | {PACK_BATTERY_PERCENT, 0x00, 0x5E, 1, 0, 0, UINT_FIELD}, 67 | 68 | {PACK_NUM, 0x00, 0x60, 1, 0, 0, UINT_FIELD}, 69 | 70 | {INTERNAL_CELL01_VOLTAGE, 0x00, 0x69, 1, 2 ,0, DECIMAL_FIELD}, 71 | {INTERNAL_CELL02_VOLTAGE, 0x00, 0x6A, 1, 2 ,0, DECIMAL_FIELD}, 72 | {INTERNAL_CELL03_VOLTAGE, 0x00, 0x6B, 1, 2 ,0, DECIMAL_FIELD}, 73 | {INTERNAL_CELL04_VOLTAGE, 0x00, 0x6C, 1, 2 ,0, DECIMAL_FIELD}, 74 | {INTERNAL_CELL05_VOLTAGE, 0x00, 0x6D, 1, 2 ,0, DECIMAL_FIELD}, 75 | {INTERNAL_CELL06_VOLTAGE, 0x00, 0x6E, 1, 2 ,0, DECIMAL_FIELD}, 76 | {INTERNAL_CELL07_VOLTAGE, 0x00, 0x6F, 1, 2 ,0, DECIMAL_FIELD}, 77 | {INTERNAL_CELL08_VOLTAGE, 0x00, 0x70, 1, 2 ,0, DECIMAL_FIELD}, 78 | {INTERNAL_CELL09_VOLTAGE, 0x00, 0x71, 1, 2 ,0, DECIMAL_FIELD}, 79 | {INTERNAL_CELL10_VOLTAGE, 0x00, 0x72, 1, 2 ,0, DECIMAL_FIELD}, 80 | {INTERNAL_CELL11_VOLTAGE, 0x00, 0x73, 1, 2 ,0, DECIMAL_FIELD}, 81 | {INTERNAL_CELL12_VOLTAGE, 0x00, 0x74, 1, 2 ,0, DECIMAL_FIELD}, 82 | {INTERNAL_CELL13_VOLTAGE, 0x00, 0x75, 1, 2 ,0, DECIMAL_FIELD}, 83 | {INTERNAL_CELL14_VOLTAGE, 0x00, 0x76, 1, 2 ,0, DECIMAL_FIELD}, 84 | {INTERNAL_CELL15_VOLTAGE, 0x00, 0x77, 1, 2 ,0, DECIMAL_FIELD}, 85 | {INTERNAL_CELL16_VOLTAGE, 0x00, 0x78, 1, 2 ,0, DECIMAL_FIELD}, 86 | 87 | // {INTERNAL_DC_INPUT_CURRENT, 0x00, 0x88, 1, 1, 0, DECIMAL_FIELD}, 88 | 89 | //Page 0x00 - Controls 90 | {UPS_MODE, 0x0B, 0xB9, 1, 0, 0, UINT_FIELD}, 91 | //{PACK_NUM, 0x0B, 0xBE, 1, 0, 0, UINT_FIELD}, 92 | {GRID_CHARGE_ON, 0x0B, 0xC3, 1, 0, 0, BOOL_FIELD}, 93 | {AUTO_SLEEP_MODE, 0x0B, 0xF5, 1, 0, 0, UINT_FIELD} 94 | 95 | }; 96 | 97 | static device_field_data_t bluetti_device_command[] = { 98 | /*Page 0x0B Core */ 99 | {AC_OUTPUT_ON, 0x0B, 0xBF, 1, 0, 0, BOOL_FIELD}, 100 | {DC_OUTPUT_ON, 0x0B, 0xC0, 1, 0, 0, BOOL_FIELD}, 101 | {GRID_CHARGE_ON, 0x0B, 0xC3, 1, 0, 0, BOOL_FIELD}, 102 | {UPS_MODE, 0x0B, 0xB9, 1, 0, 0, UINT_FIELD}, 103 | {PACK_NUM, 0x0B, 0xBE, 1, 0, 0, UINT_FIELD}, 104 | /* from EB3A 105 | {LED_MODE, 0x0B, 0xDA, 1, 0, 0, ENUM_FIELD}, 106 | {POWER_OFF, 0x0B, 0xF4, 1, 0, 0, BOOL_FIELD}, 107 | {ECO_ON, 0x0B, 0xF7, 1, 0, 0, BOOL_FIELD}, 108 | {ECO_SHUTDOWN, 0x0B, 0xF8, 1, 0, 0, ENUM_FIELD}, 109 | {CHARGING_MODE, 0x0B, 0xF9, 1, 0, 0, ENUM_FIELD}, 110 | {POWER_LIFTING_ON, 0x0B, 0xFA, 1, 0, 0, BOOL_FIELD}, 111 | */ 112 | // Time after the display switches off -> WRITE 113 | // Caution: there is no check on the device, if the value is within the list of alowed values. 114 | // for allowed values see above, use of other values seems to confuse the HMI. 115 | // The possibility to set this parameter on the HMI (Diplay) disappears. 116 | // But by writing an allowed value it turns back to normality, don't be afraid 117 | {AUTO_SLEEP_MODE, 0x0B, 0xF5, 1, 0, 0, UINT_FIELD} 118 | }; 119 | 120 | 121 | static device_field_data_t bluetti_polling_command[] = { 122 | {FIELD_UNDEFINED, 0x00, 0x0A, 0x28 ,0 , 0, TYPE_UNDEFINED}, 123 | {FIELD_UNDEFINED, 0x00, 0x46, 0x15 ,0 , 0, TYPE_UNDEFINED}, 124 | {FIELD_UNDEFINED, 0x0B, 0xDA, 0x01 ,0 , 0, TYPE_UNDEFINED}, 125 | {FIELD_UNDEFINED, 0x0B, 0xF5, 0x07 ,0 , 0, TYPE_UNDEFINED}, 126 | //Pack Polling 127 | {FIELD_UNDEFINED, 0x00, 0x5B, 0x25 ,0 , 0, TYPE_UNDEFINED} 128 | }; 129 | 130 | static device_field_data_t bluetti_logging_command[] = { 131 | {FIELD_UNDEFINED, 0x00, 0x0A, 0x35 ,0 , 0, TYPE_UNDEFINED}, 132 | {FIELD_UNDEFINED, 0x00, 0x46, 0x42 ,0 , 0, TYPE_UNDEFINED}, 133 | {FIELD_UNDEFINED, 0x00, 0x88, 0x4A ,0 , 0, TYPE_UNDEFINED}, 134 | {FIELD_UNDEFINED, 0x0B, 0xB8, 0x43 ,0 , 0, TYPE_UNDEFINED} 135 | }; 136 | 137 | 138 | #endif 139 | -------------------------------------------------------------------------------- /Bluetti_ESP32/BTooth.cpp: -------------------------------------------------------------------------------- 1 | #include "BluettiConfig.h" 2 | #include "BTooth.h" 3 | #include "utils.h" 4 | #include "PayloadParser.h" 5 | #include "BWifi.h" 6 | #include "display.h" 7 | 8 | 9 | int pollTick = 0; 10 | 11 | struct command_handle { 12 | uint8_t page; 13 | uint8_t offset; 14 | int length; 15 | }; 16 | 17 | QueueHandle_t commandHandleQueue; 18 | QueueHandle_t sendQueue; 19 | 20 | unsigned long lastBTMessage = 0; 21 | 22 | class MyClientCallback : public BLEClientCallbacks { 23 | void onConnect(BLEClient* pclient) { 24 | Serial.println(F("BLE - onConnect")); 25 | #ifdef DISPLAYSSD1306 26 | disp_setBlueTooth(true); 27 | #endif 28 | } 29 | 30 | void onDisconnect(BLEClient* pclient) { 31 | connected = false; 32 | Serial.println(F("BLE - onDisconnect")); 33 | #ifdef DISPLAYSSD1306 34 | disp_setBlueTooth(false); 35 | #endif 36 | #ifdef RELAISMODE 37 | #ifdef DEBUG 38 | Serial.println(F("deactivate relais contact")); 39 | #endif 40 | digitalWrite(RELAIS_PIN, RELAIS_LOW); 41 | #endif 42 | } 43 | }; 44 | 45 | /** 46 | * Scan for BLE servers and find the first one that advertises the service we are looking for. 47 | */ 48 | class BluettiAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { 49 | /** 50 | * Called for each advertising BLE server. 51 | */ 52 | void onResult(BLEAdvertisedDevice *advertisedDevice) { 53 | Serial.print(F("[BLE] Advertised Device found: ")); 54 | Serial.println(advertisedDevice->toString().c_str()); 55 | 56 | ESPBluettiSettings settings = get_esp32_bluetti_settings(); 57 | // We have found a device, let us now see if it contains the service we are looking for. 58 | if (advertisedDevice->haveServiceUUID() && advertisedDevice->isAdvertisingService(serviceUUID) && (strcmp(advertisedDevice->getName().c_str(),settings.bluetti_device_id)==0) ) { 59 | BLEDevice::getScan()->stop(); 60 | bluettiDevice = advertisedDevice; 61 | doConnect = true; 62 | doScan = true; 63 | } 64 | } 65 | }; 66 | 67 | void initBluetooth(){ 68 | BLEDevice::init(""); 69 | BLEScan* pBLEScan = BLEDevice::getScan(); 70 | pBLEScan->setAdvertisedDeviceCallbacks(new BluettiAdvertisedDeviceCallbacks()); 71 | pBLEScan->setInterval(1349); 72 | pBLEScan->setWindow(449); 73 | pBLEScan->setActiveScan(true); 74 | pBLEScan->start(5, false); 75 | 76 | commandHandleQueue = xQueueCreate( 5, sizeof(bt_command_t ) ); 77 | sendQueue = xQueueCreate( 5, sizeof(bt_command_t) ); 78 | } 79 | 80 | 81 | static void notifyCallback( 82 | BLERemoteCharacteristic* pBLERemoteCharacteristic, 83 | uint8_t* pData, 84 | size_t length, 85 | bool isNotify) { 86 | 87 | #ifdef DEBUG 88 | Serial.println("[BT] F01 - Write Response"); 89 | /* pData Debug... */ 90 | for (int i=1; i<=length; i++){ 91 | 92 | Serial.printf("%02x", pData[i-1]); 93 | 94 | if(i % 2 == 0){ 95 | Serial.print(" "); 96 | } 97 | 98 | if(i % 16 == 0){ 99 | Serial.println(); 100 | } 101 | } 102 | Serial.println(); 103 | #endif 104 | 105 | bt_command_t command_handle; 106 | if(xQueueReceive(commandHandleQueue, &command_handle, 500)){ 107 | parse_bluetooth_data(command_handle.page, command_handle.offset, pData, length); 108 | } 109 | 110 | } 111 | 112 | bool connectToServer() { 113 | Serial.print(F("[BT] Forming a connection to ")); 114 | Serial.println(bluettiDevice->getAddress().toString().c_str()); 115 | 116 | BLEDevice::setMTU(517); // set client to request maximum MTU from server (default is 23 otherwise) 117 | BLEClient* pClient = BLEDevice::createClient(); 118 | Serial.println(F("[BT] - Created client")); 119 | 120 | pClient->setClientCallbacks(new MyClientCallback()); 121 | 122 | // Connect to the remove BLE Server. 123 | pClient->connect(bluettiDevice); // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private) 124 | Serial.println(F("[BT] - Connected to server")); 125 | // pClient->setMTU(517); //set client to request maximum MTU from server (default is 23 otherwise) 126 | 127 | // Obtain a reference to the service we are after in the remote BLE server. 128 | BLERemoteService* pRemoteService = pClient->getService(serviceUUID); 129 | if (pRemoteService == nullptr) { 130 | Serial.print(F("[BT] Failed to find our service UUID: ")); 131 | Serial.println(serviceUUID.toString().c_str()); 132 | pClient->disconnect(); 133 | return false; 134 | } 135 | Serial.println(F("[BT] - Found our service")); 136 | 137 | 138 | // Obtain a reference to the characteristic in the service of the remote BLE server. 139 | pRemoteWriteCharacteristic = pRemoteService->getCharacteristic(WRITE_UUID); 140 | if (pRemoteWriteCharacteristic == nullptr) { 141 | Serial.print(F("[BT] Failed to find our characteristic UUID: ")); 142 | Serial.println(WRITE_UUID.toString().c_str()); 143 | pClient->disconnect(); 144 | return false; 145 | } 146 | Serial.println(F("[BT] - Found our Write characteristic")); 147 | 148 | // Obtain a reference to the characteristic in the service of the remote BLE server. 149 | pRemoteNotifyCharacteristic = pRemoteService->getCharacteristic(NOTIFY_UUID); 150 | if (pRemoteNotifyCharacteristic == nullptr) { 151 | Serial.print(F("[BT] Failed to find our characteristic UUID: ")); 152 | Serial.println(NOTIFY_UUID.toString().c_str()); 153 | pClient->disconnect(); 154 | return false; 155 | } 156 | Serial.println(F("[BT] - Found our Write characteristic")); 157 | 158 | // Read the value of the characteristic. 159 | if(pRemoteWriteCharacteristic->canRead()) { 160 | std::string value = pRemoteWriteCharacteristic->readValue(); 161 | Serial.print(F("[BT] The characteristic value was: ")); 162 | Serial.println(value.c_str()); 163 | } 164 | 165 | if(pRemoteNotifyCharacteristic->canNotify()) 166 | pRemoteNotifyCharacteristic->registerForNotify(notifyCallback); 167 | 168 | connected = true; 169 | #ifdef RELAISMODE 170 | #ifdef DEBUG 171 | Serial.println(F("[BT] activate relais contact")); 172 | #endif 173 | digitalWrite(RELAIS_PIN, RELAIS_HIGH); 174 | #endif 175 | 176 | return true; 177 | } 178 | 179 | 180 | void handleBTCommandQueue(){ 181 | 182 | bt_command_t command; 183 | if(xQueueReceive(sendQueue, &command, 0)) { 184 | 185 | #ifdef DEBUG 186 | Serial.print("[BT] Write Request FF02 - Value: "); 187 | 188 | for(int i=0; i<8; i++){ 189 | if ( i % 2 == 0){ Serial.print(" "); }; 190 | Serial.printf("%02x", ((uint8_t*)&command)[i]); 191 | } 192 | 193 | Serial.println(""); 194 | #endif 195 | pRemoteWriteCharacteristic->writeValue((uint8_t*)&command, sizeof(command),true); 196 | 197 | }; 198 | } 199 | 200 | void sendBTCommand(bt_command_t command){ 201 | bt_command_t cmd = command; 202 | xQueueSend(sendQueue, &cmd, 0); 203 | } 204 | 205 | void handleBluetooth(){ 206 | 207 | if (doConnect == true) { 208 | if (connectToServer()) { 209 | Serial.println(F("We are now connected to the Bluetti BLE Server.")); 210 | } else { 211 | Serial.println(F("We have failed to connect to the server; there is nothing more we will do.")); 212 | } 213 | doConnect = false; 214 | } 215 | 216 | if ((millis() - lastBTMessage) > (MAX_DISCONNECTED_TIME_UNTIL_REBOOT * 60000)){ 217 | Serial.println(F("[BT] disconnected over allowed limit, reboot device")); 218 | #ifdef SLEEP_TIME_ON_BT_NOT_AVAIL 219 | esp_deep_sleep_start(); 220 | #else 221 | ESP.restart(); 222 | #endif 223 | } 224 | 225 | if (connected) { 226 | 227 | // poll for device state 228 | if ( millis() - lastBTMessage > BLUETOOTH_QUERY_MESSAGE_DELAY){ 229 | 230 | bt_command_t command; 231 | command.prefix = 0x01; 232 | command.field_update_cmd = 0x03; 233 | command.page = bluetti_polling_command[pollTick].f_page; 234 | command.offset = bluetti_polling_command[pollTick].f_offset; 235 | command.len = (uint16_t) bluetti_polling_command[pollTick].f_size << 8; 236 | command.check_sum = modbus_crc((uint8_t*)&command,6); 237 | 238 | xQueueSend(commandHandleQueue, &command, portMAX_DELAY); 239 | xQueueSend(sendQueue, &command, portMAX_DELAY); 240 | 241 | if (pollTick == sizeof(bluetti_polling_command)/sizeof(device_field_data_t)-1 ){ 242 | pollTick = 0; 243 | } else { 244 | pollTick++; 245 | } 246 | 247 | lastBTMessage = millis(); 248 | } 249 | 250 | handleBTCommandQueue(); 251 | 252 | }else if(doScan){ 253 | BLEDevice::getScan()->start(0); 254 | } 255 | } 256 | 257 | void btResetStack() 258 | { 259 | connected=false; 260 | 261 | } 262 | 263 | bool isBTconnected(){ 264 | return connected; 265 | } 266 | 267 | unsigned long getLastBTMessageTime(){ 268 | return lastBTMessage; 269 | } 270 | 271 | 272 | -------------------------------------------------------------------------------- /Bluetti_ESP32/BWifi.cpp: -------------------------------------------------------------------------------- 1 | #include "BluettiConfig.h" 2 | #include "BWifi.h" 3 | #include "BTooth.h" 4 | #include "MQTT.h" 5 | #include "index.h" //Web page header file 6 | #include 7 | #include 8 | #include // https://github.com/me-no-dev/ESPAsyncWebServer/archive/master.zip 9 | #include // https://github.com/me-no-dev/AsyncTCP/archive/master.zip 10 | #include 11 | #include // https://github.com/ayushsharma82/ElegantOTA/archive/master.zip 12 | #include "display.h" 13 | 14 | AsyncWebServer server(80); 15 | AsyncEventSource events("/events"); 16 | 17 | unsigned long lastTimeWebUpdate = 0; 18 | 19 | String lastMsg = ""; 20 | 21 | bool msgViewerDetails = false; 22 | bool shouldSaveConfig = false; 23 | int wifiReconnectCounter = 0; 24 | 25 | char mqtt_server[40] = "127.0.0.1"; 26 | char mqtt_port[6] = "1883"; 27 | char bluetti_device_id[40] = "e.g. ACXXXYYYYYYYY"; 28 | 29 | void saveConfigCallback () { 30 | shouldSaveConfig = true; 31 | } 32 | 33 | 34 | ESPBluettiSettings wifiConfig; 35 | 36 | ESPBluettiSettings get_esp32_bluetti_settings(){ 37 | return wifiConfig; 38 | return wifiConfig; 39 | } 40 | 41 | void eeprom_read(){ 42 | Serial.println(F("Loading Values from EEPROM")); 43 | EEPROM.begin(512); 44 | EEPROM.get(0, wifiConfig); 45 | EEPROM.end(); 46 | } 47 | 48 | void eeprom_saveconfig(){ 49 | Serial.println(F("Saving Values to EEPROM")); 50 | EEPROM.begin(512); 51 | EEPROM.put(0, wifiConfig); 52 | EEPROM.commit(); 53 | EEPROM.end(); 54 | } 55 | 56 | void setWiFiPowerSavingMode(){ 57 | //esp_wifi_set_ps(WIFI_PS_MAX_MODEM); // maximum power saving, does not make sense here 58 | //esp_wifi_set_ps(WIFI_PS_NONE); // will cause kernel panic and reboot on my ESP32 (AlexBurghardt) 59 | esp_wifi_set_ps(WIFI_PS_MIN_MODEM); // default 60 | } 61 | 62 | void initBWifi(bool resetWifi){ 63 | 64 | eeprom_read(); 65 | 66 | WiFiManagerParameter custom_mqtt_server("server", "MQTT Server Address", mqtt_server, 40); 67 | WiFiManagerParameter custom_mqtt_port("port", "MQTT Server Port", mqtt_port, 6); 68 | WiFiManagerParameter custom_mqtt_username("username", "MQTT Username", "", 40); 69 | WiFiManagerParameter custom_mqtt_password("password", "MQTT Password", "", 40, "type=password"); 70 | WiFiManagerParameter custom_ota_username("ota_username", "OTA Username", "", 40); 71 | WiFiManagerParameter custom_ota_password("ota_password", "OTA Password", "", 40, "type=password"); 72 | WiFiManagerParameter custom_bluetti_device("bluetti", "Bluetti Bluetooth ID", bluetti_device_id, 40); 73 | 74 | WiFiManager wifiManager; 75 | 76 | if (resetWifi){ 77 | wifiManager.resetSettings(); 78 | ESPBluettiSettings defaults; 79 | wifiConfig = defaults; 80 | eeprom_saveconfig(); 81 | } else if (wifiConfig.salt != EEPROM_SALT) { 82 | Serial.println("Invalid settings in EEPROM, trying with defaults"); 83 | ESPBluettiSettings defaults; 84 | wifiConfig = defaults; 85 | } else { 86 | wifiManager.setConfigPortalTimeout(300); 87 | } 88 | 89 | wifiManager.setSaveConfigCallback(saveConfigCallback); 90 | 91 | wifiManager.addParameter(&custom_mqtt_server); 92 | wifiManager.addParameter(&custom_mqtt_port); 93 | wifiManager.addParameter(&custom_mqtt_username); 94 | wifiManager.addParameter(&custom_mqtt_password); 95 | wifiManager.addParameter(&custom_ota_username); 96 | wifiManager.addParameter(&custom_ota_password); 97 | wifiManager.addParameter(&custom_bluetti_device); 98 | 99 | wifiManager.setAPCallback([&](WiFiManager* wifiManager) { 100 | Serial.printf("Entered config mode:ip=%s, ssid='%s'\n", 101 | WiFi.softAPIP().toString().c_str(), 102 | wifiManager->getConfigPortalSSID().c_str()); 103 | #ifdef DISPLAYSSD1306 104 | wrDisp_wifisignal(2); //AP mode 105 | wrDisp_IP(WiFi.softAPIP().toString().c_str()); 106 | wrDisp_Status("Setup Wifi"); 107 | #endif 108 | }); 109 | 110 | if (!wifiManager.autoConnect("Bluetti_ESP32")) { 111 | ESP.restart(); 112 | } 113 | 114 | if (shouldSaveConfig) { 115 | strlcpy(wifiConfig.mqtt_server, custom_mqtt_server.getValue(), 40); 116 | strlcpy(wifiConfig.mqtt_port, custom_mqtt_port.getValue(), 6); 117 | strlcpy(wifiConfig.mqtt_username, custom_mqtt_username.getValue(), 40); 118 | strlcpy(wifiConfig.mqtt_password, custom_mqtt_password.getValue(), 40); 119 | strlcpy(wifiConfig.ota_username, custom_ota_username.getValue(), 40); 120 | strlcpy(wifiConfig.ota_password, custom_ota_password.getValue(), 40); 121 | strlcpy(wifiConfig.bluetti_device_id, custom_bluetti_device.getValue(), 40); 122 | eeprom_saveconfig(); 123 | } 124 | 125 | // Wait for connection 126 | while (WiFi.status() != WL_CONNECTED) { 127 | // display will have blinking wifi signal until connected. 128 | #ifdef DISPLAYSSD1306 129 | disp_setPrevStateIcon(0); 130 | wrDisp_wifisignal(0); 131 | delay(200); 132 | Serial.print("."); 133 | disp_setPrevStateIcon(1); 134 | wrDisp_wifisignal(0); 135 | #else 136 | delay(500); 137 | Serial.print("."); 138 | #endif 139 | 140 | } 141 | 142 | WiFi.setAutoReconnect(true); 143 | 144 | Serial.println(F("")); 145 | Serial.println(F("IP address: ")); 146 | Serial.println(WiFi.localIP()); 147 | #ifdef DISPLAYSSD1306 148 | wrDisp_IP(WiFi.localIP().toString().c_str()); 149 | disp_setWifiSignal(1, WiFi.RSSI()); 150 | #endif 151 | if (MDNS.begin(DEVICE_NAME)) { 152 | Serial.println(F("MDNS responder started")); 153 | } 154 | 155 | //setup web server handling 156 | #if MSG_VIEWER_DETAILS 157 | msgViewerDetails = true; 158 | Serial.println(F("webserver BT/MQTT variable logging enabled...")); 159 | #else 160 | msgViewerDetails = false; 161 | Serial.println(F("webserver BT/MQTT variable logging disabled...")); 162 | #endif 163 | 164 | server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ 165 | request->send_P(200, "text/html", index_html, processorWebsiteUpdates); 166 | }); 167 | server.on("/switchLogging", HTTP_GET, [](AsyncWebServerRequest *request){ 168 | msgViewerDetails = !msgViewerDetails; 169 | if(msgViewerDetails){ 170 | Serial.println(F("webserver BT/MQTT variable logging enabled...")); 171 | } 172 | else{ 173 | Serial.println(F("webserver BT/MQTT variable logging disabled...")); 174 | } 175 | request->send_P(200, "text/html", index_html, processorWebsiteUpdates); 176 | }); 177 | server.on("/rebootDevice", [](AsyncWebServerRequest *request) { 178 | request->send(200, "text/plain", "reboot in 2sec"); 179 | delay(2000); 180 | ESP.restart(); 181 | }); 182 | server.on("/resetConfig", [](AsyncWebServerRequest *request) { 183 | request->send(200, "text/plain", "reset Wifi and reboot in 2sec"); 184 | delay(2000); 185 | initBWifi(true); 186 | }); 187 | //setup web server events 188 | events.onConnect([](AsyncEventSourceClient *client){ 189 | if(client->lastId()){ 190 | Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId()); 191 | } 192 | client->send("hello my friend, I'm just your data feed!", NULL, millis(), 10000); 193 | }); 194 | server.addHandler(&events); 195 | 196 | if (!wifiConfig.ota_username) { 197 | ElegantOTA.begin(&server); 198 | } else { 199 | ElegantOTA.begin(&server, wifiConfig.ota_username, wifiConfig.ota_password); 200 | } 201 | 202 | server.begin(); 203 | Serial.println(F("HTTP server started")); 204 | 205 | } 206 | 207 | void handleWebserver() { 208 | 209 | //Serial.println(F("DEBUG handleWebserver")); 210 | if ((millis() - lastTimeWebUpdate) > MSG_VIEWER_REFRESH_CYCLE*1000) { 211 | 212 | // check wifi status every MSG_VIEWER_REFRESH_CYCLE and set display 213 | if (WiFi.status() != WL_CONNECTED) { 214 | Serial.println(F("WiFi is disconnected, try to reconnect...")); 215 | #ifdef DISPLAYSSD1306 216 | disp_setWifiMode(0); 217 | disp_setStatus("Wifi err.."); 218 | #endif 219 | WiFi.disconnect(); 220 | WiFi.reconnect(); 221 | AddtoMsgView(String(millis()) + ": WLAN ERROR! try to reconnect"); 222 | wifiReconnectCounter++; 223 | //delay(1000); no delay as we only check every 5 seconds. Removing 1 second blocking of the program in the loop. 224 | } else { 225 | #ifdef DISPLAYSSD1306 226 | disp_setWifiSignal(1,WiFi.RSSI()); 227 | if (wifiReconnectCounter > 0) 228 | { 229 | //only update display ones after wifi is recovered. 230 | disp_setStatus("Running!"); 231 | wifiReconnectCounter = 0; 232 | } 233 | #endif 234 | } 235 | 236 | #ifdef DISPLAYSSD1306 237 | // update display 238 | disp_setBlueTooth(isBTconnected()); 239 | disp_setMqttStatus(isMQTTconnected()); 240 | #endif 241 | 242 | // Send Events to the Web Server with current data 243 | events.send("ping",NULL,millis()); 244 | events.send(String(millis()).c_str(),"runtime",millis()); 245 | events.send(String(WiFi.RSSI()).c_str(),"rssi",millis()); 246 | events.send(String(isMQTTconnected()).c_str(),"mqtt_connected",millis()); 247 | events.send(String(getLastMQTTMessageTime()).c_str(),"mqtt_last_msg_time",millis()); 248 | events.send(String(isBTconnected()).c_str(),"bt_connected",millis()); 249 | events.send(String(getLastBTMessageTime()).c_str(),"bt_last_msg_time",millis()); 250 | if(msgViewerDetails){ 251 | events.send(lastMsg.c_str(),"last_msg",millis()); 252 | } 253 | 254 | lastTimeWebUpdate = millis(); 255 | } 256 | } 257 | 258 | 259 | String processorWebsiteUpdates(const String& var){ 260 | 261 | if(var == "IP"){ 262 | return String(WiFi.localIP().toString()); 263 | } 264 | else if(var == "RSSI"){ 265 | return String(WiFi.RSSI()); 266 | } 267 | else if(var == "SSID"){ 268 | return String(WiFi.SSID()); 269 | } 270 | else if(var == "MAC"){ 271 | return String(WiFi.macAddress()); 272 | } 273 | else if(var == "RUNTIME"){ 274 | return String(millis()); 275 | } 276 | else if(var == "MQTT_IP"){ 277 | char msg[40]; 278 | if (strlen(wifiConfig.mqtt_server) == 0){ 279 | strlcpy(msg, "No MQTT server configured", 40); 280 | }else{ 281 | strlcpy(msg, wifiConfig.mqtt_server, 40); 282 | } 283 | 284 | return msg; 285 | } 286 | else if(var == "MQTT_PORT"){ 287 | char msg[6]; 288 | strlcpy(msg, wifiConfig.mqtt_port, 6); 289 | return msg; 290 | } 291 | else if(var == "MQTT_CONNECTED"){ 292 | return String(isMQTTconnected()); 293 | } 294 | else if(var == "LAST_MQTT_MSG_TIME"){ 295 | return String(getLastMQTTMessageTime()); 296 | } 297 | else if(var == "DEVICE_ID"){ 298 | char msg[40]; 299 | strlcpy(msg, wifiConfig.bluetti_device_id, 40); 300 | return msg; 301 | } 302 | else if(var == "BT_CONNECTED"){ 303 | return String(isBTconnected()); 304 | } 305 | else if(var == "LAST_BT_MSG_TIME"){ 306 | return String(getLastBTMessageTime()); 307 | } 308 | else if(var == "BT_ERROR"){ 309 | return String(getPublishErrorCount()); 310 | } 311 | else if(var == "LAST_MSG"){ 312 | if (msgViewerDetails){ 313 | return String("...waiting for data..."); 314 | } 315 | else{ 316 | return String("...disabled..."); 317 | } 318 | } 319 | else //return something, else this if then else will crash in case calles without VAR set.... 320 | { 321 | return String(""); 322 | } 323 | } 324 | 325 | void AddtoMsgView(String data){ 326 | 327 | String tempMsg = ""; 328 | 329 | int firstPos = lastMsg.indexOf("

"); 330 | int nextPos = firstPos; 331 | int numEntry = 0; 332 | while(nextPos > 0){ 333 | nextPos = lastMsg.indexOf("

",nextPos+4); 334 | if (nextPos > 0){ 335 | numEntry++; 336 | } 337 | } 338 | 339 | if (numEntry > MSG_VIEWER_ENTRY_COUNT-2){ 340 | tempMsg = lastMsg.substring(firstPos+4); 341 | lastMsg = tempMsg + "

" + data + "

"; 342 | } 343 | else{ 344 | lastMsg = lastMsg + "

" + data + "

"; 345 | } 346 | } 347 | -------------------------------------------------------------------------------- /Bluetti_ESP32/MQTT.cpp: -------------------------------------------------------------------------------- 1 | #include "BluettiConfig.h" 2 | #include "MQTT.h" 3 | #include "BWifi.h" 4 | #include "BTooth.h" 5 | #include "utils.h" 6 | #include "display.h" 7 | #include "config.h" 8 | 9 | #include 10 | #include 11 | 12 | WiFiClient mqttClient; 13 | PubSubClient client(mqttClient); 14 | int publishErrorCount = 0; 15 | unsigned long lastMQTTMessage = 0; 16 | unsigned long previousDeviceStatePublish = 0; 17 | unsigned long previousDeviceStateStatusPublish = 0; 18 | unsigned long previousMqttReconnect = 0; 19 | 20 | String map_field_name(enum field_names f_name){ 21 | switch(f_name) { 22 | case DC_OUTPUT_POWER: 23 | return "dc_output_power"; 24 | break; 25 | case AC_OUTPUT_POWER: 26 | return "ac_output_power"; 27 | break; 28 | case DC_OUTPUT_ON: 29 | return "dc_output_on"; 30 | break; 31 | case AC_OUTPUT_ON: 32 | return "ac_output_on"; 33 | break; 34 | case AC_OUTPUT_MODE: 35 | return "ac_output_mode"; 36 | break; 37 | case POWER_GENERATION: 38 | return "power_generation"; 39 | break; 40 | case TOTAL_BATTERY_PERCENT: 41 | return "total_battery_percent"; 42 | break; 43 | case DC_INPUT_POWER: 44 | return "dc_input_power"; 45 | break; 46 | case AC_INPUT_POWER: 47 | return "ac_input_power"; 48 | break; 49 | case AC_INPUT_VOLTAGE: 50 | return "ac_input_voltage"; 51 | break; 52 | case AC_INPUT_FREQUENCY: 53 | return "ac_input_frequency"; 54 | break; 55 | case PACK_VOLTAGE: 56 | return "pack_voltage"; 57 | break; 58 | case INTERNAL_PACK_VOLTAGE: 59 | return "internal_pack_voltage"; 60 | break; 61 | case SERIAL_NUMBER: 62 | return "serial_number"; 63 | break; 64 | case ARM_VERSION: 65 | return "arm_version"; 66 | break; 67 | case DSP_VERSION: 68 | return "dsp_version"; 69 | break; 70 | case DEVICE_TYPE: 71 | return "device_type"; 72 | break; 73 | case UPS_MODE: 74 | return "ups_mode"; 75 | break; 76 | case AUTO_SLEEP_MODE: 77 | return "auto_sleep_mode"; 78 | break; 79 | case GRID_CHARGE_ON: 80 | return "grid_charge_on"; 81 | break; 82 | case INTERNAL_AC_VOLTAGE: 83 | return "internal_ac_voltage"; 84 | break; 85 | case INTERNAL_AC_FREQUENCY: 86 | return "internal_ac_frequency"; 87 | break; 88 | case INTERNAL_CURRENT_ONE: 89 | return "internal_current_one"; 90 | break; 91 | case INTERNAL_POWER_ONE: 92 | return "internal_power_one"; 93 | break; 94 | case INTERNAL_CURRENT_TWO: 95 | return "internal_current_two"; 96 | break; 97 | case INTERNAL_POWER_TWO: 98 | return "internal_power_two"; 99 | break; 100 | case INTERNAL_CURRENT_THREE: 101 | return "internal_current_three"; 102 | break; 103 | case INTERNAL_POWER_THREE: 104 | return "internal_power_three"; 105 | break; 106 | case PACK_NUM_MAX: 107 | return "pack_max_num"; 108 | break; 109 | case PACK_NUM: 110 | return "pack_num"; 111 | break; 112 | case PACK_BATTERY_PERCENT: 113 | return "pack_battery_percent"; 114 | break; 115 | case INTERNAL_DC_INPUT_VOLTAGE: 116 | return "internal_dc_input_voltage"; 117 | break; 118 | case INTERNAL_DC_INPUT_POWER: 119 | return "internal_dc_input_power"; 120 | break; 121 | case INTERNAL_DC_INPUT_CURRENT: 122 | return "internal_dc_input_current"; 123 | break; 124 | case INTERNAL_CELL01_VOLTAGE: 125 | return "internal_cell01_voltage"; 126 | break; 127 | case INTERNAL_CELL02_VOLTAGE: 128 | return "internal_cell02_voltage"; 129 | break; 130 | case INTERNAL_CELL03_VOLTAGE: 131 | return "internal_cell03_voltage"; 132 | break; 133 | case INTERNAL_CELL04_VOLTAGE: 134 | return "internal_cell04_voltage"; 135 | break; 136 | case INTERNAL_CELL05_VOLTAGE: 137 | return "internal_cell05_voltage"; 138 | break; 139 | case INTERNAL_CELL06_VOLTAGE: 140 | return "internal_cell06_voltage"; 141 | break; 142 | case INTERNAL_CELL07_VOLTAGE: 143 | return "internal_cell07_voltage"; 144 | break; 145 | case INTERNAL_CELL08_VOLTAGE: 146 | return "internal_cell08_voltage"; 147 | break; 148 | case INTERNAL_CELL09_VOLTAGE: 149 | return "internal_cell09_voltage"; 150 | break; 151 | case INTERNAL_CELL10_VOLTAGE: 152 | return "internal_cell10_voltage"; 153 | break; 154 | case INTERNAL_CELL11_VOLTAGE: 155 | return "internal_cell11_voltage"; 156 | break; 157 | case INTERNAL_CELL12_VOLTAGE: 158 | return "internal_cell12_voltage"; 159 | break; 160 | case INTERNAL_CELL13_VOLTAGE: 161 | return "internal_cell13_voltage"; 162 | break; 163 | case INTERNAL_CELL14_VOLTAGE: 164 | return "internal_cell14_voltage"; 165 | break; 166 | case INTERNAL_CELL15_VOLTAGE: 167 | return "internal_cell15_voltage"; 168 | break; 169 | case INTERNAL_CELL16_VOLTAGE: 170 | return "internal_cell16_voltage"; 171 | break; 172 | case LED_MODE: 173 | return "led_mode"; 174 | break; 175 | case POWER_OFF: 176 | return "power_off"; 177 | break; 178 | case ECO_ON: 179 | return "eco_on"; 180 | break; 181 | case ECO_SHUTDOWN: 182 | return "eco_shutdown"; 183 | break; 184 | case CHARGING_MODE: 185 | return "charging_mode"; 186 | break; 187 | case POWER_LIFTING_ON: 188 | return "power_lifting_on"; 189 | break; 190 | case AC_INPUT_POWER_MAX: 191 | return "ac_input_power_max"; 192 | break; 193 | case AC_INPUT_CURRENT_MAX: 194 | return "ac_input_current_max"; 195 | break; 196 | case AC_OUTPUT_POWER_MAX: 197 | return "ac_output_power_max"; 198 | break; 199 | case AC_OUTPUT_CURRENT_MAX: 200 | return "ac_output_current_max"; 201 | break; 202 | case BATTERY_MIN_PERCENTAGE: 203 | return "battery_min_percentage"; 204 | break; 205 | case AC_CHARGE_MAX_PERCENTAGE: 206 | return "ac_charge_max_percentage"; 207 | break; 208 | default: 209 | #ifdef DEBUG 210 | Serial.println(F("Info 'map_field_name' found unknown field!")); 211 | #endif 212 | return "unknown"; 213 | break; 214 | } 215 | 216 | } 217 | 218 | //There is no reflection to do string to enum 219 | //There are a couple of ways to work aroung it... but basically are just "case" statements 220 | //Wapped them in a fuction 221 | String map_command_value(String command_name, String value){ 222 | String toRet = value; 223 | value.toUpperCase(); 224 | command_name.toUpperCase(); //force case indipendence 225 | 226 | //on / off commands 227 | if(command_name == "POWER_OFF" || command_name == "AC_OUTPUT_ON" || command_name == "DC_OUTPUT_ON" || command_name == "ECO_ON" || command_name == "POWER_LIFTING_ON") { 228 | if (value == "ON") { 229 | toRet = "1"; 230 | } 231 | if (value == "OFF") { 232 | toRet = "0"; 233 | } 234 | } 235 | 236 | //See DEVICE_EB3A enums 237 | if(command_name == "LED_MODE"){ 238 | if (value == "LED_LOW") { 239 | toRet = "1"; 240 | } 241 | if (value == "LED_HIGH") { 242 | toRet = "2"; 243 | } 244 | if (value == "LED_SOS") { 245 | toRet = "3"; 246 | } 247 | if (value == "LED_OFF") { 248 | toRet = "4"; 249 | } 250 | } 251 | 252 | //See DEVICE_EB3A enums 253 | if(command_name == "ECO_SHUTDOWN"){ 254 | if (value == "ONE_HOUR") { 255 | toRet = "1"; 256 | } 257 | if (value == "TWO_HOURS") { 258 | toRet = "2"; 259 | } 260 | if (value == "THREE_HOURS") { 261 | toRet = "3"; 262 | } 263 | if (value == "FOUR_HOURS") { 264 | toRet = "4"; 265 | } 266 | } 267 | 268 | //See DEVICE_EB3A enums 269 | if(command_name == "CHARGING_MODE"){ 270 | if (value == "STANDARD") { 271 | toRet = "0"; 272 | } 273 | if (value == "SILENT") { 274 | toRet = "1"; 275 | } 276 | if (value == "TURBO") { 277 | toRet = "2"; 278 | } 279 | } 280 | 281 | 282 | return toRet; 283 | } 284 | 285 | // Callback function 286 | void callback(char* topic, byte* payload, unsigned int length) { 287 | payload[length] = '\0'; 288 | String topic_path = String(topic); 289 | topic_path.toLowerCase();//in case we recieve DC_OUTPUT_ON instead of the expected dc_output_on 290 | 291 | Serial.print("MQTT Message arrived on topic: "); 292 | Serial.print(topic); 293 | Serial.print(" Payload: "); 294 | String strPayload = String((char * ) payload); 295 | Serial.println(strPayload); 296 | 297 | bt_command_t command; 298 | command.prefix = 0x01; 299 | command.field_update_cmd = 0x06; 300 | 301 | for (int i=0; i< sizeof(bluetti_device_command)/sizeof(device_field_data_t); i++){ 302 | if (topic_path.indexOf(map_field_name(bluetti_device_command[i].f_name)) > -1){ 303 | command.page = bluetti_device_command[i].f_page; 304 | command.offset = bluetti_device_command[i].f_offset; 305 | 306 | String current_name = map_field_name(bluetti_device_command[i].f_name); 307 | strPayload = map_command_value(current_name,strPayload); 308 | } 309 | } 310 | Serial.print(" Payload - switched: "); 311 | Serial.println(strPayload); 312 | 313 | command.len = swap_bytes(strPayload.toInt()); 314 | command.check_sum = modbus_crc((uint8_t*)&command,6); 315 | lastMQTTMessage = millis(); 316 | 317 | sendBTCommand(command); 318 | } 319 | 320 | void subscribeTopic(enum field_names field_name) { 321 | #ifdef DEBUG 322 | Serial.println("[MQTT] subscribe to topic: " + map_field_name(field_name)); 323 | #endif 324 | char subscribeTopicBuf[512]; 325 | ESPBluettiSettings settings = get_esp32_bluetti_settings(); 326 | 327 | sprintf(subscribeTopicBuf, "bluetti/%s/command/%s", settings.bluetti_device_id, map_field_name(field_name).c_str() ); 328 | client.subscribe(subscribeTopicBuf); 329 | lastMQTTMessage = millis(); 330 | 331 | } 332 | 333 | void publishTopic(enum field_names field_name, String value){ 334 | char publishTopicBuf[1024]; 335 | ESPBluettiSettings settings = get_esp32_bluetti_settings(); 336 | 337 | #ifdef DEBUG 338 | Serial.println("[MQTT] publish topic for field: " + map_field_name(field_name)); 339 | #endif 340 | 341 | //sometimes we get empty values / wrong vales - all the time device_type is empty 342 | if (map_field_name(field_name) == "device_type" && value.length() < 3){ 343 | 344 | //Serial.println(F("[MQTT] Error while publishTopic! 'device_type' can't be empty, reboot device)")); 345 | ESP.restart(); 346 | Serial.println(F("[MQTT] Error while publishTopic! 'device_type' can't be empty, restarting BlueTooth Stack)")); 347 | // btResetStack(); 348 | 349 | } 350 | 351 | sprintf(publishTopicBuf, "bluetti/%s/state/%s", settings.bluetti_device_id, map_field_name(field_name).c_str() ); 352 | if (strlen(settings.mqtt_server) == 0){ 353 | AddtoMsgView(String(millis()) +": " + map_field_name(field_name) + " -> " + value); 354 | #ifdef DEBUG 355 | Serial.println("[MQTT] No MQTT server specified!"); 356 | #endif 357 | }else{ 358 | lastMQTTMessage = millis(); 359 | if (!client.publish(publishTopicBuf, value.c_str() )){ 360 | publishErrorCount++; 361 | #ifdef DEBUG 362 | Serial.println("[MQTT] Publish error: " + String(lastMQTTMessage) + ": publish ERROR! " + map_field_name(field_name) + " -> " + value); 363 | #endif 364 | AddtoMsgView(String(lastMQTTMessage) + ": publish ERROR! " + map_field_name(field_name) + " -> " + value); 365 | } 366 | else{ 367 | #ifdef DEBUG 368 | Serial.println("[MQTT] Last Message: " + String(lastMQTTMessage) + ": " + map_field_name(field_name) + " -> " + value); 369 | #endif 370 | AddtoMsgView(String(lastMQTTMessage) + ": " + map_field_name(field_name) + " -> " + value); 371 | } 372 | } 373 | 374 | 375 | } 376 | 377 | void publishDeviceState(){ 378 | char publishTopicBuf[1024]; 379 | 380 | ESPBluettiSettings settings = get_esp32_bluetti_settings(); 381 | sprintf(publishTopicBuf, "bluetti/%s/state/%s", settings.bluetti_device_id, "device" ); 382 | String value = "{\"IP\":\"" + WiFi.localIP().toString() + "\", \"MAC\":\"" + WiFi.macAddress() + "\", \"Uptime\":" + millis() + "}"; 383 | #ifdef DEBUG 384 | Serial.println("[MQTT] PublishingDeviceState: "+value); 385 | #endif 386 | if (!client.publish(publishTopicBuf, value.c_str() )){ 387 | publishErrorCount++; 388 | } 389 | lastMQTTMessage = millis(); 390 | previousDeviceStatePublish = millis(); 391 | 392 | } 393 | 394 | void publishDeviceStateStatus(){ 395 | char publishTopicBuf[1024]; 396 | 397 | ESPBluettiSettings settings = get_esp32_bluetti_settings(); 398 | sprintf(publishTopicBuf, "bluetti/%s/state/%s", settings.bluetti_device_id, "device_status" ); 399 | String value = "{\"MQTTconnected\":" + String(isMQTTconnected()) + ", \"BTconnected\":" + String(isBTconnected()) + "}"; 400 | #ifdef DEBUG 401 | Serial.println("[MQTT] PublishingDeviceStateStatus: "+value); 402 | #endif 403 | if (!client.publish(publishTopicBuf, value.c_str() )){ 404 | publishErrorCount++; 405 | } 406 | lastMQTTMessage = millis(); 407 | previousDeviceStateStatusPublish = millis(); 408 | 409 | } 410 | 411 | void initMQTT(){ 412 | 413 | enum field_names f_name; 414 | ESPBluettiSettings settings = get_esp32_bluetti_settings(); 415 | Serial.println("[MQTT] init MQTT"); 416 | if (strlen(settings.mqtt_server) == 0){ 417 | Serial.println("[MQTT] No MQTT server configured"); 418 | return; 419 | } 420 | Serial.print("[MQTT] Connecting to MQTT at: "); 421 | Serial.print(settings.mqtt_server); 422 | Serial.print(":"); 423 | Serial.println(F(settings.mqtt_port)); 424 | 425 | client.setServer(settings.mqtt_server, atoi(settings.mqtt_port)); 426 | client.setCallback(callback); 427 | 428 | bool connect_result; 429 | const char connect_id[] = "Bluetti_ESP32"; 430 | if (settings.mqtt_username) { 431 | connect_result = client.connect(connect_id, settings.mqtt_username, settings.mqtt_password); 432 | } else { 433 | connect_result = client.connect(connect_id); 434 | } 435 | 436 | if (connect_result) { 437 | 438 | Serial.println(F("[MQTT] Connected to MQTT Server... ")); 439 | 440 | // subscribe to topics for commands 441 | for (int i=0; i< sizeof(bluetti_device_command)/sizeof(device_field_data_t); i++){ 442 | subscribeTopic(bluetti_device_command[i].f_name); 443 | } 444 | 445 | publishDeviceState(); 446 | publishDeviceStateStatus(); 447 | } 448 | 449 | 450 | 451 | }; 452 | 453 | void handleMQTT(){ 454 | ESPBluettiSettings settings = get_esp32_bluetti_settings(); 455 | if (strlen(settings.mqtt_server) == 0){ 456 | return; 457 | } 458 | if ((millis() - lastMQTTMessage) > (MAX_DISCONNECTED_TIME_UNTIL_REBOOT * 60000)){ 459 | Serial.println(F("MQTT is disconnected over allowed limit, reboot device")); 460 | ESP.restart(); 461 | } 462 | 463 | if ((millis() - previousDeviceStatePublish) > (DEVICE_STATE_UPDATE * 60000)){ 464 | publishDeviceState(); 465 | } 466 | if ((millis() - previousDeviceStateStatusPublish) > (DEVICE_STATE_STATUS_UPDATE * 60000)){ 467 | publishDeviceStateStatus(); 468 | } 469 | if (!isMQTTconnected() && publishErrorCount > 5){ 470 | if ((millis() - previousMqttReconnect) > 5000) 471 | { 472 | previousMqttReconnect = millis(); 473 | Serial.println(F("[MQTT] lost connection, try to reconnect")); 474 | #ifdef DISPLAYSSD1306 475 | disp_setMqttStatus(false); 476 | #endif 477 | client.disconnect(); 478 | lastMQTTMessage=0; 479 | previousDeviceStatePublish=0; 480 | previousDeviceStateStatusPublish=0; 481 | publishErrorCount=0; 482 | AddtoMsgView(String(millis()) + ": MQTT connection lost, try reconnect"); 483 | initMQTT(); 484 | } 485 | } 486 | 487 | client.loop(); 488 | } 489 | 490 | bool isMQTTconnected(){ 491 | if (client.connected()){ 492 | return true; 493 | } 494 | else 495 | { 496 | return false; 497 | } 498 | } 499 | 500 | int getPublishErrorCount(){ 501 | return publishErrorCount; 502 | } 503 | unsigned long getLastMQTTMessageTime(){ 504 | return lastMQTTMessage; 505 | } 506 | unsigned long getLastMQTTDeviceStateMessageTime(){ 507 | return previousDeviceStatePublish; 508 | } 509 | unsigned long getLastMQTTDeviceStateStatusMessageTime(){ 510 | return previousDeviceStateStatusPublish; 511 | } 512 | -------------------------------------------------------------------------------- /Bluetti_ESP32/display.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "display.h" 6 | #include "config.h" 7 | 8 | // used for millis loops 9 | const unsigned long flProgressBar = 200; // speed of update progressbar 10 | const unsigned long flWifiBTStarting = 500; //flash speed Of wifi & BT icon on starting 11 | const unsigned long flWifiSignal = 5000; //frequency updating wifi signal strength icon 12 | unsigned long prevTimerProgressBar = 0; 13 | unsigned long prevTimerWifiStarting = 0; 14 | unsigned long prevTimerBtStarting = 0; 15 | unsigned long prevTimerDebugger = 0; 16 | unsigned long prevTimerBtRunning = 0; 17 | unsigned long prevTimerRuntime = 0; 18 | unsigned long prevTimerWifiSignal = 0; 19 | unsigned long prevTimerMQStarting = 0; 20 | unsigned long prevTimerMQRunning = 0; 21 | 22 | // Used variables 23 | int progress = 0; 24 | bool btConnected = false; 25 | bool mqConnected = false; 26 | byte byteWifiMode; 27 | int intWifiSignal; 28 | byte year = 0; 29 | byte hours = 0; 30 | byte minutes = 0; 31 | byte days = 0; 32 | bool enableProgressbar=false; 33 | String strdispIP = "NoConf"; 34 | String strdispStatus="boot.."; 35 | byte prevStateIcons = 0; 36 | byte prevBTStateIcons = 0; 37 | byte prevMQStateIcon = 0; 38 | 39 | 40 | #define SCREEN_WIDTH 128 41 | #define SCREEN_HEIGHT 64 42 | Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1); 43 | 44 | void initDisplay() 45 | { 46 | #if DISPLAY_RST_PORT 47 | // Reset required for some displays like LoRa TTGO v1.0 48 | pinMode(DISPLAY_RST_PORT, OUTPUT); 49 | digitalWrite(DISPLAY_RST_PORT, HIGH); 50 | delay(20); 51 | digitalWrite(DISPLAY_RST_PORT, LOW); 52 | delay(20); 53 | digitalWrite(DISPLAY_RST_PORT, HIGH); 54 | delay(20); 55 | #endif 56 | Wire.begin(DISPLAY_SDA_PORT, DISPLAY_SCL_PORT); 57 | if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C, false, false)) 58 | { 59 | Serial.println(F("display: SSD1306 allocation failed")); 60 | for (;;) 61 | ; 62 | } 63 | display.clearDisplay(); 64 | display.setTextSize(1); // Draw 2X-scale text 65 | display.setTextColor(BLACK,WHITE); 66 | display.setCursor(1, 1); 67 | display.drawRect(0,0,73,10,WHITE); 68 | display.println("BlueTTI Wifi"); 69 | wrDisp_IP(); 70 | wrDisp_Running(); 71 | wrDisp_Status("Init...."); 72 | btConnected = false; 73 | mqConnected = false; 74 | byteWifiMode = 0; 75 | } 76 | void handleDisplay() 77 | { 78 | // progress bar 79 | if (enableProgressbar == true) 80 | { 81 | if (millis() - prevTimerProgressBar >= flProgressBar) 82 | { 83 | progress = (progress + 5) % 110; 84 | drawProgressbar(10, 59, 108, 5, progress); 85 | prevTimerProgressBar = millis(); 86 | } 87 | } 88 | // update running time every 30 seconds 89 | if (millis() - prevTimerRuntime >= 30000) 90 | { 91 | wrDisp_Running(); 92 | prevTimerRuntime = millis(); 93 | } 94 | // debugging 95 | #ifdef DEBUGDISP 96 | if (millis() - prevTimerDebugger >= 5000) 97 | { 98 | prevTimerDebugger = millis(); 99 | 100 | Serial.println("[DISP] BlueTooth status: "+String(btConnected)); 101 | Serial.println("[DISP] WifiStatus status: "+String(byteWifiMode)); 102 | Serial.println("[DISP] MQ status: "+String(mqConnected)); 103 | Serial.println("FreeHeap: "+String(ESP.getFreeHeap())); 104 | } 105 | #endif 106 | // blue not connected is blinking 107 | if (btConnected == false) 108 | { 109 | if (millis() - prevTimerBtStarting >= flWifiBTStarting) 110 | { 111 | prevTimerBtStarting = millis(); 112 | if (prevBTStateIcons == 0) 113 | { 114 | // Flash background white 115 | prevBTStateIcons = 1; 116 | wrDisp_blueToothSignal(btConnected); 117 | } 118 | else 119 | { 120 | // flash background Black 121 | prevBTStateIcons = 0; 122 | wrDisp_blueToothSignal(btConnected); 123 | } 124 | } 125 | } 126 | else 127 | { 128 | //static bluetooth 129 | // updata only 1 time per 5 sec 130 | if (millis() - prevTimerBtRunning >= 5000) 131 | { 132 | prevTimerBtRunning = millis(); 133 | wrDisp_blueToothSignal(btConnected); 134 | } 135 | } 136 | if (mqConnected == false) 137 | { 138 | if (millis() - prevTimerMQStarting >= flWifiBTStarting) 139 | { 140 | prevTimerMQStarting = millis(); 141 | if (prevMQStateIcon == 0) 142 | { 143 | // Flash background white 144 | prevMQStateIcon = 1; 145 | wrDisp_mqttConnected(mqConnected); 146 | } 147 | else 148 | { 149 | // flash background Black 150 | prevMQStateIcon = 0; 151 | wrDisp_mqttConnected(mqConnected); 152 | } 153 | 154 | } 155 | } 156 | else 157 | { 158 | if (millis() - prevTimerMQRunning >= 5000) 159 | { 160 | prevTimerMQRunning = millis(); 161 | wrDisp_mqttConnected(mqConnected); 162 | } 163 | 164 | } 165 | if (byteWifiMode == 0) 166 | { 167 | if (millis() - prevTimerWifiStarting >= flWifiBTStarting) 168 | { 169 | prevTimerWifiStarting = millis(); 170 | if (prevStateIcons == 0) 171 | { 172 | // Flash background white 173 | prevStateIcons = 1; 174 | wrDisp_wifisignal(0); 175 | } 176 | else 177 | { 178 | // flash background Black 179 | prevStateIcons = 0; 180 | wrDisp_wifisignal(0); 181 | } 182 | 183 | } 184 | } else 185 | { 186 | if (millis() - prevTimerWifiSignal >= flWifiSignal) 187 | { 188 | prevTimerWifiSignal = millis(); 189 | #ifdef DEBUGDISP 190 | Serial.println("[DISP] Wifi connected"); 191 | #endif 192 | wrDisp_wifisignal(byteWifiMode, intWifiSignal); 193 | 194 | } 195 | } 196 | 197 | } 198 | void wrDisp_IP(String strIP) 199 | { 200 | display.fillRect(0,14,114,8,0); 201 | display.setTextColor(WHITE,BLACK); 202 | display.setCursor(0, 14); 203 | display.println("IP:"+ strIP); 204 | display.display(); 205 | } 206 | void wrDisp_Running() 207 | { 208 | display.fillRect(0,22,114,8,0); 209 | display.setTextColor(WHITE,BLACK); 210 | display.setCursor(0, 22); 211 | // important: millis resets after 49days - currently not taken into account in the calculations 212 | // example output: 365d23h60m 213 | 214 | if (((millis()/1000) > 60) && (millis()/1000 <3600)) 215 | { 216 | 217 | minutes = ((int)((millis()/1000)/60)); 218 | } else if ((millis()/1000 > 3600) && (millis()/1000 <86400)) 219 | { 220 | 221 | hours = ((int)(millis()/1000)/3600); 222 | minutes = ((int)(((millis()/1000)-(hours*3600))/60)); 223 | } else if ((millis()/1000 > 86400)) 224 | { 225 | days = ((int)(millis()/1000)/86400); 226 | hours = ((int)(((millis()/1000)/3600)-((days*24)))); 227 | minutes = ((int)(((millis()/1000)-(hours*3600))/60)); 228 | } 229 | display.println("Runtime: "+ String(days)+"d"+String(hours)+"h"+String(minutes)+"m"); //running time will be max 49days until millis is reset 230 | display.display(); 231 | } 232 | void wrDisp_Status(String strStatus) 233 | { 234 | display.fillRect(0,30,114,8,0); 235 | display.setTextColor(WHITE,BLACK); 236 | display.setCursor(0, 30); 237 | display.println("Status:" + strStatus); 238 | display.display(); 239 | } 240 | void wrDisp_mqttConnected(bool blMqttConnected) 241 | { 242 | display.fillRect(115, 136, 13, 13, 0); 243 | display.display(); 244 | 245 | if(blMqttConnected) 246 | { 247 | display.setTextColor(1, 0); 248 | display.setCursor(116, 39); 249 | display.print("MQ"); 250 | display.display(); 251 | } 252 | else 253 | { 254 | if (prevMQStateIcon == 0) 255 | { 256 | display.fillRect(115, 36, 13, 13, 0); 257 | display.setTextColor(1, 0); 258 | display.setCursor(116, 39); 259 | display.print("MQ"); 260 | }else 261 | { 262 | display.fillRect(115, 36, 13, 13, 0); 263 | } 264 | display.display(); 265 | } 266 | } 267 | void wrDisp_blueToothSignal(bool blConnected) 268 | { 269 | display.fillRect(115, 18, 13, 13, 0); 270 | display.display(); 271 | if (blConnected == true) 272 | { 273 | display.writePixel(118, 21, 1); 274 | display.writePixel(118, 27, 1); 275 | display.writePixel(119, 22, 1); 276 | display.writePixel(119, 26, 1); 277 | display.writePixel(120, 25, 1); 278 | display.writePixel(120, 23, 1); 279 | display.drawLine(121, 19, 121, 29, 1); 280 | display.writePixel(122, 19, 1); 281 | display.writePixel(122, 24, 1); 282 | display.writePixel(122, 29, 1); 283 | display.writePixel(123, 20, 1); 284 | display.writePixel(123, 23, 1); 285 | display.writePixel(123, 25, 1); 286 | display.writePixel(123, 28, 1); 287 | display.writePixel(124, 21, 1); 288 | display.writePixel(124, 22, 1); 289 | display.writePixel(124, 26, 1); 290 | display.writePixel(124, 27, 1); 291 | display.display(); 292 | } 293 | else 294 | { 295 | display.writePixel(118, 21, prevBTStateIcons); 296 | display.writePixel(118, 27, prevBTStateIcons); 297 | display.writePixel(119, 22, prevBTStateIcons); 298 | display.writePixel(119, 26, prevBTStateIcons); 299 | display.writePixel(120, 25, prevBTStateIcons); 300 | display.writePixel(120, 23, prevBTStateIcons); 301 | display.drawLine(121, 19, 121, 29, prevBTStateIcons); 302 | display.writePixel(122, 19, prevBTStateIcons); 303 | display.writePixel(122, 24, prevBTStateIcons); 304 | display.writePixel(122, 29, prevBTStateIcons); 305 | display.writePixel(123, 20, prevBTStateIcons); 306 | display.writePixel(123, 23, prevBTStateIcons); 307 | display.writePixel(123, 25, prevBTStateIcons); 308 | display.writePixel(123, 28, prevBTStateIcons); 309 | display.writePixel(124, 21, prevBTStateIcons); 310 | display.writePixel(124, 22, prevBTStateIcons); 311 | display.writePixel(124, 26, prevBTStateIcons); 312 | display.writePixel(124, 27, prevBTStateIcons); 313 | display.display(); 314 | } 315 | } 316 | void wrDisp_wifisignal_rewrite_static() 317 | { 318 | wrDisp_wifisignal(byteWifiMode,intWifiSignal); 319 | } 320 | void wrDisp_wifisignal(int intMode, int intSignal) 321 | { 322 | // intMode: 323 | // 0, not connected 324 | // 1, connected 325 | // 2, AP mode 326 | 327 | // -55 or higher: 4 bars 328 | // -56 to -66: 3 bars 329 | // -67 to -77: 2 bars 330 | // -78 to -88: 1 bar 331 | // -89 or lower: 0 bars -> not implemented 332 | display.fillRect(115, 0, 13, 13, 0); 333 | display.display(); 334 | byte textColor = 1; // 1 for White and 0 for black 335 | if (intMode == 1) 336 | { 337 | if (textColor == 0) 338 | { 339 | // Black on white 340 | display.fillRect(115, 0, 13, 13, 1); 341 | display.display(); 342 | } else 343 | { 344 | // White on black 345 | display.fillRect(115, 0, 13, 13, 0); 346 | //display.drawRect(115, 0, 13, 13, 1); 347 | display.display(); 348 | 349 | } 350 | if ((intSignal < -85)) 351 | { 352 | // extreme weak signal 1 bar 353 | display.writePixel(121, 11, textColor); 354 | } else if ((intSignal > -85) && (intSignal <= -67)) 355 | { 356 | // 2 bars 357 | 358 | // one bar 359 | display.writePixel(121, 11, textColor); 360 | // 2 bar 361 | display.writePixel(119, 9, textColor); 362 | display.writePixel(123, 9, textColor); 363 | display.writePixel(120, 8, textColor); 364 | display.writePixel(121, 8, textColor); 365 | display.writePixel(122, 8, textColor); 366 | } else if ((intSignal > -66) && (intSignal <= -56)) 367 | { 368 | // 3 bars 369 | 370 | // one bar 371 | display.writePixel(121, 11, textColor); 372 | // 2 bar 373 | display.writePixel(119, 9, textColor); 374 | display.writePixel(123, 9, textColor); 375 | display.writePixel(120, 8, textColor); 376 | display.writePixel(121, 8, textColor); 377 | display.writePixel(122, 8, textColor); 378 | // 3 bar 379 | display.writePixel(118, 6, textColor); 380 | display.writePixel(118, 6, textColor); 381 | display.writePixel(124, 6, textColor); 382 | display.writePixel(119, 5, textColor); 383 | display.writePixel(120, 5, textColor); 384 | display.writePixel(121, 5, textColor); 385 | display.writePixel(122, 5, textColor); 386 | display.writePixel(123, 5, textColor); 387 | } 388 | else if (intSignal > -55) 389 | { 390 | // 4 bars 391 | 392 | // one bar 393 | display.writePixel(121, 11, textColor); 394 | // 2 bar 395 | display.writePixel(119, 9, textColor); 396 | display.writePixel(123, 9, textColor); 397 | display.writePixel(120, 8, textColor); 398 | display.writePixel(121, 8, textColor); 399 | display.writePixel(122, 8, textColor); 400 | // 3 bar 401 | display.writePixel(118, 6, textColor); 402 | display.writePixel(118, 6, textColor); 403 | display.writePixel(124, 6, textColor); 404 | display.writePixel(119, 5, textColor); 405 | display.writePixel(120, 5, textColor); 406 | display.writePixel(121, 5, textColor); 407 | display.writePixel(122, 5, textColor); 408 | display.writePixel(123, 5, textColor); 409 | // 4 bar 410 | display.writePixel(116, 4, textColor); 411 | display.writePixel(126, 4, textColor); 412 | display.writePixel(117, 3, textColor); 413 | display.writePixel(125, 3, textColor); 414 | display.writePixel(118, 2, textColor); 415 | display.writePixel(119, 2, textColor); 416 | display.writePixel(120, 2, textColor); 417 | display.writePixel(121, 2, textColor); 418 | display.writePixel(122, 2, textColor); 419 | display.writePixel(123, 2, textColor); 420 | display.writePixel(124, 2, textColor); 421 | } 422 | display.display(); 423 | } 424 | else if (intMode == 0) 425 | { 426 | 427 | if (prevStateIcons == 0) 428 | { 429 | //display.fillRect(115, 0, 13, 13, 1); 430 | } 431 | else 432 | { 433 | //display.fillRect(115, 0, 13, 13, 0); 434 | } 435 | // one bar 436 | display.writePixel(121, 11, prevStateIcons); 437 | // 2 bar 438 | display.writePixel(119, 9, prevStateIcons); 439 | display.writePixel(123, 9, prevStateIcons); 440 | display.writePixel(120, 8, prevStateIcons); 441 | display.writePixel(121, 8, prevStateIcons); 442 | display.writePixel(122, 8, prevStateIcons); 443 | // 3 bar 444 | display.writePixel(118, 6, prevStateIcons); 445 | display.writePixel(118, 6, prevStateIcons); 446 | display.writePixel(124, 6, prevStateIcons); 447 | display.writePixel(119, 5, prevStateIcons); 448 | display.writePixel(120, 5, prevStateIcons); 449 | display.writePixel(121, 5, prevStateIcons); 450 | display.writePixel(122, 5, prevStateIcons); 451 | display.writePixel(123, 5, prevStateIcons); 452 | // 4 bar 453 | display.writePixel(116, 4, prevStateIcons); 454 | display.writePixel(126, 4, prevStateIcons); 455 | display.writePixel(117, 3, prevStateIcons); 456 | display.writePixel(125, 3, prevStateIcons); 457 | display.writePixel(118, 2, prevStateIcons); 458 | display.writePixel(119, 2, prevStateIcons); 459 | display.writePixel(120, 2, prevStateIcons); 460 | display.writePixel(121, 2, prevStateIcons); 461 | display.writePixel(122, 2, prevStateIcons); 462 | display.writePixel(123, 2, prevStateIcons); 463 | display.writePixel(124, 2, prevStateIcons); 464 | // not connected / trying to connect 465 | // wifi logo should blink, trying to make connection 466 | display.display(); 467 | } 468 | else if (intMode == 2) 469 | { 470 | // AP mode 471 | // wifi logo should contain AP as text 472 | display.fillRect(115, 0, 13, 13, 1); 473 | display.setTextColor(BLACK, WHITE); 474 | display.setCursor(116, 3); 475 | display.print("AP"); 476 | display.display(); 477 | } 478 | } 479 | void disp_setWifiSignal(int extWifMode, int extSignal) 480 | { 481 | intWifiSignal = extSignal; 482 | byteWifiMode = extWifMode; 483 | wrDisp_wifisignal(extWifMode,extSignal); 484 | } 485 | void disp_setWifiMode(byte wMode) 486 | { 487 | byteWifiMode = wMode; 488 | } 489 | void disp_setIP(String strIP) 490 | { 491 | if (strIP != strdispIP) 492 | { 493 | wrDisp_Status(strIP); 494 | strdispIP = strIP; 495 | } 496 | } 497 | void disp_setStatus(String strStatus) 498 | { 499 | if (strStatus != strdispStatus) 500 | { 501 | wrDisp_Status(strStatus); 502 | strdispStatus = strStatus; 503 | } 504 | } 505 | void disp_setBlueTooth(bool boolBtConn) 506 | { 507 | btConnected = boolBtConn; 508 | } 509 | void disp_setMqttStatus(bool blMqttconnected) 510 | { 511 | mqConnected = blMqttconnected; 512 | } 513 | void disp_setPrevStateIcon(byte bytePrevState) 514 | { 515 | prevStateIcons = bytePrevState; 516 | } 517 | void disp_setBTPrevStateIcon(byte bytePrevState) 518 | { 519 | prevBTStateIcons = bytePrevState; 520 | } 521 | void drawProgressbar(int x,int y, int width,int height, int progress) 522 | { 523 | 524 | // clear old data 525 | //display.drawRect(x, y, width, height, BLACK); 526 | display.fillRect(x, y, width , height, BLACK); 527 | display.display(); 528 | 529 | progress = progress > 100 ? 100 : progress; 530 | progress = progress < 0 ? 0 :progress; 531 | 532 | float bar = ((float)(width-1) / 100) * progress; 533 | 534 | //display.drawRect(x, y, width, height, WHITE); 535 | display.fillRect(x, y, bar , height, WHITE); 536 | display.display(); 537 | } 538 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------