simulator for Windows, WSL2 and Linux

This commit is contained in:
KlausMu 2024-03-10 19:27:46 +01:00
parent a4fb311c59
commit 153535b586
176 changed files with 7072 additions and 2535 deletions

View file

@ -0,0 +1,32 @@
#include <Arduino.h>
// uint8_t CRG_STAT_GPIO = 21; // battery charger feedback, GPIO21, VSPIHD, EMAC_TX_EN
uint8_t ADC_BAT_GPIO = 36; // Battery voltage sense input (1/2 divider), GPIO36, ADC1_CH0, RTC_GPIO0
void init_battery_HAL(void) {
// Currently the battery charge status cannot be recognized in a reliable way due to a design flaw in the PCB.
// See https://github.com/CoretechR/OMOTE/issues/55
// So charge status is deactivated for now.
//pinMode(CRG_STAT_GPIO, INPUT_PULLUP);
pinMode(ADC_BAT_GPIO, INPUT);
}
void get_battery_status_HAL(int *battery_voltage, int *battery_percentage) {
int battery_analogRead = 0;
battery_analogRead = analogRead(ADC_BAT_GPIO);
// original values
// battery_voltage = battery_analogRead*2*3300/4095 + 350; // 350mV ADC offset
// adjusted values due to new measurements
*battery_voltage = battery_analogRead*2*3350/4095 + 325;
*battery_percentage = constrain(map(*battery_voltage, 3700, 4200, 0, 100), 0, 100);
// Check if battery is charging, fully charged or disconnected
/*
"disconnected" cannot be recognized
https://electronics.stackexchange.com/questions/615215/level-shifting-of-a-3-state-pin
https://electrical.codidact.com/posts/286209
https://how2electronics.com/lithium-ion-battery-charger-circuit-using-mcp73831/
*/
//*battery_ischarging = !digitalRead(CRG_STAT_GPIO);
}

View file

@ -0,0 +1,4 @@
#pragma once
void init_battery_HAL(void);
void get_battery_status_HAL(int *battery_voltage, int *battery_percentage);

View file

@ -0,0 +1,22 @@
#include <Arduino.h>
#include <Wire.h>
#include "tft_hal_esp32.h"
uint8_t SDA_GPIO = 19;
uint8_t SCL_GPIO = 22;
void init_hardware_general_HAL(void) {
// Make sure ESP32 is running at full speed
setCpuFrequencyMhz(240);
// For I2C to work correctly, the tft has to be powered.
// Otherwise the IMU cannot be initialized.
// The tft touch controller, being on the same I2C bus, seems to disturb if not powered.
pinMode(LCD_EN_GPIO, OUTPUT);
digitalWrite(LCD_EN_GPIO, LOW);
// SDA and SCL need to be set explicitly, because for IMU you cannot set it explicitly in the constructor.
// Configure i2c pins and set frequency to 400kHz
Wire.begin(SDA_GPIO, SCL_GPIO, 400000);
}

View file

@ -0,0 +1,3 @@
#pragma once
void init_hardware_general_HAL(void);

View file

@ -0,0 +1,8 @@
#include <Arduino.h>
void get_heapUsage_HAL(unsigned long *heapSize, unsigned long *freeHeap, unsigned long *maxAllocHeap, unsigned long *minFreeHeap) {
*heapSize = ESP.getHeapSize();
*freeHeap = ESP.getFreeHeap();
*maxAllocHeap = ESP.getMaxAllocHeap();
*minFreeHeap = ESP.getMinFreeHeap();
}

View file

@ -0,0 +1,3 @@
#pragma once
void get_heapUsage_HAL(unsigned long *heapSize, unsigned long *freeHeap, unsigned long *maxAllocHeap, unsigned long *minFreeHeap);

View file

@ -0,0 +1,15 @@
#pragma once
#include "ESP32/battery_hal_esp32.h"
#include "ESP32/hardware_general_hal_esp32.h"
#include "ESP32/heapUsage_hal_esp32.h"
#include "ESP32/infrared_receiver_hal_esp32.h"
#include "ESP32/infrared_sender_hal_esp32.h"
#include "ESP32/keyboard_ble_hal_esp32.h"
#include "ESP32/keypad_keys_hal_esp32.h"
#include "ESP32/lvgl_hal_esp32.h"
#include "ESP32/mqtt_hal_esp32.h"
#include "ESP32/preferencesStorage_hal_esp32.h"
#include "ESP32/sleep_hal_esp32.h"
#include "ESP32/tft_hal_esp32.h"
#include "ESP32/user_led_hal_esp32.h"

View file

