Update apps and create Diceware (#3)

This commit is contained in:
Ken Van Hoeylandt
2025-10-02 23:41:29 +02:00
committed by GitHub
parent 79a1403053
commit d8727d79e6
23 changed files with 8908 additions and 175 deletions
+9 -1
View File
@@ -1,6 +1,14 @@
file(GLOB_RECURSE SOURCE_FILES Source/*.c*) 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**
)
idf_component_register( idf_component_register(
SRCS ${SOURCE_FILES} 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
REQUIRES TactilitySDK REQUIRES TactilitySDK
) )
+12 -12
View File
@@ -1,11 +1,11 @@
#include "Calculator.h" #include "Calculator.h"
#include "Stack.h"
#include <cstdio> #include <cstdio>
#include <ctype.h> #include <ctype.h>
#include <tt_lvgl_toolbar.h> #include <tt_lvgl_toolbar.h>
#include <stack>
constexpr const char* TAG = "Calculator"; constexpr auto* TAG = "Calculator";
static int precedence(char op) { static int precedence(char op) {
if (op == '+' || op == '-') return 1; if (op == '+' || op == '-') return 1;
@@ -45,9 +45,9 @@ void Calculator::handleInput(const char* txt) {
} }
} }
Dequeue<Str> Calculator::infixToRPN(const Str& infix) { std::deque<Str> Calculator::infixToRPN(const Str& infix) {
Stack<char> opStack; std::stack<char> opStack;
Dequeue<Str> output; std::deque<Str> output;
Str token; Str token;
size_t i = 0; size_t i = 0;
@@ -57,19 +57,19 @@ Dequeue<Str> Calculator::infixToRPN(const Str& infix) {
if (isdigit(ch)) { if (isdigit(ch)) {
token.clear(); token.clear();
while (i < infix.length() && (isdigit(infix[i]) || infix[i] == '.')) { token.append(infix[i++]); } while (i < infix.length() && (isdigit(infix[i]) || infix[i] == '.')) { token.append(infix[i++]); }
output.pushBack(token); output.push_back(token);
continue; continue;
} }
if (ch == '(') { opStack.push(ch); } else if (ch == ')') { if (ch == '(') { opStack.push(ch); } else if (ch == ')') {
while (!opStack.empty() && opStack.top() != '(') { while (!opStack.empty() && opStack.top() != '(') {
output.pushBack(Str(1, opStack.top())); output.push_back(Str(1, opStack.top()));
opStack.pop(); opStack.pop();
} }
opStack.pop(); opStack.pop();
} else if (strchr("+-*/", ch)) { } else if (strchr("+-*/", ch)) {
while (!opStack.empty() && precedence(opStack.top()) >= precedence(ch)) { while (!opStack.empty() && precedence(opStack.top()) >= precedence(ch)) {
output.pushBack(Str(1, opStack.top())); output.push_back(Str(1, opStack.top()));
opStack.pop(); opStack.pop();
} }
opStack.push(ch); opStack.push(ch);
@@ -79,19 +79,19 @@ Dequeue<Str> Calculator::infixToRPN(const Str& infix) {
} }
while (!opStack.empty()) { while (!opStack.empty()) {
output.pushBack(Str(1, opStack.top())); output.push_back(Str(1, opStack.top()));
opStack.pop(); opStack.pop();
} }
return output; return output;
} }
double Calculator::evaluateRPN(Dequeue<Str> rpnQueue) { double Calculator::evaluateRPN(std::deque<Str> rpnQueue) {
Stack<double> values; std::stack<double> values;
while (!rpnQueue.empty()) { while (!rpnQueue.empty()) {
Str token = rpnQueue.front(); Str token = rpnQueue.front();
rpnQueue.popFront(); rpnQueue.pop_front();
if (isdigit(token[0])) { if (isdigit(token[0])) {
double d; double d;
+4 -4
View File
@@ -3,8 +3,8 @@
#include "tt_app.h" #include "tt_app.h"
#include <lvgl.h> #include <lvgl.h>
#include "Str.h" #include <deque>
#include "Dequeue.h" #include <Str.h>
class Calculator { class Calculator {
@@ -17,8 +17,8 @@ class Calculator {
void handleInput(const char* txt); void handleInput(const char* txt);
void evaluateExpression(); void evaluateExpression();
double computeFormula(); double computeFormula();
static Dequeue<Str> infixToRPN(const Str& infix); static std::deque<Str> infixToRPN(const Str& infix);
static double evaluateRPN(Dequeue<Str> rpnQueue); static double evaluateRPN(std::deque<Str> rpnQueue);
void resetCalculator(); void resetCalculator();
public: public:
-95
View File
@@ -1,95 +0,0 @@
#pragma once
template <typename DataType>
class Dequeue {
struct Node {
DataType data;
Node* next;
Node* previous;
Node(DataType data, Node* next, Node* previous):
data(data),
next(next),
previous(previous)
{}
};
int count = 0;
Node* head = nullptr;
Node* tail = nullptr;
public:
void pushFront(DataType data) {
auto* new_node = new Node(data, head, nullptr);
if (head != nullptr) {
head->previous = new_node;
}
if (tail == nullptr) {
tail = new_node;
}
head = new_node;
count++;
}
void pushBack(DataType data) {
auto* new_node = new Node(data, nullptr, tail);
if (head == nullptr) {
head = new_node;
}
if (tail != nullptr) {
tail->next = new_node;
}
tail = new_node;
count++;
}
void popFront() {
if (head != nullptr) {
bool is_last_node = (head == tail);
Node* node_to_delete = head;
head = node_to_delete->next;
if (is_last_node) {
tail = nullptr;
}
delete node_to_delete;
count--;
}
}
void popBack() {
if (tail != nullptr) {
bool is_last_node = (head == tail);
Node* node_to_delete = tail;
tail = node_to_delete->previous;
if (is_last_node) {
head = nullptr;
}
delete node_to_delete;
count--;
}
}
DataType back() const {
assert(tail != nullptr);
return tail->data;
}
DataType front() const {
assert(head != nullptr);
return head->data;
}
bool empty() const {
return head == nullptr;
}
int size() const { return count; }
};
-21
View File
@@ -1,21 +0,0 @@
#pragma once
#include "Dequeue.h"
template <typename DataType>
class Stack {
Dequeue<DataType> dequeue;
public:
void push(DataType data) { dequeue.pushFront(data); }
void pop() { dequeue.popFront(); }
DataType top() const { return dequeue.front(); }
bool empty() const { return dequeue.empty(); }
int size() const { return dequeue.size(); }
};
+1 -1
View File
@@ -1,7 +1,7 @@
[manifest] [manifest]
version=0.1 version=0.1
[target] [target]
sdk=0.6.0-SNAPSHOT3 sdk=0.6.0-SNAPSHOT7
platforms=esp32,esp32s3 platforms=esp32,esp32s3
[app] [app]
id=one.tactility.calculator id=one.tactility.calculator
+36 -10
View File
@@ -14,12 +14,13 @@ import shutil
import configparser import configparser
ttbuild_path = ".tactility" ttbuild_path = ".tactility"
ttbuild_version = "2.3.1" ttbuild_version = "2.3.4"
ttbuild_cdn = "https://cdn.tactility.one" ttbuild_cdn = "https://cdn.tactility.one"
ttbuild_sdk_json_validity = 3600 # seconds ttbuild_sdk_json_validity = 3600 # seconds
ttport = 6666 ttport = 6666
verbose = False verbose = False
use_local_sdk = False use_local_sdk = False
local_base_path = None
valid_platforms = ["esp32", "esp32s3"] valid_platforms = ["esp32", "esp32s3"]
no_animations = False no_animations = False
@@ -69,7 +70,7 @@ def print_help():
print("") print("")
print("Options:") print("Options:")
print(" --help Show this commandline info") print(" --help Show this commandline info")
print(" --local-sdk Use SDK specified by environment variable TACTILITY_SDK_PATH") 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(" --skip-build Run everything except the idf.py/CMake commands")
print(" --verbose Show extra console output") print(" --verbose Show extra console output")
print(" --no-animations Disable animations during building (e.g. for CI jobs)") print(" --no-animations Disable animations during building (e.g. for CI jobs)")
@@ -126,13 +127,30 @@ def read_sdk_json():
return json.load(json_file) return json.load(json_file)
def get_sdk_dir(version, platform): def get_sdk_dir(version, platform):
global use_local_sdk global use_local_sdk, local_base_path
if use_local_sdk: if use_local_sdk:
return os.environ.get("TACTILITY_SDK_PATH") 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: else:
global ttbuild_cdn
return os.path.join(ttbuild_path, f"{version}-{platform}", "TactilitySDK") 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): def get_sdk_root_dir(version, platform):
global ttbuild_cdn global ttbuild_cdn
return os.path.join(ttbuild_path, f"{version}-{platform}") return os.path.join(ttbuild_path, f"{version}-{platform}")
@@ -188,7 +206,7 @@ def validate_environment():
exit_with_error("manifest.properties not found") exit_with_error("manifest.properties not found")
if use_local_sdk == False and os.environ.get("TACTILITY_SDK_PATH") is not None: 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("TACTILITY_SDK_PATH is set, but will be ignored by this command.")
print_warning("If you want to use it, use the 'build local' parameters.") 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: 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.") exit_with_error("local build was requested, but TACTILITY_SDK_PATH environment variable is not set.")
@@ -315,10 +333,11 @@ def build_all(version, platforms, skip_build):
# This can lead to code caching issues, so sometimes a clean build is required # This can lead to code caching issues, so sometimes a clean build is required
if find_elf_file(platform) is None: if find_elf_file(platform) is None:
if not build_first(version, platform, skip_build): if not build_first(version, platform, skip_build):
break return False
else: else:
if not build_consecutively(version, platform, skip_build): if not build_consecutively(version, platform, skip_build):
break return False
return True
def wait_for_build(process, platform): def wait_for_build(process, platform):
global no_animations global no_animations
@@ -454,9 +473,16 @@ def build_action(manifest, platform_arg):
# Environment validation # Environment validation
validate_environment() validate_environment()
platforms_to_build = get_manifest_target_platforms(manifest, platform_arg) platforms_to_build = get_manifest_target_platforms(manifest, platform_arg)
if not use_local_sdk:
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): if should_fetch_sdkconfig_files(platforms_to_build):
fetch_sdkconfig_files(platforms_to_build) fetch_sdkconfig_files(platforms_to_build)
if not use_local_sdk:
sdk_json = read_sdk_json() sdk_json = read_sdk_json()
validate_self(sdk_json) validate_self(sdk_json)
if not "versions" in sdk_json: if not "versions" in sdk_json:
@@ -467,7 +493,7 @@ def build_action(manifest, platform_arg):
validate_version_and_platforms(sdk_json, sdk_version, platforms_to_build) validate_version_and_platforms(sdk_json, sdk_version, platforms_to_build)
if not sdk_download_all(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") exit_with_error("Failed to download one or more SDKs")
build_all(sdk_version, platforms_to_build, skip_build) # Environment validation if build_all(sdk_version, platforms_to_build, skip_build): # Environment validation
if not skip_build: if not skip_build:
package_all(platforms_to_build) package_all(platforms_to_build)
+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(Diceware)
tactility_project(Diceware)
+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.
File diff suppressed because it is too large Load Diff
+15
View File
@@ -0,0 +1,15 @@
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**
)
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
REQUIRES TactilitySDK
)
+181
View File
@@ -0,0 +1,181 @@
#include "Application.h"
#include <tt_app_alertdialog.h>
#include <tt_file.h>
#include <tt_lock.h>
#include <tt_lvgl.h>
#include <tt_lvgl_toolbar.h>
#include <esp_random.h>
#include <esp_log.h>
constexpr char* TAG = "Diceware";
static void skipNewlines(FILE* file, const int count) {
char c;
int count_in_file = 0;
while (count_in_file < count && fread(&c, 1, 1, file)) {
if (c == '\n') {
count_in_file++;
}
}
}
static Str readWord(FILE* file) {
char c;
Str result;
// Read word until newline
while (fread(&c, 1, 1, file) && c != '\n') { result.append(c); }
return result;
}
static Str readWordAtLine(const AppHandle handle, const int lineIndex) {
char path[256];
size_t size = 256;
tt_app_get_assets_child_path(handle, "eff_large_wordlist.txt", path, &size);
if (size == 0) {
ESP_LOGE(TAG, "Failed to get assets path");
return "";
}
auto lock = tt_lock_alloc_for_file(path);
Str word;
if (tt_lock_acquire(lock, TT_MAX_TICKS)) {
FILE* file = fopen(path, "r");
if (file != nullptr) {
skipNewlines(file, lineIndex);
word = readWord(file);
fclose(file);
} else { ESP_LOGE(TAG, "Failed to open %s", path); }
tt_lock_release(lock);
} else { ESP_LOGE(TAG, "Failed to acquire lock for %s", path); }
tt_lock_free(lock);
return word;
}
int32_t Application::jobMain(void* data) {
Application* application = static_cast<Application*>(data);
Str result;
for (int i = 0; i < application->wordCount; i++) {
constexpr int line_count = 7776;
const auto line_index = esp_random() % line_count;
auto word = readWordAtLine(application->handle, line_index);
result.appendf("%s ", word.c_str());
}
application->onFinishJob(result);
return 0;
}
void Application::cleanupJob() {
if (jobThread != nullptr) {
tt_thread_join(jobThread, TT_MAX_TICKS);
tt_thread_free(jobThread);
}
}
void Application::startJob(uint32_t jobWordCount) {
cleanupJob();
wordCount = jobWordCount;
jobThread = tt_thread_alloc_ext("Diceware", 4096, jobMain, this);
tt_thread_start(jobThread);
}
void Application::onFinishJob(Str result) {
tt_lvgl_lock();
lv_label_set_text(resultLabel, result.c_str());
tt_lvgl_unlock();
}
void Application::onClickGenerate(lv_event_t* e) {
auto* application = static_cast<Application*>(lv_event_get_user_data(e));
auto* spinbox = application->spinbox;
lv_label_set_text(application->resultLabel, "Generating...");
const auto word_count = lv_spinbox_get_value(spinbox);
application->startJob(word_count);
}
void Application::onSpinboxDecrement(lv_event_t* e) {
auto* spinbox = static_cast<lv_obj_t*>(lv_event_get_user_data(e));
lv_spinbox_decrement(spinbox);
}
void Application::onSpinboxIncrement(lv_event_t* e) {
auto* spinbox = static_cast<lv_obj_t*>(lv_event_get_user_data(e));
lv_spinbox_increment(spinbox);
}
void Application::onHelpClicked(lv_event_t* e) {
const char* buttons[] = { "OK" };
tt_app_alertdialog_start("Diceware Info", "The hardware random number generator can use the Wi-Fi radio to improve randomness. There's no need to connect to a Wi-Fi network for this to work.", buttons, 1);
}
void Application::onShow(AppHandle appHandle, lv_obj_t* parent) {
handle = appHandle;
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);
tt_lvgl_toolbar_add_text_button_action(toolbar, "?", onHelpClicked, nullptr);
auto* wrapper = lv_obj_create(parent);
lv_obj_set_style_border_width(wrapper, 0, LV_STATE_DEFAULT);
lv_obj_set_flex_flow(wrapper, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(wrapper, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_START);
lv_obj_set_width(wrapper, LV_PCT(100));
lv_obj_set_flex_grow(wrapper, 1);
auto* top_row_wrapper = lv_obj_create(wrapper);
lv_obj_set_style_border_width(top_row_wrapper, 0, LV_STATE_DEFAULT);
lv_obj_set_size(top_row_wrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_pad_all(top_row_wrapper, 0, LV_STATE_DEFAULT);
auto* generate_button = lv_button_create(top_row_wrapper);
lv_obj_align(generate_button, LV_ALIGN_LEFT_MID, 0, 0);
auto* generate_label = lv_label_create(generate_button);
lv_label_set_text(generate_label, "Generate");
lv_obj_add_event_cb(generate_button, onClickGenerate, LV_EVENT_SHORT_CLICKED, this);
spinbox = lv_spinbox_create(top_row_wrapper);
lv_spinbox_set_range(spinbox, 4, 12);
lv_spinbox_set_value(spinbox, 5);
lv_spinbox_set_step(spinbox, 1);
lv_spinbox_set_digit_format(spinbox, 1, 0);
lv_obj_set_width(spinbox, 30);
auto* spinbox_dec_button = lv_button_create(top_row_wrapper);
lv_obj_set_style_bg_image_src(spinbox_dec_button, LV_SYMBOL_MINUS, LV_STATE_DEFAULT);
lv_obj_add_event_cb(spinbox_dec_button, onSpinboxDecrement, LV_EVENT_SHORT_CLICKED, spinbox);
lv_obj_set_style_pad_all(spinbox_dec_button, 16, LV_STATE_DEFAULT);
auto* spinbox_inc_button = lv_button_create(top_row_wrapper);
// lv_obj_align_to(spinbox_inc_button, spinbox, LV_ALIGN_OUT_RIGHT_MID, 5, 0);
lv_obj_set_style_bg_image_src(spinbox_inc_button, LV_SYMBOL_PLUS, LV_STATE_DEFAULT);
lv_obj_add_event_cb(spinbox_inc_button, onSpinboxIncrement, LV_EVENT_SHORT_CLICKED, spinbox);
lv_obj_set_style_pad_all(spinbox_inc_button, 16, LV_STATE_DEFAULT);
// Align spinbox widgets
lv_obj_align(spinbox_inc_button, LV_ALIGN_RIGHT_MID, 0, 0);
lv_obj_align_to(spinbox, spinbox_inc_button, LV_ALIGN_OUT_LEFT_MID, -5, 0);
lv_obj_align_to(spinbox_dec_button, spinbox, LV_ALIGN_OUT_LEFT_MID, -5, 0);
auto* result_wrapper = lv_obj_create(wrapper);
lv_obj_set_flex_grow(result_wrapper, 1);
lv_obj_set_width(result_wrapper, LV_PCT(100));
lv_obj_set_style_pad_all(result_wrapper, 0, LV_STATE_DEFAULT);
resultLabel = lv_label_create(result_wrapper);
// See https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html
lv_label_set_text(resultLabel, "Press Generate button\nWi-Fi improves randomness.\nSee info button.");
lv_label_set_long_mode(resultLabel, LV_LABEL_LONG_MODE_WRAP);
lv_obj_set_size(resultLabel, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_align(resultLabel, LV_ALIGN_CENTER);
lv_obj_set_style_text_align(resultLabel, LV_TEXT_ALIGN_CENTER, LV_STATE_DEFAULT);
}
void Application::onHide(AppHandle context) { cleanupJob(); }
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include "tt_app.h"
#include "tt_thread.h"
#include <Str.h>
#include <lvgl.h>
class Application final {
AppHandle handle = nullptr;
lv_obj_t* spinbox = nullptr;
lv_obj_t* resultLabel = nullptr;
ThreadHandle jobThread = nullptr;
uint32_t wordCount = 5;
static void onClickGenerate(lv_event_t* e);
static void onSpinboxDecrement(lv_event_t* e);
static void onSpinboxIncrement(lv_event_t* e);
static void onHelpClicked(lv_event_t* e);
static int32_t jobMain(void* data);
void startJob(uint32_t jobWordCount);
void onFinishJob(Str result);
void cleanupJob();
public:
void onShow(AppHandle context, lv_obj_t* parent);
void onHide(AppHandle context);
};
+34
View File
@@ -0,0 +1,34 @@
#include <tt_app.h>
#include "Application.h"
static void onShowApp(AppHandle appHandle, void* data, lv_obj_t* parent) {
static_cast<Application*>(data)->onShow(appHandle, parent);
}
static void onHideApp(AppHandle appHandle, void* data) {
static_cast<Application*>(data)->onHide(appHandle);
}
static void* createApp() {
return new Application();
}
static void destroyApp(void* app) {
delete static_cast<Application*>(app);
}
ExternalAppManifest manifest = {
.createData = createApp,
.destroyData = destroyApp,
.onShow = onShowApp,
.onHide = onHideApp,
};
extern "C" {
int main(int argc, char* argv[]) {
tt_app_register(&manifest);
return 0;
}
}
+10
View File
@@ -0,0 +1,10 @@
[manifest]
version=0.1
[target]
sdk=0.6.0-SNAPSHOT7
platforms=esp32,esp32s3
[app]
id=one.tactility.diceware
versionName=0.1.0
versionCode=1
name=Diceware
+673
View File
@@ -0,0 +1,673 @@
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.3.4"
ttbuild_cdn = "https://cdn.tactility.one"
ttbuild_sdk_json_validity = 3600 # seconds
ttport = 6666
verbose = False
use_local_sdk = False
local_base_path = None
valid_platforms = ["esp32", "esp32s3"]
no_animations = False
spinner_pattern = [
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
]
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")
print(" --no-animations Disable animations during building (e.g. for CI jobs)")
# 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 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_build(process, platform):
global no_animations
buffer = []
os.set_blocking(process.stdout.fileno(), False)
if no_animations:
print(f"Building for {platform}")
while process.poll() is None:
for i in spinner_pattern:
time.sleep(0.1)
if not no_animations:
progress_text = f"Building for {platform} {shell_color_cyan}" + str(i) + shell_color_reset
sys.stdout.write(progress_text + "\r")
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("Building first build")
cmake_path = get_cmake_path(platform)
with subprocess.Popen(["idf.py", "-B", cmake_path, "build"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as process:
build_output = wait_for_build(process, platform)
# 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(f"{shell_color_red}Building for {platform} failed ❌{shell_color_reset}")
return False
else:
print(f"{shell_color_green}Building for {platform}{shell_color_reset}")
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)
with subprocess.Popen(["idf.py", "-B", cmake_path, "elf"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as process:
build_output = wait_for_build(process, platform)
if process.returncode == 0:
print(f"{shell_color_green}Building for {platform}{shell_color_reset}")
return True
else:
for line in build_output:
print(line, end="")
print(f"{shell_color_red}Building for {platform} failed ❌{shell_color_reset}")
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):
print("Packaging app")
package_intermediate(platforms)
# Create build/something.app
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()
#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 build_all(sdk_version, platforms_to_build, skip_build): # Environment validation
if not skip_build:
package_all(platforms_to_build)
def clean_action():
if os.path.exists("build"):
print(f"Removing build/")
shutil.rmtree("build")
else:
print("Nothing to clean")
def clear_cache_action():
if os.path.exists(ttbuild_path):
print(f"Removing {ttbuild_path}/")
shutil.rmtree(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(f"Getting device info from {ip}")
url = get_url(ip, "/info")
try:
response = requests.get(url)
if response.status_code != 200:
print_error("Run failed")
else:
print(response.json())
print(f"{shell_color_green}Run successful ✅{shell_color_reset}")
except requests.RequestException as e:
print(f"Request failed: {e}")
def run_action(manifest, ip):
app_id = manifest["app"]["id"]
print(f"Running {app_id} on {ip}")
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(f"{shell_color_green}Run successful ✅{shell_color_reset}")
except requests.RequestException as e:
print(f"Request failed: {e}")
def install_action(ip, platforms):
for platform in platforms:
elf_path = find_elf_file(platform)
if elf_path is None:
exit_with_error(f"ELF file not built for {platform}")
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_error("Install failed")
else:
print(f"{shell_color_green}Installation successful ✅{shell_color_reset}")
except requests.RequestException as e:
print_error(f"Installation failed: {e}")
except IOError as e:
print_error(f"File error: {e}")
def uninstall_action(manifest, ip):
app_id = manifest["app"]["id"]
print(f"Uninstalling {app_id} on {ip}")
url = get_url(ip, "/app/uninstall")
params = {'id': app_id}
try:
response = requests.put(url, params=params)
if response.status_code != 200:
print_error("Uninstall failed")
else:
print(f"{shell_color_green}Uninstall successful ✅{shell_color_reset}")
except requests.RequestException as e:
print(f"Request failed: {e}")
#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")
if "--no-animations" in sys.argv:
no_animations = True
sys.argv.remove("--no-animations")
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]
build_action(manifest, platform)
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 -1
View File
@@ -1,7 +1,7 @@
[manifest] [manifest]
version=0.1 version=0.1
[target] [target]
sdk=0.6.0-SNAPSHOT3 sdk=0.6.0-SNAPSHOT7
platforms=esp32,esp32s3 platforms=esp32,esp32s3
[app] [app]
id=one.tactility.graphicsdemo id=one.tactility.graphicsdemo
+36 -10
View File
@@ -14,12 +14,13 @@ import shutil
import configparser import configparser
ttbuild_path = ".tactility" ttbuild_path = ".tactility"
ttbuild_version = "2.3.1" ttbuild_version = "2.3.4"
ttbuild_cdn = "https://cdn.tactility.one" ttbuild_cdn = "https://cdn.tactility.one"
ttbuild_sdk_json_validity = 3600 # seconds ttbuild_sdk_json_validity = 3600 # seconds
ttport = 6666 ttport = 6666
verbose = False verbose = False
use_local_sdk = False use_local_sdk = False
local_base_path = None
valid_platforms = ["esp32", "esp32s3"] valid_platforms = ["esp32", "esp32s3"]
no_animations = False no_animations = False
@@ -69,7 +70,7 @@ def print_help():
print("") print("")
print("Options:") print("Options:")
print(" --help Show this commandline info") print(" --help Show this commandline info")
print(" --local-sdk Use SDK specified by environment variable TACTILITY_SDK_PATH") 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(" --skip-build Run everything except the idf.py/CMake commands")
print(" --verbose Show extra console output") print(" --verbose Show extra console output")
print(" --no-animations Disable animations during building (e.g. for CI jobs)") print(" --no-animations Disable animations during building (e.g. for CI jobs)")
@@ -126,13 +127,30 @@ def read_sdk_json():
return json.load(json_file) return json.load(json_file)
def get_sdk_dir(version, platform): def get_sdk_dir(version, platform):
global use_local_sdk global use_local_sdk, local_base_path
if use_local_sdk: if use_local_sdk:
return os.environ.get("TACTILITY_SDK_PATH") 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: else:
global ttbuild_cdn
return os.path.join(ttbuild_path, f"{version}-{platform}", "TactilitySDK") 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): def get_sdk_root_dir(version, platform):
global ttbuild_cdn global ttbuild_cdn
return os.path.join(ttbuild_path, f"{version}-{platform}") return os.path.join(ttbuild_path, f"{version}-{platform}")
@@ -188,7 +206,7 @@ def validate_environment():
exit_with_error("manifest.properties not found") exit_with_error("manifest.properties not found")
if use_local_sdk == False and os.environ.get("TACTILITY_SDK_PATH") is not None: 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("TACTILITY_SDK_PATH is set, but will be ignored by this command.")
print_warning("If you want to use it, use the 'build local' parameters.") 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: 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.") exit_with_error("local build was requested, but TACTILITY_SDK_PATH environment variable is not set.")
@@ -315,10 +333,11 @@ def build_all(version, platforms, skip_build):
# This can lead to code caching issues, so sometimes a clean build is required # This can lead to code caching issues, so sometimes a clean build is required
if find_elf_file(platform) is None: if find_elf_file(platform) is None:
if not build_first(version, platform, skip_build): if not build_first(version, platform, skip_build):
break return False
else: else:
if not build_consecutively(version, platform, skip_build): if not build_consecutively(version, platform, skip_build):
break return False
return True
def wait_for_build(process, platform): def wait_for_build(process, platform):
global no_animations global no_animations
@@ -454,9 +473,16 @@ def build_action(manifest, platform_arg):
# Environment validation # Environment validation
validate_environment() validate_environment()
platforms_to_build = get_manifest_target_platforms(manifest, platform_arg) platforms_to_build = get_manifest_target_platforms(manifest, platform_arg)
if not use_local_sdk:
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): if should_fetch_sdkconfig_files(platforms_to_build):
fetch_sdkconfig_files(platforms_to_build) fetch_sdkconfig_files(platforms_to_build)
if not use_local_sdk:
sdk_json = read_sdk_json() sdk_json = read_sdk_json()
validate_self(sdk_json) validate_self(sdk_json)
if not "versions" in sdk_json: if not "versions" in sdk_json:
@@ -467,7 +493,7 @@ def build_action(manifest, platform_arg):
validate_version_and_platforms(sdk_json, sdk_version, platforms_to_build) validate_version_and_platforms(sdk_json, sdk_version, platforms_to_build)
if not sdk_download_all(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") exit_with_error("Failed to download one or more SDKs")
build_all(sdk_version, platforms_to_build, skip_build) # Environment validation if build_all(sdk_version, platforms_to_build, skip_build): # Environment validation
if not skip_build: if not skip_build:
package_all(platforms_to_build) package_all(platforms_to_build)
+1 -1
View File
@@ -1,7 +1,7 @@
[manifest] [manifest]
version=0.1 version=0.1
[target] [target]
sdk=0.6.0-SNAPSHOT3 sdk=0.6.0-SNAPSHOT7
platforms=esp32,esp32s3 platforms=esp32,esp32s3
[app] [app]
id=one.tactility.helloworld id=one.tactility.helloworld
+36 -10
View File
@@ -14,12 +14,13 @@ import shutil
import configparser import configparser
ttbuild_path = ".tactility" ttbuild_path = ".tactility"
ttbuild_version = "2.3.1" ttbuild_version = "2.3.4"
ttbuild_cdn = "https://cdn.tactility.one" ttbuild_cdn = "https://cdn.tactility.one"
ttbuild_sdk_json_validity = 3600 # seconds ttbuild_sdk_json_validity = 3600 # seconds
ttport = 6666 ttport = 6666
verbose = False verbose = False
use_local_sdk = False use_local_sdk = False
local_base_path = None
valid_platforms = ["esp32", "esp32s3"] valid_platforms = ["esp32", "esp32s3"]
no_animations = False no_animations = False
@@ -69,7 +70,7 @@ def print_help():
print("") print("")
print("Options:") print("Options:")
print(" --help Show this commandline info") print(" --help Show this commandline info")
print(" --local-sdk Use SDK specified by environment variable TACTILITY_SDK_PATH") 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(" --skip-build Run everything except the idf.py/CMake commands")
print(" --verbose Show extra console output") print(" --verbose Show extra console output")
print(" --no-animations Disable animations during building (e.g. for CI jobs)") print(" --no-animations Disable animations during building (e.g. for CI jobs)")
@@ -126,13 +127,30 @@ def read_sdk_json():
return json.load(json_file) return json.load(json_file)
def get_sdk_dir(version, platform): def get_sdk_dir(version, platform):
global use_local_sdk global use_local_sdk, local_base_path
if use_local_sdk: if use_local_sdk:
return os.environ.get("TACTILITY_SDK_PATH") 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: else:
global ttbuild_cdn
return os.path.join(ttbuild_path, f"{version}-{platform}", "TactilitySDK") 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): def get_sdk_root_dir(version, platform):
global ttbuild_cdn global ttbuild_cdn
return os.path.join(ttbuild_path, f"{version}-{platform}") return os.path.join(ttbuild_path, f"{version}-{platform}")
@@ -188,7 +206,7 @@ def validate_environment():
exit_with_error("manifest.properties not found") exit_with_error("manifest.properties not found")
if use_local_sdk == False and os.environ.get("TACTILITY_SDK_PATH") is not None: 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("TACTILITY_SDK_PATH is set, but will be ignored by this command.")
print_warning("If you want to use it, use the 'build local' parameters.") 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: 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.") exit_with_error("local build was requested, but TACTILITY_SDK_PATH environment variable is not set.")
@@ -315,10 +333,11 @@ def build_all(version, platforms, skip_build):
# This can lead to code caching issues, so sometimes a clean build is required # This can lead to code caching issues, so sometimes a clean build is required
if find_elf_file(platform) is None: if find_elf_file(platform) is None:
if not build_first(version, platform, skip_build): if not build_first(version, platform, skip_build):
break return False
else: else:
if not build_consecutively(version, platform, skip_build): if not build_consecutively(version, platform, skip_build):
break return False
return True
def wait_for_build(process, platform): def wait_for_build(process, platform):
global no_animations global no_animations
@@ -454,9 +473,16 @@ def build_action(manifest, platform_arg):
# Environment validation # Environment validation
validate_environment() validate_environment()
platforms_to_build = get_manifest_target_platforms(manifest, platform_arg) platforms_to_build = get_manifest_target_platforms(manifest, platform_arg)
if not use_local_sdk:
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): if should_fetch_sdkconfig_files(platforms_to_build):
fetch_sdkconfig_files(platforms_to_build) fetch_sdkconfig_files(platforms_to_build)
if not use_local_sdk:
sdk_json = read_sdk_json() sdk_json = read_sdk_json()
validate_self(sdk_json) validate_self(sdk_json)
if not "versions" in sdk_json: if not "versions" in sdk_json:
@@ -467,7 +493,7 @@ def build_action(manifest, platform_arg):
validate_version_and_platforms(sdk_json, sdk_version, platforms_to_build) validate_version_and_platforms(sdk_json, sdk_version, platforms_to_build)
if not sdk_download_all(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") exit_with_error("Failed to download one or more SDKs")
build_all(sdk_version, platforms_to_build, skip_build) # Environment validation if build_all(sdk_version, platforms_to_build, skip_build): # Environment validation
if not skip_build: if not skip_build:
package_all(platforms_to_build) package_all(platforms_to_build)
+15
View File
@@ -0,0 +1,15 @@
cmake_minimum_required(VERSION 3.20)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
file(GLOB SOURCES "Source/*.c*")
file(GLOB HEADERS "Include/*.h*")
add_library(Str STATIC)
target_sources(Str PRIVATE ${SOURCES})
include_directories(Str "Include/")
target_include_directories(Str PUBLIC "Include/")