Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • 89-apps-should-be-able-to-specify-if-they-want-wifi-to-be-disabled-when-entering-them
  • 9Rmain
  • allow-reloading-sunmenu
  • always-have-a-wifi-instance
  • anon/gpndemo
  • anon/update-sim
  • anon/webflasher
  • app_text_viewer
  • audio_input
  • audio_io
  • blm_dev_chan
  • ch3/bl00mbox_docs
  • ci-1690580595
  • dev_p4
  • dev_p4-iggy
  • dev_p4-iggy-rebased
  • dx/dldldld
  • dx/fb-save-restore
  • dx/hint-hint
  • dx/jacksense-headset-mic-only
  • events
  • fil3s-limit-filesize
  • fil3s-media
  • fpletz/flake
  • gr33nhouse-improvements
  • history-rewrite
  • icon-flower
  • iggy/stemming
  • iggy/stemming_merge
  • led_fix_fix
  • main
  • main+schneider
  • media_has_video_has_audio
  • micropython_api
  • mixer2
  • moon2_demo_temp
  • moon2_migrate_apps
  • more-accurate-battery
  • pippin/ctx_sprite_sheet_support
  • pippin/display-python-errors-on-display
  • pippin/make_empty_drawlists_skip_render_and_blit
  • pippin/more-accurate-battery
  • pippin/tcp_redirect_hack
  • pippin/tune_ctx_config_update_from_upstream
  • pippin/uhm_flash_access_bust
  • pressable_bugfix
  • py_only_update_fps_overlay_when_changing
  • q3k/doom-poc
  • q3k/render-to-texture
  • rahix/flow3rseeds
  • raw_captouch_new
  • raw_captouch_old
  • release/1.0.0
  • release/1.1.0
  • release/1.1.1
  • release/1.2.0
  • release/1.3.0
  • release/1.4.0
  • restore_blit
  • return_of_melodic_demo
  • rev4_micropython
  • schneider/application-remove-name
  • schneider/bhi581
  • schneider/factory_test
  • schneider/recovery
  • scope_hack
  • sdkconfig-spiram-tinyusb
  • sec/auto-nick
  • sec/blinky
  • sector_size_512
  • shoegaze-fps
  • smaller_gradient_lut
  • store_delta_ms_and_ins_as_class_members
  • task_cleanup
  • uctx-wip
  • w1f1-in-sim
  • widgets_draw
  • wifi-json-error-handling
  • wip-docs
  • wip-tinyusb
  • v1.0.0
  • v1.0.0+rc1
  • v1.0.0+rc2
  • v1.0.0+rc3
  • v1.0.0+rc4
  • v1.0.0+rc5
  • v1.0.0+rc6
  • v1.1.0
  • v1.1.0+rc1
  • v1.1.1
  • v1.2.0
  • v1.2.0+rc1
  • v1.3.0
  • v1.4.0
94 results

Target

Select target project
No results found
Select Git revision
  • 9Rmain
  • anon/gpndemo
  • anon/update-sim
  • anon/webflasher
  • audio_input
  • audio_io
  • bl00mbox
  • bl00mbox_old
  • ch3/bl00mbox_docs
  • ci-1690580595
  • compressor
  • dev_p4
  • dev_p4-iggy
  • dev_p4-iggy-rebased
  • events
  • fm_fix
  • fm_fix2
  • fpletz/flake
  • history-rewrite
  • icon-flower
  • iggy/stemming
  • iggy/stemming_merge
  • main
  • main+schneider
  • micropython_api
  • moon2_applications
  • moon2_demo_temp
  • moon2_gay_drums
  • pippin/display-python-errors-on-display
  • pippin/make_empty_drawlists_skip_render_and_blit
  • pippin/media_framework
  • pippin/uhm_flash_access_bust
  • pressable_bugfix
  • q3k/doom-poc
  • rahix/flow3rseeds
  • raw_captouch_new
  • raw_captouch_old
  • release/1.0.0
  • release/1.1.0
  • release/1.1.1
  • rev4_micropython
  • schneider/application-remove-name
  • schneider/bhi581
  • schneider/factory_test
  • schneider/recovery
  • scope_hack
  • sdkconfig-spiram-tinyusb
  • sec/auto-nick
  • sec/blinky
  • uctx-wip
  • wip-docs
  • wip-tinyusb
  • v1.0.0
  • v1.0.0+rc1
  • v1.0.0+rc2
  • v1.0.0+rc3
  • v1.0.0+rc4
  • v1.0.0+rc5
  • v1.0.0+rc6
  • v1.1.0
  • v1.1.0+rc1
  • v1.1.1
62 results
Show changes
1000 files
+ 163008
21174
Compare changes
  • Side-by-side
  • Inline

Files

.clang-format

0 → 100644
+5 −0
Original line number Diff line number Diff line
---
BasedOnStyle: Google
IndentWidth: 4
IncludeBlocks: Preserve
Cpp11BracedListStyle: false

.clang-tidy

0 → 100644
+3 −0
Original line number Diff line number Diff line
# Don't care about deprecated APIs (noisy) and about memcpy/strcpy (we'll fix
# that later).
Checks: '-clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling,-clang-diagnostic-deprecated-declarations'
+13 −0
Original line number Diff line number Diff line
@@ -4,12 +4,25 @@ sdkconfig
dependencies.lock
build

.sdkconfig.defaults.generated

# micropython
__pycache__

# editor crud
.vscode
*swp
*~

# Python
.venv
/venv/

# sphinx
docs/_build/

/tools/mypy.sh

# bl00mbox docs
components/bl00mbox/docs/
components/bl00mbox/public/
+76 −25
Original line number Diff line number Diff line
stages:
  - check
  - build
  - deploy

build-p1:
  stage: build
  tags:
    - nixos
variables:
  GIT_SUBMODULE_STRATEGY: recursive
  GIT_DEPTH: 0

default:
  # built via:
  #     docker load < $(nix-build nix/docker-image.nix)
  image: registry.gitlab.com/flow3r-badge/flow3r-build:238576xsg79mjr2bkqg106qisvd3b5q9

clang-tidy:
  stage: check
  script:
    - nix-shell nix/shell.nix --command "idf.py -g p1 build"
    - "bash tools/clang-tidy.sh"
    - "python3 tools/codequal-report.py clang-tidy warnings.txt > cqual.json"
  artifacts:
    expose_as: 'Proto 1 ELF'
    paths: ['build/badge23.elf']
    when: always
    reports:
      codequality: cqual.json

build-p3:
format:
  stage: check
  script:
    - "git clean -fdx"
    - "bash tools/format.sh"
    - "[ -z \"$(git status --porcelain)\" ] || (echo 'Differences found, please run tools/format.sh.' && git diff HEAD && exit 1)"

build:
  stage: build
  tags:
    - nixos
  script:
    - nix-shell nix/shell.nix --command "idf.py -g p3 build"
    - idf.py -g c23 build size
  artifacts:
    expose_as: 'Proto 3 ELF'
    paths: ['build/badge23.elf']
    expose_as: 'firmware'
    paths: ['build/flow3r.bin']
    expire_in: 5 hours

build-p4:
build_recovery:
  stage: build
  tags:
    - nixos
  script:
    - nix-shell nix/shell.nix --command "idf.py -g p4 build"
    - cd recovery
    - idf.py build size
  artifacts:
    expose_as: 'Proto 4 ELF'
    paths: ['build/badge23.elf']
    expose_as: 'Recovery'
    paths: ['recovery/build/flow3r-recovery.bin', 'recovery/build/partition_table/partition-table.bin', 'recovery/build/bootloader/bootloader.bin']
    expire_in: 5 hours

build-p6:
simulate:
  stage: build
  tags:
    - nixos
  script:
    - nix-shell nix/shell.nix --command "idf.py -g p6 build"
    - python3 sim/run.py --screenshot
  artifacts:
    expose_as: 'Simulator Screenshot'
    paths: ['flow3r.png']
    expire_in: 5 hours