@ -39,11 +39,18 @@
#include <IRtext.h>
#include <IRutils.h>
#include "hardware/infrared_receiver.h"
#include "gui_general_and_keys/gui_irReceiver.h"
#include "infrared_receiver_hal_esp32.h"
uint8_t IR_RX_GPIO = 15; // IR receiver input
uint8_t IR_VCC_GPIO = 25; // IR receiver power
bool irReceiverEnabled = false;
tShowNewIRmessage_cb thisShowNewIRmessage_cb = NULL;
void set_showNewIRmessage_cb_HAL(tShowNewIRmessage_cb pShowNewIRmessage_cb) {
thisShowNewIRmessage_cb = pShowNewIRmessage_cb;
}
// The Serial connection baud rate.
// i.e. Status message will be sent to the PC at this baud rate.
// Try to avoid slow speeds like 9600, as you will miss messages and
@ -122,20 +129,20 @@ const uint8_t kTolerancePercentage = kTolerance; // kTolerance is normally 25%
// ==================== end of TUNEABLE PARAMETERS ====================
// Use turn on the save buffer feature for more complete capture coverage.
IRrecv irrecv(IR_RX, kCaptureBufferSize, kTimeout, true);
IRrecv irrecv(IR_RX_GPIO, kCaptureBufferSize, kTimeout, true);
decode_results results; // Somewhere to store the results
// This section of code runs only once at start-up.
void init_infraredReceiver() {
pinMode(IR_RX, INPUT);
pinMode(IR_VCC, OUTPUT);
digitalWrite(IR_VCC, HIGH); // Turn on IR receiver
void start_infraredReceiver_HAL() {
pinMode(IR_RX_GPIO, INPUT);
pinMode(IR_VCC_GPIO, OUTPUT);
digitalWrite(IR_VCC_GPIO, HIGH); // Turn on IR receiver
// Perform a low level sanity checks that the compiler performs bit field
// packing as we expect and Endianness is as we expect.
assert(irutils::lowLevelSanityCheck() == 0);
Serial.printf("\n" D_STR_IRRECVDUMP_STARTUP "\n", IR_RX);
Serial.printf("\n" D_STR_IRRECVDUMP_STARTUP "\n", IR_RX_GPIO);
#if DECODE_HASH
// Ignore messages with less than minimum on or off pulses.
irrecv.setUnknownThreshold(kMinUnknownSize);
@ -144,13 +151,13 @@ void init_infraredReceiver() {
irrecv.enableIRIn(); // Start the receiver
}
void shutdown_infraredReceiver() {
void shutdown_infraredReceiver_HAL() {
irrecv.disableIRIn();
digitalWrite(IR_VCC, LOW); // IR Receiver off
digitalWrite(IR_VCC_GPIO, LOW); // IR Receiver off
}
// The repeating section of the code
void infraredReceiver_loop() {
void infraredReceiver_loop_HAL() {
// Check if the IR code has been received.
if (irrecv.decode(&results)) {
// Display a crude timestamp.
@ -183,7 +190,9 @@ void infraredReceiver_loop() {
message += typeToString((&results)->decode_type, (&results)->repeat);
message += " ";
message += resultToHexidecimal(&results);
showNewIRmessage(message);
if (thisShowNewIRmessage_cb != NULL) {
thisShowNewIRmessage_cb(std::string(message.c_str()));
}
yield(); // Feed the WDT (again)
@ -195,3 +204,10 @@ void infraredReceiver_loop() {
}
}
bool get_irReceiverEnabled_HAL() {
return irReceiverEnabled;
}
void set_irReceiverEnabled_HAL(bool aIrReceiverEnabled) {
irReceiverEnabled = aIrReceiverEnabled;
}

View file

@ -0,0 +1,15 @@
#pragma once
extern uint8_t IR_VCC_GPIO;
#include <string>
void start_infraredReceiver_HAL(void);
void shutdown_infraredReceiver_HAL(void);
void infraredReceiver_loop_HAL(void);
bool get_irReceiverEnabled_HAL();
void set_irReceiverEnabled_HAL(bool aIrReceiverEnabled);
typedef void (*tShowNewIRmessage_cb)(std::string message);
void set_showNewIRmessage_cb_HAL(tShowNewIRmessage_cb pShowNewIRmessage_cb);

View file

@ -0,0 +1,133 @@
#include <Arduino.h>
#include <string>
#include <list>
#include <sstream>
#include <IRremoteESP8266.h>
#include <IRsend.h>
uint8_t IR_LED_GPIO = 33; // IR LED output
IRsend IrSender(IR_LED_GPIO, true);
void init_infraredSender_HAL(void) {
// IR Pin Definition
pinMode(IR_LED_GPIO, OUTPUT);
digitalWrite(IR_LED_GPIO, HIGH); // HIGH off - LOW on
IrSender.begin();
}
// IR protocols
enum IRprotocols {
IR_PROTOCOL_GC = 0,
IR_PROTOCOL_NEC = 1,
IR_PROTOCOL_SAMSUNG = 2,
IR_PROTOCOL_SONY = 3,
IR_PROTOCOL_RC5 = 4,
IR_PROTOCOL_DENON = 5
};
void sendIRcode_HAL(int protocol, std::list<std::string> commandPayloads, std::string additionalPayload) {
switch (protocol) {
case IR_PROTOCOL_GC: {
auto current = commandPayloads.begin();
std::string arrayStr = *current;
// first create array of needed size
std::string::difference_type size = std::count(arrayStr.begin(), arrayStr.end(), ',');
size += 1;
uint16_t *buf = new uint16_t[size];
// now get comma separated values and fill array
int pos = 0;
std::stringstream ss(arrayStr);
while(ss.good()) {
std::string dataStr;
std::getline(ss, dataStr, ',');
// https://cplusplus.com/reference/string/stoull/
std::string::size_type sz = 0; // alias of size_t
const uint64_t data = std::stoull(dataStr, &sz, 0);
// Serial.printf(" next string value %s (%" PRIu64 ")\r\n", dataStr.c_str(), data);
buf[pos] = data;
pos += 1;
}
Serial.printf("execute: will send IR GC, array size %d\r\n", size);
IrSender.sendGC(buf, size);
delete [] buf;
break;
}
case IR_PROTOCOL_NEC: {
auto current = commandPayloads.begin();
std::string dataStr = *current;
// https://cplusplus.com/reference/string/stoull/
std::string::size_type sz = 0; // alias of size_t
const uint64_t data = std::stoull(dataStr, &sz, 0);
Serial.printf("execute: will send IR NEC, data %s (%" PRIu64 ")\r\n", dataStr.c_str(), data);
IrSender.sendNEC(data);
break;
}
case IR_PROTOCOL_SAMSUNG: {
auto current = commandPayloads.begin();
std::string dataStr = *current;
// https://cplusplus.com/reference/string/stoull/
std::string::size_type sz = 0; // alias of size_t
const uint64_t data = std::stoull(dataStr, &sz, 0);
Serial.printf("execute: will send IR SAMSUNG, data %s (%" PRIu64 ")\r\n", dataStr.c_str(), data);
IrSender.sendSAMSUNG(data);
break;
}
case IR_PROTOCOL_SONY: {
std::string::size_type sz = 0; // alias of size_t
uint64_t data;
if (commandPayloads.empty() && (additionalPayload == "")) {
Serial.printf("execute: cannot send IR SONY, because both data and payload are empty\r\n");
} else {
if (additionalPayload != "") {
data = std::stoull(additionalPayload, &sz, 0);
} else {
auto current = commandPayloads.begin();
data = std::stoull(*current, &sz, 0);
}
Serial.printf("execute: will send IR SONY 15 bit, data (%" PRIu64 ")\r\n", data);
IrSender.sendSony(data, 15);
}
break;
}
case IR_PROTOCOL_RC5: {
std::string::size_type sz = 0; // alias of size_t
uint64_t data;
if (commandPayloads.empty() && (additionalPayload == "")) {
Serial.printf("execute: cannot send IR RC5, because both data and payload are empty\r\n");
} else {
if (additionalPayload != "") {
data = std::stoull(additionalPayload, &sz, 0);
} else {
auto current = commandPayloads.begin();
data = std::stoull(*current, &sz, 0);
}
Serial.printf("execute: will send IR RC5, data (%" PRIu64 ")\r\n", data);
IrSender.sendRC5(IrSender.encodeRC5X(0x00, data));
}
break;
}
case IR_PROTOCOL_DENON: {
std::string::size_type sz = 0; // alias of size_t
uint64_t data;
if (commandPayloads.empty() && (additionalPayload == "")) {
Serial.printf("execute: cannot send IR DENON 48 bit, because both data and payload are empty\r\n");
} else {
if (additionalPayload != "") {
data = std::stoull(additionalPayload, &sz, 0);
} else {
auto current = commandPayloads.begin();
data = std::stoull(*current, &sz, 0);
}
Serial.printf("execute: will send IR DENON 48 bit, data (%" PRIu64 ")\r\n", data);
IrSender.sendDenon(data, 48);
}
break;
}
}
}

View file

@ -0,0 +1,8 @@
#pragma once
#include <string>
#include <list>
// infrared
void init_infraredSender_HAL(void);
void sendIRcode_HAL(int protocol, std::list<std::string> commandPayloads, std::string additionalPayload);

View file

@ -0,0 +1,54 @@
#if (ENABLE_KEYBOARD_BLE == 1)
#include "lib/ESP32-BLE-Keyboard/BleKeyboard.h"
#include "battery_hal_esp32.h"
BleKeyboard bleKeyboard("OMOTE Keyboard", "CoretechR");
void init_keyboardBLE_HAL() {
int battery_voltage;
int battery_percentage;
get_battery_status_HAL(&battery_voltage, &battery_percentage);
bleKeyboard.setBatteryLevel(battery_percentage);
bleKeyboard.begin();
}
bool keyboardBLE_isConnected_HAL() {
return bleKeyboard.isConnected();
}
void keyboardBLE_end_HAL() {
bleKeyboard.end();
}
void keyboardBLE_write_HAL(uint8_t c) {
bleKeyboard.write(c);
}
void keyboardBLE_longpress_HAL(uint8_t c) {
bleKeyboard.press(c);
delay(1000);
bleKeyboard.release(c);
}
void keyboardBLE_home_HAL() {
bleKeyboard.press(KEY_LEFT_ALT);
bleKeyboard.press(KEY_ESC);
bleKeyboard.releaseAll();
}
void keyboardBLE_sendString_HAL(const std::string &s) {
bleKeyboard.print(s.c_str());
}
void consumerControlBLE_write_HAL(const MediaKeyReport value) {
bleKeyboard.write(value);
}
void consumerControlBLE_longpress_HAL(const MediaKeyReport value) {
bleKeyboard.press(value);
delay(1000);
bleKeyboard.release(value);
}
#endif

View file

@ -0,0 +1,17 @@
#pragma once
#if (ENABLE_KEYBOARD_BLE == 1)
#include "lib/ESP32-BLE-Keyboard/BleKeyboard.h"
void init_keyboardBLE_HAL();
bool keyboardBLE_isConnected_HAL();
void keyboardBLE_end_HAL();
void keyboardBLE_write_HAL(uint8_t c);
void keyboardBLE_longpress_HAL(uint8_t c);
void keyboardBLE_home_HAL();
void keyboardBLE_sendString_HAL(const std::string &s);
void consumerControlBLE_write_HAL(const MediaKeyReport value);
void consumerControlBLE_longpress_HAL(const MediaKeyReport value);
#endif

View file

@ -0,0 +1,82 @@
#include <Arduino.h>
#include "lib/Keypad/src/Keypad.h" // modified for inverted logic
uint8_t SW_1_GPIO = 32; // 1...5: Output
uint8_t SW_2_GPIO = 26;
uint8_t SW_3_GPIO = 27;
uint8_t SW_4_GPIO = 14;
uint8_t SW_5_GPIO = 12;
uint8_t SW_A_GPIO = 37; // A...E: Input
uint8_t SW_B_GPIO = 38;
uint8_t SW_C_GPIO = 39;
uint8_t SW_D_GPIO = 34;
uint8_t SW_E_GPIO = 35;
uint64_t BUTTON_PIN_BITMASK = 0b1110110000000000000000000010000000000000; //IO34+IO35+IO37+IO38+IO39(+IO13)
const byte ROWS = 5; //five rows
const byte COLS = 5; //five columns
// Keypad declarations
// define the symbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
{'s','^','-','m','e'}, // source, channel+, Volume-, mute, record
{'i','r','+','k','d'}, // info, right, Volume+, OK, down
{'4','v','1','3','2'}, // blue, channel-, red, yellow, green
{'>','o','b','u','l'}, // forward, off, back, up, left
{'?','p','c','<','='} // ?, play, config, rewind, stop
};
/*
off o
stop = rewind < play p forward >
config c info i
up u
left l OK k right r
down d
back b source s
Volume+ + mute m channel+ ^
Volume- - record e channel- v
red 1 green 2 yellow 3 blue 4
*/
byte rowPins[ROWS] = {SW_A_GPIO, SW_B_GPIO, SW_C_GPIO, SW_D_GPIO, SW_E_GPIO}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {SW_1_GPIO, SW_2_GPIO, SW_3_GPIO, SW_4_GPIO, SW_5_GPIO}; //connect to the column pinouts of the keypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
void init_keys_HAL(void) {
// Button Pin Definition
pinMode(SW_1_GPIO, OUTPUT);
pinMode(SW_2_GPIO, OUTPUT);
pinMode(SW_3_GPIO, OUTPUT);
pinMode(SW_4_GPIO, OUTPUT);
pinMode(SW_5_GPIO, OUTPUT);
pinMode(SW_A_GPIO, INPUT);
pinMode(SW_B_GPIO, INPUT);
pinMode(SW_C_GPIO, INPUT);
pinMode(SW_D_GPIO, INPUT);
pinMode(SW_E_GPIO, INPUT);
}
enum keypad_keyStates {IDLE_HAL, PRESSED_HAL, HOLD_HAL, RELEASED_HAL};
struct keypad_key {
char kchar;
int kcode;
keypad_keyStates kstate;
boolean stateChanged;
};
keypad_key keys[10];
void keys_getKeys_HAL(void* ptr) {
customKeypad.getKeys();
for(int i=0; i < LIST_MAX; i++) {
(*(keypad_key*)ptr).kchar = customKeypad.key[i].kchar;
(*(keypad_key*)ptr).kcode = customKeypad.key[i].kcode;
(*(keypad_key*)ptr).kstate = (keypad_keyStates)(customKeypad.key[i].kstate);
(*(keypad_key*)ptr).stateChanged = customKeypad.key[i].stateChanged;
// https://www.geeksforgeeks.org/void-pointer-c-cpp/
ptr = (void *) ((intptr_t)(ptr) + sizeof(keypad_key));
}
}

View file

@ -0,0 +1,16 @@
#pragma once
extern uint8_t SW_1_GPIO; // 1...5: Output
extern uint8_t SW_2_GPIO;
extern uint8_t SW_3_GPIO;
extern uint8_t SW_4_GPIO;
extern uint8_t SW_5_GPIO;
extern uint8_t SW_A_GPIO; // A...E: Input
extern uint8_t SW_B_GPIO;
extern uint8_t SW_C_GPIO;
extern uint8_t SW_D_GPIO;
extern uint8_t SW_E_GPIO;
extern uint64_t BUTTON_PIN_BITMASK;
void init_keys_HAL(void);
void keys_getKeys_HAL(void* ptr);

View file

@ -0,0 +1 @@
{"type": "library", "name": "ESP32 BLE Keyboard", "version": "0.3.2", "spec": {"owner": "t-vk", "id": 6749, "name": "ESP32 BLE Keyboard", "requirements": null, "uri": null}}

View file

@ -0,0 +1,552 @@
#include "BleKeyboard.h"
#if defined(USE_NIMBLE)
#include <NimBLEDevice.h>
#include <NimBLEServer.h>
#include <NimBLEUtils.h>
#include <NimBLEHIDDevice.h>
#else
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include "BLE2902.h"
#include "BLEHIDDevice.h"
#endif // USE_NIMBLE
#include "HIDTypes.h"
#include <driver/adc.h>
#include "sdkconfig.h"
#if defined(CONFIG_ARDUHAL_ESP_LOG)
#include "esp32-hal-log.h"
#define LOG_TAG ""
#else
#include "esp_log.h"
static const char* LOG_TAG = "BLEDevice";
#endif
// Report IDs:
#define KEYBOARD_ID 0x01
#define MEDIA_KEYS_ID 0x02
static const uint8_t _hidReportDescriptor[] = {
USAGE_PAGE(1), 0x01, // USAGE_PAGE (Generic Desktop Ctrls)
USAGE(1), 0x06, // USAGE (Keyboard)
COLLECTION(1), 0x01, // COLLECTION (Application)
// ------------------------------------------------- Keyboard
REPORT_ID(1), KEYBOARD_ID, // REPORT_ID (1)
USAGE_PAGE(1), 0x07, // USAGE_PAGE (Kbrd/Keypad)
USAGE_MINIMUM(1), 0xE0, // USAGE_MINIMUM (0xE0)
USAGE_MAXIMUM(1), 0xE7, // USAGE_MAXIMUM (0xE7)
LOGICAL_MINIMUM(1), 0x00, // LOGICAL_MINIMUM (0)
LOGICAL_MAXIMUM(1), 0x01, // Logical Maximum (1)
REPORT_SIZE(1), 0x01, // REPORT_SIZE (1)
REPORT_COUNT(1), 0x08, // REPORT_COUNT (8)
HIDINPUT(1), 0x02, // INPUT (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
REPORT_COUNT(1), 0x01, // REPORT_COUNT (1) ; 1 byte (Reserved)
REPORT_SIZE(1), 0x08, // REPORT_SIZE (8)
HIDINPUT(1), 0x01, // INPUT (Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position)
REPORT_COUNT(1), 0x05, // REPORT_COUNT (5) ; 5 bits (Num lock, Caps lock, Scroll lock, Compose, Kana)
REPORT_SIZE(1), 0x01, // REPORT_SIZE (1)
USAGE_PAGE(1), 0x08, // USAGE_PAGE (LEDs)
USAGE_MINIMUM(1), 0x01, // USAGE_MINIMUM (0x01) ; Num Lock
USAGE_MAXIMUM(1), 0x05, // USAGE_MAXIMUM (0x05) ; Kana
HIDOUTPUT(1), 0x02, // OUTPUT (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile)
REPORT_COUNT(1), 0x01, // REPORT_COUNT (1) ; 3 bits (Padding)
REPORT_SIZE(1), 0x03, // REPORT_SIZE (3)
HIDOUTPUT(1), 0x01, // OUTPUT (Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile)
REPORT_COUNT(1), 0x06, // REPORT_COUNT (6) ; 6 bytes (Keys)
REPORT_SIZE(1), 0x08, // REPORT_SIZE(8)
LOGICAL_MINIMUM(1), 0x00, // LOGICAL_MINIMUM(0)
LOGICAL_MAXIMUM(1), 0x65, // LOGICAL_MAXIMUM(0x65) ; 101 keys
USAGE_PAGE(1), 0x07, // USAGE_PAGE (Kbrd/Keypad)
USAGE_MINIMUM(1), 0x00, // USAGE_MINIMUM (0)
USAGE_MAXIMUM(1), 0x65, // USAGE_MAXIMUM (0x65)
HIDINPUT(1), 0x00, // INPUT (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position)
END_COLLECTION(0), // END_COLLECTION
// ------------------------------------------------- Media Keys
USAGE_PAGE(1), 0x0C, // USAGE_PAGE (Consumer)
USAGE(1), 0x01, // USAGE (Consumer Control)
COLLECTION(1), 0x01, // COLLECTION (Application)
REPORT_ID(1), MEDIA_KEYS_ID, // REPORT_ID (3)
USAGE_PAGE(1), 0x0C, // USAGE_PAGE (Consumer)
LOGICAL_MINIMUM(1), 0x00, // LOGICAL_MINIMUM (0)
LOGICAL_MAXIMUM(1), 0x01, // LOGICAL_MAXIMUM (1)
REPORT_SIZE(1), 0x01, // REPORT_SIZE (1)
REPORT_COUNT(1), 0x10, // REPORT_COUNT (16)
USAGE(1), 0xB5, // USAGE (Scan Next Track) ; bit 0: 1
USAGE(1), 0xB6, // USAGE (Scan Previous Track) ; bit 1: 2
USAGE(1), 0xB7, // USAGE (Stop) ; bit 2: 4
USAGE(1), 0xCD, // USAGE (Play/Pause) ; bit 3: 8
USAGE(1), 0xE2, // USAGE (Mute) ; bit 4: 16
USAGE(1), 0xE9, // USAGE (Volume Increment) ; bit 5: 32
USAGE(1), 0xEA, // USAGE (Volume Decrement) ; bit 6: 64
USAGE(2), 0x23, 0x02, // Usage (WWW Home) ; bit 7: 128
USAGE(2), 0x94, 0x01, // Usage (My Computer) ; bit 0: 1
// original from BLE-Keyboard
// USAGE(2), 0x92, 0x01, // Usage (Calculator) ; bit 1: 2
// changed for usage in OMOTE
USAGE(1), 0xB3, // USAGE (Fast Forward); bit 1: 2
USAGE(2), 0x2A, 0x02, // Usage (WWW fav) ; bit 2: 4
USAGE(2), 0x21, 0x02, // Usage (WWW search) ; bit 3: 8
USAGE(2), 0x26, 0x02, // Usage (WWW stop) ; bit 4: 16
USAGE(2), 0x24, 0x02, // Usage (WWW back) ; bit 5: 32
USAGE(2), 0x83, 0x01, // Usage (Media sel) ; bit 6: 64
// original from BLE-Keyboard
// USAGE(2), 0x8A, 0x01, // Usage (Mail) ; bit 7: 128
// changed for usage in OMOTE
USAGE(1), 0xB4, // USAGE (Rewind) ; bit 7: 128
HIDINPUT(1), 0x02, // INPUT (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
END_COLLECTION(0) // END_COLLECTION
};
BleKeyboard::BleKeyboard(std::string deviceName, std::string deviceManufacturer, uint8_t batteryLevel)
: hid(0)
, deviceName(std::string(deviceName).substr(0, 15))
, deviceManufacturer(std::string(deviceManufacturer).substr(0,15))
, batteryLevel(batteryLevel) {}
void BleKeyboard::begin(void)
{
BLEDevice::init(deviceName);
BLEServer* pServer = BLEDevice::createServer();
pServer->setCallbacks(this);
hid = new BLEHIDDevice(pServer);
inputKeyboard = hid->inputReport(KEYBOARD_ID); // <-- input REPORTID from report map
outputKeyboard = hid->outputReport(KEYBOARD_ID);
inputMediaKeys = hid->inputReport(MEDIA_KEYS_ID);
outputKeyboard->setCallbacks(this);
hid->manufacturer()->setValue(deviceManufacturer);
hid->pnp(0x02, vid, pid, version);
hid->hidInfo(0x00, 0x01);
#if defined(USE_NIMBLE)
BLEDevice::setSecurityAuth(true, true, true);
#else
BLESecurity* pSecurity = new BLESecurity();
pSecurity->setAuthenticationMode(ESP_LE_AUTH_REQ_SC_MITM_BOND);
#endif // USE_NIMBLE
hid->reportMap((uint8_t*)_hidReportDescriptor, sizeof(_hidReportDescriptor));
hid->startServices();
onStarted(pServer);
advertising = pServer->getAdvertising();
advertising->setAppearance(HID_KEYBOARD);
advertising->addServiceUUID(hid->hidService()->getUUID());
advertising->setScanResponse(false);
advertising->start();
hid->setBatteryLevel(batteryLevel);
ESP_LOGD(LOG_TAG, "Advertising started!");
}
void BleKeyboard::end(void)
{
}
bool BleKeyboard::isConnected(void) {
return this->connected;
}
void BleKeyboard::setBatteryLevel(uint8_t level) {
this->batteryLevel = level;
if (hid != 0)
this->hid->setBatteryLevel(this->batteryLevel);
}
//must be called before begin in order to set the name
void BleKeyboard::setName(std::string deviceName) {
this->deviceName = deviceName;
}
/**
* @brief Sets the waiting time (in milliseconds) between multiple keystrokes in NimBLE mode.
*
* @param ms Time in milliseconds
*/
void BleKeyboard::setDelay(uint32_t ms) {
this->_delay_ms = ms;
}
void BleKeyboard::set_vendor_id(uint16_t vid) {
this->vid = vid;
}
void BleKeyboard::set_product_id(uint16_t pid) {
this->pid = pid;
}
void BleKeyboard::set_version(uint16_t version) {
this->version = version;
}
void BleKeyboard::sendReport(KeyReport* keys)
{
if (this->isConnected())
{
this->inputKeyboard->setValue((uint8_t*)keys, sizeof(KeyReport));
this->inputKeyboard->notify();
#if defined(USE_NIMBLE)
// vTaskDelay(delayTicks);
this->delay_ms(_delay_ms);
#endif // USE_NIMBLE
}
}
void BleKeyboard::sendReport(MediaKeyReport* keys)
{
if (this->isConnected())
{
this->inputMediaKeys->setValue((uint8_t*)keys, sizeof(MediaKeyReport));
this->inputMediaKeys->notify();
#if defined(USE_NIMBLE)
//vTaskDelay(delayTicks);
this->delay_ms(_delay_ms);
#endif // USE_NIMBLE
}
}
extern
const uint8_t _asciimap[128] PROGMEM;
#define SHIFT 0x80
const uint8_t _asciimap[128] =
{
0x00, // NUL
0x00, // SOH
0x00, // STX
0x00, // ETX
0x00, // EOT
0x00, // ENQ
0x00, // ACK
0x00, // BEL
0x2a, // BS Backspace
0x2b, // TAB Tab
0x28, // LF Enter
0x00, // VT
0x00, // FF
0x00, // CR
0x00, // SO
0x00, // SI
0x00, // DEL
0x00, // DC1
0x00, // DC2
0x00, // DC3
0x00, // DC4
0x00, // NAK
0x00, // SYN
0x00, // ETB
0x00, // CAN
0x00, // EM
0x00, // SUB
0x00, // ESC
0x00, // FS
0x00, // GS
0x00, // RS
0x00, // US
0x2c, // ' '
0x1e|SHIFT, // !
0x34|SHIFT, // "
0x20|SHIFT, // #
0x21|SHIFT, // $
0x22|SHIFT, // %
0x24|SHIFT, // &
0x34, // '
0x26|SHIFT, // (
0x27|SHIFT, // )
0x25|SHIFT, // *
0x2e|SHIFT, // +
0x36, // ,
0x2d, // -
0x37, // .
0x38, // /
0x27, // 0
0x1e, // 1
0x1f, // 2
0x20, // 3
0x21, // 4
0x22, // 5
0x23, // 6
0x24, // 7
0x25, // 8
0x26, // 9
0x33|SHIFT, // :
0x33, // ;
0x36|SHIFT, // <
0x2e, // =
0x37|SHIFT, // >
0x38|SHIFT, // ?
0x1f|SHIFT, // @
0x04|SHIFT, // A
0x05|SHIFT, // B
0x06|SHIFT, // C
0x07|SHIFT, // D
0x08|SHIFT, // E
0x09|SHIFT, // F
0x0a|SHIFT, // G
0x0b|SHIFT, // H
0x0c|SHIFT, // I
0x0d|SHIFT, // J
0x0e|SHIFT, // K
0x0f|SHIFT, // L
0x10|SHIFT, // M
0x11|SHIFT, // N
0x12|SHIFT, // O
0x13|SHIFT, // P
0x14|SHIFT, // Q
0x15|SHIFT, // R
0x16|SHIFT, // S
0x17|SHIFT, // T
0x18|SHIFT, // U
0x19|SHIFT, // V
0x1a|SHIFT, // W
0x1b|SHIFT, // X
0x1c|SHIFT, // Y
0x1d|SHIFT, // Z
0x2f, // [
0x31, // bslash
0x30, // ]
0x23|SHIFT, // ^
0x2d|SHIFT, // _
0x35, // `
0x04, // a
0x05, // b
0x06, // c
0x07, // d
0x08, // e
0x09, // f
0x0a, // g
0x0b, // h
0x0c, // i
0x0d, // j
0x0e, // k
0x0f, // l
0x10, // m
0x11, // n
0x12, // o
0x13, // p
0x14, // q
0x15, // r
0x16, // s
0x17, // t
0x18, // u
0x19, // v
0x1a, // w
0x1b, // x
0x1c, // y
0x1d, // z
0x2f|SHIFT, // {
0x31|SHIFT, // |
0x30|SHIFT, // }
0x35|SHIFT, // ~
0 // DEL
};
uint8_t USBPutChar(uint8_t c);
// press() adds the specified key (printing, non-printing, or modifier)
// to the persistent key report and sends the report. Because of the way
// USB HID works, the host acts like the key remains pressed until we
// call release(), releaseAll(), or otherwise clear the report and resend.
size_t BleKeyboard::press(uint8_t k)
{
uint8_t i;
if (k >= 136) { // it's a non-printing key (not a modifier)
k = k - 136;
} else if (k >= 128) { // it's a modifier key
_keyReport.modifiers |= (1<<(k-128));
k = 0;
} else { // it's a printing key
k = pgm_read_byte(_asciimap + k);
if (!k) {
setWriteError();
return 0;
}
if (k & 0x80) { // it's a capital letter or other character reached with shift
_keyReport.modifiers |= 0x02; // the left shift modifier
k &= 0x7F;
}
}
// Add k to the key report only if it's not already present
// and if there is an empty slot.
if (_keyReport.keys[0] != k && _keyReport.keys[1] != k &&
_keyReport.keys[2] != k && _keyReport.keys[3] != k &&
_keyReport.keys[4] != k && _keyReport.keys[5] != k) {
for (i=0; i<6; i++) {
if (_keyReport.keys[i] == 0x00) {
_keyReport.keys[i] = k;
break;
}
}
if (i == 6) {
setWriteError();
return 0;
}
}
sendReport(&_keyReport);
return 1;
}
size_t BleKeyboard::press(const MediaKeyReport k)
{
uint16_t k_16 = k[1] | (k[0] << 8);
uint16_t mediaKeyReport_16 = _mediaKeyReport[1] | (_mediaKeyReport[0] << 8);
mediaKeyReport_16 |= k_16;
_mediaKeyReport[0] = (uint8_t)((mediaKeyReport_16 & 0xFF00) >> 8);
_mediaKeyReport[1] = (uint8_t)(mediaKeyReport_16 & 0x00FF);
sendReport(&_mediaKeyReport);
return 1;
}
// release() takes the specified key out of the persistent key report and
// sends the report. This tells the OS the key is no longer pressed and that
// it shouldn't be repeated any more.
size_t BleKeyboard::release(uint8_t k)
{
uint8_t i;
if (k >= 136) { // it's a non-printing key (not a modifier)
k = k - 136;
} else if (k >= 128) { // it's a modifier key
_keyReport.modifiers &= ~(1<<(k-128));
k = 0;
} else { // it's a printing key
k = pgm_read_byte(_asciimap + k);
if (!k) {
return 0;
}
if (k & 0x80) { // it's a capital letter or other character reached with shift
_keyReport.modifiers &= ~(0x02); // the left shift modifier
k &= 0x7F;
}
}
// Test the key report to see if k is present. Clear it if it exists.
// Check all positions in case the key is present more than once (which it shouldn't be)
for (i=0; i<6; i++) {
if (0 != k && _keyReport.keys[i] == k) {
_keyReport.keys[i] = 0x00;
}
}
sendReport(&_keyReport);
return 1;
}
size_t BleKeyboard::release(const MediaKeyReport k)
{
uint16_t k_16 = k[1] | (k[0] << 8);
uint16_t mediaKeyReport_16 = _mediaKeyReport[1] | (_mediaKeyReport[0] << 8);
mediaKeyReport_16 &= ~k_16;
_mediaKeyReport[0] = (uint8_t)((mediaKeyReport_16 & 0xFF00) >> 8);
_mediaKeyReport[1] = (uint8_t)(mediaKeyReport_16 & 0x00FF);
sendReport(&_mediaKeyReport);
return 1;
}
void BleKeyboard::releaseAll(void)
{
_keyReport.keys[0] = 0;
_keyReport.keys[1] = 0;
_keyReport.keys[2] = 0;
_keyReport.keys[3] = 0;
_keyReport.keys[4] = 0;
_keyReport.keys[5] = 0;
_keyReport.modifiers = 0;
_mediaKeyReport[0] = 0;
_mediaKeyReport[1] = 0;
sendReport(&_keyReport);
}
size_t BleKeyboard::write(uint8_t c)
{
uint8_t p = press(c); // Keydown
release(c); // Keyup
return p; // just return the result of press() since release() almost always returns 1
}
size_t BleKeyboard::write(const MediaKeyReport c)
{
uint16_t p = press(c); // Keydown
release(c); // Keyup
return p; // just return the result of press() since release() almost always returns 1
}
size_t BleKeyboard::write(const uint8_t *buffer, size_t size) {
size_t n = 0;
while (size--) {
if (*buffer != '\r') {
if (write(*buffer)) {
n++;
} else {
break;
}
}
buffer++;
}
return n;
}
void BleKeyboard::onConnect(BLEServer* pServer) {
this->connected = true;
#if !defined(USE_NIMBLE)
BLE2902* desc = (BLE2902*)this->inputKeyboard->getDescriptorByUUID(BLEUUID((uint16_t)0x2902));
desc->setNotifications(true);
desc = (BLE2902*)this->inputMediaKeys->getDescriptorByUUID(BLEUUID((uint16_t)0x2902));
desc->setNotifications(true);
#endif // !USE_NIMBLE
}
void BleKeyboard::onDisconnect(BLEServer* pServer) {
this->connected = false;
#if !defined(USE_NIMBLE)
BLE2902* desc = (BLE2902*)this->inputKeyboard->getDescriptorByUUID(BLEUUID((uint16_t)0x2902));
desc->setNotifications(false);
desc = (BLE2902*)this->inputMediaKeys->getDescriptorByUUID(BLEUUID((uint16_t)0x2902));
desc->setNotifications(false);
advertising->start();
#endif // !USE_NIMBLE
}
void BleKeyboard::onWrite(BLECharacteristic* me) {
uint8_t* value = (uint8_t*)(me->getValue().c_str());
(void)value;
ESP_LOGI(LOG_TAG, "special keys: %d", *value);
}
void BleKeyboard::delay_ms(uint64_t ms) {
uint64_t m = esp_timer_get_time();
if(ms){
uint64_t e = (m + (ms * 1000));
if(m > e){ //overflow
while(esp_timer_get_time() > e) { }
}
while(esp_timer_get_time() < e) {}
}
}

View file

@ -0,0 +1,189 @@
// uncomment the following line to use NimBLE library
//#define USE_NIMBLE
#ifndef ESP32_BLE_KEYBOARD_H
#define ESP32_BLE_KEYBOARD_H
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED)
#if defined(USE_NIMBLE)
#include "NimBLECharacteristic.h"
#include "NimBLEHIDDevice.h"
#define BLEDevice NimBLEDevice
#define BLEServerCallbacks NimBLEServerCallbacks
#define BLECharacteristicCallbacks NimBLECharacteristicCallbacks
#define BLEHIDDevice NimBLEHIDDevice
#define BLECharacteristic NimBLECharacteristic
#define BLEAdvertising NimBLEAdvertising
#define BLEServer NimBLEServer
#else
#include "BLEHIDDevice.h"
#include "BLECharacteristic.h"
#endif // USE_NIMBLE
#include "Print.h"
#define BLE_KEYBOARD_VERSION "0.0.4"
#define BLE_KEYBOARD_VERSION_MAJOR 0
#define BLE_KEYBOARD_VERSION_MINOR 0
#define BLE_KEYBOARD_VERSION_REVISION 4
const uint8_t KEY_LEFT_CTRL = 0x80;
const uint8_t KEY_LEFT_SHIFT = 0x81;
const uint8_t KEY_LEFT_ALT = 0x82;
const uint8_t KEY_LEFT_GUI = 0x83;
const uint8_t KEY_RIGHT_CTRL = 0x84;
const uint8_t KEY_RIGHT_SHIFT = 0x85;
const uint8_t KEY_RIGHT_ALT = 0x86;
const uint8_t KEY_RIGHT_GUI = 0x87;
const uint8_t KEY_UP_ARROW = 0xDA;
const uint8_t KEY_DOWN_ARROW = 0xD9;
const uint8_t KEY_LEFT_ARROW = 0xD8;
const uint8_t KEY_RIGHT_ARROW = 0xD7;
const uint8_t KEY_BACKSPACE = 0xB2;
const uint8_t KEY_TAB = 0xB3;
const uint8_t KEY_RETURN = 0xB0;
const uint8_t KEY_ESC = 0xB1;
const uint8_t KEY_INSERT = 0xD1;
const uint8_t KEY_PRTSC = 0xCE;
const uint8_t KEY_DELETE = 0xD4;
const uint8_t KEY_PAGE_UP = 0xD3;
const uint8_t KEY_PAGE_DOWN = 0xD6;
const uint8_t KEY_HOME = 0xD2;
const uint8_t KEY_END = 0xD5;
const uint8_t KEY_CAPS_LOCK = 0xC1;
const uint8_t KEY_F1 = 0xC2;
const uint8_t KEY_F2 = 0xC3;
const uint8_t KEY_F3 = 0xC4;
const uint8_t KEY_F4 = 0xC5;
const uint8_t KEY_F5 = 0xC6;
const uint8_t KEY_F6 = 0xC7;
const uint8_t KEY_F7 = 0xC8;
const uint8_t KEY_F8 = 0xC9;
const uint8_t KEY_F9 = 0xCA;
const uint8_t KEY_F10 = 0xCB;
const uint8_t KEY_F11 = 0xCC;
const uint8_t KEY_F12 = 0xCD;
const uint8_t KEY_F13 = 0xF0;
const uint8_t KEY_F14 = 0xF1;
const uint8_t KEY_F15 = 0xF2;
const uint8_t KEY_F16 = 0xF3;
const uint8_t KEY_F17 = 0xF4;
const uint8_t KEY_F18 = 0xF5;
const uint8_t KEY_F19 = 0xF6;
const uint8_t KEY_F20 = 0xF7;
const uint8_t KEY_F21 = 0xF8;
const uint8_t KEY_F22 = 0xF9;
const uint8_t KEY_F23 = 0xFA;
const uint8_t KEY_F24 = 0xFB;
const uint8_t KEY_NUM_0 = 0xEA;
const uint8_t KEY_NUM_1 = 0xE1;
const uint8_t KEY_NUM_2 = 0xE2;
const uint8_t KEY_NUM_3 = 0xE3;
const uint8_t KEY_NUM_4 = 0xE4;
const uint8_t KEY_NUM_5 = 0xE5;
const uint8_t KEY_NUM_6 = 0xE6;
const uint8_t KEY_NUM_7 = 0xE7;
const uint8_t KEY_NUM_8 = 0xE8;
const uint8_t KEY_NUM_9 = 0xE9;
const uint8_t KEY_NUM_SLASH = 0xDC;
const uint8_t KEY_NUM_ASTERISK = 0xDD;
const uint8_t KEY_NUM_MINUS = 0xDE;
const uint8_t KEY_NUM_PLUS = 0xDF;
const uint8_t KEY_NUM_ENTER = 0xE0;
const uint8_t KEY_NUM_PERIOD = 0xEB;
typedef uint8_t MediaKeyReport[2];
const MediaKeyReport KEY_MEDIA_NEXT_TRACK = {1, 0};
const MediaKeyReport KEY_MEDIA_PREVIOUS_TRACK = {2, 0};
const MediaKeyReport KEY_MEDIA_STOP = {4, 0};
const MediaKeyReport KEY_MEDIA_PLAY_PAUSE = {8, 0};
const MediaKeyReport KEY_MEDIA_MUTE = {16, 0};
const MediaKeyReport KEY_MEDIA_VOLUME_UP = {32, 0};
const MediaKeyReport KEY_MEDIA_VOLUME_DOWN = {64, 0};
const MediaKeyReport KEY_MEDIA_WWW_HOME = {128, 0};
const MediaKeyReport KEY_MEDIA_LOCAL_MACHINE_BROWSER = {0, 1}; // Opens "My Computer" on Windows
// original from BLE-Keyboard
// const MediaKeyReport KEY_MEDIA_CALCULATOR = {0, 2};
// changed for usage in OMOTE
const MediaKeyReport KEY_MEDIA_FASTFORWARD = {0, 2};
const MediaKeyReport KEY_MEDIA_WWW_BOOKMARKS = {0, 4};
const MediaKeyReport KEY_MEDIA_WWW_SEARCH = {0, 8};
const MediaKeyReport KEY_MEDIA_WWW_STOP = {0, 16};
const MediaKeyReport KEY_MEDIA_WWW_BACK = {0, 32};
const MediaKeyReport KEY_MEDIA_CONSUMER_CONTROL_CONFIGURATION = {0, 64}; // Media Selection
// original from BLE-Keyboard
// const MediaKeyReport KEY_MEDIA_EMAIL_READER = {0, 128};
// changed for usage in OMOTE
const MediaKeyReport KEY_MEDIA_REWIND = {0, 128};
// Low level key report: up to 6 keys and shift, ctrl etc at once
typedef struct
{
uint8_t modifiers;
uint8_t reserved;
uint8_t keys[6];
} KeyReport;
class BleKeyboard : public Print, public BLEServerCallbacks, public BLECharacteristicCallbacks
{
private:
BLEHIDDevice* hid;
BLECharacteristic* inputKeyboard;
BLECharacteristic* outputKeyboard;
BLECharacteristic* inputMediaKeys;
BLEAdvertising* advertising;
KeyReport _keyReport;
MediaKeyReport _mediaKeyReport;
std::string deviceName;
std::string deviceManufacturer;
uint8_t batteryLevel;
bool connected = false;
uint32_t _delay_ms = 7;
void delay_ms(uint64_t ms);
uint16_t vid = 0x05ac;
uint16_t pid = 0x820a;
uint16_t version = 0x0210;
public:
BleKeyboard(std::string deviceName = "ESP32 Keyboard", std::string deviceManufacturer = "Espressif", uint8_t batteryLevel = 100);
void begin(void);
void end(void);
void sendReport(KeyReport* keys);
void sendReport(MediaKeyReport* keys);
size_t press(uint8_t k);
size_t press(const MediaKeyReport k);
size_t release(uint8_t k);
size_t release(const MediaKeyReport k);
size_t write(uint8_t c);
size_t write(const MediaKeyReport c);
size_t write(const uint8_t *buffer, size_t size);
void releaseAll(void);
bool isConnected(void);
void setBatteryLevel(uint8_t level);
void setName(std::string deviceName);
void setDelay(uint32_t ms);
void set_vendor_id(uint16_t vid);
void set_product_id(uint16_t pid);
void set_version(uint16_t version);
protected:
virtual void onStarted(BLEServer *pServer) { };
virtual void onConnect(BLEServer* pServer) override;
virtual void onDisconnect(BLEServer* pServer) override;
virtual void onWrite(BLECharacteristic* me) override;
};
#endif // CONFIG_BT_ENABLED
#endif // ESP32_BLE_KEYBOARD_H

View file

@ -0,0 +1,162 @@
# ESP32 BLE Keyboard library
This library allows you to make the ESP32 act as a Bluetooth Keyboard and control what it does.
You might also be interested in:
- [ESP32-BLE-Mouse](https://github.com/T-vK/ESP32-BLE-Mouse)
- [ESP32-BLE-Gamepad](https://github.com/lemmingDev/ESP32-BLE-Gamepad)
## Features
- [x] Send key strokes
- [x] Send text
- [x] Press/release individual keys
- [x] Media keys are supported
- [ ] Read Numlock/Capslock/Scrolllock state
- [x] Set battery level (basically works, but doesn't show up in Android's status bar)
- [x] Compatible with Android
- [x] Compatible with Windows
- [x] Compatible with Linux
- [x] Compatible with MacOS X (not stable, some people have issues, doesn't work with old devices)
- [x] Compatible with iOS (not stable, some people have issues, doesn't work with old devices)
## Installation
- (Make sure you can use the ESP32 with the Arduino IDE. [Instructions can be found here.](https://github.com/espressif/arduino-esp32#installation-instructions))
- [Download the latest release of this library from the release page.](https://github.com/T-vK/ESP32-BLE-Keyboard/releases)
- In the Arduino IDE go to "Sketch" -> "Include Library" -> "Add .ZIP Library..." and select the file you just downloaded.
- You can now go to "File" -> "Examples" -> "ESP32 BLE Keyboard" and select any of the examples to get started.
## Example
``` C++
/**
* This example turns the ESP32 into a Bluetooth LE keyboard that writes the words, presses Enter, presses a media key and then Ctrl+Alt+Delete
*/
#include <BleKeyboard.h>
BleKeyboard bleKeyboard;
void setup() {
Serial.begin(115200);
Serial.println("Starting BLE work!");
bleKeyboard.begin();
}
void loop() {
if(bleKeyboard.isConnected()) {
Serial.println("Sending 'Hello world'...");
bleKeyboard.print("Hello world");
delay(1000);
Serial.println("Sending Enter key...");
bleKeyboard.write(KEY_RETURN);
delay(1000);
Serial.println("Sending Play/Pause media key...");
bleKeyboard.write(KEY_MEDIA_PLAY_PAUSE);
delay(1000);
//
// Below is an example of pressing multiple keyboard modifiers
// which by default is commented out.
//
/* Serial.println("Sending Ctrl+Alt+Delete...");
bleKeyboard.press(KEY_LEFT_CTRL);
bleKeyboard.press(KEY_LEFT_ALT);
bleKeyboard.press(KEY_DELETE);
delay(100);
bleKeyboard.releaseAll();
*/
}
Serial.println("Waiting 5 seconds...");
delay(5000);
}
```
## API docs
The BleKeyboard interface is almost identical to the Keyboard Interface, so you can use documentation right here:
https://www.arduino.cc/reference/en/language/functions/usb/keyboard/
Just remember that you have to use `bleKeyboard` instead of just `Keyboard` and you need these two lines at the top of your script:
```
#include <BleKeyboard.h>
BleKeyboard bleKeyboard;
```
In addition to that you can send media keys (which is not possible with the USB keyboard library). Supported are the following:
- KEY_MEDIA_NEXT_TRACK
- KEY_MEDIA_PREVIOUS_TRACK
- KEY_MEDIA_STOP
- KEY_MEDIA_PLAY_PAUSE
- KEY_MEDIA_MUTE
- KEY_MEDIA_VOLUME_UP
- KEY_MEDIA_VOLUME_DOWN
- KEY_MEDIA_WWW_HOME
- KEY_MEDIA_LOCAL_MACHINE_BROWSER // Opens "My Computer" on Windows
- KEY_MEDIA_CALCULATOR
- KEY_MEDIA_WWW_BOOKMARKS
- KEY_MEDIA_WWW_SEARCH
- KEY_MEDIA_WWW_STOP
- KEY_MEDIA_WWW_BACK
- KEY_MEDIA_CONSUMER_CONTROL_CONFIGURATION // Media Selection
- KEY_MEDIA_EMAIL_READER
There is also Bluetooth specific information that you can set (optional):
Instead of `BleKeyboard bleKeyboard;` you can do `BleKeyboard bleKeyboard("Bluetooth Device Name", "Bluetooth Device Manufacturer", 100);`. (Max lenght is 15 characters, anything beyond that will be truncated.)
The third parameter is the initial battery level of your device. To adjust the battery level later on you can simply call e.g. `bleKeyboard.setBatteryLevel(50)` (set battery level to 50%).
By default the battery level will be set to 100%, the device name will be `ESP32 Bluetooth Keyboard` and the manufacturer will be `Espressif`.
There is also a `setDelay` method to set a delay between each key event. E.g. `bleKeyboard.setDelay(10)` (10 milliseconds). The default is `8`.
This feature is meant to compensate for some applications and devices that can't handle fast input and will skip letters if too many keys are sent in a small time frame.
## NimBLE-Mode
The NimBLE mode enables a significant saving of RAM and FLASH memory.
### Comparison (SendKeyStrokes.ino at compile-time)
**Standard**
```
RAM: [= ] 9.3% (used 30548 bytes from 327680 bytes)
Flash: [======== ] 75.8% (used 994120 bytes from 1310720 bytes)
```
**NimBLE mode**
```
RAM: [= ] 8.3% (used 27180 bytes from 327680 bytes)
Flash: [==== ] 44.2% (used 579158 bytes from 1310720 bytes)
```
### Comparison (SendKeyStrokes.ino at run-time)
| | Standard | NimBLE mode | difference
|---|--:|--:|--:|
| `ESP.getHeapSize()` | 296.804 | 321.252 | **+ 24.448** |
| `ESP.getFreeHeap()` | 143.572 | 260.764 | **+ 117.192** |
| `ESP.getSketchSize()` | 994.224 | 579.264 | **- 414.960** |
## How to activate NimBLE mode?
### ArduinoIDE:
Uncomment the first line in BleKeyboard.h
```C++
#define USE_NIMBLE
```
### PlatformIO:
Change your `platformio.ini` to the following settings
```ini
lib_deps =
NimBLE-Arduino
build_flags =
-D USE_NIMBLE
```
## Credits
Credits to [chegewara](https://github.com/chegewara) and [the authors of the USB keyboard library](https://github.com/arduino-libraries/Keyboard/) as this project is heavily based on their work!
Also, credits to [duke2421](https://github.com/T-vK/ESP32-BLE-Keyboard/issues/1) who helped a lot with testing, debugging and fixing the device descriptor!
And credits to [sivar2311](https://github.com/sivar2311) for adding NimBLE support, greatly reducing the memory footprint, fixing advertising issues and for adding the `setDelay` method.

View file

@ -0,0 +1,46 @@
/**
* This example turns the ESP32 into a Bluetooth LE keyboard that writes the words, presses Enter, presses a media key and then Ctrl+Alt+Delete
*/
#include <BleKeyboard.h>
BleKeyboard bleKeyboard;
void setup() {
Serial.begin(115200);
Serial.println("Starting BLE work!");
bleKeyboard.begin();
}
void loop() {
if(bleKeyboard.isConnected()) {
Serial.println("Sending 'Hello world'...");
bleKeyboard.print("Hello world");
delay(1000);
Serial.println("Sending Enter key...");
bleKeyboard.write(KEY_RETURN);
delay(1000);
Serial.println("Sending Play/Pause media key...");
bleKeyboard.write(KEY_MEDIA_PLAY_PAUSE);
delay(1000);
//
// Below is an example of pressing multiple keyboard modifiers
// which by default is commented out.
/*
Serial.println("Sending Ctrl+Alt+Delete...");
bleKeyboard.press(KEY_LEFT_CTRL);
bleKeyboard.press(KEY_LEFT_ALT);
bleKeyboard.press(KEY_DELETE);
delay(100);
bleKeyboard.releaseAll();
*/
}
Serial.println("Waiting 5 seconds...");
delay(5000);
}

View file

@ -0,0 +1,24 @@
#######################################
# Syntax Coloring Map For ESP32 BLE Keyboard
#######################################
# Class
#######################################
BleKeyboard KEYWORD1
#######################################
# Methods and Functions
#######################################
begin KEYWORD2
end KEYWORD2
write KEYWORD2
press KEYWORD2
release KEYWORD2
releaseAll KEYWORD2
setBatteryLevel KEYWORD2
isConnected KEYWORD2
#######################################
# Constants
#######################################

View file

@ -0,0 +1,9 @@
name=ESP32 BLE Keyboard
version=0.3.2
author=T-vK
maintainer=T-vK
sentence=Bluetooth LE Keyboard library for the ESP32.
paragraph=Bluetooth LE Keyboard library for the ESP32.
category=Communication
url=https://github.com/T-vK/ESP32-BLE-Keyboard
architectures=esp32

View file

@ -0,0 +1,675 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View file

@ -0,0 +1,9 @@
## Keypad library for Arduino
**Authors:** *Mark Stanley***,** *Alexander Brevig*
This repository is a copy of the code found here [[Arduino Playground]](http://playground.arduino.cc/Code/Keypad).
The source and file structure has been modified to conform to the newer `1.5r2` library specification and is not compatible with legacy IDE's.
For these IDE's, visit the link above to grab the pre `1.0` compatible version, or download it directly here: [[pre `1.0` version]](http://playground.arduino.cc/uploads/Code/keypad.zip).

View file

@ -0,0 +1,37 @@
/* @file CustomKeypad.pde
|| @version 1.0
|| @author Alexander Brevig
|| @contact alexanderbrevig@gmail.com
||
|| @description
|| | Demonstrates changing the keypad size and key values.
|| #
*/
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
{'0','1','2','3'},
{'4','5','6','7'},
{'8','9','A','B'},
{'C','D','E','F'}
};
byte rowPins[ROWS] = {3, 2, 1, 0}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {7, 6, 5, 4}; //connect to the column pinouts of the keypad
//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
void setup(){
Serial.begin(9600);
}
void loop(){
char customKey = customKeypad.getKey();
if (customKey){
Serial.println(customKey);
}
}

View file

@ -0,0 +1,213 @@
/* @file DynamicKeypad.pde
|| @version 1.2
|| @author Mark Stanley
|| @contact mstanley@technologist.com
||
|| 07/11/12 - Re-modified (from DynamicKeypadJoe2) to use direct-connect kpds
|| 02/28/12 - Modified to use I2C i/o G. D. (Joe) Young
||
||
|| @dificulty: Intermediate
||
|| @description
|| | This is a demonstration of keypadEvents. It's used to switch between keymaps
|| | while using only one keypad. The main concepts being demonstrated are:
|| |
|| | Using the keypad events, PRESSED, HOLD and RELEASED to simplify coding.
|| | How to use setHoldTime() and why.
|| | Making more than one thing happen with the same key.
|| | Assigning and changing keymaps on the fly.
|| |
|| | Another useful feature is also included with this demonstration although
|| | it's not really one of the concepts that I wanted to show you. If you look
|| | at the code in the PRESSED event you will see that the first section of that
|| | code is used to scroll through three different letters on each key. For
|| | example, pressing the '2' key will step through the letters 'd', 'e' and 'f'.
|| |
|| |
|| | Using the keypad events, PRESSED, HOLD and RELEASED to simplify coding
|| | Very simply, the PRESSED event occurs imediately upon detecting a pressed
|| | key and will not happen again until after a RELEASED event. When the HOLD
|| | event fires it always falls between PRESSED and RELEASED. However, it will
|| | only occur if a key has been pressed for longer than the setHoldTime() interval.
|| |
|| | How to use setHoldTime() and why
|| | Take a look at keypad.setHoldTime(500) in the code. It is used to set the
|| | time delay between a PRESSED event and the start of a HOLD event. The value
|| | 500 is in milliseconds (mS) and is equivalent to half a second. After pressing
|| | a key for 500mS the HOLD event will fire and any code contained therein will be
|| | executed. This event will stay active for as long as you hold the key except
|| | in the case of bug #1 listed above.
|| |
|| | Making more than one thing happen with the same key.
|| | If you look under the PRESSED event (case PRESSED:) you will see that the '#'
|| | is used to print a new line, Serial.println(). But take a look at the first
|| | half of the HOLD event and you will see the same key being used to switch back
|| | and forth between the letter and number keymaps that were created with alphaKeys[4][5]
|| | and numberKeys[4][5] respectively.
|| |
|| | Assigning and changing keymaps on the fly
|| | You will see that the '#' key has been designated to perform two different functions
|| | depending on how long you hold it down. If you press the '#' key for less than the
|| | setHoldTime() then it will print a new line. However, if you hold if for longer
|| | than that it will switch back and forth between numbers and letters. You can see the
|| | keymap changes in the HOLD event.
|| |
|| |
|| | In addition...
|| | You might notice a couple of things that you won't find in the Arduino language
|| | reference. The first would be #include <ctype.h>. This is a standard library from
|| | the C programming language and though I don't normally demonstrate these types of
|| | things from outside the Arduino language reference I felt that its use here was
|| | justified by the simplicity that it brings to this sketch.
|| | That simplicity is provided by the two calls to isalpha(key) and isdigit(key).
|| | The first one is used to decide if the key that was pressed is any letter from a-z
|| | or A-Z and the second one decides if the key is any number from 0-9. The return
|| | value from these two functions is either a zero or some positive number greater
|| | than zero. This makes it very simple to test a key and see if it is a number or
|| | a letter. So when you see the following:
|| |
|| | if (isalpha(key)) // this tests to see if your key was a letter
|| |
|| | And the following may be more familiar to some but it is equivalent:
|| |
|| | if (isalpha(key) != 0) // this tests to see if your key was a letter
|| |
|| | And Finally...
|| | To better understand how the event handler affects your code you will need to remember
|| | that it gets called only when you press, hold or release a key. However, once a key
|| | is pressed or held then the event handler gets called at the full speed of the loop().
|| |
|| #
*/
#include <Keypad.h>
#include <ctype.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
// Define the keymaps. The blank spot (lower left) is the space character.
char alphaKeys[ROWS][COLS] = {
{ 'a','d','g' },
{ 'j','m','p' },
{ 's','v','y' },
{ ' ','.','#' }
};
char numberKeys[ROWS][COLS] = {
{ '1','2','3' },
{ '4','5','6' },
{ '7','8','9' },
{ ' ','0','#' }
};
boolean alpha = false; // Start with the numeric keypad.
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad
// Create two new keypads, one is a number pad and the other is a letter pad.
Keypad numpad( makeKeymap(numberKeys), rowPins, colPins, sizeof(rowPins), sizeof(colPins) );
Keypad ltrpad( makeKeymap(alphaKeys), rowPins, colPins, sizeof(rowPins), sizeof(colPins) );
unsigned long startTime;
const byte ledPin = 13; // Use the LED on pin 13.
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW); // Turns the LED on.
ltrpad.begin( makeKeymap(alphaKeys) );
numpad.begin( makeKeymap(numberKeys) );
ltrpad.addEventListener(keypadEvent_ltr); // Add an event listener.
ltrpad.setHoldTime(500); // Default is 1000mS
numpad.addEventListener(keypadEvent_num); // Add an event listener.
numpad.setHoldTime(500); // Default is 1000mS
}
char key;
void loop() {
if( alpha )
key = ltrpad.getKey( );
else
key = numpad.getKey( );
if (alpha && millis()-startTime>100) { // Flash the LED if we are using the letter keymap.
digitalWrite(ledPin,!digitalRead(ledPin));
startTime = millis();
}
}
static char virtKey = NO_KEY; // Stores the last virtual key press. (Alpha keys only)
static char physKey = NO_KEY; // Stores the last physical key press. (Alpha keys only)
static char buildStr[12];
static byte buildCount;
static byte pressCount;
static byte kpadState;
// Take care of some special events.
void keypadEvent_ltr(KeypadEvent key) {
// in here when in alpha mode.
kpadState = ltrpad.getState( );
swOnState( key );
} // end ltrs keypad events
void keypadEvent_num( KeypadEvent key ) {
// in here when using number keypad
kpadState = numpad.getState( );
swOnState( key );
} // end numbers keypad events
void swOnState( char key ) {
switch( kpadState ) {
case PRESSED:
if (isalpha(key)) { // This is a letter key so we're using the letter keymap.
if (physKey != key) { // New key so start with the first of 3 characters.
pressCount = 0;
virtKey = key;
physKey = key;
}
else { // Pressed the same key again...
virtKey++; // so select the next character on that key.
pressCount++; // Tracks how many times we press the same key.
}
if (pressCount > 2) { // Last character reached so cycle back to start.
pressCount = 0;
virtKey = key;
}
Serial.print(virtKey); // Used for testing.
}
if (isdigit(key) || key == ' ' || key == '.')
Serial.print(key);
if (key == '#')
Serial.println();
break;
case HOLD:
if (key == '#') { // Toggle between keymaps.
if (alpha == true) { // We are currently using a keymap with letters
alpha = false; // Now we want a keymap with numbers.
digitalWrite(ledPin, LOW);
}
else { // We are currently using a keymap with numbers
alpha = true; // Now we want a keymap with letters.
}
}
else { // Some key other than '#' was pressed.
buildStr[buildCount++] = (isalpha(key)) ? virtKey : key;
buildStr[buildCount] = '\0';
Serial.println();
Serial.println(buildStr);
}
break;
case RELEASED:
if (buildCount >= sizeof(buildStr)) buildCount = 0; // Our string is full. Start fresh.
break;
} // end switch-case
}// end switch on state function

View file

@ -0,0 +1,73 @@
/* @file EventSerialKeypad.pde
|| @version 1.0
|| @author Alexander Brevig
|| @contact alexanderbrevig@gmail.com
||
|| @description
|| | Demonstrates using the KeypadEvent.
|| #
*/
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
byte ledPin = 13;
boolean blink = false;
boolean ledPin_state;
void setup(){
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // Sets the digital pin as output.
digitalWrite(ledPin, HIGH); // Turn the LED on.
ledPin_state = digitalRead(ledPin); // Store initial LED state. HIGH when LED is on.
keypad.addEventListener(keypadEvent); // Add an event listener for this keypad
}
void loop(){
char key = keypad.getKey();
if (key) {
Serial.println(key);
}
if (blink){
digitalWrite(ledPin,!digitalRead(ledPin)); // Change the ledPin from Hi2Lo or Lo2Hi.
delay(100);
}
}
// Taking care of some special events.
void keypadEvent(KeypadEvent key){
switch (keypad.getState()){
case PRESSED:
if (key == '#') {
digitalWrite(ledPin,!digitalRead(ledPin));
ledPin_state = digitalRead(ledPin); // Remember LED state, lit or unlit.
}
break;
case RELEASED:
if (key == '*') {
digitalWrite(ledPin,ledPin_state); // Restore LED state from before it started blinking.
blink = false;
}
break;
case HOLD:
if (key == '*') {
blink = true; // Blink the LED when holding the * key.
}
break;
}
}

View file

@ -0,0 +1,35 @@
/* @file HelloKeypad.pde
|| @version 1.0
|| @author Alexander Brevig
|| @contact alexanderbrevig@gmail.com
||
|| @description
|| | Demonstrates the simplest use of the matrix Keypad library.
|| #
*/
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup(){
Serial.begin(9600);
}
void loop(){
char key = keypad.getKey();
if (key){
Serial.println(key);
}
}

View file

@ -0,0 +1,68 @@
#include <Keypad.h>
const byte ROWS = 2; // use 4X4 keypad for both instances
const byte COLS = 2;
char keys[ROWS][COLS] = {
{'1','2'},
{'3','4'}
};
byte rowPins[ROWS] = {5, 4}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {7, 6}; //connect to the column pinouts of the keypad
Keypad kpd( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const byte ROWSR = 2;
const byte COLSR = 2;
char keysR[ROWSR][COLSR] = {
{'a','b'},
{'c','d'}
};
byte rowPinsR[ROWSR] = {3, 2}; //connect to the row pinouts of the keypad
byte colPinsR[COLSR] = {7, 6}; //connect to the column pinouts of the keypad
Keypad kpdR( makeKeymap(keysR), rowPinsR, colPinsR, ROWSR, COLSR );
const byte ROWSUR = 4;
const byte COLSUR = 1;
char keysUR[ROWSUR][COLSUR] = {
{'M'},
{'A'},
{'R'},
{'K'}
};
// Digitran keypad, bit numbers of PCF8574 i/o port
byte rowPinsUR[ROWSUR] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPinsUR[COLSUR] = {8}; //connect to the column pinouts of the keypad
Keypad kpdUR( makeKeymap(keysUR), rowPinsUR, colPinsUR, ROWSUR, COLSUR );
void setup(){
// Wire.begin( );
kpdUR.begin( makeKeymap(keysUR) );
kpdR.begin( makeKeymap(keysR) );
kpd.begin( makeKeymap(keys) );
Serial.begin(9600);
Serial.println( "start" );
}
//byte alternate = false;
char key, keyR, keyUR;
void loop(){
// alternate = !alternate;
key = kpd.getKey( );
keyUR = kpdUR.getKey( );
keyR = kpdR.getKey( );
if (key){
Serial.println(key);
}
if( keyR ) {
Serial.println( keyR );
}
if( keyUR ) {
Serial.println( keyUR );
}
}

View file

@ -0,0 +1,78 @@
/* @file MultiKey.ino
|| @version 1.0
|| @author Mark Stanley
|| @contact mstanley@technologist.com
||
|| @description
|| | The latest version, 3.0, of the keypad library supports up to 10
|| | active keys all being pressed at the same time. This sketch is an
|| | example of how you can get multiple key presses from a keypad or
|| | keyboard.
|| #
*/
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the kpd
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the kpd
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
unsigned long loopCount;
unsigned long startTime;
String msg;
void setup() {
Serial.begin(9600);
loopCount = 0;
startTime = millis();
msg = "";
}
void loop() {
loopCount++;
if ( (millis()-startTime)>5000 ) {
Serial.print("Average loops per second = ");
Serial.println(loopCount/5);
startTime = millis();
loopCount = 0;
}
// Fills kpd.key[ ] array with up-to 10 active keys.
// Returns true if there are ANY active keys.
if (kpd.getKeys())
{
for (int i=0; i<LIST_MAX; i++) // Scan the whole key list.
{
if ( kpd.key[i].stateChanged ) // Only find keys that have changed state.
{
switch (kpd.key[i].kstate) { // Report active key state : IDLE, PRESSED, HOLD, or RELEASED
case PRESSED:
msg = " PRESSED.";
break;
case HOLD:
msg = " HOLD.";
break;
case RELEASED:
msg = " RELEASED.";
break;
case IDLE:
msg = " IDLE.";
}
Serial.print("Key ");
Serial.print(kpd.key[i].kchar);
Serial.println(msg);
}
}
}
} // End loop

View file

@ -0,0 +1,46 @@
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
unsigned long loopCount = 0;
unsigned long timer_ms = 0;
void setup(){
Serial.begin(9600);
// Try playing with different debounceTime settings to see how it affects
// the number of times per second your loop will run. The library prevents
// setting it to anything below 1 millisecond.
kpd.setDebounceTime(10); // setDebounceTime(mS)
}
void loop(){
char key = kpd.getKey();
// Report the number of times through the loop in 1 second. This will give
// you a relative idea of just how much the debounceTime has changed the
// speed of your code. If you set a high debounceTime your loopCount will
// look good but your keypresses will start to feel sluggish.
if ((millis() - timer_ms) > 1000) {
Serial.print("Your loop code ran ");
Serial.print(loopCount);
Serial.println(" times over the last second");
loopCount = 0;
timer_ms = millis();
}
loopCount++;
if(key)
Serial.println(key);
}

View file

@ -0,0 +1,38 @@
# Keypad Library data types
KeyState KEYWORD1
Keypad KEYWORD1
KeypadEvent KEYWORD1
# Keypad Library constants
NO_KEY LITERAL1
IDLE LITERAL1
PRESSED LITERAL1
HOLD LITERAL1
RELEASED LITERAL1
# Keypad Library methods & functions
addEventListener KEYWORD2
bitMap KEYWORD2
findKeyInList KEYWORD2
getKey KEYWORD2
getKeys KEYWORD2
getState KEYWORD2
holdTimer KEYWORD2
isPressed KEYWORD2
keyStateChanged KEYWORD2
numKeys KEYWORD2
pin_mode KEYWORD2
pin_write KEYWORD2
pin_read KEYWORD2
setDebounceTime KEYWORD2
setHoldTime KEYWORD2
waitForKey KEYWORD2
# this is a macro that converts 2d arrays to pointers
makeKeymap KEYWORD2
# List of objects created in the example sketches.
kpd KEYWORD3
keypad KEYWORD3
kbrd KEYWORD3
keyboard KEYWORD3

View file

@ -0,0 +1,9 @@
name=Keypad
version=3.1.1
author=Mark Stanley, Alexander Brevig
maintainer=Community https://github.com/Chris--A/Keypad
sentence=Keypad is a library for using matrix style keypads with the Arduino.
paragraph=As of version 3.0 it now supports mulitple keypresses. This library is based upon the Keypad Tutorial. It was created to promote Hardware Abstraction. It improves readability of the code by hiding the pinMode and digitalRead calls for the user.
category=Device Control
url=http://playground.arduino.cc/Code/Keypad
architectures=*

View file

@ -0,0 +1,61 @@
/*
|| @file Key.cpp
|| @version 1.0
|| @author Mark Stanley
|| @contact mstanley@technologist.com
||
|| @description
|| | Key class provides an abstract definition of a key or button
|| | and was initially designed to be used in conjunction with a
|| | state-machine.
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|| #
||
*/
#include <Key.h>
// default constructor
Key::Key() {
kchar = NO_KEY;
kstate = IDLE;
stateChanged = false;
}
// constructor
Key::Key(char userKeyChar) {
kchar = userKeyChar;
kcode = -1;
kstate = IDLE;
stateChanged = false;
}
void Key::key_update (char userKeyChar, KeyState userState, boolean userStatus) {
kchar = userKeyChar;
kstate = userState;
stateChanged = userStatus;
}
/*
|| @changelog
|| | 1.0 2012-06-04 - Mark Stanley : Initial Release
|| #
*/

View file

@ -0,0 +1,68 @@
/*
||
|| @file Key.h
|| @version 1.0
|| @author Mark Stanley
|| @contact mstanley@technologist.com
||
|| @description
|| | Key class provides an abstract definition of a key or button
|| | and was initially designed to be used in conjunction with a
|| | state-machine.
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|| #
||
*/
#ifndef Keypadlib_KEY_H_
#define Keypadlib_KEY_H_
#include <Arduino.h>
#define OPEN LOW
#define CLOSED HIGH
typedef unsigned int uint;
typedef enum{ IDLE, PRESSED, HOLD, RELEASED } KeyState;
const char NO_KEY = '\0';
class Key {
public:
// members
char kchar;
int kcode;
KeyState kstate;
boolean stateChanged;
// methods
Key();
Key(char userKeyChar);
void key_update(char userKeyChar, KeyState userState, boolean userStatus);
private:
};
#endif
/*
|| @changelog
|| | 1.0 2012-06-04 - Mark Stanley : Initial Release
|| #
*/

View file

@ -0,0 +1,306 @@
/*
||
|| @file Keypad.cpp
|| @version 3.1
|| @author Mark Stanley, Alexander Brevig
|| @contact mstanley@technologist.com, alexanderbrevig@gmail.com
||
|| @description
|| | This library provides a simple interface for using matrix
|| | keypads. It supports multiple keypresses while maintaining
|| | backwards compatibility with the old single key library.
|| | It also supports user selectable pins and definable keymaps.
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|| #
||
*/
#include <Keypad.h>
// <<constructor>> Allows custom keymap, pin configuration, and keypad sizes.
Keypad::Keypad(char *userKeymap, byte *row, byte *col, byte numRows, byte numCols) {
rowPins = row;
columnPins = col;
sizeKpd.rows = numRows;
sizeKpd.columns = numCols;
begin(userKeymap);
setDebounceTime(10);
setHoldTime(500);
keypadEventListener = 0;
startTime = 0;
single_key = false;
}
// Let the user define a keymap - assume the same row/column count as defined in constructor
void Keypad::begin(char *userKeymap) {
keymap = userKeymap;
}
// Returns a single key only. Retained for backwards compatibility.
char Keypad::getKey() {
single_key = true;
if (getKeys() && key[0].stateChanged && (key[0].kstate==PRESSED))
return key[0].kchar;
single_key = false;
return NO_KEY;
}
// Populate the key list.
bool Keypad::getKeys() {
bool keyActivity = false;
// Limit how often the keypad is scanned. This makes the loop() run 10 times as fast.
if ( (millis()-startTime)>debounceTime ) {
scanKeys();
keyActivity = updateList();
startTime = millis();
}
return keyActivity;
}
// Private : Hardware scan
void Keypad::scanKeys() {
// Re-intialize the row pins. Allows sharing these pins with other hardware.
for (byte r=0; r<sizeKpd.rows; r++) {
// Logic needs to be inverted. This way the ESP32s EXT1 wakeup can be used to detect if the accelerometer pin or any button pin goes high
// original from Keypad
// pin_mode(rowPins[r],INPUT_PULLUP);
// changed for usage in OMOTE
pin_mode(rowPins[r],INPUT);
}
// bitMap stores ALL the keys that are being pressed.
for (byte c=0; c<sizeKpd.columns; c++) {
pin_mode(columnPins[c],OUTPUT);
// original from Keypad
// pin_write(columnPins[c], LOW); // Begin column pulse output.
// changed for usage in OMOTE
pin_write(columnPins[c], HIGH); // Begin column pulse output.
for (byte r=0; r<sizeKpd.rows; r++) {
// original from Keypad
// bitWrite(bitMap[r], c, !pin_read(rowPins[r])); // keypress is active low so invert to high.
// changed for usage in OMOTE
bitWrite(bitMap[r], c, pin_read(rowPins[r])); // keypress is active low so invert to high.
}
// Set pin to high impedance input. Effectively ends column pulse.
// original from Keypad
// pin_write(columnPins[c],HIGH);
// changed for usage in OMOTE
pin_write(columnPins[c], LOW);
pin_mode(columnPins[c],INPUT);
}
}
// Manage the list without rearranging the keys. Returns true if any keys on the list changed state.
bool Keypad::updateList() {
bool anyActivity = false;
// Delete any IDLE keys
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].kstate==IDLE) {
key[i].kchar = NO_KEY;
key[i].kcode = -1;
key[i].stateChanged = false;
}
}
// Add new keys to empty slots in the key list.
for (byte r=0; r<sizeKpd.rows; r++) {
for (byte c=0; c<sizeKpd.columns; c++) {
boolean button = bitRead(bitMap[r],c);
char keyChar = keymap[r * sizeKpd.columns + c];
int keyCode = r * sizeKpd.columns + c;
int idx = findInList (keyCode);
// Key is already on the list so set its next state.
if (idx > -1) {
nextKeyState(idx, button);
}
// Key is NOT on the list so add it.
if ((idx == -1) && button) {
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].kchar==NO_KEY) { // Find an empty slot or don't add key to list.
key[i].kchar = keyChar;
key[i].kcode = keyCode;
key[i].kstate = IDLE; // Keys NOT on the list have an initial state of IDLE.
nextKeyState (i, button);
break; // Don't fill all the empty slots with the same key.
}
}
}
}
}
// Report if the user changed the state of any key.
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].stateChanged) anyActivity = true;
}
return anyActivity;
}
// Private
// This function is a state machine but is also used for debouncing the keys.
void Keypad::nextKeyState(byte idx, boolean button) {
key[idx].stateChanged = false;
switch (key[idx].kstate) {
case IDLE:
if (button==CLOSED) {
transitionTo (idx, PRESSED);
holdTimer = millis(); } // Get ready for next HOLD state.
break;
case PRESSED:
if ((millis()-holdTimer)>holdTime) // Waiting for a key HOLD...
transitionTo (idx, HOLD);
else if (button==OPEN) // or for a key to be RELEASED.
transitionTo (idx, RELEASED);
break;
case HOLD:
if (button==OPEN)
transitionTo (idx, RELEASED);
break;
case RELEASED:
transitionTo (idx, IDLE);
break;
}
}
// New in 2.1
bool Keypad::isPressed(char keyChar) {
for (byte i=0; i<LIST_MAX; i++) {
if ( key[i].kchar == keyChar ) {
if ( (key[i].kstate == PRESSED) && key[i].stateChanged )
return true;
}
}
return false; // Not pressed.
}
// Search by character for a key in the list of active keys.
// Returns -1 if not found or the index into the list of active keys.
int Keypad::findInList (char keyChar) {
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].kchar == keyChar) {
return i;
}
}
return -1;
}
// Search by code for a key in the list of active keys.
// Returns -1 if not found or the index into the list of active keys.
int Keypad::findInList (int keyCode) {
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].kcode == keyCode) {
return i;
}
}
return -1;
}
// New in 2.0
char Keypad::waitForKey() {
char waitKey = NO_KEY;
while( (waitKey = getKey()) == NO_KEY ); // Block everything while waiting for a keypress.
return waitKey;
}
// Backwards compatibility function.
KeyState Keypad::getState() {
return key[0].kstate;
}
// The end user can test for any changes in state before deciding
// if any variables, etc. needs to be updated in their code.
bool Keypad::keyStateChanged() {
return key[0].stateChanged;
}
// The number of keys on the key list, key[LIST_MAX], equals the number
// of bytes in the key list divided by the number of bytes in a Key object.
byte Keypad::numKeys() {
return sizeof(key)/sizeof(Key);
}
// Minimum debounceTime is 1 mS. Any lower *will* slow down the loop().
void Keypad::setDebounceTime(uint debounce) {
debounce<1 ? debounceTime=1 : debounceTime=debounce;
}
void Keypad::setHoldTime(uint hold) {
holdTime = hold;
}
void Keypad::addEventListener(void (*listener)(char)){
keypadEventListener = listener;
}
void Keypad::transitionTo(byte idx, KeyState nextState) {
key[idx].kstate = nextState;
key[idx].stateChanged = true;
// Sketch used the getKey() function.
// Calls keypadEventListener only when the first key in slot 0 changes state.
if (single_key) {
if ( (keypadEventListener!=NULL) && (idx==0) ) {
keypadEventListener(key[0].kchar);
}
}
// Sketch used the getKeys() function.
// Calls keypadEventListener on any key that changes state.
else {
if (keypadEventListener!=NULL) {
keypadEventListener(key[idx].kchar);
}
}
}
/*
|| @changelog
|| | 3.1 2013-01-15 - Mark Stanley : Fixed missing RELEASED & IDLE status when using a single key.
|| | 3.0 2012-07-12 - Mark Stanley : Made library multi-keypress by default. (Backwards compatible)
|| | 3.0 2012-07-12 - Mark Stanley : Modified pin functions to support Keypad_I2C
|| | 3.0 2012-07-12 - Stanley & Young : Removed static variables. Fix for multiple keypad objects.
|| | 3.0 2012-07-12 - Mark Stanley : Fixed bug that caused shorted pins when pressing multiple keys.
|| | 2.0 2011-12-29 - Mark Stanley : Added waitForKey().
|| | 2.0 2011-12-23 - Mark Stanley : Added the public function keyStateChanged().
|| | 2.0 2011-12-23 - Mark Stanley : Added the private function scanKeys().
|| | 2.0 2011-12-23 - Mark Stanley : Moved the Finite State Machine into the function getKeyState().
|| | 2.0 2011-12-23 - Mark Stanley : Removed the member variable lastUdate. Not needed after rewrite.
|| | 1.8 2011-11-21 - Mark Stanley : Added decision logic to compile WProgram.h or Arduino.h
|| | 1.8 2009-07-08 - Alexander Brevig : No longer uses arrays
|| | 1.7 2009-06-18 - Alexander Brevig : Every time a state changes the keypadEventListener will trigger, if set.
|| | 1.7 2009-06-18 - Alexander Brevig : Added setDebounceTime. setHoldTime specifies the amount of
|| | microseconds before a HOLD state triggers
|| | 1.7 2009-06-18 - Alexander Brevig : Added transitionTo
|| | 1.6 2009-06-15 - Alexander Brevig : Added getState() and state variable
|| | 1.5 2009-05-19 - Alexander Brevig : Added setHoldTime()
|| | 1.4 2009-05-15 - Alexander Brevig : Added addEventListener
|| | 1.3 2009-05-12 - Alexander Brevig : Added lastUdate, in order to do simple debouncing
|| | 1.2 2009-05-09 - Alexander Brevig : Changed getKey()
|| | 1.1 2009-04-28 - Alexander Brevig : Modified API, and made variables private
|| | 1.0 2007-XX-XX - Mark Stanley : Initial Release
|| #
*/

