diff --git a/.github/workflows/core_build.yml b/.github/workflows/core_build.yml deleted file mode 100644 index 2b1404b02b..0000000000 --- a/.github/workflows/core_build.yml +++ /dev/null @@ -1,121 +0,0 @@ -name: Core Build - -on: - push: - branches: [ "master" ] - pull_request: - branches: [ "master" ] - workflow_dispatch: # manual trigger - -jobs: - setup: - runs-on: ubuntu-latest - outputs: - vortex_version_major: ${{ steps.set_version.outputs.vortex_version_major }} - vortex_version_minor: ${{ steps.set_version.outputs.vortex_version_minor }} - vortex_build_number: ${{ steps.set_version.outputs.vortex_build_number }} - vortex_version_number: ${{ steps.set_version.outputs.vortex_version_number }} - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 # Fetches all history for all branches and tags - - name: Determine Version and Build Number - id: set_version - run: | - # Fetch all tags - git fetch --depth=1 origin +refs/tags/*:refs/tags/* - # Get the latest tag that matches the branch suffix - LATEST_TAG=$(git tag --list | grep -E "^[[:digit:]]+\.[[:digit:]]+\$" | sort -V | tail -n1) - if [ -z "$LATEST_TAG" ]; then - echo "No matching tags found. Setting default version." - VERSION_MAJOR="0" - VERSION_MINOR="1" - BUILD_NUMBER="0" - else - echo "Found latest tag: $LATEST_TAG" - VERSION_MAJOR=$(echo $LATEST_TAG | cut -d. -f1) - VERSION_MINOR=$(echo $LATEST_TAG | cut -d. -f2) - BUILD_NUMBER=$(git rev-list --count $LATEST_TAG..HEAD) - fi - FULL_VERSION="$VERSION_MAJOR.$VERSION_MINOR.$BUILD_NUMBER" - echo "vortex_version_major=$VERSION_MAJOR" >> $GITHUB_OUTPUT - echo "vortex_version_minor=$VERSION_MINOR" >> $GITHUB_OUTPUT - echo "vortex_build_number=$BUILD_NUMBER" >> $GITHUB_OUTPUT - echo "vortex_version_number=$FULL_VERSION" >> $GITHUB_OUTPUT - echo "Version Number: $FULL_VERSION" - - test: - needs: setup - runs-on: ubuntu-latest - steps: - - name: Checkout current repository - uses: actions/checkout@v3 - - name: Update Package Lists - run: sudo apt-get update - - name: Install Dependencies - run: sudo apt-get install valgrind g++ make --fix-missing - - name: Build - run: | - export VORTEX_VERSION_MAJOR=${{ needs.setup.outputs.vortex_version_major }} - export VORTEX_VERSION_MINOR=${{ needs.setup.outputs.vortex_version_minor }} - export VORTEX_BUILD_NUMBER=${{ needs.setup.outputs.vortex_build_number }} - export VORTEX_VERSION_NUMBER=${{ needs.setup.outputs.vortex_version_number }} - make -j - working-directory: VortexEngine - - name: Set execute permissions for test script - run: chmod +x ./runtests.sh - working-directory: VortexEngine/tests - - name: Run general tests - run: ./runtests.sh --general - working-directory: VortexEngine/tests - - wasm: - needs: [setup, test] - runs-on: ubuntu-latest - steps: - - name: Checkout current repository - uses: actions/checkout@v3 - - name: Update Package Lists - run: sudo apt-get update - - name: Install Emscripten - run: | - sudo apt install -y cmake python3 - git clone https://github.com/emscripten-core/emsdk.git - cd emsdk - ./emsdk install latest - ./emsdk activate latest - working-directory: VortexEngine/VortexLib - - name: Build Webassembly - run: | - source ./emsdk/emsdk_env.sh - export VORTEX_VERSION_MAJOR=${{ needs.setup.outputs.vortex_version_major }} - export VORTEX_VERSION_MINOR=${{ needs.setup.outputs.vortex_version_minor }} - export VORTEX_BUILD_NUMBER=${{ needs.setup.outputs.vortex_build_number }} - export VORTEX_VERSION_NUMBER=${{ needs.setup.outputs.vortex_version_number }} - make -j wasm - working-directory: VortexEngine/VortexLib - - docs: - needs: [setup, test, wasm] - runs-on: ubuntu-latest - if: github.ref == 'refs/heads/master' - steps: - - name: Checkout current repository - uses: actions/checkout@v3 - - name: Update Package Lists - run: sudo apt-get update - - name: Install Dependencies - run: sudo apt-get install doxygen graphviz texlive --fix-missing - - name: Checkout doxygen-awesome - run: git clone https://github.com/jothepro/doxygen-awesome-css.git doxygen-awesome-css - - name: Generate Documentation - run: | - mkdir -p docs/core - doxygen Doxyfile - echo "Listing contents of docs/core:" - ls -R docs/core || echo "No files found in docs/core" - - name: Upload Doxygen Documentation as Artifact - uses: actions/upload-artifact@v3 - with: - name: doxygen-docs-core - path: docs/core diff --git a/.github/workflows/spark_build.yml b/.github/workflows/spark_build.yml new file mode 100644 index 0000000000..f4c9380425 --- /dev/null +++ b/.github/workflows/spark_build.yml @@ -0,0 +1,181 @@ +name: Spark Build + +on: + push: + branches: [ "spark" ] + pull_request: + branches: [ "spark" ] + workflow_dispatch: # manual trigger + +jobs: + setup: + runs-on: ubuntu-latest + outputs: + vortex_version_major: ${{ steps.set_version.outputs.vortex_version_major }} + vortex_version_minor: ${{ steps.set_version.outputs.vortex_version_minor }} + vortex_build_number: ${{ steps.set_version.outputs.vortex_build_number }} + vortex_version_number: ${{ steps.set_version.outputs.vortex_version_number }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # Fetches all history for all branches and tags + - name: Determine Version and Build Number + id: set_version + run: | + BRANCH_SUFFIX="s" + # Fetch all tags + git fetch --depth=1 origin +refs/tags/*:refs/tags/* + # Get the latest tag that matches the branch suffix + LATEST_TAG=$(git tag --list "*${BRANCH_SUFFIX}" | sort -V | tail -n1) + if [ -z "$LATEST_TAG" ]; then + echo "No matching tags found. Setting default version." + VERSION_MAJOR="0" + VERSION_MINOR="1" + BUILD_NUMBER="0" + else + echo "Found latest tag: $LATEST_TAG" + VERSION_NUMBER=$(echo $LATEST_TAG | sed "s/${BRANCH_SUFFIX}//g") + VERSION_MAJOR=$(echo $VERSION_NUMBER | cut -d. -f1) + VERSION_MINOR=$(echo $VERSION_NUMBER | cut -d. -f2) + BUILD_NUMBER=$(git rev-list --count $LATEST_TAG..HEAD) + fi + FULL_VERSION="$VERSION_MAJOR.$VERSION_MINOR.$BUILD_NUMBER" + echo "vortex_version_major=$VERSION_MAJOR" >> $GITHUB_OUTPUT + echo "vortex_version_minor=$VERSION_MINOR" >> $GITHUB_OUTPUT + echo "vortex_build_number=$BUILD_NUMBER" >> $GITHUB_OUTPUT + echo "vortex_version_number=$FULL_VERSION" >> $GITHUB_OUTPUT + echo "Version Number: $FULL_VERSION" + + test: + needs: setup + runs-on: ubuntu-latest + steps: + - name: Checkout current repository + uses: actions/checkout@v4 + - name: Update Package Lists + run: sudo apt-get update + - name: Install Dependencies + run: sudo apt-get install valgrind g++ make --fix-missing + - name: Build + run: | + export VORTEX_VERSION_MAJOR=${{ needs.setup.outputs.vortex_version_major }} + export VORTEX_VERSION_MINOR=${{ needs.setup.outputs.vortex_version_minor }} + export VORTEX_BUILD_NUMBER=${{ needs.setup.outputs.vortex_build_number }} + export VORTEX_VERSION_NUMBER=${{ needs.setup.outputs.vortex_version_number }} + make -j + working-directory: VortexEngine + - name: Set execute permissions for test script + run: chmod +x ./runtests.sh + working-directory: VortexEngine/tests + - name: Run general tests + run: ./runtests.sh --general + working-directory: VortexEngine/tests + + embedded: + needs: [setup, test] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.x' + - name: Install Dependencies + run: make install + - name: Build Binary + run: | + export VORTEX_VERSION_MAJOR=${{ needs.setup.outputs.vortex_version_major }} + export VORTEX_VERSION_MINOR=${{ needs.setup.outputs.vortex_version_minor }} + export VORTEX_BUILD_NUMBER=${{ needs.setup.outputs.vortex_build_number }} + export VORTEX_VERSION_NUMBER=${{ needs.setup.outputs.vortex_version_number }} + make build + - name: Zip firmware files + run: | + zip SparkFirmware.zip \ + build/VortexEngine.ino.bootloader.bin \ + build/VortexEngine.ino.partitions.bin \ + ~/.arduino15/packages/esp32/hardware/esp32/3.0.4/tools/partitions/boot_app0.bin \ + build/VortexEngine.ino.bin + - name: Archive firmware zip + uses: actions/upload-artifact@v4 + with: + name: spark-firmware-zip + path: SparkFirmware.zip + + wasm: + needs: [setup, test, embedded] + runs-on: ubuntu-latest + steps: + - name: Checkout current repository + uses: actions/checkout@v4 + - name: Update Package Lists + run: sudo apt-get update + - name: Install Emscripten + run: | + sudo apt install -y cmake python3 + git clone https://github.com/emscripten-core/emsdk.git + cd emsdk + ./emsdk install latest + ./emsdk activate latest + working-directory: VortexEngine/VortexLib + - name: Build Webassembly + run: | + source ./emsdk/emsdk_env.sh + export VORTEX_VERSION_MAJOR=${{ needs.setup.outputs.vortex_version_major }} + export VORTEX_VERSION_MINOR=${{ needs.setup.outputs.vortex_version_minor }} + export VORTEX_BUILD_NUMBER=${{ needs.setup.outputs.vortex_build_number }} + export VORTEX_VERSION_NUMBER=${{ needs.setup.outputs.vortex_version_number }} + make -j wasm + working-directory: VortexEngine/VortexLib + + docs: + #todo: fix the depends to be setup, test, embedded, wasm + needs: [setup, test] + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/spark' + steps: + - name: Checkout current repository + uses: actions/checkout@v4 + - name: Update Package Lists + run: sudo apt-get update + - name: Install Dependencies + run: sudo apt-get install doxygen graphviz texlive --fix-missing + - name: Checkout doxygen-awesome + run: git clone https://github.com/jothepro/doxygen-awesome-css.git doxygen-awesome-css + - name: Generate Documentation + run: | + mkdir -p docs/spark + doxygen Doxyfile + echo "Listing contents of docs/spark:" + ls -R docs/spark || echo "No files found in docs/spark" + - name: Upload Doxygen Documentation as Artifact + uses: actions/upload-artifact@v3 + with: + name: doxygen-docs-spark + path: docs/spark + + deploy: + needs: [setup, test, embedded, wasm, docs] + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/spark' + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: spark-firmware-zip + path: build + - name: Rename and Deploy Firmware + run: | + DEVICE_TYPE="spark" + VERSIONED_FILENAME="VortexEngine-${DEVICE_TYPE}-${{ needs.setup.outputs.vortex_version_number }}.zip" + mv build/SparkFirmware.zip build/$VERSIONED_FILENAME + echo "Version is ${{ needs.setup.outputs.vortex_version_number }}" + echo "Filename is $VERSIONED_FILENAME" + curl -X POST \ + -F "file=@build/$VERSIONED_FILENAME" \ + -F "device=$DEVICE_TYPE" \ + -F "version=${{ needs.setup.outputs.vortex_version_number }}" \ + -F "category=firmware" \ + -F "clientApiKey=${{ secrets.VORTEX_COMMUNITY_API_KEY }}" \ + https://vortex.community/firmware/upload + diff --git a/Doxyfile b/Doxyfile index 9db6ecc800..b9aeb83476 100644 --- a/Doxyfile +++ b/Doxyfile @@ -58,7 +58,7 @@ PROJECT_LOGO = # entered, it will be relative to the location where doxygen was started. If # left blank the current directory will be used. -OUTPUT_DIRECTORY = docs/core +OUTPUT_DIRECTORY = docs/spark # If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- # directories (in 2 levels) under the output directory of each output format and diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000..fa0b3a0d4a --- /dev/null +++ b/Makefile @@ -0,0 +1,66 @@ +.PHONY: all install build upload clean compute_version + +ARDUINO_CLI = ./bin/arduino-cli --verbose +BOARD = esp32:esp32:XIAO_ESP32C3 +PORT = COMx # Replace 'x' with the appropriate COM port number +PROJECT_NAME = VortexEngine/VortexEngine.ino +BUILD_PATH = build +CONFIG_FILE = $(HOME)/.arduino15/arduino-cli.yaml + +# The branch/tag suffix for this device +BRANCH_SUFFIX=s + +DEFINES=\ + -D VORTEX_VERSION_MAJOR=$(VORTEX_VERSION_MAJOR) \ + -D VORTEX_VERSION_MINOR=$(VORTEX_VERSION_MINOR) \ + -D VORTEX_BUILD_NUMBER=$(VORTEX_BUILD_NUMBER) \ + -D VORTEX_VERSION_NUMBER=$(VORTEX_VERSION_NUMBER) \ + -MMD -c #due to a bug need the -MMD and -c otherwise esp won't build + +# Default target +all: build + +update-index: + $(ARDUINO_CLI) core update-index + +install: + sudo apt-get update + sudo apt-get install -y build-essential + pip install pyserial + mkdir -p $(HOME)/.arduino15 + if ! command -v $(ARDUINO_CLI) &> /dev/null ; then \ + curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | sudo sh ; \ + fi + echo 'board_manager: \n additional_urls: \n - https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json' | sudo tee $(CONFIG_FILE) + $(ARDUINO_CLI) lib update-index + $(ARDUINO_CLI) core update-index --config-file $(CONFIG_FILE) + $(ARDUINO_CLI) core install esp32:esp32 --config-file $(CONFIG_FILE) + $(ARDUINO_CLI) lib install FastLED@3.7.6 + +build: compute_version + $(ARDUINO_CLI) compile --fqbn $(BOARD) $(PROJECT_NAME) \ + --config-file $(CONFIG_FILE) \ + --build-path $(BUILD_PATH) \ + --build-property compiler.cpp.extra_flags="$(DEFINES)" \ + --build-property compiler.c.extra_flags="$(DEFINES)" + @echo "== Success building Spark v$(VORTEX_VERSION_NUMBER) ==" + +upload: + $(ARDUINO_CLI) upload -p $(PORT) --fqbn $(BOARD) $(PROJECT_NAME) --config-file $(CONFIG_FILE) + +core-list: + $(ARDUINO_CLI) core list + +clean: + rm -rf $(BUILD_PATH) + +# calculate the version number of the build +compute_version: + $(eval LATEST_TAG ?= $(shell git fetch --depth=1 origin +refs/tags/*:refs/tags/* &> /dev/null && git tag --list "*$(BRANCH_SUFFIX)" | sort -V | tail -n1)) + $(eval VORTEX_VERSION_MAJOR ?= $(shell echo $(LATEST_TAG) | cut -d. -f1)) + $(eval VORTEX_VERSION_MINOR ?= $(shell echo $(LATEST_TAG) | sed 's/$(BRANCH_SUFFIX)$$//' | cut -d. -f2)) + $(eval VORTEX_BUILD_NUMBER ?= $(shell git rev-list --count $(LATEST_TAG)..HEAD)) + $(eval VORTEX_VERSION_MAJOR := $(if $(VORTEX_VERSION_MAJOR),$(VORTEX_VERSION_MAJOR),0)) + $(eval VORTEX_VERSION_MINOR := $(if $(VORTEX_VERSION_MINOR),$(VORTEX_VERSION_MINOR),1)) + $(eval VORTEX_BUILD_NUMBER := $(if $(VORTEX_BUILD_NUMBER),$(VORTEX_BUILD_NUMBER),0)) + $(eval VORTEX_VERSION_NUMBER := $(VORTEX_VERSION_MAJOR).$(VORTEX_VERSION_MINOR).$(VORTEX_BUILD_NUMBER)) diff --git a/VortexEngine/VortexCLI/Makefile b/VortexEngine/VortexCLI/Makefile index b4b2f2b541..9f3599ccc2 100644 --- a/VortexEngine/VortexCLI/Makefile +++ b/VortexEngine/VortexCLI/Makefile @@ -19,6 +19,9 @@ RANLIB=ranlib CFLAGS=-O2 -g -Wall +# The branch/tag suffix for this device +BRANCH_SUFFIX=s + # compiler defines DEFINES=\ -D VORTEX_LIB \ @@ -135,9 +138,9 @@ clean: # calculate the version number of the build compute_version: - $(eval LATEST_TAG ?= $(shell git fetch --depth=1 origin +refs/tags/*:refs/tags/* &> /dev/null && git tag --list | grep --invert-match '[a-zA-Z]' | sort -V | tail -n1)) + $(eval LATEST_TAG ?= $(shell git fetch --depth=1 origin +refs/tags/*:refs/tags/* &> /dev/null && git tag --list "*$(BRANCH_SUFFIX)" | sort -V | tail -n1)) $(eval VORTEX_VERSION_MAJOR ?= $(shell echo $(LATEST_TAG) | cut -d. -f1)) - $(eval VORTEX_VERSION_MINOR ?= $(shell echo $(LATEST_TAG) | cut -d. -f2)) + $(eval VORTEX_VERSION_MINOR ?= $(shell echo $(LATEST_TAG) | sed 's/$(BRANCH_SUFFIX)$$//' | cut -d. -f2)) $(eval VORTEX_BUILD_NUMBER ?= $(shell git rev-list --count $(LATEST_TAG)..HEAD)) $(eval VORTEX_VERSION_MAJOR := $(if $(VORTEX_VERSION_MAJOR),$(VORTEX_VERSION_MAJOR),0)) $(eval VORTEX_VERSION_MINOR := $(if $(VORTEX_VERSION_MINOR),$(VORTEX_VERSION_MINOR),1)) diff --git a/VortexEngine/VortexEngine.ino b/VortexEngine/VortexEngine.ino new file mode 100644 index 0000000000..a0985e6bd1 --- /dev/null +++ b/VortexEngine/VortexEngine.ino @@ -0,0 +1,14 @@ +#include +#include "src/VortexEngine.h" + +void setup() +{ + if (!VortexEngine::init()) { + // uhoh + } +} + +void loop() +{ + VortexEngine::tick(); +} diff --git a/VortexEngine/VortexLib/Makefile b/VortexEngine/VortexLib/Makefile index 98900f08b8..d51ed0f74c 100644 --- a/VortexEngine/VortexLib/Makefile +++ b/VortexEngine/VortexLib/Makefile @@ -24,6 +24,9 @@ ifndef WASM CFLAGS += -g endif +# The branch/tag suffix for this device +BRANCH_SUFFIX=s + # compiler defines DEFINES=\ -D VORTEX_LIB \ @@ -146,9 +149,9 @@ clean: # calculate the version number of the build compute_version: - $(eval LATEST_TAG ?= $(shell git fetch --depth=1 origin +refs/tags/*:refs/tags/* &> /dev/null && git tag --list | grep --invert-match '[a-zA-Z]' | sort -V | tail -n1)) + $(eval LATEST_TAG ?= $(shell git fetch --depth=1 origin +refs/tags/*:refs/tags/* &> /dev/null && git tag --list "*$(BRANCH_SUFFIX)" | sort -V | tail -n1)) $(eval VORTEX_VERSION_MAJOR ?= $(shell echo $(LATEST_TAG) | cut -d. -f1)) - $(eval VORTEX_VERSION_MINOR ?= $(shell echo $(LATEST_TAG) | cut -d. -f2)) + $(eval VORTEX_VERSION_MINOR ?= $(shell echo $(LATEST_TAG) | sed 's/$(BRANCH_SUFFIX)$$//' | cut -d. -f2)) $(eval VORTEX_BUILD_NUMBER ?= $(shell git rev-list --count $(LATEST_TAG)..HEAD)) $(eval VORTEX_VERSION_MAJOR := $(if $(VORTEX_VERSION_MAJOR),$(VORTEX_VERSION_MAJOR),0)) $(eval VORTEX_VERSION_MINOR := $(if $(VORTEX_VERSION_MINOR),$(VORTEX_VERSION_MINOR),1)) diff --git a/VortexEngine/VortexLib/VortexLib.cpp b/VortexEngine/VortexLib/VortexLib.cpp index 09e5e61c77..c492b7f335 100644 --- a/VortexEngine/VortexLib/VortexLib.cpp +++ b/VortexEngine/VortexLib/VortexLib.cpp @@ -215,10 +215,6 @@ EMSCRIPTEN_BINDINGS(Vortex) { .value("LED_3", LedPos::LED_3) .value("LED_4", LedPos::LED_4) .value("LED_5", LedPos::LED_5) - .value("LED_6", LedPos::LED_6) - .value("LED_7", LedPos::LED_7) - .value("LED_8", LedPos::LED_8) - .value("LED_9", LedPos::LED_9) .value("LED_COUNT", LedPos::LED_COUNT) .value("LED_LAST", LedPos::LED_LAST) .value("LED_ALL", LedPos::LED_ALL) diff --git a/VortexEngine/src/Buttons/Button.cpp b/VortexEngine/src/Buttons/Button.cpp index e565dbbb5c..b8ca93e271 100644 --- a/VortexEngine/src/Buttons/Button.cpp +++ b/VortexEngine/src/Buttons/Button.cpp @@ -8,6 +8,10 @@ #include "VortexLib.h" #endif +#ifdef VORTEX_EMBEDDED +#include +#endif + Button::Button() : m_pinNum(0), m_pressTime(0), @@ -46,12 +50,19 @@ bool Button::init(uint8_t pin) m_longClick = false; m_pinNum = pin; +#ifdef VORTEX_EMBEDDED + pinMode(m_pinNum, INPUT_PULLUP); +#endif return true; } bool Button::check() { +#ifdef VORTEX_EMBEDDED + return digitalRead(m_pinNum) == LOW; +#else return (Vortex::vcallbacks()->checkPinHook(m_pinNum) == 0); +#endif } void Button::update() diff --git a/VortexEngine/src/Buttons/Buttons.cpp b/VortexEngine/src/Buttons/Buttons.cpp index 466b22920c..b17c2f36b1 100644 --- a/VortexEngine/src/Buttons/Buttons.cpp +++ b/VortexEngine/src/Buttons/Buttons.cpp @@ -7,12 +7,17 @@ #include "../Time/Timings.h" #endif +// spark button pin +#define BUTTON_PIN 5 + // Since there is only one button I am just going to expose a global pointer to // access it, instead of making the Button class static in case a second button // is added. This makes it easier to access the button from other places while // still allowing for a second instance to be added. I wish there was a more // elegant way to make the button accessible but not global. // This will simply point at Buttons::m_button. + +// Button Button *g_pButton = nullptr; // static members @@ -20,8 +25,8 @@ Button Buttons::m_buttons[NUM_BUTTONS]; bool Buttons::init() { - // initialize the button on pin 1 - if (!m_buttons[0].init(1)) { + // initialize the button on pins 9/10/11 + if (!m_buttons[0].init(BUTTON_PIN)) { return false; } g_pButton = &m_buttons[0]; diff --git a/VortexEngine/src/Buttons/Buttons.h b/VortexEngine/src/Buttons/Buttons.h index 7f02e34c73..fabe5b9fbb 100644 --- a/VortexEngine/src/Buttons/Buttons.h +++ b/VortexEngine/src/Buttons/Buttons.h @@ -29,7 +29,7 @@ class Buttons static Button m_buttons[NUM_BUTTONS]; }; -// best way I think +// Button Mid extern Button *g_pButton; #endif diff --git a/VortexEngine/src/Leds/LedTypes.h b/VortexEngine/src/Leds/LedTypes.h index 73bcce80f3..6d2b03d229 100644 --- a/VortexEngine/src/Leds/LedTypes.h +++ b/VortexEngine/src/Leds/LedTypes.h @@ -19,10 +19,6 @@ enum LedPos : uint8_t LED_3, LED_4, LED_5, - LED_6, - LED_7, - LED_8, - LED_9, // the number of entries above LED_COUNT, @@ -71,8 +67,6 @@ enum Pair : uint8_t PAIR_0 = PAIR_FIRST, PAIR_1, PAIR_2, - PAIR_3, - PAIR_4, PAIR_COUNT, PAIR_LAST = (PAIR_COUNT - 1), @@ -81,6 +75,14 @@ enum Pair : uint8_t // Compile-time check on the number of pairs and leds static_assert(LED_COUNT == (PAIR_COUNT * 2), "Incorrect number of Pairs for Leds! Adjust the Led enum or Pair enum to match"); +// map other leds for multi compatibility +#define LED_6 LED_0 +#define LED_7 LED_1 +#define LED_8 LED_2 +#define LED_9 LED_3 +#define PAIR_3 PAIR_0 +#define PAIR_4 PAIR_1 + // check if an led is even or odd #define isEven(pos) ((pos % 2) == 0) #define isOdd(pos) ((pos % 2) != 0) @@ -152,6 +154,9 @@ inline LedPos ledmapGetNextLed(LedMap map, LedPos pos) #define MAP_PAIR_EVENS (((1 << LED_COUNT) - 1) & 0x55555555) #define MAP_PAIR_ODDS (((1 << LED_COUNT) - 1) & 0xAAAAAAAA) +#define MAP_OUTER_RING ((((1 << LED_COUNT) - 1) >> (LED_COUNT / 2)) << (LED_COUNT / 2)) +#define MAP_INNER_RING ((((1 << LED_COUNT) - 1) << (LED_COUNT / 2)) >> (LED_COUNT / 2)) + // Some preset bitmaps for pair groupings #define MAP_PAIR_ODD_EVENS (MAP_PAIR_EVEN(PAIR_0) | MAP_PAIR_EVEN(PAIR_2) | MAP_PAIR_EVEN(PAIR_4)) #define MAP_PAIR_ODD_ODDS (MAP_PAIR_ODD(PAIR_0) | MAP_PAIR_ODD(PAIR_2) | MAP_PAIR_ODD(PAIR_4)) @@ -159,6 +164,11 @@ inline LedPos ledmapGetNextLed(LedMap map, LedPos pos) #define MAP_PAIR_EVEN_EVENS (MAP_PAIR_EVEN(PAIR_3) | MAP_PAIR_EVEN(PAIR_1)) #define MAP_PAIR_EVEN_ODDS (MAP_PAIR_ODD(PAIR_3) | MAP_PAIR_ODD(PAIR_1)) +// bitmaps specific to Sparks +#define MAP_OPPOSITES_1 (MAP_LED(LED_0) | MAP_LED(LED_3)) +#define MAP_OPPOSITES_2 (MAP_LED(LED_1) | MAP_LED(LED_4)) +#define MAP_OPPOSITES_3 (MAP_LED(LED_2) | MAP_LED(LED_5)) + // set a single led inline void ledmapSetLed(LedMap &map, LedPos pos) { diff --git a/VortexEngine/src/Leds/Leds.cpp b/VortexEngine/src/Leds/Leds.cpp index 0d1dd4c400..09a665aa06 100644 --- a/VortexEngine/src/Leds/Leds.cpp +++ b/VortexEngine/src/Leds/Leds.cpp @@ -12,6 +12,12 @@ #include "../../VortexLib/VortexLib.h" #endif +#ifdef VORTEX_EMBEDDED +#pragma GCC diagnostic ignored "-Wclass-memaccess" +#include +#define LED_PIN 0 +#endif + // global brightness uint8_t Leds::m_brightness = DEFAULT_BRIGHTNESS; // array of led color values @@ -19,6 +25,10 @@ RGBColor Leds::m_ledColors[LED_COUNT] = { RGB_OFF }; bool Leds::init() { +#ifdef VORTEX_EMBEDDED + FastLED.addLeds((CRGB *)m_ledColors, LED_COUNT); + FastLED.setMaxRefreshRate(0); +#endif #ifdef VORTEX_LIB Vortex::vcallbacks()->ledsInit(m_ledColors, LED_COUNT); #endif @@ -74,8 +84,10 @@ void Leds::setRangeEvens(Pair first, Pair last, RGBColor col) void Leds::setAllEvens(RGBColor col) { - for (Pair pos = PAIR_FIRST; pos <= PAIR_LAST; pos++) { - setIndex(pairEven(pos), col); + for (LedPos pos = LED_FIRST; pos <= LED_LAST; pos++) { + if (isEven(pos)) { + setIndex(pos, col); + } } } @@ -88,8 +100,10 @@ void Leds::setRangeOdds(Pair first, Pair last, RGBColor col) void Leds::setAllOdds(RGBColor col) { - for (Pair pos = PAIR_FIRST; pos <= PAIR_LAST; pos++) { - setIndex(pairOdd(pos), col); + for (LedPos pos = LED_FIRST; pos <= LED_LAST; pos++) { + if (isOdd(pos)) { + setIndex(pos, col); + } } } @@ -102,8 +116,10 @@ void Leds::clearRangeEvens(Pair first, Pair last) void Leds::clearAllEvens() { - for (Pair pos = PAIR_FIRST; pos <= PAIR_LAST; pos++) { - clearIndex(pairEven(pos)); + for (LedPos pos = LED_FIRST; pos <= LED_LAST; pos++) { + if (isEven(pos)) { + clearIndex(pos); + } } } @@ -116,8 +132,10 @@ void Leds::clearRangeOdds(Pair first, Pair last) void Leds::clearAllOdds() { - for (Pair pos = PAIR_FIRST; pos <= PAIR_LAST; pos++) { - clearIndex(pairOdd(pos)); + for (LedPos pos = LED_FIRST; pos <= LED_LAST; pos++) { + if (isOdd(pos)) { + clearIndex(pos); + } } } @@ -260,6 +278,9 @@ void Leds::holdAll(RGBColor col) void Leds::update() { +#ifdef VORTEX_EMBEDDED + FastLED.show(m_brightness); +#endif #ifdef VORTEX_LIB Vortex::vcallbacks()->ledsShow(); #endif diff --git a/VortexEngine/src/Log/Log.cpp b/VortexEngine/src/Log/Log.cpp index 19877548da..c79ff42b06 100644 --- a/VortexEngine/src/Log/Log.cpp +++ b/VortexEngine/src/Log/Log.cpp @@ -11,12 +11,27 @@ #include "VortexLib.h" #endif +#ifdef VORTEX_EMBEDDED +#include +#endif + #if LOGGING_LEVEL > 0 void InfoMsg(const char *msg, ...) { +#ifdef VORTEX_EMBEDDED + if (!SerialComs::isConnected()) { + return; + } +#endif va_list list; va_start(list, msg); +#ifdef VORTEX_EMBEDDED + char buf[2048] = {0}; + vsnprintf(buf, sizeof(buf), msg, list); + Serial.println(buf); +#else Vortex::printlog(NULL, NULL, 0, msg, list); +#endif va_end(list); } #endif @@ -24,9 +39,22 @@ void InfoMsg(const char *msg, ...) #if LOGGING_LEVEL > 1 void ErrorMsg(const char *func, const char *msg, ...) { +#ifdef VORTEX_EMBEDDED + if (!SerialComs::isConnected()) { + return; + } +#endif va_list list; va_start(list, msg); +#ifdef VORTEX_EMBEDDED + char fmt[2048] = {0}; + snprintf(fmt, sizeof(fmt), "%s(): %s", func, msg); + char buf[2048] = {0}; + vsnprintf(buf, sizeof(buf), fmt, list); + Serial.println(buf); +#else Vortex::printlog(NULL, func, 0, msg, list); +#endif va_end(list); } #endif @@ -34,6 +62,11 @@ void ErrorMsg(const char *func, const char *msg, ...) #if LOGGING_LEVEL > 2 void DebugMsg(const char *file, const char *func, int line, const char *msg, ...) { +#ifdef VORTEX_EMBEDDED + if (!SerialComs::isConnected()) { + return; + } +#endif va_list list; va_start(list, msg); const char *ptr = file + strlen(file); @@ -46,7 +79,15 @@ void DebugMsg(const char *file, const char *func, int line, const char *msg, ... } ptr--; } +#ifdef VORTEX_EMBEDDED + char fmt[2048] = {0}; + snprintf(fmt, sizeof(fmt), "%s:%d %s(): %s", file, line, func, msg); + char buf[2048] = {0}; + vsnprintf(buf, sizeof(buf), fmt, list); + Serial.println(buf); +#else Vortex::printlog(file, func, line, msg, list); +#endif va_end(list); } #endif diff --git a/VortexEngine/src/Memory/Memory.cpp b/VortexEngine/src/Memory/Memory.cpp index 9172488167..ff3381cd78 100644 --- a/VortexEngine/src/Memory/Memory.cpp +++ b/VortexEngine/src/Memory/Memory.cpp @@ -120,14 +120,14 @@ uint32_t cur_memory_usage_total() #ifndef VORTEX_LIB // for C++11 need the following: -void *operator new (size_t size) { return vmalloc(size); } -void *operator new[](size_t size) { return vmalloc(size); } -void operator delete (void *ptr) { vfree(ptr); } -void operator delete[](void *ptr) { vfree(ptr); } -void *operator new (size_t size, void *ptr) noexcept { return ptr; } -void *operator new[](size_t size, void *ptr) noexcept { return ptr; } -void operator delete (void *ptr, size_t size) noexcept { vfree(ptr); } -void operator delete[](void *ptr, size_t size) noexcept { vfree(ptr); } +//void *operator new (size_t size) { return vmalloc(size); } +//void *operator new[](size_t size) { return vmalloc(size); } +//void operator delete (void *ptr) { vfree(ptr); } +//void operator delete[](void *ptr) { vfree(ptr); } +//void *operator new (size_t size, void *ptr) noexcept { return ptr; } +//void *operator new[](size_t size, void *ptr) noexcept { return ptr; } +//void operator delete (void *ptr, size_t size) noexcept { vfree(ptr); } +//void operator delete[](void *ptr, size_t size) noexcept { vfree(ptr); } //void *operator new (size_t size, std::align_val_t al) { return vmalloc(size); } //void *operator new[](size_t size, std::align_val_t al) { return vmalloc(size); } //void operator delete (void *ptr, std::align_val_t al) noexcept { vfree(ptr); } @@ -136,7 +136,7 @@ void operator delete[](void *ptr, size_t size) noexcept { vfree(ptr); } //void operator delete[](void *ptr, size_t size, std::align_val_t al) noexcept { vfree(ptr); } // needed for C++ virtual functions -extern "C" void __cxa_pure_virtual(void) {} -extern "C" void __cxa_deleted_virtual(void) {} +//extern "C" void __cxa_pure_virtual(void) {} +//extern "C" void __cxa_deleted_virtual(void) {} #endif diff --git a/VortexEngine/src/Memory/Memory.h b/VortexEngine/src/Memory/Memory.h index b851d781ec..faf042e82a 100644 --- a/VortexEngine/src/Memory/Memory.h +++ b/VortexEngine/src/Memory/Memory.h @@ -37,14 +37,14 @@ uint32_t cur_memory_usage_total(); #endif #ifndef VORTEX_LIB -void *operator new (size_t size); -void *operator new[](size_t size); -void operator delete (void *ptr); -void operator delete[](void *ptr); -void *operator new (size_t size, void *ptr) noexcept; -void *operator new[](size_t size, void *ptr) noexcept; -void operator delete (void *ptr, size_t size) noexcept; -void operator delete[](void *ptr, size_t size) noexcept; +//void *operator new (size_t size); +//void *operator new[](size_t size); +//void operator delete (void *ptr); +//void operator delete[](void *ptr); +//void *operator new (size_t size, void *ptr) noexcept; +//void *operator new[](size_t size, void *ptr) noexcept; +//void operator delete (void *ptr, size_t size) noexcept; +//void operator delete[](void *ptr, size_t size) noexcept; //void *operator new (size_t size, std::align_val_t al); //void *operator new[](size_t size, std::align_val_t al); //void operator delete (void *ptr, std::align_val_t al) noexcept; diff --git a/VortexEngine/src/Menus/Menu.cpp b/VortexEngine/src/Menus/Menu.cpp index abfa81f77b..6e76e7a93c 100644 --- a/VortexEngine/src/Menus/Menu.cpp +++ b/VortexEngine/src/Menus/Menu.cpp @@ -2,7 +2,7 @@ #include "../Time/TimeControl.h" #include "../Time/Timings.h" -#include "../Buttons/Button.h" +#include "../Buttons/Buttons.h" #include "../Menus/Menus.h" #include "../Modes/Modes.h" #include "../Modes/Mode.h" @@ -131,18 +131,27 @@ void Menu::nextBulbSelection() // do not allow multi led to select anything else //break; } - m_targetLeds = MAP_LED(LED_FIRST); + m_targetLeds = MAP_LED(LED_MULTI); break; - case MAP_LED(LED_LAST): + case MAP_LED(LED_MULTI): m_targetLeds = MAP_PAIR_EVENS; break; case MAP_PAIR_EVENS: m_targetLeds = MAP_PAIR_ODDS; break; case MAP_PAIR_ODDS: - m_targetLeds = MAP_LED(LED_MULTI); + m_targetLeds = MAP_OPPOSITES_1; break; - case MAP_LED(LED_MULTI): + case MAP_OPPOSITES_1: + m_targetLeds = MAP_OPPOSITES_2; + break; + case MAP_OPPOSITES_2: + m_targetLeds = MAP_OPPOSITES_3; + break; + case MAP_OPPOSITES_3: + m_targetLeds = MAP_LED(LED_FIRST); + break; + case MAP_LED(LED_LAST): m_targetLeds = MAP_LED_ALL; break; default: // LED_FIRST through LED_LAST diff --git a/VortexEngine/src/Menus/MenuList/EditorConnection.cpp b/VortexEngine/src/Menus/MenuList/EditorConnection.cpp index c8dade7503..72d8f6646d 100644 --- a/VortexEngine/src/Menus/MenuList/EditorConnection.cpp +++ b/VortexEngine/src/Menus/MenuList/EditorConnection.cpp @@ -5,7 +5,9 @@ #include "../../Serial/Serial.h" #include "../../Storage/Storage.h" #include "../../Wireless/VLSender.h" +#include "../../Wireless/VLReceiver.h" #include "../../Time/TimeControl.h" +#include "../../Time/Timings.h" #include "../../Colors/Colorset.h" #include "../../Modes/Modes.h" #include "../../Modes/Mode.h" @@ -14,12 +16,19 @@ #include +#define FIRMWARE_TRANSFER_BLOCK_SIZE 512 + EditorConnection::EditorConnection(const RGBColor &col, bool advanced) : Menu(col, advanced), m_state(STATE_DISCONNECTED), + m_timeOutStartTime(0), + m_chromaModeIdx(0), m_allowReset(true), m_previousModeIndex(0), - m_numModesToReceive(0) + m_numModesToReceive(0), + m_curStep(0), + m_firmwareSize(0), + m_firmwareOffset(0) { } @@ -36,6 +45,7 @@ bool EditorConnection::init() // skip led selection m_ledSelected = true; clearDemo(); + DEBUG_LOG("Entering Editor Connection"); return true; } @@ -65,14 +75,6 @@ bool EditorConnection::receiveMessage(const char *message) return true; } -void EditorConnection::clearDemo() -{ - Colorset set(RGB_WHITE0); - PatternArgs args(1, 0, 0); - m_previewMode.setPattern(PATTERN_STROBE, LED_ALL, &args, &set); - m_previewMode.init(); -} - Menu::MenuAction EditorConnection::run() { MenuAction result = Menu::run(); @@ -84,8 +86,17 @@ Menu::MenuAction EditorConnection::run() showEditor(); // receive any data from serial into the receive buffer receiveData(); + // handle the current state + handleState(); + return MENU_CONTINUE; +} + +void EditorConnection::handleState() +{ // operate on the state of the editor connection switch (m_state) { + // ------------------------------- + // Disconnected case STATE_DISCONNECTED: default: // not connected yet so check for connections @@ -98,21 +109,30 @@ Menu::MenuAction EditorConnection::run() // a connection was found, say hello m_state = STATE_GREETING; break; + + // ------------------------------- + // Send Greeting case STATE_GREETING: m_receiveBuffer.clear(); // send the hello greeting with our version number and build time SerialComs::write(EDITOR_VERB_GREETING); m_state = STATE_IDLE; break; + + // ------------------------------- + // Chillin case STATE_IDLE: // parse the receive buffer for any commands from the editor handleCommand(); // watch for disconnects - if (!SerialComs::isConnected()) { - Leds::holdAll(RGB_GREEN); + if (!SerialComs::isConnectedReal()) { + Leds::holdAll(RGB_RED); leaveMenu(true); } break; + + // ------------------------------- + // Send Modes to PC case STATE_PULL_MODES: // editor requested pull modes, send the modes sendModes(); @@ -131,6 +151,9 @@ Menu::MenuAction EditorConnection::run() // go idle m_state = STATE_IDLE; break; + + // ------------------------------- + // Receive Modes from PC case STATE_PUSH_MODES: // editor requested to push modes, clear first and reset first m_receiveBuffer.clear(); @@ -152,6 +175,9 @@ Menu::MenuAction EditorConnection::run() SerialComs::write(EDITOR_VERB_PUSH_MODES_ACK); m_state = STATE_IDLE; break; + + // ------------------------------- + // Demo Mode from PC case STATE_DEMO_MODE: // editor requested to push modes, clear first and reset first m_receiveBuffer.clear(); @@ -173,12 +199,18 @@ Menu::MenuAction EditorConnection::run() SerialComs::write(EDITOR_VERB_DEMO_MODE_ACK); m_state = STATE_IDLE; break; + + // ------------------------------- + // Reset Demo to Nothing case STATE_CLEAR_DEMO: clearDemo(); m_receiveBuffer.clear(); SerialComs::write(EDITOR_VERB_CLEAR_DEMO_ACK); m_state = STATE_IDLE; break; + + // ------------------------------- + // Send Mode to Duo case STATE_TRANSMIT_MODE_VL: #if VL_ENABLE_SENDER == 1 // if still sending and the send command indicated more data @@ -196,6 +228,22 @@ Menu::MenuAction EditorConnection::run() SerialComs::write(EDITOR_VERB_TRANSMIT_VL_ACK); m_state = STATE_IDLE; break; + + // ------------------------------- + // Receive Mode from Duo + case STATE_LISTEN_MODE_VL: + showReceiveModeVL(); + receiveModeVL(); + break; + case STATE_LISTEN_MODE_VL_DONE: + // done transmitting + m_receiveBuffer.clear(); + SerialComs::write(EDITOR_VERB_LISTEN_VL_ACK); + m_state = STATE_IDLE; + break; + + // ------------------------------- + // Send Modes to PC Safer case STATE_PULL_EACH_MODE: // editor requested pull modes, send the modes m_receiveBuffer.clear(); @@ -242,6 +290,9 @@ Menu::MenuAction EditorConnection::run() // go idle m_state = STATE_IDLE; break; + + // ------------------------------- + // Receive Modes from PC Safer case STATE_PUSH_EACH_MODE: // editor requested to push modes, find out how many m_receiveBuffer.clear(); @@ -280,7 +331,6 @@ Menu::MenuAction EditorConnection::run() m_state = STATE_IDLE; break; } - return MENU_CONTINUE; } void EditorConnection::sendCurModeVL() @@ -293,7 +343,15 @@ void EditorConnection::sendCurModeVL() m_state = STATE_TRANSMIT_MODE_VL; } -// handlers for clicks +void EditorConnection::listenModeVL() +{ +#if VL_ENABLE_SENDER == 1 + // immediately load the mode and send it now + VLReceiver::beginReceiving(); +#endif + m_state = STATE_LISTEN_MODE_VL; +} + void EditorConnection::onShortClick() { // if the device has received any commands do not reset! @@ -313,12 +371,34 @@ void EditorConnection::onLongClick() leaveMenu(true); } +// handlers for clicks void EditorConnection::leaveMenu(bool doSave) { SerialComs::write(EDITOR_VERB_GOODBYE); Menu::leaveMenu(true); } +void EditorConnection::handleCommand() +{ + if (receiveMessage(EDITOR_VERB_PULL_MODES)) { + m_state = STATE_PULL_MODES; + } else if (receiveMessage(EDITOR_VERB_PUSH_MODES)) { + m_state = STATE_PUSH_MODES; + } else if (receiveMessage(EDITOR_VERB_DEMO_MODE)) { + m_state = STATE_DEMO_MODE; + } else if (receiveMessage(EDITOR_VERB_CLEAR_DEMO)) { + m_state = STATE_CLEAR_DEMO; + } else if (receiveMessage(EDITOR_VERB_PULL_EACH_MODE)) { + m_state = STATE_PULL_EACH_MODE; + } else if (receiveMessage(EDITOR_VERB_PUSH_EACH_MODE)) { + m_state = STATE_PUSH_EACH_MODE; + } else if (receiveMessage(EDITOR_VERB_TRANSMIT_VL)) { + sendCurModeVL(); + } else if (receiveMessage(EDITOR_VERB_LISTEN_VL)) { + listenModeVL(); + } +} + void EditorConnection::showEditor() { switch (m_state) { @@ -327,7 +407,9 @@ void EditorConnection::showEditor() Leds::blinkAll(250, 150, RGB_WHITE0); break; case STATE_IDLE: - m_previewMode.play(); + if (m_curStep == 0) { + m_previewMode.play(); + } break; default: // do nothing! @@ -372,7 +454,7 @@ void EditorConnection::sendCurMode() SerialComs::write(modeBuffer); } -bool EditorConnection::receiveModes() +bool EditorConnection::receiveBuffer(ByteStream &buffer) { // need at least the buffer size first uint32_t size = 0; @@ -392,13 +474,46 @@ bool EditorConnection::receiveModes() return false; } // create a new ByteStream that will hold the full buffer of data - ByteStream buf(m_receiveBuffer.rawSize()); + buffer.init(m_receiveBuffer.rawSize()); // then copy everything from the receive buffer into the rawdata // which is going to overwrite the crc/size/flags of the ByteStream - memcpy(buf.rawData(), m_receiveBuffer.data() + sizeof(size), + memcpy(buffer.rawData(), m_receiveBuffer.data() + sizeof(size), m_receiveBuffer.size() - sizeof(size)); // clear the receive buffer m_receiveBuffer.clear(); + if (!buffer.checkCRC()) { + return false; + } + return true; +} + +bool EditorConnection::receiveFirmwareChunk(ByteStream &buffer) +{ + // need at least the buffer size first + uint32_t size = 0; + // read the 140 byte chunk + SerialComs::readAmount(144, m_receiveBuffer); + // create a new ByteStream that will hold the full buffer of data + buffer.init(m_receiveBuffer.rawSize()); + // then copy everything from the receive buffer into the rawdata + // which is going to overwrite the crc/size/flags of the ByteStream + memcpy(buffer.rawData(), m_receiveBuffer.data() + sizeof(size), + m_receiveBuffer.size() - sizeof(size)); + // clear the receive buffer + m_receiveBuffer.clear(); + if (!buffer.checkCRC()) { + return false; + } + return true; +} + +bool EditorConnection::receiveModes() +{ + // create a new ByteStream that will hold the full buffer of data + ByteStream buf; + if (!receiveBuffer(buf)) { + return false; + } Modes::loadFromBuffer(buf); Modes::saveStorage(); return true; @@ -475,54 +590,94 @@ bool EditorConnection::receiveMode() } bool EditorConnection::receiveDemoMode() +{ + // create a new ByteStream that will hold the full buffer of data + ByteStream buf; + if (!receiveBuffer(buf)) { + return false; + } + // unserialize the mode into the demo mode + if (!m_previewMode.loadFromBuffer(buf)) { + // failure + } + return true; +} + +void EditorConnection::clearDemo() +{ + Colorset set(RGB_WHITE0); + PatternArgs args(1, 0, 0); + m_previewMode.setPattern(PATTERN_STROBE, LED_ALL, &args, &set); + m_previewMode.init(); +} + +void EditorConnection::receiveModeVL() +{ + // if reveiving new data set our last data time + if (VLReceiver::onNewData()) { + m_timeOutStartTime = Time::getCurtime(); + // if our last data was more than time out duration reset the recveiver + } else if (m_timeOutStartTime > 0 && (m_timeOutStartTime + MAX_TIMEOUT_DURATION) < Time::getCurtime()) { + VLReceiver::resetVLState(); + m_timeOutStartTime = 0; + return; + } + // check if the VLReceiver has a full packet available + if (!VLReceiver::dataReady()) { + // nothing available yet + return; + } + DEBUG_LOG("Mode ready to receive! Receiving..."); + // receive the VL mode into the current mode + if (!VLReceiver::receiveMode(&m_previewMode)) { + ERROR_LOG("Failed to receive mode"); + return; + } + DEBUG_LOGF("Success receiving mode: %u", m_previewMode.getPatternID()); + Modes::updateCurMode(&m_previewMode); + ByteStream modeBuffer; + m_previewMode.saveToBuffer(modeBuffer); + SerialComs::write(modeBuffer); + m_state = STATE_LISTEN_MODE_VL_DONE; +} + +void EditorConnection::showReceiveModeVL() +{ + if (VLReceiver::isReceiving()) { + // using uint32_t to avoid overflow, the result should be within 10 to 255 + //Leds::setAll(RGBColor(0, VLReceiver::percentReceived(), 0)); + Leds::setRange(LED_0, (LedPos)(VLReceiver::percentReceived() / 10), RGB_GREEN6); + } else { + Leds::setAll(RGB_WHITE0); + } +} + +bool EditorConnection::receiveModeIdx(uint8_t &idx) { // need at least the buffer size first - uint32_t size = 0; - if (m_receiveBuffer.size() < sizeof(size)) { + if (m_receiveBuffer.size() < sizeof(idx)) { // wait, not enough data available yet return false; } - // grab the size out of the start m_receiveBuffer.resetUnserializer(); - size = m_receiveBuffer.peek32(); - if (m_receiveBuffer.size() < (size + sizeof(size))) { - // don't unserialize yet, not ready - return false; - } // okay unserialize now, first unserialize the size - if (!m_receiveBuffer.unserialize32(&size)) { + if (!m_receiveBuffer.unserialize8(&idx)) { return false; } - // create a new ByteStream that will hold the full buffer of data - ByteStream buf(m_receiveBuffer.rawSize()); - // then copy everything from the receive buffer into the rawdata - // which is going to overwrite the crc/size/flags of the ByteStream - memcpy(buf.rawData(), m_receiveBuffer.data() + sizeof(size), - m_receiveBuffer.size() - sizeof(size)); - // clear the receive buffer - m_receiveBuffer.clear(); - // unserialize the mode into the demo mode - if (!m_previewMode.loadFromBuffer(buf)) { - // failure - } return true; } -void EditorConnection::handleCommand() +bool EditorConnection::receiveFirmwareSize(uint32_t &size) { - if (receiveMessage(EDITOR_VERB_PULL_MODES)) { - m_state = STATE_PULL_MODES; - } else if (receiveMessage(EDITOR_VERB_PUSH_MODES)) { - m_state = STATE_PUSH_MODES; - } else if (receiveMessage(EDITOR_VERB_DEMO_MODE)) { - m_state = STATE_DEMO_MODE; - } else if (receiveMessage(EDITOR_VERB_CLEAR_DEMO)) { - m_state = STATE_CLEAR_DEMO; - } else if (receiveMessage(EDITOR_VERB_PULL_EACH_MODE)) { - m_state = STATE_PULL_EACH_MODE; - } else if (receiveMessage(EDITOR_VERB_PUSH_EACH_MODE)) { - m_state = STATE_PUSH_EACH_MODE; - } else if (receiveMessage(EDITOR_VERB_TRANSMIT_VL)) { - sendCurModeVL(); + // need at least the buffer size first + if (m_receiveBuffer.size() < sizeof(size)) { + // wait, not enough data available yet + return false; + } + m_receiveBuffer.resetUnserializer(); + // okay unserialize now, first unserialize the size + if (!m_receiveBuffer.unserialize32(&size)) { + return false; } + return true; } diff --git a/VortexEngine/src/Menus/MenuList/EditorConnection.h b/VortexEngine/src/Menus/MenuList/EditorConnection.h index a8f5a729ff..443ff4050c 100644 --- a/VortexEngine/src/Menus/MenuList/EditorConnection.h +++ b/VortexEngine/src/Menus/MenuList/EditorConnection.h @@ -17,6 +17,7 @@ class EditorConnection : public Menu // broadcast the current preview mode over VL void sendCurModeVL(); + void listenModeVL(); // handlers for clicks void onShortClick() override; @@ -26,18 +27,25 @@ class EditorConnection : public Menu void leaveMenu(bool doSave = false) override; private: + void handleCommand(); void showEditor(); void receiveData(); + void handleState(); void sendModes(); void sendModeCount(); void sendCurMode(); + bool receiveBuffer(ByteStream &buffer); + bool receiveFirmwareChunk(ByteStream &buffer); bool receiveModes(); bool receiveModeCount(); bool receiveMode(); bool receiveDemoMode(); - void handleCommand(); bool receiveMessage(const char *message); void clearDemo(); + void receiveModeVL(); + void showReceiveModeVL(); + bool receiveModeIdx(uint8_t &idx); + bool receiveFirmwareSize(uint32_t &idx); enum EditorConnectionState { // the editor is not connected @@ -71,6 +79,10 @@ class EditorConnection : public Menu STATE_TRANSMIT_MODE_VL, STATE_TRANSMIT_MODE_VL_DONE, + // receive a mode over VL + STATE_LISTEN_MODE_VL, + STATE_LISTEN_MODE_VL_DONE, + // editor pulls the modes from device (safer version) STATE_PULL_EACH_MODE, STATE_PULL_EACH_MODE_COUNT, @@ -84,18 +96,50 @@ class EditorConnection : public Menu STATE_PUSH_EACH_MODE_RECEIVE, STATE_PUSH_EACH_MODE_WAIT, STATE_PUSH_EACH_MODE_DONE, + + // pull the header from the chromalinked duo + STATE_PULL_HEADER_CHROMALINK, + + // pull a mode from the chromalinked duo + STATE_PULL_MODE_CHROMALINK, + STATE_PULL_MODE_CHROMALINK_SEND, + + // push the header to the chromalinked duo + STATE_PUSH_HEADER_CHROMALINK, + STATE_PUSH_HEADER_CHROMALINK_RECEIVE, + + // push a mode to the chromalinked duo + STATE_PUSH_MODE_CHROMALINK, + STATE_PUSH_MODE_CHROMALINK_RECEIVE_IDX, + STATE_PUSH_MODE_CHROMALINK_RECEIVE, + + // flash the firmware of the chromalinked duo + STATE_CHROMALINK_FLASH_FIRMWARE, + STATE_CHROMALINK_FLASH_FIRMWARE_RECEIVE_SIZE, + STATE_CHROMALINK_FLASH_FIRMWARE_RECEIVE, }; // state of the editor EditorConnectionState m_state; // the data that is received ByteStream m_receiveBuffer; + // receiver timeout + uint32_t m_timeOutStartTime; + // target chroma mode index for read/write + uint8_t m_chromaModeIdx; // Whether at least one command has been received yet bool m_allowReset; // the mode index to return to after iterating the modes to send them uint8_t m_previousModeIndex; // the number of modes that should be received uint8_t m_numModesToReceive; + + // current step of transfer + uint32_t m_curStep; + // firmware size for flashing duo + uint32_t m_firmwareSize; + // how much firmware written so far + uint32_t m_firmwareOffset; }; #endif diff --git a/VortexEngine/src/Menus/MenuList/ModeSharing.cpp b/VortexEngine/src/Menus/MenuList/ModeSharing.cpp index e3391c1df2..62e2212192 100644 --- a/VortexEngine/src/Menus/MenuList/ModeSharing.cpp +++ b/VortexEngine/src/Menus/MenuList/ModeSharing.cpp @@ -4,8 +4,9 @@ #include "../../Serial/Serial.h" #include "../../Time/TimeControl.h" #include "../../Time/Timings.h" -#include "../../Wireless/IRReceiver.h" +#include "../../Wireless/VLReceiver.h" #include "../../Wireless/VLSender.h" +#include "../../Wireless/IRReceiver.h" #include "../../Wireless/IRSender.h" #include "../../Buttons/Button.h" #include "../../Modes/Modes.h" @@ -15,8 +16,10 @@ ModeSharing::ModeSharing(const RGBColor &col, bool advanced) : Menu(col, advanced), - m_sharingMode(ModeShareState::SHARE_RECEIVE), - m_timeOutStartTime(0) + m_sharingMode(ModeShareState::SHARE_RECEIVE_IR), + m_timeOutStartTime(0), + m_lastSendTime(0), + m_shouldEndSend(false) { } @@ -31,10 +34,14 @@ bool ModeSharing::init() } // skip led selection m_ledSelected = true; - // start on receive because it's the more responsive of the two - // the odds of opening receive and then accidentally receiving - // a mode that is being broadcast nearby is completely unlikely - beginReceivingIR(); + if (m_advanced) { + // start on receive because it's the more responsive of the two + // the odds of opening receive and then accidentally receiving + // a mode that is being broadcast nearby is completely unlikely + beginReceivingVL(); + } else { + beginReceivingIR(); + } DEBUG_LOG("Entering Mode Sharing"); return true; } @@ -46,11 +53,11 @@ Menu::MenuAction ModeSharing::run() return result; } switch (m_sharingMode) { - case ModeShareState::SHARE_SEND_IR: - // render the 'send mode' lights - showSendModeIR(); - // continue sending any data as long as there is more to send - continueSendingIR(); + case ModeShareState::SHARE_RECEIVE_VL: + // render the 'receive mode' lights + showReceiveModeVL(); + // load any modes that are received + receiveModeVL(); break; case ModeShareState::SHARE_SEND_VL: // render the 'send mode' lights @@ -58,12 +65,18 @@ Menu::MenuAction ModeSharing::run() // continue sending any data as long as there is more to send continueSendingVL(); break; - case ModeShareState::SHARE_RECEIVE: + case ModeShareState::SHARE_RECEIVE_IR: // render the 'receive mode' lights - showReceiveMode(); + showReceiveModeIR(); // load any modes that are received receiveModeIR(); break; + case ModeShareState::SHARE_SEND_IR: + // render the 'send mode' lights + showSendModeIR(); + // continue sending any data as long as there is more to send + continueSendingIR(); + break; } return MENU_CONTINUE; } @@ -72,11 +85,22 @@ Menu::MenuAction ModeSharing::run() void ModeSharing::onShortClick() { switch (m_sharingMode) { - case ModeShareState::SHARE_RECEIVE: + case ModeShareState::SHARE_RECEIVE_VL: // click while on receive -> end receive, start sending - IRReceiver::endReceiving(); - beginSendingIR(); - DEBUG_LOG("Switched to send mode"); + VLReceiver::endReceiving(); + beginSendingVL(); + DEBUG_LOG("Switched to send VL"); + break; + case ModeShareState::SHARE_RECEIVE_IR: + if (!IRSender::isSending()) { + beginSendingIR(); + DEBUG_LOG("Switched to send IR"); + } else { + m_shouldEndSend = true; + } + break; + case ModeShareState::SHARE_SEND_IR: + m_shouldEndSend = true; break; default: break; @@ -86,25 +110,24 @@ void ModeSharing::onShortClick() void ModeSharing::onLongClick() { - Modes::updateCurMode(&m_previewMode); - leaveMenu(true); + leaveMenu(); } -void ModeSharing::beginSendingVL() +void ModeSharing::switchVLIR() { - // if the sender is sending then cannot start again - if (VLSender::isSending()) { - ERROR_LOG("Cannot begin sending, sender is busy"); - return; - } - m_sharingMode = ModeShareState::SHARE_SEND_VL; - // initialize it with the current mode data - VLSender::loadMode(Modes::curMode()); - // send the first chunk of data, leave if we're done - if (!VLSender::send()) { - // when send has completed, stores time that last action was completed to calculate interval between sends + switch (m_sharingMode) { + case ModeShareState::SHARE_RECEIVE_VL: + VLReceiver::endReceiving(); beginReceivingIR(); + break; + case ModeShareState::SHARE_RECEIVE_IR: + IRReceiver::endReceiving(); + beginReceivingVL(); + break; + default: + break; } + Leds::clearAll(); } void ModeSharing::beginSendingIR() @@ -115,47 +138,47 @@ void ModeSharing::beginSendingIR() return; } m_sharingMode = ModeShareState::SHARE_SEND_IR; + Leds::clearAll(); + Leds::update(); // initialize it with the current mode data IRSender::loadMode(Modes::curMode()); // send the first chunk of data, leave if we're done if (!IRSender::send()) { - // when send has completed, stores time that last action was completed to calculate interval between sends - beginReceivingIR(); - } -} - -void ModeSharing::continueSendingVL() -{ - // if the sender isn't sending then nothing to do - if (!VLSender::isSending()) { - return; - } - if (!VLSender::send()) { - // when send has completed, stores time that last action was completed to calculate interval between sends - beginReceivingIR(); + // just set the last time and wait + m_lastSendTime = Time::getCurtime(); } + DEBUG_LOG("Switched to sending IR"); } void ModeSharing::continueSendingIR() { // if the sender isn't sending then nothing to do if (!IRSender::isSending()) { + if (m_lastSendTime && m_lastSendTime < (Time::getCurtime() + MS_TO_TICKS(350))) { + if (m_shouldEndSend) { + beginReceivingIR(); + m_shouldEndSend = false; + } else { + beginSendingIR(); + } + } return; } if (!IRSender::send()) { - // when send has completed, stores time that last action was completed to calculate interval between sends - beginReceivingIR(); + // just set the last time and wait + m_lastSendTime = Time::getCurtime(); } } void ModeSharing::beginReceivingIR() { - m_sharingMode = ModeShareState::SHARE_RECEIVE; + m_sharingMode = ModeShareState::SHARE_RECEIVE_IR; IRReceiver::beginReceiving(); + DEBUG_LOG("Switched to receiving IR"); } void ModeSharing::receiveModeIR() -{ + { // if reveiving new data set our last data time if (IRReceiver::onNewData()) { m_timeOutStartTime = Time::getCurtime(); @@ -177,11 +200,74 @@ void ModeSharing::receiveModeIR() return; } DEBUG_LOGF("Success receiving mode: %u", m_previewMode.getPatternID()); - if (!m_advanced) { - Modes::updateCurMode(&m_previewMode); - // leave menu and save settings, even if the mode was the same whatever - leaveMenu(true); + Modes::updateCurMode(&m_previewMode); + // leave menu and save settings, even if the mode was the same whatever + leaveMenu(true); +} + +void ModeSharing::beginSendingVL() +{ + // if the sender is sending then cannot start again + if (VLSender::isSending()) { + ERROR_LOG("Cannot begin sending, sender is busy"); + return; + } + m_sharingMode = ModeShareState::SHARE_SEND_VL; + // initialize it with the current mode data + VLSender::loadMode(Modes::curMode()); + // send the first chunk of data, leave if we're done + if (!VLSender::send()) { + // when send has completed, stores time that last action was completed to calculate interval between sends + beginReceivingVL(); + } + DEBUG_LOG("Switched to sending VL"); +} + +void ModeSharing::continueSendingVL() +{ + // if the sender isn't sending then nothing to do + if (!VLSender::isSending()) { + return; + } + if (!VLSender::send()) { + // when send has completed, stores time that last action was completed to calculate interval between sends + beginReceivingVL(); + } +} + +void ModeSharing::beginReceivingVL() +{ + m_sharingMode = ModeShareState::SHARE_RECEIVE_VL; + VLReceiver::beginReceiving(); + DEBUG_LOG("Switched to receiving VL"); +} + +void ModeSharing::receiveModeVL() +{ + // if reveiving new data set our last data time + if (VLReceiver::onNewData()) { + m_timeOutStartTime = Time::getCurtime(); + // if our last data was more than time out duration reset the recveiver + } else if (m_timeOutStartTime > 0 && (m_timeOutStartTime + MAX_TIMEOUT_DURATION) < Time::getCurtime()) { + VLReceiver::resetVLState(); + m_timeOutStartTime = 0; + return; } + // check if the VLReceiver has a full packet available + if (!VLReceiver::dataReady()) { + // nothing available yet + return; + } + DEBUG_LOG("Mode ready to receive! Receiving..."); + // receive the VL mode into the current mode + if (!VLReceiver::receiveMode(&m_previewMode)) { + ERROR_LOG("Failed to receive mode"); + return; + } + DEBUG_LOGF("Success receiving mode: %u", m_previewMode.getPatternID()); + Modes::updateCurMode(&m_previewMode); + // leave menu and save settings, even if the mode was the same whatever + leaveMenu(true); } void ModeSharing::showSendModeVL() @@ -193,19 +279,28 @@ void ModeSharing::showSendModeVL() void ModeSharing::showSendModeIR() { // show a dim color when not sending - Leds::clearAll(); + Leds::setAll(RGB_CYAN5); + Leds::setAllEvens(RGB_CYAN0); } -void ModeSharing::showReceiveMode() +void ModeSharing::showReceiveModeVL() { - if (IRReceiver::isReceiving()) { + if (VLReceiver::isReceiving()) { // using uint32_t to avoid overflow, the result should be within 10 to 255 - Leds::setAll(RGBColor(0, IRReceiver::percentReceived(), 0)); + Leds::clearAll(); + Leds::setRange(LED_FIRST, (LedPos)(VLReceiver::percentReceived() / 16), RGBColor(0, 1, 0)); } else { - if (m_advanced) { - m_previewMode.play(); - } else { - Leds::setAll(RGB_WHITE0); - } + Leds::setAll(0x010101); + } +} + +void ModeSharing::showReceiveModeIR() +{ + if (VLReceiver::isReceiving()) { + // using uint32_t to avoid overflow, the result should be within 10 to 255 + Leds::clearAll(); + Leds::setRange(LED_FIRST, (LedPos)(IRReceiver::percentReceived() / 16), RGBColor(0, 255, 0)); + } else { + Leds::setAll(RGB_WHITE0); } } diff --git a/VortexEngine/src/Menus/MenuList/ModeSharing.h b/VortexEngine/src/Menus/MenuList/ModeSharing.h index dc5adf2357..aae4198d81 100644 --- a/VortexEngine/src/Menus/MenuList/ModeSharing.h +++ b/VortexEngine/src/Menus/MenuList/ModeSharing.h @@ -18,26 +18,37 @@ class ModeSharing : public Menu private: void beginSendingVL(); - void beginSendingIR(); void continueSendingVL(); + void beginReceivingVL(); + void receiveModeVL(); + + void beginSendingIR(); void continueSendingIR(); void beginReceivingIR(); void receiveModeIR(); void showSendModeVL(); void showSendModeIR(); - void showReceiveMode(); + void showReceiveModeVL(); + void showReceiveModeIR(); + + void switchVLIR(); enum class ModeShareState { - SHARE_SEND_IR, // send mode over ir - SHARE_SEND_VL, // send mode over vl - SHARE_RECEIVE, // receive mode + SHARE_RECEIVE_VL, + SHARE_SEND_VL, + SHARE_RECEIVE_IR, + SHARE_SEND_IR, }; ModeShareState m_sharingMode; // the start time when checking for timing out uint32_t m_timeOutStartTime; + uint32_t m_lastSendTime; + + // whether to end the next send and go back to receive + bool m_shouldEndSend; }; #endif diff --git a/VortexEngine/src/Modes/DefaultModes.cpp b/VortexEngine/src/Modes/DefaultModes.cpp index a0f4be8b7c..78b3d2416e 100644 --- a/VortexEngine/src/Modes/DefaultModes.cpp +++ b/VortexEngine/src/Modes/DefaultModes.cpp @@ -122,7 +122,31 @@ const default_mode_entry default_modes[MAX_MODES] = { RGB_GREEN, RGB_BLUE } + }, + { + PATTERN_STROBE, 2, { + RGB_RED, + RGB_GREEN, + } + }, + { + PATTERN_DRIP, 4, { + RGB_RED, + RGB_GREEN, + RGB_BLUE, + RGB_YELLOW + } + }, + { + PATTERN_DASHCYCLE, 3, { + RGB_RED, + RGB_GREEN, + RGB_BLUE + } } + + + }; // exposed size of the default modes array diff --git a/VortexEngine/src/Patterns/Multi/FillPattern.cpp b/VortexEngine/src/Patterns/Multi/FillPattern.cpp index 87e034e4c1..50a88eefa3 100644 --- a/VortexEngine/src/Patterns/Multi/FillPattern.cpp +++ b/VortexEngine/src/Patterns/Multi/FillPattern.cpp @@ -28,13 +28,13 @@ void FillPattern::init() void FillPattern::blinkOn() { - Leds::setPairs(PAIR_FIRST, (Pair)m_progress, m_colorset.peekNext()); - Leds::setPairs((Pair)m_progress, PAIR_COUNT, m_colorset.cur()); + Leds::setRange(LED_FIRST, (LedPos)m_progress, m_colorset.peekNext()); + Leds::setRange((LedPos)m_progress, LED_LAST, m_colorset.cur()); } void FillPattern::poststep() { - m_progress = (m_progress + 1) % PAIR_COUNT; + m_progress = (m_progress + 1) % LED_COUNT; if (m_progress == 0) { m_colorset.getNext(); } diff --git a/VortexEngine/src/Patterns/Multi/HueShiftPattern.cpp b/VortexEngine/src/Patterns/Multi/HueShiftPattern.cpp index d86a35810f..0a39133551 100644 --- a/VortexEngine/src/Patterns/Multi/HueShiftPattern.cpp +++ b/VortexEngine/src/Patterns/Multi/HueShiftPattern.cpp @@ -75,9 +75,17 @@ void HueShiftPattern::play() m_cur.hue += sign; } HSVColor showColor = HSVColor(m_cur.hue, 255, 255); - // set the target led with the current HSV color - for (LedPos pos = LED_FIRST; pos < LED_COUNT; ++pos) { - Leds::setIndex(pos, hsv_to_rgb_generic(showColor)); - showColor.hue = (showColor.hue + 5) % 256; + + // variable amount to shift, more LEDs should have smaller shifts + uint8_t shiftAmount = 108 / LED_COUNT; + // if you increment color with each led index there's a sharp contrast between the first and last led + // instead this creates a perfectly looped gradient between the first and last led which is better + for (LedPos pos = LED_FIRST; pos < (LED_COUNT / 2) + 1; ++pos) { + if (((LED_COUNT / 2) + pos) != LED_COUNT) { + // set the target led with the current HSV color + Leds::setIndex((LedPos)((LED_COUNT / 2) + pos), hsv_to_rgb_generic(showColor)); + } + Leds::setIndex((LedPos)((LED_COUNT / 2) - pos), hsv_to_rgb_generic(showColor)); + showColor.hue = (showColor.hue + shiftAmount) % 256; } } diff --git a/VortexEngine/src/Patterns/Multi/PulsishPattern.cpp b/VortexEngine/src/Patterns/Multi/PulsishPattern.cpp index 9c9e9b49b9..93c5fc6da6 100644 --- a/VortexEngine/src/Patterns/Multi/PulsishPattern.cpp +++ b/VortexEngine/src/Patterns/Multi/PulsishPattern.cpp @@ -55,16 +55,16 @@ void PulsishPattern::play() { // when the step timer triggers if (m_stepTimer.alarm() == 0) { - m_progress = (m_progress + 1) % PAIR_COUNT; + m_progress = (m_progress + 1) % LED_COUNT; } switch (m_blinkTimer.alarm()) { case -1: // just return return; case 0: // turn on the leds - for (Pair pair = PAIR_FIRST; pair < PAIR_COUNT; ++pair) { - if (pair != m_progress) { - Leds::setPair(pair, m_colorset.cur()); + for (LedPos pos = LED_FIRST; pos < LED_COUNT; ++pos) { + if (pos != m_progress) { + Leds::setIndex(pos, m_colorset.cur()); } } m_colorset.skip(); @@ -73,9 +73,9 @@ void PulsishPattern::play() } break; case 1: - for (Pair pair = PAIR_FIRST; pair < PAIR_COUNT; ++pair) { - if (pair != m_progress) { - Leds::clearPair(pair); + for (LedPos pos = LED_FIRST; pos < LED_COUNT; ++pos) { + if (pos != m_progress) { + Leds::clearIndex(pos); } } break; @@ -85,10 +85,10 @@ void PulsishPattern::play() case -1: // just return return; case 0: // turn on the leds - Leds::setPair((Pair)m_progress, m_colorset.get(0)); + Leds::setIndex((LedPos)m_progress, m_colorset.get(0)); break; case 1: - Leds::clearPair((Pair)m_progress); + Leds::clearIndex((LedPos)m_progress); break; } } diff --git a/VortexEngine/src/Patterns/Multi/SnowballPattern.cpp b/VortexEngine/src/Patterns/Multi/SnowballPattern.cpp index 32d7121c17..92667b4ca2 100644 --- a/VortexEngine/src/Patterns/Multi/SnowballPattern.cpp +++ b/VortexEngine/src/Patterns/Multi/SnowballPattern.cpp @@ -2,7 +2,7 @@ #include "../../Leds/Leds.h" -#define WORM_SIZE 6 +#define WORM_SIZE LED_COUNT / 3 SnowballPattern::SnowballPattern(const PatternArgs &args) : BlinkStepPattern(args), diff --git a/VortexEngine/src/Patterns/Multi/SparkleTracePattern.cpp b/VortexEngine/src/Patterns/Multi/SparkleTracePattern.cpp index 2221850d58..f2a778724b 100644 --- a/VortexEngine/src/Patterns/Multi/SparkleTracePattern.cpp +++ b/VortexEngine/src/Patterns/Multi/SparkleTracePattern.cpp @@ -21,10 +21,17 @@ void SparkleTracePattern::blinkOn() Leds::setAll(m_colorset.get(0)); } +void SparkleTracePattern::blinkOff() +{ + //this empty overriden function must be here to prevent the base + //blinkOff function from causing the ribbon in the blinkOn function + //to strobe instead +} + void SparkleTracePattern::poststep() { - for (uint8_t dot = 0; dot < 4; ++dot) { - Leds::setPair((Pair)m_randCtx.next8(PAIR_FIRST, PAIR_LAST), m_colorset.cur()); + for (uint8_t dot = 0; dot < LED_COUNT / 6; ++dot) { + Leds::setIndex((LedPos)m_randCtx.next8(LED_FIRST, LED_LAST), m_colorset.cur()); } m_colorset.skip(); if (m_colorset.curIndex() == 0) { diff --git a/VortexEngine/src/Patterns/Multi/SparkleTracePattern.h b/VortexEngine/src/Patterns/Multi/SparkleTracePattern.h index ef03a71827..13f8804021 100644 --- a/VortexEngine/src/Patterns/Multi/SparkleTracePattern.h +++ b/VortexEngine/src/Patterns/Multi/SparkleTracePattern.h @@ -13,6 +13,7 @@ class SparkleTracePattern : public BlinkStepPattern protected: virtual void blinkOn() override; + virtual void blinkOff() override; virtual void poststep() override; Random m_randCtx; diff --git a/VortexEngine/src/Patterns/Multi/TheaterChasePattern.cpp b/VortexEngine/src/Patterns/Multi/TheaterChasePattern.cpp index fbd527c7db..2398365301 100644 --- a/VortexEngine/src/Patterns/Multi/TheaterChasePattern.cpp +++ b/VortexEngine/src/Patterns/Multi/TheaterChasePattern.cpp @@ -2,7 +2,7 @@ #include "../../Leds/Leds.h" -#define THEATER_CHASE_STEPS 10 +#define THEATER_CHASE_STEPS (LED_COUNT / 2) TheaterChasePattern::TheaterChasePattern(const PatternArgs &args) : BlinkStepPattern(args), @@ -21,7 +21,7 @@ void TheaterChasePattern::init() { BlinkStepPattern::init(); // starts on odd evens - m_ledPositions = MAP_PAIR_ODD_EVENS; + m_ledPositions = MAP_OPPOSITES_1; m_stepCounter = 0; } @@ -32,12 +32,14 @@ void TheaterChasePattern::blinkOn() void TheaterChasePattern::poststep() { - // the first 5 steps are odd evens/odds alternating each step - if (m_stepCounter < 5) { - m_ledPositions = (m_stepCounter % 2) ? MAP_PAIR_ODD_ODDS : MAP_PAIR_ODD_EVENS; - } else { - // the end 5 steps are even evens/odds alternating each step - m_ledPositions = (m_stepCounter % 2) ? MAP_PAIR_EVEN_ODDS : MAP_PAIR_EVEN_EVENS; + if (m_stepCounter == 0) { + m_ledPositions = MAP_OPPOSITES_1; + } + if (m_stepCounter == 1) { + m_ledPositions = MAP_OPPOSITES_2; + } + if (m_stepCounter == 2) { + m_ledPositions = MAP_OPPOSITES_3; } // increment step counter m_stepCounter = (m_stepCounter + 1) % THEATER_CHASE_STEPS; diff --git a/VortexEngine/src/Patterns/Multi/VortexPattern.cpp b/VortexEngine/src/Patterns/Multi/VortexPattern.cpp index b879687b11..deedf0304b 100644 --- a/VortexEngine/src/Patterns/Multi/VortexPattern.cpp +++ b/VortexEngine/src/Patterns/Multi/VortexPattern.cpp @@ -33,14 +33,16 @@ void VortexPattern::init() void VortexPattern::blinkOn() { // Sets an LED at opposite ends of the strip and progresses towards the center - Leds::setIndex((LedPos)m_progress, m_colorset.peekNext()); - Leds::setIndex((LedPos)(LED_LAST - m_progress), m_colorset.peekNext()); + if (MIDDLE_POINT + m_progress != LED_COUNT) { + Leds::setIndex((LedPos)(MIDDLE_POINT + m_progress), m_colorset.cur()); + } + Leds::setIndex((LedPos)(MIDDLE_POINT - m_progress), m_colorset.cur()); } void VortexPattern::poststep() { // step till the middle point - m_progress = (m_progress + 1) % MIDDLE_POINT; + m_progress = (m_progress + 1) % (MIDDLE_POINT + 1); // each cycle progress to the next color if (m_progress == 0) { m_colorset.getNext(); diff --git a/VortexEngine/src/Patterns/Multi/VortexWipePattern.cpp b/VortexEngine/src/Patterns/Multi/VortexWipePattern.cpp index 1a2b19b185..23d92e7e07 100644 --- a/VortexEngine/src/Patterns/Multi/VortexWipePattern.cpp +++ b/VortexEngine/src/Patterns/Multi/VortexWipePattern.cpp @@ -5,19 +5,8 @@ #include "../../Leds/Leds.h" #include "../../Log/Log.h" -const LedPos VortexWipePattern::ledStepPositions[] = { - LED_9, - LED_7, - LED_5, - LED_3, - LED_1, - - LED_0, - LED_2, - LED_4, - LED_6, - LED_8 -}; +// add 1 to prevent the middle point from being led 0 +#define MIDDLE_POINT ((LED_COUNT + 1) / 2) VortexWipePattern::VortexWipePattern(const PatternArgs &args) : BlinkStepPattern(args), @@ -43,17 +32,20 @@ void VortexWipePattern::init() void VortexWipePattern::blinkOn() { - for (int index = 0; index < m_progress; ++index) { - Leds::setIndex(ledStepPositions[index], m_colorset.peekNext()); + Leds::setAll(m_colorset.cur()); + if (!m_progress) { + // none } - for (int index = m_progress; index < LED_COUNT; ++index) { - Leds::setIndex(ledStepPositions[index], m_colorset.cur()); + if (m_progress) { + Leds::setRange((LedPos)(MIDDLE_POINT - (m_progress - 1)), (LedPos)(MIDDLE_POINT + (m_progress - 1)), m_colorset.peekNext()); } } void VortexWipePattern::poststep() { - m_progress = (m_progress + 1) % LED_COUNT; + // step till the middle point + m_progress = (m_progress + 1) % (MIDDLE_POINT + 1); + // each cycle progress to the next color if (m_progress == 0) { m_colorset.getNext(); } diff --git a/VortexEngine/src/Patterns/Multi/WarpPattern.cpp b/VortexEngine/src/Patterns/Multi/WarpPattern.cpp index 24770e4328..318250b313 100644 --- a/VortexEngine/src/Patterns/Multi/WarpPattern.cpp +++ b/VortexEngine/src/Patterns/Multi/WarpPattern.cpp @@ -30,12 +30,12 @@ void WarpPattern::init() void WarpPattern::blinkOn() { Leds::setAll(m_colorset.cur()); - Leds::setPair((Pair)m_progress, m_colorset.peekNext()); + Leds::setIndex((LedPos)m_progress, m_colorset.peekNext()); } void WarpPattern::poststep() { - m_progress = (m_progress + 1) % PAIR_COUNT; + m_progress = (m_progress + 1) % LED_COUNT; if (m_progress == 0) { m_colorset.getNext(); } diff --git a/VortexEngine/src/Patterns/Multi/WarpWormPattern.cpp b/VortexEngine/src/Patterns/Multi/WarpWormPattern.cpp index b6311ad339..d50190ddd8 100644 --- a/VortexEngine/src/Patterns/Multi/WarpWormPattern.cpp +++ b/VortexEngine/src/Patterns/Multi/WarpWormPattern.cpp @@ -29,7 +29,7 @@ void WarpWormPattern::init() void WarpWormPattern::blinkOn() { - int wormSize = 6; + int wormSize = LED_COUNT / 3; Leds::setAll(m_colorset.get(0)); for (int body = 0; body < wormSize; ++body) { if (body + m_progress < LED_COUNT) { diff --git a/VortexEngine/src/Patterns/Multi/ZigzagPattern.cpp b/VortexEngine/src/Patterns/Multi/ZigzagPattern.cpp index 02062917eb..a5cb0d80b3 100644 --- a/VortexEngine/src/Patterns/Multi/ZigzagPattern.cpp +++ b/VortexEngine/src/Patterns/Multi/ZigzagPattern.cpp @@ -8,17 +8,19 @@ // The lights runs across evens, then back across odds. // Index this array with m_step in order to get correct LedPos const LedPos ZigzagPattern::ledStepPositions[] = { - LED_1, + LED_0, LED_3, - LED_5, - LED_7, - LED_9, - - LED_8, - LED_6, + LED_1, LED_4, LED_2, + + LED_5, + LED_3, LED_0, + LED_4, + LED_1, + LED_5, + LED_2 }; // There just happens to be LED_COUNT steps in the pattern diff --git a/VortexEngine/src/Patterns/Patterns.h b/VortexEngine/src/Patterns/Patterns.h index 65f3b90bb7..e6bbf409dc 100644 --- a/VortexEngine/src/Patterns/Patterns.h +++ b/VortexEngine/src/Patterns/Patterns.h @@ -97,6 +97,7 @@ enum PatternID : int8_t INTERNAL_PATTERNS_END, // <<< DON'T USE OR TOUCH THIS ONE PATTERN_MULTI_LAST = (INTERNAL_PATTERNS_END - 1), PATTERN_MULTI_COUNT = (PATTERN_MULTI_LAST - PATTERN_MULTI_FIRST) + 1, + PATTERN_LAST = PATTERN_MULTI_LAST, PATTERN_COUNT = (PATTERN_LAST - PATTERN_FIRST) + 1, // total number of patterns }; diff --git a/VortexEngine/src/Serial/Serial.cpp b/VortexEngine/src/Serial/Serial.cpp index 5079e80455..efd96fc9a6 100644 --- a/VortexEngine/src/Serial/Serial.cpp +++ b/VortexEngine/src/Serial/Serial.cpp @@ -3,6 +3,8 @@ #include "../Serial/ByteStream.h" #include "../Time/TimeControl.h" #include "../Time/Timings.h" +#include "../Modes/Modes.h" +#include "../Menus/Menus.h" #include "../Log/Log.h" #include "../VortexEngine.h" @@ -12,14 +14,19 @@ #include #endif +#ifdef VORTEX_EMBEDDED +#include +#include "soc/usb_serial_jtag_reg.h" +#include "HWCDC.h" +#endif + bool SerialComs::m_serialConnected = false; uint32_t SerialComs::m_lastCheck = 0; +uint32_t SerialComs::m_lastConnected = 0; // init serial bool SerialComs::init() { - // Try connecting serial ? - //checkSerial(); return true; } @@ -29,9 +36,45 @@ void SerialComs::cleanup() bool SerialComs::isConnected() { +#ifdef VORTEX_EMBEDDED + if (!isConnectedReal()) { + m_serialConnected = false; + return false; + } +#endif return m_serialConnected; } +bool SerialComs::isConnectedReal() +{ + static bool lastState = true; + static unsigned long lastChangeTime = 0; + +#ifdef VORTEX_EMBEDDED + bool currentState = HWCDCSerial.isConnected(); +#else + bool currentState = true; +#endif + + unsigned long currentTime = Time::getCurtime(); + if (!currentState) { + // Check if the state has been false for at least 1 millisecond + if (lastChangeTime && (currentTime - lastChangeTime) < 300) { + return lastState; // State hasn't been false long enough + } + if (currentState != lastState) { + // Update the last state and change time + lastChangeTime = currentTime; + lastState = currentState; + return lastState; + } + } else { + lastState = currentState; + lastChangeTime = currentTime; + } + return currentState; +} + // check for any serial connection or messages bool SerialComs::checkSerial() { @@ -53,18 +96,19 @@ bool SerialComs::checkSerial() } Vortex::vcallbacks()->serialBegin(SERIAL_BAUD_RATE); #else + // Begin serial communications (turns out this is actually a NO-OP in trinket source) + Serial.begin(SERIAL_BAUD_RATE); // This will check if the serial communication is open - if (!Serial.available()) { + if (!Serial && !Serial.available()) { // serial is not connected return false; } - // Begin serial communications - Serial.begin(SERIAL_BAUD_RATE); #endif #endif // serial is now connected m_serialConnected = true; - return true; + // rely on the low level 'real' connection now + return isConnectedReal(); } void SerialComs::write(const char *msg, ...) @@ -134,6 +178,26 @@ void SerialComs::read(ByteStream &byteStream) #endif } +void SerialComs::readAmount(uint32_t amount, ByteStream &byteStream) +{ +#if VORTEX_SLIM == 0 + if (!isConnected()) { + return; + } + do { + uint8_t byte = 0; +#ifdef VORTEX_LIB + if (!Vortex::vcallbacks()->serialRead((char *)&byte, 1)) { + return; + } +#else + byte = Serial.read(); +#endif + byteStream.serialize8(byte); + } while (--amount > 0); +#endif +} + bool SerialComs::dataReady() { #if VORTEX_SLIM == 0 diff --git a/VortexEngine/src/Serial/Serial.h b/VortexEngine/src/Serial/Serial.h index 0121b5bbb0..1ae2fe9d06 100644 --- a/VortexEngine/src/Serial/Serial.h +++ b/VortexEngine/src/Serial/Serial.h @@ -17,6 +17,9 @@ class SerialComs // whether serial is initialized static bool isConnected(); + // why do I need this + static bool isConnectedReal(); + // check for any serial connection or messages static bool checkSerial(); @@ -29,6 +32,9 @@ class SerialComs // read a message from serial static void read(ByteStream &byteStream); + // read a specific chunk size + static void readAmount(uint32_t amount, ByteStream &byteStream); + // data in the socket ready to read static bool dataReady(); @@ -36,6 +42,7 @@ class SerialComs // whether serial communications are initialized static bool m_serialConnected; static uint32_t m_lastCheck; + static uint32_t m_lastConnected; }; #endif diff --git a/VortexEngine/src/Storage/Storage.cpp b/VortexEngine/src/Storage/Storage.cpp index 357cc6bd3c..d97f08611c 100644 --- a/VortexEngine/src/Storage/Storage.cpp +++ b/VortexEngine/src/Storage/Storage.cpp @@ -12,10 +12,13 @@ #include "../VortexLib/VortexLib.h" #endif -#ifndef VORTEX_EMBEDDED +#ifdef VORTEX_EMBEDDED +#include "../Leds/Leds.h" +#include +#else // VORTEX_EMBEDDED #ifdef _WIN32 #include -#else +#else // _WIN32 #include #endif #endif @@ -30,6 +33,7 @@ std::string Storage::m_storageFilename; #endif uint32_t Storage::m_lastSaveSize = 0; +uint8_t Storage::m_storagePage = 0; Storage::Storage() { @@ -49,6 +53,11 @@ void Storage::cleanup() { } +void Storage::setStoragePage(uint8_t page) +{ + m_storagePage = page; +} + // store a serial buffer to storage bool Storage::write(uint16_t slot, ByteStream &buffer) { @@ -69,7 +78,20 @@ bool Storage::write(uint16_t slot, ByteStream &buffer) // just in case buffer.recalcCRC(); #ifdef VORTEX_EMBEDDED - // implement device storage here + // ESP32 Arduino environment + nvs_handle_t nvs; + uint8_t name[3] = { (uint8_t)('a' + m_storagePage), (uint8_t)('a' + (uint8_t)slot), 0 }; + esp_err_t err = nvs_open((char *)name, NVS_READWRITE, &nvs); + if (err != ESP_OK) { + nvs_close(nvs); + return false; + } + err = nvs_set_blob(nvs, (char *)name, buffer.rawData(), buffer.rawSize()); + if (err != ESP_OK) { + nvs_close(nvs); + return false; + } + nvs_close(nvs); #elif defined(_WIN32) HANDLE hFile = CreateFile(STORAGE_FILENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { @@ -77,7 +99,7 @@ bool Storage::write(uint16_t slot, ByteStream &buffer) return false; } DWORD written = 0; - DWORD offset = slot * MAX_MODE_SIZE; + DWORD offset = (slot * MAX_MODE_SIZE) + (m_storagePage * (MAX_MODE_SIZE * MAX_MODES)); SetFilePointer(hFile, offset, NULL, FILE_BEGIN); if (!WriteFile(hFile, buffer.rawData(), MAX_MODE_SIZE, &written, NULL)) { // error @@ -89,7 +111,7 @@ bool Storage::write(uint16_t slot, ByteStream &buffer) if (!f) { return false; } - long offset = slot * MAX_MODE_SIZE; + long offset = (slot * MAX_MODE_SIZE) + (m_storagePage * (MAX_MODE_SIZE * MAX_MODES)); fseek(f, offset, SEEK_SET); if (!fwrite(buffer.rawData(), sizeof(char), MAX_MODE_SIZE, f)) { return false; @@ -118,7 +140,22 @@ bool Storage::read(uint16_t slot, ByteStream &buffer) return false; } #ifdef VORTEX_EMBEDDED - // implement device storage here + // ESP32 Arduino environment + nvs_handle_t nvs; + uint8_t name[3] = { (uint8_t)('a' + m_storagePage), (uint8_t)('a' + (uint8_t)slot), 0 }; + esp_err_t err = nvs_open((char *)name, NVS_READWRITE, &nvs); + if (err != ESP_OK) { + nvs_close(nvs); + return false; + } + size_t read_size = size; + // build a two letter name based on the slot and page + err = nvs_get_blob(nvs, (char *)name, buffer.rawData(), &read_size); + if (err != ESP_OK) { + nvs_close(nvs); + return false; + } + nvs_close(nvs); #elif defined(_WIN32) HANDLE hFile = CreateFile(STORAGE_FILENAME, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { @@ -126,7 +163,7 @@ bool Storage::read(uint16_t slot, ByteStream &buffer) return false; } DWORD bytesRead = 0; - DWORD offset = slot * MAX_MODE_SIZE; + DWORD offset = (slot * MAX_MODE_SIZE) + (m_storagePage * (MAX_MODE_SIZE * MAX_MODES)); SetFilePointer(hFile, offset, NULL, FILE_BEGIN); if (!ReadFile(hFile, buffer.rawData(), MAX_MODE_SIZE, &bytesRead, NULL)) { // error @@ -138,7 +175,7 @@ bool Storage::read(uint16_t slot, ByteStream &buffer) if (!f) { return false; } - long offset = slot * MAX_MODE_SIZE; + long offset = (slot * MAX_MODE_SIZE) + (m_storagePage * (MAX_MODE_SIZE * MAX_MODES)); fseek(f, offset, SEEK_SET); if (!fread(buffer.rawData(), sizeof(char), MAX_MODE_SIZE, f)) { return false; diff --git a/VortexEngine/src/Storage/Storage.h b/VortexEngine/src/Storage/Storage.h index 19f0999f54..58b39072f0 100644 --- a/VortexEngine/src/Storage/Storage.h +++ b/VortexEngine/src/Storage/Storage.h @@ -18,6 +18,9 @@ class Storage static bool init(); static void cleanup(); + // set the global storage page, the chromadeck has 8 pages of 16 slots each + static void setStoragePage(uint8_t page); + // store a serial buffer to storage static bool write(uint16_t slot, ByteStream &buffer); // read a serial buffer from storage @@ -38,6 +41,9 @@ class Storage // the size of the last save static uint32_t m_lastSaveSize; + + // the curren storage page + static uint8_t m_storagePage; }; #endif diff --git a/VortexEngine/src/Time/TimeControl.cpp b/VortexEngine/src/Time/TimeControl.cpp index 8493deb667..ba13756287 100644 --- a/VortexEngine/src/Time/TimeControl.cpp +++ b/VortexEngine/src/Time/TimeControl.cpp @@ -2,6 +2,8 @@ #include +#include "../VortexConfig.h" + #include "../Memory/Memory.h" #include "../Log/Log.h" @@ -22,6 +24,10 @@ static LARGE_INTEGER tps; static LARGE_INTEGER start; #endif +#if VORTEX_EMBEDDED == 1 +#include +#endif + // static members #if VARIABLE_TICKRATE == 1 uint32_t Time::m_tickrate = DEFAULT_TICKRATE; @@ -190,7 +196,7 @@ uint32_t Time::microseconds() void Time::delayMicroseconds(uint32_t us) { -#ifdef _WIN32 +#if VORTEX_EMBEDDED == 1 || defined(_WIN32) uint32_t newtime = microseconds() + us; while (microseconds() < newtime) { // busy loop @@ -202,11 +208,8 @@ void Time::delayMicroseconds(uint32_t us) void Time::delayMilliseconds(uint32_t ms) { -#ifdef VORTEX_EMBEDDED - // not very accurate - for (uint16_t i = 0; i < ms; ++i) { - delayMicroseconds(1000); - } +#if VORTEX_EMBEDDED == 1 + delay(ms); #elif defined(_WIN32) Sleep(ms); #else diff --git a/VortexEngine/src/VortexConfig.h b/VortexEngine/src/VortexConfig.h index dc47583a5c..ab1dc852c6 100644 --- a/VortexEngine/src/VortexConfig.h +++ b/VortexEngine/src/VortexConfig.h @@ -38,7 +38,7 @@ // the engine flavour, this should change for each device/flavour // of the engine that branches off from the main indefinitely -#define VORTEX_NAME "Core" +#define VORTEX_NAME "Spark" // the full name of this build for ex: // Vortex Engine v1.0 'Igneous' (built Tue Jan 31 19:03:55 2023) @@ -52,6 +52,10 @@ // uses too much stack space to run on smaller devices #define VORTEX_SLIM 0 +// Turn on this flag to change from Spark Orbit pins to Spark Handle pins +// TODO: remove this once the spark orbit and handle have matching hardware +#define SPARK_HANDLE 0 + // =================================================================== // Numeric Configurations @@ -158,7 +162,7 @@ // // The starting default global brightness if there is no savefile // present The maximum value is 255 -#define DEFAULT_BRIGHTNESS 185 +#define DEFAULT_BRIGHTNESS 255 // Max Modes // @@ -176,7 +180,7 @@ // This should not be set to 0, it should be a specific maximum for // each separate device // -#define MAX_MODES 13 +#define MAX_MODES 16 // Default Tickrate in Ticks Per Second (TPS) // @@ -314,7 +318,7 @@ // Serial Baud Rate // // The serial connection baud rate for the editor and anything else serial -#define SERIAL_BAUD_RATE 9600 +#define SERIAL_BAUD_RATE 115200 // =================================================================== // Boolean Configurations (0 or 1) diff --git a/VortexEngine/src/VortexEngine.cpp b/VortexEngine/src/VortexEngine.cpp index 087931c7d9..f247a81141 100644 --- a/VortexEngine/src/VortexEngine.cpp +++ b/VortexEngine/src/VortexEngine.cpp @@ -30,12 +30,12 @@ bool VortexEngine::m_autoCycle = false; bool VortexEngine::init() { // all of the global controllers - if (!SerialComs::init()) { - DEBUG_LOG("Serial failed to initialize"); + if (!Time::init()) { + //DEBUG_LOG("Time failed to initialize"); return false; } - if (!Time::init()) { - DEBUG_LOG("Time failed to initialize"); + if (!SerialComs::init()) { + DEBUG_LOG("Serial failed to initialize"); return false; } if (!Storage::init()) { @@ -178,6 +178,13 @@ void VortexEngine::runMainLogic() return; } + // check for serial first before anything runs, but as a result if we open + // editor we have to call modes load inside here + if ((Menus::curMenuID() != MENU_EDITOR_CONNECTION) && SerialComs::checkSerial()) { + // directly open the editor connection menu because we are connected to USB serial + Menus::openMenu(MENU_EDITOR_CONNECTION); + } + // if the menus are open and running then just return if (Menus::run()) { return; diff --git a/VortexEngine/src/Wireless/IRConfig.h b/VortexEngine/src/Wireless/IRConfig.h index 2a8e68ddf2..e763b6b17d 100644 --- a/VortexEngine/src/Wireless/IRConfig.h +++ b/VortexEngine/src/Wireless/IRConfig.h @@ -39,7 +39,7 @@ #define IR_DIVIDER_SPACE_MIN IR_HEADER_MARK_MIN #define IR_DIVIDER_SPACE_MAX IR_HEADER_MARK_MAX -#define IR_SEND_PWM_PIN 0 -#define IR_RECEIVER_PIN 2 +#define IR_SEND_PWM_PIN 3 +#define IR_RECEIVER_PIN 4 #endif diff --git a/VortexEngine/src/Wireless/IRReceiver.cpp b/VortexEngine/src/Wireless/IRReceiver.cpp index 47ec50ef4d..0190d52e8a 100644 --- a/VortexEngine/src/Wireless/IRReceiver.cpp +++ b/VortexEngine/src/Wireless/IRReceiver.cpp @@ -9,6 +9,10 @@ #include "../Modes/Mode.h" #include "../Log/Log.h" +#ifdef VORTEX_EMBEDDED +#include +#endif + BitStream IRReceiver::m_irData; IRReceiver::RecvState IRReceiver::m_recvState = WAITING_HEADER_MARK; uint32_t IRReceiver::m_prevTime = 0; @@ -17,6 +21,9 @@ uint32_t IRReceiver::m_previousBytes = 0; bool IRReceiver::init() { +#ifdef VORTEX_EMBEDDED + pinMode(IR_RECEIVER_PIN, INPUT_PULLUP); +#endif m_irData.init(IR_RECV_BUF_SIZE); return true; } @@ -83,12 +90,18 @@ bool IRReceiver::receiveMode(Mode *pMode) bool IRReceiver::beginReceiving() { +#ifdef VORTEX_EMBEDDED + attachInterrupt(digitalPinToInterrupt(IR_RECEIVER_PIN), IRReceiver::recvPCIHandler, CHANGE); +#endif resetIRState(); return true; } bool IRReceiver::endReceiving() { +#ifdef VORTEX_EMBEDDED + detachInterrupt(digitalPinToInterrupt(IR_RECEIVER_PIN)); +#endif resetIRState(); return true; } @@ -138,7 +151,7 @@ void IRReceiver::recvPCIHandler() // check previous time for validity if (!m_prevTime || m_prevTime > now) { m_prevTime = now; - DEBUG_LOG("Bad first time diff, resetting..."); + //DEBUG_LOG("Bad first time diff, resetting..."); resetIRState(); return; } @@ -155,7 +168,7 @@ void IRReceiver::handleIRTiming(uint32_t diff) { // if the diff is too long or too short then it's not useful if ((diff > IR_HEADER_MARK_MAX && m_recvState < READING_DATA_MARK) || diff < IR_TIMING_MIN) { - DEBUG_LOGF("bad delay: %u, resetting...", diff); + //DEBUG_LOGF("bad delay: %u, resetting...", diff); resetIRState(); return; } @@ -164,7 +177,7 @@ void IRReceiver::handleIRTiming(uint32_t diff) if (diff >= IR_HEADER_MARK_MIN && diff <= IR_HEADER_MARK_MAX) { m_recvState = WAITING_HEADER_SPACE; } else { - DEBUG_LOGF("Bad header mark %u, resetting...", diff); + //DEBUG_LOGF("Bad header mark %u, resetting...", diff); resetIRState(); } break; @@ -172,7 +185,7 @@ void IRReceiver::handleIRTiming(uint32_t diff) if (diff >= IR_HEADER_SPACE_MIN && diff <= IR_HEADER_SPACE_MAX) { m_recvState = READING_DATA_MARK; } else { - DEBUG_LOGF("Bad header space %u, resetting...", diff); + //DEBUG_LOGF("Bad header space %u, resetting...", diff); resetIRState(); } break; @@ -186,7 +199,7 @@ void IRReceiver::handleIRTiming(uint32_t diff) m_recvState = READING_DATA_MARK; break; default: // ?? - DEBUG_LOGF("Bad receive state: %u", m_recvState); + //DEBUG_LOGF("Bad receive state: %u", m_recvState); break; } } @@ -197,7 +210,7 @@ void IRReceiver::resetIRState() m_recvState = WAITING_HEADER_MARK; // zero out the receive buffer and reset bit receiver position m_irData.reset(); - DEBUG_LOG("IR State Reset"); + //DEBUG_LOG("IR State Reset"); } #endif diff --git a/VortexEngine/src/Wireless/IRSender.cpp b/VortexEngine/src/Wireless/IRSender.cpp index 1d127a1978..b211680d4a 100644 --- a/VortexEngine/src/Wireless/IRSender.cpp +++ b/VortexEngine/src/Wireless/IRSender.cpp @@ -11,6 +11,10 @@ #include "VortexLib.h" #endif +#ifdef VORTEX_EMBEDDED +#include +#endif + // the serial buffer for the data ByteStream IRSender::m_serialBuf; // a bit walker for the serial data @@ -32,6 +36,9 @@ uint32_t IRSender::m_writeCounter = 0; bool IRSender::init() { +#ifdef VORTEX_EMBEDDED + initPWM(); +#endif return true; } @@ -144,6 +151,9 @@ void IRSender::sendMark(uint16_t time) #ifdef VORTEX_LIB // send mark timing over socket Vortex::vcallbacks()->infraredWrite(true, time); +#else + startPWM(); + Time::delayMicroseconds(time); #endif } @@ -152,7 +162,34 @@ void IRSender::sendSpace(uint16_t time) #ifdef VORTEX_LIB // send space timing over socket Vortex::vcallbacks()->infraredWrite(false, time); +#else + stopPWM(); + Time::delayMicroseconds(time); #endif } +#ifdef VORTEX_EMBEDDED +const uint32_t pwmFrequency = 39062; // Actual frequency with divider = 8 +const uint8_t pwmResolution = 8; +const uint32_t pwmDutyCycle = 85; + +void IRSender::initPWM() +{ + // Configure the PWM on the specified pin with initial duty cycle of 0 + ledcAttach(IR_SEND_PWM_PIN, pwmFrequency, pwmResolution); +} + +void IRSender::startPWM() +{ + // Start PWM with the specified duty cycle + ledcWrite(IR_SEND_PWM_PIN, pwmDutyCycle); +} + +void IRSender::stopPWM() +{ + // Stop PWM by setting the duty cycle to 0 + ledcWrite(IR_SEND_PWM_PIN, 0); +} +#endif + #endif diff --git a/VortexEngine/src/Wireless/IRSender.h b/VortexEngine/src/Wireless/IRSender.h index 8f65fa7048..2b2048ffad 100644 --- a/VortexEngine/src/Wireless/IRSender.h +++ b/VortexEngine/src/Wireless/IRSender.h @@ -27,6 +27,12 @@ class IRSender static uint32_t percentDone() { return (uint32_t)(((float)m_writeCounter / (float)m_size) * 100.0); } private: +#ifdef VORTEX_EMBEDDED + static void initPWM(); + static void startPWM(); + static void stopPWM(); +#endif + // sender functions static void beginSend(); // send a full 8 bits in a tight loop diff --git a/VortexEngine/src/Wireless/VLConfig.h b/VortexEngine/src/Wireless/VLConfig.h index 2ee8490d67..a2a310c6f3 100644 --- a/VortexEngine/src/Wireless/VLConfig.h +++ b/VortexEngine/src/Wireless/VLConfig.h @@ -42,6 +42,6 @@ #define VL_DIVIDER_SPACE_MAX VL_HEADER_MARK_MAX #define VL_SEND_PWM_PIN 0 -#define VL_RECEIVER_PIN 0 +#define VL_RECEIVER_PIN 1 #endif diff --git a/VortexEngine/src/Wireless/VLReceiver.cpp b/VortexEngine/src/Wireless/VLReceiver.cpp index 8d2f12a9a1..aa6c9cab2d 100644 --- a/VortexEngine/src/Wireless/VLReceiver.cpp +++ b/VortexEngine/src/Wireless/VLReceiver.cpp @@ -16,8 +16,57 @@ uint32_t VLReceiver::m_prevTime = 0; uint8_t VLReceiver::m_pinState = 0; uint32_t VLReceiver::m_previousBytes = 0; +#ifdef VORTEX_EMBEDDED +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "driver/adc.h" +#include "esp_adc_cal.h" +#include "esp_log.h" +#include "esp_timer.h" + +#include "../Serial/Serial.h" + +// ADC and timer configuration +#define ADC_CHANNEL ADC1_CHANNEL_1 // Update this based on the actual ADC channel used +#define ADC_ATTEN ADC_ATTEN_DB_0 +#define ADC_WIDTH ADC_WIDTH_BIT_12 +#define TIMER_INTERVAL_MICRO_SEC 1000 // Check every 10ms, adjust as needed for your application + +// Timer handle as a global variable for control in beginReceiving and endReceiving +esp_timer_handle_t periodic_timer = nullptr; +esp_adc_cal_characteristics_t adc_chars; + +#define MIN_THRESHOLD 200 +#define BASE_OFFSET 100 +#define THRESHOLD_BEGIN (MIN_THRESHOLD + BASE_OFFSET) +// the threshold needs to start high then it will be automatically pulled down +uint32_t threshold = THRESHOLD_BEGIN; +void VLReceiver::adcCheckTimerCallback(void *arg) +{ + static bool wasAboveThreshold = false; + uint32_t raw = adc1_get_raw(ADC_CHANNEL); + uint32_t val = esp_adc_cal_raw_to_voltage(raw, &adc_chars); + + if (val > MIN_THRESHOLD && val < (threshold + BASE_OFFSET)) { + threshold = val + BASE_OFFSET; + } + bool isAboveThreshold = (val > threshold); + if (wasAboveThreshold != isAboveThreshold) { + wasAboveThreshold = isAboveThreshold; + VLReceiver::recvPCIHandler(); + } +} +#endif + bool VLReceiver::init() { +#ifdef VORTEX_EMBEDDED + // Initialize ADC for GPIO1 (or appropriate pin connected to your light sensor) + adc1_config_width(ADC_WIDTH); + adc1_config_channel_atten(ADC_CHANNEL, ADC_ATTEN); + memset(&adc_chars, 0, sizeof(adc_chars)); + esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN, ADC_WIDTH, 0, &adc_chars); +#endif return m_vlData.init(VL_RECV_BUF_SIZE); } @@ -83,12 +132,36 @@ bool VLReceiver::receiveMode(Mode *pMode) bool VLReceiver::beginReceiving() { +#ifdef VORTEX_EMBEDDED + if (periodic_timer) { + DEBUG_LOG("VL Reception already running."); + return false; // Timer is already running + } + // Initialize timer for periodic ADC checks + const esp_timer_create_args_t periodic_timer_args = { + .callback = &VLReceiver::adcCheckTimerCallback, + .name = "adc_check_timer", + }; + ESP_ERROR_CHECK(esp_timer_create(&periodic_timer_args, &periodic_timer)); + ESP_ERROR_CHECK(esp_timer_start_periodic(periodic_timer, TIMER_INTERVAL_MICRO_SEC)); +#endif resetVLState(); return true; } bool VLReceiver::endReceiving() { +#ifdef VORTEX_EMBEDDED + if (periodic_timer == nullptr) { + DEBUG_LOG("VL Reception was not running."); + return false; // Timer was not running + } + // Stop and delete the timer + ESP_ERROR_CHECK(esp_timer_stop(periodic_timer)); + ESP_ERROR_CHECK(esp_timer_delete(periodic_timer)); + periodic_timer = nullptr; + DEBUG_LOG("VL Reception stopped."); +#endif resetVLState(); return true; } @@ -138,10 +211,11 @@ void VLReceiver::recvPCIHandler() // check previous time for validity if (!m_prevTime || m_prevTime > now) { m_prevTime = now; - DEBUG_LOG("Bad first time diff, resetting..."); + //DEBUG_LOG("Bad first time diff, resetting..."); resetVLState(); return; } + //DEBUG_LOGF("Received: %u", m_pinState); // calc time difference between previous change and now uint32_t diff = (uint32_t)(now - m_prevTime); // and update the previous changetime for next loop @@ -155,7 +229,7 @@ void VLReceiver::handleVLTiming(uint32_t diff) { // if the diff is too long or too short then it's not useful if ((diff > VL_HEADER_MARK_MAX && m_recvState < READING_DATA_MARK) || diff < VL_TIMING_MIN) { - DEBUG_LOGF("bad delay: %u, resetting...", diff); + //DEBUG_LOGF("bad delay: %u, resetting...", diff); resetVLState(); return; } @@ -164,7 +238,7 @@ void VLReceiver::handleVLTiming(uint32_t diff) if (diff >= VL_HEADER_SPACE_MIN && diff <= VL_HEADER_MARK_MAX) { m_recvState = WAITING_HEADER_SPACE; } else { - DEBUG_LOGF("Bad header mark %u, resetting...", diff); + //DEBUG_LOGF("Bad header mark %u, resetting...", diff); resetVLState(); } break; @@ -172,7 +246,7 @@ void VLReceiver::handleVLTiming(uint32_t diff) if (diff >= VL_HEADER_SPACE_MIN && diff <= VL_HEADER_MARK_MAX) { m_recvState = READING_DATA_MARK; } else { - DEBUG_LOGF("Bad header space %u, resetting...", diff); + //DEBUG_LOGF("Bad header space %u, resetting...", diff); resetVLState(); } break; @@ -186,7 +260,7 @@ void VLReceiver::handleVLTiming(uint32_t diff) m_recvState = READING_DATA_MARK; break; default: // ?? - DEBUG_LOGF("Bad receive state: %u", m_recvState); + //DEBUG_LOGF("Bad receive state: %u", m_recvState); break; } } @@ -197,7 +271,7 @@ void VLReceiver::resetVLState() m_recvState = WAITING_HEADER_MARK; // zero out the receive buffer and reset bit receiver position m_vlData.reset(); - DEBUG_LOG("VL State Reset"); + //DEBUG_LOG("VL State Reset"); } #endif diff --git a/VortexEngine/src/Wireless/VLReceiver.h b/VortexEngine/src/Wireless/VLReceiver.h index be4b0a68b5..1d7d35628b 100644 --- a/VortexEngine/src/Wireless/VLReceiver.h +++ b/VortexEngine/src/Wireless/VLReceiver.h @@ -9,6 +9,10 @@ #if VL_ENABLE_RECEIVER == 1 +#ifdef VORTEX_EMBEDDED +#include +#endif + class ByteStream; class Mode; @@ -73,6 +77,10 @@ class VLReceiver // used to compare if received data has changed since last checking static uint32_t m_previousBytes; +#ifdef VORTEX_EMBEDDED + static void adcCheckTimerCallback(void *arg); +#endif + #ifdef VORTEX_LIB friend class Vortex; #endif diff --git a/VortexEngine/tests/tests_general.tar.gz b/VortexEngine/tests/tests_general.tar.gz index 5c0e6df188..f981bb72fd 100644 Binary files a/VortexEngine/tests/tests_general.tar.gz and b/VortexEngine/tests/tests_general.tar.gz differ