pages:
  stage: deploy
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
  script:
    - git tag | xargs git tag -d
    - git checkout origin/main
    - git checkout -b dev
    - git branch --all
    - git branch --all | sed -e 's/..//' | grep '^remotes/origin/release/' | while read b; do git checkout -b "v${b#remotes/origin/release/}" "$b"; done
    - git checkout dev
    - git branch
    - mkdir public
    - cd docs
    - make versionedhtml
    - cp -r _build/$(git branch --sort=version:refname | tail -n1 | sed -e 's/..//')/* _build/
    - python redirects.py
    - cp -r _build/* ../public/
    - find ../public/
  artifacts:
    paths: ['public']
    expire_in: 1d

dist:
  stage: deploy
  variables:
    # Force a full clone to make version machinery work.
    GIT_STRATEGY: clone
  rules:
    - if: $CI_COMMIT_TAG
  script:
    - bash tools/dist.sh
  artifacts:
    expose_as: 'Proto 6 ELF'
    paths: ['build/badge23.elf']
    paths: ['dist']
+2 −2
Original line number Diff line number Diff line
[submodule "lib/berkeley-db-1.xx"]
	path = micropython/lib/berkeley-db-1.xx
	path = components/micropython/vendor/lib/berkeley-db-1.xx
	url = https://github.com/pfalcon/berkeley-db-1.xx
[submodule "lib/micropython-lib"]
	path = micropython/lib/micropython-lib
	path = components/micropython/vendor/lib/micropython-lib
	url = https://github.com/micropython/micropython-lib.git

CHANGELOG.md

0 → 100644
+273 −0
Original line number Diff line number Diff line
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

## [Unreleased]

## [1.4.0] - 2024-12-24
### Summary

- documentation reworked and expanded
- primary context menu: can be opened at any time to view help texts, open the audio mixer or force-exit an application.
- help viewer: applications can provide context-sensitive help texts to make it easier to figure them out and reduce
  the load on appilcation writers to explain everything on a small screen.
- audio mixer: set levels of bl00mbox channels and mute/unmute them. Muted channels don't use CPU.
- secondary context menu: can be opened in an application menu to delete apps, set them as autostart or mark them as
  favorite to sort them to the top of menus
- new preloaded apps: violin, wobbler, mp3 player
- major rework of captouch driver features
- added `st3m.ui.widgets` module for easier app integration of user inputs (for example, captouch gestures)
- bl00mbox can now run channel-specific micropython callbacks whenever the channel is rendered, allowing
  for much more flexible backgrounded music applications

### Added
- system: unregistered apps are marked as "new"
- system: new category "Demos" for things that focus on being technical examples rather than being use case oriented
- gdb: micropython REPL available while debugging
- micropython: added `indent` keyword to `json.dumps`/`json.dump`
- apps: added overrides for OS button
- apps: added `get_help()` method to provide context sensitive help texts to users
- settings: Touch UI (default off) activates preview for captouch menu navigation
- media: support for more (most) mp3 tag types
- gr33nhouse: sort by application type
- captouch: no more silent captouch calibration, driver saves persistent calibration file and guides user through manual
  calibration when none is found.
- captouch: petals can be turned off run with reduced output to increase data rate
- captouch: unfiltered data log is accessible
- captouch: added `PetalLog` helper class for data processing
- bl00mbox: added .delete() method for various objects, added destructors for better garbabe collection behavior
- bl00mbox: added RMS volume collection option and provide volume normalization guidelines in flo3r docs

### Changed
- settings: "Enable WiFi on Boot" option is now "Always-On Wi-Fi" (but is functionally identical), should help reduce confusion about Wi-Fi turning off automatically
- captouch: normalized positional output in new `.pos`/`.raw_pos` attributes, deprecated old `.position` API
- captouch: normalized raw capacitance output in new `.raw_cap` attribute, deprecated old `.pressure` API
- captouch: removed all abstractions that indicate petal pads without replacement,
  i.e. `InputController.petals[x].ccw` or `InputState.petals[x].raw`

### Fixed
- updat3r: Improved version comparison logic, making the "you are up to date :)" logic work
- captouch: petal 5 fully functional
- bl00mbox: a whole lot of bugs and performance issues (but not all :P)

## [1.3.0] - 2023-11-26
### Summary
- Wifi connection UI
- Media framework
- SD card works reliably
- Performance improvements
- Backend improvements
- Wider micropython API
- Improved preloaded applications
- ...and many bugfixes!

### Added
- Added the `Audio Passthrough` app for toggling audio passthrough through
  line-in/mic to speaker or lineout.
- Added the `w1f1` app for managing wifi access to Settings, incorporates
  an in-progress cap-touch multi-tap keyboard (`k3yboard`).
- Added the `Scalar` app in `Music` category for playing scales.
- Added the `Mandelbrot` app, which illustrates how one can do direct
  framebuffer access and control 8bpp palettized modes from python.
- Added configuration of audio adjustments and startup dB level to `settings.json`.
- Added configuration of wifi credentials + hostname via `settings.json`
- Added support for apps to set wifi state automatically (configurable in
  settings: `Let apps change WiFi`)
- Added task profiler which prints over serial (configurable in
  settings: `Debug: ftop`)
- Added an error screen to the `Nick` app when `nick.json` is invalid.
- Added `urequests` and `uos` support in the simulator.
- Added audio/video media framework, and `Wurzelitzer` app as a small jukebox
  frontend - currently supporting mp3 audio, mpeg1 video, GIF and protracker
  .mod files.
- Added exporting of built firmwares as part of CI.
- Added basic implementation of `os.statvfs()` to fetch full/available
  disk space on flash and SD.
- Added `set_position` and `scroll_to` methods to `ScrollController`
- graphics: sprite sheet support for `ctx.image()`
- graphics: `ctx.parse()` for parsing SVG-path-data/ctx-protocol.
- graphics: 1,2,4,8,16,24 and 32 bits-per-pixel graphics modes.
- graphics: direct framebuffer access.
- graphics: palette setting in 1,2,4 and 8bpp graphics modes.
- graphics: flags for 2x 3x and 4x pixel doubling, low-latency and direct-ctx modes.
- graphics: experimental smart redraw mode
- graphics: clipped and composited overlay buffer
- graphics: allow a graphics state depth of up to 10 (`ctx.save()` `ctx.restore()`)
- graphics: virtual framebuffer with scrolling
- battery: Main menu shows a charge percentage estimate based on real battery characterization
- Added basic media playback in the `fil3s` app.
- Added a delete button to `fil3s`/Files app to allow for deleting files,
  folders and apps on-device.
- Added new menu categories, `Media` and `Games`, and made category handling more robust
  to correctly handle introducing new categories in the future.
- Added configuration UI for audio, appearance and graphics settings.
- Added configurable LED patterns for the main menu.
- Added "restore defaults" option in the settings menu.
- Added wah modulation in `Otamatone`.
- Added several API functions for `ViewManager` to make complex view handling in apps
  easier and robust.
- Added firmware update app, `updat3r`.
- Added storage information in `About` app.
- Added audio equalization for built-in speakers.
- Added a function to retrieve scope data for manual drawing/processing.
- Added I2C scanner app.
- Added sensor demo app.
- Added `CONFIG_DEBUG_GDB_ENABLED` flag for easy debugging over USB JTAG.
- Added saving/restoring state to several apps.
- Added variable sequence length support in `gay drums`.

### Changed
- Changed the st3m\_tar logic to only update files on flash after an update
  if they've been changed, greatly improving start times after an update.
- Flashing flow3r through idf.py now automatically restarts it.
- Switched the REPL/fatal/disk restart button to the OS shoulder button (right
  shoulder button, unless swapped in settings).
- Improved performance of the `gr33nhouse` app list by not rendering hidden
  entries and scrolling ones too long to fit on screen.
- Changed the audio adjustment logic, and added support for holding down the
  shoulder to keep increasing/decreasing level.
- Improved download reliability of the `gr33nhouse` app by adding chunked
  downloads, some `gc.collect()` calls, progress bar and an error screen.
- Settings are now automatically loaded and saved when entering and leaving
  the settings page.
- Moved the `Clouds` app to the `Badge` menu and updated it to use IMU data.
- Added a more sane commandline interface to the simulator.
- More stub functions for the simulator.
- Improved performance of system menus by not rendering hidden entries.
- Added visualization of state, instead of an audio scope in UI of `harmonic
  demo` and `melodic demo`.
- The system provided scope is now always stroked.
- Improved BPM tap accuracy in `gay drums`.
- Some shell code rewritten to avoid the expensive calls `ctx.start_group()` and
  `ctx.end_group()`.
- Overlay graphics gets rendered to a separate framebuffer, of which a clipped rectangle
  is composited during scan-out. The python overlay code has been adapted to keep track
  of which parts of overlay need refresh.
- Slightly lower AA quality; for a 3x performance boost in the
  worst-case scanline rasterization code path.
- The entry section in `flow3r.toml` can now be omitted if the Application
  class is called `App`.
- disabled support for compositing group API in ctx, where used global\_alpha on
  its own did was responsible for it seeming to work.
- Split the `settings.py` file into two, creating `settings_menu.py` to hold
  UI-related code and allow `settings` to be used import loops without
  in many cases.
- When running apps through REPL mode (with `mpremote` etc), multi-view apps
  are now properly handled and don't restart whenever OS shoulder is pressed.
- A multitude of built-in apps now scroll names to fit the screen.
- Apps are now sorted and deduplicated by display name, not by folder name.
- Improved handedness in buttons.
- `harmonic demo` turned into a fully-featured `chord organ`
- `menu` key in `flow3r.toml` has been replaced with `category`. The old key can still
  be used to maintain backwards compatibility with older firmwares.
- Backported recent improvements for micropython's garbage collection to make it faster.
- `shoegaze` can now use chords configured in `chord organ`.
- Changed the priority of additional threads spawned by micropython to be equal to its
  main thread's priority.
- Apps that require Wi-Fi connection can directly take the user to Wi-Fi settings.
- Changed the default app installation directory on flash to `/flash/apps`.
- `gr33nhouse` now installs apps on SD card if available.
- Increased the frequency of LED animations.
- Changed the way LED colors are blended when using slew rates lower than 255 to be
  more in line with color perception.
- Rearranged system menu.
- Made system indicator icons bigger.
- Removed CCCamp's Wi-Fi settings from the default config.
- Made InputState and parts of InputController lazily evaluated.
- bl00mbox: allow circular signal dependencies
- bl00mbox: several plugins and patches deprecated and replaced with updated
  versions, see https://gitlab.com/moon2embeddedaudio/bl00mbox/-/blob/main/README.md

### Fixed
- Fixed `tiny sampler` keeping the microphone active after app exit.
- Fixed missing `include/` dir on builds on Darwin.
- Fixed the `time` module in the simulator being broken for apps trying to use it.
- Fixed wrong petal ordering in the simulator.
- Fixed simulator not exiting when closed.
- Fixed `Comic Mono` missing in the simulator.
- Fixed initialization orientation of display and transform initialization for
  ctx contexts, (this enables arbitrary transformations to images and gradients.)
- Fixed broken anti-aliasing for compressed side of curved strokes.
- Fixed cleanup at exit for firmware apps
- Fixed sampler start bug in bl00mbox
- Fixed reset of graphics subsystem upon entering REPL / using mpremote.
- Fixed multitude of issues with transition animations.
- Fixed lost captouch and button presses when they're shorter than a think cycle.
- Fixed `ScrollController`'s handling of high delta values.
- Fixed many crashes in `fil3s` app.
- Fixed a crash in `CapScrollController`.
- Fixed gamma LUT setting for LEDs.
- Fixed bl00mbox channels leaking on micropython's soft reboot.
- Fixed importing bl00mbox's fake stub in the simulator.
- Performance fixes for bl00mbox.
- Fixed troubles with deleting files on some SD cards (like the bundled one).
- Fixed the default I2C1 pins in micropython's I2C interface.
- Fixed large files being truncated when installing apps via `gr33nhouse`.
- Fixed LED color handling in the simulator.
- Fixed flickering .down property of Pressable when going through REPEATED state.


## [1.2.0] - 2023-08-18
### Added
- Added a WiFi status indicator icon.
- Added a battery status indicator icon.
- Added support for loading apps from `/sd/apps` and `/flash/apps`.
- Added an error screen when apps fail to start.
- Added Python/st3m API to access battery charge status.
- Added the ability to always hide icons (*System**Settings**Show Icons*).

### Fixed
- File descriptor leak on app load.  This would lead to the OS crashing when
  too many apps are installed.


## [1.1.1] - 2023-08-17
### Fixed
- Crash on WiFi startup


## [1.1.0] - 2023-08-17

### Added
- Added _Comic Mono_ font.
- Added a setting for automatically connecting to Camp WiFi.
- Added a *System**Get Apps* App for downloading apps directly from <https://flow3r.garden/apps/>.
- Added `ApplicationContext.bundle_path` so apps can find out what directory
  they live in.  This should be used for loading app assets from the correct
  path.
- Added TLS support for MicroPython.
- Added modules for `.tar.gz` extraction.
- Added `aioble` module (Bluetooth Low Energy).
- Added line-in support to bl00mbox.
- Added pronoun support in the Nick app.
- Added color options in the Nick app.
- Added IMU-based rotation in the Nick app.

### Changed
- `ctx.get_font_name()` now raises an exception for unknown fonts.
- Raised max concurrent texture limit to 32.

### Fixed
- Fixed PNG without alpha and JPEG support by enabling `CTX_FORMAT_RGB8`.
- Fixed image cache eviction by introducing a ctx frameclock.
- Fixed incorrect merging of settings dicts in `st3m.settings`.
- Fixed some USB problems.
- Fixed sound filenames not working when they start with `/flash/` or `/sd/`.
- Fixed syntax errors in `flow3r.toml` crashing the menu.


## [1.0.0] - 2023-08-13

Initial Release


[unreleased]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/compare/v1.4.0...main
[1.4.0]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/compare/v1.3.0...v1.4.0
[1.3.0]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/compare/v1.2.0...v1.3.0
[1.2.0]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/compare/v1.1.1...v1.2.0
[1.1.1]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/compare/v1.1.0...v1.1.1
[1.1.0]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/compare/v1.0.0...v1.1.0
[1.0.0]: https://git.flow3r.garden/flow3r/flow3r-firmware/-/tags/v1.0.0
+16 −1
Original line number Diff line number Diff line
@@ -4,4 +4,19 @@ set(IDF_TARGET esp32s3)

include($ENV{IDF_PATH}/tools/cmake/project.cmake)

project(badge23)
project(flow3r)

# Make `1.1` literals into single-point precision float instead of double
# precision. Also warn any time something gets promoted to a double. We
# generally don't want doubles, doubles on ESP32 bad.
idf_component_get_property(st3m_lib st3m COMPONENT_LIB)
idf_component_get_property(flow3r_bsp_lib flow3r_bsp COMPONENT_LIB)
idf_component_get_property(bl00mbox_lib bl00mbox COMPONENT_LIB)
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
    target_compile_options(${st3m_lib} PRIVATE -cl-single-precision-constant -Wdouble-promotion)
    target_compile_options(${flow3r_bsp_lib} PRIVATE -cl-single-precision-constant -Wdouble-promotion)
    target_compile_options(${bl00mbox_lib} PRIVATE -Wno-error=unknown-pragmas)
else()
    target_compile_options(${st3m_lib} PRIVATE -fsingle-precision-constant -Wdouble-promotion)
    target_compile_options(${flow3r_bsp_lib} PRIVATE -fsingle-precision-constant -Wdouble-promotion)
endif()

COPYING

0 → 100644
+674 −0

File added.

Preview size limit exceeded, changes collapsed.

COPYING.LESSER

0 → 100644
+165 −0
Original line number Diff line number Diff line
                   GNU LESSER GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.


  This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.

  0. Additional Definitions.

  As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.

  "The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.

  An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.

  A "Combined Work" is a work produced by combining or linking an
Application with the Library.  The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".

  The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.

  The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.

  1. Exception to Section 3 of the GNU GPL.

  You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.

  2. Conveying Modified Versions.

  If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:

   a) under this License, provided that you make a good faith effort to
   ensure that, in the event an Application does not supply the
   function or data, the facility still operates, and performs
   whatever part of its purpose remains meaningful, or

   b) under the GNU GPL, with none of the additional permissions of
   this License applicable to that copy.

  3. Object Code Incorporating Material from Library Header Files.

  The object code form of an Application may incorporate material from
a header file that is part of the Library.  You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:

   a) Give prominent notice with each copy of the object code that the
   Library is used in it and that the Library and its use are
   covered by this License.

   b) Accompany the object code with a copy of the GNU GPL and this license
   document.

  4. Combined Works.

  You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:

   a) Give prominent notice with each copy of the Combined Work that
   the Library is used in it and that the Library and its use are
   covered by this License.

   b) Accompany the Combined Work with a copy of the GNU GPL and this license
   document.

   c) For a Combined Work that displays copyright notices during
   execution, include the copyright notice for the Library among
   these notices, as well as a reference directing the user to the
   copies of the GNU GPL and this license document.

   d) Do one of the following:

       0) Convey the Minimal Corresponding Source under the terms of this
       License, and the Corresponding Application Code in a form
       suitable for, and under terms that permit, the user to
       recombine or relink the Application with a modified version of
       the Linked Version to produce a modified Combined Work, in the
       manner specified by section 6 of the GNU GPL for conveying
       Corresponding Source.

       1) Use a suitable shared library mechanism for linking with the
       Library.  A suitable mechanism is one that (a) uses at run time
       a copy of the Library already present on the user's computer
       system, and (b) will operate properly with a modified version
       of the Library that is interface-compatible with the Linked
       Version.

   e) Provide Installation Information, but only if you would otherwise
   be required to provide such information under section 6 of the
   GNU GPL, and only to the extent that such information is
   necessary to install and execute a modified version of the
   Combined Work produced by recombining or relinking the
   Application with a modified version of the Linked Version. (If
   you use option 4d0, the Installation Information must accompany
   the Minimal Corresponding Source and Corresponding Application
   Code. If you use option 4d1, you must provide the Installation
   Information in the manner specified by section 6 of the GNU GPL
   for conveying Corresponding Source.)

  5. Combined Libraries.

  You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:

   a) Accompany the combined library with a copy of the same work based
   on the Library, uncombined with any other library facilities,
   conveyed under the terms of this License.

   b) Give prominent notice with the combined library that part of it
   is a work based on the Library, and explaining where to find the
   accompanying uncombined form of the same work.

  6. Revised Versions of the GNU Lesser General Public License.

  The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.

  Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.

  If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
+7 −245
Original line number Diff line number Diff line
## Demo Payload
# flow3r badge

See python_payload/README.md for a demo application.
See https://docs.flow3r.garden/badge/firmware-development.html for a firmware development guide.

Files can be transferred with mpremote, such as:
## License
All original source code in this repository is Copyright (C) 2023 Flow3r Badge Contributors. This source code is licensed under the GNU Lesser General Public License Version 3.0 as described in the file COPYING.

```
mpremote fs cp python_payload/boot.py :boot.py
```
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License Version 3.0 as published by the Free Software Foundation.

Alternatively, adafruit-ampy may work more reliably sometimes:
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.

```
ampy -p /dev/ttyACM0 -d3 put boot.py
```

Please transfer all .py files in python_payload/ for using the demo payload.

## How to install dependencies

### Generic

1. install esp-idf v4.4:
(copied from https://www.wemos.cc/en/latest/tutorials/others/build\_micropython\_esp32.html)
```
$ cd ~
$ git clone https://github.com/espressif/esp-idf.git
$ cd esp-idf
$ git checkout v4.4.4
$ git submodule update --init --recursive

$ cd esp-idf
$ ./install.sh
$ source export.sh
```
best put something like "alias espidf='source ~/esp-idf/export.sh'" in your .bashrc etc,
you need to run it in every new terminal and adding it to autostart did bother us

### Nix(OS)

```
$ nix-shell nix/shell.nix
```

## How to build and flash

Standard ESP-IDF project machinery present and working. You can run `idf.py` from the git checkout and things should just work.

### Building

Prepare submodules:

```
git submodule update --init --recursive
```

Build normally with idf.py:

```
$ idf.py build
```

By default, code for the fourth generation prototype will be built. To select a different generation, either set `-g`/`--generation` during an `idf.py build` (which will get cached for subsequent builds) or set the BADGE_GENERATION environment variable to one of the following values:

^ `-g` / `BADGE_GENERATION` value ^ Badge Generation                   ^ 
| `p1` or `proto1`                | Prototype 1                        |
| `p3` or `proto3`                | Prototype 3 (B3xx)                 |
| `p4` or `proto4`                | Prototype 4 (B4xx)                 |

**Important**: when switching generations, do a full clean by running `rm -rf sdkconfig build`. Otherwise you will get _weird_ errors and likely will end up building for the wrong architecture.

### Flashing

Put badge into bootloader mode by holding left should button down during boot.

```
$ idf.py -p /dev/ttyACM0 flash
```

You can skip `-p /dev/ttyACM0` if you set the environment variable `ESPPORT=/dev/ttyACM0`. This environment variable is also set by default when using Nix.

After flashing, remember to powercycle your badge to get it into the user application.


### Cleaning

For a full clean, do **not** trust `idf.py clean` or `idf.py fullclean`. Instead, do:

```
$ rm -rf build sdkconfig
```

### Accessing MicroPython REPL:

```
$ picocom -b 115200 /dev/ttyACM0
$ # or
$ screen /dev/ttyACM0
$ # or (will eat newlines in REPL, though)
$ idf.py -p /dev/ttyACM0 monitor
```

### Use CMake

`idf.py` calls cmake under the hood for most operations. If you dislike using wrappers you can do the same work yourself:

```
mkdir build
cd build
cmake .. -G Ninja
ninja
```

There's `flash/monitor` targets, too (but no openocd/gdb...). To pick what port to flash to/monitor, set the ESPPORT environment variable.

## How to modify

### Structure

```
main/               - main module, starts micropython on core1 and continues
                      executing components/badge23/.
usermodule/         - `hardware`, `synth`, ... C modules exposed to micropython.
components/badge23/ - main ESP-IDF `app_main`, runs on core 0 after micropython
                      gets started on core1.
components/gc9a01/  - low-level LCD driver.
```

### General info

Global + micropython entry point: `app_main()` in `micropython/ports/esp32/main.c`, compiled into `main/` component.

C entry point, called by^: `os_app_main()` in components/badge23/espan.c

Register new C files for compilation: add to components/badge23/CMakelists.txt

Change output volume in the `set_global_vol_dB(int8_t)` call; -90 for mute

### Debugging

The badge is currently configured to run in HW USB UART/JTAG mode (vs. using TinyUSB and 'software' CDC/whatever using the generic OTG peripheral).

What this means:

1. You can use the MicroPython REPL over a USB console,
2. The MicroPython REPL will also print ESP-IDF logs, including panics,
3. You can use OpenOCD/GDB.

#### printf() debugging and logging in C-land

Given the above, you can do the following to get a log. This is part of ESP-IDF's standard logging functionality.

```
static const char *TAG = "misery";
// ...
ESP_LOGI(TAG, "i love C");
```

However, this will **only work** if you first set `CONFIG_LOG_DEFAULT_LEVEL_INFO=y` (which will likely break programs interacting with micropython REPL as many components of the ESP-IDF will suddenly become very chatty). But that's fine for troubleshooting some C-land bugs.

If you want to only log errors or just add temporary logs, use `ESP_LOGE` instead, which will always print to the USB console.

`printf()` also just works. But it should only be used for development debugging, for long-term logging statements please use `ESP_LOG*` instead.

#### Running OpenOCD+GDB

First, make sure your badge is running in application mode (not bootloader mode! that will stay in bootloader mode).

Then, start OpenOCD:

```
$ OPENOCD_COMMANDS="-f board/esp32s3-builtin.cfg" idf.py openocd
```

(you can skip setting `OPENOCD_COMMANDS` if you're using Nix)

Then, in another terminal:

```
$ idf.py gdb
```

Good luck. The idf.py gdb/openocd scripts seem somewhat buggy.

### ESP-IDF functionality

#### sdkconfig / menuconfig

We have an sdkconfig.default file per badge generation. See the build
instructions above to see how to select the generation to build against.

The build system will generate an sdkconfig, but it should not be committed into
version control. Instead, treat it like an ephemeral artifact that you can also
modify for your own needs during development.

To run menuconfig, do the usual::

```
$ idf.py  menuconfig
```

(Specify -g or BADGE_GENERATION if you haven't built the firmware yet)

Then, either save into the temporary sdkconfig by using 'S', or save into a
defconfig by using 'D'. The resulting `build/defconfig` file can then be copied
into `sdkconfig.$generation` to change the defaults for a given generation.

### Badge link

Badge link lets you have UART between badges or other devices using a 3.5mm
audio cable.

Baud rates up to 5mbit are supported in theory, but data corruption is likely
with higher rates.

Use baud rate 31250 for MIDI.

Note that `badge_link.enable()` will refuse to enable line out if the cable is
not connected. Connect it first. Connecting headphones with badge link enabled
is not recommended, especially not when wearing them.

Example usage:

On both badges:

```
import badge_link
from machine import UART
badge_link.enable(badge_link.PIN_MASK_ALL)
```

On badge 1, connect the cable to line out, and configure uart with tx on tip
(as an example)

```
uart = UART(1, baudrate=115200, tx=badge_link.PIN_INDEX_LINE_OUT_TIP, rx=badge_link.PIN_INDEX_LINE_OUT_RING)
```

On badge 2, connect the cable to line in, and configure uart with tx on ring:

```
uart = UART(1, baudrate=115200, tx=badge_link.PIN_INDEX_LINE_IN_RING, rx=badge_link.PIN_INDEX_LINE_IN_TIP)
```

Then write and read from each side:

```
uart.write("hiiii")
uart.read(5)
```
You should have received a copy of the GNU Lesser General Public License Version 3.0 along with this program.  If not, see <https://www.gnu.org/licenses/>.
+8 −0
Original line number Diff line number Diff line
idf_component_register(
    SRCS
        audio_mod.c
    INCLUDE_DIRS
        .
        ../ctx
        ../st3m
)
+140 −0
Original line number Diff line number Diff line
#ifndef __clang__
#pragma GCC optimize("O2")
#endif

#include <fcntl.h>
#include <st3m_audio.h>
#include <st3m_media.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "ctx.h"

#define POCKETMOD_IMPLEMENTATION
#include "pocketmod.h"

typedef struct {
    st3m_media control;
    pocketmod_context pocketmod;
    uint8_t *data;
    size_t size;
    char *path;
    float scroll_pos;
} mod_state;

static void mod_draw(st3m_media *media, Ctx *ctx) {
    mod_state *self = (void *)media;

    ctx_rectangle(ctx, -120, -120, 240, 240);
    ctx_gray(ctx, 0);
    ctx_fill(ctx);
    // ctx_arc(ctx, 0, 0, 10, 10);
    ctx_rgb(ctx, 1.0, 1.0, 1.0);
    ctx_font_size(ctx, 20);
    char buf[100];
    sprintf(buf, "pat:%i/%i line:%i", self->pocketmod.pattern,
            self->pocketmod.num_patterns, self->pocketmod.line);
    ctx_text_align(ctx, CTX_TEXT_ALIGN_CENTER);
    ctx_move_to(ctx, 0, -20);
    ctx_text(ctx, buf);
    ctx_fill(ctx);

    ctx_font_size(ctx, 14);
    int xpos = 0;
    int str_width = ctx_text_width(ctx, self->path);
    if (str_width > 220) {
        xpos = ctx_sinf(self->scroll_pos) * (str_width - 220) / 2;
    }
    ctx_move_to(ctx, xpos, 14);
    ctx_gray(ctx, 0.6);
    ctx_text(ctx, self->path);
}

static void mod_think(st3m_media *media, float ms_elapsed) {
    mod_state *self = (void *)media;
    if (self->control.paused) return;

    if (self->control.seek == 0) {
        pocketmod_init(&self->pocketmod, self->data, self->size, 48000);
        self->control.seek = -1;
    }

    int samples_needed = (ms_elapsed / 1000.0) * 48000;
    if (samples_needed > 1000) samples_needed = 1000;

    float rendered[samples_needed * 2];
    int rend = pocketmod_render(&self->pocketmod, rendered, sizeof(rendered));
    st3m_pcm_queue_float(48000, 2, rend / (sizeof(float) * 2), rendered);

    if (self->control.duration == 0) {
        self->control.duration = self->pocketmod.num_patterns + 1;
    }
    if (self->pocketmod.pattern >= self->control.duration)
        self->control.duration = self->pocketmod.pattern + 1;
    self->control.position = self->pocketmod.pattern;
    if (self->pocketmod.loop_count)
        self->control.duration = self->control.position;

    self->scroll_pos += ms_elapsed / 1000.0;
}

static void mod_destroy(st3m_media *media) {
    mod_state *self = (void *)media;
    if (self->data) free(self->data);
    if (self->path) free(self->path);
    free(self);
}

static int file_get_contents(const char *path, uint8_t **contents,
                             size_t *length) {
    FILE *file;
    long size;
    long remaining;
    uint8_t *buffer;
    file = fopen(path, "rb");
    if (!file) {
        return -1;
    }
    fseek(file, 0, SEEK_END);
    size = remaining = ftell(file);

    if (length) {
        *length = size;
    }
    rewind(file);
    buffer = malloc(size + 2);
    if (!buffer) {
        fclose(file);
        return -1;
    }
    remaining -= fread(buffer, 1, remaining, file);
    if (remaining) {
        fclose(file);
        free(buffer);
        return -1;
    }
    fclose(file);
    *contents = (unsigned char *)buffer;
    buffer[size] = 0;
    return 0;
}

st3m_media *st3m_media_load_mod(const char *path) {
    mod_state *self = (mod_state *)malloc(sizeof(mod_state));
    memset(self, 0, sizeof(mod_state));
    self->control.draw = mod_draw;
    self->control.think = mod_think;
    self->control.destroy = mod_destroy;
    self->control.has_audio = true;
    file_get_contents(path, &self->data, &self->size);
    if (!self->data ||
        !pocketmod_init(&self->pocketmod, self->data, self->size, 48000)) {
        if (self->data) free(self->data);
        free(self);
        return NULL;
    }
    self->path = strdup(path);
    self->scroll_pos = 0;
    return (st3m_media *)self;
}
+8 −0
Original line number Diff line number Diff line
idf_component_register(
    SRCS
        audio_mp3.c
    INCLUDE_DIRS
        .
        ../ctx
        ../st3m
)
+117 −0
Original line number Diff line number Diff line
CC0 1.0 Universal

Statement of Purpose

The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator and
subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").

Certain owners wish to permanently relinquish those rights to a Work for the
purpose of contributing to a commons of creative, cultural and scientific
works ("Commons") that the public can reliably and without fear of later
claims of infringement build upon, modify, incorporate in other works, reuse
and redistribute as freely as possible in any form whatsoever and for any
purposes, including without limitation commercial purposes. These owners may
contribute to the Commons to promote the ideal of a free culture and the
further production of creative, cultural and scientific works, or to gain
reputation or greater distribution for their Work in part through the use and
efforts of others.

For these and/or other purposes and motivations, and without any expectation
of additional consideration or compensation, the person associating CC0 with a
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
and publicly distribute the Work under its terms, with knowledge of his or her
Copyright and Related Rights in the Work and the meaning and intended legal
effect of CC0 on those rights.

1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not limited
to, the following:

  i. the right to reproduce, adapt, distribute, perform, display, communicate,
  and translate a Work;

  ii. moral rights retained by the original author(s) and/or performer(s);

  iii. publicity and privacy rights pertaining to a person's image or likeness
  depicted in a Work;

  iv. rights protecting against unfair competition in regards to a Work,
  subject to the limitations in paragraph 4(a), below;

  v. rights protecting the extraction, dissemination, use and reuse of data in
  a Work;

  vi. database rights (such as those arising under Directive 96/9/EC of the
  European Parliament and of the Council of 11 March 1996 on the legal
  protection of databases, and under any national implementation thereof,
  including any amended or successor version of such directive); and

  vii. other similar, equivalent or corresponding rights throughout the world
  based on applicable law or treaty, and any national implementations thereof.

2. Waiver. To the greatest extent permitted by, but not in contravention of,
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
and Related Rights and associated claims and causes of action, whether now
known or unknown (including existing as well as future claims and causes of
action), in the Work (i) in all territories worldwide, (ii) for the maximum
duration provided by applicable law or treaty (including future time
extensions), (iii) in any current or future medium and for any number of
copies, and (iv) for any purpose whatsoever, including without limitation
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
the Waiver for the benefit of each member of the public at large and to the
detriment of Affirmer's heirs and successors, fully intending that such Waiver
shall not be subject to revocation, rescission, cancellation, termination, or
any other legal or equitable action to disrupt the quiet enjoyment of the Work
by the public as contemplated by Affirmer's express Statement of Purpose.

3. Public License Fallback. Should any part of the Waiver for any reason be
judged legally invalid or ineffective under applicable law, then the Waiver
shall be preserved to the maximum extent permitted taking into account
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
is so judged Affirmer hereby grants to each affected person a royalty-free,
non transferable, non sublicensable, non exclusive, irrevocable and
unconditional license to exercise Affirmer's Copyright and Related Rights in
the Work (i) in all territories worldwide, (ii) for the maximum duration
provided by applicable law or treaty (including future time extensions), (iii)
in any current or future medium and for any number of copies, and (iv) for any
purpose whatsoever, including without limitation commercial, advertising or
promotional purposes (the "License"). The License shall be deemed effective as
of the date CC0 was applied by Affirmer to the Work. Should any part of the
License for any reason be judged legally invalid or ineffective under
applicable law, such partial invalidity or ineffectiveness shall not
invalidate the remainder of the License, and in such case Affirmer hereby
affirms that he or she will not (i) exercise any of his or her remaining
Copyright and Related Rights in the Work or (ii) assert any associated claims
and causes of action with respect to the Work, in either case contrary to
Affirmer's express Statement of Purpose.

4. Limitations and Disclaimers.

  a. No trademark or patent rights held by Affirmer are waived, abandoned,
  surrendered, licensed or otherwise affected by this document.

  b. Affirmer offers the Work as-is and makes no representations or warranties
  of any kind concerning the Work, express, implied, statutory or otherwise,
  including without limitation warranties of title, merchantability, fitness
  for a particular purpose, non infringement, or the absence of latent or
  other defects, accuracy, or the present or absence of errors, whether or not
  discoverable, all to the greatest extent permissible under applicable law.

  c. Affirmer disclaims responsibility for clearing rights of other persons
  that may apply to the Work or any use thereof, including without limitation
  any person's Copyright and Related Rights in the Work. Further, Affirmer
  disclaims responsibility for obtaining any necessary consents, permissions
  or other rights required for any use of the Work.

  d. Affirmer understands and acknowledges that Creative Commons is not a
  party to this document and has no duty or obligation with respect to this
  CC0 or use of the Work.

For more information, please see
<http://creativecommons.org/publicdomain/zero/1.0/>
+568 −0
Original line number Diff line number Diff line
#ifndef __clang__
#pragma GCC optimize("O2")
#endif

#include <fcntl.h>
#include <st3m_audio.h>
#include <st3m_media.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "lwip/igmp.h"
#include "lwip/ip4.h"
#include "lwip/netdb.h"
#include "lwip/sockets.h"

#include "ctx.h"

#define MINIMP3_NONSTANDARD_BUT_LOGICAL
#define MINIMP3_NO_SIMD
#define MINIMP3_IMPLEMENTATION
#include "minimp3.h"

typedef struct {
    st3m_media control;
    mp3dec_t mp3d;
    char *path;
    char *artist;
    char *title;
    int year;
    int started;
    int samplerate;
    int channels;
    uint8_t *data;
    size_t size;
    size_t count;

    int pos;
    int offset;
    int buffer_size;

    int file_size;
    FILE *file;

    int socket;

    int in_buffering;
    float scroll_pos;
} mp3_state;

static int has_data(mp3_state *mp3) {
    if (mp3->file) return 1;
    fd_set rfds;
    struct timeval tv = { 0, 0 };
    FD_ZERO(&rfds);
    FD_SET(mp3->socket, &rfds);
    if (select(mp3->socket + 1, &rfds, NULL, NULL, &tv) == 1)
        return FD_ISSET(mp3->socket, &rfds);
    return 0;
}

static void mp3_fetch_data(mp3_state *mp3) {
    if (mp3->pos) {
        memmove(mp3->data, &mp3->data[mp3->pos], mp3->count - mp3->pos);
        mp3->offset += mp3->pos;
        mp3->count -= mp3->pos;
        mp3->pos = 0;
    }

    // if incoming data-buffer falls below 16kb - do a full buffer fill
    if (!mp3->file && (mp3->count < 16 * 1024)) {
        mp3->in_buffering = 1;
    }

    if ((mp3->size - mp3->count > 0) && has_data(mp3)) {
        int desire_bytes = (mp3->size - mp3->count);
        if (desire_bytes > 2048) desire_bytes = 2048;
        if (desire_bytes) {
            int read_bytes;
            if (mp3->file)
                read_bytes =
                    fread(mp3->data + mp3->count, 1, desire_bytes, mp3->file);
            else
                read_bytes =
                    read(mp3->socket, mp3->data + mp3->count, desire_bytes);
            mp3->count += read_bytes;
        }
    }
}

static char *mp3_get_string(st3m_media *media, const char *key) {
    mp3_state *self = (void *)media;
    if (strcmp(key, "artist") == 0) {
        return strdup(self->artist);
    } else if (strcmp(key, "title") == 0) {
        return strdup(self->title);
    }
    return NULL;
}

static void mp3_draw(st3m_media *media, Ctx *ctx) {
    mp3_state *self = (void *)media;

    ctx_rectangle(ctx, -120, -120, 240, 240);
    ctx_gray(ctx, 0);
    ctx_fill(ctx);
    ctx_rgb(ctx, 1.0, 1.0, 1.0);
    ctx_rectangle(ctx, -120, 0, 240, 1);
    ctx_rectangle(ctx, -120 + self->offset * 240.0 / self->file_size, -32, 2,
                  64);
    ctx_fill(ctx);
    ctx_font_size(ctx, 24);
    ctx_text_align(ctx, CTX_TEXT_ALIGN_CENTER);

    int xpos = 0;
    int str_width = ctx_text_width(ctx, self->artist);
    if (str_width > 200) {
        xpos = ctx_sinf(self->scroll_pos) * (str_width - 200) / 2;
    }
    ctx_move_to(ctx, xpos, -40);
    ctx_text(ctx, self->artist);

    str_width = ctx_text_width(ctx, self->title);
    xpos = 0;
    if (str_width > 200) {
        xpos = ctx_sinf(self->scroll_pos) * (str_width - 200) / 2;
    }
    ctx_move_to(ctx, xpos, 64);
    ctx_text(ctx, self->title);

    ctx_font_size(ctx, 14);
    str_width = ctx_text_width(ctx, self->path);
    xpos = 0;
    if (str_width > 220) {
        xpos = ctx_sinf(self->scroll_pos) * (str_width - 220) / 2;
    }
    ctx_move_to(ctx, xpos, 14);
    ctx_gray(ctx, 0.6);
    ctx_text(ctx, self->path);

    if (!self->file) {
        ctx_rectangle(ctx, -100, 65, self->count * 200.0 / self->size, 55);
        if (self->in_buffering)
            ctx_rgba(ctx, 0.8, 0.2, 0.0, 1.0);
        else
            ctx_gray(ctx, 0.2);
        ctx_fill(ctx);
    }
}

static void mp3_think(st3m_media *media, float ms_elapsed) {
    mp3_state *self = (void *)media;

    if (self->file && self->control.seek >= 0) {
        if (self->control.seek > 1.0) {
            self->control.seek = 1.0;
        }
        float seek = self->control.seek * self->control.duration;
        fseek(self->file, seek, SEEK_SET);
        self->offset = seek;
        self->pos = 0;
        self->count = 0;
        self->control.time = 0;
        self->control.position = self->offset;
        self->control.seek = -1;
        mp3dec_init(&self->mp3d);
    }

    mp3_fetch_data(self);

    self->scroll_pos += ms_elapsed / 1000.0;

    if (self->in_buffering) {
        if (self->size - self->count > 0) return;
        self->in_buffering = 0;
    }

    if (self->control.paused) return;

    if (self->file) {
        self->control.position = self->offset;
        if (self->offset + 512 >= self->file_size)
            self->control.position = self->file_size;
    }

    if (!self->started) {
        self->started = 1;
        mp3_think(media, 100);
    }
    int samples_needed = (((st3m_pcm_queue_length() - st3m_pcm_queued()) / 2)) /
                         48000.0 * self->samplerate;

    int samples;
    mp3dec_frame_info_t info = {
        0,
    };
    if (samples_needed > 0 &&
        ((self->offset + 512 < self->file_size) || (!self->file))) {
        do {
            int16_t rendered[MINIMP3_MAX_SAMPLES_PER_FRAME];
            samples =
                mp3dec_decode_frame(&self->mp3d, self->data + self->pos,
                                    self->count - self->pos, rendered, &info);
            self->pos += info.frame_bytes;
            if (samples) {
                self->samplerate = info.hz;
                self->channels = info.channels;
                self->control.time += samples / (float)self->samplerate;
                st3m_pcm_queue_s16(self->samplerate, self->channels, samples,
                                   rendered);
            } else if (info.frame_bytes) {
                mp3_fetch_data(self);
            } else {
                break;
            }
            samples_needed -= (samples);
        } while (samples_needed > 0);
    }
}

static void mp3_destroy(st3m_media *media) {
    mp3_state *self = (void *)media;
    if (self->data) free(self->data);
    if (self->file) fclose(self->file);
    if (self->socket) {
        shutdown(self->socket, SHUT_RDWR);
        close(self->socket);
    }
    if (self->path) free(self->path);
    if (self->title) free(self->title);
    if (self->artist) free(self->artist);
    free(self);
}

typedef struct {
    char tag[3];
    char title[30];
    char artist[30];
    char album[30];
    char year[4];
    char comment[30];
    char genre[1];
    char pad[128];
} id3tag_t;

st3m_media *st3m_media_load_mp3(const char *path) {
    mp3_state *self = (mp3_state *)malloc(sizeof(mp3_state));
    if (!self) return NULL;
    memset(self, 0, sizeof(mp3_state));
    self->control.draw = mp3_draw;
    self->control.think = mp3_think;
    self->control.destroy = mp3_destroy;
    self->control.get_string = mp3_get_string;
    self->control.has_audio = true;
    self->samplerate = 44100;
    self->buffer_size = 32 * 1024;
    self->scroll_pos = 0;

    if (!strncmp(path, "http://", 7)) {
        int port = 80;
        char *hostname = strdup(path + 7);
        char *rest = NULL;
        self->buffer_size = 96 * 1024;
        rest = strchr(hostname, '/') + 1;
        strchr(hostname, '/')[0] = 0;
        if (strchr(hostname, ':')) {
            port = atoi(strchr(hostname, ':') + 1);
            strchr(hostname, ':')[0] = 0;
        }

        struct hostent *host;
        struct sockaddr_in addr;
        self->socket = socket(PF_INET, SOCK_STREAM, 0);
        if (self->socket < 0) {
            free(hostname);
            mp3_destroy((st3m_media *)self);
            return NULL;
        }
        int flag = 1;
        setsockopt(self->socket, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(int));
        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        host = gethostbyname(hostname);
        if (!host) {
            mp3_destroy((st3m_media *)self);
            free(hostname);
            return NULL;
        }
        addr.sin_addr.s_addr = ((long unsigned int **)host->h_addr_list)[0][0];

        if (connect(self->socket, (struct sockaddr *)&addr, sizeof(addr)) ==
            0) {
            char s[1024];
            sprintf(s, "GET /%s HTTP/1.1\r\n", rest);
            write(self->socket, s, strlen(s));
            sprintf(s, "Range: bytes=0-\r\n");
            write(self->socket, s, strlen(s));
            if (hostname) {
                sprintf(s, "Host: %s\r\n", hostname);
                write(self->socket, s, strlen(s));
            }
            sprintf(s, "User-Agent: flow3r\r\n");
            write(self->socket, s, strlen(s));
            sprintf(s, "\r\n");
            write(self->socket, s, strlen(s));
            fsync(self->socket);

            self->data = malloc(self->buffer_size);
            self->size = self->buffer_size;

            mp3dec_init(&self->mp3d);
            self->control.duration = -1;
            free(hostname);

            if (!self->data) {
                mp3_destroy((st3m_media *)self);
                return NULL;
            }

            self->in_buffering = 1;
            self->path = strdup(path);
            return (st3m_media *)self;
        }
        free(hostname);

        mp3_destroy((st3m_media *)self);
        return NULL;
    }
    st3m_media_tags_t *tags = st3m_media_get_tags(path);
    if (tags) {
        if (tags->title) self->title = strdup(tags->title);
        if (tags->artist) self->artist = strdup(tags->artist);
        self->year = tags->year;
        st3m_media_free_tags(tags);
    }

    self->file = fopen(path, "r");
    if (!self->file) {
        mp3_destroy((st3m_media *)self);
        return NULL;
    }
    fseek(self->file, 0, SEEK_END);
    self->file_size = ftell(self->file);

    self->data = malloc(self->buffer_size);
    if (!self->data) {
        mp3_destroy((st3m_media *)self);
        return NULL;
    }
    self->size = self->buffer_size;
    mp3dec_init(&self->mp3d);
    self->control.duration = self->file_size;

    self->path = strdup(path);
    if (!self->path) {
        mp3_destroy((st3m_media *)self);
        return NULL;
    }

    rewind(self->file);

    return (st3m_media *)self;
}

static uint32_t id3v2_decode_size(char *start, bool syncsafe) {
    uint32_t ret = 0;
    if (syncsafe) {
        for (int j = 0; j < 4; j++) {
            ret += (start[3 - j] & 0b1111111) << (7 * j);
        }
    } else {
        for (int j = 0; j < 4; j++) {
            ret += start[3 - j] << (8 * j);
        }
    }
    return ret;
}

static char *strndup_textframe(char *content, int len) {
    char *ret;
    if (content[0] == 1) {  // corrupt bytes should be assumed to be 0
        // utf-16:
        int string_start = 1;
        bool byte_flip = false;
        if (content[1] == ((char)0xFF) && content[2] == ((char)0xFE)) {
            string_start += 2;
        } else if (content[1] == ((char)0xFE) && content[2] == ((char)0xFF)) {
            string_start += 2;
            byte_flip = true;
        }
        int ascii_len =
            (len - string_start) /
            2;  // one extra byte is in there already, preventing round-downs
        ret = malloc(ascii_len + 1);
        if (!ret) return NULL;
        ret[ascii_len] = 0;
        for (int i = 0; i < ascii_len; i++) {
            if (content[string_start + 2 * i + 1 - byte_flip]) {
                ret[i] = '?';
            } else {
                ret[i] = content[string_start + 2 * i + byte_flip];
            }
        }
    } else {
        // iso-8859-1
        ret = strndup(&content[1], len - 1);
    }
    int ret_len = strlen(ret);
    // filter out high bit special chars
    for (int i = 0; i < ret_len; i++) {
        if (ret[i] & 0x80) ret[i] = '?';
    }
    return ret;
}

enum supported_tags { NONE, TITLE, ARTIST, ALBUM, TRACK_NUMBER, YEAR };

st3m_media_tags_t *audio_mp3_get_tags(const char *path) {
    // returns a new media_tags_t object with tag information
    // retrieved from file at path (or NULL). freeing is up to the user.
    FILE *file = fopen(path, "r");
    if (!file) return NULL;
    fseek(file, 0, SEEK_END);
    int file_size = ftell(file);

    st3m_media_tags_t *tags = calloc(1, sizeof(st3m_media_tags_t));
    if (!tags) return NULL;

    // ID3v1/ID3v1.1
    fseek(file, file_size - 128, SEEK_SET);
    id3tag_t id3;
    fread(&id3, 128, 1, file);
    if (id3.tag[0] == 'T' && id3.tag[1] == 'A' && id3.tag[2] == 'G') {
        tags->title = strndup(id3.title, 30);
        while (tags->title[strlen(tags->title) - 1] == ' ')
            tags->title[strlen(tags->title) - 1] = 0;

        tags->artist = strndup(id3.artist, 30);
        while (tags->artist[strlen(tags->artist) - 1] == ' ')
            tags->artist[strlen(tags->artist) - 1] = 0;

        tags->album = strndup(id3.album, 30);
        while (tags->album[strlen(tags->album) - 1] == ' ')
            tags->album[strlen(tags->album) - 1] = 0;

        tags->year = atoi(id3.year);

        if (!id3.comment[28]) {
            tags->track_number = id3.comment[29];
        }
        fclose(file);
        return tags;
    }

    // ID3v2
    fseek(file, 0, SEEK_SET);
    char buf[10];
    fread(buf, 10, 1, file);
    if (buf[0] == 'I' && buf[1] == 'D' && buf[2] == '3') {
        uint32_t frame_pos = 10;
        uint8_t version = buf[3];
        if (version < 2 || version > 4) {
            fclose(file);
            free(tags);
            return NULL;
        }
        uint32_t tag_size = 10 + id3v2_decode_size(&buf[6], version >= 3);
        if (buf[4] & 0b100000) {  // extended header
            fread(buf, 10, 1, file);
            frame_pos += id3v2_decode_size(&buf[0], version >= 3);
        }
        while (frame_pos < tag_size) {
            uint32_t frame_size = 0;
            fseek(file, frame_pos, SEEK_SET);
            if (version > 2) {
                fread(buf, 10, 1, file);
                frame_size = id3v2_decode_size(&buf[4], version >= 4);
                frame_pos += 10;
            } else {
                fread(buf, 6, 1, file);
                frame_size = id3v2_decode_size(&buf[3], false);
                frame_size >>= 8;
                frame_pos += 6;
            }
#if 0
            printf("\nframe pos: %lu, frame size: %lu, tag size: %lu\n", frame_pos, frame_size, tag_size);
            char tag[5];
            memcpy(tag, buf, 4);
            tag[4] = 0;
            printf("tag: %s\n", tag);
#endif

            if (frame_pos + frame_size > tag_size) break;

            enum supported_tags frame_tag = NONE;
            if (version > 2) {
                if (strncmp(buf, "TIT2", 4) == 0) {
                    frame_tag = TITLE;
                } else if (strncmp(buf, "TPE1", 4) == 0) {
                    frame_tag = ARTIST;
                } else if (strncmp(buf, "TRCK", 4) == 0) {
                    frame_tag = TRACK_NUMBER;
                } else if (strncmp(buf, "TYER", 4) == 0) {
                    frame_tag = YEAR;
                } else if (strncmp(buf, "TALB", 4) == 0) {
                    frame_tag = ALBUM;
                }
            } else {
                if (strncmp(buf, "TT2", 3) == 0) {
                    frame_tag = TITLE;
                } else if (strncmp(buf, "TP1", 3) == 0) {
                    frame_tag = ARTIST;
                } else if (strncmp(buf, "TRK", 3) == 0) {
                    frame_tag = TRACK_NUMBER;
                } else if (strncmp(buf, "TYE", 3) == 0) {
                    frame_tag = YEAR;
                } else if (strncmp(buf, "TAL", 3) == 0) {
                    frame_tag = ALBUM;
                }
            }
            if (frame_tag == NONE) continue;

            char *fbuf = malloc(
                frame_size);  // putting it on heap bc task stack may overflow
            if (!fbuf)
                continue;  // earlier, don't wanna worried about limits here
            if (fread(fbuf, 1, frame_size, file) != frame_size) {
                free(fbuf);
                break;
            }

            switch (frame_tag) {
                case TITLE:
                    tags->title = strndup_textframe(fbuf, frame_size);
                    break;
                case ARTIST:
                    tags->artist = strndup_textframe(fbuf, frame_size);
                    break;
                case TRACK_NUMBER:;
                    char *slashpos = strchr(fbuf, '/');
                    if (slashpos) *slashpos = 0;
                    tags->track_number = atoi(fbuf);
                    break;
                case YEAR:
                    tags->year = atoi(fbuf);
                    break;
                case ALBUM:
                    tags->album = strndup_textframe(fbuf, frame_size);
                    break;
                default:
                    break;  // should never be reached, just to make compiler
                            // happy
            }
            free(fbuf);
            if (tags->title && tags->artist && tags->track_number &&
                tags->year && tags->album)
                break;
            frame_pos += frame_size;
        }
        fclose(file);
        return tags;
    }

    free(tags);
    fclose(file);
    return NULL;
}

components/badge23/CMakeLists.txt

deleted100644 → 0
+0 −18
Original line number Diff line number Diff line
idf_component_register(
    SRCS
        apa102LEDStrip.c
        audio.c
        captouch.c
        display.c
        espan.c
        leds.c
        scope.c
        synth.c
        spio.c
    INCLUDE_DIRS
        include
    REQUIRES
        flow3r_bsp
        st3m
        espressif__led_strip
)

components/badge23/README.md

deleted100644 → 0
+0 −6
Original line number Diff line number Diff line
badge23/espan
===

Transitional component containing all custom C code for badge23, including drivers for peripherals and 'espan' application leftovers.

This will be likely split up into sub-components.
+0 −50
Original line number Diff line number Diff line
#include "badge23/apa102LEDStrip.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

void initLEDs(struct apa102LEDStrip *ledObject, short int numLEDs, unsigned char bytesPerLED, unsigned char globalBrightness)
{  
  ledObject->_numLEDs = numLEDs;
  ledObject->_bytesPerLED = bytesPerLED;
  ledObject->_endFrameLength = 1;//round( (numLEDs/2)/8 );
  ledObject->_frameLength = (1+numLEDs+ledObject->_endFrameLength)*bytesPerLED;
  ledObject->_globalBrightness = globalBrightness;
  ledObject->LEDs = (unsigned char *)malloc(ledObject->_frameLength*sizeof(unsigned char)); 
  
  //Start Frame
  ledObject->LEDs[0] = 0;
  ledObject->LEDs[1] = 0;
  ledObject->LEDs[2] = 0;
  ledObject->LEDs[3] = 0;
  //Driver frame+PIXEL frames
  for(ledObject->_counter=ledObject->_bytesPerLED; ledObject->_counter<ledObject->_frameLength-(ledObject->_endFrameLength*ledObject->_bytesPerLED); ledObject->_counter+=ledObject->_bytesPerLED)
  {
    ledObject->LEDs[ledObject->_counter] = ledObject->_globalBrightness;
    ledObject->LEDs[ledObject->_counter+1] = 0;
    ledObject->LEDs[ledObject->_counter+2] = 0;
    ledObject->LEDs[ledObject->_counter+3] = 0;
  }
  //END frames
  for(ledObject->_counter=ledObject->_frameLength-(ledObject->_endFrameLength*ledObject->_bytesPerLED); ledObject->_counter<ledObject->_frameLength; ledObject->_counter+=ledObject->_bytesPerLED)
  {
    ledObject->LEDs[ledObject->_counter] = 255;
    ledObject->LEDs[ledObject->_counter+1] = 255;
    ledObject->LEDs[ledObject->_counter+2] = 255;
    ledObject->LEDs[ledObject->_counter+3] = 255;
  }
}
void setPixel(struct apa102LEDStrip *ledObject, short int pixelIndex, unsigned char *pixelColour)
{
  ledObject->_counter = 4*(pixelIndex+1);
  ledObject->LEDs[ ledObject->_counter + 1 ] = pixelColour[2];
  ledObject->LEDs[ ledObject->_counter + 2 ] = pixelColour[1];
  ledObject->LEDs[ ledObject->_counter + 3 ] = pixelColour[0];
}
void getPixel(struct apa102LEDStrip *ledObject, short int pixelIndex, unsigned char *pixelColour)
{
  ledObject->_counter = 4*(pixelIndex+1);
  pixelColour[2] = ledObject->LEDs[ ledObject->_counter + 1 ];
  pixelColour[1] = ledObject->LEDs[ ledObject->_counter + 2 ];
  pixelColour[0] = ledObject->LEDs[ ledObject->_counter + 3 ];
}

components/badge23/audio.c

deleted100644 → 0
+0 −626

File deleted.

Preview size limit exceeded, changes collapsed.

components/badge23/display.c

deleted100644 → 0
+0 −110
Original line number Diff line number Diff line
#include "badge23/display.h"

#include <stdio.h>
#include <string.h>
#include <math.h>

#include "esp_log.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"


#include "../../usermodule/uctx/uctx/ctx.h"

#include "flow3r_bsp.h"
#include "st3m_gfx.h"


typedef struct {
    Ctx *ctx;
    st3m_framebuffer_desc_t *desc;
} ctx_target_t;

static void new_ctx_target(ctx_target_t *target, st3m_framebuffer_desc_t *desc) {
    Ctx *ctx = ctx_new_for_framebuffer(
        desc->buffer,
        FLOW3R_BSP_DISPLAY_WIDTH,
        FLOW3R_BSP_DISPLAY_HEIGHT,
        FLOW3R_BSP_DISPLAY_WIDTH * 2,
        CTX_FORMAT_RGB565_BYTESWAPPED
    );
    assert(ctx != NULL);

	int32_t offset_x = FLOW3R_BSP_DISPLAY_WIDTH / 2;
	int32_t offset_y = FLOW3R_BSP_DISPLAY_HEIGHT / 2;
    // rotate by 180 deg and translate x and y by 120 px to have (0,0) at the center of the screen
    ctx_apply_transform(ctx,-1,0,offset_x,0,-1,offset_y,0,0,1);

    target->ctx = ctx;
    target->desc = desc;
}

static ctx_target_t targets[ST3M_GFX_NBUFFERS];

static void display_loading_splash(ctx_target_t *target) {
    ctx_rgb(target->ctx, 0.157, 0.129, 0.167);
    ctx_rectangle(target->ctx, -120, -120, 240, 240);
    ctx_fill(target->ctx);
    
    ctx_move_to(target->ctx, 0, 0);
    ctx_rgb(target->ctx, 0.9, 0.9, 0.9);
    ctx_text_align(target->ctx, CTX_TEXT_ALIGN_CENTER);
    ctx_text_baseline(target->ctx, CTX_TEXT_BASELINE_ALPHABETIC);
    ctx_text(target->ctx, "Loading...");
}

static ctx_target_t *next_target(void) {
    st3m_framebuffer_desc_t *desc = st3m_gfx_framebuffer_get(portMAX_DELAY);
    if (targets[desc->num].ctx == NULL) {
        new_ctx_target(&targets[desc->num], desc);
    }

    return &targets[desc->num];
}

static bool initialized = false;
static ctx_target_t *sync_target = NULL;

void display_init() {
    // HACK: needed until we have new async gfx api.
    assert(ST3M_GFX_NBUFFERS == 1);

    st3m_gfx_init();
    for (int i = 0; i < ST3M_GFX_NBUFFERS; i++) {
        targets[i].ctx = NULL;
        targets[i].desc = NULL;
    }

	ctx_target_t *tgt = next_target();
    display_loading_splash(tgt);
    st3m_gfx_framebuffer_queue(tgt->desc);

	sync_target = next_target();
    flow3r_bsp_display_set_backlight(100);
    initialized = true;
}


void display_update(){
    if (!initialized) {
        return;
    }

    st3m_gfx_framebuffer_queue(sync_target->desc);
    ctx_target_t *tgt = next_target();
    assert(tgt == sync_target);
}

void display_set_backlight(uint8_t percent) {
    if (!initialized) {
        return;
    }
    flow3r_bsp_display_set_backlight(percent);
}

Ctx *display_global_ctx(void) {
    if (!initialized) {
        return NULL;
    }
    return sync_target->ctx;
}
 No newline at end of file

components/badge23/espan.c

deleted100644 → 0
+0 −136
Original line number Diff line number Diff line
#include "badge23/captouch.h"
#include "badge23/audio.h"
#include "badge23/leds.h"
#include "badge23/display.h"
#include "badge23/spio.h"
#include "badge23/lock.h"

#include "flow3r_bsp.h"

#include "esp_log.h"
#include "driver/i2c.h"
#include "driver/spi_master.h"
#include <freertos/timers.h>

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdint.h>

static const char *TAG = "espan";

#define I2C_MASTER_NUM              0                          /*!< I2C master i2c port number, the number of i2c peripheral interfaces available will depend on the chip */
#define I2C_MASTER_FREQ_HZ          400000                     /*!< I2C master clock frequency */
#define I2C_MASTER_TX_BUF_DISABLE   0                          /*!< I2C master doesn't need buffer */
#define I2C_MASTER_RX_BUF_DISABLE   0                          /*!< I2C master doesn't need buffer */