View file

@ -0,0 +1,149 @@
/*
||
|| @file Keypad.h
|| @version 3.1
|| @author Mark Stanley, Alexander Brevig
|| @contact mstanley@technologist.com, alexanderbrevig@gmail.com
||
|| @description
|| | This library provides a simple interface for using matrix
|| | keypads. It supports multiple keypresses while maintaining
|| | backwards compatibility with the old single key library.
|| | It also supports user selectable pins and definable keymaps.
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|| #
||
*/
#ifndef KEYPAD_H
#define KEYPAD_H
#include "Key.h"
// bperrybap - Thanks for a well reasoned argument and the following macro(s).
// See http://arduino.cc/forum/index.php/topic,142041.msg1069480.html#msg1069480
#ifndef INPUT_PULLUP
#warning "Using pinMode() INPUT_PULLUP AVR emulation"
#define INPUT_PULLUP 0x2
#define pinMode(_pin, _mode) _mypinMode(_pin, _mode)
#define _mypinMode(_pin, _mode) \
do { \
if(_mode == INPUT_PULLUP) \
pinMode(_pin, INPUT); \
digitalWrite(_pin, 1); \
if(_mode != INPUT_PULLUP) \
pinMode(_pin, _mode); \
}while(0)
#endif
#define OPEN LOW
#define CLOSED HIGH
typedef char KeypadEvent;
typedef unsigned int uint;
typedef unsigned long ulong;
// Made changes according to this post http://arduino.cc/forum/index.php?topic=58337.0
// by Nick Gammon. Thanks for the input Nick. It actually saved 78 bytes for me. :)
typedef struct {
byte rows;
byte columns;
} KeypadSize;
#define LIST_MAX 10 // Max number of keys on the active list.
#define MAPSIZE 10 // MAPSIZE is the number of rows (times 16 columns)
#define makeKeymap(x) ((char*)x)
//class Keypad : public Key, public HAL_obj {
class Keypad : public Key {
public:
Keypad(char *userKeymap, byte *row, byte *col, byte numRows, byte numCols);
virtual void pin_mode(byte pinNum, byte mode) { pinMode(pinNum, mode); }
virtual void pin_write(byte pinNum, boolean level) { digitalWrite(pinNum, level); }
virtual int pin_read(byte pinNum) { return digitalRead(pinNum); }
uint bitMap[MAPSIZE]; // 10 row x 16 column array of bits. Except Due which has 32 columns.
Key key[LIST_MAX];
unsigned long holdTimer;
char getKey();
bool getKeys();
KeyState getState();
void begin(char *userKeymap);
bool isPressed(char keyChar);
void setDebounceTime(uint);
void setHoldTime(uint);
void addEventListener(void (*listener)(char));
int findInList(char keyChar);
int findInList(int keyCode);
char waitForKey();
bool keyStateChanged();
byte numKeys();
private:
unsigned long startTime;
char *keymap;
byte *rowPins;
byte *columnPins;
KeypadSize sizeKpd;
uint debounceTime;
uint holdTime;
bool single_key;
void scanKeys();
bool updateList();
void nextKeyState(byte n, boolean button);
void transitionTo(byte n, KeyState nextState);
void (*keypadEventListener)(char);
};
#endif
/*
|| @changelog
|| | 3.1 2013-01-15 - Mark Stanley : Fixed missing RELEASED & IDLE status when using a single key.
|| | 3.0 2012-07-12 - Mark Stanley : Made library multi-keypress by default. (Backwards compatible)
|| | 3.0 2012-07-12 - Mark Stanley : Modified pin functions to support Keypad_I2C
|| | 3.0 2012-07-12 - Stanley & Young : Removed static variables. Fix for multiple keypad objects.
|| | 3.0 2012-07-12 - Mark Stanley : Fixed bug that caused shorted pins when pressing multiple keys.
|| | 2.0 2011-12-29 - Mark Stanley : Added waitForKey().
|| | 2.0 2011-12-23 - Mark Stanley : Added the public function keyStateChanged().
|| | 2.0 2011-12-23 - Mark Stanley : Added the private function scanKeys().
|| | 2.0 2011-12-23 - Mark Stanley : Moved the Finite State Machine into the function getKeyState().
|| | 2.0 2011-12-23 - Mark Stanley : Removed the member variable lastUdate. Not needed after rewrite.
|| | 1.8 2011-11-21 - Mark Stanley : Added test to determine which header file to compile,
|| | WProgram.h or Arduino.h.
|| | 1.8 2009-07-08 - Alexander Brevig : No longer uses arrays
|| | 1.7 2009-06-18 - Alexander Brevig : This library is a Finite State Machine every time a state changes
|| | the keypadEventListener will trigger, if set
|| | 1.7 2009-06-18 - Alexander Brevig : Added setDebounceTime setHoldTime specifies the amount of
|| | microseconds before a HOLD state triggers
|| | 1.7 2009-06-18 - Alexander Brevig : Added transitionTo
|| | 1.6 2009-06-15 - Alexander Brevig : Added getState() and state variable
|| | 1.5 2009-05-19 - Alexander Brevig : Added setHoldTime()
|| | 1.4 2009-05-15 - Alexander Brevig : Added addEventListener
|| | 1.3 2009-05-12 - Alexander Brevig : Added lastUdate, in order to do simple debouncing
|| | 1.2 2009-05-09 - Alexander Brevig : Changed getKey()
|| | 1.1 2009-04-28 - Alexander Brevig : Modified API, and made variables private
|| | 1.0 2007-XX-XX - Mark Stanley : Initial Release
|| #
*/

