Add Serial Console app and update other apps for new SDK (#10)

This commit is contained in:
Ken Van Hoeylandt
2025-10-08 23:28:37 +02:00
committed by GitHub
parent d33e7a41df
commit a42f018ddc
29 changed files with 1679 additions and 30 deletions
+8
View File
@@ -49,3 +49,11 @@ jobs:
uses: ./.github/actions/build-app uses: ./.github/actions/build-app
with: with:
app_name: HelloWorld app_name: HelloWorld
SerialConsole:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: "Build"
uses: ./.github/actions/build-app
with:
app_name: SerialConsole
+1 -1
View File
@@ -1,7 +1,7 @@
[manifest] [manifest]
version=0.1 version=0.1
[target] [target]
sdk=0.6.0-SNAPSHOT10 sdk=0.6.0-SNAPSHOT11
platforms=esp32,esp32s3 platforms=esp32,esp32s3
[app] [app]
id=one.tactility.calculator id=one.tactility.calculator
+2 -3
View File
@@ -1,7 +1,6 @@
#include "Diceware.h" #include "Diceware.h"
#include <tt_app_alertdialog.h> #include <tt_app_alertdialog.h>
#include <tt_file.h>
#include <tt_lock.h> #include <tt_lock.h>
#include <tt_lvgl.h> #include <tt_lvgl.h>
#include <tt_lvgl_toolbar.h> #include <tt_lvgl_toolbar.h>
@@ -38,7 +37,7 @@ static Str readWordAtLine(const AppHandle handle, const int lineIndex) {
return ""; return "";
} }
auto lock = tt_lock_alloc_for_file(path); auto lock = tt_lock_alloc_for_path(path);
Str word; Str word;
if (tt_lock_acquire(lock, TT_MAX_TICKS)) { if (tt_lock_acquire(lock, TT_MAX_TICKS)) {
FILE* file = fopen(path, "r"); FILE* file = fopen(path, "r");
@@ -85,7 +84,7 @@ void Diceware::startJob(uint32_t jobWordCount) {
} }
void Diceware::onFinishJob(Str result) { void Diceware::onFinishJob(Str result) {
tt_lvgl_lock(); tt_lvgl_lock(TT_MAX_TICKS);
lv_label_set_text(resultLabel, result.c_str()); lv_label_set_text(resultLabel, result.c_str());
tt_lvgl_unlock(); tt_lvgl_unlock();
} }
+1 -1
View File
@@ -1,7 +1,7 @@
[manifest] [manifest]
version=0.1 version=0.1
[target] [target]
sdk=0.6.0-SNAPSHOT10 sdk=0.6.0-SNAPSHOT11
platforms=esp32,esp32s3 platforms=esp32,esp32s3
[app] [app]
id=one.tactility.diceware id=one.tactility.diceware
+1
View File
@@ -3,6 +3,7 @@ file(GLOB_RECURSE SOURCE_FILES
# Library source files must be included directly, # Library source files must be included directly,
# because all regular dependencies get stripped by elf_loader's cmake script # because all regular dependencies get stripped by elf_loader's cmake script
../../../Libraries/Str/Source/*.c** ../../../Libraries/Str/Source/*.c**
../../../Libraries/TactilityCpp/Source/*.c**
) )
idf_component_register( idf_component_register(
+9 -17
View File
@@ -11,16 +11,16 @@
constexpr char* TAG = "GPIO"; constexpr char* TAG = "GPIO";
void Gpio::updatePinStates() { void Gpio::updatePinStates() {
tt_mutex_lock(mutex, TT_MAX_TICKS); mutex.lock();
// Update pin states // Update pin states
for (int i = 0; i < pinStates.size(); ++i) { for (int i = 0; i < pinStates.size(); ++i) {
pinStates[i] = tt_hal_gpio_get_level(i); pinStates[i] = tt_hal_gpio_get_level(i);
} }
tt_mutex_unlock(mutex); mutex.unlock();
} }
void Gpio::updatePinWidgets() { void Gpio::updatePinWidgets() {
tt_lvgl_lock(); tt_lvgl_lock(TT_MAX_TICKS);
assert(pinStates.size() == pinWidgets.size()); assert(pinStates.size() == pinWidgets.size());
for (int j = 0; j < pinStates.size(); ++j) { for (int j = 0; j < pinStates.size(); ++j) {
int level = pinStates[j]; int level = pinStates[j];
@@ -56,11 +56,11 @@ void Gpio::onTimer(void* context) {
} }
void Gpio::startTask() { void Gpio::startTask() {
tt_mutex_lock(mutex, TT_MAX_TICKS); mutex.lock();
assert(timer == nullptr); assert(timer == nullptr);
timer = tt_timer_alloc(TimerTypePeriodic, onTimer, this); timer = tt_timer_alloc(TimerTypePeriodic, onTimer, this);
tt_timer_start(timer, 100 / portTICK_PERIOD_MS); tt_timer_start(timer, 100 / portTICK_PERIOD_MS);
tt_mutex_unlock(mutex); mutex.unlock();
} }
void Gpio::stopTask() { void Gpio::stopTask() {
@@ -81,14 +81,6 @@ static int getSquareSpacing(UiScale scale) {
} }
} }
void Gpio::onCreate(AppHandle app) {
mutex = tt_mutex_alloc(MUTEX_TYPE_RECURSIVE);
}
void Gpio::onDestroy(AppHandle app) {
tt_mutex_free(mutex);
}
void Gpio::onShow(AppHandle app, lv_obj_t* parent) { void Gpio::onShow(AppHandle app, lv_obj_t* parent) {
// auto ui_scale = hal::getConfiguration()->uiScale; // auto ui_scale = hal::getConfiguration()->uiScale;
@@ -126,7 +118,7 @@ void Gpio::onShow(AppHandle app, lv_obj_t* parent) {
auto* row_wrapper = createGpioRowWrapper(centering_wrapper); auto* row_wrapper = createGpioRowWrapper(centering_wrapper);
lv_obj_align(row_wrapper, LV_ALIGN_TOP_MID, 0, 0); lv_obj_align(row_wrapper, LV_ALIGN_TOP_MID, 0, 0);
tt_mutex_lock(mutex, TT_MAX_TICKS); mutex.lock();
auto pin_count = tt_hal_gpio_get_pin_count(); auto pin_count = tt_hal_gpio_get_pin_count();
pinStates.resize(pin_count); pinStates.resize(pin_count);
@@ -166,7 +158,7 @@ void Gpio::onShow(AppHandle app, lv_obj_t* parent) {
} }
} }
tt_mutex_unlock(mutex); mutex.unlock();
startTask(); startTask();
} }
@@ -174,8 +166,8 @@ void Gpio::onShow(AppHandle app, lv_obj_t* parent) {
void Gpio::onHide(AppHandle app) { void Gpio::onHide(AppHandle app) {
stopTask(); stopTask();
tt_mutex_lock(mutex, TT_MAX_TICKS); mutex.lock();
pinWidgets.clear(); pinWidgets.clear();
pinStates.clear(); pinStates.clear();
tt_mutex_unlock(mutex); mutex.unlock();
} }
+3 -4
View File
@@ -3,9 +3,10 @@
#include <TactilityCpp/App.h> #include <TactilityCpp/App.h>
#include <tt_app.h> #include <tt_app.h>
#include <tt_mutex.h>
#include <tt_timer.h> #include <tt_timer.h>
#include <TactilityCpp/Mutex.h>
#include <lvgl.h> #include <lvgl.h>
#include <vector> #include <vector>
@@ -14,15 +15,13 @@ class Gpio final : public App {
std::vector<lv_obj_t*> pinWidgets; std::vector<lv_obj_t*> pinWidgets;
std::vector<bool> pinStates; std::vector<bool> pinStates;
TimerHandle timer; TimerHandle timer;
MutexHandle mutex; Mutex mutex = Mutex(MutexTypeRecursive);
static lv_obj_t* createGpioRowWrapper(lv_obj_t* parent); static lv_obj_t* createGpioRowWrapper(lv_obj_t* parent);
static void onTimer(void* parameter); static void onTimer(void* parameter);
public: public:
void onCreate(AppHandle app) override;
void onDestroy(AppHandle app) override;
void onShow(AppHandle context, lv_obj_t* parent) override; void onShow(AppHandle context, lv_obj_t* parent) override;
void onHide(AppHandle context) override; void onHide(AppHandle context) override;
+1 -1
View File
@@ -1,7 +1,7 @@
[manifest] [manifest]
version=0.1 version=0.1
[target] [target]
sdk=0.6.0-SNAPSHOT10 sdk=0.6.0-SNAPSHOT11
platforms=esp32,esp32s3 platforms=esp32,esp32s3
[app] [app]
id=one.tactility.gpio id=one.tactility.gpio
+1 -1
View File
@@ -1,7 +1,7 @@
[manifest] [manifest]
version=0.1 version=0.1
[target] [target]
sdk=0.6.0-SNAPSHOT10 sdk=0.6.0-SNAPSHOT11
platforms=esp32,esp32s3 platforms=esp32,esp32s3
[app] [app]
id=one.tactility.graphicsdemo id=one.tactility.graphicsdemo
+1 -1
View File
@@ -1,7 +1,7 @@
[manifest] [manifest]
version=0.1 version=0.1
[target] [target]
sdk=0.6.0-SNAPSHOT10 sdk=0.6.0-SNAPSHOT11
platforms=esp32,esp32s3 platforms=esp32,esp32s3
[app] [app]
id=one.tactility.helloworld id=one.tactility.helloworld
+17
View File
@@ -0,0 +1,17 @@
cmake_minimum_required(VERSION 3.20)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
if (DEFINED ENV{TACTILITY_SDK_PATH})
set(TACTILITY_SDK_PATH $ENV{TACTILITY_SDK_PATH})
else()
set(TACTILITY_SDK_PATH "../../release/TactilitySDK")
message(WARNING "⚠️ TACTILITY_SDK_PATH environment variable is not set, defaulting to ${TACTILITY_SDK_PATH}")
endif()
include("${TACTILITY_SDK_PATH}/TactilitySDK.cmake")
set(EXTRA_COMPONENT_DIRS ${TACTILITY_SDK_PATH})
project(SerialConsole)
tactility_project(SerialConsole)
+10
View File
@@ -0,0 +1,10 @@
# Diceware
This application is based on the [Diceware](https://en.wikipedia.org/wiki/Diceware) passphrase generator.
In a regular Diceware scenario, you roll 6 dice and match it with the corresponding word from the word list.
In this application, it is simplified by getting a 32 bit random integer to get a random word from the word list.
The application asks to enable Wi-Fi because of the hardware [random generator on the ESP32](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html).
You can enable the Wi-Fi radio to improve the randomness. You don't have to be connected to any network.
If you automatically connect to a Wi-Fi network, go to the network settings and manually disconnect from it.
+17
View File
@@ -0,0 +1,17 @@
file(GLOB_RECURSE SOURCE_FILES
Source/*.c*
# Library source files must be included directly,
# because all regular dependencies get stripped by elf_loader's cmake script
../../../Libraries/Str/Source/*.c**
../../../Libraries/TactilityCpp/Source/*.c**
)
idf_component_register(
SRCS ${SOURCE_FILES}
# Library headers must be included directly,
# because all regular dependencies get stripped by elf_loader's cmake script
INCLUDE_DIRS ../../../Libraries/Str/Include
INCLUDE_DIRS ../../../Libraries/TactilityCpp/Include
REQUIRES TactilitySDK
)
@@ -0,0 +1,171 @@
#pragma once
#include "View.h"
#include <string>
#include <vector>
#include <lvgl.h>
#include <Str.h>
#include <functional>
#include <memory>
#include <tt_app_alertdialog.h>
#include <tt_hal_uart.h>
#include <tt_lvgl.h>
#include <TactilityCpp/LvglLock.h>
#include <TactilityCpp/Uart.h>
#include <TactilityCpp/Preferences.h>
class ConnectView final : public View {
public:
typedef std::function<void(std::unique_ptr<Uart>)> OnConnectedFunction;
std::vector<Str> uartNames;
Preferences preferences = Preferences("SerialConsole");
LvglLock lvglLock;
private:
OnConnectedFunction onConnected;
lv_obj_t* busDropdown = nullptr;
lv_obj_t* speedTextarea = nullptr;
Str join(const std::vector<Str>& list) {
Str output;
for (int i = list.size() - 1; i >= 0; i--) {
output.append(list[i].c_str());
if (i < list.size() - 1) {
output.append(",");
}
}
return output;
}
int32_t getSpeedInput() const {
auto* speed_text = lv_textarea_get_text(speedTextarea);
return atoi(speed_text);
}
void onConnect() {
auto lock = lvglLock.asScopedLock();
if (!lock.lock(TT_LVGL_DEFAULT_LOCK_TIME)) {
return;
}
const char* alert_dialog_labels[] = { "OK" };
auto selected_uart_index = lv_dropdown_get_selected(busDropdown);
if (selected_uart_index >= uartNames.size()) {
tt_app_alertdialog_start("Error", "No UART selected", alert_dialog_labels, 1);
return;
}
auto uart = Uart::open(selected_uart_index);
if (uart == nullptr) {
tt_app_alertdialog_start("Error", "Failed to connect to UART", alert_dialog_labels, 1);
return;
}
int speed = getSpeedInput();
if (speed <= 0) {
tt_app_alertdialog_start("Error", "Invalid speed", alert_dialog_labels, 1);
return;
}
if (!uart->start()) {
tt_app_alertdialog_start("Error", "Failed to initialize", alert_dialog_labels, 1);
return;
}
if (!uart->setBaudRate(speed)) {
uart->stop();
tt_app_alertdialog_start("Error", "Failed to set baud rate", alert_dialog_labels, 1);
return;
}
onConnected(std::move(uart));
}
static void onConnectCallback(lv_event_t* event) {
auto* view = static_cast<ConnectView*>(lv_event_get_user_data(event));
view->onConnect();
}
static lv_obj_t* createRowWrapper(lv_obj_t* parent) {
auto* wrapper = lv_obj_create(parent);
lv_obj_set_size(wrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_border_width(wrapper, 0, LV_STATE_DEFAULT);
lv_obj_set_style_pad_all(wrapper, 0, LV_STATE_DEFAULT);
return wrapper;
}
public:
explicit ConnectView(OnConnectedFunction onConnected) : onConnected(std::move(onConnected)) {}
void onStart(lv_obj_t* parent) {
uartNames = Uart::getNames();
auto* wrapper = lv_obj_create(parent);
lv_obj_set_flex_flow(wrapper, LV_FLEX_FLOW_COLUMN);
lv_obj_set_size(wrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_border_width(wrapper, 0, LV_STATE_DEFAULT);
lv_obj_set_style_bg_opa(wrapper, 0, LV_STATE_DEFAULT);
// Bus selection
auto* bus_wrapper = createRowWrapper(wrapper);
busDropdown = lv_dropdown_create(bus_wrapper);
auto bus_options = join(uartNames);
lv_dropdown_set_options(busDropdown, bus_options.c_str());
lv_obj_align(busDropdown, LV_ALIGN_RIGHT_MID, 0, 0);
lv_obj_set_width(busDropdown, LV_PCT(50));
int32_t bus_index = 0;
preferences.optInt32("bus", bus_index);
if (bus_index < uartNames.size()) {
lv_dropdown_set_selected(busDropdown, bus_index);
}
auto* bus_label = lv_label_create(bus_wrapper);
lv_obj_align(bus_label, LV_ALIGN_LEFT_MID, 0, 0);
lv_label_set_text(bus_label, "Bus");
// Baud rate selection
auto* baud_wrapper = createRowWrapper(wrapper);
int32_t speed = 115200;
preferences.optInt32("speed", speed);
speedTextarea = lv_textarea_create(baud_wrapper);
lv_textarea_set_text(speedTextarea, std::to_string(speed).c_str());
lv_textarea_set_one_line(speedTextarea, true);
lv_obj_set_width(speedTextarea, LV_PCT(50));
lv_obj_align(speedTextarea, LV_ALIGN_TOP_RIGHT, 0, 0);
auto* baud_rate_label = lv_label_create(baud_wrapper);
lv_obj_align(baud_rate_label, LV_ALIGN_TOP_LEFT, 0, 0);
lv_label_set_text(baud_rate_label, "Baud");
// Connect
auto* connect_wrapper = createRowWrapper(wrapper);
auto* connect_button = lv_button_create(connect_wrapper);
lv_obj_align(connect_button, LV_ALIGN_CENTER, 0, 0);
lv_obj_add_event_cb(connect_button, onConnectCallback, LV_EVENT_SHORT_CLICKED, this);
auto* connect_label = lv_label_create(connect_button);
lv_label_set_text(connect_label, "Connect");
}
void onStop() override {
int speed = getSpeedInput();
if (speed > 0) {
preferences.putInt32("speed", speed);
}
auto bus_index = static_cast<int32_t>(lv_dropdown_get_selected(busDropdown));
preferences.putInt32("bus", bus_index);
}
};
@@ -0,0 +1,299 @@
#pragma once
#include "View.h"
#include "esp_log.h"
#include <Str.h>
#include <sstream>
#include <lvgl.h>
#include <memory>
#include <tt_lvgl.h>
#include <tt_thread.h>
#include <TactilityCpp/Mutex.h>
#include <TactilityCpp/Thread.h>
#include <TactilityCpp/LvglLock.h>
constexpr size_t receiveBufferSize = 512;
constexpr size_t renderBufferSize = receiveBufferSize + 2; // Leave space for newline at split and null terminator at the end
class ConsoleView final : public View {
const char* TAG = "SerialConsole";
lv_obj_t* _Nullable parent = nullptr;
lv_obj_t* _Nullable logTextarea = nullptr;
lv_obj_t* _Nullable inputTextarea = nullptr;
std::shared_ptr<Uart> _Nullable uart = nullptr;
std::shared_ptr<Thread> uartThread _Nullable = nullptr;
bool uartThreadInterrupted = false;
std::shared_ptr<Thread> viewThread _Nullable = nullptr;
bool viewThreadInterrupted = false;
Mutex mutex = Mutex(MutexTypeRecursive);
uint8_t receiveBuffer[receiveBufferSize];
uint8_t renderBuffer[renderBufferSize];
size_t receiveBufferPosition = 0;
Str terminatorString = "\n";
LvglLock lvglLock;
bool isUartThreadInterrupted() const {
auto lock = mutex.asScopedLock();
lock.lock();
return uartThreadInterrupted;
}
bool isViewThreadInterrupted() const {
auto lock = mutex.asScopedLock();
lock.lock();
return viewThreadInterrupted;
}
void updateViews() {
auto scoped_lvgl_lock = lvglLock.asScopedLock();
if (!scoped_lvgl_lock.lock()) {
return;
}
if (parent == nullptr) {
return;
}
// Updating the view is expensive, so we only want to set the text once:
// Gather all the lines in a single buffer
if (mutex.lock()) {
size_t first_part_size = receiveBufferSize - receiveBufferPosition;
memcpy(renderBuffer, receiveBuffer + receiveBufferPosition, first_part_size);
renderBuffer[receiveBufferPosition] = '\n';
if (receiveBufferPosition > 0) {
memcpy(renderBuffer + first_part_size + 1, receiveBuffer, (receiveBufferSize - first_part_size));
renderBuffer[receiveBufferSize - 1] = 0x00;
}
mutex.unlock();
}
tt_lvgl_lock(TT_MAX_TICKS);
lv_textarea_set_text(logTextarea, (const char*)renderBuffer);
tt_lvgl_unlock();
}
int32_t viewThreadMain() {
while (!isViewThreadInterrupted()) {
auto start_time = tt_kernel_get_ticks();
updateViews();
auto end_time = tt_kernel_get_ticks();
auto time_diff = end_time - start_time;
if (time_diff < 500U) {
tt_kernel_delay_ticks((500U - time_diff) / portTICK_PERIOD_MS);
}
}
return 0;
}
static int32_t viewThreadMainStatic(void* context) {
auto* self = static_cast<ConsoleView*>(context);
return self->viewThreadMain();
}
int32_t uartThreadMain() {
char byte;
while (!isUartThreadInterrupted()) {
assert(uart != nullptr);
bool success = uart->readByte(&byte, 50 / portTICK_PERIOD_MS);
// Thread might've been interrupted in the meanwhile
if (isUartThreadInterrupted()) {
break;
}
if (success) {
mutex.lock();
receiveBuffer[receiveBufferPosition++] = byte;
if (receiveBufferPosition == receiveBufferSize) {
receiveBufferPosition = 0;
}
mutex.unlock();
}
}
return 0;
}
static int32_t uartThreadMainStatic(void* view) {
auto* self = static_cast<ConsoleView*>(view);
return self->uartThreadMain();
}
static void onSendClickedCallback(lv_event_t* event) {
auto* view = (ConsoleView*)lv_event_get_user_data(event);
view->onSendClicked();
}
static void onTerminatorDropdownValueChangedCallback(lv_event_t* event) {
auto* view = (ConsoleView*)lv_event_get_user_data(event);
view->onTerminatorDropDownValueChanged(event);
}
void onTerminatorDropDownValueChanged(lv_event_t* event) {
auto* dropdown = static_cast<lv_obj_t*>(lv_event_get_target(event));
mutex.lock();
switch (lv_dropdown_get_selected(dropdown)) {
case 0:
terminatorString = "\n";
break;
case 1:
terminatorString = "\r\n";
break;
}
mutex.unlock();
}
void onSendClicked() {
mutex.lock();
Str input_text = lv_textarea_get_text(inputTextarea);
Str to_send;
to_send.appendf("%s%s", input_text.c_str(), terminatorString.c_str());
mutex.unlock();
if (uart != nullptr) {
if (!uart->writeBytes(to_send.c_str(), to_send.length(), 100 / portTICK_PERIOD_MS)) {
ESP_LOGE(TAG, "Failed to send \"%s\"", input_text.c_str());
}
}
lv_textarea_set_text(inputTextarea, "");
}
public:
void startLogic(std::unique_ptr<Uart> newUart) {
memset(receiveBuffer, 0, receiveBufferSize);
assert(uartThread == nullptr);
assert(uart == nullptr);
uart = std::move(newUart);
uartThreadInterrupted = false;
uartThread = std::make_unique<Thread>(
"SerConsUart",
4096,
uartThreadMainStatic,
this
);
uartThread->setPriority(ThreadPriorityHigh);
uartThread->start();
}
void startViews(lv_obj_t* parent) {
this->parent = parent;
lv_obj_set_style_pad_gap(parent, 2, 0);
logTextarea = lv_textarea_create(parent);
lv_textarea_set_placeholder_text(logTextarea, "Waiting for data...");
lv_obj_set_flex_grow(logTextarea, 1);
lv_obj_set_width(logTextarea, LV_PCT(100));
lv_obj_add_state(logTextarea, LV_STATE_DISABLED);
lv_obj_set_style_margin_ver(logTextarea, 0, 0);
auto* input_wrapper = lv_obj_create(parent);
lv_obj_set_size(input_wrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_pad_all(input_wrapper, 0, 0);
lv_obj_set_style_border_width(input_wrapper, 0, 0);
lv_obj_set_width(input_wrapper, LV_PCT(100));
lv_obj_set_flex_flow(input_wrapper, LV_FLEX_FLOW_ROW);
inputTextarea = lv_textarea_create(input_wrapper);
lv_textarea_set_one_line(inputTextarea, true);
lv_textarea_set_placeholder_text(inputTextarea, "Text to send");
lv_obj_set_width(inputTextarea, LV_PCT(100));
lv_obj_set_flex_grow(inputTextarea, 1);
auto* terminator_dropdown = lv_dropdown_create(input_wrapper);
lv_dropdown_set_options(terminator_dropdown, "\\n\n\\r\\n");
lv_obj_set_width(terminator_dropdown, 70);
lv_obj_add_event_cb(terminator_dropdown, onTerminatorDropdownValueChangedCallback, LV_EVENT_VALUE_CHANGED, this);
auto* button = lv_button_create(input_wrapper);
auto* button_label = lv_label_create(button);
lv_label_set_text(button_label, "Send");
lv_obj_add_event_cb(button, onSendClickedCallback, LV_EVENT_SHORT_CLICKED, this);
viewThreadInterrupted = false;
viewThread = std::make_unique<Thread>(
"SerConsView",
4096,
viewThreadMainStatic,
this
);
viewThread->setPriority(ThreadPriorityHigher);
viewThread->start();
}
void stopLogic() {
auto lock = mutex.asScopedLock();
lock.lock();
uartThreadInterrupted = true;
// Detach thread, it will auto-delete when leaving the current scope
auto old_uart_thread = std::move(uartThread);
// Unlock so thread can lock
lock.unlock();
if (old_uart_thread->getState() != ThreadStateStopped) {
// Wait for thread to finish
old_uart_thread->join();
}
}
void stopViews() {
auto lock = mutex.asScopedLock();
lock.lock();
viewThreadInterrupted = true;
// Detach thread, it will auto-delete when leaving the current scope
auto old_view_thread = std::move(viewThread);
// Unlock so thread can lock
lock.unlock();
if (old_view_thread->getState() != ThreadStateStopped) {
// Wait for thread to finish
old_view_thread->join();
}
}
void stopUart() {
auto lock = mutex.asScopedLock();
lock.lock();
if (uart != nullptr && uart->isStarted()) {
uart->stop();
uart = nullptr;
}
}
void onStart(lv_obj_t* parent, std::unique_ptr<Uart> newUart) {
auto lock = mutex.asScopedLock();
lock.lock();
startLogic(std::move(newUart));
startViews(parent);
}
void onStop() override {
stopViews();
stopLogic();
stopUart();
}
};
@@ -0,0 +1,60 @@
#include "SerialConsole.h"
#include <tt_lvgl_toolbar.h>
constexpr auto* TAG = "SerialMonitor";
void SerialConsole::stopActiveView() {
if (activeView != nullptr) {
activeView->onStop();
lv_obj_clean(wrapperWidget);
activeView = nullptr;
}
}
void SerialConsole::showConsoleView(std::unique_ptr<Uart> uart) {
stopActiveView();
activeView = &consoleView;
consoleView.onStart(wrapperWidget, std::move(uart));
lv_obj_remove_flag(disconnectButton, LV_OBJ_FLAG_HIDDEN);
}
void SerialConsole::showConnectView() {
stopActiveView();
activeView = &connectView;
connectView.onStart(wrapperWidget);
lv_obj_add_flag(disconnectButton, LV_OBJ_FLAG_HIDDEN);
}
void SerialConsole::onDisconnect() {
// Changing views (calling ConsoleView::stop()) also disconnects the UART
showConnectView();
}
void SerialConsole::onDisconnectPressed(lv_event_t* event) {
auto* app = static_cast<SerialConsole*>(lv_event_get_user_data(event));
app->onDisconnect();
}
void SerialConsole::onShow(AppHandle appHandle, lv_obj_t* parent) {
lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_row(parent, 0, LV_STATE_DEFAULT);
auto* toolbar = tt_lvgl_toolbar_create_for_app(parent, appHandle);
disconnectButton = tt_lvgl_toolbar_add_image_button_action(toolbar, LV_SYMBOL_POWER, onDisconnectPressed, this);
lv_obj_add_flag(disconnectButton, LV_OBJ_FLAG_HIDDEN);
wrapperWidget = lv_obj_create(parent);
lv_obj_set_width(wrapperWidget, LV_PCT(100));
lv_obj_set_flex_grow(wrapperWidget, 1);
lv_obj_set_flex_flow(wrapperWidget, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_all(wrapperWidget, 0, LV_STATE_DEFAULT);
lv_obj_set_style_border_width(wrapperWidget, 0, LV_STATE_DEFAULT);
lv_obj_set_style_bg_opa(wrapperWidget, 0, LV_STATE_DEFAULT);
showConnectView();
}
void SerialConsole::onHide(AppHandle context) {
stopActiveView();
}
@@ -0,0 +1,28 @@
#pragma once
#include "ConnectView.h"
#include "ConsoleView.h"
#include <TactilityCpp/App.h>
class SerialConsole final : public App {
lv_obj_t* disconnectButton = nullptr;
lv_obj_t* wrapperWidget = nullptr;
ConnectView connectView = ConnectView([this](auto uart){
showConsoleView(std::move(uart));
});
ConsoleView consoleView;
View* activeView = nullptr;
void stopActiveView();
void showConsoleView(std::unique_ptr<Uart> uart);
void showConnectView();
void onDisconnect();
static void onDisconnectPressed(lv_event_t* event);
public:
void onShow(AppHandle context, lv_obj_t* parent) override;
void onHide(AppHandle context) override;
};
+6
View File
@@ -0,0 +1,6 @@
#pragma once
class View {
public:
virtual void onStop() = 0;
};
+11
View File
@@ -0,0 +1,11 @@
#include "SerialConsole.h"
#include <TactilityCpp/App.h>
extern "C" {
int main(int argc, char* argv[]) {
registerApp<SerialConsole>();
return 0;
}
}
+10
View File
@@ -0,0 +1,10 @@
[manifest]
version=0.1
[target]
sdk=0.6.0-SNAPSHOT11
platforms=esp32,esp32s3
[app]
id=one.tactility.serialconsole
versionName=0.1.0
versionCode=1
name=Serial Console
+678
View File
@@ -0,0 +1,678 @@
import configparser
import json
import os
import re
import shutil
import sys
import subprocess
import time
import urllib.request
import zipfile
import requests
import tarfile
import shutil
import configparser
ttbuild_path = ".tactility"
ttbuild_version = "2.4.0"
ttbuild_cdn = "https://cdn.tactility.one"
ttbuild_sdk_json_validity = 3600 # seconds
ttport = 6666
verbose = False
use_local_sdk = False
local_base_path = None
if sys.platform == "win32":
shell_color_red = ""
shell_color_orange = ""
shell_color_green = ""
shell_color_purple = ""
shell_color_cyan = ""
shell_color_reset = ""
else:
shell_color_red = "\033[91m"
shell_color_orange = "\033[93m"
shell_color_green = "\033[32m"
shell_color_purple = "\033[35m"
shell_color_cyan = "\033[36m"
shell_color_reset = "\033[m"
def print_help():
print("Usage: python tactility.py [action] [options]")
print("")
print("Actions:")
print(" build [esp32,esp32s3] Build the app. Optionally specify a platform.")
print(" esp32: ESP32")
print(" esp32s3: ESP32 S3")
print(" clean Clean the build folders")
print(" clearcache Clear the SDK cache")
print(" updateself Update this tool")
print(" run [ip] Run the application")
print(" install [ip] Install the application")
print(" uninstall [ip] Uninstall the application")
print(" bir [ip] [esp32,esp32s3] Build, install then run. Optionally specify a platform.")
print(" brrr [ip] [esp32,esp32s3] Functionally the same as \"bir\", but \"app goes brrr\" meme variant.")
print("")
print("Options:")
print(" --help Show this commandline info")
print(" --local-sdk Use SDK specified by environment variable TACTILITY_SDK_PATH with platform subfolders matching target platforms.")
print(" --skip-build Run everything except the idf.py/CMake commands")
print(" --verbose Show extra console output")
# region Core
def download_file(url, filepath):
global verbose
if verbose:
print(f"Downloading from {url} to {filepath}")
request = urllib.request.Request(
url,
data=None,
headers={
"User-Agent": f"Tactility Build Tool {ttbuild_version}"
}
)
try:
response = urllib.request.urlopen(request)
file = open(filepath, mode="wb")
file.write(response.read())
file.close()
return True
except OSError as error:
if verbose:
print_error(f"Failed to fetch URL {url}\n{error}")
return False
def print_warning(message):
print(f"{shell_color_orange}WARNING: {message}{shell_color_reset}")
def print_error(message):
print(f"{shell_color_red}ERROR: {message}{shell_color_reset}")
def print_status_busy(status):
sys.stdout.write(f"{status}\r")
def print_status_success(status):
# Trailing spaces are to overwrite previously written characters by a potentially shorter print_status_busy() text
print(f"{shell_color_green}{status}{shell_color_reset} ")
def print_status_error(status):
# Trailing spaces are to overwrite previously written characters by a potentially shorter print_status_busy() text
print(f"{shell_color_red}{status}{shell_color_reset} ")
def exit_with_error(message):
print_error(message)
sys.exit(1)
def get_url(ip, path):
return f"http://{ip}:{ttport}{path}"
def read_properties_file(path):
config = configparser.RawConfigParser()
config.read(path)
return config
#endregion Core
#region SDK helpers
def read_sdk_json():
json_file_path = os.path.join(ttbuild_path, "sdk.json")
json_file = open(json_file_path)
return json.load(json_file)
def get_sdk_dir(version, platform):
global use_local_sdk, local_base_path
if use_local_sdk:
base_path = local_base_path
if base_path is None:
exit_with_error("TACTILITY_SDK_PATH environment variable is not set")
sdk_parent_dir = os.path.join(base_path, f"{version}-{platform}")
sdk_dir = os.path.join(sdk_parent_dir, "TactilitySDK")
if not os.path.isdir(sdk_dir):
exit_with_error(f"Local SDK folder not found for platform {platform}: {sdk_dir}")
return sdk_dir
else:
return os.path.join(ttbuild_path, f"{version}-{platform}", "TactilitySDK")
def validate_local_sdks(platforms, version):
if not use_local_sdk:
return
global local_base_path
base_path = local_base_path
for platform in platforms:
sdk_parent_dir = os.path.join(base_path, f"{version}-{platform}")
sdk_dir = os.path.join(sdk_parent_dir, "TactilitySDK")
if not os.path.isdir(sdk_dir):
exit_with_error(f"Local SDK folder missing for {platform}: {sdk_dir}")
def get_sdk_root_dir(version, platform):
global ttbuild_cdn
return os.path.join(ttbuild_path, f"{version}-{platform}")
def get_sdk_url(version, platform):
global ttbuild_cdn
return f"{ttbuild_cdn}/TactilitySDK-{version}-{platform}.zip"
def sdk_exists(version, platform):
sdk_dir = get_sdk_dir(version, platform)
return os.path.isdir(sdk_dir)
def should_update_sdk_json():
global ttbuild_cdn
json_filepath = os.path.join(ttbuild_path, "sdk.json")
if os.path.exists(json_filepath):
json_modification_time = os.path.getmtime(json_filepath)
now = time.time()
global ttbuild_sdk_json_validity
minimum_seconds_difference = ttbuild_sdk_json_validity
return (now - json_modification_time) > minimum_seconds_difference
else:
return True
def update_sdk_json():
global ttbuild_cdn, ttbuild_path
json_url = f"{ttbuild_cdn}/sdk.json"
json_filepath = os.path.join(ttbuild_path, "sdk.json")
return download_file(json_url, json_filepath)
def should_fetch_sdkconfig_files(platform_targets):
for platform in platform_targets:
sdkconfig_filename = f"sdkconfig.app.{platform}"
if not os.path.exists(os.path.join(ttbuild_path, sdkconfig_filename)):
return True
return False
def fetch_sdkconfig_files(platform_targets):
for platform in platform_targets:
sdkconfig_filename = f"sdkconfig.app.{platform}"
target_path = os.path.join(ttbuild_path, sdkconfig_filename)
if not download_file(f"{ttbuild_cdn}/{sdkconfig_filename}", target_path):
exit_with_error(f"Failed to download sdkconfig file for {platform}")
#endregion SDK helpers
#region Validation
def validate_environment():
if os.environ.get("IDF_PATH") is None:
exit_with_error("Cannot find the Espressif IDF SDK. Ensure it is installed and that it is activated via $PATH_TO_IDF_SDK/export.sh")
if not os.path.exists("manifest.properties"):
exit_with_error("manifest.properties not found")
if use_local_sdk == False and os.environ.get("TACTILITY_SDK_PATH") is not None:
print_warning("TACTILITY_SDK_PATH is set, but will be ignored by this command.")
print_warning("If you want to use it, use the '--local-sdk' parameter")
elif use_local_sdk == True and os.environ.get("TACTILITY_SDK_PATH") is None:
exit_with_error("local build was requested, but TACTILITY_SDK_PATH environment variable is not set.")
def validate_version_and_platforms(sdk_json, sdk_version, platforms_to_build):
version_map = sdk_json["versions"]
if not sdk_version in version_map:
exit_with_error(f"Version not found: {sdk_version}")
version_data = version_map[sdk_version]
available_platforms = version_data["platforms"]
for desired_platform in platforms_to_build:
if not desired_platform in available_platforms:
exit_with_error(f"Platform {desired_platform} is not available. Available ones: {available_platforms}")
def validate_self(sdk_json):
if not "toolVersion" in sdk_json:
exit_with_error("Server returned invalid SDK data format (toolVersion not found)")
if not "toolCompatibility" in sdk_json:
exit_with_error("Server returned invalid SDK data format (toolCompatibility not found)")
if not "toolDownloadUrl" in sdk_json:
exit_with_error("Server returned invalid SDK data format (toolDownloadUrl not found)")
tool_version = sdk_json["toolVersion"]
tool_compatibility = sdk_json["toolCompatibility"]
if tool_version != ttbuild_version:
print_warning(f"New version available: {tool_version} (currently using {ttbuild_version})")
print_warning(f"Run 'tactility.py updateself' to update.")
if re.search(tool_compatibility, ttbuild_version) is None:
print_error("The tool is not compatible anymore.")
print_error("Run 'tactility.py updateself' to update.")
sys.exit(1)
#endregion Validation
#region Manifest
def read_manifest():
return read_properties_file("manifest.properties")
def validate_manifest(manifest):
# [manifest]
if not "manifest" in manifest:
exit_with_error("Invalid manifest format: [manifest] not found")
if not "version" in manifest["manifest"]:
exit_with_error("Invalid manifest format: [manifest] version not found")
# [target]
if not "target" in manifest:
exit_with_error("Invalid manifest format: [target] not found")
if not "sdk" in manifest["target"]:
exit_with_error("Invalid manifest format: [target] sdk not found")
if not "platforms" in manifest["target"]:
exit_with_error("Invalid manifest format: [target] platforms not found")
# [app]
if not "app" in manifest:
exit_with_error("Invalid manifest format: [app] not found")
if not "id" in manifest["app"]:
exit_with_error("Invalid manifest format: [app] id not found")
if not "versionName" in manifest["app"]:
exit_with_error("Invalid manifest format: [app] versionName not found")
if not "versionCode" in manifest["app"]:
exit_with_error("Invalid manifest format: [app] versionCode not found")
if not "name" in manifest["app"]:
exit_with_error("Invalid manifest format: [app] name not found")
def is_valid_manifest_platform(manifest, platform):
manifest_platforms = manifest["target"]["platforms"].split(",")
return platform in manifest_platforms
def validate_manifest_platform(manifest, platform):
if not is_valid_manifest_platform(manifest, platform):
exit_with_error(f"Platform {platform} is not available in the manifest.")
def get_manifest_target_platforms(manifest, requested_platform):
if requested_platform == "" or requested_platform is None:
return manifest["target"]["platforms"].split(",")
else:
validate_manifest_platform(manifest, requested_platform)
return [requested_platform]
#endregion Manifest
#region SDK download
def sdk_download(version, platform):
sdk_root_dir = get_sdk_root_dir(version, platform)
os.makedirs(sdk_root_dir, exist_ok=True)
sdk_url = get_sdk_url(version, platform)
filepath = os.path.join(sdk_root_dir, f"{version}-{platform}.zip")
print(f"Downloading SDK version {version} for {platform}")
if download_file(sdk_url, filepath):
with zipfile.ZipFile(filepath, "r") as zip_ref:
zip_ref.extractall(os.path.join(sdk_root_dir, "TactilitySDK"))
return True
else:
return False
def sdk_download_all(version, platforms):
for platform in platforms:
if not sdk_exists(version, platform):
if not sdk_download(version, platform):
return False
else:
if verbose:
print(f"Using cached download for SDK version {version} and platform {platform}")
return True
#endregion SDK download
#region Building
def get_cmake_path(platform):
return os.path.join("build", f"cmake-build-{platform}")
def find_elf_file(platform):
cmake_dir = get_cmake_path(platform)
if os.path.exists(cmake_dir):
for file in os.listdir(cmake_dir):
if file.endswith(".app.elf"):
return os.path.join(cmake_dir, file)
return None
def build_all(version, platforms, skip_build):
for platform in platforms:
# First build command must be "idf.py build", otherwise it fails to execute "idf.py elf"
# We check if the ELF file exists and run the correct command
# This can lead to code caching issues, so sometimes a clean build is required
if find_elf_file(platform) is None:
if not build_first(version, platform, skip_build):
return False
else:
if not build_consecutively(version, platform, skip_build):
return False
return True
def wait_for_process(process):
buffer = []
os.set_blocking(process.stdout.fileno(), False)
while process.poll() is None:
while True:
line = process.stdout.readline()
decoded_line = line.decode("UTF-8")
if decoded_line != "":
buffer.append(decoded_line)
else:
break
return buffer
# The first build must call "idf.py build" and consecutive builds must call "idf.py elf" as it finishes faster.
# The problem is that the "idf.py build" always results in an error, even though the elf file is created.
# The solution is to suppress the error if we find that the elf file was created.
def build_first(version, platform, skip_build):
sdk_dir = get_sdk_dir(version, platform)
if verbose:
print(f"Using SDK at {sdk_dir}")
os.environ["TACTILITY_SDK_PATH"] = sdk_dir
sdkconfig_path = os.path.join(ttbuild_path, f"sdkconfig.app.{platform}")
os.system(f"cp {sdkconfig_path} sdkconfig")
elf_path = find_elf_file(platform)
# Remove previous elf file: re-creation of the file is used to measure if the build succeeded,
# as the actual build job will always fail due to technical issues with the elf cmake script
if elf_path is not None:
os.remove(elf_path)
if skip_build:
return True
print(f"Building first {platform} build")
cmake_path = get_cmake_path(platform)
print_status_busy(f"Building {platform} ELF")
with subprocess.Popen(["idf.py", "-B", cmake_path, "build"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as process:
build_output = wait_for_process(process)
# The return code is never expected to be 0 due to a bug in the elf cmake script, but we keep it just in case
if process.returncode == 0:
print(f"{shell_color_green}Building for {platform}{shell_color_reset}")
return True
else:
if find_elf_file(platform) is None:
for line in build_output:
print(line, end="")
print_status_error(f"Building {platform} ELF")
return False
else:
print_status_success(f"Building {platform} ELF")
return True
def build_consecutively(version, platform, skip_build):
sdk_dir = get_sdk_dir(version, platform)
if verbose:
print(f"Using SDK at {sdk_dir}")
os.environ["TACTILITY_SDK_PATH"] = sdk_dir
sdkconfig_path = os.path.join(ttbuild_path, f"sdkconfig.app.{platform}")
os.system(f"cp {sdkconfig_path} sdkconfig")
if skip_build:
return True
cmake_path = get_cmake_path(platform)
print_status_busy(f"Building {platform} ELF")
with subprocess.Popen(["idf.py", "-B", cmake_path, "elf"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as process:
build_output = wait_for_process(process)
if process.returncode == 0:
print_status_success(f"Building {platform} ELF")
return True
else:
for line in build_output:
print(line, end="")
print_status_error(f"Building {platform} ELF")
return False
#endregion Building
#region Packaging
def package_intermediate_manifest(target_path):
if not os.path.isfile("manifest.properties"):
print_error("manifest.properties not found")
return
shutil.copy("manifest.properties", os.path.join(target_path, "manifest.properties"))
def package_intermediate_binaries(target_path, platforms):
elf_dir = os.path.join(target_path, "elf")
os.makedirs(elf_dir, exist_ok=True)
for platform in platforms:
elf_path = find_elf_file(platform)
if elf_path is None:
print_error(f"ELF file not found at {elf_path}")
return
shutil.copy(elf_path, os.path.join(elf_dir, f"{platform}.elf"))
def package_intermediate_assets(target_path):
if os.path.isdir("assets"):
shutil.copytree("assets", os.path.join(target_path, "assets"), dirs_exist_ok=True)
def package_intermediate(platforms):
target_path = os.path.join("build", "package-intermediate")
if os.path.isdir(target_path):
shutil.rmtree(target_path)
os.makedirs(target_path, exist_ok=True)
package_intermediate_manifest(target_path)
package_intermediate_binaries(target_path, platforms)
package_intermediate_assets(target_path)
def package_name(platforms):
elf_path = find_elf_file(platforms[0])
elf_base_name = os.path.basename(elf_path).removesuffix(".app.elf")
return os.path.join("build", f"{elf_base_name}.app")
def package_all(platforms):
status = f"Building package with {platforms}"
print_status_busy(status)
package_intermediate(platforms)
# Create build/something.app
try:
tar_path = package_name(platforms)
tar = tarfile.open(tar_path, mode="w", format=tarfile.USTAR_FORMAT)
tar.add(os.path.join("build", "package-intermediate"), arcname="")
tar.close()
print_status_success(status)
return True
except Exception as e:
print_status_error(f"Building package failed: {e.message}")
return False
#endregion Packaging
def setup_environment():
global ttbuild_path
os.makedirs(ttbuild_path, exist_ok=True)
def build_action(manifest, platform_arg):
# Environment validation
validate_environment()
platforms_to_build = get_manifest_target_platforms(manifest, platform_arg)
if use_local_sdk:
global local_base_path
local_base_path = os.environ.get("TACTILITY_SDK_PATH")
validate_local_sdks(platforms_to_build, manifest["target"]["sdk"])
if should_fetch_sdkconfig_files(platforms_to_build):
fetch_sdkconfig_files(platforms_to_build)
if not use_local_sdk:
sdk_json = read_sdk_json()
validate_self(sdk_json)
if not "versions" in sdk_json:
exit_with_error("Version data not found in sdk.json")
# Build
sdk_version = manifest["target"]["sdk"]
if not use_local_sdk:
validate_version_and_platforms(sdk_json, sdk_version, platforms_to_build)
if not sdk_download_all(sdk_version, platforms_to_build):
exit_with_error("Failed to download one or more SDKs")
if not build_all(sdk_version, platforms_to_build, skip_build): # Environment validation
return False
if not skip_build:
package_all(platforms_to_build)
return True
def clean_action():
if os.path.exists("build"):
print_status_busy("Removing build/")
shutil.rmtree("build")
print_status_success("Removed build/")
else:
print("Nothing to clean")
def clear_cache_action():
if os.path.exists(ttbuild_path):
print_status_busy(f"Removing {ttbuild_path}/")
shutil.rmtree(ttbuild_path)
print_status_success(f"Removed {ttbuild_path}/")
else:
print("Nothing to clear")
def update_self_action():
sdk_json = read_sdk_json()
tool_download_url = sdk_json["toolDownloadUrl"]
if download_file(tool_download_url, "tactility.py"):
print("Updated")
else:
exit_with_error("Update failed")
def get_device_info(ip):
print_status_busy(f"Requesting device info")
url = get_url(ip, "/info")
try:
response = requests.get(url)
if response.status_code != 200:
print_error("Run failed")
else:
print_status_success(f"Received device info:")
print(response.json())
except requests.RequestException as e:
print_status_error(f"Device info request failed: {e.message}")
def run_action(manifest, ip):
app_id = manifest["app"]["id"]
print_status_busy("Running")
url = get_url(ip, "/app/run")
params = {'id': app_id}
try:
response = requests.post(url, params=params)
if response.status_code != 200:
print_error("Run failed")
else:
print_status_success("Running")
except requests.RequestException as e:
print_status_error(f"Running request failed: {e.message}")
def install_action(ip, platforms):
print_status_busy("Installing")
for platform in platforms:
elf_path = find_elf_file(platform)
if elf_path is None:
print_status_error(f"ELF file not built for {platform}")
return False
package_path = package_name(platforms)
# print(f"Installing {package_path} to {ip}")
url = get_url(ip, "/app/install")
try:
# Prepare multipart form data
with open(package_path, 'rb') as file:
files = {
'elf': file
}
response = requests.put(url, files=files)
if response.status_code != 200:
print_status_error("Install failed")
return True
else:
print_status_success("Installing")
return True
except requests.RequestException as e:
print_status_error(f"Install request failed: {e.message}")
return False
except IOError as e:
print_status_error(f"Install file error: {e.message}")
return False
def uninstall_action(manifest, ip):
app_id = manifest["app"]["id"]
print_status_busy("Uninstalling")
url = get_url(ip, "/app/uninstall")
params = {'id': app_id}
try:
response = requests.put(url, params=params)
if response.status_code != 200:
print_status_error("Server responded that uninstall failed")
else:
print_status_success("Uninstalled")
except requests.RequestException as e:
print_status_success(f"Uninstall request failed: {e.message}")
#region Main
if __name__ == "__main__":
print(f"Tactility Build System v{ttbuild_version}")
if "--help" in sys.argv:
print_help()
sys.exit()
# Argument validation
if len(sys.argv) == 1:
print_help()
sys.exit()
if "--verbose" in sys.argv:
verbose = True
sys.argv.remove("--verbose")
skip_build = False
if "--skip-build" in sys.argv:
skip_build = True
sys.argv.remove("--skip-build")
if "--local-sdk" in sys.argv:
use_local_sdk = True
sys.argv.remove("--local-sdk")
action_arg = sys.argv[1]
# Environment setup
setup_environment()
if not os.path.isfile("manifest.properties"):
exit_with_error("manifest.properties not found")
manifest = read_manifest()
validate_manifest(manifest)
all_platform_targets = manifest["target"]["platforms"].split(",")
# Update SDK cache (sdk.json)
if should_update_sdk_json() and not update_sdk_json():
exit_with_error("Failed to retrieve SDK info")
# Actions
if action_arg == "build":
if len(sys.argv) < 2:
print_help()
exit_with_error("Commandline parameter missing")
platform = None
if len(sys.argv) > 2:
platform = sys.argv[2]
build_action(manifest, platform)
elif action_arg == "clean":
clean_action()
elif action_arg == "clearcache":
clear_cache_action()
elif action_arg == "updateself":
update_self_action()
elif action_arg == "run":
if len(sys.argv) < 3:
print_help()
exit_with_error("Commandline parameter missing")
run_action(manifest, sys.argv[2])
elif action_arg == "install":
if len(sys.argv) < 3:
print_help()
exit_with_error("Commandline parameter missing")
platform = None
platforms_to_install = all_platform_targets
if len(sys.argv) >= 4:
platform = sys.argv[3]
platforms_to_install = [platform]
install_action(sys.argv[2], platforms_to_install)
elif action_arg == "uninstall":
if len(sys.argv) < 3:
print_help()
exit_with_error("Commandline parameter missing")
uninstall_action(manifest, sys.argv[2])
elif action_arg == "bir" or action_arg == "brrr":
if len(sys.argv) < 3:
print_help()
exit_with_error("Commandline parameter missing")
platform = None
platforms_to_install = all_platform_targets
if len(sys.argv) >= 4:
platform = sys.argv[3]
platforms_to_install = [platform]
if build_action(manifest, platform):
if install_action(sys.argv[2], platforms_to_install):
run_action(manifest, sys.argv[2])
else:
print_help()
exit_with_error("Unknown commandline parameter")
#endregion Main
@@ -1,7 +1,7 @@
#pragma once #pragma once
#include <concepts>
#include <tt_app.h> #include <tt_app.h>
#include <type_traits>
class App { class App {
public: public:
@@ -0,0 +1,51 @@
#pragma once
#include <tt_lock.h>
class ScopedLock;
/** Represents a lock/mutex */
class Lock {
public:
virtual ~Lock() = default;
virtual bool lock(TickType timeout) const = 0;
bool lock() const { return lock(TT_MAX_TICKS); }
virtual bool unlock() const = 0;
ScopedLock asScopedLock() const;
};
/**
* Represents a lockable instance that is scoped to a specific lifecycle.
* Once the ScopedLock is destroyed, unlock() is called automatically.
*
* In other words:
* You have to lock() this object manually, but unlock() happens automatically on destruction.
*/
class ScopedLock final : public Lock {
const Lock& lockable;
public:
using Lock::lock;
explicit ScopedLock(const Lock& lockable) : lockable(lockable) {}
~ScopedLock() override {
lockable.unlock(); // We don't care whether it succeeded or not
}
bool lock(TickType timeout) const override {
return lockable.lock(timeout);
}
bool unlock() const override {
return lockable.unlock();
}
};
@@ -0,0 +1,22 @@
#pragma once
#include <TactilityCpp/Lock.h>
#include <tt_lvgl.h>
class LvglLock final : public Lock {
public:
bool lock(TickType timeout = TT_MAX_TICKS) const override {
tt_lvgl_lock(timeout);
return true;
}
bool unlock() const override {
tt_lvgl_unlock();
return true;
}
};
@@ -0,0 +1,27 @@
#pragma once
#include <tt_lock.h>
#include <TactilityCpp/Lock.h>
class Mutex final : public Lock {
LockHandle handle;
public:
explicit Mutex(TtMutexType type) : handle(tt_lock_alloc_mutex(type)) {};
~Mutex() override {
tt_lock_free(handle);
}
bool lock(TickType timeout = TT_MAX_TICKS) const override {
return tt_lock_acquire(handle, timeout);
}
bool unlock() const override {
return tt_lock_release(handle);
}
};
@@ -0,0 +1,98 @@
#pragma once
#include <tt_preferences.h>
#include <cstdint>
#include <cstring>
#include <memory>
#include <string>
class Preferences {
PreferencesHandle handle = nullptr;
public:
// Open preferences with the given identifier/namespace
explicit Preferences(const char* identifier) : handle(tt_preferences_alloc(identifier)) {}
// Non-copyable (owns a handle)
Preferences(const Preferences&) = delete;
Preferences& operator=(const Preferences&) = delete;
// Movable
Preferences(Preferences&& other) noexcept : handle(other.handle) {
other.handle = nullptr;
}
Preferences& operator=(Preferences&& other) noexcept {
if (this != &other) {
if (handle) {
tt_preferences_free(handle);
}
handle = other.handle;
other.handle = nullptr;
}
return *this;
}
~Preferences() {
if (handle) {
tt_preferences_free(handle);
}
}
bool optBool(const char* key, bool& out) const {
return tt_preferences_opt_bool(handle, key, &out);
}
bool getBool(const char* key, bool defaultValue = false) const {
bool value = defaultValue;
(void) tt_preferences_opt_bool(handle, key, &value);
return value;
}
void putBool(const char* key, bool value) const {
tt_preferences_put_bool(handle, key, value);
}
bool optInt32(const char* key, int32_t& out) const {
return tt_preferences_opt_int32(handle, key, &out);
}
int32_t getInt32(const char* key, int32_t defaultValue = 0) const {
int32_t value = defaultValue;
(void) tt_preferences_opt_int32(handle, key, &value);
return value;
}
void putInt32(const char* key, int32_t value) const {
tt_preferences_put_int32(handle, key, value);
}
bool optString(const char* key, char* out, uint32_t outSize) const {
return tt_preferences_opt_string(handle, key, out, outSize);
}
template <size_t N>
bool optString(const char* key, char (&out)[N]) const {
return tt_preferences_opt_string(handle, key, out, static_cast<uint32_t>(N));
}
std::string getString(const char* key, size_t maxSize, const std::string& defaultValue = std::string()) const {
if (maxSize == 0) return defaultValue;
std::string buf;
buf.resize(maxSize);
if (tt_preferences_opt_string(handle, key, buf.data(), static_cast<uint32_t>(maxSize))) {
buf.resize(std::strlen(buf.c_str()));
return buf;
}
return defaultValue;
}
void putString(const char* key, const char* value) const {
tt_preferences_put_string(handle, key, value);
}
void putString(const char* key, const std::string& value) const {
tt_preferences_put_string(handle, key, value.c_str());
}
};
@@ -0,0 +1,65 @@
#pragma once
#include <tt_thread.h>
class Thread {
ThreadHandle handle;
public:
Thread() : handle(tt_thread_alloc()) {}
Thread(
const char* name,
uint32_t stackSize,
ThreadCallback callback,
void* _Nullable callbackContext
) : handle(tt_thread_alloc_ext(name, stackSize, callback, callbackContext)) {}
~Thread() {
tt_thread_free(handle);
}
void start() const {
tt_thread_start(handle);
}
bool join(TickType timeout = TT_MAX_TICKS) const {
return tt_thread_join(handle, timeout);
}
void setName(const char* name) const {
tt_thread_set_name(handle, name);
}
void setStackSize(size_t stackSize) const {
tt_thread_set_stack_size(handle, stackSize);
}
void setAffinity(int affinity) const {
tt_thread_set_affinity(handle, affinity);
}
void setCallback(ThreadCallback callback, void* _Nullable callbackContext) const {
tt_thread_set_callback(handle, callback, callbackContext);
}
void setPriority(ThreadPriority priority) const {
tt_thread_set_priority(handle, priority);
}
void setStateCallback(ThreadStateCallback callback, void* _Nullable callbackContext) const {
tt_thread_set_state_callback(handle, callback, callbackContext);
}
ThreadState getState() const {
return tt_thread_get_state(handle);
}
ThreadId getId() const {
return tt_thread_get_id(handle);
}
int32_t getReturnCode() const {
return tt_thread_get_return_code(handle);
}
};
@@ -0,0 +1,74 @@
#pragma once
#include <tt_hal_uart.h>
#include <Str.h>
#include <vector>
class Uart {
UartHandle handle;
public:
explicit Uart(UartHandle handle) : handle(handle) {}
~Uart() {
tt_hal_uart_free(handle);
}
static std::unique_ptr<Uart> open(size_t index) {
auto handle = tt_hal_uart_alloc(index);
return std::make_unique<Uart>(handle);
}
static std::vector<Str> getNames() {
std::vector<Str> names;
size_t count = tt_hal_uart_get_count();
for (size_t i = 0; i < count; i++) {
char buffer[64];
if (tt_hal_uart_get_name(i, buffer, sizeof(buffer))) {
names.push_back(Str(buffer));
}
}
return names;
}
bool start() const {
return tt_hal_uart_start(handle);
}
bool isStarted() const {
return tt_hal_uart_is_started(handle);
}
bool stop() const {
return tt_hal_uart_stop(handle);
}
size_t readBytes(char* buffer, size_t bufferSize, TickType timeout) const {
return tt_hal_uart_read_bytes(handle, buffer, bufferSize, timeout);
}
bool readByte(char* output, TickType timeout) const {
return tt_hal_uart_read_bytes(handle, output, 1, timeout);
}
size_t writeBytes(const char* buffer, size_t bufferSize, TickType timeout) const {
return tt_hal_uart_write_bytes(handle, buffer, bufferSize, timeout);
}
size_t available() const {
return tt_hal_uart_available(handle);
}
bool setBaudRate(size_t baud_rate) const {
return tt_hal_uart_set_baud_rate(handle, baud_rate);
}
uint32_t getBaudRate() const {
return tt_hal_uart_get_baud_rate(handle);
}
void flushInput() const {
tt_hal_uart_flush_input(handle);
}
};
+6
View File
@@ -0,0 +1,6 @@
#include <TactilityCpp/Lock.h>
ScopedLock Lock::asScopedLock() const {
return ScopedLock(*this);
}