#if defined(CONFIG_BADGE23_HW_GEN_P3) || defined(CONFIG_BADGE23_HW_GEN_P4) || defined(CONFIG_BADGE23_HW_GEN_P6)
#define CONFIG_I2C_MASTER_SDA 2
#define CONFIG_I2C_MASTER_SCL 1

#elif defined(CONFIG_BADGE23_HW_GEN_P1)
#define CONFIG_I2C_MASTER_SDA 10
#define CONFIG_I2C_MASTER_SCL 9

#else
#error "i2c not implemented for this badge generation"
#endif

static QueueHandle_t i2c_queue = NULL;
static QueueHandle_t slow_system_status_queue = NULL;
static uint8_t dummy_data;

static esp_err_t i2c_master_init(void)
{
    int i2c_master_port = I2C_MASTER_NUM;

    i2c_config_t conf = {
        .mode = I2C_MODE_MASTER,
        .sda_io_num = CONFIG_I2C_MASTER_SDA,
        .scl_io_num = CONFIG_I2C_MASTER_SCL,
        .sda_pullup_en = GPIO_PULLUP_ENABLE,
        .scl_pullup_en = GPIO_PULLUP_ENABLE,
        .master.clk_speed = I2C_MASTER_FREQ_HZ,
    };

    i2c_param_config(i2c_master_port, &conf);

    return i2c_driver_install(i2c_master_port, conf.mode, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0);
}