View file

@ -0,0 +1,90 @@
#include <lvgl.h>
#include "tft_hal_esp32.h"
#include "sleep_hal_esp32.h"
// -----------------------
// https://docs.lvgl.io/8.3/porting/display.html?highlight=lv_disp_draw_buf_init#buffering-modes
// With two buffers, the rendering and refreshing of the display become parallel operations
// Second buffer needs 15.360 bytes more memory in heap.
#define useTwoBuffersForlvgl
// Display flushing
void my_disp_flush( lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p ){
uint32_t w = ( area->x2 - area->x1 + 1 );
uint32_t h = ( area->y2 - area->y1 + 1 );
tft.startWrite();
tft.setAddrWindow(area->x1, area->y1, w, h);
#ifdef useTwoBuffersForlvgl
tft.pushPixelsDMA((uint16_t*)&color_p->full, w * h);
#else
tft.pushColors((uint16_t*)&color_p->full, w * h, true);
#endif
tft.endWrite();
lv_disp_flush_ready( disp );
}
// Read the touchpad
void my_touchpad_read(lv_indev_drv_t * indev_driver, lv_indev_data_t * data){
int16_t touchX;
int16_t touchY;
get_touchpoint(&touchX, &touchY);
bool touched = false;
if ((touchX > 0) || (touchY > 0)) {
touched = true;
setLastActivityTimestamp_HAL();
}
if( !touched ){
data->state = LV_INDEV_STATE_REL;
}
else{
data->state = LV_INDEV_STATE_PR;
// Set the coordinates
data->point.x = SCR_WIDTH - touchX;
data->point.y = SCR_HEIGHT - touchY;
//Serial.print( "touchpoint: x" );
//Serial.print( touchX );
//Serial.print( " y" );
//Serial.println( touchY );
//tft.drawFastHLine(0, SCR_HEIGHT - touchY, SCR_WIDTH, TFT_RED);
//tft.drawFastVLine(SCR_WIDTH - touchX, 0, SCR_HEIGHT, TFT_RED);
}
}
static lv_disp_draw_buf_t draw_buf;
void init_lvgl_HAL() {
// first init TFT
init_tft();
#ifdef useTwoBuffersForlvgl
lv_color_t * bufA = (lv_color_t *) malloc(sizeof(lv_color_t) * SCR_WIDTH * SCR_HEIGHT / 10);
lv_color_t * bufB = (lv_color_t *) malloc(sizeof(lv_color_t) * SCR_WIDTH * SCR_HEIGHT / 10);
lv_disp_draw_buf_init(&draw_buf, bufA, bufB, SCR_WIDTH * SCR_HEIGHT / 10);
#else
lv_color_t * bufA = (lv_color_t *) malloc(sizeof(lv_color_t) * SCR_WIDTH * SCR_HEIGHT / 10);
lv_disp_draw_buf_init(&draw_buf, bufA, NULL, SCR_WIDTH * SCR_HEIGHT / 10);
#endif
// Initialize the display driver --------------------------------------------------------------------------
static lv_disp_drv_t disp_drv;
lv_disp_drv_init( &disp_drv );
disp_drv.hor_res = SCR_WIDTH;
disp_drv.ver_res = SCR_HEIGHT;
disp_drv.flush_cb = my_disp_flush;
disp_drv.draw_buf = &draw_buf;
lv_disp_drv_register( &disp_drv );
// Initialize the touchscreen driver
static lv_indev_drv_t indev_drv;
lv_indev_drv_init( &indev_drv );
indev_drv.type = LV_INDEV_TYPE_POINTER;
indev_drv.read_cb = my_touchpad_read;
lv_indev_drv_register( &indev_drv );
}

View file

@ -0,0 +1,3 @@
#pragma once
void init_lvgl_HAL();

View file