#define CAPTOUCH_POLLING_PERIOD 10
#define SLOW_SYSTEM_STATUS_PERIOD 100
static uint8_t hw_init_done = 0;

void i2c_timer(TimerHandle_t data){
    xQueueSend(i2c_queue, &dummy_data, 0);
}

void i2c_task(void * data){
    while(1){
        xQueueReceive(i2c_queue, &dummy_data, portMAX_DELAY);
        captouch_read_cycle();
        update_button_state();
    }
}

void slow_system_status_timer(TimerHandle_t data){
    xQueueSend(slow_system_status_queue, &dummy_data, 0);
}

void slow_system_status_task(void * data){
    while(1){
        xQueueReceive(slow_system_status_queue, &dummy_data, portMAX_DELAY);
        //read out stuff like jack detection, battery status, usb connection etc.
        audio_update_jacksense();
        leds_update_hardware();
    }
}

void locks_init(){
    mutex_i2c = xSemaphoreCreateMutex();
    mutex_LED = xSemaphoreCreateMutex();
}

void os_app_main(void)
{
    // Initialize display first as that gives us a nice splash screen.
    display_init();

    locks_init();
    ESP_LOGI(TAG, "Starting on %s...", flow3r_bsp_hw_name);
    ESP_ERROR_CHECK(i2c_master_init());
    ESP_LOGI(TAG, "I2C initialized successfully");

    audio_init();
    leds_init();
    init_buttons();
    captouch_init();
    spio_badge_link_disable(255);

    captouch_force_calibration();


    i2c_queue = xQueueCreate(1,1);

    TaskHandle_t i2c_task_handle;
    xTaskCreatePinnedToCore(&i2c_task, "I2C task", 4096, NULL, configMAX_PRIORITIES-1, &i2c_task_handle, 0);

    TimerHandle_t i2c_timer_handle = xTimerCreate("I2C timer", pdMS_TO_TICKS(CAPTOUCH_POLLING_PERIOD), pdTRUE, (void *) 0, *i2c_timer);
    if( xTimerStart(i2c_timer_handle, 0 ) != pdPASS) ESP_LOGI(TAG, "I2C timer initialization failed");

    slow_system_status_queue = xQueueCreate(1,1);

    TaskHandle_t slow_system_status_task_handle;
    xTaskCreatePinnedToCore(&slow_system_status_task, "slow system status task", 4096, NULL, configMAX_PRIORITIES-2, &slow_system_status_task_handle, 0);

    TimerHandle_t slow_system_status_timer_handle = xTimerCreate("slow system status timer", pdMS_TO_TICKS(SLOW_SYSTEM_STATUS_PERIOD), pdTRUE, (void *) 0, *slow_system_status_timer);
    if( xTimerStart(slow_system_status_timer_handle, 0 ) != pdPASS) ESP_LOGI(TAG, "I2C task initialization failed");

    hw_init_done = 1;
}

uint8_t hardware_is_initialized(){
    return hw_init_done;
}
Original line number Diff line number Diff line
#ifndef DEF_apa102LEDStrip
#define DEF_apa102LEDStrip

struct apa102LEDStrip
{
    unsigned char *LEDs;
    short int _frameLength;
    short int _endFrameLength;
    short int _numLEDs;
    unsigned char _bytesPerLED;
    short int _counter;
    unsigned char _globalBrightness;
};
void initLEDs(struct apa102LEDStrip *ledObject, short int numLEDs, unsigned char bytesPerLED, unsigned char globalBrightness);
void setPixel(struct apa102LEDStrip *ledObject, short int pixelIndex, unsigned char *pixelColour);
void getPixel(struct apa102LEDStrip *ledObject, short int pixelIndex, unsigned char *pixelColour);
#endif
+0 −129
Original line number Diff line number Diff line
#pragma once
#include <stdint.h>

/* GENERAL INFORMATION
 *
 * petal index:     0 is the top petal above the USB-C jack, increases ccw so that
 *                  bottom petals are uneven and top petals even.
 *                  TODO: LEDs are indexed differently, this should be harmonized
 *                  in the impending API refactor.
 *
 * captouch data:   full uint16_t range per stage, higher values indicate touch.
 * pad index:       defined in captouch.c
 *
 *
 * IOU: the internals are still subject to major restructuring and are not
 * documented as of yet. will do once the data structures actually make sense
 * and are not duct tape upon duct tape.
 */