@ -1,13 +1,21 @@
#include "WiFi.h"
#include <PubSubClient.h>
#include <lvgl.h>
#include "hardware/mqtt.h"
#include "gui_general_and_keys/guiBase.h"
#include "mqtt_hal_esp32.h"
#include "secrets.h"
#include "commandHandler.h"
#if ENABLE_WIFI_AND_MQTT == 1
#if (ENABLE_WIFI_AND_MQTT == 1)
WiFiClient espClient;
PubSubClient mqttClient(espClient);
bool isWifiConnected = false;
showWiFiconnected_cb thisShowWiFiconnected_cb = NULL;
void set_showWiFiconnected_cb_HAL(showWiFiconnected_cb pShowWiFiconnected_cb) {
thisShowWiFiconnected_cb = pShowWiFiconnected_cb;
}
bool getIsWifiConnected_HAL() {
return isWifiConnected;
}
// WiFi status event
void WiFiEvent(WiFiEvent_t event){
@ -21,11 +29,13 @@ void WiFiEvent(WiFiEvent_t event){
// Set status bar icon based on WiFi status
if (event == ARDUINO_EVENT_WIFI_STA_GOT_IP || event == ARDUINO_EVENT_WIFI_STA_GOT_IP6) {
if (WifiLabel != NULL) {lv_label_set_text(WifiLabel, LV_SYMBOL_WIFI);}
isWifiConnected = true;
thisShowWiFiconnected_cb(true);
Serial.printf("WiFi connected, IP address: %s\r\n", WiFi.localIP().toString().c_str());
} else if (event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) {
if (WifiLabel != NULL) {lv_label_set_text(WifiLabel, "");}
isWifiConnected = false;
thisShowWiFiconnected_cb(false);
// automatically try to reconnect
Serial.printf("WiFi got disconnected. Will try to reconnect.\r\n");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
@ -33,12 +43,13 @@ void WiFiEvent(WiFiEvent_t event){
} else {
// e.g. ARDUINO_EVENT_WIFI_STA_CONNECTED or many others
// connected is not enough, will wait for IP
if (WifiLabel != NULL) {lv_label_set_text(WifiLabel, "");}
isWifiConnected = false;
thisShowWiFiconnected_cb(false);
}
}
void init_mqtt(void) {
void init_mqtt_HAL(void) {
// Setup WiFi
WiFi.setHostname("OMOTE"); //define hostname
WiFi.onEvent(WiFiEvent);
@ -69,7 +80,7 @@ bool checkMQTTconnection() {
}
}
bool publishMQTTMessage(const char *topic, const char *payload){
bool publishMQTTMessage_HAL(const char *topic, const char *payload){
if (checkMQTTconnection()) {
// Serial.printf("Sending mqtt payload to topic \"%s\": %s\r\n", topic, payload);
@ -86,4 +97,10 @@ bool publishMQTTMessage(const char *topic, const char *payload){
}
return false;
}
void wifiStop_HAL() {
WiFi.disconnect();
WiFi.mode(WIFI_OFF);
}
#endif

View file

@ -0,0 +1,14 @@
#pragma once
#if (ENABLE_WIFI_AND_MQTT == 1)
void init_mqtt_HAL(void);
bool getIsWifiConnected_HAL();
bool publishMQTTMessage_HAL(const char *topic, const char *payload);
void wifiStop_HAL();
typedef void (*showWiFiconnected_cb)(bool connected);
void set_showWiFiconnected_cb_HAL(showWiFiconnected_cb pShowWiFiconnected_cb);
#endif

View file

@ -0,0 +1,57 @@
#include <Preferences.h>
#include "sleep_hal_esp32.h"
#include "tft_hal_esp32.h"
Preferences preferences;
std::string currentScene;
std::string currentGUIname;
void init_preferences_HAL(void) {
// Restore settings from internal flash memory
preferences.begin("settings", false);
if (preferences.getBool("alreadySetUp")) {
// from sleep.h
set_wakeupByIMUEnabled_HAL(preferences.getBool("wkpByIMU"));
set_sleepTimeout_HAL(preferences.getUInt("slpTimeout"));
// from tft.h
set_backlightBrightness_HAL(preferences.getUChar("blBrightness"));
// from here
currentScene = std::string(preferences.getString("currentScene").c_str());
currentGUIname = std::string(preferences.getString("currentGUIname").c_str());
// Serial.printf("Preferences restored: brightness %d, GUI %s, scene %s\r\n", get_backlightBrightness_HAL(), get_currentGUIname().c_str(), get_currentScene().c_str());
} else {
// Serial.printf("No preferences to restore\r\n");
}
preferences.end();
}
void save_preferences_HAL(void) {
preferences.begin("settings", false);
// from sleep.h
preferences.putBool("wkpByIMU", get_wakeupByIMUEnabled_HAL());
// from tft.h
preferences.putUInt("slpTimeout", get_sleepTimeout_HAL());
preferences.putUChar("blBrightness", get_backlightBrightness_HAL());
// from here
preferences.putString("currentScene", currentScene.c_str());
preferences.putString("currentGUIname", currentGUIname.c_str());
if (!preferences.getBool("alreadySetUp")) {
preferences.putBool("alreadySetUp", true);
}
preferences.end();
}
std::string get_currentScene_HAL() {
return currentScene;
}
void set_currentScene_HAL(std::string aCurrentScene) {
currentScene = aCurrentScene;
}
std::string get_currentGUIname_HAL(){
return currentGUIname;
}
void set_currentGUIname_HAL(std::string aCurrentGUIname) {
currentGUIname = aCurrentGUIname;
}

View file

@ -0,0 +1,11 @@
#pragma once
#include <string>
void init_preferences_HAL(void);
void save_preferences_HAL(void);
std::string get_currentScene_HAL();
void set_currentScene_HAL(std::string aCurrentScene);
std::string get_currentGUIname_HAL();
void set_currentGUIname_HAL(std::string aCurrentGUIname);

View file

@ -0,0 +1,251 @@
#include <Arduino.h>
#include "SparkFunLIS3DH.h"
#include "sleep_hal_esp32.h"
// before going to sleep, some tasks have to be done
// save settings
#include "preferencesStorage_hal_esp32.h"
// turn off power of IR receiver
#include "infrared_receiver_hal_esp32.h"
// turn off tft
#include "tft_hal_esp32.h"
// disconnect WiFi
#include "mqtt_hal_esp32.h"
// disconnect BLE keyboard
#include "keyboard_ble_hal_esp32.h"
// prepare keypad keys to wakeup
#include "keypad_keys_hal_esp32.h"
// 20 (doesn't exist?) and 13 both work.
// It even works when "pinMode(ACC_INT_GPIO, INPUT);" is not set
uint8_t ACC_INT_GPIO = 20;
int MOTION_THRESHOLD = 50; // motion above threshold keeps device awake
int DEFAULT_SLEEP_TIMEOUT = 20000; // default time until device enters sleep mode in milliseconds. Can be overridden.
// is "lift to wake" enabled
bool wakeupByIMUEnabled = true;
// timeout before going to sleep
uint32_t sleepTimeout;
// Timestamp of the last activity. Go to sleep if (millis() - lastActivityTimestamp > sleepTimeout)
uint32_t lastActivityTimestamp;
LIS3DH IMU(I2C_MODE, 0x19);
Wakeup_reasons wakeup_reason;
void setLastActivityTimestamp_HAL() {
// There was motion, touchpad or key hit.
// Set the time where this happens.
lastActivityTimestamp = millis();
}
void activityDetection() {
// if there is any motion, setLastActivityTimestamp_HAL() is called
int motion = 0;
// A variable declared static inside a function is visible only inside that function, exists only once (not created/destroyed for each call) and is permanent. It is in a sense a private global variable.
static int accXold;
static int accYold;
static int accZold;
int accX = IMU.readFloatAccelX()*1000;
int accY = IMU.readFloatAccelY()*1000;
int accZ = IMU.readFloatAccelZ()*1000;
// determine motion value as da/dt
motion = (abs(accXold - accX) + abs(accYold - accY) + abs(accZold - accZ));
// If the motion exceeds the threshold, the lastActivityTimestamp is updated
if(motion > MOTION_THRESHOLD) {
setLastActivityTimestamp_HAL();
}
// Store the current acceleration and time
accXold = accX;
accYold = accY;
accZold = accZ;
}
void configIMUInterruptsBeforeGoingToSleep()
{
uint8_t dataToWrite = 0;
//LIS3DH_INT1_CFG
//dataToWrite |= 0x80;//AOI, 0 = OR 1 = AND
//dataToWrite |= 0x40;//6D, 0 = interrupt source, 1 = 6 direction source
//Set these to enable individual axes of generation source (or direction)
// -- high and low are used generically
dataToWrite |= 0x20;//Z high
//dataToWrite |= 0x10;//Z low
dataToWrite |= 0x08;//Y high
//dataToWrite |= 0x04;//Y low
dataToWrite |= 0x02;//X high
//dataToWrite |= 0x01;//X low
if (wakeupByIMUEnabled) {
IMU.writeRegister(LIS3DH_INT1_CFG, 0b00101010);
} else {
IMU.writeRegister(LIS3DH_INT1_CFG, 0b00000000);
}
//LIS3DH_INT1_THS
dataToWrite = 0;
//Provide 7 bit value, 0x7F always equals max range by accelRange setting
dataToWrite |= 0x45;
IMU.writeRegister(LIS3DH_INT1_THS, dataToWrite);
//LIS3DH_INT1_DURATION
dataToWrite = 0;
//minimum duration of the interrupt
//LSB equals 1/(sample rate)
dataToWrite |= 0x00; // 1 * 1/50 s = 20ms
IMU.writeRegister(LIS3DH_INT1_DURATION, dataToWrite);
//LIS3DH_CTRL_REG5
//Int1 latch interrupt and 4D on int1 (preserve fifo en)
IMU.readRegister(&dataToWrite, LIS3DH_CTRL_REG5);
dataToWrite &= 0xF3; //Clear bits of interest
dataToWrite |= 0x08; //Latch interrupt (Cleared by reading int1_src)
//dataToWrite |= 0x04; //Pipe 4D detection from 6D recognition to int1?
IMU.writeRegister(LIS3DH_CTRL_REG5, dataToWrite);
//LIS3DH_CTRL_REG3
//Choose source for pin 1
dataToWrite = 0;
//dataToWrite |= 0x80; //Click detect on pin 1
dataToWrite |= 0x40; //AOI1 event (Generator 1 interrupt on pin 1)
dataToWrite |= 0x20; //AOI2 event ()
//dataToWrite |= 0x10; //Data ready
//dataToWrite |= 0x04; //FIFO watermark
//dataToWrite |= 0x02; //FIFO overrun
IMU.writeRegister(LIS3DH_CTRL_REG3, dataToWrite);
}
// Enter Sleep Mode
void enterSleep(){
// Save settings to internal flash memory
save_preferences_HAL();
// Configure IMU
uint8_t intDataRead;
// clear interrupt
IMU.readRegister(&intDataRead, LIS3DH_INT1_SRC);
configIMUInterruptsBeforeGoingToSleep();
// really clear interrupt
IMU.readRegister(&intDataRead, LIS3DH_INT1_SRC);
#if (ENABLE_WIFI_AND_MQTT == 1)
// Power down modem
wifiStop_HAL();
#endif
#if (ENABLE_KEYBOARD_BLE == 1)
keyboardBLE_end_HAL();
#endif
// Prepare IO states
digitalWrite(TFT_DC, LOW); // LCD control signals off
digitalWrite(TFT_CS, LOW);
digitalWrite(TFT_MOSI, LOW);
digitalWrite(TFT_SCLK, LOW);
digitalWrite(LCD_EN_GPIO, HIGH); // LCD logic off
digitalWrite(LCD_BL_GPIO, HIGH); // LCD backlight off
// pinMode(CRG_STAT, INPUT); // Disable Pull-Up
digitalWrite(IR_VCC_GPIO, LOW); // IR Receiver off
// Configure button matrix for ext1 interrupt
pinMode(SW_1_GPIO, OUTPUT);
pinMode(SW_2_GPIO, OUTPUT);
pinMode(SW_3_GPIO, OUTPUT);
pinMode(SW_4_GPIO, OUTPUT);
pinMode(SW_5_GPIO, OUTPUT);
digitalWrite(SW_1_GPIO, HIGH);
digitalWrite(SW_2_GPIO, HIGH);
digitalWrite(SW_3_GPIO, HIGH);
digitalWrite(SW_4_GPIO, HIGH);
digitalWrite(SW_5_GPIO, HIGH);
gpio_hold_en((gpio_num_t)SW_1_GPIO);
gpio_hold_en((gpio_num_t)SW_2_GPIO);
gpio_hold_en((gpio_num_t)SW_3_GPIO);
gpio_hold_en((gpio_num_t)SW_4_GPIO);
gpio_hold_en((gpio_num_t)SW_5_GPIO);
// Force display pins to high impedance
// Without this the display might not wake up from sleep
pinMode(LCD_BL_GPIO, INPUT);
pinMode(LCD_EN_GPIO, INPUT);
gpio_hold_en((gpio_num_t)LCD_BL_GPIO);
gpio_hold_en((gpio_num_t)LCD_EN_GPIO);
gpio_deep_sleep_hold_en();
esp_sleep_enable_ext1_wakeup(BUTTON_PIN_BITMASK, ESP_EXT1_WAKEUP_ANY_HIGH);
delay(100);
// Sleep
esp_deep_sleep_start();
}
void init_sleep_HAL() {
// will be called after boot or wakeup. Releases GPIO hold and sets wakeup_reason
if (sleepTimeout == 0){
sleepTimeout = DEFAULT_SLEEP_TIMEOUT;
}
// Find out wakeup cause
if (esp_sleep_get_wakeup_cause() == ESP_SLEEP_WAKEUP_EXT1) {
if (log(esp_sleep_get_ext1_wakeup_status())/log(2) == 13) {
wakeup_reason = WAKEUP_BY_IMU;
} else {
wakeup_reason = WAKEUP_BY_KEYPAD;
}
} else {
wakeup_reason = WAKEUP_BY_RESET;
}
pinMode(ACC_INT_GPIO, INPUT);
// Release GPIO hold in case we are coming out of standby
gpio_hold_dis((gpio_num_t)SW_1_GPIO);
gpio_hold_dis((gpio_num_t)SW_2_GPIO);
gpio_hold_dis((gpio_num_t)SW_3_GPIO);
gpio_hold_dis((gpio_num_t)SW_4_GPIO);
gpio_hold_dis((gpio_num_t)SW_5_GPIO);
gpio_hold_dis((gpio_num_t)LCD_EN_GPIO);
gpio_hold_dis((gpio_num_t)LCD_BL_GPIO);
gpio_deep_sleep_hold_dis();
}
void init_IMU_HAL(void) {
// setup IMU to recognize motion
IMU.settings.accelSampleRate = 50; //Hz. Can be: 0,1,10,25,50,100,200,400,1600,5000 Hz
IMU.settings.accelRange = 2; //Max G force readable. Can be: 2, 4, 8, 16
IMU.settings.adcEnabled = 0;
IMU.settings.tempEnabled = 0;
IMU.settings.xAccelEnabled = 1;
IMU.settings.yAccelEnabled = 1;
IMU.settings.zAccelEnabled = 1;
IMU.begin();
uint8_t intDataRead;
IMU.readRegister(&intDataRead, LIS3DH_INT1_SRC);//clear interrupt
}
void check_activity_HAL() {
activityDetection();
if(millis() - lastActivityTimestamp > sleepTimeout){
Serial.println("Entering Sleep Mode. Goodbye.");
enterSleep();
}
}
uint32_t get_sleepTimeout_HAL() {
return sleepTimeout;
}
void set_sleepTimeout_HAL(uint32_t aSleepTimeout) {
sleepTimeout = aSleepTimeout;
}
bool get_wakeupByIMUEnabled_HAL() {
return wakeupByIMUEnabled;
}
void set_wakeupByIMUEnabled_HAL(bool aWakeupByIMUEnabled) {
wakeupByIMUEnabled = aWakeupByIMUEnabled;
}
uint32_t get_lastActivityTimestamp() {
return lastActivityTimestamp;
}

View file

@ -0,0 +1,21 @@
#pragma once
#include <Arduino.h>
// wakeup reason
enum Wakeup_reasons{WAKEUP_BY_RESET, WAKEUP_BY_IMU, WAKEUP_BY_KEYPAD};
extern Wakeup_reasons wakeup_reason;
// only called by tft.cpp, needs to know this because tft gets dimmed 2000 ms before going to sleep
uint32_t get_lastActivityTimestamp();
// called from the HAL
void init_sleep_HAL();
void init_IMU_HAL();
void check_activity_HAL();
void setLastActivityTimestamp_HAL();
uint32_t get_sleepTimeout_HAL();
void set_sleepTimeout_HAL(uint32_t aSleepTimeout);
bool get_wakeupByIMUEnabled_HAL();
void set_wakeupByIMUEnabled_HAL(bool aWakeupByIMUEnabled);

View file

@ -0,0 +1,109 @@
#include <Arduino.h>
#include "driver/ledc.h"
#include "tft_hal_esp32.h"
#include "sleep_hal_esp32.h"
uint8_t LCD_BL_GPIO = 4;
uint8_t LCD_EN_GPIO = 10;
TFT_eSPI tft = TFT_eSPI();
Adafruit_FT6206 touch = Adafruit_FT6206();
TS_Point touchPoint;
byte backlightBrightness = 255;
void init_tft(void) {
// this is power for the TFT IC
pinMode(LCD_EN_GPIO, OUTPUT);
digitalWrite(LCD_EN_GPIO, HIGH);
// this is power for backlight LEDs
pinMode(LCD_BL_GPIO, OUTPUT);
digitalWrite(LCD_BL_GPIO, HIGH);
// Configure the backlight PWM
// Manual setup because ledcSetup() briefly turns on the backlight
ledc_channel_config_t ledc_channel_left;
ledc_channel_left.gpio_num = (gpio_num_t)LCD_BL_GPIO;
ledc_channel_left.speed_mode = LEDC_HIGH_SPEED_MODE;
ledc_channel_left.channel = LEDC_CHANNEL_5;
ledc_channel_left.intr_type = LEDC_INTR_DISABLE;
ledc_channel_left.timer_sel = LEDC_TIMER_1;
// LEDC channel duty, the range of duty setting is [0, (2**duty_resolution)]
ledc_channel_left.duty = 0;
// needs to be set to 0, otherwise log message "E (324) ledc: ledc_set_duty_with_hpoint(699): hpoint argument is invalid"
// https://github.com/mudassar-tamboli/ESP32-OV7670-WebSocket-Camera/issues/13
// LEDC channel hpoint value, the max value is 0xfffff
ledc_channel_left.hpoint = 0;
ledc_channel_left.flags.output_invert = 1; // Can't do this with ledcSetup()
// hpoint and duty explained:
// https://miro.medium.com/v2/resize:fit:1400/1*ViqSTFdH9COZ51iKYrIyMA.png
ledc_channel_config(&ledc_channel_left);
ledc_timer_config_t ledc_timer;
ledc_timer.speed_mode = LEDC_HIGH_SPEED_MODE;
ledc_timer.duty_resolution = LEDC_TIMER_8_BIT;
ledc_timer.timer_num = LEDC_TIMER_1;
ledc_timer.freq_hz = 640;
// https://github.com/mudassar-tamboli/ESP32-OV7670-WebSocket-Camera/issues/13
// otherwise crash with "assert failed: ledc_clk_cfg_to_global_clk ledc.c:444 (false)"
ledc_timer.clk_cfg = LEDC_USE_APB_CLK;
esp_err_t err = ledc_timer_config(&ledc_timer);
if (err != ESP_OK) {
Serial.println("Error when calling ledc_timer_config!");
}
#if (OMOTE_HARDWARE_REV == 1)
// Slowly charge the VSW voltage to prevent a brownout
// Workaround for hardware rev 1!
Serial.println("Will slowly charge VSW voltage to prevent that screen is completely bright, with no content");
for(int i = 0; i < 100; i++) {
digitalWrite(LCD_EN_GPIO, HIGH); // LCD Logic off
delayMicroseconds(1);
digitalWrite(LCD_EN_GPIO, LOW); // LCD Logic on
}
#else
Serial.println("Will immediately charge VSW voltage. If screen is completely bright, with no content, then this is the reason.");
digitalWrite(LCD_EN_GPIO, LOW);
#endif
delay(100); // Wait for the LCD driver to power on
tft.init();
tft.initDMA();
tft.setRotation(0);
tft.fillScreen(TFT_BLACK);
tft.setSwapBytes(true);
// Setup touchscreen
touch.begin(128); // Initialize touchscreen and set sensitivity threshold
}
void get_touchpoint(int16_t *touchX, int16_t *touchY) {
touchPoint = touch.getPoint();
*touchX = touchPoint.x;
*touchY = touchPoint.y;
}
void update_backligthBrighness_HAL(void) {
// A variable declared static inside a function is visible only inside that function, exists only once (not created/destroyed for each call) and is permanent. It is in a sense a private global variable.
static int fadeInTimer = millis(); // fadeInTimer = time after setup
if (millis() < fadeInTimer + backlightBrightness) {
// after boot or wakeup, fade in backlight brightness
// fade in lasts for <backlightBrightness> ms
ledcWrite(5, millis() - fadeInTimer);
} else {
if (millis() - get_lastActivityTimestamp() > get_sleepTimeout_HAL() - 2000) {
// less than 2000 ms until standby
// dim backlight
ledcWrite(5, get_backlightBrightness_HAL() * 0.3);
} else {
// normal mode, set full backlightBrightness
ledcWrite(5, backlightBrightness);
}
}
}
uint8_t get_backlightBrightness_HAL() {
return backlightBrightness;
};
void set_backlightBrightness_HAL(uint8_t aBacklightBrightness) {
backlightBrightness = aBacklightBrightness;
};

View file

@ -0,0 +1,19 @@
#pragma once
#include <TFT_eSPI.h>
#include <Adafruit_FT6206.h>
extern uint8_t LCD_BL_GPIO;
extern uint8_t LCD_EN_GPIO;
// used in lvgl_hal.cpp "void my_disp_flush(..."
extern TFT_eSPI tft;
// only called from lvgl_hal.cpp, not from the HAL
void init_tft(void);
void get_touchpoint(int16_t *touchX, int16_t *touchY);
// called from the HAL
void update_backligthBrighness_HAL(void);
uint8_t get_backlightBrightness_HAL();
void set_backlightBrightness_HAL(uint8_t aBacklightBrightness);

View file

@ -0,0 +1,12 @@
#include <Arduino.h>
uint8_t USER_LED_GPIO = 2;
void init_userled_HAL(void) {
pinMode(USER_LED_GPIO, OUTPUT);
digitalWrite(USER_LED_GPIO, LOW);
}
void update_userled_HAL(void) {
digitalWrite(USER_LED_GPIO, millis() % 2000 > 1000);
}

View file

@ -0,0 +1,4 @@
#pragma once
void init_userled_HAL(void);
void update_userled_HAL(void);

View file

@ -0,0 +1,7 @@
#pragma once
#if defined(WIN32) || defined(__linux__)
#include "windows_linux/include_hal_windows_linux.h"
#elif defined(ARDUINO)
#include "ESP32/include_hal_esp32.h"
#endif

View file

@ -0,0 +1,6 @@
void init_battery_HAL(void) {};
void get_battery_status_HAL(int *battery_voltage, int *battery_percentage) {
*battery_voltage = 3950;
*battery_percentage = 50;
}

View file

@ -0,0 +1,4 @@
#pragma once
void init_battery_HAL(void);
void get_battery_status_HAL(int *battery_voltage, int *battery_percentage);

View file

@ -0,0 +1,3 @@
void init_hardware_general_HAL(void) {
}

View file

@ -0,0 +1,3 @@
#pragma once
void init_hardware_general_HAL(void);

View file

@ -0,0 +1,36 @@
#include <malloc.h>
#if defined(WIN32)
// https://www.daniweb.com/programming/software-development/threads/135188/calculate-the-amount-of-heap-memory
// returns used heap size in bytes or negative if heap is corrupted.
long HeapUsed()
{
_HEAPINFO info = { 0, 0, 0 };
long used = 0;
int rc;
while ((rc=_heapwalk(&info)) == _HEAPOK)
{
if (info._useflag == _USEDENTRY)
used += info._size;
}
if (rc != _HEAPEND && rc != _HEAPEMPTY)
used = (used?-used:-1);
return used;
}
#elif defined(__linux__)
long HeapUsed() {
// don't know how to get used heap size in linux
return 800000;
}
#endif
void get_heapUsage_HAL(unsigned long *heapSize, unsigned long *freeHeap, unsigned long *maxAllocHeap, unsigned long *minFreeHeap) {
*freeHeap = HeapUsed();
// Don't know how big heap can get including swap. So we report twice the size of used heap. With that, free heap is the same as used heap.
*heapSize = 2 * *freeHeap;
*maxAllocHeap = 0;
*minFreeHeap = 0;
}

View file

@ -0,0 +1,3 @@
#pragma once
void get_heapUsage_HAL(unsigned long *heapSize, unsigned long *freeHeap, unsigned long *maxAllocHeap, unsigned long *minFreeHeap);

View file

@ -0,0 +1,15 @@
#pragma once
#include "windows_linux/battery_hal_windows_linux.h"
#include "windows_linux/hardware_general_hal_windows_linux.h"
#include "windows_linux/heapUsage_hal_windows_linux.h"
#include "windows_linux/infrared_receiver_hal_windows_linux.h"
#include "windows_linux/infrared_sender_hal_windows_linux.h"
#include "windows_linux/keyboard_ble_hal_windows_linux.h"
#include "windows_linux/keypad_keys_hal_windows_linux.h"
#include "windows_linux/lvgl_hal_windows_linux.h"
#include "windows_linux/mqtt_hal_windows_linux.h"
#include "windows_linux/preferencesStorage_hal_windows_linux.h"
#include "windows_linux/sleep_hal_windows_linux.h"
#include "windows_linux/tft_hal_windows_linux.h"
#include "windows_linux/user_led_hal_windows_linux.h"

View file

@ -0,0 +1,22 @@
#include "infrared_receiver_hal_windows_linux.h"
bool irReceiverEnabled = false;
void start_infraredReceiver_HAL() {
}
void shutdown_infraredReceiver_HAL() {
}
// The repeating section of the code
void infraredReceiver_loop_HAL() {
}
bool get_irReceiverEnabled_HAL() {
return irReceiverEnabled;
}
void set_irReceiverEnabled_HAL(bool aIrReceiverEnabled) {
irReceiverEnabled = aIrReceiverEnabled;
}
void set_showNewIRmessage_cb_HAL(tShowNewIRmessage_cb pShowNewIRmessage_cb) {}

View file

@ -0,0 +1,13 @@
#pragma once
#include <string>
void start_infraredReceiver_HAL(void);
void shutdown_infraredReceiver_HAL(void);
void infraredReceiver_loop_HAL(void);
bool get_irReceiverEnabled_HAL();
void set_irReceiverEnabled_HAL(bool aIrReceiverEnabled);
typedef void (*tShowNewIRmessage_cb)(std::string message);
void set_showNewIRmessage_cb_HAL(tShowNewIRmessage_cb pShowNewIRmessage_cb);

View file

@ -0,0 +1,17 @@
#include <string>
#include <list>
void init_infraredSender_HAL(void) {
}
// IR protocols
enum IRprotocols {
IR_PROTOCOL_GC = 0,
IR_PROTOCOL_NEC = 1,
IR_PROTOCOL_SAMSUNG = 2,
IR_PROTOCOL_SONY = 3,
IR_PROTOCOL_RC5 = 4,
IR_PROTOCOL_DENON = 5
};
void sendIRcode_HAL(int protocol, std::list<std::string> commandPayloads, std::string additionalPayload) {
}

View file

@ -0,0 +1,8 @@
#pragma once
#include <string>
#include <list>
// infrared
void init_infraredSender_HAL(void);
void sendIRcode_HAL(int protocol, std::list<std::string> commandPayloads, std::string additionalPayload);

View file

@ -0,0 +1,16 @@
#if (ENABLE_KEYBOARD_BLE == 1)
#include <string>
#include "keyboard_ble_hal_windows_linux.h"
void init_keyboardBLE_HAL() {};
bool keyboardBLE_isConnected_HAL() {return false;};
void keyboardBLE_end_HAL() {};
void keyboardBLE_write_HAL(uint8_t c) {};
void keyboardBLE_longpress_HAL(uint8_t c) {};
void keyboardBLE_home_HAL() {};
void keyboardBLE_sendString_HAL(const std::string &s) {};
void consumerControlBLE_write_HAL(const MediaKeyReport value) {};
void consumerControlBLE_longpress_HAL(const MediaKeyReport value) {};
#endif

View file

@ -0,0 +1,35 @@
#pragma once
#if (ENABLE_KEYBOARD_BLE == 1)
#include <string>
#include <stdint.h>
typedef uint8_t MediaKeyReport[2];
const uint8_t KEY_UP_ARROW = 0;
const uint8_t KEY_DOWN_ARROW = 0;
const uint8_t KEY_RIGHT_ARROW = 0;
const uint8_t KEY_LEFT_ARROW = 0;
const uint8_t KEY_RETURN = 0;
const MediaKeyReport KEY_MEDIA_WWW_BACK = {0, 0};
const MediaKeyReport KEY_MEDIA_WWW_HOME = {0, 0};
const MediaKeyReport KEY_MEDIA_PREVIOUS_TRACK = {0, 0};
const MediaKeyReport KEY_MEDIA_REWIND = {0, 0};
const MediaKeyReport KEY_MEDIA_PLAY_PAUSE = {0, 0};
const MediaKeyReport KEY_MEDIA_FASTFORWARD = {0, 0};
const MediaKeyReport KEY_MEDIA_NEXT_TRACK = {0, 0};
const MediaKeyReport KEY_MEDIA_MUTE = {0, 0};
const MediaKeyReport KEY_MEDIA_VOLUME_UP = {0, 0};
const MediaKeyReport KEY_MEDIA_VOLUME_DOWN = {0, 0};
void init_keyboardBLE_HAL();
bool keyboardBLE_isConnected_HAL();
void keyboardBLE_end_HAL();
void keyboardBLE_write_HAL(uint8_t c);
void keyboardBLE_longpress_HAL(uint8_t c);
void keyboardBLE_home_HAL();
void keyboardBLE_sendString_HAL(const std::string &s);
void consumerControlBLE_write_HAL(const MediaKeyReport value);
void consumerControlBLE_longpress_HAL(const MediaKeyReport value);
#endif

View file

@ -0,0 +1,24 @@
#include <stdint.h>
void init_keys_HAL(void) {
}
enum keypad_keyStates {IDLE_HAL, PRESSED_HAL, HOLD_HAL, RELEASED_HAL};
struct keypad_key {
char kchar;
int kcode;
keypad_keyStates kstate;
bool stateChanged;
};
keypad_key keys[10];
void keys_getKeys_HAL(void* ptr) {
for(int i=0; i < 19; i++) {
(*(keypad_key*)ptr).kchar = ' ';
(*(keypad_key*)ptr).kcode = 0;
(*(keypad_key*)ptr).kstate = IDLE_HAL;
(*(keypad_key*)ptr).stateChanged = false;
// https://www.geeksforgeeks.org/void-pointer-c-cpp/
ptr = (void *) ((intptr_t)(ptr) + sizeof(keypad_key));
}
}

View file

@ -0,0 +1,4 @@
#pragma once
void init_keys_HAL(void);
void keys_getKeys_HAL(void* ptr);

View file

@ -0,0 +1,109 @@
#include <stdlib.h>
#include <sys/time.h>
#include <lvgl.h>
#include <SDL2/SDL_thread.h>
#include "sdl/sdl.h"
#include "SDL2/SDL_events.h"
long long current_timestamp_hal_windowsLinux() {
struct timeval te;
gettimeofday(&te, NULL); // get current time
long long milliseconds = te.tv_sec*1000LL + te.tv_usec/1000; // calculate milliseconds
// printf("milliseconds: %lld\r\n", milliseconds);
return milliseconds;
}
/**
* A task to measure the elapsed time for LittlevGL
* @param data unused
* @return never return
*/
static int tick_thread(void * data)
{
(void)data;
long long lastTimestamp = current_timestamp_hal_windowsLinux();
long long newTimestamp = 0;
while(1) {
// we don't use this blackbox
// SDL_Delay(5); /*Sleep for 5 millisecond*/
// lv_tick_inc(5); /*Tell lvgl that 5 milliseconds were elapsed*/
newTimestamp = current_timestamp_hal_windowsLinux();
if ((newTimestamp - lastTimestamp) > 5) {
lv_tick_inc(newTimestamp - lastTimestamp);
lastTimestamp = newTimestamp;
}
}
return 0;
}
static lv_disp_draw_buf_t draw_buf;
void init_lvgl_HAL() {
// Workaround for sdl2 `-m32` crash
// https://bugs.launchpad.net/ubuntu/+source/libsdl2/+bug/1775067/comments/7
#ifndef WIN32
setenv("DBUS_FATAL_WARNINGS", "0", 1);
#endif
#ifdef useTwoBuffersForlvgl
lv_color_t * bufA = (lv_color_t *) malloc(sizeof(lv_color_t) * SDL_HOR_RES * SDL_VER_RES / 10);
lv_color_t * bufB = (lv_color_t *) malloc(sizeof(lv_color_t) * SDL_HOR_RES * SDL_VER_RES / 10);
lv_disp_draw_buf_init(&draw_buf, bufA, bufB, SDL_HOR_RES * SDL_VER_RES / 10);
#else
lv_color_t * bufA = (lv_color_t *) malloc(sizeof(lv_color_t) * SDL_HOR_RES * SDL_VER_RES / 10);
lv_disp_draw_buf_init(&draw_buf, bufA, NULL, SDL_HOR_RES * SDL_VER_RES / 10);
#endif
// Initialize the display driver --------------------------------------------------------------------------
static lv_disp_drv_t disp_drv;
lv_disp_drv_init( &disp_drv );
disp_drv.hor_res = SDL_HOR_RES;
disp_drv.ver_res = SDL_VER_RES;
disp_drv.flush_cb = sdl_display_flush; /*Used when `LV_VDB_SIZE != 0` in lv_conf.h (buffered drawing)*/
disp_drv.draw_buf = &draw_buf;
//disp_drv.disp_fill = monitor_fill; /*Used when `LV_VDB_SIZE == 0` in lv_conf.h (unbuffered drawing)*/
//disp_drv.disp_map = monitor_map; /*Used when `LV_VDB_SIZE == 0` in lv_conf.h (unbuffered drawing)*/
lv_disp_drv_register( &disp_drv );
/* Add the mouse as input device
* Use the 'mouse' driver which reads the PC's mouse*/
static lv_indev_drv_t indev_drv_mouse;
lv_indev_drv_init( &indev_drv_mouse );
indev_drv_mouse.type = LV_INDEV_TYPE_POINTER;
indev_drv_mouse.read_cb = sdl_mouse_read; /*This function will be called periodically (by the library) to get the mouse position and state*/
lv_indev_drv_register( &indev_drv_mouse );
// /* Add the keyboard as input device
// * did not work */
// static lv_indev_drv_t indev_drv_keyboard;
// lv_indev_drv_init( &indev_drv_keyboard );
// indev_drv_keyboard.type = LV_INDEV_TYPE_KEYPAD;
// indev_drv_keyboard.read_cb = sdl_keyboard_read; /*This function will be called periodically (by the library) to get the keyboard events*/
// lv_indev_t *keyboard_device = lv_indev_drv_register( &indev_drv_keyboard );
// lv_group_t *group = lv_group_create();
// lv_indev_set_group(keyboard_device, group);
// lv_group_add_obj(group, lv_scr_act());
// lv_group_add_obj(group, tabview);
// lv_group_add_obj(group, lv_tabview_get_content(tabview));
// lv_group_add_obj(group, tabs);
//
// need to be in a loop
// printf("last key: %d\n",lv_indev_get_key(keyboard_device));
sdl_init();
// Get the SDL window via an event
SDL_Event aWindowIdFinder;
SDL_PollEvent(&aWindowIdFinder);
SDL_Window *mSimWindow = SDL_GetWindowFromID(aWindowIdFinder.window.windowID);
SDL_SetWindowTitle(mSimWindow, "OMOTE simulator");
/* Tick init.
* You have to call 'lv_tick_inc()' in periodically to inform lvgl about how much time were elapsed
* Create an SDL thread to do this*/
SDL_CreateThread(tick_thread, "tick", NULL);
}

View file

@ -0,0 +1,3 @@
#pragma once
void init_lvgl_HAL();

View file

@ -0,0 +1,18 @@
#include "mqtt_hal_windows_linux.h"
#if (ENABLE_WIFI_AND_MQTT == 1)
bool getIsWifiConnected_HAL() {
return true;
}
void init_mqtt_HAL(void) {}
bool publishMQTTMessage_HAL(const char *topic, const char *payload){
return false;
}
void wifiStop_HAL() {}
void set_showWiFiconnected_cb_HAL(showWiFiconnected_cb pShowWiFiconnected_cb) {}
#endif

View file

@ -0,0 +1,13 @@
#pragma once
#if (ENABLE_WIFI_AND_MQTT == 1)
void init_mqtt_HAL(void);
bool getIsWifiConnected_HAL();
bool publishMQTTMessage_HAL(const char *topic, const char *payload);
void wifiStop_HAL();
typedef void (*showWiFiconnected_cb)(bool connected);
void set_showWiFiconnected_cb_HAL(showWiFiconnected_cb pShowWiFiconnected_cb);
#endif

View file

@ -0,0 +1,22 @@
#include <string>
std::string currentScene;
std::string currentGUIname;
void init_preferences_HAL(void) {
}
void save_preferences_HAL(void) {
}
std::string get_currentScene_HAL() {
return currentScene;
}
void set_currentScene_HAL(std::string aCurrentScene) {
currentScene = aCurrentScene;
}
std::string get_currentGUIname_HAL(){
return currentGUIname;
}
void set_currentGUIname_HAL(std::string aCurrentGUIname) {
currentGUIname = aCurrentGUIname;
}

View file

@ -0,0 +1,11 @@
#pragma once
#include <string>
void init_preferences_HAL(void);
void save_preferences_HAL(void);
std::string get_currentScene_HAL();
void set_currentScene_HAL(std::string aCurrentScene);
std::string get_currentGUIname_HAL();
void set_currentGUIname_HAL(std::string aCurrentGUIname);

View file

@ -0,0 +1,27 @@
#include <stdio.h>
#include <stdint.h>
// is "lift to wake" enabled
bool wakeupByIMUEnabled = true;
// timeout before going to sleep
uint32_t sleepTimeout;
void init_sleep_HAL() {}
void init_IMU_HAL(void) {}
void check_activity_HAL() {}
void setLastActivityTimestamp_HAL() {}
uint32_t get_sleepTimeout_HAL() {
return sleepTimeout;
}
void set_sleepTimeout_HAL(uint32_t aSleepTimeout) {
sleepTimeout = aSleepTimeout;
printf("sleep timeout set to %u ms\r\n", aSleepTimeout);
}
bool get_wakeupByIMUEnabled_HAL() {
return wakeupByIMUEnabled;
}
void set_wakeupByIMUEnabled_HAL(bool aWakeupByIMUEnabled) {
wakeupByIMUEnabled = aWakeupByIMUEnabled;
printf("lift to wake set to %d\r\n", aWakeupByIMUEnabled);
}

View file

@ -0,0 +1,11 @@
#pragma once
void init_sleep_HAL();
void init_IMU_HAL();
void check_activity_HAL();
void setLastActivityTimestamp_HAL();
uint32_t get_sleepTimeout_HAL();
void set_sleepTimeout_HAL(uint32_t aSleepTimeout);
bool get_wakeupByIMUEnabled_HAL();
void set_wakeupByIMUEnabled_HAL(bool aWakeupByIMUEnabled);

View file

@ -0,0 +1,16 @@
#include <stdio.h>
#include <stdint.h>
uint8_t backlightBrightness = 255;
void update_backligthBrighness_HAL(void) {
// nothing to do, we don't want to dim the simulator
};
uint8_t get_backlightBrightness_HAL() {
return backlightBrightness;
};
void set_backlightBrightness_HAL(uint8_t aBacklightBrightness) {
backlightBrightness = aBacklightBrightness;
printf("backlight brightness set to %u\r\n", aBacklightBrightness);
};

View file

@ -0,0 +1,5 @@
#pragma once
void update_backligthBrighness_HAL(void);
uint8_t get_backlightBrightness_HAL();
void set_backlightBrightness_HAL(uint8_t aBacklightBrightness);

View file

@ -0,0 +1,2 @@
void init_userled_HAL(void) {};
void update_userled_HAL(void) {};

View file

@ -0,0 +1,4 @@
#pragma once
void init_userled_HAL(void);
void update_userled_HAL(void);

View file

@ -8,47 +8,34 @@
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:esp32]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
board_build.f_flash = 80000000L
board_build.f_cpu = 240000000L
board_build.partitions = huge_app.csv
upload_speed = 1000000
[platformio]
default_envs = esp32
[env]
;-- platformio.ini custom options, reused by TFT_eSPI, SDL2 and in OMOTE code -
custom_screen_width = 240
custom_screen_heigth = 320
lib_deps =
bodmer/TFT_eSPI@^2.5.23
adafruit/Adafruit FT6206 Library@^1.0.6
lvgl/lvgl@^8.3.4
sparkfun/SparkFun LIS3DH Arduino Library@^1.0.3
crankyoldgit/IRremoteESP8266@^2.8.4
knolleary/PubSubClient@^2.8
h2zero/NimBLE-Arduino@^1.4.1
;chris--a/Keypad@^3.1.1
;t-vk/ESP32 BLE Keyboard@^0.3.2
build_flags =
lvgl/lvgl@^8.3.11
build_flags =
;-- OMOTE -----------------------------------------------------------------
-D ENABLE_WIFI_AND_MQTT=1
-D ENABLE_KEYBOARD_MQTT=1
-D ENABLE_BLUETOOTH=1
;-- Arduino log -----------------------------------------------------------
;-D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_NONE
;-D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_ERROR
;-D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_WARN
-D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_INFO
;-D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_DEBUG
;-D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_VERBOSE
-D ENABLE_KEYBOARD_BLE=1
-D SCR_WIDTH=${env.custom_screen_width}
-D SCR_HEIGHT=${env.custom_screen_heigth}
;-- lvgl ------------------------------------------------------------------
; lvgl variant 1:
; Don't use lv_conf.h. Tweak params via platfom.ini. See lv_conf_internal.h line 31. Don't change this line.
-D LV_CONF_SKIP=1
; use millis() from "Arduino.h" to tell the elapsed time in milliseconds
-D LV_TICK_CUSTOM=1
; Set this in specific environments below. Will be different in Arduino and Windows/Linux
;-D LV_TICK_CUSTOM=1
; dynamic memory. Takes as much as it gets from heap (DRAM). Needs approx. 25%-30% more memory than static memory.
;-D LV_MEM_CUSTOM=1
; static memory, will be allocated in static DRAM
-D LV_MEM_CUSTOM=0
-D LV_MEM_SIZE="(32U * 1024U)"
; Set this in specific environments below. 32 bit and 64 bit need differenz sizes.
;-D LV_MEM_CUSTOM=0
;-D LV_MEM_SIZE="(32U * 1024U)"
; fonts and theme
-D LV_FONT_MONTSERRAT_10=1
-D LV_FONT_MONTSERRAT_12=1
@ -81,14 +68,55 @@ build_flags =
; lvgl variant 2:
; or define where lv_conf.h is, relative to the `lvgl` folder
;-D LV_CONF_PATH=../../../../src/gui_general_and_keys/lv_conf.h
[env:esp32]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
board_build.f_flash = 80000000L
board_build.f_cpu = 240000000L
board_build.partitions = huge_app.csv
upload_speed = 1000000
lib_deps =
${env.lib_deps}
bodmer/TFT_eSPI@^2.5.43
adafruit/Adafruit BusIO@^1.15.0
adafruit/Adafruit FT6206 Library@^1.1.0
sparkfun/SparkFun LIS3DH Arduino Library@^1.0.3
crankyoldgit/IRremoteESP8266@^2.8.6
knolleary/PubSubClient@^2.8
h2zero/NimBLE-Arduino@^1.4.1
;chris--a/Keypad@^3.1.1
;t-vk/ESP32 BLE Keyboard@^0.3.2
build_flags =
${env.build_flags}
;-- OMOTE -----------------------------------------------------------------
; 1: rev1 - Slowly charge the VSW voltage to prevent a brownout
; 2: rev2 - still necessary in this revision
; 3: rev3 - still necessary in this revision
-D OMOTE_HARDWARE_REV=3
;-- Arduino log -----------------------------------------------------------
;-D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_NONE
;-D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_ERROR
;-D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_WARN
-D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_INFO
;-D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_DEBUG
;-D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_VERBOSE
;-- lvgl arduino ----------------------------------------------------------
; use millis() from "Arduino.h" to tell the elapsed time in milliseconds
-D LV_TICK_CUSTOM=1
; static memory, will be allocated in static DRAM
-D LV_MEM_CUSTOM=0
-D LV_MEM_SIZE="(32U * 1024U)"
;-- TFT_eSPI --------------------------------------------------------------
-D DISABLE_ALL_LIBRARY_WARNINGS=1
; The following lines replace the TFT_eSPI User_setup.h-file
-D USER_SETUP_LOADED=1
-D ILI9341_DRIVER=1
-D TFT_WIDTH=240
-D TFT_HEIGHT=320
;-D TFT_MISO
-D TFT_WIDTH=${env.custom_screen_width}
-D TFT_HEIGHT=${env.custom_screen_heigth}
;-D TFT_MISO not connected
-D TFT_MOSI=23
-D TFT_SCLK=18
-D TFT_CS=5
@ -104,5 +132,65 @@ build_flags =
;-D LOAD_FONT8=1
;-D LOAD_GFXFF=1
;-D SMOOTH_FONT=1
;-- for BLE Keyboard. Don't change this line! -----------------------------
;-- for BLE Keyboard. Don't change this line! -----------------------------
-D USE_NIMBLE=1
;-- hardware abstraction, needed to find hardwareLayer.h ------------------
-I hardware
-I hardware/ESP32/lib/Keypad/src
;-I hardware/ESP32/lib/ESP32-BLE-Keyboard
build_src_filter =
+<*>
+<../hardware/ESP32/*>
;+<../hardware/ESP32/lib/ESP32-BLE-Keyboard/*>
; use this if you have a 64 bit compiler (Ubuntu, WSL2, Windows with MSYS2 MINGW64)
[env:windows_linux_64bit]
platform = native@^1.2.1
lib_deps =
${env.lib_deps}
;we need the master branch from github because of this commit https://github.com/lvgl/lv_drivers/commit/7b9dee11c93ad27e2591182457c1eba7677473be
lv_drivers=https://github.com/lvgl/lv_drivers
;lvgl/lv_drivers@^8.3.0
build_flags =
${env.build_flags}
;-- lvgl ------------------------------------------------------------------
; 64 bit needs a lot more static memory
-D LV_MEM_CUSTOM=0
-D LV_MEM_SIZE="(64U * 1024U)"
;SDL2 from msys64
-l SDL2
; settings for lv_drivers
-D LV_LVGL_H_INCLUDE_SIMPLE
-D LV_DRV_NO_CONF
-D USE_SDL
-D SDL_INCLUDE_PATH="\"SDL2/SDL.h\""
-D SDL_HOR_RES=${env.custom_screen_width}
-D SDL_VER_RES=${env.custom_screen_heigth}
-D SDL_ZOOM=2
;-- hardware abstraction, needed to find hardwareLayer.h ------------------
-I hardware
build_src_filter =
+<*>
+<../hardware/windows_linux/*>
; use this if you have a 32 bit compiler (Windows MSYS2 MINGW32)
[env:windows_linux_32bit]
extends = env:windows_linux_64bit
build_unflags =
${env:windows_linux_64bit.build_unflags}
;-- lvgl ------------------------------------------------------------------
-D LV_MEM_CUSTOM=0
-D LV_MEM_SIZE="(64U * 1024U)"
build_flags =
${env:windows_linux_64bit.build_flags}
;-- lvgl ------------------------------------------------------------------
; 32 bit needs exact the same lvgl memory as on ESP32
-D LV_MEM_CUSTOM=0
-D LV_MEM_SIZE="(32U * 1024U)"
; Take care. If you have a 64 bit compiler, this setting will tell the compiler to cross compile to 32 bit.
; Compiling is successfull, but linker fails. So use this env only with a 32 bit compiler.
; Probably a custom linker script would be needed for cross compiling to work.
; Ubuntu and WSL2 are using 64 bit compilers! So you can only build the 32 bit simulator with Windows MSYS2 MINGW32
-m32
;linker option
-Wl,-mi386pe

View file

@ -0,0 +1,252 @@
#include <string>
#include <list>
#include <sstream>
#include <algorithm>
#include <stdexcept>
#include "applicationInternal/commandHandler.h"
#include "applicationInternal/scenes/sceneHandler.h"
#include "applicationInternal/hardware/hardwarePresenter.h"
#include "devices/misc/device_specialCommands.h"
uint16_t KEYBOARD_DUMMY_UP ; //"Keyboard_dummy_up"
uint16_t KEYBOARD_DUMMY_DOWN ; //"Keyboard_dummy_down"
uint16_t KEYBOARD_DUMMY_RIGHT ; //"Keyboard_dummy_right"
uint16_t KEYBOARD_DUMMY_LEFT ; //"Keyboard_dummy_left"
uint16_t KEYBOARD_DUMMY_SELECT ; //"Keyboard_dummy_select"
uint16_t KEYBOARD_DUMMY_SENDSTRING ; //"Keyboard_dummy_sendstring"
uint16_t KEYBOARD_DUMMY_BACK ; //"Keyboard_dummy_back"
uint16_t KEYBOARD_DUMMY_HOME ; //"Keyboard_dummy_home"
uint16_t KEYBOARD_DUMMY_MENU ; //"Keyboard_dummy_menu"
uint16_t KEYBOARD_DUMMY_SCAN_PREVIOUS_TRACK ; //"Keyboard_dummy_scan_previous_track"
uint16_t KEYBOARD_DUMMY_REWIND_LONG ; //"Keyboard_dummy_rewind_long"
uint16_t KEYBOARD_DUMMY_REWIND ; //"Keyboard_dummy_rewind"
uint16_t KEYBOARD_DUMMY_PLAYPAUSE ; //"Keyboard_dummy_playpause"
uint16_t KEYBOARD_DUMMY_FASTFORWARD ; //"Keyboard_dummy_fastforward"
uint16_t KEYBOARD_DUMMY_FASTFORWARD_LONG ; //"Keyboard_dummy_fastforward_long"
uint16_t KEYBOARD_DUMMY_SCAN_NEXT_TRACK ; //"Keyboard_dummy_scan_next_track"
uint16_t KEYBOARD_DUMMY_MUTE ; //"Keyboard_dummy_mute"
uint16_t KEYBOARD_DUMMY_VOLUME_INCREMENT ; //"Keyboard_dummy_volume_increment"
uint16_t KEYBOARD_DUMMY_VOLUME_DECREMENT ; //"Keyboard_dummy_volume_decrement"
uint16_t KEYBOARD_UP ; //PPCAT(KEYBOARD_PREFIX, UP)
uint16_t KEYBOARD_DOWN ; //PPCAT(KEYBOARD_PREFIX, DOWN)
uint16_t KEYBOARD_RIGHT ; //PPCAT(KEYBOARD_PREFIX, RIGHT)
uint16_t KEYBOARD_LEFT ; //PPCAT(KEYBOARD_PREFIX, LEFT)
uint16_t KEYBOARD_SELECT ; //PPCAT(KEYBOARD_PREFIX, SELECT)
uint16_t KEYBOARD_SENDSTRING ; //PPCAT(KEYBOARD_PREFIX, SENDSTRING)
uint16_t KEYBOARD_BACK ; //PPCAT(KEYBOARD_PREFIX, BACK)
uint16_t KEYBOARD_HOME ; //PPCAT(KEYBOARD_PREFIX, HOME)
uint16_t KEYBOARD_MENU ; //PPCAT(KEYBOARD_PREFIX, MENU)
uint16_t KEYBOARD_SCAN_PREVIOUS_TRACK ; //PPCAT(KEYBOARD_PREFIX, SCAN_PREVIOUS_TRACK)
uint16_t KEYBOARD_REWIND_LONG ; //PPCAT(KEYBOARD_PREFIX, REWIND_LONG)
uint16_t KEYBOARD_REWIND ; //PPCAT(KEYBOARD_PREFIX, REWIND)
uint16_t KEYBOARD_PLAYPAUSE ; //PPCAT(KEYBOARD_PREFIX, PLAYPAUSE)
uint16_t KEYBOARD_FASTFORWARD ; //PPCAT(KEYBOARD_PREFIX, FASTFORWARD)
uint16_t KEYBOARD_FASTFORWARD_LONG ; //PPCAT(KEYBOARD_PREFIX, FASTFORWARD_LONG)
uint16_t KEYBOARD_SCAN_NEXT_TRACK ; //PPCAT(KEYBOARD_PREFIX, SCAN_NEXT_TRACK)
uint16_t KEYBOARD_MUTE ; //PPCAT(KEYBOARD_PREFIX, MUTE)
uint16_t KEYBOARD_VOLUME_INCREMENT ; //PPCAT(KEYBOARD_PREFIX, VOLUME_INCREMENT)
uint16_t KEYBOARD_VOLUME_DECREMENT ; //PPCAT(KEYBOARD_PREFIX, VOLUME_DECREMENT)
std::map<uint16_t, commandData> commands;
uint16_t uniqueCommandID = 0;
// we don't yet have a command id
void register_command(uint16_t *command, commandData aCommandData) {
*command = uniqueCommandID;
uniqueCommandID++;
commands[*command] = aCommandData;
}
// we already have a command id. Only used by BLE keyboard
void register_command_withID(uint16_t command, commandData aCommandData) {
commands[command] = aCommandData;
}
// only get a unique ID. used by KEYBOARD_DUMMY, COMMAND_UNKNOWN and BLE keyboard
void get_uniqueCommandID(uint16_t *command) {
*command = uniqueCommandID;
uniqueCommandID++;
}
void register_keyboardCommands() {
get_uniqueCommandID(&KEYBOARD_DUMMY_UP );
get_uniqueCommandID(&KEYBOARD_DUMMY_DOWN );
get_uniqueCommandID(&KEYBOARD_DUMMY_RIGHT );
get_uniqueCommandID(&KEYBOARD_DUMMY_LEFT );
get_uniqueCommandID(&KEYBOARD_DUMMY_SELECT );
get_uniqueCommandID(&KEYBOARD_DUMMY_SENDSTRING );
get_uniqueCommandID(&KEYBOARD_DUMMY_BACK );
get_uniqueCommandID(&KEYBOARD_DUMMY_HOME );
get_uniqueCommandID(&KEYBOARD_DUMMY_MENU );
get_uniqueCommandID(&KEYBOARD_DUMMY_SCAN_PREVIOUS_TRACK );
get_uniqueCommandID(&KEYBOARD_DUMMY_REWIND_LONG );
get_uniqueCommandID(&KEYBOARD_DUMMY_REWIND );
get_uniqueCommandID(&KEYBOARD_DUMMY_PLAYPAUSE );
get_uniqueCommandID(&KEYBOARD_DUMMY_FASTFORWARD );
get_uniqueCommandID(&KEYBOARD_DUMMY_FASTFORWARD_LONG );
get_uniqueCommandID(&KEYBOARD_DUMMY_SCAN_NEXT_TRACK );
get_uniqueCommandID(&KEYBOARD_DUMMY_MUTE );
get_uniqueCommandID(&KEYBOARD_DUMMY_VOLUME_INCREMENT );
get_uniqueCommandID(&KEYBOARD_DUMMY_VOLUME_DECREMENT );
#if (ENABLE_KEYBOARD_BLE == 1)
KEYBOARD_UP = KEYBOARD_BLE_UP;
KEYBOARD_DOWN = KEYBOARD_BLE_DOWN;
KEYBOARD_RIGHT = KEYBOARD_BLE_RIGHT;
KEYBOARD_LEFT = KEYBOARD_BLE_LEFT;
KEYBOARD_SELECT = KEYBOARD_BLE_SELECT;
KEYBOARD_SENDSTRING = KEYBOARD_BLE_SENDSTRING;
KEYBOARD_BACK = KEYBOARD_BLE_BACK;
KEYBOARD_HOME = KEYBOARD_BLE_HOME;
KEYBOARD_MENU = KEYBOARD_BLE_MENU;
KEYBOARD_SCAN_PREVIOUS_TRACK = KEYBOARD_BLE_SCAN_PREVIOUS_TRACK;
KEYBOARD_REWIND_LONG = KEYBOARD_BLE_REWIND_LONG;
KEYBOARD_REWIND = KEYBOARD_BLE_REWIND;
KEYBOARD_PLAYPAUSE = KEYBOARD_BLE_PLAYPAUSE;
KEYBOARD_FASTFORWARD = KEYBOARD_BLE_FASTFORWARD;
KEYBOARD_FASTFORWARD_LONG = KEYBOARD_BLE_FASTFORWARD_LONG;
KEYBOARD_SCAN_NEXT_TRACK = KEYBOARD_BLE_SCAN_NEXT_TRACK;
KEYBOARD_MUTE = KEYBOARD_BLE_MUTE;
KEYBOARD_VOLUME_INCREMENT = KEYBOARD_BLE_VOLUME_INCREMENT;
KEYBOARD_VOLUME_DECREMENT = KEYBOARD_BLE_VOLUME_DECREMENT;
#elif (ENABLE_KEYBOARD_MQTT == 1)
KEYBOARD_UP = KEYBOARD_MQTT_UP;
KEYBOARD_DOWN = KEYBOARD_MQTT_DOWN;
KEYBOARD_RIGHT = KEYBOARD_MQTT_RIGHT;
KEYBOARD_LEFT = KEYBOARD_MQTT_LEFT;
KEYBOARD_SELECT = KEYBOARD_MQTT_SELECT;
KEYBOARD_SENDSTRING = KEYBOARD_MQTT_SENDSTRING;
KEYBOARD_BACK = KEYBOARD_MQTT_BACK;
KEYBOARD_HOME = KEYBOARD_MQTT_HOME;
KEYBOARD_MENU = KEYBOARD_MQTT_MENU;
KEYBOARD_SCAN_PREVIOUS_TRACK = KEYBOARD_MQTT_SCAN_PREVIOUS_TRACK;
KEYBOARD_REWIND_LONG = KEYBOARD_MQTT_REWIND_LONG;
KEYBOARD_REWIND = KEYBOARD_MQTT_REWIND;
KEYBOARD_PLAYPAUSE = KEYBOARD_MQTT_PLAYPAUSE;
KEYBOARD_FASTFORWARD = KEYBOARD_MQTT_FASTFORWARD;
KEYBOARD_FASTFORWARD_LONG = KEYBOARD_MQTT_FASTFORWARD_LONG;
KEYBOARD_SCAN_NEXT_TRACK = KEYBOARD_MQTT_SCAN_NEXT_TRACK;
KEYBOARD_MUTE = KEYBOARD_MQTT_MUTE;
KEYBOARD_VOLUME_INCREMENT = KEYBOARD_MQTT_VOLUME_INCREMENT;
KEYBOARD_VOLUME_DECREMENT = KEYBOARD_MQTT_VOLUME_DECREMENT;
#else
// Of course keyboard commands will not work if neither BLE nor MQTT keyboard is enabled, but at least code will compile.
// But you have to change keys.cpp, gui_numpad.cpp and commandHandler.cpp where keyboard commands are used so that a command can be executed successfully.
// Search for "executeCommand(Key" to find them.
KEYBOARD_UP = KEYBOARD_DUMMY_UP;
KEYBOARD_DOWN = KEYBOARD_DUMMY_DOWN;
KEYBOARD_RIGHT = KEYBOARD_DUMMY_RIGHT;
KEYBOARD_LEFT = KEYBOARD_DUMMY_LEFT;
KEYBOARD_SELECT = KEYBOARD_DUMMY_SELECT;
KEYBOARD_SENDSTRING = KEYBOARD_DUMMY_SENDSTRING;
KEYBOARD_BACK = KEYBOARD_DUMMY_BACK;
KEYBOARD_HOME = KEYBOARD_DUMMY_HOME;
KEYBOARD_MENU = KEYBOARD_DUMMY_MENU;
KEYBOARD_SCAN_PREVIOUS_TRACK = KEYBOARD_DUMMY_SCAN_PREVIOUS_TRACK;
KEYBOARD_REWIND_LONG = KEYBOARD_DUMMY_REWIND_LONG;
KEYBOARD_REWIND = KEYBOARD_DUMMY_REWIND;
KEYBOARD_PLAYPAUSE = KEYBOARD_DUMMY_PLAYPAUSE;
KEYBOARD_FASTFORWARD = KEYBOARD_DUMMY_FASTFORWARD;
KEYBOARD_FASTFORWARD_LONG = KEYBOARD_DUMMY_FASTFORWARD_LONG;
KEYBOARD_SCAN_NEXT_TRACK = KEYBOARD_DUMMY_SCAN_NEXT_TRACK;
KEYBOARD_MUTE = KEYBOARD_DUMMY_MUTE;
KEYBOARD_VOLUME_INCREMENT = KEYBOARD_DUMMY_VOLUME_INCREMENT;
KEYBOARD_VOLUME_DECREMENT = KEYBOARD_DUMMY_VOLUME_DECREMENT;
#endif
}
commandData makeCommandData(commandHandlers a, std::list<std::string> b) {
commandData c = {a, b};
return c;
}
std::string convertStringListToString(std::list<std::string> listOfStrings) {
std::string result;
for(const auto &word : listOfStrings) {
result += word + ",";
}
return result;
}
void executeCommandWithData(uint16_t command, commandData commandData, std::string additionalPayload = "") {
switch (commandData.commandHandler) {
case IR: {
// Serial.printf(" generic IR, payloads %s\r\n", convertStringListToString(commandData.commandPayloads).c_str());
// we received a comma separated list of strings
// the first string is the IR protocol, the second is the payload to be sent
std::list<std::string>::iterator it = commandData.commandPayloads.begin();
// get protocol and erase first element in list
std::string protocol = *it;
it = commandData.commandPayloads.erase(it);
// Serial.printf(" protocol %s, payload %s\r\n", protocol.c_str(), convertStringListToString(commandData.commandPayloads).c_str());
sendIRcode((IRprotocols)std::stoi(protocol), commandData.commandPayloads, additionalPayload);
break;
}
#if (ENABLE_WIFI_AND_MQTT == 1)
case MQTT: {
auto current = commandData.commandPayloads.begin();
std::string topic = *current;
std::string payload;
if (additionalPayload == "") {
current = std::next(current, 1);
payload = *current;
} else {
payload = additionalPayload;
}
Serial.printf("execute: will send MQTT, topic '%s', payload '%s'\r\n", topic.c_str(), payload.c_str());
publishMQTTMessage(topic.c_str(), payload.c_str());
break;
}
#endif
#if (ENABLE_KEYBOARD_BLE == 1)
case BLE_KEYBOARD: {
// the real command for the BLE keyboard is the first element in payload
auto current = commandData.commandPayloads.begin();
uint16_t command = std::stoi(*current);
std::string payload = "";
if (additionalPayload != "") {
payload = additionalPayload;
}
Serial.printf("execute: will send BLE keyboard command, command '%u', payload '%s'\r\n", command, payload.c_str());
keyboard_ble_executeCommand(command, payload);
break;
}
#endif
case SCENE: {
// let the sceneHandler do the scene stuff
Serial.printf("execute: will send scene command to the sceneHandler\r\n");
handleScene(command, commandData, additionalPayload);
break;
}
case SPECIAL: {
if (command == MY_SPECIAL_COMMAND) {
// do your special command here
Serial.printf("execute: could execute a special command here, if you define one\r\n");
}
break;
}
}
}
void executeCommand(uint16_t command, std::string additionalPayload) {
try {
if (commands.count(command) > 0) {
Serial.printf("command: will execute command '%u' with additionalPayload '%s'\r\n", command, additionalPayload.c_str());
executeCommandWithData(command, commands.at(command), additionalPayload);
} else {
Serial.printf("command: command '%u' not found\r\n", command);
}
}
catch (const std::out_of_range& oor) {
Serial.printf("executeCommand: internal error, command not registered\r\n");
}
}

View file

@ -0,0 +1,118 @@
#pragma once
#include <string>
#include <list>
#include <map>
#include "devices/keyboard/device_keyboard_mqtt/device_keyboard_mqtt.h"
#include "devices/keyboard/device_keyboard_ble/device_keyboard_ble.h"
/*
Depending on which keyboard is enabled (BLE or MQTT), we define KEYBOARD_UP, KEYBOARD_DOWN and so on.
These defines are used in keys.cpp, gui*.cpp and commandHandler.cpp
Example:
If BLE is enabled, then KEYBOARD_UP will be the same as KEYBOARD_BLE_UP
If MQTT is enabled, then KEYBOARD_UP will be the same as KEYBOARD_MQTT_UP
If none of them is enabled, then KEYBOARD_UP will be the same as KEYBOARD_UP_DUMMY
Doing so you can switch between the keyboards without changing the UI code (keys.cpp, gui*.cpp and commandHandler.cpp)
If you need something different than this behaviour, then you can change the code in 'register_keyboardCommands()'
or you can of course change keys.cpp, gui*.cpp and commandHandler.cpp so that they directly use KEYBOARD_BLE_UP or KEYBOARD_MQTT_UP etc.
*/
extern uint16_t KEYBOARD_DUMMY_UP;
extern uint16_t KEYBOARD_DUMMY_DOWN;
extern uint16_t KEYBOARD_DUMMY_RIGHT;
extern uint16_t KEYBOARD_DUMMY_LEFT;
extern uint16_t KEYBOARD_DUMMY_SELECT;
extern uint16_t KEYBOARD_DUMMY_SENDSTRING;
extern uint16_t KEYBOARD_DUMMY_BACK;
extern uint16_t KEYBOARD_DUMMY_HOME;
extern uint16_t KEYBOARD_DUMMY_MENU;
extern uint16_t KEYBOARD_DUMMY_SCAN_PREVIOUS_TRACK;
extern uint16_t KEYBOARD_DUMMY_REWIND_LONG;
extern uint16_t KEYBOARD_DUMMY_REWIND;
extern uint16_t KEYBOARD_DUMMY_PLAYPAUSE;
extern uint16_t KEYBOARD_DUMMY_FASTFORWARD;
extern uint16_t KEYBOARD_DUMMY_FASTFORWARD_LONG;
extern uint16_t KEYBOARD_DUMMY_SCAN_NEXT_TRACK;
extern uint16_t KEYBOARD_DUMMY_MUTE;
extern uint16_t KEYBOARD_DUMMY_VOLUME_INCREMENT;
extern uint16_t KEYBOARD_DUMMY_VOLUME_DECREMENT;
#if (ENABLE_KEYBOARD_BLE == 1)
#define KEYBOARD_PREFIX KEYBOARD_BLE_
#elif (ENABLE_KEYBOARD_MQTT == 1)
#define KEYBOARD_PREFIX KEYBOARD_MQTT_
#else
// Of course keyboard commands will not work if neither BLE nor MQTT keyboard is enabled, but at least code will compile.
// But you have to change keys.cpp, gui_numpad.cpp and commandHandler.cpp where keyboard commands are used so that a command can be executed successfully.
// Search for "executeCommand(Key" to find them.
#define KEYBOARD_PREFIX KEYBOARD_DUMMY_
#endif
extern uint16_t KEYBOARD_UP;
extern uint16_t KEYBOARD_DOWN;
extern uint16_t KEYBOARD_RIGHT;
extern uint16_t KEYBOARD_LEFT;
extern uint16_t KEYBOARD_SELECT;
extern uint16_t KEYBOARD_SENDSTRING;
extern uint16_t KEYBOARD_BACK;
extern uint16_t KEYBOARD_HOME;
extern uint16_t KEYBOARD_MENU;
extern uint16_t KEYBOARD_SCAN_PREVIOUS_TRACK;
extern uint16_t KEYBOARD_REWIND_LONG;
extern uint16_t KEYBOARD_REWIND;
extern uint16_t KEYBOARD_PLAYPAUSE;
extern uint16_t KEYBOARD_FASTFORWARD;
extern uint16_t KEYBOARD_FASTFORWARD_LONG;
extern uint16_t KEYBOARD_SCAN_NEXT_TRACK;
extern uint16_t KEYBOARD_MUTE;
extern uint16_t KEYBOARD_VOLUME_INCREMENT;
extern uint16_t KEYBOARD_VOLUME_DECREMENT;
// Not needed anymore, but maybe again in future
// /*
// * Concatenate preprocessor tokens A and B without expanding macro definitions
// * (however, if invoked from a macro, macro arguments are expanded).
// */
// #define PPCAT_NX(A, B) A ## B
// /*
// * Concatenate preprocessor tokens A and B after macro-expanding them.
// */
// #define PPCAT(A, B) PPCAT_NX(A, B)
//
// Test
// https://stackoverflow.com/questions/5256313/c-c-macro-string-concatenation
// #define STR(x) #x
// #define XSTR(x) STR(x)
// #pragma message "1 The value is: " XSTR(KEYBOARD_BLE_UP)
// #pragma message "2 The value is: " XSTR(KEYBOARD_MQTT_UP)
// #pragma message "3 The value is: " XSTR(KEYBOARD_UP)
enum commandHandlers {
SPECIAL,
SCENE,
IR,
#if (ENABLE_WIFI_AND_MQTT == 1)
MQTT,
#endif
#if (ENABLE_KEYBOARD_BLE == 1)
BLE_KEYBOARD,
#endif
};
struct commandData {
commandHandlers commandHandler;
std::list<std::string> commandPayloads;
};
// we don't yet have a command id
void register_command(uint16_t *command, commandData aCommandData);
// we already have a command id. Only used by BLE keyboard
void register_command_withID(uint16_t command, commandData aCommandData);
// only get a unique ID. used by KEYBOARD_DUMMY, COMMAND_UNKNOWN and BLE keyboard
void get_uniqueCommandID(uint16_t *command);
void register_keyboardCommands();
commandData makeCommandData(commandHandlers a, std::list<std::string> b);
void executeCommand(uint16_t command, std::string additionalPayload = "");

View file

@ -1,10 +1,7 @@
#include <lvgl.h>
#include "hardware/tft.h"
#include "hardware/sleep.h"
#include "hardware/memoryUsage.h"
#include "gui_general_and_keys/guiBase.h"
#include "gui_general_and_keys/guiRegistry.h"
#include "gui_general_and_keys/guiMemoryOptimizer.h"
#include "applicationInternal/hardware/hardwarePresenter.h"
#include "applicationInternal/memoryUsage.h"
#include "applicationInternal/gui/guiMemoryOptimizer.h"
lv_color_t color_primary = lv_color_hex(0x303030); // gray
lv_obj_t* MemoryUsageLabel = NULL;
@ -28,6 +25,9 @@ lv_style_t panel_style;
lv_style_t style_red_border;
#endif
void guis_doTabCreationAtStartup();
void guis_doAfterSliding(int oldTabID, int newTabID);
// Helper Functions -----------------------------------------------------------------------------------------------------------------------
// Set the page indicator (panel) scroll position relative to the tabview content scroll position
@ -35,9 +35,9 @@ lv_style_t style_red_border;
void tabview_content_is_scrolling_event_cb(lv_event_t* e){
if (panel == NULL) { return;}
float bias = float(150.0 + 8.0) / 240.0;
// screenwidth indicator ?? 2 small hidden buttons ??
int offset = 240 / 2 - 150 / 2 - 8 - 2*50 / 2 -4;
float bias = float(150.0 + 8.0) / SCR_WIDTH;
// screenwidth indicator ?? 2 small hidden buttons ??
int offset = SCR_WIDTH / 2 - 150 / 2 - 8 - 2*50 / 2 -4;
// get the object to which the event is sent
lv_obj_t* tabviewContent = lv_event_get_target(e);
@ -57,7 +57,7 @@ void tabview_content_is_scrolling_event_cb(lv_event_t* e){
static bool waitBeforeActionAfterSlidingAnimationEnded = false;
static unsigned long waitBeforeActionAfterSlidingAnimationEnded_timerStart;
// This is the callback when the animation of the tab sliding ended
void tabview_animation_ready_cb(lv_anim_t* a) {
static void tabview_animation_ready_cb(lv_anim_t* a) {
// Unfortunately, the animation has not completely ended here. We cannot do the recreation of the tabs here.
// We have to wait some more milliseconds or at least one cycle of lv_timer_handler();
// calling lv_timer_handler(); here does not help
@ -71,7 +71,7 @@ void tabview_animation_ready_cb(lv_anim_t* a) {
// Update currentTabID when a new tab is selected
// this is a callback if the tabview is changed (LV_EVENT_VALUE_CHANGED)
// Sent when a new tab is selected by sliding or clicking the tab button. lv_tabview_get_tab_act(tabview) returns the zero based index of the current tab.
void tabview_tab_changed_event_cb(lv_event_t* e){
void tabview_tab_changed_event_cb(lv_event_t* e) {
if (lv_event_get_code(e) == LV_EVENT_VALUE_CHANGED) {
oldTabID = currentTabID;
@ -85,61 +85,17 @@ void tabview_tab_changed_event_cb(lv_event_t* e){
// (lv_anim_exec_xcb_t) lv_obj_set_x does not find an animation. NULL is good as well.
lv_anim_t* anim = lv_anim_get(tabContainer, NULL); // (lv_anim_exec_xcb_t) lv_obj_set_x);
if(anim) {
// Swipe is not yet complete. User released the touch screen, an animation will bring it to the end.
// That's the normal (and only?) case for the tft touchscreen
lv_anim_set_ready_cb(anim, tabview_animation_ready_cb);
} else {
// Swipe is complete, no additional animation is needed. Most likely only possible in simulator
Serial.println("Change of tab detected, without animation at the end. Will directly do my job after sliding.");
guis_doAfterSliding(oldTabID, currentTabID);
}
}
}
// Display flushing
void my_disp_flush( lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p ){
uint32_t w = ( area->x2 - area->x1 + 1 );
uint32_t h = ( area->y2 - area->y1 + 1 );
tft.startWrite();
tft.setAddrWindow(area->x1, area->y1, w, h);
#ifdef useTwoBuffersForlvgl
tft.pushPixelsDMA((uint16_t*)&color_p->full, w * h);
#else
tft.pushColors((uint16_t*)&color_p->full, w * h, true);
#endif
tft.endWrite();
lv_disp_flush_ready( disp );
}
// Read the touchpad
void my_touchpad_read(lv_indev_drv_t * indev_driver, lv_indev_data_t * data){
// int16_t touchX, touchY;
touchPoint = touch.getPoint();
int16_t touchX = touchPoint.x;
int16_t touchY = touchPoint.y;
bool touched = false;
if ((touchX > 0) || (touchY > 0)) {
touched = true;
resetStandbyTimer();
}
if( !touched ){
data->state = LV_INDEV_STATE_REL;
}
else{
data->state = LV_INDEV_STATE_PR;
// Set the coordinates
data->point.x = screenWidth - touchX;
data->point.y = screenHeight - touchY;
//Serial.print( "touchpoint: x" );
//Serial.print( touchX );
//Serial.print( " y" );
//Serial.println( touchY );
//tft.drawFastHLine(0, screenHeight - touchY, screenWidth, TFT_RED);
//tft.drawFastVLine(screenWidth - touchX, 0, screenHeight, TFT_RED);
}
}
static lv_disp_draw_buf_t draw_buf;
void setMainWidgetsHeightAndPosition();
void init_gui_status_bar();
void init_gui_memoryUsage_bar();
@ -148,30 +104,7 @@ void init_gui(void) {
// Setup LVGL ---------------------------------------------------------------------------------------------
lv_init();
#ifdef useTwoBuffersForlvgl
lv_color_t * bufA = (lv_color_t *) malloc(sizeof(lv_color_t) * screenWidth * screenHeight / 10);
lv_color_t * bufB = (lv_color_t *) malloc(sizeof(lv_color_t) * screenWidth * screenHeight / 10);
lv_disp_draw_buf_init(&draw_buf, bufA, bufB, screenWidth * screenHeight / 10);
#else
lv_color_t * bufA = (lv_color_t *) malloc(sizeof(lv_color_t) * screenWidth * screenHeight / 10);
lv_disp_draw_buf_init(&draw_buf, bufA, NULL, screenWidth * screenHeight / 10);
#endif
// Initialize the display driver --------------------------------------------------------------------------
static lv_disp_drv_t disp_drv;
lv_disp_drv_init( &disp_drv );
disp_drv.hor_res = screenWidth;
disp_drv.ver_res = screenHeight;
disp_drv.flush_cb = my_disp_flush;
disp_drv.draw_buf = &draw_buf;
lv_disp_drv_register( &disp_drv );
// Initialize the touchscreen driver
static lv_indev_drv_t indev_drv;
lv_indev_drv_init( &indev_drv );
indev_drv.type = LV_INDEV_TYPE_POINTER;
indev_drv.read_cb = my_touchpad_read;
lv_indev_drv_register( &indev_drv );
init_lvgl_hardware();
// -- draw red border around the main widgets -------------------------------------------------------------
if (!global_styles_already_initialized) {
@ -192,7 +125,7 @@ void init_gui(void) {
lv_obj_set_style_bg_color(lv_scr_act(), lv_color_black(), LV_PART_MAIN);
// set default height and position of main widgets
setMainWidgetsHeightAndPosition();
// At startup, set current GUI according to currentGUIname, and create the content of that tab (and the previous and the next) for the first time
// At startup, set current GUI according to get_currentGUIname(), and create the content of that tab (and the previous and the next) for the first time
guis_doTabCreationAtStartup();
// memoryUsage bar
init_gui_memoryUsage_bar();
@ -216,7 +149,7 @@ void setMainWidgetsHeightAndPosition() {
statusbarTop = memoryUsageBarTop + memoryUsageBarHeight;
statusbarHeight = 20;
tabviewTop = statusbarTop + statusbarHeight;
tabviewHeight = 320 - memoryUsageBarHeight - statusbarHeight - panelHeight;
tabviewHeight = SCR_HEIGHT - memoryUsageBarHeight - statusbarHeight - panelHeight;
labelsPositionTop = -2;
}
@ -226,22 +159,22 @@ lv_obj_t* statusbar;
void showMemoryUsageBar(bool showBar) {
setMainWidgetsHeightAndPosition();
lv_obj_set_size(memoryUsageBar, 240, memoryUsageBarHeight);
lv_obj_set_size(memoryUsageBar, SCR_WIDTH, memoryUsageBarHeight);
lv_obj_align(memoryUsageBar, LV_ALIGN_TOP_MID, 0, memoryUsageBarTop);
lv_obj_set_size(statusbar, 240, statusbarHeight);
lv_obj_set_size(statusbar, SCR_WIDTH, statusbarHeight);
lv_obj_align(statusbar, LV_ALIGN_TOP_MID, 0, statusbarTop);
lv_obj_set_size(tabview, screenWidth, tabviewHeight);
lv_obj_set_size(tabview, SCR_WIDTH, tabviewHeight);
lv_obj_align(tabview, LV_ALIGN_TOP_MID, 0, tabviewTop);
return;
if (showBar) {
// lv_obj_clear_flag(memoryUsageBar, LV_OBJ_FLAG_HIDDEN);
lv_obj_set_size(memoryUsageBar, 240, memoryUsageBarHeight);
lv_obj_set_size(memoryUsageBar, SCR_WIDTH, memoryUsageBarHeight);
lv_obj_align(memoryUsageBar, LV_ALIGN_TOP_MID, 0, memoryUsageBarTop);
lv_obj_set_size(statusbar, 240, statusbarHeight);
lv_obj_set_size(statusbar, SCR_WIDTH, statusbarHeight);
lv_obj_align(statusbar, LV_ALIGN_TOP_MID, 0, statusbarTop);
lv_obj_set_size(tabview, screenWidth, tabviewHeight);
lv_obj_set_size(tabview, SCR_WIDTH, tabviewHeight);
lv_obj_align(tabview, LV_ALIGN_TOP_MID, 0, tabviewTop);
} else {
// lv_obj_add_flag(memoryUsageBar, LV_OBJ_FLAG_HIDDEN);
@ -252,7 +185,7 @@ void showMemoryUsageBar(bool showBar) {
void init_gui_memoryUsage_bar() {
// Create a memory status text bar at the top -------------------------------------------------------------
memoryUsageBar = lv_btn_create(lv_scr_act());
lv_obj_set_size(memoryUsageBar, 240, memoryUsageBarHeight);
lv_obj_set_size(memoryUsageBar, SCR_WIDTH, memoryUsageBarHeight);
lv_obj_set_style_shadow_width(memoryUsageBar, 0, LV_PART_MAIN);
lv_obj_set_style_bg_color(memoryUsageBar, lv_color_black(), LV_PART_MAIN);
#ifdef drawRedBorderAroundMainWidgets
@ -272,7 +205,7 @@ void init_gui_memoryUsage_bar() {
void init_gui_status_bar() {
// Create a status bar at the top -------------------------------------------------------------------------
statusbar = lv_btn_create(lv_scr_act());
lv_obj_set_size(statusbar, 240, statusbarHeight);
lv_obj_set_size(statusbar, SCR_WIDTH, statusbarHeight);
lv_obj_set_style_shadow_width(statusbar, 0, LV_PART_MAIN);
lv_obj_set_style_bg_color(statusbar, lv_color_black(), LV_PART_MAIN);
#ifdef drawRedBorderAroundMainWidgets
@ -286,7 +219,7 @@ void init_gui_status_bar() {
// WiFi -------------------------------------------------------------------------
WifiLabel = lv_label_create(statusbar);
lv_label_set_text(WifiLabel, "");
lv_obj_align(WifiLabel, LV_ALIGN_TOP_LEFT, 0, labelsPositionTopStatusbar +1);
lv_obj_align(WifiLabel, LV_ALIGN_TOP_LEFT, 0, labelsPositionTopStatusbar);
lv_obj_set_style_text_font(WifiLabel, &lv_font_montserrat_12, LV_PART_MAIN);
// Bluetooth --------------------------------------------------------------------
BluetoothLabel = lv_label_create(statusbar);
@ -357,3 +290,11 @@ void setActiveTab(uint32_t index, lv_anim_enable_t anim_en) {
// log_memory();
}
}
void showWiFiConnected_cb(bool connected) {
if (connected) {
if (WifiLabel != NULL) {lv_label_set_text(WifiLabel, LV_SYMBOL_WIFI);}
} else {
if (WifiLabel != NULL) {lv_label_set_text(WifiLabel, "");}
}
}

View file

@ -1,48 +1,37 @@
#ifndef __GUIBASE_H__
#define __GUIBASE_H__
#pragma once
#include <lvgl.h>
#include "../hardware/tft.h"
// -----------------------
// https://docs.lvgl.io/8.3/porting/display.html?highlight=lv_disp_draw_buf_init#buffering-modes
// With two buffers, the rendering and refreshing of the display become parallel operations
// Second buffer needs 15.360 bytes more memory in heap.
#define useTwoBuffersForlvgl
// LVGL declarations
LV_IMG_DECLARE(high_brightness);
LV_IMG_DECLARE(low_brightness);
// used by memoryUsage.cpp
extern lv_obj_t* MemoryUsageLabel;
extern lv_obj_t* WifiLabel;
// used by guiStatusUpdate.cpp
extern lv_obj_t* BluetoothLabel;
extern lv_obj_t* SceneLabel;
extern lv_obj_t* BattPercentageLabel;
extern lv_obj_t* BattIconLabel;
// used by sceneHandler.cpp
extern lv_obj_t* SceneLabel;
// used by guiMemoryOptimizer.cpp
extern lv_style_t panel_style;
extern int tabviewTop;
extern int tabviewHeight;
extern int panelHeight;
extern uint32_t currentTabID;
// used by almost all gui_*.cpp
extern lv_color_t color_primary;
//#define drawRedBorderAroundMainWidgets
#ifdef drawRedBorderAroundMainWidgets
extern lv_style_t style_red_border;
#endif
extern lv_style_t panel_style;
extern int tabviewTop;
extern int tabviewHeight;
extern int panelHeight;
extern lv_color_t color_primary;
extern uint32_t currentTabID;
// used by main.cpp and sceneHandler.cpp
void init_gui(void);
void gui_loop(void);
// used by guiMemoryOptimizer.cpp
void tabview_content_is_scrolling_event_cb(lv_event_t* e);
void tabview_tab_changed_event_cb(lv_event_t* e);
void guis_doTabCreationAtStartup();
void guis_doAfterSliding(int oldTabID, int newTabID);
void setActiveTab(uint32_t index, lv_anim_enable_t anim_en);
// used by memoryUsage.cpp
void showMemoryUsageBar(bool showBar);
#endif /*__GUIBASE_H__*/
// used as callback from hardware
void showWiFiConnected_cb(bool connected);

View file

@ -0,0 +1,42 @@
#include <lvgl.h>
#ifndef LV_ATTRIBUTE_MEM_ALIGN
#define LV_ATTRIBUTE_MEM_ALIGN
#endif
#ifndef LV_ATTRIBUTE_IMG_GRADIENTLEFT
#define LV_ATTRIBUTE_IMG_GRADIENTLEFT
#endif
const LV_ATTRIBUTE_MEM_ALIGN LV_ATTRIBUTE_LARGE_CONST LV_ATTRIBUTE_IMG_GRADIENTLEFT uint8_t gradientLeft_map[] = {
0xfa, 0xf2, 0xea, 0xe2, 0xda, 0xd1, 0xc7, 0xbe, 0xb7, 0xae, 0xa6, 0x9e, 0x95, 0x8d, 0x84, 0x7d, 0x74, 0x6c, 0x62, 0x5a, 0x51, 0x48, 0x41, 0x38, 0x2f, 0x28, 0x1f, 0x17, 0x0f, 0x07,
};
const lv_img_dsc_t gradientLeft = {
.header.cf = LV_IMG_CF_ALPHA_8BIT,
.header.always_zero = 0,
.header.reserved = 0,
.header.w = 30,
.header.h = 1,
.data_size = 30,
.data = gradientLeft_map,
};
#ifndef LV_ATTRIBUTE_IMG_GRADIENTRIGHT
#define LV_ATTRIBUTE_IMG_GRADIENTRIGHT
#endif
const LV_ATTRIBUTE_MEM_ALIGN LV_ATTRIBUTE_LARGE_CONST LV_ATTRIBUTE_IMG_GRADIENTRIGHT uint8_t gradientRight_map[] = {
0x07, 0x0f, 0x17, 0x1f, 0x28, 0x2f, 0x38, 0x41, 0x48, 0x51, 0x5a, 0x62, 0x6c, 0x74, 0x7d, 0x84, 0x8d, 0x95, 0x9e, 0xa6, 0xae, 0xb7, 0xbe, 0xc7, 0xd1, 0xda, 0xe2, 0xea, 0xf2, 0xfa,
};
const lv_img_dsc_t gradientRight = {
.header.cf = LV_IMG_CF_ALPHA_8BIT,
.header.always_zero = 0,
.header.reserved = 0,
.header.w = 30,
.header.h = 1,
.data_size = 30,
.data = gradientRight_map,
};

View file

@ -1,7 +1,7 @@
#include <Arduino.h>
#include <lvgl.h>
#include "gui_general_and_keys/guiRegistry.h"
#include "gui_general_and_keys/guiBase.h"
#include "applicationInternal/gui/guiBase.h"
#include "applicationInternal/gui/guiRegistry.h"
#include "applicationInternal/hardware/hardwarePresenter.h"
struct tab_in_memory {
lv_obj_t* tab;
@ -71,7 +71,7 @@ lv_obj_t* create_tabview() {
lv_obj_add_style(tabview, &style_red_border, LV_PART_MAIN);
#endif
lv_obj_set_style_bg_color(tabview, lv_color_black(), LV_PART_MAIN);
lv_obj_set_size(tabview, screenWidth, tabviewHeight);
lv_obj_set_size(tabview, SCR_WIDTH, tabviewHeight);
lv_obj_align(tabview, LV_ALIGN_TOP_MID, 0, tabviewTop);
return tabview;
}
@ -80,7 +80,7 @@ lv_obj_t* create_panel() {
// Create a page indicator at the bottom ------------------------------------------------------------------
lv_obj_t* panel = lv_obj_create(lv_scr_act());
lv_obj_clear_flag(panel, LV_OBJ_FLAG_CLICKABLE); // This indicator will not be clickable
lv_obj_set_size(panel, screenWidth, panelHeight);
lv_obj_set_size(panel, SCR_WIDTH, panelHeight);
lv_obj_set_flex_flow(panel, LV_FLEX_FLOW_ROW);
lv_obj_align(panel, LV_ALIGN_BOTTOM_MID, 0, 0);
lv_obj_set_scrollbar_mode(panel, LV_SCROLLBAR_MODE_OFF);
@ -133,7 +133,7 @@ void doTabCreation_strategyMax3(lv_obj_t* tabview, uint32_t oldTabID, uint32_t n
// This is the initialization after the ESP32 has booted.
if ((tabs_in_memory_previous_listIndex[0] < list_of_guis_to_be_shown.size()) && (tabs_in_memory_previous_listIndex[0] != -1)) {
// In gui_memoryOptimizer_prepare_startup, the index of currentGUIname in list_of_guis_to_be_shown was saved, if found.
// In gui_memoryOptimizer_prepare_startup, the index of get_currentGUIname() in list_of_guis_to_be_shown was saved, if found.
// We can resume at this old state.
oldListIndex = tabs_in_memory_previous_listIndex[0] ;
if (oldListIndex == 0) {
@ -219,7 +219,7 @@ void doTabCreation_strategyMax3(lv_obj_t* tabview, uint32_t oldTabID, uint32_t n
// set the tab we swiped to as active
setActiveTab(tabToBeActivated, LV_ANIM_OFF);
currentGUIname = nameOfNewActiveTab;
set_currentGUIname(nameOfNewActiveTab);
currentTabID = tabToBeActivated;
}
}
@ -279,7 +279,7 @@ void fillPanelWithPageIndicator_strategyMax3(lv_obj_t* panel, lv_obj_t* img1, lv
lv_obj_clear_flag(btn, LV_OBJ_FLAG_CLICKABLE);
lv_obj_set_size(btn, 150, lv_pct(100));
lv_obj_t* label = lv_label_create(btn);
lv_label_set_text_fmt(label, nameOfTab.c_str());
lv_label_set_text_fmt(label, "%s", nameOfTab.c_str());
lv_obj_align(label, LV_ALIGN_CENTER, 0, 0);
lv_obj_set_style_shadow_width(btn, 0, LV_PART_MAIN);
lv_obj_set_style_bg_color(btn, color_primary, LV_PART_MAIN);
@ -333,10 +333,10 @@ void fillPanelWithPageIndicator_strategyMax3(lv_obj_t* panel, lv_obj_t* img1, lv
}
void gui_memoryOptimizer_prepare_startup() {
// find index of currentGUIname in list_of_guis_to_be_shown
// find index of get_currentGUIname() in list_of_guis_to_be_shown
for (int i=0; i<list_of_guis_to_be_shown.size(); i++) {
if (list_of_guis_to_be_shown[i] == currentGUIname) {
Serial.printf("Startup: found GUI with name \"%s\" in \"list_of_guis_to_be_shown\" at position %d\r\n", currentGUIname.c_str(), i);
if (list_of_guis_to_be_shown[i] == get_currentGUIname()) {
Serial.printf("Startup: found GUI with name \"%s\" in \"list_of_guis_to_be_shown\" at position %d\r\n", get_currentGUIname().c_str(), i);
// save position so that "guis_doAfterSliding" can use it
tabs_in_memory[0].listIndex = i;
}

View file

@ -1,7 +1,4 @@
#ifndef __GUIMEMORYOPTIMIZER_H__
#define __GUIMEMORYOPTIMIZER_H__
#pragma once
void gui_memoryOptimizer_prepare_startup();
void gui_memoryOptimizer_doAfterSliding_deletionAndCreation(lv_obj_t** tabview, int oldTabID, int newTabID, lv_obj_t** panel, lv_obj_t** img1, lv_obj_t** img2);
#endif /*__GUIMEMORYOPTIMIZER_H__*/

View file

@ -1,11 +1,11 @@
#include <Arduino.h>
#include <map>
#include <string>
#include <list>
#include <map>
#include <lvgl.h>
#include "guiRegistry.h"
#include "gui_general_and_keys/guiBase.h"
#include "applicationInternal/gui/guiBase.h"
#include "applicationInternal/hardware/hardwarePresenter.h"
// ------------------------------------------------------------------------------------
// this is a map of the registered_guis that can be accessed by name
@ -13,7 +13,6 @@ std::map<std::string, gui_definition> registered_guis_byName_map;
// This is the list of the guis that we want to be available when swiping. Need not to be all the guis that have been registered, can be only a subset.
// You can swipe through these guis. Will be in the order you place them here in the vector.
std::vector<std::string> list_of_guis_to_be_shown;
std::string currentGUIname = "";
// ------------------------------------------------------------------------------------

View file

@ -1,5 +1,4 @@
#ifndef __GUIREGISTRY_H__
#define __GUIREGISTRY_H__
#pragma once
/*
If you want to create a new GUI (tab in terms of lvgl) for the touch screen, then
@ -38,8 +37,5 @@ struct gui_definition {
extern std::map<std::string, gui_definition> registered_guis_byName_map;
extern std::vector<std::string> list_of_guis_to_be_shown;
extern std::string currentGUIname;
void register_gui(std::string a_name, create_tab_content a_create_tab_content, notify_tab_before_delete a_notify_tab_before_delete);
#endif /*__GUIREGISTRY_H__*/

View file

@ -0,0 +1,90 @@
#include <lvgl.h>
#include "applicationInternal/hardware/hardwarePresenter.h"
#include "applicationInternal/memoryUsage.h"
#include "guis/gui_settings.h"
#include "applicationInternal/gui/guiBase.h"
// --- regularly update hardware values and update GUI, used by "main.cpp" ----
void updateBatteryStatusOnGUI() {
int battery_voltage;
int battery_percentage;
get_battery_status(&battery_voltage, &battery_percentage);
char buffer1[20];
sprintf(buffer1, "Voltage: %.2f V", (float)battery_voltage / 1000);
// GUI settings
if (objBattSettingsVoltage != NULL) {lv_label_set_text_fmt(objBattSettingsVoltage, "%s", buffer1);}
if (objBattSettingsPercentage != NULL) {lv_label_set_text_fmt(objBattSettingsPercentage, "Percentage: %d%%", battery_percentage);}
//lv_label_set_text_fmt(objBattSettingsIscharging, "Is charging: %s", battery_ischarging ? "yes" : "no");
// GUI status bar at the top
char buffer2[12];
// Voltage and percentage
// sprintf(buffer2, "%.1fV, %d%%", (float)getBatteryVoltage() / 1000, battery_percentage);
// only percentage
sprintf(buffer2, "%d%%", battery_percentage);
for (int i=0; i<strlen(buffer2); i++) {
if (buffer2[i] == '.') {
buffer2[i] = ',';
}
}
// if (battery_ischarging /*|| (!battery_ischarging && getBatteryVoltage() > 4350)*/){
// // if (BattPercentageLabel != NULL) {lv_label_set_text(BattPercentageLabel, "");}
// // lv_label_set_text_fmt(BattPercentageLabel, "%d%%", battery_percentage);
// // lv_label_set_text_fmt(BattPercentageLabel, "%.1f, %d%%", (float)getBatteryVoltage() / 1000, battery_percentage);
// if (BattPercentageLabel != NULL) {lv_label_set_text(BattPercentageLabel, buffer2);}
// if (BattIconLabel != NULL) {lv_label_set_text(BattIconLabel, LV_SYMBOL_USB);}
// } else
{
// Update status bar battery indicator
// lv_label_set_text_fmt(BattPercentageLabel, "%.1f, %d%%", (float)getBatteryVoltage() / 1000, battery_percentage);
if (BattPercentageLabel != NULL) {lv_label_set_text(BattPercentageLabel, buffer2);}
if (BattIconLabel != NULL) {
if(battery_percentage > 95) lv_label_set_text(BattIconLabel, LV_SYMBOL_BATTERY_FULL);
else if(battery_percentage > 75) lv_label_set_text(BattIconLabel, LV_SYMBOL_BATTERY_3);
else if(battery_percentage > 50) lv_label_set_text(BattIconLabel, LV_SYMBOL_BATTERY_2);
else if(battery_percentage > 25) lv_label_set_text(BattIconLabel, LV_SYMBOL_BATTERY_1);
else lv_label_set_text(BattIconLabel, LV_SYMBOL_BATTERY_EMPTY);
}
}
}
#if (ENABLE_KEYBOARD_BLE == 1)
// if bluetooth is in pairing mode (pairing mode is always on, if not connected), but not connected, then blink
bool blinkBluetoothLabelIsOn = false;
void updateKeyboardBLEstatusOnGUI() {
if (!keyboardBLE_isConnected()) {
blinkBluetoothLabelIsOn = !blinkBluetoothLabelIsOn;
if (blinkBluetoothLabelIsOn) {
if (BluetoothLabel != NULL) {lv_label_set_text(BluetoothLabel, LV_SYMBOL_BLUETOOTH);}
} else {
if (BluetoothLabel != NULL) {lv_label_set_text(BluetoothLabel, "");}
}
} else {
if (!blinkBluetoothLabelIsOn) {
blinkBluetoothLabelIsOn = true;
if (BluetoothLabel != NULL) {lv_label_set_text(BluetoothLabel, LV_SYMBOL_BLUETOOTH);}
}
}
}
#endif
// update user_led, battery, BLE, memoryUsage on GUI
void updateHardwareStatusAndShowOnGUI(void) {
update_userled();
updateBatteryStatusOnGUI();
#if (ENABLE_BLUETOOTH == 1)
// adjust this if you implement other bluetooth devices than the BLE keyboard
#if (ENABLE_KEYBOARD_BLE == 1)
updateKeyboardBLEstatusOnGUI();
#endif
#endif
doLogMemoryUsage();
}

View file

@ -0,0 +1,3 @@
#pragma once
void updateHardwareStatusAndShowOnGUI(void);

View file

@ -0,0 +1,66 @@
#if defined(WIN32) || defined(__linux__)
#include "applicationInternal/hardware/arduinoLayer.h"
#include <stdarg.h>
#include <stdio.h>
#include <sys/time.h>
//#include "sdl/sdl.h"
long long current_timestamp() {
struct timeval te;
gettimeofday(&te, NULL); // get current time
long long milliseconds = te.tv_sec*1000LL + te.tv_usec/1000; // calculate milliseconds
// printf("milliseconds: %lld\r\n", milliseconds);
return milliseconds;
}
void delay(uint32_t ms) {
// we don't use this blackbox
// SDL_Delay(ms);
unsigned long startTimer = millis();
while ((millis() - startTimer) < ms) {
}
}
// we have to simulate millis()
// the first call sets firstTimestampAtProgramstart and is the reference from that on
bool millisAlreadyInitialized = false;
long long firstTimestampAtProgramstart = 0;
unsigned long millis() {
unsigned long res;
if (!millisAlreadyInitialized) {
firstTimestampAtProgramstart = current_timestamp();
millisAlreadyInitialized = true;
res = 0;
} else {
res = current_timestamp() - firstTimestampAtProgramstart;
}
// printf("millis(): %lu\r\n", res);
return res;
}
SerialClass Serial;
void SerialClass::begin(unsigned long) {
// Serial.begin is one of the first methods called in main.cpp
// So we use this to initialize the timer
unsigned long dummy = millis();
}
size_t SerialClass::printf(const char * format, ...) {
// see how they are doing it in lv_log.c
va_list args;
va_start(args, format);
int ret = vprintf(format, args);
va_end(args);
return ret;
}
size_t SerialClass::println(const char c[]) {
return printf("%s\r\n", c);
}
size_t SerialClass::println(int nr) {
return printf("%d\r\n", nr);
}
#endif

View file

@ -0,0 +1,24 @@
#pragma once
#include <stddef.h>
#if defined(ARDUINO)
// for env:esp32 we need "Arduino.h" e.g. for Serial, delay(), millis()
#include <Arduino.h>
#elif defined(WIN32) || defined(__linux__)
#include <stdint.h>
// For Windows and Linux there is no Arduino framework available. So we have to simulate at least those very few calls to Arduino functions which are left in the code.
// Note: Of course there is a lot more Arduino code in folder "hardware/ESP32/*", but this code is only active in case of esp32, so we don't have to simulate this in the Arduino layer if Windows/Linux is active.
void delay(uint32_t ms);
unsigned long millis();
class SerialClass {
public:
void begin(unsigned long);
size_t printf(const char * format, ...) __attribute__ ((format (printf, 2, 3)));
size_t println(const char c[]);
size_t println(int nr);
};
extern SerialClass Serial;
#endif

View file

@ -0,0 +1,190 @@
#include <string>
#include <list>
#include "applicationInternal/hardware/hardwarePresenter.h"
// for registering the callback to show received IR messages
#include "guis/gui_irReceiver.h"
// for registering the callback to show WiFi status
#include "applicationInternal/gui/guiBase.h"
// This include of "hardwareLayer.h" is the one and only link to folder "hardware". The file "hardwareLayer.h" does the differentiation between ESP32 and Windows/Linux.
// "hardwareLayer.h" includes all the other hardware header files as well. So everything from all hardware header files is available here - and only here.
// This include has to be here in "hardwarePresenter.cpp" and not in "hardwarePresenter.h". Otherwise the whole rest of the code would have access to the hardware too.
// The rest of the code is only allowed to use "hardwarePresenter.h".
#include "hardwareLayer.h"
// --- hardware general -------------------------------------------------------
void init_hardware_general(void) {
init_hardware_general_HAL();
}
// --- preferences ------------------------------------------------------------
void init_preferences(void) {
init_preferences_HAL();
};
void save_preferences(void) {
save_preferences_HAL();
};
std::string get_currentScene() {
return get_currentScene_HAL();
}
void set_currentScene(std::string aCurrentScene) {
set_currentScene_HAL(aCurrentScene);
}
std::string get_currentGUIname() {
return get_currentGUIname_HAL();
}
void set_currentGUIname(std::string aCurrentGUIname) {
set_currentGUIname_HAL(aCurrentGUIname);
}
// --- user led ---------------------------------------------------------------
void init_userled(void) {
init_userled_HAL();
}
void update_userled() {
update_userled_HAL();
}
// --- battery ----------------------------------------------------------------
void init_battery(void) {
init_battery_HAL();
}
void get_battery_status(int *battery_voltage, int *battery_percentage) {
get_battery_status_HAL(battery_voltage, battery_percentage);
}
// --- sleep / IMU ------------------------------------------------------------
void init_sleep() {
init_sleep_HAL();
};
void init_IMU() {
init_IMU_HAL();
};
void check_activity() {
check_activity_HAL();
};
void setLastActivityTimestamp() {
setLastActivityTimestamp_HAL();
};
uint32_t get_sleepTimeout() {
return get_sleepTimeout_HAL();
}
void set_sleepTimeout(uint32_t aSleepTimeout) {
set_sleepTimeout_HAL(aSleepTimeout);
}
bool get_wakeupByIMUEnabled() {
return get_wakeupByIMUEnabled_HAL();
}
void set_wakeupByIMUEnabled(bool aWakeupByIMUEnabled) {
set_wakeupByIMUEnabled_HAL(aWakeupByIMUEnabled);
}
// --- keypad -----------------------------------------------------------------
void init_keys(void) {
init_keys_HAL();
}
keypad_key keypad_keys[keypad_maxkeys];
void getKeys(keypad_key *keys) {
keys_getKeys_HAL(keys);
}
// --- IR sender --------------------------------------------------------------
void init_infraredSender(void) {
init_infraredSender_HAL();
}
void sendIRcode(IRprotocols protocol, std::list<std::string> commandPayloads, std::string additionalPayload) {
sendIRcode_HAL(protocol, commandPayloads, additionalPayload);
}
// --- IR receiver ------------------------------------------------------------
void start_infraredReceiver(void) {
start_infraredReceiver_HAL();
};
void shutdown_infraredReceiver(void) {
shutdown_infraredReceiver_HAL();
};
void infraredReceiver_loop(void) {
infraredReceiver_loop_HAL();
};
bool get_irReceiverEnabled() {
return get_irReceiverEnabled_HAL();
}
void set_irReceiverEnabled(bool aIrReceiverEnabled) {
if (aIrReceiverEnabled) {
set_showNewIRmessage_cb_HAL(&showNewIRmessage_cb);
} else {
set_showNewIRmessage_cb_HAL(NULL);
}
set_irReceiverEnabled_HAL(aIrReceiverEnabled);
}
// --- BLE keyboard -----------------------------------------------------------
#if (ENABLE_KEYBOARD_BLE == 1)
void init_keyboardBLE() {
init_keyboardBLE_HAL();
}
// used by "device_keyboard_ble.cpp", "sleep.cpp"
bool keyboardBLE_isConnected() {
return keyboardBLE_isConnected_HAL();
}
void keyboardBLE_end() {
keyboardBLE_end_HAL();
}
void keyboardBLE_write(uint8_t c) {
keyboardBLE_write_HAL(c);
}
void keyboardBLE_longpress(uint8_t c) {
keyboardBLE_longpress_HAL(c);
}
void keyboardBLE_home() {
keyboardBLE_home_HAL();
}
void keyboardBLE_sendString(const std::string &s) {
keyboardBLE_sendString_HAL(s);
}
void consumerControlBLE_write(const MediaKeyReport value) {
consumerControlBLE_write_HAL(value);
}
void consumerControlBLE_longpress(const MediaKeyReport value) {
consumerControlBLE_longpress_HAL(value);
}
#endif
// --- tft --------------------------------------------------------------------
void update_backligthBrighness(void) {
update_backligthBrighness_HAL();
};
uint8_t get_backlightBrightness() {
return get_backlightBrightness_HAL();
}
void set_backlightBrightness(uint8_t aBacklightBrightness){
set_backlightBrightness_HAL(aBacklightBrightness);
}
// --- lvgl -------------------------------------------------------------------
void init_lvgl_hardware() {
init_lvgl_HAL();
};
// --- WiFi / MQTT ------------------------------------------------------------
#if (ENABLE_WIFI_AND_MQTT == 1)
void init_mqtt(void) {
set_showWiFiconnected_cb_HAL(&showWiFiConnected_cb);
init_mqtt_HAL();
}
// used by "commandHandler.cpp", "sleep.cpp"
bool getIsWifiConnected() {
return getIsWifiConnected_HAL();
}
bool publishMQTTMessage(const char *topic, const char *payload) {
return publishMQTTMessage_HAL(topic, payload);
}
void wifiStop() {
wifiStop_HAL();
}
#endif
// --- memory usage -----------------------------------------------------------
void get_heapUsage(unsigned long *heapSize, unsigned long *freeHeap, unsigned long *maxAllocHeap, unsigned long *minFreeHeap) {
get_heapUsage_HAL(heapSize, freeHeap, maxAllocHeap, minFreeHeap);
}

View file

@ -0,0 +1,116 @@
#pragma once
#include <list>
#include <string>
#include "applicationInternal/hardware/arduinoLayer.h"
// --- hardware general -------------------------------------------------------
void init_hardware_general(void);
// --- preferences ------------------------------------------------------------
void init_preferences(void);
void save_preferences(void);
std::string get_currentScene();
void set_currentScene(std::string aCurrentScene);
std::string get_currentGUIname();
void set_currentGUIname(std::string aCurrentGUIname);
// --- user led ---------------------------------------------------------------
void init_userled(void);
void update_userled();
// --- battery ----------------------------------------------------------------
void init_battery(void);
void get_battery_status(int *battery_voltage, int *battery_percentage);
// --- sleep / IMU ------------------------------------------------------------
void init_sleep();
void init_IMU();
void check_activity();
void setLastActivityTimestamp();
uint32_t get_sleepTimeout();
void set_sleepTimeout(uint32_t aSleepTimeout);
bool get_wakeupByIMUEnabled();
void set_wakeupByIMUEnabled(bool aWakeupByIMUEnabled);
// --- keypad -----------------------------------------------------------------
void init_keys(void);
enum keypad_keyStates {IDLE, PRESSED, HOLD, RELEASED};
struct keypad_key {
char kchar;
int kcode;
keypad_keyStates kstate;
bool stateChanged;
};
const uint8_t keypad_maxkeys = 10;
extern keypad_key keypad_keys[keypad_maxkeys];
void getKeys(keypad_key *keypad_keys);
// --- IR sender --------------------------------------------------------------
void init_infraredSender(void);
enum IRprotocols {
IR_PROTOCOL_GC = 0,
IR_PROTOCOL_NEC = 1,
IR_PROTOCOL_SAMSUNG = 2,
IR_PROTOCOL_SONY = 3,
IR_PROTOCOL_RC5 = 4,
IR_PROTOCOL_DENON = 5
};
void sendIRcode(IRprotocols protocol, std::list<std::string> commandPayloads, std::string additionalPayload);
// --- IR receiver ------------------------------------------------------------
void start_infraredReceiver(void);
void shutdown_infraredReceiver(void);
void infraredReceiver_loop(void);
bool get_irReceiverEnabled();
void set_irReceiverEnabled(bool aIrReceiverEnabled);
// --- BLE keyboard -----------------------------------------------------------
#if (ENABLE_KEYBOARD_BLE == 1)
void init_keyboardBLE();
// used by "device_keyboard_ble.cpp", "sleep.cpp"
typedef uint8_t MediaKeyReport[2];
const uint8_t BLE_KEY_UP_ARROW = 0xDA;
const uint8_t BLE_KEY_DOWN_ARROW = 0xD9;
const uint8_t BLE_KEY_RIGHT_ARROW = 0xD7;
const uint8_t BLE_KEY_LEFT_ARROW = 0xD8;
const uint8_t BLE_KEY_RETURN = 0xB0;
const MediaKeyReport BLE_KEY_MEDIA_WWW_BACK = {0, 32};
const MediaKeyReport BLE_KEY_MEDIA_WWW_HOME = {128, 0};
const MediaKeyReport BLE_KEY_MEDIA_PREVIOUS_TRACK = {2, 0};
const MediaKeyReport BLE_KEY_MEDIA_REWIND = {0, 128};
const MediaKeyReport BLE_KEY_MEDIA_PLAY_PAUSE = {8, 0};
const MediaKeyReport BLE_KEY_MEDIA_FASTFORWARD = {0, 2};
const MediaKeyReport BLE_KEY_MEDIA_NEXT_TRACK = {1, 0};
const MediaKeyReport BLE_KEY_MEDIA_MUTE = {16, 0};
const MediaKeyReport BLE_KEY_MEDIA_VOLUME_UP = {32, 0};
const MediaKeyReport BLE_KEY_MEDIA_VOLUME_DOWN = {64, 0};
bool keyboardBLE_isConnected();
void keyboardBLE_end();
void keyboardBLE_write(uint8_t c);
void keyboardBLE_longpress(uint8_t c);
void keyboardBLE_home();
void keyboardBLE_sendString(const std::string &s);
void consumerControlBLE_write(const MediaKeyReport value);
void consumerControlBLE_longpress(const MediaKeyReport value);
#endif
// --- tft --------------------------------------------------------------------
void update_backligthBrighness(void);
uint8_t get_backlightBrightness();
void set_backlightBrightness(uint8_t aBacklightBrightness);
// --- lvgl -------------------------------------------------------------------
void init_lvgl_hardware();
// --- WiFi / MQTT ------------------------------------------------------------
#if (ENABLE_WIFI_AND_MQTT == 1)
void init_mqtt(void);
// used by "commandHandler.cpp", "sleep.cpp"
bool getIsWifiConnected();
bool publishMQTTMessage(const char *topic, const char *payload);
void wifiStop();
#endif
// --- memory usage -----------------------------------------------------------
void get_heapUsage(unsigned long *heapSize, unsigned long *freeHeap, unsigned long *maxAllocHeap, unsigned long *minFreeHeap);

View file

@ -0,0 +1,123 @@
#include <string>
#include "devices/misc/device_specialCommands.h"
#include "applicationInternal/scenes/sceneRegistry.h"
#include "applicationInternal/scenes/sceneHandler.h"
#include "applicationInternal/commandHandler.h"
#include "applicationInternal/hardware/hardwarePresenter.h"
const uint8_t ROWS = 5; //five rows
const uint8_t COLS = 5; //five columns
keypad_keyStates lastKeyState[ROWS][COLS] = {
{IDLE,IDLE,IDLE,IDLE,IDLE},
{IDLE,IDLE,IDLE,IDLE,IDLE},
{IDLE,IDLE,IDLE,IDLE,IDLE},
{IDLE,IDLE,IDLE,IDLE,IDLE},
{IDLE,IDLE,IDLE,IDLE,IDLE},
};
unsigned long lastTimeSent[ROWS][COLS] ={
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
};
bool keyIsHold[ROWS][COLS] = {
{false,false,false,false,false},
{false,false,false,false,false},
{false,false,false,false,false},
{false,false,false,false,false},
{false,false,false,false,false}
};
int repeatRate = 125; // in milliseconds
void doShortPress(char keyChar, int keyCode){
unsigned long currentMillis = millis();
if ((currentMillis - lastTimeSent[keyCode/ROWS][keyCode%ROWS]) > repeatRate) {
lastTimeSent[keyCode/ROWS][keyCode%ROWS] = currentMillis;
uint16_t command = get_command_short(get_currentScene(), keyChar);
if (command != COMMAND_UNKNOWN) {
Serial.printf("key: key '%c', will use command '%u'\r\n", keyChar, command);
executeCommand(command);
} else {
Serial.printf("key: key '%c', but no command defined\r\n", keyChar);
}
}
}
void doLongPress(char keyChar, int keyCode){
uint16_t command = get_command_long(get_currentScene(), keyChar);
if (command != COMMAND_UNKNOWN) {
Serial.printf("key: key '%c' (long press), will use command '%u'\r\n", keyChar, command);
executeCommand(command);
} else {
Serial.printf("key: key '%c' (long press), but no command defined\r\n", keyChar);
}
}
void keypad_loop(void) {
// we have to ignore the result, because in case of SINGLE_REPEATED we want to send the command again and again, but the keypad would give us only one single HOLD state, not repeatedly
getKeys(keypad_keys);
for(int i=0; i < keypad_maxkeys; i++) {
if (!keypad_keys[i].stateChanged) {
// we are not allowed to do this, because of the same reason as above
// continue;
} else {
setLastActivityTimestamp(); // Reset the sleep timer when a button is pressed
}
char keyChar = keypad_keys[i].kchar;
int keyCode = keypad_keys[i].kcode;
if (keypad_keys[i].kstate == PRESSED) {
// Serial.println("pressed");
if ((get_key_repeatMode(get_currentScene(), keyChar) == SHORT) && (lastKeyState[keyCode/ROWS][keyCode%ROWS] != PRESSED)) {
// Serial.printf("key: PRESSED of SHORT key %c (%d)\r\n", keyChar, keyCode);
doShortPress(keyChar, keyCode);
} else if ((get_key_repeatMode(get_currentScene(), keyChar) == SHORT_REPEATED) && (lastKeyState[keyCode/ROWS][keyCode%ROWS] != PRESSED)) { // here do not repeat it too early, do the repeat only in HOLD
// Serial.printf("key: PRESSED of SHORT_REPEATED key %c (%d)\r\n", keyChar, keyCode);
doShortPress(keyChar, keyCode);
}
lastKeyState[keyCode/ROWS][keyCode%ROWS] = PRESSED;
} else if (keypad_keys[i].kstate == HOLD) {
// Serial.println("hold");
if ((get_key_repeatMode(get_currentScene(), keyChar) == SHORTorLONG) && (lastKeyState[keyCode/ROWS][keyCode%ROWS] != HOLD)) {
// Serial.printf("key: HOLD of SHORTorLONG key %c (%d)\r\n", keyChar, keyCode);
// Serial.printf("will set keyIsHold to TRUE for keycode %d\r\n", keyCode);
keyIsHold[keyCode/ROWS][keyCode%ROWS] = true;
doLongPress(keyChar, keyCode);
} else if (get_key_repeatMode(get_currentScene(), keyChar) == SHORT_REPEATED) { // this is the only case where we do not check the lastKeyState, because here it is intended to repeat the action
// Serial.printf("key: HOLD of SHORT_REPEATED key %c (%d)\r\n", keyChar, keyCode);
doShortPress(keyChar, keyCode);
}
lastKeyState[keyCode/ROWS][keyCode%ROWS] = HOLD;
} else if (keypad_keys[i].kstate == RELEASED) {
// Serial.println("released");
if ((get_key_repeatMode(get_currentScene(), keyChar) == SHORTorLONG) && !keyIsHold[keyCode/ROWS][keyCode%ROWS] && (lastKeyState[keyCode/ROWS][keyCode%ROWS] != RELEASED)) {
// Serial.printf("value of keyIsHold for keycode %d is %d\r\n", keyCode, keyIsHold[keyCode/ROWS][keyCode%ROWS]);
// Serial.printf("key: RELEASED of SHORTorLONG key %c (%d)\r\n", keyChar, keyCode);
doShortPress(keyChar, keyCode);
}
// Serial.printf("will set keyIsHold to FALSE for keycode %d\r\n", keyCode);
keyIsHold[keyCode/ROWS][keyCode%ROWS] = false;
// Serial.printf("key: press of key %c (%d)\r\n", keyChar, keyCode);
lastKeyState[keyCode/ROWS][keyCode%ROWS] = RELEASED;
} else if (keypad_keys[i].kstate == IDLE) {
// Serial.println("idle");
// Serial.printf("key: idle of key %c (%d)\r\n", keyChar, keyCode);
lastKeyState[keyCode/ROWS][keyCode%ROWS] = IDLE;
}
}
}

View file

@ -1,20 +1,4 @@
#ifndef __KEYS_H__
#define __KEYS_H__
#include <Keypad.h> // modified for inverted logic
#define SW_1 32 // 1...5: Output
#define SW_2 26
#define SW_3 27
#define SW_4 14
#define SW_5 12
#define SW_A 37 // A...E: Input
#define SW_B 38
#define SW_C 39
#define SW_D 34
#define SW_E 35
#define BUTTON_PIN_BITMASK 0b1110110000000000000000000010000000000000 //IO34+IO35+IO37+IO38+IO39(+IO13)
#pragma once
enum repeatModes {
// only as fallback
@ -31,7 +15,4 @@ enum repeatModes {
SHORTorLONG,
};
void init_keys(void);
void keypad_loop(void);
#endif /*__KEYS_H__*/

View file

@ -1,6 +1,6 @@
#include <Arduino.h>
#include <lvgl.h>
#include "gui_general_and_keys/guiBase.h"
#include "applicationInternal/gui/guiBase.h"
#include "applicationInternal/hardware/hardwarePresenter.h"
bool showMemoryUsage = 0;
@ -13,13 +13,21 @@ static unsigned long updateSerialLogTimer = 0;
bool getShowMemoryUsage() {
return showMemoryUsage;
}
// forward declaration
void doLogMemoryUsage();
void setShowMemoryUsage(bool aShowMemoryUsage) {
showMemoryUsage = aShowMemoryUsage;
showMemoryUsageBar(showMemoryUsage);
doLogMemoryUsage();
}
void doLogMemoryUsage() {
// Serial.println("inside doLogMemoryUsage");
unsigned long systemHeapSize;
unsigned long freeSystemHeap;
unsigned long maxAllocSystemHeap;
unsigned long minfreeSystemHeap;
get_heapUsage(&systemHeapSize, &freeSystemHeap, &maxAllocSystemHeap, &minfreeSystemHeap);
int thresholdForESP32HeapFreeWarning; // in bytes free in heap
#if (ENABLE_WIFI_AND_MQTT == 1) && (ENABLE_BLUETOOTH == 1)
@ -31,7 +39,7 @@ void doLogMemoryUsage() {
#elif ENABLE_WIFI_AND_MQTT == 1
thresholdForESP32HeapFreeWarning = 5000;
#endif
bool doESPHeapWarning = (ESP.getFreeHeap() < thresholdForESP32HeapFreeWarning);
bool doESPHeapWarning = (freeSystemHeap < thresholdForESP32HeapFreeWarning);
bool doLVGLMemoryWarning = false;
#if LV_MEM_CUSTOM == 0
@ -40,6 +48,7 @@ void doLogMemoryUsage() {
doLVGLMemoryWarning = ((100 - mon.used_pct) < thresholdForLVGLmemoryFreeWarning);
#endif
#if defined(SHOW_LOG_ON_SERIAL)
// Serial log every 5 sec
if(millis() - updateSerialLogTimer >= 5000) {
// Serial.println("inside doLogMemoryUsage: will do serial log");
@ -50,10 +59,10 @@ void doLogMemoryUsage() {
}
Serial.printf(
"ESP32 heap: size: %6lu, used: %6lu (%2.0f%%), free: %6lu (%2.0f%%), heapMax: %6lu, heapMin: %6lu\r\n",
ESP.getHeapSize(),
ESP.getHeapSize() - ESP.getFreeHeap(), float(ESP.getHeapSize() - ESP.getFreeHeap()) / ESP.getHeapSize() * 100,
ESP.getFreeHeap(), float(ESP.getFreeHeap()) / ESP.getHeapSize() * 100,
ESP.getMaxAllocHeap(), ESP.getMinFreeHeap());
systemHeapSize,
systemHeapSize - freeSystemHeap, float(systemHeapSize - freeSystemHeap) / systemHeapSize * 100,
freeSystemHeap, float(freeSystemHeap) / systemHeapSize * 100,
maxAllocSystemHeap, minfreeSystemHeap);
#if LV_MEM_CUSTOM == 0
if (doLVGLMemoryWarning) {
@ -69,6 +78,7 @@ void doLogMemoryUsage() {
} else {
// Serial.println("inside doLogMemoryUsage: serial log skipped");
}
#endif
if (showMemoryUsage) {
char buffer[80];
@ -87,15 +97,15 @@ void doLogMemoryUsage() {
#if LV_MEM_CUSTOM != 0
#ifdef SHOW_USED_MEMORY_INSTEAD_OF_FREE_IN_GUI
sprintf(buffer, ESP32HeapWarnBegin.append("%lu/%lu (%.0f%%)").append(ESP32HeapWarnEnd).c_str() , ESP.getHeapSize()-ESP.getFreeHeap(), ESP.getHeapSize(), float(ESP.getHeapSize()-ESP.getFreeHeap()) / ESP.getHeapSize() * 100);
sprintf(buffer, ESP32HeapWarnBegin.append("%lu/%lu (%.0f%%)").append(ESP32HeapWarnEnd).c_str() , systemHeapSize-freeSystemHeap, systemHeapSize, float(systemHeapSize-freeSystemHeap) / systemHeapSize * 100);
#else
sprintf(buffer, ESP32HeapWarnBegin.append("%lu/%lu (%.0f%%)").append(ESP32HeapWarnEnd).c_str() , ESP.getFreeHeap(), ESP.getHeapSize(), float(ESP.getFreeHeap()) / ESP.getHeapSize() * 100);
sprintf(buffer, ESP32HeapWarnBegin.append("%lu/%lu (%.0f%%)").append(ESP32HeapWarnEnd).c_str() , freeSystemHeap, systemHeapSize, float(freeSystemHeap) / systemHeapSize * 100);
#endif
#else
#ifdef SHOW_USED_MEMORY_INSTEAD_OF_FREE_IN_GUI
sprintf(buffer, ESP32HeapWarnBegin.append("%lu/%lu (%.0f%%)").append(ESP32HeapWarnEnd).append(" / ").append(LVGLMemorWarnBegin).append("%lu/%lu (%d%%)").append(LVGLMemorWarnEnd).c_str(), ESP.getHeapSize()-ESP.getFreeHeap(), ESP.getHeapSize(), float(ESP.getHeapSize()-ESP.getFreeHeap()) / ESP.getHeapSize() * 100, mon.total_size - mon.free_size, mon.total_size, mon.used_pct);
sprintf(buffer, ESP32HeapWarnBegin.append("%lu/%lu (%.0f%%)").append(ESP32HeapWarnEnd).append(" / ").append(LVGLMemorWarnBegin).append("%lu/%lu (%d%%)").append(LVGLMemorWarnEnd).c_str(), systemHeapSize-freeSystemHeap, systemHeapSize, float(systemHeapSize-freeSystemHeap) / systemHeapSize * 100, mon.total_size - mon.free_size, mon.total_size, mon.used_pct);
#else
sprintf(buffer, ESP32HeapWarnBegin.append("%lu/%lu (%.0f%%)").append(ESP32HeapWarnEnd).append(" / ").append(LVGLMemorWarnBegin).append("%lu/%lu (%d%%)").append(LVGLMemorWarnEnd).c_str(), ESP.getFreeHeap(), ESP.getHeapSize(), float(ESP.getFreeHeap()) / ESP.getHeapSize() * 100, mon.free_size, mon.total_size, 100-mon.used_pct);
sprintf(buffer, ESP32HeapWarnBegin.append("%lu/%lu (%.0f%%)").append(ESP32HeapWarnEnd).append(" / ").append(LVGLMemorWarnBegin).append("%lu/%lu (%d%%)").append(LVGLMemorWarnEnd).c_str(), freeSystemHeap, systemHeapSize, float(freeSystemHeap) / systemHeapSize * 100, mon.free_size, mon.total_size, 100-mon.used_pct);
#endif
#endif

View file

@ -0,0 +1,12 @@
#pragma once
// activate log on serial output
// log on GUI is activated by button on GUI
//#define SHOW_LOG_ON_SERIAL
// comment it out to see free memory instead of used memory in GUI. Serial log will always show both.
//#define SHOW_USED_MEMORY_INSTEAD_OF_FREE_IN_GUI
bool getShowMemoryUsage();
void setShowMemoryUsage(bool aShowMemoryUsage);
void doLogMemoryUsage(void);

View file

@ -0,0 +1,51 @@
#include <string>
#include <lvgl.h>
#include "applicationInternal/gui/guiBase.h"
#include "applicationInternal/scenes/sceneRegistry.h"
#include "applicationInternal/hardware/hardwarePresenter.h"
#include "applicationInternal/commandHandler.h"
void handleScene(uint16_t command, commandData commandData, std::string additionalPayload = "") {
auto current = commandData.commandPayloads.begin();
std::string scene_name = *current;
// check if we know the new scene
if (!sceneExists(scene_name)) {
Serial.printf("scene: cannot start scene %s, because it is unknown\r\n", scene_name.c_str());
return;
} else {
Serial.printf("scene: will switch from old scene %s to new scene %s\r\n", get_currentScene().c_str(), scene_name.c_str());
}
if (SceneLabel != NULL) {lv_label_set_text(SceneLabel, "changing...");}
gui_loop();
// end old scene
if (!sceneExists(get_currentScene()) && (get_currentScene() != "")) {
Serial.printf("scene: WARNING: cannot end scene %s, because it is unknown\r\n", get_currentScene().c_str());
} else {
if (get_currentScene() != "") {
Serial.printf("scene: will call end sequence for scene %s\r\n", get_currentScene().c_str());
scene_end_sequence_from_registry(get_currentScene());
}
}
// start new scene
Serial.printf("scene: will call start sequence for scene %s\r\n", scene_name.c_str());
scene_start_sequence_from_registry(scene_name);
set_currentScene(scene_name);
if (SceneLabel != NULL) {lv_label_set_text(SceneLabel, get_currentScene().c_str());}
Serial.printf("scene: scene handling finished, new scene %s is active\r\n", get_currentScene().c_str());
}
void setLabelCurrentScene() {
if ((SceneLabel != NULL) && sceneExists(get_currentScene())) {
lv_label_set_text(SceneLabel, get_currentScene().c_str());
}
}

View file

@ -0,0 +1,7 @@
#pragma once
#include <string>
#include "applicationInternal/commandHandler.h"
void handleScene(uint16_t command, commandData commandData, std::string additionalPayload = "");
void setLabelCurrentScene();

View file

@ -1,44 +1,10 @@
#include <map>
#include <string>
#include "device_samsungTV/device_samsungTV.h"
#include "device_yamahaAmp/device_yamahaAmp.h"
#include "scenes/sceneRegistry.h"
#include "scenes/scene_allOff.h"
#include "scenes/scene_TV.h"
#include "scenes/scene_fireTV.h"
#include "scenes/scene_chromecast.h"
#include "commandHandler.h"
std::map<char, repeatModes> key_repeatModes_default {
{'o', SHORT },
{'=', SHORT }, {'<', SHORTorLONG }, {'p', SHORT }, {'>', SHORTorLONG },
{'c', SHORT }, {'i', SHORT },
{'u', SHORT },
{'l', SHORT }, {'k', SHORT }, {'r', SHORT },
{'d', SHORT },
{'b', SHORT }, {'s', SHORT },
{'+', SHORT_REPEATED}, {'m', SHORT }, {'^', SHORT },
{'-', SHORT_REPEATED}, {'e', SHORT }, {'v', SHORT },
{'1', SHORT }, {'2', SHORT }, {'3', SHORT }, {'4', SHORT },
};
std::map<char, std::string> key_commands_short_default {
{'o', SCENE_ALLOFF},
/*{'=', COMMAND_UNKNOWN},*/ /*{'<', COMMAND_UNKNOWN},*/ /*{'p', COMMAND_UNKNOWN},*/ /*{'>', COMMAND_UNKNOWN},*/
/*{'c', COMMAND_UNKNOWN}, */ /*{'i', COMMAND_UNKNOWN},*/
/*{'u', COMMAND_UNKNOWN},*/
/*{'l', COMMAND_UNKNOWN},*/ /*{'k', COMMAND_UNKNOWN},*/ /*{'r', COMMAND_UNKNOWN},*/
/*{'d', COMMAND_UNKNOWN},*/
/* {'b', COMMAND_UNKNOWN},*/ /*{'s', COMMAND_UNKNOWN},*/
{'+', YAMAHA_VOL_PLUS}, {'m', YAMAHA_MUTE_TOGGLE}, /*{'^', COMMAND_UNKNOWN},*/
{'-', YAMAHA_VOL_MINUS}, /*{'e', COMMAND_UNKNOWN},*/ /*{'v', COMMAND_UNKNOWN},*/
{'1', SCENE_TV}, {'2', SCENE_FIRETV}, {'3', SCENE_CHROMECAST}, {'4', YAMAHA_STANDARD},
};
std::map<char, std::string> key_commands_long_default {
};
#include <stdexcept>
#include "devices/misc/device_specialCommands.h"
#include "applicationInternal/scenes/sceneRegistry.h"
#include "applicationInternal/hardware/hardwarePresenter.h"
// scenes
#include "scenes/scene__defaultKeys.h"
// https://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work
struct scene_definition {
@ -115,7 +81,7 @@ repeatModes get_key_repeatMode(std::string sceneName, char keyChar) {
}
}
std::string get_command_short(std::string sceneName, char keyChar) {
uint16_t get_command_short(std::string sceneName, char keyChar) {
try {
// look if the map of the current scene has a definition for it
if ((registered_scenes.count(sceneName) > 0) && (registered_scenes.at(sceneName).this_key_commands_short->count(keyChar) > 0)) {
@ -140,7 +106,7 @@ std::string get_command_short(std::string sceneName, char keyChar) {
}
std::string get_command_long(std::string sceneName, char keyChar) {
uint16_t get_command_long(std::string sceneName, char keyChar) {
try {
// look if the map of the current scene has a definition for it
if ((registered_scenes.count(sceneName) > 0) && (registered_scenes.at(sceneName).this_key_commands_long->count(keyChar) > 0)) {
@ -165,3 +131,27 @@ std::string get_command_long(std::string sceneName, char keyChar) {
}
char KEY_OFF = 'o';
char KEY_STOP = '=';
char KEY_REWI = '<';
char KEY_PLAY = 'p';
char KEY_FORW = '>';
char KEY_CONF = 'c';
char KEY_INFO = 'i';
char KEY_UP = 'u';
char KEY_DOWN = 'd';
char KEY_LEFT = 'l';
char KEY_RIGHT = 'r';
char KEY_OK = 'k';
char KEY_BACK = 'b';
char KEY_SRC = 's';
char KEY_VOLUP = '+';
char KEY_VOLDO = '-';
char KEY_MUTE = 'm';
char KEY_REC = 'e';
char KEY_CHUP = '^';
char KEY_CHDOW = 'v';
char KEY_RED = '1';
char KEY_GREEN = '2';
char KEY_YELLO = '3';
char KEY_BLUE = '4';

Some files were not shown because too many files have changed in this diff Show more