/* polls data from both captouch chips and processes it, either by updating
 * the captouch data exposed to the user or running a calibration cycle.
 *
 * the captouch chips has updated their registers every 9.2ms, so the fn
 * should be called every 10ms or so.
 *
 * this will be replaced someday by an interrupt event triggered system,
 * but this would ideally already implement configuration switching to
 * optimize latency by grouping pads and to expose the unused pad which
 * is a nontrivial task for another day.
 */
void captouch_read_cycle(void);

/* the captouch chip can generate an "afe" offset in the analog domain before
 * the ADC to optimize the readout range. according to the datasheet this should
 * be in the middle of the 16bit delta sigma ADC range (without much reasoning
 * supplied), however we found that having a higher range is beneficial.
 * 
 * the calibration cycle is optimizing the afe coefficients so that the output of
 * the "untouched" pads is close to the target set with this with this function/
 *
 * default target: 6000, manufacturer recommendation: 32676
 */
void captouch_set_calibration_afe_target(uint16_t target);

/* starts a a calibration cycle which is intended to run when the captouch
 * pads are not being touched. the cycle consists of two parts:
 * 
 * 1) optimize the afe coefficients (see captouch_set_calibration_afe_target)
 *
 * 2) with the new afe coefficients applied, average the readings in the untouched
 *    state into a software calibration list  which is normally subtracted from the
 *    captouch outputs. this makes up for the limited resolution of the of the afe
 *    coefficient calibration.
 */
void captouch_force_calibration();

/* indicates if a calibration cycle is currently active. the readings for
 * captouch_read_cycle and captouch_get_petal_* during a calibration cycle.
 *
 * 1: calibration cycle active
 * 0: calibration cycle inactive
 */
uint8_t captouch_calibration_active();


/* returns uint16_t which encodes each petal "touched" state as the bit
 * corresponding to the petal index. "touched" is determined by checking if
 * any of the pads belonging to the petal read a value higher than their
 * calibration value plus their threshold (see captouch_set_petal_pad_threshold)
 */
uint16_t read_captouch(void);

/* sets threshold for a petal pad above which read_captouch considers a pad as
 * touched.
 *
 * petal: petal index
 * pad:   pad index
 * thres: threshold value
 */
void captouch_set_petal_pad_threshold(uint8_t petal, uint8_t pad, uint16_t thres);

/* returns last read captouch value from a petal pad without subtracting its
 * calibration reference. typically only needed for debugging.
 *
 * petal: petal index
 * pad:   pad index
 */
uint16_t captouch_get_petal_pad_raw(uint8_t petal, uint8_t pad);

/* returns calibration reference for a petal pad.
 *
 * petal: petal index
 * pad:   pad index
 */
uint16_t captouch_get_petal_pad_calib_ref(uint8_t petal, uint8_t pad);

/* returns calibrated value from petal. clamps below 0.
 *
 * petal: petal index
 * pad:   pad index
 */
uint16_t captouch_get_petal_pad(uint8_t petal, uint8_t pad);

/* estimates the azimuthal finger position on a petal in arbitrary units.
 * returns 0 if hardware doesn't support this.
 * 
 * petal: petal index
 * pad:   pad index
 */
int32_t captouch_get_petal_phi(uint8_t petal);

/* estimates the radial finger position on a petal in arbitrary units.
 * returns 0 if hardware doesn't support this.
 * 
 * petal: petal index
 * pad:   pad index
 */
int32_t captouch_get_petal_rad(uint8_t petal);


/* configures the captouch chips, prefills internal structs etc.
 */
void captouch_init(void);

/* TODO: didn't look into what it does, never used it, just copied it from
 * the hardware verification firmware along with the rest. didn't break it
 * _intentionally_ but never tested it either.
 */
void captouch_print_debug_info(void);

components/badge23/leds.c

deleted100644 → 0
+0 −351

File deleted.

Preview size limit exceeded, changes collapsed.

components/badge23/scope.c

deleted100644 → 0
+0 −88

File deleted.

Preview size limit exceeded, changes collapsed.

components/badge23/spio.c

deleted100644 → 0
+0 −409

File deleted.

Preview size limit exceeded, changes collapsed.

components/badge23/synth.c

deleted100644 → 0
+0 −201

File deleted.

Preview size limit exceeded, changes collapsed.

components/badge23/tags

deleted100644 → 0
+0 −162

File deleted.

Preview size limit exceeded, changes collapsed.