diff --git a/.clang-tidy b/.clang-tidy index df52357d..88ca6c54 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,6 +1,7 @@ Checks: '*, -altera-unroll-loops, -llvmlibc-callee-namespace, + -llvmlibc-implementation-in-namespace, -llvmlibc-restrict-system-libc-headers, -llvm-header-guard, -llvm-namespace-comment, @@ -8,6 +9,7 @@ Checks: '*, -google-runtime-int, -google-readability-namespace-comments, -fuchsia-statically-constructed-objects, + -cppcoreguidelines-prefer-member-initializer, -cppcoreguidelines-pro-bounds-array-to-pointer-decay, -cppcoreguidelines-pro-bounds-constant-array-index, -cppcoreguidelines-pro-type-static-cast-downcast, diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 778fe9cb..1bb315f7 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -12,7 +12,9 @@ // Set *default* container specific settings.json values on container create. "settings": { - "terminal.integrated.shell.linux": "/bin/bash" + "terminal.integrated.shell.linux": "/bin/bash", + "editor.formatOnSave": true, + "clang-format.executable": "clang-format-12" }, // Add the IDs of extensions you want installed when the container is created. @@ -33,4 +35,4 @@ // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. // "remoteUser": "vscode" "remoteUser": "infinitime" -} \ No newline at end of file +} diff --git a/.github/ISSUE_TEMPLATE/bug-report.yaml b/.github/ISSUE_TEMPLATE/bug-report.yaml index f0fb076e..6e9f6606 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.yaml +++ b/.github/ISSUE_TEMPLATE/bug-report.yaml @@ -9,6 +9,7 @@ body: *Please, before opening a bug report, check if similar issues already exist. In that case, use those issues to provide your feedback instead.* - type: checkboxes attributes: + label: Verification options: - label: I searched for similar bug reports and found none was relevant. required: true diff --git a/.github/ISSUE_TEMPLATE/feature-request.yaml b/.github/ISSUE_TEMPLATE/feature-request.yaml index 26e4fa0f..a35bbfed 100644 --- a/.github/ISSUE_TEMPLATE/feature-request.yaml +++ b/.github/ISSUE_TEMPLATE/feature-request.yaml @@ -9,6 +9,7 @@ body: *Please, before opening a feature request, check if similar issues already exist. In that case, use those issues to provide your feedback instead.* - type: checkboxes attributes: + label: Verification options: - label: I searched for similar feature request and found none was relevant. required: true diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 3b753a37..58a63931 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -113,7 +113,7 @@ jobs: run: | mkdir -p build cd build - cmake -DARM_NONE_EABI_TOOLCHAIN_PATH=${{ runner.temp }}/arm-none-eabi -DNRF5_SDK_PATH=${{ runner.temp }}/nrf5_sdk -DUSE_OPENOCD=1 -DBUILD_DFU=1 ../ + cmake -G Ninja -DARM_NONE_EABI_TOOLCHAIN_PATH=${{ runner.temp }}/arm-none-eabi -DNRF5_SDK_PATH=${{ runner.temp }}/nrf5_sdk -DUSE_OPENOCD=1 -DBUILD_DFU=1 ../ ######################################################################################### # Make and Upload DFU Package @@ -125,8 +125,7 @@ jobs: - name: Make pinetime-mcuboot-app run: | - cd build - make pinetime-mcuboot-app + cmake --build build --target pinetime-mcuboot-app - name: Unzip DFU package run: | @@ -144,8 +143,7 @@ jobs: - name: Make pinetime-app run: | - cd build - make pinetime-app + cmake --build build --target pinetime-app - name: Upload standalone firmware uses: actions/upload-artifact@v2 @@ -158,8 +156,7 @@ jobs: - name: Make pinetime-recovery run: | - cd build - make pinetime-recovery + cmake --build build --target pinetime-recovery ######################################################################################### # Finish diff --git a/.gitignore b/.gitignore index 39fb672b..0474017b 100644 --- a/.gitignore +++ b/.gitignore @@ -43,3 +43,7 @@ Testing/Temporary/ #VSCODE .vscode/.cortex-debug.registers.state.json .vscode/.cortex-debug.peripherals.state.json + +#build files +src/nRF5_SDK_15.3.0_59ac345 +src/arm-none-eabi diff --git a/.gitmodules b/.gitmodules index 815fc022..8d302ae7 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,3 +4,6 @@ [submodule "src/libs/littlefs"] path = src/libs/littlefs url = https://github.com/littlefs-project/littlefs.git +[submodule "src/libs/QCBOR"] + path = src/libs/QCBOR + url = https://github.com/laurencelundblade/QCBOR.git diff --git a/CMakeLists.txt b/CMakeLists.txt index a8ecb81f..b5880666 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(pinetime VERSION 1.6.0 LANGUAGES C CXX ASM) +project(pinetime VERSION 1.7.1 LANGUAGES C CXX ASM) set(CMAKE_C_STANDARD 99) set(CMAKE_CXX_STANDARD 14) diff --git a/README.md b/README.md index 765aa863..ae315f24 100644 --- a/README.md +++ b/README.md @@ -1,81 +1,33 @@ -# InfiniTime +# [InfiniTime](https://github.com/InfiniTimeOrg/InfiniTime) [![Build PineTime Firmware](https://github.com/InfiniTimeOrg/InfiniTime/workflows/Build%20PineTime%20Firmware/badge.svg?branch=master)](https://github.com/InfiniTimeOrg/InfiniTime/actions) -![InfiniTime logo](images/infinitime-logo.jpg "InfiniTime Logo") +![InfiniTime logo](images/infinitime-logo-small.jpg "InfiniTime Logo") -The goal of this project is to design an open-source firmware for the [Pinetime smartwatch](https://www.pine64.org/pinetime/) : - - - Code written in **modern C++**; - - Build system based on **CMake**; - - Based on **[FreeRTOS 10.0.0](https://freertos.org)** real-time OS. - - Using **[LittleVGL/LVGL 7](https://lvgl.io/)** as UI library... - - ... and **[NimBLE 1.3.0](https://github.com/apache/mynewt-nimble)** as BLE stack. +Fast open-source firmware for the [PineTime smartwatch](https://www.pine64.org/pinetime/) with many features, written in modern C++. ## New to InfiniTime? - - [Getting started with InfiniTime 1.0 (quick user guide, update bootloader and InfiniTime,...)](doc/gettingStarted/gettingStarted-1.0.md) - - [Flash, upgrade (OTA), time synchronization,...](doc/gettingStarted/ota-gadgetbridge-nrfconnect.md) + - [Getting started with InfiniTime](doc/gettingStarted/gettingStarted-1.0.md) + - [Updating the software](doc/gettingStarted/updating-software.md) + - [About the firmware and bootloader](doc/gettingStarted/about-software.md) +### Companion apps + - [Gadgetbridge](https://gadgetbridge.org/) (Android) + - [AmazFish](https://openrepos.net/content/piggz/amazfish/) (SailfishOS) + - [Siglo](https://github.com/alexr4535/siglo) (Linux) + - [InfiniLink](https://github.com/xan-m/InfiniLink) **[Experimental]** (iOS) -## Overview +## Development -![Pinetime screens](images/1.0.0/collage.png "PinetimeScreens") - -As of now, here is the list of achievements of this project: - - - Fast and optimized LCD driver - - BLE communication - - Rich user interface via display, touchscreen and pushbutton - - Time synchronization via BLE - - Notification via BLE - - Heart rate measurements - - Step counting - - Wake-up on wrist rotation - - Quick actions - * Disable vibration on notification - * Brightness settings - * Flashlight - * Settings - - 3 watch faces: - * Digital - * Analog - * [PineTimeStyle](https://wiki.pine64.org/wiki/PineTimeStyle) - - Multiple 'apps' : - * Music (control the playback of music on your phone) - * Heart rate (measure your heart rate) - * Navigation (displays navigation instructions coming from the companion app) - * Notification (displays the last notification received) - * Paddle (single player pong-like game) - * Twos (2048 clone game) - * Stopwatch - * Steps (displays the number of steps taken) - * Timer (set a countdown timer that will notify you when it expires) - * Metronome (vibrates to a given bpm with a customizable beats per bar) - - User settings: - * Display timeout - * Wake-up condition - * Time format (12/24h) - * Default watch face - * Daily step goal - * Battery status - * Firmware validation - * System information - - Supported by 3 companion apps (development is in progress): - * [Gadgetbridge](https://codeberg.org/Freeyourgadget/Gadgetbridge/) (on Android via F-Droid) - * [Amazfish](https://openrepos.net/content/piggz/amazfish) (on SailfishOS and Linux) - * [Siglo](https://github.com/alexr4535/siglo) (on Linux) - * **[Experimental]** [WebBLEWatch](https://hubmartin.github.io/WebBLEWatch/) Synchronize time directly from your web browser. [video](https://youtu.be/IakiuhVDdrY) - * **[Experimental]** [InfiniLink](https://github.com/xan-m/InfiniLink) (on iOS) - - OTA (Over-the-air) update via BLE - - [Bootloader](https://github.com/JF002/pinetime-mcuboot-bootloader) based on [MCUBoot](https://www.mcuboot.com) - -## Documentation - -### Develop - [Rough structure of the code](doc/code/Intro.md) - [How to implement an application](doc/code/Apps.md) - [Generate the fonts and symbols](src/displayapp/fonts/README.md) - [Creating a stopwatch in Pinetime(article)](https://pankajraghav.com/2021/04/03/PINETIME-STOPCLOCK.html) + - [Tips on designing an app UI](doc/ui_guidelines.md) + +### Contributing + - [How to contribute?](/doc/contribute.md) + - [Coding conventions](/doc/coding-convention.md) ### Build, flash and debug @@ -84,16 +36,11 @@ As of now, here is the list of achievements of this project: - [Files included in the release notes](doc/filesInReleaseNotes.md) - [Build the project](doc/buildAndProgram.md) - [Flash the firmware using OpenOCD and STLinkV2](doc/openOCD.md) + - [Flash the firmware using SWD interface](doc/SWD.md) - [Build the project with Docker](doc/buildWithDocker.md) - [Build the project with VSCode](doc/buildWithVScode.md) - [Bootloader, OTA and DFU](./bootloader/README.md) - [Stub using NRF52-DK](./doc/PinetimeStubWithNrf52DK.md) - - Logging with JLink RTT. - - Using files from the releases - -### Contribute - - - [How to contribute ?](doc/contribute.md) ### API @@ -103,30 +50,6 @@ As of now, here is the list of achievements of this project: - [Memory analysis](./doc/MemoryAnalysis.md) -### Using the firmware - - - [Integration with Gadgetbridge](doc/companionapps/Gadgetbridge.md) - - [Integration with AmazFish](doc/companionapps/Amazfish.md) - - [Firmware update, OTA](doc/companionapps/NrfconnectOTA.md) - -## TODO - contribute - -This project is far from being finished, and there are still a lot of things to do for this project to become a firmware usable by the general public. - -Here a quick list out of my head of things to do for this project: - - - Improve BLE communication stability and reliability - - Improve OTA and MCUBoot bootloader - - Add more functionalities : Alarm, chronometer, configuration, activities, heart rate logging, games,... - - Add more BLE functionalities : call notifications, agenda, configuration, data logging,... - - Measure power consumption and improve battery life - - Improve documentation, take better pictures and video than mine - - Improve the UI - - Create companion app for multiple OSes (Linux, Android, iOS) and platforms (desktop, ARM, mobile). Do not forget the other devices from Pine64 like [the Pinephone](https://www.pine64.org/pinephone/) and the [Pinebook Pro](https://www.pine64.org/pinebook-pro/). - - Design a simple CI (preferably self-hosted and easy to reproduce). - -Do not hesitate to clone/fork the code, hack it and create pull-requests. I'll do my best to review and merge them :) - ## Licenses This project is released under the GNU General Public License version 3 or, at your option, any later version. diff --git a/bootloader/README.md b/bootloader/README.md index 9f99602b..1a02ebdc 100644 --- a/bootloader/README.md +++ b/bootloader/README.md @@ -115,8 +115,6 @@ sudo dfu.py -z /home/jf/nrf52/bootloader/dfu.zip -a --leg **Note** : dfu.py is a slightly modified version of [this repo](https://github.com/daniel-thompson/ota-dfu-python). -See [this page](../doc/CompanionApps/NrfconnectOTA.md) for more info about OTA with NRFConect - ### Firmware validation Once the OTA is done, InfiniTime will reset the watch to apply the update. When the watch reboots, the new firmware is running. @@ -126,12 +124,12 @@ If the new firmware is working correctly, open the application menu and tap on t Firmware validation application in the menu: -![Firmware Validation App](../doc/CompanionApps/firmwareValidationApp.jpg "Firmware Validation App") +![Firmware Validation App](../doc/bootloader/firmwareValidationApp.jpg "Firmware Validation App") The firmware is not validated yet. Tap 'Validate' to validate it, or 'Reset' to rollback to the previous version. -![Firmware Not Validated](../doc/CompanionApps/firmwareNoValidated.jpg "Firmware Not Validated") +![Firmware Not Validated](../doc/bootloader/firmwareNoValidated.jpg "Firmware Not Validated") The firmware is validated! -![Firmware Validated](../doc/CompanionApps/firmwareValidated.jpg "Firmware Validated") +![Firmware Validated](../doc/bootloader/firmwareValidated.jpg "Firmware Validated") diff --git a/doc/BLEFS.md b/doc/BLEFS.md new file mode 100644 index 00000000..519d84a9 --- /dev/null +++ b/doc/BLEFS.md @@ -0,0 +1,167 @@ +# BLE FS +--- + +The BLE FS protocol in InfiniTime is mostly Adafruit's BLE file transfer protocol, as described in [adafruit/Adafruit_CircuitPython_BLE_File_Transfer](https://github.com/adafruit/Adafruit_CircuitPython_BLE_File_Transfer). There are some deviations, such as the status codes. These will be described later in the document. + +--- + +## UUIDs + +There are two relevant UUIDs in this protocol: the version characteristic, and the raw transfer characteristic. + +### Version + +UUID: `adaf0100-4669-6c65-5472-616e73666572` + +The version characteristic returns the version of the protocol to which the sender adheres. It returns a single unsigned 32-bit integer. The latest version at the time of writing this is 4. + +### Transfer + +UUID: `adaf0200-4669-6c65-5472-616e73666572` + +The transfer characteristic is responsible for all the data transfer between the client and the watch. It supports write and notify. Writing a packet on the characteristic results in a response via notify. + +--- + +## Usage + +The separator for paths is `/`, and absolute paths must start with `/`. + +All of the following commands and responses are transferred via the transfer characteristic + +### Read file + +To begin reading a file, a header must first be sent. The header packet should be formatted like so: + +- Command (single byte): `0x10` +- 1 byte of padding +- Unsigned 16-bit integer encoding the length of the file path. +- Unsigned 32-bit integer encoding the location at which to start reading the first chunk. +- Unsigned 32-bit integer encoding the amount of bytes to be read. +- File path: UTF-8 encoded string that is _not_ null terminated. + +To continue reading the file after this initial packet, the following packet should be sent until all the data has been received. No close command is required after the data has been received. + +- Command (single byte): `0x12` +- Status: `0x01` +- 2 bytes of padding +- Unsigned 32-bit integer encoding the location at which to start reading the next chunk. +- Unsigned 32-bit integer encoding the amount of bytes to be read. This may be different from the size in the header. + +Both of these commands receive the following response: + +- Command (single byte): `0x11` +- Status (signed 8-bit integer) +- 2 bytes of padding +- Unsigned 32-bit integer encoding the offset of this chunk +- Unsigned 32-bit integer encoding the total size of the file +- Unsigned 32-bit integer encoding the amount of data in the current chunk +- Contents of the current chunk + +### Write file + +To begin writing to a file, a header must first be sent. The header packet should be formatted like so: + +- Command (single byte): `0x20` +- 1 byte of padding +- Unsigned 16-bit integer encoding the length of the file path. +- Unsigned 32-bit integer encoding the location at which to start writing to the file. +- Unsigned 64-bit integer encoding the unix timestamp with nanosecond resolution. This will be used as the modification time. At the time of writing, this is not implemented in InfiniTime, but may be in the future. +- Unsigned 32-bit integer encoding the size of the file that will be sent +- File path: UTF-8 encoded string that is _not_ null terminated. + +To continue reading the file after this initial packet, the following packet should be sent until all the data has been sent and a response had been received with 0 free space. No close command is required after the data has been received. + +- Command (single byte): `0x22` +- Status: `0x01` +- 2 bytes of padding. +- Unsigned 32-bit integer encoding the location at which to write the next chunk. +- Unsigned 32-bit integer encoding the amount of bytes to be written. +- Data + +Both of these commands receive the following response: + +- Command (single byte): `0x21` +- Status (signed 8-bit integer) +- 2 bytes of padding +- Unsigned 32-bit integer encoding the current offset in the file +- Unsigned 64-bit integer encoding the unix timestamp with nanosecond resolution. This will be used as the modification time. At the time of writing, this is not implemented in InfiniTime, but may be in the future. +- Unsigned 32-bit integer encoding the amount of data the client can send until the file is full. + +### Delete file + +- Command (single byte): `0x30` +- 1 byte of padding +- Unsigned 16-bit integer encoding the length of the file path. +- File path: UTF-8 encoded string that is _not_ null terminated. + +The response to this packet will be as follows: + +- Command (single byte): `0x31` +- Status (signed 8-bit integer) + +### Make directory + +- Command (single byte): `0x40` +- 1 byte of padding +- Unsigned 16-bit integer encoding the length of the file path. +- 4 bytes of padding +- Unsigned 64-bit integer encoding the unix timestamp with nanosecond resolution. +- File path: UTF-8 encoded string that is _not_ null terminated. + +The response to this packet will be as follows: + +- Command (single byte): `0x41` +- Status (signed 8-bit integer) +- 6 bytes of padding +- Unsigned 64-bit integer encoding the unix timestamp with nanosecond resolution. + +### List directory + +Paths returned by this command are relative to the path given in the request + +- Command (single byte): `0x50` +- 1 byte of padding +- Unsigned 16-bit integer encoding the length of the file path. +- File path: UTF-8 encoded string that is _not_ null terminated. + +The response to this packet will be as follows. Responses will be sent until the final entry, which will have entry number == total entries + +- Command (single byte): `0x51` +- Status (signed 8-bit integer) +- Unsigned 16-bit integer encoding the length of the file path. +- Unsigned 32-bit integer encoding the entry number +- Unsigned 32-bit integer encoding the total amount of entries +- Flags: unsigned 32-bit integer + + Bit 0: Set when entry is a directory + + Bits 1-7: Reserved +- Unsigned 64-bit integer encoding the unix timestamp of the modification time with nanosecond resolution +- Unsigned 32-bit integer encoding the size of the file +- Path: UTF-8 encoded string that is _not_ null terminated. + +### Move file or directory + +- Command (single byte): `0x60` +- 1 byte of padding +- Unsigned 16-bit integer encoding the length of the old path +- Unsigned 16-bit integer encoding the length of the new path +- Old path: UTF-8 encoded string that is _not_ null terminated. +- 1 byte of padding +- Newpath: UTF-8 encoded string that is _not_ null terminated. + +The response to this packet will be as follows: + +- Command (single byte): `0x61` +- Status (signed 8-bit integer) + +--- + +## Deviations + +This section describes the differences between Adafruit's spec and InfiniTime's implementation. + +### Status codes + +The status codes returned by InfiniTime are a signed 8-bit integer, rather than an unsigned one as described in the spec. + +InfiniTime uses LittleFS error codes rather than the ones described in the spec. Those codes can be found in [lfs.h](https://github.com/littlefs-project/littlefs/blob/master/lfs.h#L70). \ No newline at end of file diff --git a/doc/MemoryAnalysis.md b/doc/MemoryAnalysis.md index 7304e3f3..376f98f6 100644 --- a/doc/MemoryAnalysis.md +++ b/doc/MemoryAnalysis.md @@ -32,13 +32,13 @@ In this analysis, I used [Linkermapviz](https://github.com/PromyLOPh/linkermapvi ### Linkermapviz -[Linkermapviz](https://github.com/PromyLOPh/linkermapviz) parses the MAP file and displays its content in a graphical way into an HTML page: +[Linkermapviz](https://github.com/PromyLOPh/linkermapviz) parses the MAP file and displays its content on an HTML page as a graphic: ![linkermapviz](./memoryAnalysis/linkermapviz.png) -Using this tool, you can easily see the size of each symbol relative to the other one, and check what is using most of the space,... +Using this tool, you can compare the relative size of symbols. This can be helpful for checking memory usage at a glance. -Also, as Linkermapviz is written in Python, you can easily modify it to adapt it to your firmware, export data in another format,... For example, [I modified it to parse the contents of the MAP file and export it in a CSV file](https://github.com/InfiniTimeOrg/InfiniTime/issues/313#issuecomment-842338620). I could later on open this file in LibreOffice Calc and use sort/filter functionality to search for specific symbols in specific files... +Also, as Linkermapviz is written in Python, you can easily modify and adapt it to your firmware or export data in another format. For example, [here it is modified to parse the contents of the MAP file and export it in a CSV file](https://github.com/InfiniTimeOrg/InfiniTime/issues/313#issuecomment-842338620). This file could later be opened in LibreOffice Calc where sort/filter functionality could be used to search for specific symbols in specific files... ### Puncover [Puncover](https://github.com/HBehrens/puncover) is another useful tools that analyses the binary file generated by the compiler (the .out file that contains all debug information). It provides valuable information about the symbols (data and code): name, position, size, max stack of each functions, callers, callees... @@ -46,8 +46,8 @@ Also, as Linkermapviz is written in Python, you can easily modify it to adapt it Puncover is really easy to install: - - clone the repo and cd into the cloned directory - - setup a venv + - Clone the repo and cd into the cloned directory + - Setup a venv - `python -m virtualenv venv` - `source venv/bin/activate` - Install : `pip install .` @@ -60,13 +60,13 @@ Puncover is really easy to install: - Launch a browser at http://localhost:5000/ ### Analysis -Using the MAP file and tools, we can easily see what symbols are using most of the FLASH memory space. In this case, with no surprise, fonts and graphics are the biggest flash space consumer. +Using the MAP file and tools, we can easily see what symbols are using most of the flash memory. In this case, unsuprisingly, fonts and graphics are the largest use of flash memory. ![Puncover](./memoryAnalysis/puncover-all-symbols.png) -This way, you can easily check what needs to be optimized : we should find a way to store big static data (like fonts and graphics) in the external flash memory, for example. +This way, you can easily check what needs to be optimized. We should find a way to store big static data (like fonts and graphics) in the external flash memory, for example. -It's always a good idea to check the flash memory space when working on the project : this way, you can easily check that your developments are using a reasonable amount of space. +It's always a good idea to check the flash memory space when working on the project. This way, you can easily check that your developments are using a reasonable amount of space. ### Links - Analysis with linkermapviz : https://github.com/InfiniTimeOrg/InfiniTime/issues/313#issuecomment-842338620 @@ -210,7 +210,7 @@ NRF_LOG_INFO("heap : %d", m.uordblks); ``` #### Analysis -According to my experimentation, InfiniTime uses ~6000bytes of heap most of the time. Except when the Navigation app is launched, where the heap usage increases to... more than 9500 bytes (meaning that the heap overflows and could potentially corrupt the stack!!!). This is a bug that should be fixed in #362. +According to my experimentation, InfiniTime uses ~6000bytes of heap most of the time. Except when the Navigation app is launched, where the heap usage exceeds 9500 bytes (meaning that the heap overflows and could potentially corrupt the stack). This is a bug that should be fixed in #362. To know exactly what's consuming heap memory, you can `wrap` functions like `malloc()` into your own functions. In this wrapper, you can add logging code or put breakpoints: @@ -245,7 +245,7 @@ Using this technique, I was able to trace all malloc calls at boot (boot -> digi - https://www.embedded.com/mastering-stack-and-heap-for-system-reliability-part-3-avoiding-heap-errors/ ## LVGL -I did a deep analysis of the usage of the buffer dedicated for lvgl (managed by lv_mem). +I did a deep analysis of the usage of the buffer dedicated to lvgl (managed by lv_mem). This buffer is used by lvgl to allocated memory for drivers (display/touch), screens, themes, and all widgets created by the apps. The usage of this buffer can be monitored using this code : @@ -256,7 +256,7 @@ lv_mem_monitor(&mon); NRF_LOG_INFO("\t Free %d / %d -- max %d", mon.free_size, mon.total_size, mon.max_used); ``` -The most interesting metric is `mon.max_used` which specifies the maximum number of bytes that were used from this buffer since the initialization of lvgl. +The most interesting metric is `mon.max_used` which specifies the maximum number of bytes used from this buffer since the initialization of lvgl. According to my measurements, initializing the theme, display/touch driver and screens cost **4752** bytes! Then, initializing the digital clock face costs **1541 bytes**. For example a simple lv_label needs **~140 bytes** of memory. diff --git a/doc/MotionService.md b/doc/MotionService.md index 0d0a5514..7cec3fba 100644 --- a/doc/MotionService.md +++ b/doc/MotionService.md @@ -3,13 +3,13 @@ The motion service exposes step count and raw X/Y/Z motion value as READ and NOTIFY characteristics. ## Service -The service UUID is **00020000-78fc-48fe-8e23-433b3a1942d0** +The service UUID is **00030000-78fc-48fe-8e23-433b3a1942d0** ## Characteristics -### Step count (UUID 00020001-78fc-48fe-8e23-433b3a1942d0) +### Step count (UUID 00030001-78fc-48fe-8e23-433b3a1942d0) The current number of steps represented as a single `uint32_t` (4 bytes) value. -### Raw motion values (UUID 00020002-78fc-48fe-8e23-433b3a1942d0) +### Raw motion values (UUID 00030002-78fc-48fe-8e23-433b3a1942d0) The current raw motion values. This is a 3 `int16_t` array: - [0] : X diff --git a/doc/NavigationService.md b/doc/NavigationService.md index fd81d0bf..5a4f69e0 100644 --- a/doc/NavigationService.md +++ b/doc/NavigationService.md @@ -1,6 +1,6 @@ # Navigation Service ## Introduction -The navigation ble service provides 4 characteristics to allow the the watch to display navigation instructions from a companion application. The intended purpose is when performing some outdoor activities, for example running or cycling. +The navigation ble service provides 4 characteristics to allow the watch to display navigation instructions from a companion application. This service is intended to be used when performing some outdoor activities, for example running or cycling. The 4 characteristics are: flag (string) - Upcoming icon name @@ -22,7 +22,7 @@ This is a client supplied string describing the upcoming instruction such as "At This is a short string describing the distance to the upcoming instruction such as "50 m". ## Progress (UUID 00010004-78fc-48fe-8e23-433b3a1942d0) -The percent complete in a uint8. The watch displays this as an overall progress in a progress bar. +The percent complete in a uint8. The watch displays this as an overall progress in a progress bar. ## Full icon list * arrive diff --git a/doc/PinetimeStubWithNrf52DK.md b/doc/PinetimeStubWithNrf52DK.md index c4857921..dcaad69b 100644 --- a/doc/PinetimeStubWithNrf52DK.md +++ b/doc/PinetimeStubWithNrf52DK.md @@ -1,11 +1,11 @@ # Build a stub for PineTime using NRF52-DK -[NRF52-DK](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52-DK) is the official developpment kit for NRF52832 SoC from Nordic Semiconductor. +[NRF52-DK](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52-DK) is the official developpment kit for the NRF52832 SoC from Nordic Semiconductor used in the PineTime. -It can be very useful for PineTime development: - * You can use it embedded JLink SWD programmer/debugger to program and debug you code on the PineTime - * As it's based on the same SoC than the PineTime, you can program it to actually run the same code than the PineTime. +This development kit can be very useful for PineTime development: + * You can use its embedded JLink SWD programmer/debugger to program and debug your code on the PineTime + * As it's based on the same SoC than the PineTime, you can program it to actually run the same code as the PineTime. -This page is about the 2nd point : we will build a stub that will allow us to run the same code than the one you could run on the PineTime. This will allow you to work more easily if you don't have a PineTime dev kit around, if you don't want to modify your dev kit for SWD programming, or if you want to use some feature from the DK (like power measurement). +This page is about the 2nd point. We will build a stub that will allow us to run the same code you can run on the PineTime. This will allow you to work more easily if you don't have a PineTime dev kit around, if you don't want to modify your dev kit for SWD programming, or if you want to use some feature from the NRF52-DK (like power measurement). This stub only implements the display, the button and the BLE radio. The other features from the pintime are missing: * heart rate sensor @@ -41,7 +41,7 @@ You just need to make the following connections: | P0.13 | Button IN (D3 in my case) | | GND | GND | -You also need to enable the I/O expander to disconnect pins from buttons and led on the NRF52-DK and leave them available on the pin headers: +You also need to enable the I/O expander to disconnect pins from the buttons and LED on the NRF52-DK and leave them available on the pin headers: | NRF52 -DK | NRF52- DK | | --------- | --------- | diff --git a/doc/SPI-LCD-driver.md b/doc/SPI-LCD-driver.md index f787aab7..29f3bbfa 100644 --- a/doc/SPI-LCD-driver.md +++ b/doc/SPI-LCD-driver.md @@ -1,6 +1,6 @@ # The SPI LCD driver ## Introduction -The LCD controller that drive the display of the Pinetime is the Sitronix ST7789V. This controller is easy to integrate with an MCU thanks to its SPI interface, and has some interesting features like: +The LCD controller that drives the display of the Pinetime is the [Sitronix ST7789V](https://wiki.pine64.org/images/5/54/ST7789V_v1.6.pdf). This controller is easy to integrate with an MCU thanks to its SPI interface, and has some interesting features like: - an on-chip display data RAM that can store the whole framebuffer - partial screen update - hardware assisted vertical scrolling diff --git a/doc/SWD.md b/doc/SWD.md new file mode 100644 index 00000000..155983b3 --- /dev/null +++ b/doc/SWD.md @@ -0,0 +1,14 @@ +# How to flash InfiniTime using the SWD interface +Download the files **bootloader.bin**, **image-x.y.z.bin** and **pinetime-graphics-x.y.z.bin** from the release page: + +![Image file](imageFile.png) + +The bootloader reads a boot logo from the external SPI flash memory. The first step consists of flashing a tool in the MCU that will flash the boot logo into this SPI flash memory. This first step is optional but recommended (the bootloader will display garbage on screen for a few second if you don't do it). +Using your SWD tool, flash **pinetime-graphics-x.y.z.bin** at offset **0x0000**. Reset the MCU and wait for a few seconds until the logo is completely drawn on the display. + +Then, using your SWD tool, flash these file at the following offsets: + + - bootloader.bin : **0x0000** + - image-x.y.z.bin : **0x8000** + +Reset and voilĂ , you're running InfiniTime on your PineTime! diff --git a/doc/ble.md b/doc/ble.md index 8573166f..d2502636 100644 --- a/doc/ble.md +++ b/doc/ble.md @@ -2,13 +2,14 @@ ## Introduction This page describes the BLE implementation and API built in this firmware. -**Note** : I'm a beginner in BLE related technologies and the information in this document reflects my current knowledge and understanding of the BLE stack. This information might be erroneous or incomplete. Feel free to submit a PR if you think you can improve it. +**Note**: I'm a beginner in BLE related technologies and the information in this document reflects my current knowledge and understanding of the BLE stack. This information might be erroneous or incomplete. Feel free to submit a PR if you think you can improve it. --- ### Table of Contents - [BLE Connection](#ble-connection) +- [BLE FS](#ble-fs) - [BLE UUIDs](#ble-uuids) - [BLE Services](#ble-services) - [CTS](#cts) @@ -51,6 +52,13 @@ If **CTS** is detected, it'll request the current time to the companion applicat --- +## BLE FS + +The documentation for BLE FS can be found here: +[BLEFS.md](./BLEFS.md) + +--- + ## BLE UUIDs When possible, InfiniTime tries to implement BLE services defined by the BLE specification. @@ -72,12 +80,16 @@ The following custom services are implemented in InfiniTime: * [Navigation Service](NavigationService.md) : 00010000-78fc-48fe-8e23-433b3a1942d0 - - Since InfiniTime 0.13 - * Call characteristic (extension to the Alert Notification Service): 00020001-78fc-48fe-8e23-433b3a1942d0 - - - - Since InfiniTime 1.7: - * [Motion Service](MotionService.md) : 00030000-78fc-48fe-8e23-433b3a1942d0 +- Since InfiniTime 0.13 + * Call characteristic (extension to the Alert Notification Service): 00020001-78fc-48fe-8e23-433b3a1942d0 + + +- Since InfiniTime 1.7: + * [Motion Service](MotionService.md): 00030000-78fc-48fe-8e23-433b3a1942d0 + + +- Since InfiniTime 1.8: + * [Weather Service](/src/components/ble/weather/WeatherService.h): 00040000-78fc-48fe-8e23-433b3a1942d0 --- @@ -108,11 +120,11 @@ Reading a value from the firmware version characteristic will yield a UTF-8 enco #### Battery Level -Reading from the battery level characteristic yields a single byte of data. This byte can be converted to an unsigned 8-bit integer which will be the battery percentage. This characteristic allows notify for updates as the value changes. +Reading from the battery level characteristic yields a single byte of data. This byte can be converted to an unsigned 8-bit integer which will be the battery percentage. This characteristic allows notifications for updates as the value changes. #### Heart Rate -Reading from the heart rate characteristic yields two bytes of data. I am not sure of the function of the first byte. It appears to always be zero. The second byte can be converted to an unsigned 8-bit integer which is the current heart rate. This characteristic also allows notify for updates as the value changes. +Reading from the heart rate characteristic yields two bytes of data. I am not sure of the function of the first byte. It appears to always be zero. The second byte can be converted to an unsigned 8-bit integer which is the current heart rate. This characteristic also allows notifications for updates as the value changes. --- @@ -285,4 +297,4 @@ This characteristic expects a particular format: - Microsecond divided by `1e6*256` (`uint8`) - Binary 0001 (`uint8`) -Write all of these together, encoded as little-endian, to the current time characteristic. \ No newline at end of file +Write all of these together, encoded as little-endian, to the current time characteristic. diff --git a/doc/companionapps/firmwareNoValidated.jpg b/doc/bootloader/firmwareNoValidated.jpg similarity index 100% rename from doc/companionapps/firmwareNoValidated.jpg rename to doc/bootloader/firmwareNoValidated.jpg diff --git a/doc/companionapps/firmwareValidated.jpg b/doc/bootloader/firmwareValidated.jpg similarity index 100% rename from doc/companionapps/firmwareValidated.jpg rename to doc/bootloader/firmwareValidated.jpg diff --git a/doc/companionapps/firmwareValidationApp.jpg b/doc/bootloader/firmwareValidationApp.jpg similarity index 100% rename from doc/companionapps/firmwareValidationApp.jpg rename to doc/bootloader/firmwareValidationApp.jpg diff --git a/doc/branches.md b/doc/branches.md index ef280f40..3c86375f 100644 --- a/doc/branches.md +++ b/doc/branches.md @@ -1,7 +1,7 @@ # Branches The branching model of this project is based on the workflow named [Git flow](https://nvie.com/posts/a-successful-git-branching-model/). -It is based on 2 main branches: +The project is based on 2 main branches: - **master** : this branch is always ready to be deployed. It means that at any time, we should be able to build the branch and release a new version of the application. - **develop** : this branch contains the latest development that will be integrated in the next release once it's considered as stable. @@ -9,4 +9,4 @@ New features should be implemented in **feature branches** created from **develo To release a new version of the application, when develop is considered stable, a **release** branch is created from **develop**. This can be considered as a *release candidate* branch. When everything is OK, this release branch is merged into **master** and the release is generated (a tag is applied to git, the release note is finalized, binaries are built,...) from **master**. -Git flow also supports the creation of **hotfix** branches when a bug is discovered in a released version. The **hotfix** branch is created from **master** and will be used only to implement a fix to this bug. Multiple hotfix branches can be created for the same release if more than one bugs are discovered. \ No newline at end of file +Git flow also supports the creation of **hotfix** branches when a bug is discovered in a released version. The **hotfix** branch is created from **master** and will be used only to implement a fix to this bug. Multiple hotfix branches can be created for the same release if multiple bugs are discovered. \ No newline at end of file diff --git a/doc/buildAndProgram.md b/doc/buildAndProgram.md index 3686871a..feef9f6d 100644 --- a/doc/buildAndProgram.md +++ b/doc/buildAndProgram.md @@ -4,7 +4,7 @@ To build this project, you'll need: - A cross-compiler : [ARM-GCC (9-2020-q2-update)](https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm/downloads/9-2020-q2-update) - The NRF52 SDK 15.3.0 : [nRF-SDK v15.3.0](https://developer.nordicsemi.com/nRF5_SDK/nRF5_SDK_v15.x.x/nRF5_SDK_15.3.0_59ac345.zip) - The Python 3 modules `cbor`, `intelhex`, `click` and `cryptography` modules for the `mcuboot` tool (see [requirements.txt](../tools/mcuboot/requirements.txt)) - - To to keep the system clean a python virtual environment (`venv`) can be used to install the python modules into + - To keep the system clean, you can install python modules into a python virtual environment (`venv`) ```sh python -m venv .venv source .venv/bin/activate @@ -260,4 +260,4 @@ Finally, merge them together with **mergehex**: This file must be flashed at offset **0x00** of the internal memory of the NRF52832. #### spinor.bin -This file is the MCUBoot image of the last stable version of the recovery firmware. It must be flashed at offset **0x00** of the external SPINOR flash memory. \ No newline at end of file +This file is the MCUBoot image of the last stable version of the recovery firmware. It must be flashed at offset **0x00** of the external SPINOR flash memory. diff --git a/doc/code/Apps.md b/doc/code/Apps.md index 7c2d7a05..f067b58b 100644 --- a/doc/code/Apps.md +++ b/doc/code/Apps.md @@ -1,14 +1,15 @@ # Apps This page will teach you: -- what apps in InfiniTime are +- what screens and apps are in InfiniTime - how to implement your own app ## Theory -Apps are the things you can launch from the app selection you get by swiping up. -At the moment, settings and even the app launcher itself or the clock are implemented very similarly, this might change in the future though. + +The user interface of InfiniTime is made up of **screens**. +Screens that are opened from the app launcher are considered **apps**. Every app in InfiniTime is it's own class. -An instance of the class is created when the app is launched and destroyed when the user exits the app. -They run inside the "displayapp" task (briefly discussed [here](./Intro.md)). +An instance of the class is created when the app is launched, and destroyed when the user exits the app. +Apps run inside the "displayapp" task (briefly discussed [here](./Intro.md)). Apps are responsible for everything drawn on the screen when they are running. By default, apps only do something (as in a function is executed) when they are created or when a touch event is detected. @@ -20,30 +21,24 @@ A destructor is needed to clean up LVGL and restore any changes (for example re- App classes can override `bool OnButtonPushed()`, `bool OnTouchEvent(TouchEvents event)` and `bool OnTouchEvent(uint16_t x, uint16_t y)` to implement their own functionality for those events. If an app only needs to display some text and do something upon a touch screen button press, it does not need to override any of these functions, as LVGL can also handle touch events for you. -If you have any doubts, you can always look at how the other apps are doing things. +If you have any doubts, you can always look at how the other apps function for reference. ### Continuous updating -If your app needs to be updated continuously, yo can do so by overriding the `Refresh()` function in your class +If your app needs to be updated continuously, you can do so by overriding the `Refresh()` function in your class and calling `lv_task_create` inside the constructor. -An example call could look like this:
-`taskRefresh = lv_task_create(RefreshTaskCallback, LV_DISP_DEF_REFR_PERIOD, LV_TASK_PRIO_MID, this);`
+ +An example call could look like this: +```cpp +taskRefresh = lv_task_create(RefreshTaskCallback, LV_DISP_DEF_REFR_PERIOD, LV_TASK_PRIO_MID, this); +``` + With `taskRefresh` being a member variable of your class and of type `lv_task_t*`. Remember to delete the task again using `lv_task_del`. -The function `RefreshTaskCallback` is inherited from screen and just calls your `Refresh` function. - -### Apps with multiple screens -InfiniTime provides a mini-library in [displayapp/screens/ScreenList.h](/src/displayapp/screens/ScreenList.h) -which makes it relatively easy to add multiple screens to your app. -To use it, #include it in the header file of your app and add a ScreenList member to your class. -The template argument should be the number of screens you need. -You will also need to add `CreateScreen` functions that return `std::unique_ptr` -to your class, one for every screen you have. -There are still some things left to to that I won't cover here. -To figure them out, have a look at the "apps" ApplicationList, Settings and SystemInfo. - +The function `RefreshTaskCallback` is inherited from `Screen` and just calls your `Refresh` function. ## Creating your own app -A minimal app could look like this:
+A minimal app could look like this: + MyApp.h: ```cpp #pragma once @@ -66,13 +61,13 @@ namespace Pinetime { MyApp.cpp: ```cpp -#include "MyApp.h" +#include "displayapp/screens/MyApp.h" #include "displayapp/DisplayApp.h" using namespace Pinetime::Applications::Screens; MyApp::MyApp(DisplayApp* app) : Screen(app) { - lv_obj_t* title = lv_label_create(lv_scr_act(), NULL); + lv_obj_t* title = lv_label_create(lv_scr_act(), nullptr); lv_label_set_text_static(title, "My test application"); lv_label_set_align(title, LV_LABEL_ALIGN_CENTER); lv_obj_align(title, lv_scr_act(), LV_ALIGN_CENTER, 0, 0); @@ -95,12 +90,10 @@ Now, go to the function `DisplayApp::LoadApp` and add another case to the switch The case will be the id you gave your app earlier. If your app needs any additional arguments, this is the place to pass them. -If you want your app to be launched from the regular app launcher, go to [displayapp/screens/ApplicationList.cpp](/src/displayapp/screens/ApplicationList.cpp). -Add your app to one of the `CreateScreen` functions, or add another `CreateScreen` function if there are no empty spaces for your app.
-If your app is a setting, do the same procedure in [displayapp/screens/settings/Settings.cpp](/src/displayapp/screens/settings/Settings.cpp). +If you want to add your app in the app launcher, add your app in [displayapp/screens/ApplicationList.cpp](/src/displayapp/screens/ApplicationList.cpp) to one of the `CreateScreen` functions, or add another `CreateScreen` function if there are no empty spaces for your app. If your app is a setting, do the same procedure in [displayapp/screens/settings/Settings.cpp](/src/displayapp/screens/settings/Settings.cpp). You should now be able to [build](../buildAndProgram.md) the firmware and flash it to your PineTime. Yay! Please remember to pay attention to the [UI guidelines](../ui_guidelines.md) -when designing an app that you want to include in mainstream InfiniTime. +when designing an app that you want to be included in InfiniTime. diff --git a/doc/code/Intro.md b/doc/code/Intro.md index 762102fe..23b3ade1 100644 --- a/doc/code/Intro.md +++ b/doc/code/Intro.md @@ -21,11 +21,12 @@ Both functions are located inside [systemtask/SystemTask.cpp](/src/systemtask/Sy It also starts the **task "displayapp"**, which is responsible for launching and running apps, controlling the screen and handling touch events (or forwarding them to the active app). You can find the "displayapp" task inside [displayapp/DisplayApp.cpp](/src/displayapp/DisplayApp.cpp). There are also other tasks that are responsible for Bluetooth ("ll" and "ble" inside [libs/mynewt-nimble/porting/npl/freertos/src/nimble_port_freertos.c](/src/libs/mynewt-nimble/porting/npl/freertos/src/nimble_port_freertos.c)) -and periodic tasks like heartrate measurements ([heartratetask/HeartRateTask.cpp](/src/heartratetask/HeartRateTask.cpp)).
+and periodic tasks like heartrate measurements ([heartratetask/HeartRateTask.cpp](/src/heartratetask/HeartRateTask.cpp)). + While it is possible for you to create your own task when you need it, it is recommended to just add functionality to `SystemTask::Work()` if possible. -If you absolutely need to create another task, try to guess how much [stack space](https://www.freertos.org/FAQMem.html#StackSize) (in words/4-byte packets) +If you absolutely need to create another task, try to estimate how much [stack space](https://www.freertos.org/FAQMem.html#StackSize) (in words/4-byte packets) it will need instead of just typing in a large-ish number. -You can use the define `configMINIMAL_STACK_SIZE` which is currently set to 120 words. +You can use `configMINIMAL_STACK_SIZE` which is currently set to 120 words. ## Controllers Controllers in InfiniTime are singleton objects that can provide access to certain resources to apps. diff --git a/doc/coding-convention.md b/doc/coding-convention.md new file mode 100644 index 00000000..7198fa4f --- /dev/null +++ b/doc/coding-convention.md @@ -0,0 +1,41 @@ +# Coding convention + +## Language + +The language of this project is **C++**, and all new code must be written in C++. (Modern) C++ provides a lot of useful tools and functionalities that are beneficial for embedded software development like `constexpr`, `template` and anything that provides zero-cost abstraction. + +C code is accepted if it comes from another library like FreeRTOS, NimBLE, LVGL or the NRF-SDK. + +## Coding style + +The most important rule to follow is to try to keep the code as easy to read and maintain as possible. + +Using an autoformatter is highly recommended, but make sure it's configured properly. + +There are preconfigured autoformatter rules for: + + * CLion (IntelliJ) in [.idea/codeStyles/Project.xml](/.idea/codeStyles/Project.xml) + * `clang-format` + +Also use `clang-tidy` to check the code for other issues. + +If there are no preconfigured rules for your IDE, you can use one of the existing ones to configure your IDE. + + - **Indentation** : 2 spaces, no tabulation + - **Opening brace** at the end of the line + - **Naming** : Choose self-describing variable name + - **class** : PascalCase + - **namespace** : PascalCase + - **variable** : camelCase, **no** prefix/suffix ('_', 'm_',...) for class members + - **Include guard** : `#pragma once` (no `#ifdef __MODULE__ / #define __MODULE__ / #endif`) + - **Includes** : + - files from the project : `#include "relative/path/to/the/file.h"` + - external files and std : `#include ` + - use includes relative to included directories like `src`, not relative to the current file. Don't do: `#include "../file.h"` + - Only use [primary spellings for operators and tokens](https://en.cppreference.com/w/cpp/language/operator_alternative) + - Use auto sparingly. Don't use auto for [fundamental/built-in types](https://en.cppreference.com/w/cpp/language/types) and [fixed width integer types](https://en.cppreference.com/w/cpp/types/integer), except when initializing with a cast to avoid duplicating the type name. + - Examples: + - `auto* app = static_cast(instance);` + - `auto number = static_cast(variable);` + - `uint8_t returnValue = MyFunction();` + - Use nullptr instead of NULL diff --git a/doc/companionapps/Amazfish.md b/doc/companionapps/Amazfish.md deleted file mode 100644 index 90ad20c2..00000000 --- a/doc/companionapps/Amazfish.md +++ /dev/null @@ -1,16 +0,0 @@ -# Amazfish -[Amazfish](https://openrepos.net/content/piggz/amazfish) is a companion app that supports many smartwatches and activity trackers running on [SailfishOS](https://sailfishos.org/). - -## Features -The following features are implemented: - - Scanning & detection of Pinetime-JF / InfiniTime - - Connection / disconnection - - Time synchronization - - Notifications - - Music control - - Navigation with Puremaps - -## Demo -[This video](https://seafile.codingfield.com/f/21c5d023452740279e36/) shows how to connect to the Pinetime and control the playback of the music on the phone. -Amazfish and Sailfish OS are running on the [Pinephone](https://www.pine64.org/pinephone/), another awesome device from Pine64. - diff --git a/doc/companionapps/Gadgetbridge.md b/doc/companionapps/Gadgetbridge.md deleted file mode 100644 index 974e2828..00000000 --- a/doc/companionapps/Gadgetbridge.md +++ /dev/null @@ -1,13 +0,0 @@ -# Integration with Gadgetbridge -[Gadgetbridge](https://gadgetbridge.org/) is an Android application that supports many smartwatches and fitness trackers. - -The integration of InfiniTime (previously Pinetime-JF) is now merged into the master branch (https://codeberg.org/Freeyourgadget/Gadgetbridge/) and initial support is available [starting with version 0.47](https://codeberg.org/Freeyourgadget/Gadgetbridge/src/branch/master/CHANGELOG.md). Note that the official version is only available on F-Droid (as of May 2021), and the unofficial fork available on the Play Store is outdated and does not support Infinitime. - -## Features -The following features are implemented: - - Scanning & detection of Pinetime-JF / InfiniTime - - Connection / disconnection - - Notifications - -## Demo -[This video](https://seafile.codingfield.com/f/0a2920b9d765462385e4/) shows how to scan, connect, send notification (using the debug screen) and disconnect from the Pinetime. diff --git a/doc/companionapps/NrfconnectOTA.md b/doc/companionapps/NrfconnectOTA.md deleted file mode 100644 index 0fa3cd03..00000000 --- a/doc/companionapps/NrfconnectOTA.md +++ /dev/null @@ -1,12 +0,0 @@ -# OTA using NRFConnect -[NRFConnect](https://www.nordicsemi.com/Software-and-tools/Development-Tools/nRF-Connect-for-mobile) is a powerful application (running on Android and iOS) which allows to scan and connect to BLE devices. - -## Features - - Scanning, connect, disconnect - - Time synchronization - - OTA - -InfiniTime implements the Nordic DFU protocol for the OTA functionality. NRFConnect also supports this protocol. - -# Demo -[This video](https://seafile.codingfield.com/f/a52b69683a05472a90c7/) shows how to use NRFConnect to update the firmware running on the Pinetime. \ No newline at end of file diff --git a/doc/contribute.md b/doc/contribute.md index 595a5996..f2a4aeaa 100644 --- a/doc/contribute.md +++ b/doc/contribute.md @@ -14,10 +14,6 @@ As the documentation is part of the source code, you can submit your improvement You want to fix a bug, add a cool new functionality or improve the code? See *How to submit a pull request below*. -## Spread the word - -The Pinetime is a cool open source project that deserves to be known. Talk about it around you, on social networks, on your blog,... and let people know that we are working on an open source firmware for a smartwatch! - # How to submit a pull request? ## TL;DR @@ -25,7 +21,7 @@ The Pinetime is a cool open source project that deserves to be known. Talk about - Create a branch from develop - Work on a single subject in this branch. Create multiple branches/pulls-requests if you want to work on multiple subjects (bugs, features,...) - Test your modifications on the actual hardware - - Check the code formatting against our coding conventions and [clang-format](../.clang-format) and [clang-tidy](../.clang-tidy) + - Check your code against the [coding conventions](/doc/coding-convention.md) and [clang-format](../.clang-format) and [clang-tidy](../.clang-tidy) - Clean your code and remove files that are not needed - Write documentation related to your new feature if applicable - Create a pull request and write a great description about it: what does your PR do, why, how,... Add pictures and video if possible @@ -38,9 +34,9 @@ If you want to fix a bug, add functionality or improve the code, you'll first ne When your feature branch is ready, **make sure it actually works** and **do not forget to write documentation** about it if it's relevant. -**Creating a pull request containing modifications that haven't been tested is strongly discouraged.** If, for any reason, you cannot test your modifications but want to publish them anyway, **please mention it in the description**. This way, other contributors might be willing to test it and provide feedback about your code. +**Creating a pull request containing modifications that haven't been tested is strongly discouraged.** If for any reason you cannot test your modifications, but want to publish them anyway, **please mention it in the description**. This way, other contributors might be willing to test it and provide feedback about your code. -Also, before submitting your PR, check the coding style of your code against the **coding conventions** detailed below. This project also provides [clang-format](../.clang-format) and [clang-tidy](../.clang-tidy) configuration files. You can use them to ensure correct formatting of your code. +Before submitting a PR, check your code against the [coding conventions](/doc/coding-convention.md). This project also provides [clang-format](../.clang-format) and [clang-tidy](../.clang-tidy) configuration files. You should use them to ensure correct formatting of your code. Don't forget to check the files you are going to commit and remove those which aren't necessary (config files from your IDE, for example). Remove old comments, commented code,... @@ -50,54 +46,16 @@ Other contributors can post comments about the pull request, maybe ask for more Once the pull request is reviewed and accepted, it'll be merged into **develop** and will be released in the next version of the firmware. -## Why all these rules? +## Why all these rules? -Reviewing pull requests is a **very time consuming task** for the creator of this project ([JF002](https://github.com/JF002)) and for other contributors who take the time to review them. Everything you do to make reviewing easier will **get your PR merged faster**. +Reviewing pull requests is a **very time consuming task**. Everything you do to make reviewing easier will **get your PR merged faster**. -When reviewing PRs, the author and contributors will first look at the **description**. If it's easy to understand what the PR does, why the modification is needed or interesting and how it's done, a good part of the work is already done : we understand the PR and its context. +Reviewers will first look at the **description**. If it's easy to understand what the PR does, why the modification is needed or interesting and how it's done, a good part of the work is already done : we understand the PR and its context. -Then, reviewing **a few files that were modified for a single purpose** is a lot more easier than to review 30 files modified for many reasons (bug fix, UI improvements, typos in doc,...), even if all these changes make sense. Also, it's possible that we agree on some modification but not on some other, so we won't be able to merge the PR because of the changes that are not accepted. +Reviewing **a few files that were modified for a single purpose** is a lot easier than reviewing 30 files modified for many reasons (bug fix, UI improvements, typos in doc,...), even if all the changes make sense. Also, it's possible that we agree on some modification but not on another, so we won't be able to merge the PR because of the changes that are not accepted. -We do our best to keep the code as consistent as possible. If the formatting of the code in your PR is not consistent with our code base, we'll ask you to review it, which will take more time. +The code base should be kept as consistent as possible. If the formatting of your code is not consistent with the rest of the code base, we'll ask you to review it. -The last step of the review consists of **testing** the modification. If it doesn't work out of the box, we'll ask your to review your code and to ensure that it works as expected. +Lastly the changes are tested. If it doesn't work out of the box, we'll ask you to review your code and to ensure that it works as expected. It's totally normal for a PR to need some more work even after it was created, that's why we review them. But every round trip takes time, so it's good practice to try to reduce them as much as possible by following those simple rules. - -# Coding convention - -## Language - -The language of this project is **C++**, and all new code must be written in C++. (Modern) C++ provides a lot of useful tools and functionalities that are beneficial for embedded software development like `constexpr`, `template` and anything that provides zero-cost abstraction. - -C code is accepted if it comes from another library like FreeRTOS, NimBLE, LVGL or the NRF-SDK. - -## Coding style - -The most important rule to follow is to try to keep the code as easy to read and maintain as possible. - -Using an autoformatter is highly recommended, but make sure it's configured properly. - -There are preconfigured autoformatter rules for: - - * CLion (IntelliJ) in .idea/codeStyles/Project.xml - -If there are no preconfigured rules for your IDE, you can use one of the existing ones to configure your IDE. - - - **Indentation** : 2 spaces, no tabulation - - **Opening brace** at the end of the line - - **Naming** : Choose self-describing variable name - - **class** : PascalCase - - **namespace** : PascalCase - - **variable** : camelCase, **no** prefix/suffix ('_', 'm_',...) for class members - - **Include guard** : `#pragma once` (no `#ifdef __MODULE__ / #define __MODULE__ / #endif`) - - **Includes** : - - files from the project : `#include "relative/path/to/the/file.h"` - - external files and std : `#include ` - - Only use [primary spellings for operators and tokens](https://en.cppreference.com/w/cpp/language/operator_alternative) - - Use auto sparingly. Don't use auto for [fundamental/built-in types](https://en.cppreference.com/w/cpp/language/types) and [fixed width integer types](https://en.cppreference.com/w/cpp/types/integer), except when initializing with a cast to avoid duplicating the type name. - - Examples: - - `auto* app = static_cast(instance);` - - `auto number = static_cast(variable);` - - `uint8_t returnValue = MyFunction();` - - Use nullptr instead of NULL diff --git a/doc/gettingStarted/about-software.md b/doc/gettingStarted/about-software.md new file mode 100644 index 00000000..e935d938 --- /dev/null +++ b/doc/gettingStarted/about-software.md @@ -0,0 +1,26 @@ +# Firmware, InfiniTime, Bootloader, Recovery firmware, OTA, DFU... What is it? + +You may have already encountered these words by reading the announcement, release notes, or [the wiki guide](https://wiki.pine64.org/wiki/Upgrade_PineTime_to_InfiniTime_1.0.0) and you may find them confusing if you're not familiar with the project. + +A **firmware** is software running on the embedded hardware of a device. + +InfiniTime has three distinct firmwares: + + - **[InfiniTime](https://github.com/InfiniTimeOrg/InfiniTime)** is the operating system. + - **[The bootloader](https://github.com/JF002/pinetime-mcuboot-bootloader)** is responsible for safely applying firmware updates and runs before booting into InfiniTime. + - **The recovery firmware** is a special *application firmware* than can be loaded by the bootloader on user request. This firmware can be useful in case of serious issue, when the main application firmware cannot perform an OTA update correctly. + +**OTA** (**O**ver **T**he **A**ir) refers to updating of the firmware over BLE (**B**luetooth **L**ow **E**nergy). This is a functionality that allows the user to update the firmware on their device wirelessly. + +**DFU** (**D**evice **F**irmware **U**pdate) is the file format and protocol used to send the update of the firmware to the watch over-the-air. InfiniTime implements the (legacy) DFU protocol from Nordic Semiconductor (NRF). + +## Bootloader + +Most of the time, the bootloader just runs without your intervention (updating and loading the firmware). + +However, you can use the bootloader to rollback to the previous firmware, or load the recovery firmware using the push button: + + - Press and hold the button until the pine cone is drawn in **blue** to force the rollback of the previous version of the firmware, even if you've already validated the current one. + - Press and hold the button until the pine cone is drawn in **red** to load the recovery firmware. This recovery firmware only provides BLE connectivity and OTA functionality. + +More info about the bootloader in [its project page](https://github.com/JF002/pinetime-mcuboot-bootloader/blob/master/README.md). diff --git a/doc/gettingStarted/appmenu-071.jpg b/doc/gettingStarted/appmenu-071.jpg deleted file mode 100644 index dee7c8f6..00000000 Binary files a/doc/gettingStarted/appmenu-071.jpg and /dev/null differ diff --git a/doc/gettingStarted/appmenu.jpg b/doc/gettingStarted/appmenu.jpg deleted file mode 100644 index 1e52fe78..00000000 Binary files a/doc/gettingStarted/appmenu.jpg and /dev/null differ diff --git a/doc/gettingStarted/bootloader-1.0.jpg b/doc/gettingStarted/bootloader-1.0.jpg index 7b639184..a21f88f4 100644 Binary files a/doc/gettingStarted/bootloader-1.0.jpg and b/doc/gettingStarted/bootloader-1.0.jpg differ diff --git a/doc/gettingStarted/gettingStarted-1.0.md b/doc/gettingStarted/gettingStarted-1.0.md index 409b7c7b..890164fe 100644 --- a/doc/gettingStarted/gettingStarted-1.0.md +++ b/doc/gettingStarted/gettingStarted-1.0.md @@ -1,119 +1,57 @@ -# Getting started with InfiniTime 1.0 +# Getting started with InfiniTime -On April 22 2021, InfiniTime and Pine64 [announced the release of InfiniTime 1.0](https://www.pine64.org/2021/04/22/its-time-infinitime-1-0/) and the availability of PineTime smartwatches as *enthusiast grade end-user product*. This page aims to guide you with your first step with your new PineTime. +On April 22 2021, InfiniTime and Pine64 [announced the release of InfiniTime 1.0.0](https://www.pine64.org/2021/04/22/its-time-infinitime-1-0/) and the availability of PineTime smartwatches as an *enthusiast grade end-user product*. This page aims to guide you with your first step with your new PineTime. -## Firmware, InfiniTime, Bootloader, Recovery firmware, OTA, DFU... What is it? +It is highly recommended to update the firmware to the latest version when you receive your watch and when a new InfiniTime version is released. More information on updating the firmware [here](/doc/gettingStarted/updating-software.md). -You might have already seen these words by reading the announcement, release notes, or [the wiki guide](https://wiki.pine64.org/wiki/Upgrade_PineTime_to_InfiniTime_1.0.0) and, you may find them misleading if you're not familiar with the project. - -Basically, a **firmware** is just a software running on the embedded hardware of a device, the PineTime in this case. -**InfiniTime** is based on 3 distinct **firmwares**: - - **[InfiniTime](https://github.com/InfiniTimeOrg/InfiniTime)** itself, this is the *application firmware* running on the PineTime. This is the main firmware which provides most of the functionalities you'll use on a daily basis : bluetooth low-energy (BLE) connectivity, applications, watchfaces,... - - **[The bootloader](https://github.com/JF002/pinetime-mcuboot-bootloader)** is responsible for safely applying **updates** of the *application firmware*, reverting them in case of issues and load the recovery firmware when requested. - - **The recovery firmware** is a specific *application firmware* than can be loaded by the bootloader on user request. This firmware can be useful in case of serious issue, when the main application firmware cannot perform an OTA update correctly. Currently, this recovery firmware is based on [InfiniTime 0.14.1](https://github.com/InfiniTimeOrg/InfiniTime/releases/tag/0.14.1). - -**OTA** and **DFU** refer to the update of the firmware over BLE (**B**luetooth **L**ow **E**nergy). **OTA** means **O**ver **T**he **A**ir, this is a functionality that allows the user to update the firmware how their device using a wireless communication like BLE. When we talk about **DFU** (**D**evice **F**irmware **U**pdate), we refer to the file format and protocol used to send the update of the firmware to the watch over-the-air. InfiniTime implement the (legacy) DFU protocol from Nordic Semiconductor (NRF). - -## How to check the version of InfiniTime and the bootloader? - -Since September 2020, all PineTimes (devkits or sealed) are flashed using the **[first iteration of the bootloader](https://github.com/lupyuen/pinetime-rust-mynewt/releases/tag/v4.1.7)** and **[InfiniTime 0.7.1](https://github.com/InfiniTimeOrg/InfiniTime/releases/tag/0.7.1)**. There was no recovery firmware at that time. - -The bootloader only runs when the watch starts (from an empty battery, for example) or after a reset (after a successful OTA or a manual reset - long push on the button). - -You can recognize this first iteration of the bootloader with it greenish **PINETIME** logo. - -![Old bootloader logo](oldbootloaderlogo.jpg) - -You can check the version of InfiniTime by opening the app *SystemInfo*. For version < 1.0: - -![InfiniTime 0.7.1 Application menu](appmenu-071.jpg) -![InfiniTime 0.7.1 version](version-071.jpg) - -And for version >= 1.0 : - -![InfiniTime 1.0 version](version-1.0.jpg) - -PineTime shipped from June 2021 (to be confirmed) will be flashed with the [new version of the bootloader](https://github.com/JF002/pinetime-mcuboot-bootloader/releases/tag/1.0.0), the [recovery firmware](https://github.com/InfiniTimeOrg/InfiniTime/releases/tag/0.14.1) and [InfiniTime 1.0](https://github.com/InfiniTimeOrg/InfiniTime/releases/tag/1.0.0). - -The bootloader is easily recognizable with it white pine cone that is progressively drawn in green. It also displays its own version on the bottom (1.0.0 as of now). - -![Bootloader 1.0](bootloader-1.0.jpg) - -## How to update your PineTime? - -To update your PineTime, you can use one of the compatible companion applications. Here are the main ones: - - - **[Amazfish](https://github.com/piggz/harbour-amazfish)** (Desktop Linux, mobile Linux, SailfishOS, runs on the PinebookPro and the Pinephone) - - **[Gadgetbridge](https://www.gadgetbridge.org/)** (Android) - - **[Siglo](https://github.com/alexr4535/siglo)** (Linux, GTK based) - - **NRFConnect** (closed source, Android & iOS). - -See [this page](ota-gadgetbridge-nrfconnect.md) for more info about the OTA procedure using Gadgetbridge and NRFConnect. - -### From InfiniTime 0.7.1 / old bootloader - -If your PineTime is currently running InfiniTime 0.7.1 and the old bootloader, we strongly recommend you update them to more recent version (Bootloader 1.0.0 and InfiniTime 1.0.0 as of now). We also recommend you install the recovery firmware once the bootloader is up-do-date. - -Using the companion app of your choice, you'll need to apply the OTA procedure for these 3 firmwares in this sequence (failing to follow this specific order might temporarily or permanently brick your device): - - 1. Flash the latest version of InfiniTime. The file to upload is named **pinetime-mcuboot-app-dfu-x.y.z.zip**. Here is the link to [InfiniTime 1.0](https://github.com/InfiniTimeOrg/InfiniTime/releases/download/1.0.0/pinetime-mcuboot-app-dfu-1.0.0.zip). - 2. Update the bootloader by applying the OTA procedure with the file named [**reloader-mcuboot.zip** from the repo of the bootloader](https://github.com/JF002/pinetime-mcuboot-bootloader/releases/download/1.0.0/reloader-mcuboot.zip). - 3. Install the recovery firmware by applying the OTA procedure with the file named [**pinetime-mcuboot-recovery-loader-dfu-0.14.1.zip** from the version 0.14.1 of InfiniTime](https://github.com/InfiniTimeOrg/InfiniTime/releases/download/0.14.1/pinetime-mcuboot-recovery-loader-dfu-0.14.1.zip). - -You'll find more info about this process in [this wiki page](https://wiki.pine64.org/wiki/Upgrade_PineTime_to_InfiniTime_1.0.0). You can also see the procedure in video [here](https://video.codingfield.com/videos/watch/831077c5-16f3-47b4-9b2b-c4bbfecc6529) and [here (from Amazfish)](https://video.codingfield.com/videos/watch/f7bffb3d-a6a1-43c4-8f01-f4aeff4adf9e) - -### From version > 1.0 - -If you are already running the new "1.0.0" bootloader, all you have to do is update your version of InfiniTime when it'll be available. We'll write specific instructions when (if) we release a new version of the bootloader. - -### Firmware validation - -The bootloader requires a (manual) validation of the firmware. If the watch reset with an updated firmware that was not validated, the bootloader will consider it as non-functioning and will revert to the previous version of the firmware. This is a safety feature to prevent bricking your device with a faulty firmware. - -You can validate your updated firmware on InfiniTime >= 1.0 by following this simple procedure: - - - From the watchface, swipe **right** to display the *Quick Actions menu* - - Open the **Settings** app by tapping the *gear* icon on the bottom right - - Swipe down and tap on the entry named **Firmware** - - This app shows the version that is currently running. If it's not validated yet, it displays 2 buttons: - - **Validate** to validate your firmware - - **Reset** to reset the watch and revert to the previously running version of the firmware - -## InfiniTime 1.0 quick user guide +## InfiniTime quick user guide ### Setting the time -By default, InfiniTime starts on the digital watchface. It'll probably display the epoch time (1 Jan 1970, 00:00). The time will be automatically synchronized once you connect on of the companion app to your PineTime using BLE connectivity. InfiniTime does not provide any way to manually set the time for now. +By default, InfiniTime starts on the digital watchface. It'll probably display the epoch time (1 Jan 1970, 00:00). + +You can sync the time using companion apps. + + - Gadgetbridge automatically synchronizes the time when you connect it to your watch. More information on Gadgetbridge [here](/doc/gettingStarted/ota-gadgetbridge.md) + - [Sync the time with NRFConnect](/doc/gettingStarted/time-nrfconnect.md) + - Sync the time with your browser https://hubmartin.github.io/WebBLEWatch/ + +You can also set the time in the settings without a companion app. (version >1.7.0) + +InfiniTime doesn't handle daylight savings automatically, so make sure to set the correct the time or sync it with a companion app. + +### Digital watch face + +![Digital watch face](ui/watchface.jpg) + +This is what the default digital watch face looks like. You can change watch faces in the settings. + +The indicator on the top left is visible if you have unread notifications + +On the top right there are status icons + + - The battery icon shows roughly how much charge is remaining + - The Bluetooth icon is visible when the watch is connected to a companion app + - A plug icon is shown when the watch is plugged into a charger. + +On the bottom left you can see your heart rate if you have the measurement enabled in the heart rate app. + +On the bottom right you can see how many steps you have taken today. ### Navigation in the menu -![Quick actions](quickactions.jpg) -![Settings](settings.jpg) -![Application menu](appmenu.jpg) +![Application menu](ui/applist.jpg) +![Notifications](ui/notifications.jpg) +![Quick actions](ui/quicksettings.jpg) +![Settings](ui/settings.jpg) - - Swipe **down** to display the notification panel. Notification sent by your companion app will be displayed in this panel. - Swipe **up** to display the application menus. Apps (stopwatch, music, step, games,...) can be started from this menu. + - Swipe **down** to display the notification panel. Notification sent by your companion app will be displayed here. - Swipe **right** to display the Quick Actions menu. This menu allows you to - Set the brightness of the display - Start the **flashlight** app - - Enable/disable vibrations on notifications (Do Not Disturb mode) + - Enable/disable notifications (Do Not Disturb mode) - Enter the **settings** menu - - Settings - - Display timeout - - Wake up event (Tap, wrist rotation) - - Time format (12/24H) - - Default watchface (digital / analog) - - Battery info - - Firmware validation - - About (system info, firmware version,...) - -### Bootloader - -Most of the time, the bootloader just runs without your intervention (update and load the firmware). - -However, you can enable 2 functionalities using the push button: - - - Push the button until the pine cone is drawn in **blue** to force the rollback of the previous version of the firmware, even if you've already validated the updated one - - Push the button until the pine cone is drawn in **red** to load the recovery firmware. This recovery firmware only provides BLE connectivity and OTA functionality. - -More info about the bootloader in [its project page](https://github.com/JF002/pinetime-mcuboot-bootloader/blob/master/README.md). + - Swipe up and down to see all options + - Click the button to go back a screen. + - You can hold the button for a short time to return to the watch face. (version >1.7.0) diff --git a/doc/gettingStarted/oldbootloaderlogo.jpg b/doc/gettingStarted/oldbootloaderlogo.jpg deleted file mode 100644 index b4d0cdfb..00000000 Binary files a/doc/gettingStarted/oldbootloaderlogo.jpg and /dev/null differ diff --git a/doc/gettingStarted/ota-gadgetbridge-nrfconnect.md b/doc/gettingStarted/ota-gadgetbridge-nrfconnect.md deleted file mode 100644 index 57d16218..00000000 --- a/doc/gettingStarted/ota-gadgetbridge-nrfconnect.md +++ /dev/null @@ -1,109 +0,0 @@ -# Flash and upgrade InfiniTime -If you just want to flash or upgrade InfiniTime on your PineTime, this page is for you! - -- [InfiniTime releases and versions](#infinitime-releases-and-versions) -- [How to upgrade Over-The-Air (OTA)](#how-to-upgrade-over-the-air-ota) - - [Using Gadgetbridge](#using-gadgetbridge) - - [Using NRFConnect](#Using-nrfconnect) -- [How to flash InfiniTime using the SWD interface](#how-to-flash-infinitime-using-the-swd-interface) - -## InfiniTime releases and versions -All releases of InfiniTime are available on the [release page of the GitHub repo](https://github.com/InfiniTimeOrg/InfiniTime/releases). - -Versions that are tagged as **RELEASE CANDIDATE** are pre-release versions, that are available for testing before actually releasing a new stable version. If you want to help us debug the project and provide stable versions to other user, you can use them. If you want stable and tested version, you should not flash these release candidate version. - -Release files are available under the *Assets* button. - -## How to upgrade Over-The-Air (OTA) -OTA is the easiest method to upgrade InfiniTime. Note that it's only possible is your PineTime is already running InfiniTime (>= 0.7.1). - -2 companion apps provide support for OTA : - - [Gadgetbridge](https://gadgetbridge.org/) (open source, runs on Android, [available on F-Droid](https://f-droid.org/packages/nodomain.freeyourgadget.gadgetbridge/)). - - [NRFConnect](https://www.nordicsemi.com/Software-and-tools/Development-Tools/nRF-Connect-for-mobile) (close source, runs on Android and iOS). - -Both applications need you to download the **DFU file** of InfiniTime. This file contains the new version of InfiniTime that will be flashed into your device. It's called **dfu-x.y.z.zip** (ex: dfu-0.9.0.zip) in the release note. -![Dfu file](dfuFile.png ) - -### Using Gadgetbridge -Launch Gadgetbridge and tap on the **"+"** button on the bottom right to add a new device: - -![Gadgetbridge 0](gadgetbridge0.jpg) - -Wait for the scan to complete, your PineTime should be detected: - -![Gadgetbridge 1](gadgetbridge1.jpg) - -Tap on it. Gadgdetbridge will pair and connect to your device: - -![Gadgetbridge 2](gadgetbridge2.jpg) - -Now that Gadgetbridge is connected to your PineTime, use a file browser application (I'm using Seafile to browse my NAS) and browse to the DFU file (image-xxx.zip) you downloaded previously. Tap on it and open it using the Gadgetbridge application/firmware installer: - -![Gadgetbridge 3](gadgetbridge3.jpg) - -Read carefully the warning and tap **Install**: - -![Gadgetbridge 4](gadgetbridge4.jpg) - -Wait for the transfer to finish. Your PineTime should reset and reboot with the new version of InfiniTime! - -Don't forget to **validate** your firmware. In the InfiniTime go to the settings (swipe right, select gear icon) and Firmware option and click **validate**. Otherwise after reboot the previous firmware will be used. - -![Gadgetbridge 5](gadgetbridge5.jpg) - -### Using NRFConnect -Open NRFConnect. Swipe down in the *Scanner* tab and wait for your device to appear: - -![NRFConnect 0](nrfconnect0.jpg) - -Tap on the *Connect* button on the right of your device. NRFConnect will connect to your PineTime and discover its characteristics. Tap on the **DFU** button on the top right: - -![NRFConnect 1](nrfconnect1.jpg) - -Select **Distribution packet (ZIP)**: - -![NRFConnect 2](nrfconnect2.jpg) - -Browse to the DFU file you downloaded previously, the DFU transfer will start automatically. When the transfer is finished, your PineTime will reset and restart on the new version of InfiniTime! - -Don't forget to **validate** your firmware. In the InfiniTime go to the settings (swipe right, select gear icon) and Firmware option and click **validate**. Otherwise after reboot the previous firmware will be used. - -![NRFConnect 3](nrfconnect3.jpg) - -## How to flash InfiniTime using the SWD interface -Download the files **bootloader.bin**, **image-x.y.z.bin** and **pinetime-graphics-x.y.z.bin** from the release page: - -![Image file](imageFile.png ) - -The bootloader reads a boot logo from the external SPI flash memory. The first step consists in flashing a tool in the MCU that will flash the boot logo into this SPI flash memory. This first step is optional but recommanded (the bootloader will display garbage on screen for a few second if you don't do it). -Using your SWD tool, flash **pinetime-graphics-x.y.z.bin** at offset **0x0000**. Reset the MCU and wait for a few second, until the logo is completely drawn on the display. - -Then, using your SWD tool, flash those file at specific offset: - - - bootloader.bin : **0x0000** - - image-x.y.z.bin : **0x8000** - -Reset and voilĂ , you're running InfiniTime on your PineTime! - -If you are using OpenOCD with a STLinkV2, you can find more info [on this page](../openOCD.md). - -## How to synchronize the time - -### Using Gadgetbridge -Good news! Gadgetbridge **automatically** synchronizes the time when connecting to your PineTime! - -### Using any Chromium-based web browser -You can use it from your PC, Mac, Android. Browsers now have BLE support. -https://hubmartin.github.io/WebBLEWatch/ - -### Using NRFConnect -You must enable the **CTS** *GATT server* into NRFConnect so that InfiniTime can synchronize the time with your smartphone. - -Launch NRFConnect, tap the sandwich button on the top left and select *Configure GATT server*: - -![NRFConnect CTS 0](nrfconnectcts0.jpg) - - -Tap *Add service* and select the server configuration *Current Time service*. Tap OK and connect to your PineTime, it should automcatically sync the time once the connection is established! - -![NRFConnect CTS 1](nrfconnectcts1.jpg) diff --git a/doc/gettingStarted/ota-gadgetbridge.md b/doc/gettingStarted/ota-gadgetbridge.md new file mode 100644 index 00000000..fe26c03b --- /dev/null +++ b/doc/gettingStarted/ota-gadgetbridge.md @@ -0,0 +1,29 @@ +# Connecting to Gadgetbridge + +Launch Gadgetbridge and tap on the **"+"** button on the bottom right to add a new device: + +![Gadgetbridge 0](gadgetbridge0.jpg) + +Wait for the scan to complete, your PineTime should be detected: + +![Gadgetbridge 1](gadgetbridge1.jpg) + +Tap on it. Gadgdetbridge will pair and connect to your device: + +![Gadgetbridge 2](gadgetbridge2.jpg) + +# Updating with Gadgetbridge + +Now that Gadgetbridge is connected to your PineTime, use a file browser application and find the DFU file (`pinetime-mcuboot-app-dfu-x.x.x.zip`) you downloaded previously. Tap on it and open it using the Gadgetbridge application/firmware installer: + +![Gadgetbridge 3](gadgetbridge3.jpg) + +Read the warning carefully and tap **Install**: + +![Gadgetbridge 4](gadgetbridge4.jpg) + +Wait for the transfer to finish. Your PineTime should reset and reboot with the new version of InfiniTime! + +Don't forget to **validate** your firmware. In the InfiniTime go to the settings (swipe right, select gear icon) and Firmware option and click **validate**. Otherwise after reboot the previous firmware will be used. + +![Gadgetbridge 5](gadgetbridge5.jpg) diff --git a/doc/gettingStarted/ota-nrfconnect.md b/doc/gettingStarted/ota-nrfconnect.md new file mode 100644 index 00000000..800bd6bc --- /dev/null +++ b/doc/gettingStarted/ota-nrfconnect.md @@ -0,0 +1,22 @@ +# Updating with NRFConnect + +Open NRFConnect. Swipe down in the *Scanner* tab and wait for your device to appear: + +![NRFConnect 0](nrfconnect0.jpg) + +Tap on the *Connect* button on the right of your device. NRFConnect will connect to your PineTime and discover its characteristics. Tap on the **DFU** button on the top right: + +![NRFConnect 1](nrfconnect1.jpg) + +Select **Distribution packet (ZIP)**: + +![NRFConnect 2](nrfconnect2.jpg) + +Find the DFU file (`pinetime-mcuboot-app-dfu-x.x.x.zip`) you downloaded previously, the DFU transfer will start automatically. When the transfer is finished, your PineTime will reset and restart on the new version of InfiniTime! + +Don't forget to **validate** your firmware. In the InfiniTime go to the settings (swipe right, select gear icon) and Firmware option and click **validate**. Otherwise after reboot the previous firmware will be used. + +![NRFConnect 3](nrfconnect3.jpg) + +# Demo +[This video](https://seafile.codingfield.com/f/a52b69683a05472a90c7/) shows how to use NRFConnect to update the firmware running on the Pinetime. diff --git a/doc/gettingStarted/quickactions.jpg b/doc/gettingStarted/quickactions.jpg deleted file mode 100644 index 0d92b134..00000000 Binary files a/doc/gettingStarted/quickactions.jpg and /dev/null differ diff --git a/doc/gettingStarted/settings.jpg b/doc/gettingStarted/settings.jpg deleted file mode 100644 index 510b29eb..00000000 Binary files a/doc/gettingStarted/settings.jpg and /dev/null differ diff --git a/doc/gettingStarted/time-nrfconnect.md b/doc/gettingStarted/time-nrfconnect.md new file mode 100644 index 00000000..a30d98f8 --- /dev/null +++ b/doc/gettingStarted/time-nrfconnect.md @@ -0,0 +1,11 @@ +### Syncing time + +You must enable the **CTS** *GATT server* in NRFConnect so that InfiniTime can synchronize the time with your smartphone. + +Launch NRFConnect, tap the sandwich button on the top left and select *Configure GATT server*: + +![NRFConnect CTS 0](nrfconnectcts0.jpg) + +Tap *Add service* and select the server configuration *Current Time service*. Tap OK and connect to your PineTime, it should automcatically sync the time once the connection is established! + +![NRFConnect CTS 1](nrfconnectcts1.jpg) diff --git a/doc/gettingStarted/ui/applist.jpg b/doc/gettingStarted/ui/applist.jpg new file mode 100644 index 00000000..927780e2 Binary files /dev/null and b/doc/gettingStarted/ui/applist.jpg differ diff --git a/doc/gettingStarted/ui/notifications.jpg b/doc/gettingStarted/ui/notifications.jpg new file mode 100644 index 00000000..00b27267 Binary files /dev/null and b/doc/gettingStarted/ui/notifications.jpg differ diff --git a/doc/gettingStarted/ui/quicksettings.jpg b/doc/gettingStarted/ui/quicksettings.jpg new file mode 100644 index 00000000..250c9154 Binary files /dev/null and b/doc/gettingStarted/ui/quicksettings.jpg differ diff --git a/doc/gettingStarted/ui/settings.jpg b/doc/gettingStarted/ui/settings.jpg new file mode 100644 index 00000000..a61279bf Binary files /dev/null and b/doc/gettingStarted/ui/settings.jpg differ diff --git a/doc/gettingStarted/ui/watchface.jpg b/doc/gettingStarted/ui/watchface.jpg new file mode 100644 index 00000000..e7a9439b Binary files /dev/null and b/doc/gettingStarted/ui/watchface.jpg differ diff --git a/doc/gettingStarted/updating-software.md b/doc/gettingStarted/updating-software.md new file mode 100644 index 00000000..7a05073a --- /dev/null +++ b/doc/gettingStarted/updating-software.md @@ -0,0 +1,41 @@ +# Updating InfiniTime + +If you just want to flash or upgrade InfiniTime on your PineTime, this page is for you! If you want more information about the software and the update procedure, check out [this](/doc/gettingStarted/about-software.md) page. + +## Checking the version of InfiniTime + +You can check the InfiniTime version by first swiping right on the watchface to open quick settings, tapping the cogwheel to open settings, swipe up until you find an entry named "About" and tap on it. + +![InfiniTime 1.0 version](version-1.0.jpg) + +PineTimes shipped after June 2021 will ship with the latest version of [the bootloader](https://github.com/JF002/pinetime-mcuboot-bootloader/releases/tag/1.0.0) and [recovery firmware](https://github.com/InfiniTimeOrg/InfiniTime/releases/tag/0.14.1) + +The bootloader is run right before booting into InfiniTime. It is easily recognizable with its white pine cone that is progressively drawn in green. It also displays its own version on the bottom (1.0.0 as of now). + +![Bootloader 1.0](bootloader-1.0.jpg) + +## Updating with companion apps + +To update your PineTime, you can use one of the [compatible companion applications](/README.md#companion-apps). + +The updating process differs slightly on every companion app, so you'll need to familiarize yourself with the companion app of your choice. + +All releases of InfiniTime are available on the [release page of the GitHub repo](https://github.com/InfiniTimeOrg/InfiniTime/releases) under assets. + +To update the firmware, you need to download the DFU of the firmware version that you'd like to install, for example `pinetime-mcuboot-app-dfu-1.6.0.zip`, and flash it with your companion app. + +We have prepared instructions for flashing InfiniTime with Gadgetbridge and NRFConnect. + + - [Updating with Gadgetbridge](/doc/gettingStarted/ota-gadgetbridge.md) + - [Updating with NRFConnect](/doc/gettingStarted/ota-nrfconnect.md) + +## Firmware validation + +Firmware updates must be manually validated. If the firmware isn't validated and the watch resets, the watch will revert to the previous firmware. This is a safety feature to prevent bricking your device with faulty firmware. + +You can validate your updated firmware on InfiniTime >= 1.0 by following this simple procedure: + + - From the watchface, swipe **right** to display the *quick settings menu* + - Open settings by tapping the cogwheel on the bottom right + - Swipe up until you find an entry named **Firmware** and tap on it + - If the firmware is not validated yet, you can either validate the running firmware, or reset and revert to the previous firmware version diff --git a/doc/gettingStarted/version-071.jpg b/doc/gettingStarted/version-071.jpg deleted file mode 100644 index bc9bc5b5..00000000 Binary files a/doc/gettingStarted/version-071.jpg and /dev/null differ diff --git a/doc/gettingStarted/version-1.0.jpg b/doc/gettingStarted/version-1.0.jpg index bcfc8c63..59655b1a 100644 Binary files a/doc/gettingStarted/version-1.0.jpg and b/doc/gettingStarted/version-1.0.jpg differ diff --git a/doc/openOCD.md b/doc/openOCD.md index b3661cee..df24b30b 100644 --- a/doc/openOCD.md +++ b/doc/openOCD.md @@ -1,12 +1,12 @@ # OpenOCD and STLink OpenOCD (**Open O**n **C**hip **D**ebugger) is an open source tool that interfaces with many SWD/JTAG debugger to provide debugging and *in-system* programming for embedded target devices. -It supports the **NRF52** (the CPU of the PineTime) and the **STLinkV2**, a cheap SWD debugger. +OpenOCD supports the **NRF52** (the CPU of the PineTime) and the **STLinkV2**, a cheap SWD debugger. -It works on X86 computers, as well as ARM/ARM64 computers and SBC (like the RaspberryPi and Pine64 Pinebook Pro) ! +OpenOCD works on X86 computers, ARM/ARM64 computers, and SBCs (like the RaspberryPi and Pine64 Pinebook Pro)! ## Installation -We will build OpenOCD from sources, as packages from Linux distributions are most of the time outdated and do not support the NRF52 correctly. +We will build OpenOCD from sources, as packages from Linux distributions are most of the time outdated and do not support the NRF52 properly. - Fetch the sources from GIT, and build and install it: @@ -27,7 +27,7 @@ sudo cp contrib/60-openocd.rules /etc/udev/rules.d/ sudo udevadm control --reload-rules ``` - - You can now plug your STLinkV2 in a USB port and run OpenOCD to see if it's working correctly: + - You can now plug your STLinkV2 into a USB port and run OpenOCD to see if it's working correctly: ``` $ openocd -f interface/stlink.cfg -f target/nrf52.cfg @@ -63,7 +63,7 @@ gdb_breakpoint_override hard source [find target/nrf52.cfg] ``` -This file specifies to OpenOCD which debugger and target it will be connected to.. +This file specifies to OpenOCD which debugger and target it will be connected to. Then, we use various *user files* to use OpenOCD to flash InfiniTime binary files. diff --git a/doc/ui_guidelines.md b/doc/ui_guidelines.md index c267b79b..0cbd39f5 100644 --- a/doc/ui_guidelines.md +++ b/doc/ui_guidelines.md @@ -4,13 +4,10 @@ - Buttons should generally be at least 50px high - Buttons should generally be on the bottom edge - Make interactable objects **big** -- Recommendations for inner padding, aka distance between buttons: - - When aligning 4 objects: 4px, e.g. Settings - - When aligning 3 objects: 6px, e.g. App list - - When aligning 2 objects: 10px, e.g. Quick settings - When using a page indicator, leave 8px for it on the right side - It is acceptable to leave 8px on the left side as well to center the content - Top bar takes at least 20px + padding - Top bar right icons move 8px to the left when using a page indicator +- A black background helps to hide the screen border, allowing the UI to look less cramped when utilizing the entire display area. ![example layouts](./ui/example.png) diff --git a/doc/versioning.md b/doc/versioning.md index 48e05043..2fa36ab9 100644 --- a/doc/versioning.md +++ b/doc/versioning.md @@ -1,6 +1,6 @@ # Versioning -The versioning of this project is based on [Semantic versionning](https://semver.org/) : +The versioning of this project is based on [Semantic versioning](https://semver.org/): - - The **patch** is incremented when we fix a bug on a **released** version (most of the time using a **hotfix** branch). - - The **minor** is incremented when we release a new version with new features. It corresponds to a merge of **develop** into **master**. - - The **major** should be incremented when a breaking change is made to the application. We still have to define what is a breaking change in the context of this project. For now, I suggest that it stays **0** until we have a fully functioning firmware suited for the final user. \ No newline at end of file + - The **patch** is incremented when a bug is fixed on a **released** version (most of the time using a **hotfix** branch). + - The **minor** is incremented when a new version with new features is released. It corresponds to a merge of **develop** into **master**. + - The **major** should be incremented when a breaking change is made to the application. We still have to define what is a breaking change in the context of this project. diff --git a/images/infinitime-logo-github.jpg b/images/infinitime-logo-github.jpg deleted file mode 100644 index cf19e35c..00000000 Binary files a/images/infinitime-logo-github.jpg and /dev/null differ diff --git a/images/infinitime-logo-small.jpg b/images/infinitime-logo-small.jpg new file mode 100644 index 00000000..9949f5b0 Binary files /dev/null and b/images/infinitime-logo-small.jpg differ diff --git a/src/BootloaderVersion.h b/src/BootloaderVersion.h index f8127414..309c23c3 100644 --- a/src/BootloaderVersion.h +++ b/src/BootloaderVersion.h @@ -1,5 +1,8 @@ #pragma once +#include +#include + namespace Pinetime { class BootloaderVersion { public: diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 46deb201..80f900d4 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -154,6 +154,7 @@ set(NIMBLE_SRC libs/mynewt-nimble/nimble/controller/src/ble_ll_supp_cmd.c libs/mynewt-nimble/nimble/controller/src/ble_ll_hci_ev.c libs/mynewt-nimble/nimble/controller/src/ble_ll_rfmgmt.c + libs/mynewt-nimble/nimble/controller/src/ble_ll_resolv.c libs/mynewt-nimble/porting/nimble/src/os_cputime.c libs/mynewt-nimble/porting/nimble/src/os_cputime_pwr2.c libs/mynewt-nimble/porting/nimble/src/os_mbuf.c @@ -357,6 +358,14 @@ set(LVGL_SRC libs/lvgl/src/lv_widgets/lv_win.c ) +set(QCBOR_SRC + libs/QCBOR/src/ieee754.c + libs/QCBOR/src/qcbor_decode.c + libs/QCBOR/src/qcbor_encode.c + libs/QCBOR/src/qcbor_err_to_str.c + libs/QCBOR/src/UsefulBuf.c + ) + list(APPEND IMAGE_FILES displayapp/icons/battery/os_battery_error.c displayapp/icons/battery/os_battery_100.c @@ -407,6 +416,7 @@ list(APPEND SOURCE_FILES displayapp/screens/Label.cpp displayapp/screens/FirmwareUpdate.cpp displayapp/screens/Music.cpp + displayapp/screens/Weather.cpp displayapp/screens/Navigation.cpp displayapp/screens/Metronome.cpp displayapp/screens/Motion.cpp @@ -421,8 +431,10 @@ list(APPEND SOURCE_FILES displayapp/screens/BatteryInfo.cpp displayapp/screens/Steps.cpp displayapp/screens/Timer.cpp + displayapp/screens/PassKey.cpp displayapp/screens/Error.cpp displayapp/screens/Alarm.cpp + displayapp/screens/Styles.cpp displayapp/Colors.cpp ## Settings @@ -433,7 +445,6 @@ list(APPEND SOURCE_FILES displayapp/screens/settings/SettingWakeUp.cpp displayapp/screens/settings/SettingDisplay.cpp displayapp/screens/settings/SettingSteps.cpp - displayapp/screens/settings/SettingPineTimeStyle.cpp displayapp/screens/settings/SettingSetDate.cpp displayapp/screens/settings/SettingSetTime.cpp displayapp/screens/settings/SettingChimes.cpp @@ -472,9 +483,11 @@ list(APPEND SOURCE_FILES components/ble/CurrentTimeService.cpp components/ble/AlertNotificationService.cpp components/ble/MusicService.cpp + components/ble/weather/WeatherService.cpp components/ble/NavigationService.cpp displayapp/fonts/lv_font_navi_80.c components/ble/BatteryInformationService.cpp + components/ble/FSService.cpp components/ble/ImmediateAlertService.cpp components/ble/ServiceDiscovery.cpp components/ble/HeartRateService.cpp @@ -508,6 +521,7 @@ list(APPEND SOURCE_FILES components/heartrate/Ptagc.cpp components/heartrate/HeartRateController.cpp + buttonhandler/ButtonHandler.cpp touchhandler/TouchHandler.cpp ) @@ -542,7 +556,9 @@ list(APPEND RECOVERY_SOURCE_FILES components/ble/CurrentTimeService.cpp components/ble/AlertNotificationService.cpp components/ble/MusicService.cpp + components/ble/weather/WeatherService.cpp components/ble/BatteryInformationService.cpp + components/ble/FSService.cpp components/ble/ImmediateAlertService.cpp components/ble/ServiceDiscovery.cpp components/ble/NavigationService.cpp @@ -568,6 +584,7 @@ list(APPEND RECOVERY_SOURCE_FILES components/heartrate/Ptagc.cpp components/motor/MotorController.cpp components/fs/FS.cpp + buttonhandler/ButtonHandler.cpp touchhandler/TouchHandler.cpp ) @@ -644,6 +661,9 @@ set(INCLUDE_FILES components/datetime/DateTimeController.h components/brightness/BrightnessController.h components/motion/MotionController.h + components/firmwarevalidator/FirmwareValidator.h + components/ble/BleController.h + components/ble/NotificationManager.h components/ble/NimbleController.h components/ble/DeviceInformationService.h components/ble/CurrentTimeClient.h @@ -651,11 +671,13 @@ set(INCLUDE_FILES components/ble/DfuService.h components/firmwarevalidator/FirmwareValidator.h components/ble/BatteryInformationService.h + components/ble/FSService.h components/ble/ImmediateAlertService.h components/ble/ServiceDiscovery.h components/ble/BleClient.h components/ble/HeartRateService.h components/ble/MotionService.h + components/ble/weather/WeatherService.h components/settings/Settings.h components/timer/TimerController.h components/alarm/AlarmController.h @@ -682,6 +704,7 @@ set(INCLUDE_FILES components/heartrate/Ptagc.h components/heartrate/HeartRateController.h components/motor/MotorController.h + buttonhandler/ButtonHandler.h touchhandler/TouchHandler.h ) @@ -780,7 +803,7 @@ link_directories( ) -set(COMMON_FLAGS -MP -MD -mthumb -mabi=aapcs -Wall -Wno-unknown-pragmas -g3 -ffunction-sections -fdata-sections -fno-strict-aliasing -fno-builtin --short-enums -mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16 -Wreturn-type -Werror=return-type -fstack-usage -fno-exceptions -fno-non-call-exceptions) +set(COMMON_FLAGS -MP -MD -mthumb -mabi=aapcs -Wall -Wextra -Warray-bounds=2 -Wformat=2 -Wformat-overflow=2 -Wformat-truncation=2 -Wformat-nonliteral -ftree-vrp -Wno-unused-parameter -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-expansion-to-defined -g3 -ffunction-sections -fdata-sections -fno-strict-aliasing -fno-builtin --short-enums -mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16 -Wreturn-type -Werror=return-type -fstack-usage -fno-exceptions -fno-non-call-exceptions) add_definitions(-DCONFIG_GPIO_AS_PINRESET) add_definitions(-DNIMBLE_CFG_CONTROLLER) add_definitions(-DOS_CPUTIME_FREQ) @@ -802,10 +825,10 @@ add_library(nrf-sdk STATIC ${SDK_SOURCE_FILES}) target_include_directories(nrf-sdk SYSTEM PUBLIC . ../) target_include_directories(nrf-sdk SYSTEM PUBLIC ${INCLUDES_FROM_LIBS}) target_compile_options(nrf-sdk PRIVATE - $<$,$>: ${COMMON_FLAGS} -Og -g3> - $<$,$>: ${COMMON_FLAGS} -Os> - $<$,$>: ${COMMON_FLAGS} -Og -fno-rtti> - $<$,$>: ${COMMON_FLAGS} -Os -fno-rtti> + $<$,$>: ${COMMON_FLAGS} -Wno-expansion-to-defined -Og -g3> + $<$,$>: ${COMMON_FLAGS} -Wno-expansion-to-defined -O3> + $<$,$>: ${COMMON_FLAGS} -Wno-expansion-to-defined -Og -fno-rtti> + $<$,$>: ${COMMON_FLAGS} -Wno-expansion-to-defined -O3 -fno-rtti> $<$: -MP -MD -x assembler-with-cpp> ) @@ -833,6 +856,25 @@ target_compile_options(lvgl PRIVATE $<$: -MP -MD -x assembler-with-cpp> ) +# QCBOR +add_library(QCBOR STATIC ${QCBOR_SRC}) +target_include_directories(QCBOR SYSTEM PUBLIC libs/QCBOR/inc) +# This is required with the current configuration +target_compile_definitions(QCBOR PUBLIC QCBOR_DISABLE_FLOAT_HW_USE) +# These are for space-saving +target_compile_definitions(QCBOR PUBLIC QCBOR_DISABLE_PREFERRED_FLOAT) +target_compile_definitions(QCBOR PUBLIC QCBOR_DISABLE_EXP_AND_MANTISSA) +target_compile_definitions(QCBOR PUBLIC QCBOR_DISABLE_INDEFINITE_LENGTH_STRINGS) +#target_compile_definitions(QCBOR PUBLIC QCBOR_DISABLE_INDEFINITE_LENGTH_ARRAYS) +target_compile_definitions(QCBOR PUBLIC QCBOR_DISABLE_UNCOMMON_TAGS) +target_compile_definitions(QCBOR PUBLIC USEFULBUF_CONFIG_LITTLE_ENDIAN) +set_target_properties(QCBOR PROPERTIES LINKER_LANGUAGE C) +target_compile_options(QCBOR PRIVATE + $<$,$>: ${COMMON_FLAGS} -O0 -g3> + $<$,$>: ${COMMON_FLAGS} -O3> + $<$: -MP -MD -x assembler-with-cpp> + ) + # LITTLEFS_SRC add_library(littlefs STATIC ${LITTLEFS_SRC}) target_include_directories(littlefs SYSTEM PUBLIC . ../) @@ -851,12 +893,12 @@ set(EXECUTABLE_FILE_NAME ${EXECUTABLE_NAME}-${pinetime_VERSION_MAJOR}.${pinetime set(NRF5_LINKER_SCRIPT "${CMAKE_SOURCE_DIR}/gcc_nrf52.ld") add_executable(${EXECUTABLE_NAME} ${SOURCE_FILES}) set_target_properties(${EXECUTABLE_NAME} PROPERTIES OUTPUT_NAME ${EXECUTABLE_FILE_NAME}) -target_link_libraries(${EXECUTABLE_NAME} nimble nrf-sdk lvgl littlefs) +target_link_libraries(${EXECUTABLE_NAME} nimble nrf-sdk lvgl littlefs QCBOR) target_compile_options(${EXECUTABLE_NAME} PUBLIC - $<$,$>: ${COMMON_FLAGS} -Og -g3> - $<$,$>: ${COMMON_FLAGS} -Os> - $<$,$>: ${COMMON_FLAGS} -Og -g3 -fno-rtti> - $<$,$>: ${COMMON_FLAGS} -Os -fno-rtti> + $<$,$>: ${COMMON_FLAGS} -Wextra -Wformat -Wno-missing-field-initializers -Wno-unused-parameter -Og -g3> + $<$,$>: ${COMMON_FLAGS} -Wextra -Wformat -Wno-missing-field-initializers -Wno-unused-parameter -Os> + $<$,$>: ${COMMON_FLAGS} -Wextra -Wformat -Wno-missing-field-initializers -Wno-unused-parameter -Og -g3 -fno-rtti> + $<$,$>: ${COMMON_FLAGS} -Wextra -Wformat -Wno-missing-field-initializers -Wno-unused-parameter -Os -fno-rtti> $<$: -MP -MD -x assembler-with-cpp> ) @@ -880,7 +922,7 @@ set(IMAGE_MCUBOOT_FILE_NAME ${EXECUTABLE_MCUBOOT_NAME}-image-${pinetime_VERSION_ set(DFU_MCUBOOT_FILE_NAME ${EXECUTABLE_MCUBOOT_NAME}-dfu-${pinetime_VERSION_MAJOR}.${pinetime_VERSION_MINOR}.${pinetime_VERSION_PATCH}.zip) set(NRF5_LINKER_SCRIPT_MCUBOOT "${CMAKE_SOURCE_DIR}/gcc_nrf52-mcuboot.ld") add_executable(${EXECUTABLE_MCUBOOT_NAME} ${SOURCE_FILES}) -target_link_libraries(${EXECUTABLE_MCUBOOT_NAME} nimble nrf-sdk lvgl littlefs) +target_link_libraries(${EXECUTABLE_MCUBOOT_NAME} nimble nrf-sdk lvgl littlefs QCBOR) set_target_properties(${EXECUTABLE_MCUBOOT_NAME} PROPERTIES OUTPUT_NAME ${EXECUTABLE_MCUBOOT_FILE_NAME}) target_compile_options(${EXECUTABLE_MCUBOOT_NAME} PUBLIC $<$,$>: ${COMMON_FLAGS} -Og -g3> @@ -916,7 +958,7 @@ endif() set(EXECUTABLE_RECOVERY_NAME "pinetime-recovery") set(EXECUTABLE_RECOVERY_FILE_NAME ${EXECUTABLE_RECOVERY_NAME}-${pinetime_VERSION_MAJOR}.${pinetime_VERSION_MINOR}.${pinetime_VERSION_PATCH}) add_executable(${EXECUTABLE_RECOVERY_NAME} ${RECOVERY_SOURCE_FILES}) -target_link_libraries(${EXECUTABLE_RECOVERY_NAME} nimble nrf-sdk littlefs) +target_link_libraries(${EXECUTABLE_RECOVERY_NAME} nimble nrf-sdk littlefs QCBOR) set_target_properties(${EXECUTABLE_RECOVERY_NAME} PROPERTIES OUTPUT_NAME ${EXECUTABLE_RECOVERY_FILE_NAME}) target_compile_definitions(${EXECUTABLE_RECOVERY_NAME} PUBLIC "PINETIME_IS_RECOVERY") target_compile_options(${EXECUTABLE_RECOVERY_NAME} PUBLIC @@ -946,7 +988,7 @@ set(EXECUTABLE_RECOVERY_MCUBOOT_FILE_NAME ${EXECUTABLE_RECOVERY_MCUBOOT_NAME}-${ set(IMAGE_RECOVERY_MCUBOOT_FILE_NAME ${EXECUTABLE_RECOVERY_MCUBOOT_NAME}-image-${pinetime_VERSION_MAJOR}.${pinetime_VERSION_MINOR}.${pinetime_VERSION_PATCH}.bin) set(DFU_RECOVERY_MCUBOOT_FILE_NAME ${EXECUTABLE_RECOVERY_MCUBOOT_NAME}-dfu-${pinetime_VERSION_MAJOR}.${pinetime_VERSION_MINOR}.${pinetime_VERSION_PATCH}.zip) add_executable(${EXECUTABLE_RECOVERY_MCUBOOT_NAME} ${RECOVERY_SOURCE_FILES}) -target_link_libraries(${EXECUTABLE_RECOVERY_MCUBOOT_NAME} nimble nrf-sdk littlefs) +target_link_libraries(${EXECUTABLE_RECOVERY_MCUBOOT_NAME} nimble nrf-sdk littlefs QCBOR) set_target_properties(${EXECUTABLE_RECOVERY_MCUBOOT_NAME} PROPERTIES OUTPUT_NAME ${EXECUTABLE_RECOVERY_MCUBOOT_FILE_NAME}) target_compile_definitions(${EXECUTABLE_RECOVERY_MCUBOOT_NAME} PUBLIC "PINETIME_IS_RECOVERY") target_compile_options(${EXECUTABLE_RECOVERY_MCUBOOT_NAME} PUBLIC @@ -984,7 +1026,7 @@ endif() set(EXECUTABLE_RECOVERYLOADER_NAME "pinetime-recovery-loader") set(EXECUTABLE_RECOVERYLOADER_FILE_NAME ${EXECUTABLE_RECOVERYLOADER_NAME}-${pinetime_VERSION_MAJOR}.${pinetime_VERSION_MINOR}.${pinetime_VERSION_PATCH}) add_executable(${EXECUTABLE_RECOVERYLOADER_NAME} ${RECOVERYLOADER_SOURCE_FILES}) -target_link_libraries(${EXECUTABLE_RECOVERYLOADER_NAME} nrf-sdk) +target_link_libraries(${EXECUTABLE_RECOVERYLOADER_NAME} nrf-sdk QCBOR) set_target_properties(${EXECUTABLE_RECOVERYLOADER_NAME} PROPERTIES OUTPUT_NAME ${EXECUTABLE_RECOVERYLOADER_FILE_NAME}) target_compile_options(${EXECUTABLE_RECOVERYLOADER_NAME} PUBLIC $<$,$>: ${COMMON_FLAGS} -Og -g3> @@ -1017,7 +1059,7 @@ set(EXECUTABLE_MCUBOOT_RECOVERYLOADER_FILE_NAME ${EXECUTABLE_MCUBOOT_RECOVERYLOA set(IMAGE_MCUBOOT_RECOVERYLOADER_FILE_NAME ${EXECUTABLE_MCUBOOT_RECOVERYLOADER_NAME}-image-${pinetime_VERSION_MAJOR}.${pinetime_VERSION_MINOR}.${pinetime_VERSION_PATCH}.bin) set(DFU_MCUBOOT_RECOVERYLOADER_FILE_NAME ${EXECUTABLE_MCUBOOT_RECOVERYLOADER_NAME}-dfu-${pinetime_VERSION_MAJOR}.${pinetime_VERSION_MINOR}.${pinetime_VERSION_PATCH}.zip) add_executable(${EXECUTABLE_MCUBOOT_RECOVERYLOADER_NAME} ${RECOVERYLOADER_SOURCE_FILES}) -target_link_libraries(${EXECUTABLE_MCUBOOT_RECOVERYLOADER_NAME} nrf-sdk) +target_link_libraries(${EXECUTABLE_MCUBOOT_RECOVERYLOADER_NAME} nrf-sdk QCBOR) set_target_properties(${EXECUTABLE_MCUBOOT_RECOVERYLOADER_NAME} PROPERTIES OUTPUT_NAME ${EXECUTABLE_MCUBOOT_RECOVERYLOADER_FILE_NAME}) target_compile_options(${EXECUTABLE_MCUBOOT_RECOVERYLOADER_NAME} PUBLIC $<$,$>: ${COMMON_FLAGS} -Og -g3> diff --git a/src/Version.h.in b/src/Version.h.in index 8cd39c96..0d6219c0 100644 --- a/src/Version.h.in +++ b/src/Version.h.in @@ -2,6 +2,8 @@ @VERSION_EDIT_WARNING@ +#include + namespace Pinetime { class Version { public: diff --git a/src/buttonhandler/ButtonActions.h b/src/buttonhandler/ButtonActions.h new file mode 100644 index 00000000..21be441b --- /dev/null +++ b/src/buttonhandler/ButtonActions.h @@ -0,0 +1,7 @@ +#pragma once + +namespace Pinetime { + namespace Controllers { + enum class ButtonActions { None, Click, DoubleClick, LongPress, LongerPress }; + } +} diff --git a/src/buttonhandler/ButtonHandler.cpp b/src/buttonhandler/ButtonHandler.cpp new file mode 100644 index 00000000..02ee22cf --- /dev/null +++ b/src/buttonhandler/ButtonHandler.cpp @@ -0,0 +1,78 @@ +#include "ButtonHandler.h" + +using namespace Pinetime::Controllers; + +void ButtonTimerCallback(TimerHandle_t xTimer) { + auto* sysTask = static_cast(pvTimerGetTimerID(xTimer)); + sysTask->PushMessage(Pinetime::System::Messages::HandleButtonTimerEvent); +} + +void ButtonHandler::Init(Pinetime::System::SystemTask* systemTask) { + buttonTimer = xTimerCreate("buttonTimer", pdMS_TO_TICKS(200), pdFALSE, systemTask, ButtonTimerCallback); +} + +ButtonActions ButtonHandler::HandleEvent(Events event) { + static constexpr TickType_t doubleClickTime = pdMS_TO_TICKS(200); + static constexpr TickType_t longPressTime = pdMS_TO_TICKS(400); + static constexpr TickType_t longerPressTime = pdMS_TO_TICKS(2000); + + if (event == Events::Press) { + buttonPressed = true; + } else if (event == Events::Release) { + releaseTime = xTaskGetTickCount(); + buttonPressed = false; + } + + switch (state) { + case States::Idle: + if (event == Events::Press) { + xTimerChangePeriod(buttonTimer, doubleClickTime, 0); + xTimerStart(buttonTimer, 0); + state = States::Pressed; + } + break; + case States::Pressed: + if (event == Events::Press) { + if (xTaskGetTickCount() - releaseTime < doubleClickTime) { + xTimerStop(buttonTimer, 0); + state = States::Idle; + return ButtonActions::DoubleClick; + } + } else if (event == Events::Release) { + xTimerChangePeriod(buttonTimer, doubleClickTime, 0); + xTimerStart(buttonTimer, 0); + } else if (event == Events::Timer) { + if (buttonPressed) { + xTimerChangePeriod(buttonTimer, longPressTime - doubleClickTime, 0); + xTimerStart(buttonTimer, 0); + state = States::Holding; + } else { + state = States::Idle; + return ButtonActions::Click; + } + } + break; + case States::Holding: + if (event == Events::Release) { + xTimerStop(buttonTimer, 0); + state = States::Idle; + return ButtonActions::Click; + } else if (event == Events::Timer) { + xTimerChangePeriod(buttonTimer, longerPressTime - longPressTime - doubleClickTime, 0); + xTimerStart(buttonTimer, 0); + state = States::LongHeld; + return ButtonActions::LongPress; + } + break; + case States::LongHeld: + if (event == Events::Release) { + xTimerStop(buttonTimer, 0); + state = States::Idle; + } else if (event == Events::Timer) { + state = States::Idle; + return ButtonActions::LongerPress; + } + break; + } + return ButtonActions::None; +} diff --git a/src/buttonhandler/ButtonHandler.h b/src/buttonhandler/ButtonHandler.h new file mode 100644 index 00000000..44b20f19 --- /dev/null +++ b/src/buttonhandler/ButtonHandler.h @@ -0,0 +1,24 @@ +#pragma once + +#include "ButtonActions.h" +#include "systemtask/SystemTask.h" +#include +#include + +namespace Pinetime { + namespace Controllers { + class ButtonHandler { + public: + enum class Events : uint8_t { Press, Release, Timer }; + void Init(Pinetime::System::SystemTask* systemTask); + ButtonActions HandleEvent(Events event); + + private: + enum class States : uint8_t { Idle, Pressed, Holding, LongHeld }; + TickType_t releaseTime = 0; + TimerHandle_t buttonTimer; + bool buttonPressed = false; + States state = States::Idle; + }; + } +} diff --git a/src/components/alarm/AlarmController.cpp b/src/components/alarm/AlarmController.cpp index 67ca05a9..28b328d5 100644 --- a/src/components/alarm/AlarmController.cpp +++ b/src/components/alarm/AlarmController.cpp @@ -15,7 +15,7 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . */ -#include "AlarmController.h" +#include "components/alarm/AlarmController.h" #include "systemtask/SystemTask.h" #include "app_timer.h" #include "task.h" diff --git a/src/components/alarm/AlarmController.h b/src/components/alarm/AlarmController.h index bf85d431..f39fbded 100644 --- a/src/components/alarm/AlarmController.h +++ b/src/components/alarm/AlarmController.h @@ -18,7 +18,6 @@ #pragma once #include -#include "app_timer.h" #include "components/datetime/DateTimeController.h" namespace Pinetime { diff --git a/src/components/battery/BatteryController.cpp b/src/components/battery/BatteryController.cpp index e807f033..300d0978 100644 --- a/src/components/battery/BatteryController.cpp +++ b/src/components/battery/BatteryController.cpp @@ -1,8 +1,9 @@ -#include "BatteryController.h" +#include "components/battery/BatteryController.h" #include "drivers/PinMap.h" #include #include #include +#include using namespace Pinetime::Controllers; diff --git a/src/components/ble/AlertNotificationClient.cpp b/src/components/ble/AlertNotificationClient.cpp index 5e5c25cf..0f850874 100644 --- a/src/components/ble/AlertNotificationClient.cpp +++ b/src/components/ble/AlertNotificationClient.cpp @@ -1,6 +1,6 @@ -#include "AlertNotificationClient.h" +#include "components/ble/AlertNotificationClient.h" #include -#include "NotificationManager.h" +#include "components/ble/NotificationManager.h" #include "systemtask/SystemTask.h" using namespace Pinetime::Controllers; diff --git a/src/components/ble/AlertNotificationClient.h b/src/components/ble/AlertNotificationClient.h index dfba8143..2d6a3873 100644 --- a/src/components/ble/AlertNotificationClient.h +++ b/src/components/ble/AlertNotificationClient.h @@ -7,7 +7,7 @@ #include #undef max #undef min -#include "BleClient.h" +#include "components/ble/BleClient.h" namespace Pinetime { diff --git a/src/components/ble/AlertNotificationService.cpp b/src/components/ble/AlertNotificationService.cpp index 56fc595f..04819122 100644 --- a/src/components/ble/AlertNotificationService.cpp +++ b/src/components/ble/AlertNotificationService.cpp @@ -1,8 +1,8 @@ -#include "AlertNotificationService.h" +#include "components/ble/AlertNotificationService.h" #include #include #include -#include "NotificationManager.h" +#include "components/ble/NotificationManager.h" #include "systemtask/SystemTask.h" using namespace Pinetime::Controllers; @@ -53,8 +53,9 @@ int AlertNotificationService::OnAlert(uint16_t conn_handle, uint16_t attr_handle // Ignore notifications with empty message const auto packetLen = OS_MBUF_PKTLEN(ctxt->om); - if (packetLen <= headerSize) + if (packetLen <= headerSize) { return 0; + } size_t bufferSize = std::min(packetLen + stringTerminatorSize, maxBufferSize); auto messageSize = std::min(maxMessageSize, (bufferSize - headerSize)); diff --git a/src/components/ble/BatteryInformationService.cpp b/src/components/ble/BatteryInformationService.cpp index 29178667..9a3f86f5 100644 --- a/src/components/ble/BatteryInformationService.cpp +++ b/src/components/ble/BatteryInformationService.cpp @@ -1,5 +1,5 @@ +#include "components/ble/BatteryInformationService.h" #include -#include "BatteryInformationService.h" #include "components/battery/BatteryController.h" using namespace Pinetime::Controllers; diff --git a/src/components/ble/BleController.cpp b/src/components/ble/BleController.cpp index 7c14aeb7..a80c9719 100644 --- a/src/components/ble/BleController.cpp +++ b/src/components/ble/BleController.cpp @@ -1,4 +1,4 @@ -#include "BleController.h" +#include "components/ble/BleController.h" using namespace Pinetime::Controllers; diff --git a/src/components/ble/BleController.h b/src/components/ble/BleController.h index 2cba26a9..72b87663 100644 --- a/src/components/ble/BleController.h +++ b/src/components/ble/BleController.h @@ -9,7 +9,7 @@ namespace Pinetime { public: using BleAddress = std::array; enum class FirmwareUpdateStates { Idle, Running, Validated, Error }; - enum class AddressTypes { Public, Random }; + enum class AddressTypes { Public, Random, RPA_Public, RPA_Random }; Ble() = default; bool IsConnected() const { @@ -48,6 +48,12 @@ namespace Pinetime { void AddressType(AddressTypes t) { addressType = t; } + void SetPairingKey(uint32_t k) { + pairingKey = k; + } + uint32_t GetPairingKey() const { + return pairingKey; + } private: bool isConnected = false; @@ -57,6 +63,7 @@ namespace Pinetime { FirmwareUpdateStates firmwareUpdateState = FirmwareUpdateStates::Idle; BleAddress address; AddressTypes addressType; + uint32_t pairingKey = 0; }; } -} \ No newline at end of file +} diff --git a/src/components/ble/CurrentTimeClient.cpp b/src/components/ble/CurrentTimeClient.cpp index 90d1f0c7..dd8171b9 100644 --- a/src/components/ble/CurrentTimeClient.cpp +++ b/src/components/ble/CurrentTimeClient.cpp @@ -1,4 +1,4 @@ -#include "CurrentTimeClient.h" +#include "components/ble/CurrentTimeClient.h" #include #include #include "components/datetime/DateTimeController.h" diff --git a/src/components/ble/CurrentTimeClient.h b/src/components/ble/CurrentTimeClient.h index 6424c035..9e48be79 100644 --- a/src/components/ble/CurrentTimeClient.h +++ b/src/components/ble/CurrentTimeClient.h @@ -5,7 +5,7 @@ #undef max #undef min #include -#include "BleClient.h" +#include "components/ble/BleClient.h" namespace Pinetime { namespace Controllers { diff --git a/src/components/ble/CurrentTimeService.cpp b/src/components/ble/CurrentTimeService.cpp index eefb7ec1..e509aeaf 100644 --- a/src/components/ble/CurrentTimeService.cpp +++ b/src/components/ble/CurrentTimeService.cpp @@ -1,4 +1,4 @@ -#include "CurrentTimeService.h" +#include "components/ble/CurrentTimeService.h" #include #include diff --git a/src/components/ble/DeviceInformationService.cpp b/src/components/ble/DeviceInformationService.cpp index 778d6e35..0f47c90f 100644 --- a/src/components/ble/DeviceInformationService.cpp +++ b/src/components/ble/DeviceInformationService.cpp @@ -1,4 +1,4 @@ -#include "DeviceInformationService.h" +#include "components/ble/DeviceInformationService.h" using namespace Pinetime::Controllers; diff --git a/src/components/ble/DeviceInformationService.h b/src/components/ble/DeviceInformationService.h index 54b3e961..a269afb4 100644 --- a/src/components/ble/DeviceInformationService.h +++ b/src/components/ble/DeviceInformationService.h @@ -1,4 +1,5 @@ #pragma once +#include #define min // workaround: nimble's min/max macros conflict with libstdc++ #define max #include diff --git a/src/components/ble/DfuService.cpp b/src/components/ble/DfuService.cpp index 3d6416fa..71dcc7e6 100644 --- a/src/components/ble/DfuService.cpp +++ b/src/components/ble/DfuService.cpp @@ -1,4 +1,4 @@ -#include "DfuService.h" +#include "components/ble/DfuService.h" #include #include "components/ble/BleController.h" #include "drivers/SpiNorFlash.h" diff --git a/src/components/ble/FSService.cpp b/src/components/ble/FSService.cpp new file mode 100644 index 00000000..8dc9ed67 --- /dev/null +++ b/src/components/ble/FSService.cpp @@ -0,0 +1,330 @@ +#include +#include "FSService.h" +#include "components/ble/BleController.h" +#include "systemtask/SystemTask.h" + +using namespace Pinetime::Controllers; + +constexpr ble_uuid16_t FSService::fsServiceUuid; +constexpr ble_uuid128_t FSService::fsVersionUuid; +constexpr ble_uuid128_t FSService::fsTransferUuid; + +int FSServiceCallback(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt* ctxt, void* arg) { + auto* fsService = static_cast(arg); + return fsService->OnFSServiceRequested(conn_handle, attr_handle, ctxt); +} + +FSService::FSService(Pinetime::System::SystemTask& systemTask, Pinetime::Controllers::FS& fs) + : systemTask {systemTask}, + fs {fs}, + characteristicDefinition {{.uuid = &fsVersionUuid.u, + .access_cb = FSServiceCallback, + .arg = this, + .flags = BLE_GATT_CHR_F_READ, + .val_handle = &versionCharacteristicHandle}, + { + .uuid = &fsTransferUuid.u, + .access_cb = FSServiceCallback, + .arg = this, + .flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_NOTIFY, + .val_handle = &transferCharacteristicHandle, + }, + {0}}, + serviceDefinition { + {/* Device Information Service */ + .type = BLE_GATT_SVC_TYPE_PRIMARY, + .uuid = &fsServiceUuid.u, + .characteristics = characteristicDefinition}, + {0}, + } { +} + +void FSService::Init() { + int res = 0; + res = ble_gatts_count_cfg(serviceDefinition); + ASSERT(res == 0); + + res = ble_gatts_add_svcs(serviceDefinition); + ASSERT(res == 0); +} + +int FSService::OnFSServiceRequested(uint16_t connectionHandle, uint16_t attributeHandle, ble_gatt_access_ctxt* context) { + if (attributeHandle == versionCharacteristicHandle) { + NRF_LOG_INFO("FS_S : handle = %d", versionCharacteristicHandle); + int res = os_mbuf_append(context->om, &fsVersion, sizeof(fsVersion)); + return (res == 0) ? 0 : BLE_ATT_ERR_INSUFFICIENT_RES; + } + if (attributeHandle == transferCharacteristicHandle) { + return FSCommandHandler(connectionHandle, context->om); + } + return 0; +} + +int FSService::FSCommandHandler(uint16_t connectionHandle, os_mbuf* om) { + auto command = static_cast(om->om_data[0]); + NRF_LOG_INFO("[FS_S] -> FSCommandHandler Command %d", command); + // Just always make sure we are awake... + systemTask.PushMessage(Pinetime::System::Messages::StartFileTransfer); + vTaskDelay(10); + while (systemTask.IsSleeping()) { + vTaskDelay(100); // 50ms + } + lfs_dir_t dir = {0}; + lfs_info info = {0}; + lfs_file f = {0}; + switch (command) { + case commands::READ: { + NRF_LOG_INFO("[FS_S] -> Read"); + auto* header = (ReadHeader*) om->om_data; + uint16_t plen = header->pathlen; + if (plen > maxpathlen) { //> counts for null term + return -1; + } + memcpy(filepath, header->pathstr, plen); + filepath[plen] = 0; // Copy and null teminate string + ReadResponse resp; + os_mbuf* om; + resp.command = commands::READ_DATA; + resp.status = 0x01; + resp.chunkoff = header->chunkoff; + int res = fs.Stat(filepath, &info); + if (res == LFS_ERR_NOENT && info.type != LFS_TYPE_DIR) { + resp.status = (int8_t) res; + resp.chunklen = 0; + resp.totallen = 0; + om = ble_hs_mbuf_from_flat(&resp, sizeof(ReadResponse)); + } else { + resp.chunklen = std::min(header->chunksize, info.size); // TODO add mtu somehow + resp.totallen = info.size; + fs.FileOpen(&f, filepath, LFS_O_RDONLY); + fs.FileSeek(&f, header->chunkoff); + uint8_t fileData[resp.chunklen] = {0}; + resp.chunklen = fs.FileRead(&f, fileData, resp.chunklen); + om = ble_hs_mbuf_from_flat(&resp, sizeof(ReadResponse)); + os_mbuf_append(om, fileData, resp.chunklen); + fs.FileClose(&f); + } + + ble_gattc_notify_custom(connectionHandle, transferCharacteristicHandle, om); + break; + } + case commands::READ_PACING: { + NRF_LOG_INFO("[FS_S] -> Readpacing"); + auto* header = (ReadHeader*) om->om_data; + ReadResponse resp; + resp.command = commands::READ_DATA; + resp.status = 0x01; + resp.chunkoff = header->chunkoff; + int res = fs.Stat(filepath, &info); + if (res == LFS_ERR_NOENT && info.type != LFS_TYPE_DIR) { + resp.status = (int8_t) res; + resp.chunklen = 0; + resp.totallen = 0; + } else { + resp.chunklen = std::min(header->chunksize, info.size); // TODO add mtu somehow + resp.totallen = info.size; + fs.FileOpen(&f, filepath, LFS_O_RDONLY); + fs.FileSeek(&f, header->chunkoff); + } + os_mbuf* om; + if (resp.chunklen > 0) { + uint8_t fileData[resp.chunklen] = {0}; + resp.chunklen = fs.FileRead(&f, fileData, resp.chunklen); + om = ble_hs_mbuf_from_flat(&resp, sizeof(ReadResponse)); + os_mbuf_append(om, fileData, resp.chunklen); + } else { + resp.chunklen = 0; + om = ble_hs_mbuf_from_flat(&resp, sizeof(ReadResponse)); + } + fs.FileClose(&f); + ble_gattc_notify_custom(connectionHandle, transferCharacteristicHandle, om); + break; + } + case commands::WRITE: { + NRF_LOG_INFO("[FS_S] -> Write"); + auto* header = (WriteHeader*) om->om_data; + uint16_t plen = header->pathlen; + if (plen > maxpathlen) { //> counts for null term + return -1; // TODO make this actually return a BLE notif + } + memcpy(filepath, header->pathstr, plen); + filepath[plen] = 0; // Copy and null teminate string + fileSize = header->totalSize; + WriteResponse resp; + resp.command = commands::WRITE_PACING; + resp.offset = header->offset; + resp.modTime = 0; + + int res = fs.FileOpen(&f, filepath, LFS_O_RDWR | LFS_O_CREAT); + if (res == 0) { + fs.FileClose(&f); + resp.status = (res == 0) ? 0x01 : (int8_t) res; + } + resp.freespace = std::min(fs.getSize() - (fs.GetFSSize() * fs.getBlockSize()), fileSize - header->offset); + auto* om = ble_hs_mbuf_from_flat(&resp, sizeof(WriteResponse)); + ble_gattc_notify_custom(connectionHandle, transferCharacteristicHandle, om); + break; + } + case commands::WRITE_DATA: { + NRF_LOG_INFO("[FS_S] -> WriteData"); + auto* header = (WritePacing*) om->om_data; + WriteResponse resp; + resp.command = commands::WRITE_PACING; + resp.offset = header->offset; + int res = 0; + + if (!(res = fs.FileOpen(&f, filepath, LFS_O_RDWR | LFS_O_CREAT))) { + if ((res = fs.FileSeek(&f, header->offset)) >= 0) { + res = fs.FileWrite(&f, header->data, header->dataSize); + } + fs.FileClose(&f); + } + if (res < 0) { + resp.status = (int8_t) res; + } + resp.freespace = std::min(fs.getSize() - (fs.GetFSSize() * fs.getBlockSize()), fileSize - header->offset); + auto* om = ble_hs_mbuf_from_flat(&resp, sizeof(WriteResponse)); + ble_gattc_notify_custom(connectionHandle, transferCharacteristicHandle, om); + break; + } + case commands::DELETE: { + NRF_LOG_INFO("[FS_S] -> Delete"); + auto* header = (DelHeader*) om->om_data; + uint16_t plen = header->pathlen; + char path[plen + 1] = {0}; + memcpy(path, header->pathstr, plen); + path[plen] = 0; // Copy and null teminate string + DelResponse resp {}; + resp.command = commands::DELETE_STATUS; + int res = fs.FileDelete(path); + resp.status = (res == 0) ? 0x01 : (int8_t) res; + auto* om = ble_hs_mbuf_from_flat(&resp, sizeof(DelResponse)); + ble_gattc_notify_custom(connectionHandle, transferCharacteristicHandle, om); + break; + } + case commands::MKDIR: { + NRF_LOG_INFO("[FS_S] -> MKDir"); + auto* header = (MKDirHeader*) om->om_data; + uint16_t plen = header->pathlen; + char path[plen + 1] = {0}; + memcpy(path, header->pathstr, plen); + path[plen] = 0; // Copy and null teminate string + MKDirResponse resp {}; + resp.command = commands::MKDIR_STATUS; + resp.modification_time = 0; + int res = fs.DirCreate(path); + resp.status = (res == 0) ? 0x01 : (int8_t) res; + auto* om = ble_hs_mbuf_from_flat(&resp, sizeof(MKDirResponse)); + ble_gattc_notify_custom(connectionHandle, transferCharacteristicHandle, om); + break; + } + case commands::LISTDIR: { + NRF_LOG_INFO("[FS_S] -> ListDir"); + ListDirHeader* header = (ListDirHeader*) om->om_data; + uint16_t plen = header->pathlen; + char path[plen + 1] = {0}; + path[plen] = 0; // Copy and null teminate string + memcpy(path, header->pathstr, plen); + + ListDirResponse resp {}; + + resp.command = commands::LISTDIR_ENTRY; + resp.status = 0x01; + resp.totalentries = 0; + resp.entry = 0; + resp.modification_time = 0; + int res = fs.DirOpen(path, &dir); + if (res != 0) { + resp.status = (int8_t) res; + auto* om = ble_hs_mbuf_from_flat(&resp, sizeof(ListDirResponse)); + ble_gattc_notify_custom(connectionHandle, transferCharacteristicHandle, om); + break; + }; + while (fs.DirRead(&dir, &info)) { + resp.totalentries++; + } + fs.DirRewind(&dir); + while (true) { + res = fs.DirRead(&dir, &info); + if (res <= 0) { + break; + } + switch (info.type) { + case LFS_TYPE_REG: { + resp.flags = 0; + resp.file_size = info.size; + break; + } + case LFS_TYPE_DIR: { + resp.flags = 1; + resp.file_size = 0; + break; + } + } + + // strcpy(resp.path, info.name); + resp.path_length = strlen(info.name); + auto* om = ble_hs_mbuf_from_flat(&resp, sizeof(ListDirResponse)); + os_mbuf_append(om, info.name, resp.path_length); + ble_gattc_notify_custom(connectionHandle, transferCharacteristicHandle, om); + /* + * Todo Figure out how to know when the previous Notify was TX'd + * For now just delay 100ms to make sure that the data went out... + */ + vTaskDelay(100); // Allow stuff to actually go out over the BLE conn + resp.entry++; + } + assert(fs.DirClose(&dir) == 0); + resp.file_size = 0; + resp.path_length = 0; + resp.flags = 0; + auto* om = ble_hs_mbuf_from_flat(&resp, sizeof(ListDirResponse)); + ble_gattc_notify_custom(connectionHandle, transferCharacteristicHandle, om); + break; + } + case commands::MOVE: { + NRF_LOG_INFO("[FS_S] -> Move"); + MoveHeader* header = (MoveHeader*) om->om_data; + uint16_t plen = header->OldPathLength; + // Null Terminate string + header->pathstr[plen] = 0; + char path[header->NewPathLength + 1] = {0}; + memcpy(path, &header->pathstr[plen + 1], header->NewPathLength); + path[header->NewPathLength] = 0; // Copy and null teminate string + MoveResponse resp {}; + resp.command = commands::MOVE_STATUS; + int8_t res = (int8_t) fs.Rename(header->pathstr, path); + resp.status = (res == 0) ? 1 : res; + auto* om = ble_hs_mbuf_from_flat(&resp, sizeof(MoveResponse)); + ble_gattc_notify_custom(connectionHandle, transferCharacteristicHandle, om); + } + default: + break; + } + NRF_LOG_INFO("[FS_S] -> done "); + systemTask.PushMessage(Pinetime::System::Messages::StopFileTransfer); + return 0; +} + +// Loads resp with file data given a valid filepath header and resp +void FSService::prepareReadDataResp(ReadHeader* header, ReadResponse* resp) { + // uint16_t plen = header->pathlen; + resp->command = commands::READ_DATA; + resp->chunkoff = header->chunkoff; + resp->status = 0x01; + struct lfs_info info = {}; + int res = fs.Stat(filepath, &info); + if (res == LFS_ERR_NOENT && info.type != LFS_TYPE_DIR) { + resp->status = 0x03; + resp->chunklen = 0; + resp->totallen = 0; + } else { + lfs_file f; + resp->chunklen = std::min(header->chunksize, info.size); + resp->totallen = info.size; + fs.FileOpen(&f, filepath, LFS_O_RDONLY); + fs.FileSeek(&f, header->chunkoff); + resp->chunklen = fs.FileRead(&f, resp->chunk, resp->chunklen); + fs.FileClose(&f); + } +} diff --git a/src/components/ble/FSService.h b/src/components/ble/FSService.h new file mode 100644 index 00000000..828925a8 --- /dev/null +++ b/src/components/ble/FSService.h @@ -0,0 +1,191 @@ +#pragma once +#define min // workaround: nimble's min/max macros conflict with libstdc++ +#define max +#include +#undef max +#undef min + +#include "components/fs/FS.h" + +namespace Pinetime { + namespace System { + class SystemTask; + } + namespace Controllers { + class Ble; + class FSService { + public: + FSService(Pinetime::System::SystemTask& systemTask, Pinetime::Controllers::FS& fs); + void Init(); + + int OnFSServiceRequested(uint16_t connectionHandle, uint16_t attributeHandle, ble_gatt_access_ctxt* context); + void NotifyFSRaw(uint16_t connectionHandle); + + private: + Pinetime::System::SystemTask& systemTask; + Pinetime::Controllers::FS& fs; + static constexpr uint16_t FSServiceId {0xFEBB}; + static constexpr uint16_t fsVersionId {0x0100}; + static constexpr uint16_t fsTransferId {0x0200}; + uint16_t fsVersion = {0x0004}; + static constexpr uint16_t maxpathlen = 256; + static constexpr ble_uuid16_t fsServiceUuid { + .u {.type = BLE_UUID_TYPE_16}, + .value = {0xFEBB}}; // {0x72, 0x65, 0x66, 0x73, 0x6e, 0x61, 0x72, 0x54, 0x65, 0x6c, 0x69, 0x46, 0xBB, 0xFE, 0xAF, 0xAD}}; + + static constexpr ble_uuid128_t fsVersionUuid { + .u {.type = BLE_UUID_TYPE_128}, + .value = {0x72, 0x65, 0x66, 0x73, 0x6e, 0x61, 0x72, 0x54, 0x65, 0x6c, 0x69, 0x46, 0x00, 0x01, 0xAF, 0xAD}}; + + static constexpr ble_uuid128_t fsTransferUuid { + .u {.type = BLE_UUID_TYPE_128}, + .value = {0x72, 0x65, 0x66, 0x73, 0x6e, 0x61, 0x72, 0x54, 0x65, 0x6c, 0x69, 0x46, 0x00, 0x02, 0xAF, 0xAD}}; + + struct ble_gatt_chr_def characteristicDefinition[3]; + struct ble_gatt_svc_def serviceDefinition[2]; + uint16_t versionCharacteristicHandle; + uint16_t transferCharacteristicHandle; + + enum class commands : uint8_t { + INVALID = 0x00, + READ = 0x10, + READ_DATA = 0x11, + READ_PACING = 0x12, + WRITE = 0x20, + WRITE_PACING = 0x21, + WRITE_DATA = 0x22, + DELETE = 0x30, + DELETE_STATUS = 0x31, + MKDIR = 0x40, + MKDIR_STATUS = 0x41, + LISTDIR = 0x50, + LISTDIR_ENTRY = 0x51, + MOVE = 0x60, + MOVE_STATUS = 0x61 + }; + enum class FSState : uint8_t { + IDLE = 0x00, + READ = 0x01, + WRITE = 0x02, + }; + FSState state; + char filepath[maxpathlen]; // TODO ..ugh fixed filepath len + int fileSize; + using ReadHeader = struct __attribute__((packed)) { + commands command; + uint8_t padding; + uint16_t pathlen; + uint32_t chunkoff; + uint32_t chunksize; + char pathstr[]; + }; + + using ReadResponse = struct __attribute__((packed)) { + commands command; + uint8_t status; + uint16_t padding; + uint32_t chunkoff; + uint32_t totallen; + uint32_t chunklen; + uint8_t chunk[]; + }; + using ReadPacing = struct __attribute__((packed)) { + commands command; + uint8_t status; + uint16_t padding; + uint32_t chunkoff; + uint32_t chunksize; + }; + + using WriteHeader = struct __attribute__((packed)) { + commands command; + uint8_t padding; + uint16_t pathlen; + uint32_t offset; + uint64_t modTime; + uint32_t totalSize; + char pathstr[]; + }; + + using WriteResponse = struct __attribute__((packed)) { + commands command; + uint8_t status; + uint16_t padding; + uint32_t offset; + uint64_t modTime; + uint32_t freespace; + }; + + using WritePacing = struct __attribute__((packed)) { + commands command; + uint8_t status; + uint16_t padding; + uint32_t offset; + uint32_t dataSize; + uint8_t data[]; + }; + using ListDirHeader = struct __attribute__((packed)) { + commands command; + uint8_t padding; + uint16_t pathlen; + char pathstr[]; + }; + + using ListDirResponse = struct __attribute__((packed)) { + commands command; + uint8_t status; + uint16_t path_length; + uint32_t entry; + uint32_t totalentries; + uint32_t flags; + uint64_t modification_time; + uint32_t file_size; + char path[]; + }; + + using MKDirHeader = struct __attribute__((packed)) { + commands command; + uint8_t padding; + uint16_t pathlen; + uint32_t padding2; + uint64_t time; + char pathstr[]; + }; + + using MKDirResponse = struct __attribute__((packed)) { + commands command; + uint8_t status; + uint32_t padding1; + uint16_t padding2; + uint64_t modification_time; + }; + + using DelHeader = struct __attribute__((packed)) { + commands command; + uint8_t padding; + uint16_t pathlen; + char pathstr[]; + }; + + using DelResponse = struct __attribute__((packed)) { + commands command; + uint8_t status; + }; + using MoveHeader = struct __attribute__((packed)) { + commands command; + uint8_t padding; + uint16_t OldPathLength; + uint16_t NewPathLength; + char pathstr[]; + }; + + using MoveResponse = struct __attribute__((packed)) { + commands command; + uint8_t status; + }; + + int FSCommandHandler(uint16_t connectionHandle, os_mbuf* om); + void prepareReadDataResp(ReadHeader* header, ReadResponse* resp); + }; + } +} diff --git a/src/components/ble/HeartRateService.cpp b/src/components/ble/HeartRateService.cpp index 75a038a2..f178af79 100644 --- a/src/components/ble/HeartRateService.cpp +++ b/src/components/ble/HeartRateService.cpp @@ -1,4 +1,4 @@ -#include "HeartRateService.h" +#include "components/ble/HeartRateService.h" #include "components/heartrate/HeartRateController.h" #include "systemtask/SystemTask.h" diff --git a/src/components/ble/ImmediateAlertService.cpp b/src/components/ble/ImmediateAlertService.cpp index 17ed1a96..c80b3783 100644 --- a/src/components/ble/ImmediateAlertService.cpp +++ b/src/components/ble/ImmediateAlertService.cpp @@ -1,6 +1,6 @@ -#include "ImmediateAlertService.h" +#include "components/ble/ImmediateAlertService.h" #include -#include "NotificationManager.h" +#include "components/ble/NotificationManager.h" #include "systemtask/SystemTask.h" using namespace Pinetime::Controllers; diff --git a/src/components/ble/MotionService.cpp b/src/components/ble/MotionService.cpp index b4786ab5..6381915d 100644 --- a/src/components/ble/MotionService.cpp +++ b/src/components/ble/MotionService.cpp @@ -1,11 +1,11 @@ -#include "MotionService.h" -#include "components/motion//MotionController.h" +#include "components/ble/MotionService.h" +#include "components/motion/MotionController.h" #include "systemtask/SystemTask.h" using namespace Pinetime::Controllers; namespace { - // 0002yyxx-78fc-48fe-8e23-433b3a1942d0 + // 0003yyxx-78fc-48fe-8e23-433b3a1942d0 constexpr ble_uuid128_t CharUuid(uint8_t x, uint8_t y) { return ble_uuid128_t{ .u = {.type = BLE_UUID_TYPE_128}, @@ -13,7 +13,7 @@ namespace { }; } - // 00020000-78fc-48fe-8e23-433b3a1942d0 + // 00030000-78fc-48fe-8e23-433b3a1942d0 constexpr ble_uuid128_t BaseUuid() { return CharUuid(0x00, 0x00); } diff --git a/src/components/ble/MusicService.cpp b/src/components/ble/MusicService.cpp index 74fe9522..3457ce4c 100644 --- a/src/components/ble/MusicService.cpp +++ b/src/components/ble/MusicService.cpp @@ -15,7 +15,7 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . */ -#include "MusicService.h" +#include "components/ble/MusicService.h" #include "systemtask/SystemTask.h" namespace { diff --git a/src/components/ble/NavigationService.cpp b/src/components/ble/NavigationService.cpp index b49148d2..5418b9e5 100644 --- a/src/components/ble/NavigationService.cpp +++ b/src/components/ble/NavigationService.cpp @@ -16,7 +16,7 @@ along with this program. If not, see . */ -#include "NavigationService.h" +#include "components/ble/NavigationService.h" #include "systemtask/SystemTask.h" diff --git a/src/components/ble/NimbleController.cpp b/src/components/ble/NimbleController.cpp index 1bcae1bc..d8510bd3 100644 --- a/src/components/ble/NimbleController.cpp +++ b/src/components/ble/NimbleController.cpp @@ -1,4 +1,6 @@ -#include "NimbleController.h" +#include "components/ble/NimbleController.h" +#include + #include #define min // workaround: nimble's min/max macros conflict with libstdc++ #define max @@ -6,13 +8,16 @@ #include #include #include -#undef max -#undef min +#include +#include #include #include +#undef max +#undef min #include "components/ble/BleController.h" #include "components/ble/NotificationManager.h" #include "components/datetime/DateTimeController.h" +#include "components/fs/FS.h" #include "systemtask/SystemTask.h" using namespace Pinetime::Controllers; @@ -24,37 +29,44 @@ NimbleController::NimbleController(Pinetime::System::SystemTask& systemTask, Controllers::Battery& batteryController, Pinetime::Drivers::SpiNorFlash& spiNorFlash, Controllers::HeartRateController& heartRateController, - Controllers::MotionController& motionController) + Controllers::MotionController& motionController, + Controllers::FS& fs) : systemTask {systemTask}, bleController {bleController}, dateTimeController {dateTimeController}, notificationManager {notificationManager}, spiNorFlash {spiNorFlash}, + fs {fs}, dfuService {systemTask, bleController, spiNorFlash}, + currentTimeClient {dateTimeController}, anService {systemTask, notificationManager}, alertNotificationClient {systemTask, notificationManager}, currentTimeService {dateTimeController}, musicService {systemTask}, + weatherService {systemTask, dateTimeController}, navService {systemTask}, batteryInformationService {batteryController}, immediateAlertService {systemTask, notificationManager}, heartRateService {systemTask, heartRateController}, - motionService{systemTask, motionController}, + motionService {systemTask, motionController}, + fsService {systemTask, fs}, serviceDiscovery({¤tTimeClient, &alertNotificationClient}) { } void nimble_on_reset(int reason) { - NRF_LOG_INFO("Resetting state; reason=%d\n", reason); + NRF_LOG_INFO("Nimble lost sync, resetting state; reason=%d", reason); } void nimble_on_sync(void) { - int rc; + int rc; - rc = ble_hs_util_ensure_addr(0); - ASSERT(rc == 0); + NRF_LOG_INFO("Nimble is synced"); - nptr->StartAdvertising(); + rc = ble_hs_util_ensure_addr(0); + ASSERT(rc == 0); + + nptr->StartAdvertising(); } int GAPEventCallback(struct ble_gap_event* event, void* arg) { @@ -69,6 +81,7 @@ void NimbleController::Init() { nptr = this; ble_hs_cfg.reset_cb = nimble_on_reset; ble_hs_cfg.sync_cb = nimble_on_sync; + ble_hs_cfg.store_status_cb = ble_store_util_status_rr; ble_svc_gap_init(); ble_svc_gatt_init(); @@ -77,6 +90,7 @@ void NimbleController::Init() { currentTimeClient.Init(); currentTimeService.Init(); musicService.Init(); + weatherService.Init(); navService.Init(); anService.Init(); dfuService.Init(); @@ -84,6 +98,7 @@ void NimbleController::Init() { immediateAlertService.Init(); heartRateService.Init(); motionService.Init(); + fsService.Init(); int rc; rc = ble_hs_util_ensure_addr(0); @@ -97,28 +112,36 @@ void NimbleController::Init() { Pinetime::Controllers::Ble::BleAddress address; rc = ble_hs_id_copy_addr(addrType, address.data(), nullptr); ASSERT(rc == 0); - bleController.AddressType((addrType == 0) ? Ble::AddressTypes::Public : Ble::AddressTypes::Random); + bleController.Address(std::move(address)); + switch (addrType) { + case BLE_OWN_ADDR_PUBLIC: + bleController.AddressType(Ble::AddressTypes::Public); + break; + case BLE_OWN_ADDR_RANDOM: + bleController.AddressType(Ble::AddressTypes::Random); + break; + case BLE_OWN_ADDR_RPA_PUBLIC_DEFAULT: + bleController.AddressType(Ble::AddressTypes::RPA_Public); + break; + case BLE_OWN_ADDR_RPA_RANDOM_DEFAULT: + bleController.AddressType(Ble::AddressTypes::RPA_Random); + break; + } rc = ble_gatts_start(); ASSERT(rc == 0); - if (!ble_gap_adv_active() && !bleController.IsConnected()) - StartAdvertising(); + RestoreBond(); + + StartAdvertising(); } void NimbleController::StartAdvertising() { - int rc; - - /* set adv parameters */ struct ble_gap_adv_params adv_params; struct ble_hs_adv_fields fields; - /* advertising payload is split into advertising data and advertising - response, because all data cannot fit into single packet; name of device - is sent as response to scan request */ struct ble_hs_adv_fields rsp_fields; - /* fill all fields and parameters with zeros */ memset(&adv_params, 0, sizeof(adv_params)); memset(&fields, 0, sizeof(fields)); memset(&rsp_fields, 0, sizeof(rsp_fields)); @@ -141,10 +164,11 @@ void NimbleController::StartAdvertising() { fields.uuids128_is_complete = 1; fields.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO; - rsp_fields.name = (uint8_t*) deviceName; + rsp_fields.name = reinterpret_cast(deviceName); rsp_fields.name_len = strlen(deviceName); rsp_fields.name_is_complete = 1; + int rc; rc = ble_gap_adv_set_fields(&fields); ASSERT(rc == 0); @@ -159,15 +183,14 @@ int NimbleController::OnGAPEvent(ble_gap_event* event) { switch (event->type) { case BLE_GAP_EVENT_ADV_COMPLETE: NRF_LOG_INFO("Advertising event : BLE_GAP_EVENT_ADV_COMPLETE"); - NRF_LOG_INFO("reason=%d; status=%d", event->adv_complete.reason, event->connect.status); + NRF_LOG_INFO("reason=%d; status=%0X", event->adv_complete.reason, event->connect.status); StartAdvertising(); break; case BLE_GAP_EVENT_CONNECT: - NRF_LOG_INFO("Advertising event : BLE_GAP_EVENT_CONNECT"); - /* A new connection was established or a connection attempt failed. */ - NRF_LOG_INFO("connection %s; status=%d ", event->connect.status == 0 ? "established" : "failed", event->connect.status); + NRF_LOG_INFO("Connect event : BLE_GAP_EVENT_CONNECT"); + NRF_LOG_INFO("connection %s; status=%0X ", event->connect.status == 0 ? "established" : "failed", event->connect.status); if (event->connect.status != 0) { /* Connection failed; resume advertising. */ @@ -186,10 +209,14 @@ int NimbleController::OnGAPEvent(ble_gap_event* event) { break; case BLE_GAP_EVENT_DISCONNECT: - NRF_LOG_INFO("Advertising event : BLE_GAP_EVENT_DISCONNECT"); + /* Connection terminated; resume advertising. */ + NRF_LOG_INFO("Disconnect event : BLE_GAP_EVENT_DISCONNECT"); NRF_LOG_INFO("disconnect reason=%d", event->disconnect.reason); - /* Connection terminated; resume advertising. */ + if (event->disconnect.conn.sec_state.bonded) { + PersistBond(event->disconnect.conn); + } + currentTimeClient.Reset(); alertNotificationClient.Reset(); connectionHandle = BLE_HS_CONN_HANDLE_NONE; @@ -199,18 +226,67 @@ int NimbleController::OnGAPEvent(ble_gap_event* event) { break; case BLE_GAP_EVENT_CONN_UPDATE: - NRF_LOG_INFO("Advertising event : BLE_GAP_EVENT_CONN_UPDATE"); /* The central has updated the connection parameters. */ - NRF_LOG_INFO("update status=%d ", event->conn_update.status); + NRF_LOG_INFO("Update event : BLE_GAP_EVENT_CONN_UPDATE"); + NRF_LOG_INFO("update status=%0X ", event->conn_update.status); + break; + + case BLE_GAP_EVENT_CONN_UPDATE_REQ: + /* The central has requested updated connection parameters */ + NRF_LOG_INFO("Update event : BLE_GAP_EVENT_CONN_UPDATE_REQ"); + NRF_LOG_INFO("update request : itvl_min=%d itvl_max=%d latency=%d supervision=%d", + event->conn_update_req.peer_params->itvl_min, + event->conn_update_req.peer_params->itvl_max, + event->conn_update_req.peer_params->latency, + event->conn_update_req.peer_params->supervision_timeout); break; case BLE_GAP_EVENT_ENC_CHANGE: /* Encryption has been enabled or disabled for this connection. */ - NRF_LOG_INFO("encryption change event; status=%d ", event->enc_change.status); + NRF_LOG_INFO("Security event : BLE_GAP_EVENT_ENC_CHANGE"); + NRF_LOG_INFO("encryption change event; status=%0X ", event->enc_change.status); + + if (event->enc_change.status == 0) { + struct ble_gap_conn_desc desc; + ble_gap_conn_find(event->enc_change.conn_handle, &desc); + if (desc.sec_state.bonded) { + PersistBond(desc); + } + + NRF_LOG_INFO("new state: encrypted=%d authenticated=%d bonded=%d key_size=%d", + desc.sec_state.encrypted, + desc.sec_state.authenticated, + desc.sec_state.bonded, + desc.sec_state.key_size); + } + break; + + case BLE_GAP_EVENT_PASSKEY_ACTION: + /* Authentication has been requested for this connection. + * + * BLE authentication is determined by the combination of I/O capabilities + * on the central and peripheral. When the peripheral is display only and + * the central has a keyboard and display then passkey auth is selected. + * When both the central and peripheral have displays and support yes/no + * buttons then numeric comparison is selected. We currently advertise + * display capability only so we only handle the "display" action here. + * + * Standards insist that the rand() PRNG be deterministic. + * Use the tinycrypt prng here since rand() is predictable. + */ + NRF_LOG_INFO("Security event : BLE_GAP_EVENT_PASSKEY_ACTION"); + if (event->passkey.params.action == BLE_SM_IOACT_DISP) { + struct ble_sm_io pkey = {0}; + pkey.action = event->passkey.params.action; + pkey.passkey = ble_ll_rand() % 1000000; + bleController.SetPairingKey(pkey.passkey); + systemTask.PushMessage(Pinetime::System::Messages::OnPairing); + ble_sm_inject_io(event->passkey.conn_handle, &pkey); + } break; case BLE_GAP_EVENT_SUBSCRIBE: - NRF_LOG_INFO("subscribe event; conn_handle=%d attr_handle=%d " + NRF_LOG_INFO("Subscribe event; conn_handle=%d attr_handle=%d " "reason=%d prevn=%d curn=%d previ=%d curi=???\n", event->subscribe.conn_handle, event->subscribe.attr_handle, @@ -219,26 +295,24 @@ int NimbleController::OnGAPEvent(ble_gap_event* event) { event->subscribe.cur_notify, event->subscribe.prev_indicate); - if(event->subscribe.reason == BLE_GAP_SUBSCRIBE_REASON_TERM) { + if (event->subscribe.reason == BLE_GAP_SUBSCRIBE_REASON_TERM) { heartRateService.UnsubscribeNotification(event->subscribe.conn_handle, event->subscribe.attr_handle); motionService.UnsubscribeNotification(event->subscribe.conn_handle, event->subscribe.attr_handle); - } - else if(event->subscribe.prev_notify == 0 && event->subscribe.cur_notify == 1) { + } else if (event->subscribe.prev_notify == 0 && event->subscribe.cur_notify == 1) { heartRateService.SubscribeNotification(event->subscribe.conn_handle, event->subscribe.attr_handle); motionService.SubscribeNotification(event->subscribe.conn_handle, event->subscribe.attr_handle); - } - else if(event->subscribe.prev_notify == 1 && event->subscribe.cur_notify == 0) { + } else if (event->subscribe.prev_notify == 1 && event->subscribe.cur_notify == 0) { heartRateService.UnsubscribeNotification(event->subscribe.conn_handle, event->subscribe.attr_handle); motionService.UnsubscribeNotification(event->subscribe.conn_handle, event->subscribe.attr_handle); } break; case BLE_GAP_EVENT_MTU: - NRF_LOG_INFO("mtu update event; conn_handle=%d cid=%d mtu=%d\n", - event->mtu.conn_handle, event->mtu.channel_id, event->mtu.value); + NRF_LOG_INFO("MTU Update event; conn_handle=%d cid=%d mtu=%d", event->mtu.conn_handle, event->mtu.channel_id, event->mtu.value); break; case BLE_GAP_EVENT_REPEAT_PAIRING: { + NRF_LOG_INFO("Pairing event : BLE_GAP_EVENT_REPEAT_PAIRING"); /* We already have a bond with the peer, but it is attempting to * establish a new secure link. This app sacrifices security for * convenience: just throw away the old bond and accept the new link. @@ -257,6 +331,8 @@ int NimbleController::OnGAPEvent(ble_gap_event* event) { case BLE_GAP_EVENT_NOTIFY_RX: { /* Peer sent us a notification or indication. */ + /* Attribute data is contained in event->notify_rx.attr_data. */ + NRF_LOG_INFO("Notify event : BLE_GAP_EVENT_NOTIFY_RX"); size_t notifSize = OS_MBUF_PKTLEN(event->notify_rx.om); NRF_LOG_INFO("received %s; conn_handle=%d attr_handle=%d " @@ -268,10 +344,17 @@ int NimbleController::OnGAPEvent(ble_gap_event* event) { alertNotificationClient.OnNotification(event); } break; - /* Attribute data is contained in event->notify_rx.attr_data. */ + + case BLE_GAP_EVENT_NOTIFY_TX: + NRF_LOG_INFO("Notify event : BLE_GAP_EVENT_NOTIFY_TX"); + break; + + case BLE_GAP_EVENT_IDENTITY_RESOLVED: + NRF_LOG_INFO("Identity event : BLE_GAP_EVENT_IDENTITY_RESOLVED"); + break; default: - // NRF_LOG_INFO("Advertising event : %d", event->type); + NRF_LOG_INFO("UNHANDLED GAP event : %d", event->type); break; } return 0; @@ -292,3 +375,82 @@ void NimbleController::NotifyBatteryLevel(uint8_t level) { batteryInformationService.NotifyBatteryLevel(connectionHandle, level); } } + +void NimbleController::PersistBond(struct ble_gap_conn_desc& desc) { + union ble_store_key key; + union ble_store_value our_sec, peer_sec, peer_cccd_set[MYNEWT_VAL(BLE_STORE_MAX_CCCDS)] = {0}; + int rc; + + memset(&key, 0, sizeof key); + memset(&our_sec, 0, sizeof our_sec); + key.sec.peer_addr = desc.peer_id_addr; + rc = ble_store_read_our_sec(&key.sec, &our_sec.sec); + + if (memcmp(&our_sec.sec, &bondId, sizeof bondId) == 0) { + return; + } + + memcpy(&bondId, &our_sec.sec, sizeof bondId); + + memset(&key, 0, sizeof key); + memset(&peer_sec, 0, sizeof peer_sec); + key.sec.peer_addr = desc.peer_id_addr; + rc += ble_store_read_peer_sec(&key.sec, &peer_sec.sec); + + if (rc == 0) { + memset(&key, 0, sizeof key); + key.cccd.peer_addr = desc.peer_id_addr; + int peer_count = 0; + ble_store_util_count(BLE_STORE_OBJ_TYPE_CCCD, &peer_count); + for (int i = 0; i < peer_count; i++) { + key.cccd.idx = peer_count; + ble_store_read_cccd(&key.cccd, &peer_cccd_set[i].cccd); + } + + /* Wakeup Spi and SpiNorFlash before accessing the file system + * This should be fixed in the FS driver + */ + systemTask.PushMessage(Pinetime::System::Messages::GoToRunning); + systemTask.PushMessage(Pinetime::System::Messages::DisableSleeping); + vTaskDelay(10); + + lfs_file_t file_p; + + rc = fs.FileOpen(&file_p, "/bond.dat", LFS_O_WRONLY | LFS_O_CREAT); + if (rc == 0) { + fs.FileWrite(&file_p, reinterpret_cast(&our_sec.sec), sizeof our_sec); + fs.FileWrite(&file_p, reinterpret_cast(&peer_sec.sec), sizeof peer_sec); + fs.FileWrite(&file_p, reinterpret_cast(&peer_count), 1); + for (int i = 0; i < peer_count; i++) { + fs.FileWrite(&file_p, reinterpret_cast(&peer_cccd_set[i].cccd), sizeof(struct ble_store_value_cccd)); + } + fs.FileClose(&file_p); + } + systemTask.PushMessage(Pinetime::System::Messages::EnableSleeping); + } +} + +void NimbleController::RestoreBond() { + lfs_file_t file_p; + union ble_store_value sec, cccd; + uint8_t peer_count = 0; + + if (fs.FileOpen(&file_p, "/bond.dat", LFS_O_RDONLY) == 0) { + memset(&sec, 0, sizeof sec); + fs.FileRead(&file_p, reinterpret_cast(&sec.sec), sizeof sec); + ble_store_write_our_sec(&sec.sec); + + memset(&sec, 0, sizeof sec); + fs.FileRead(&file_p, reinterpret_cast(&sec.sec), sizeof sec); + ble_store_write_peer_sec(&sec.sec); + + fs.FileRead(&file_p, &peer_count, 1); + for (int i = 0; i < peer_count; i++) { + fs.FileRead(&file_p, reinterpret_cast(&cccd.cccd), sizeof(struct ble_store_value_cccd)); + ble_store_write_cccd(&cccd.cccd); + } + + fs.FileClose(&file_p); + fs.FileDelete("/bond.dat"); + } +} diff --git a/src/components/ble/NimbleController.h b/src/components/ble/NimbleController.h index 76f89ba8..2b300e63 100644 --- a/src/components/ble/NimbleController.h +++ b/src/components/ble/NimbleController.h @@ -7,19 +7,22 @@ #include #undef max #undef min -#include "AlertNotificationClient.h" -#include "AlertNotificationService.h" -#include "BatteryInformationService.h" -#include "CurrentTimeClient.h" -#include "CurrentTimeService.h" -#include "DeviceInformationService.h" -#include "DfuService.h" -#include "ImmediateAlertService.h" -#include "MusicService.h" -#include "NavigationService.h" -#include "ServiceDiscovery.h" -#include "HeartRateService.h" -#include "MotionService.h" +#include "components/ble/AlertNotificationClient.h" +#include "components/ble/AlertNotificationService.h" +#include "components/ble/BatteryInformationService.h" +#include "components/ble/CurrentTimeClient.h" +#include "components/ble/CurrentTimeService.h" +#include "components/ble/DeviceInformationService.h" +#include "components/ble/DfuService.h" +#include "components/ble/HeartRateService.h" +#include "components/ble/ImmediateAlertService.h" +#include "components/ble/MusicService.h" +#include "components/ble/NavigationService.h" +#include "components/ble/ServiceDiscovery.h" +#include "components/ble/MotionService.h" +#include "components/ble/weather/WeatherService.h" +#include "components/fs/FS.h" +#include "components/ble/FSService.h" namespace Pinetime { namespace Drivers { @@ -45,7 +48,8 @@ namespace Pinetime { Controllers::Battery& batteryController, Pinetime::Drivers::SpiNorFlash& spiNorFlash, Controllers::HeartRateController& heartRateController, - Controllers::MotionController& motionController); + Controllers::MotionController& motionController, + Pinetime::Controllers::FS& fs); void Init(); void StartAdvertising(); int OnGAPEvent(ble_gap_event* event); @@ -70,6 +74,9 @@ namespace Pinetime { Pinetime::Controllers::AlertNotificationService& alertService() { return anService; }; + Pinetime::Controllers::WeatherService& weather() { + return weatherService; + }; uint16_t connHandle(); void NotifyBatteryLevel(uint8_t level); @@ -79,12 +86,16 @@ namespace Pinetime { } private: + void PersistBond(struct ble_gap_conn_desc& desc); + void RestoreBond(); + static constexpr const char* deviceName = "InfiniTime"; Pinetime::System::SystemTask& systemTask; Pinetime::Controllers::Ble& bleController; DateTime& dateTimeController; Pinetime::Controllers::NotificationManager& notificationManager; Pinetime::Drivers::SpiNorFlash& spiNorFlash; + Pinetime::Controllers::FS& fs; Pinetime::Controllers::DfuService dfuService; DeviceInformationService deviceInformationService; @@ -93,23 +104,25 @@ namespace Pinetime { AlertNotificationClient alertNotificationClient; CurrentTimeService currentTimeService; MusicService musicService; + WeatherService weatherService; NavigationService navService; BatteryInformationService batteryInformationService; ImmediateAlertService immediateAlertService; HeartRateService heartRateService; MotionService motionService; + FSService fsService; + ServiceDiscovery serviceDiscovery; - uint8_t addrType; // 1 = Random, 0 = PUBLIC + uint8_t addrType; uint16_t connectionHandle = BLE_HS_CONN_HANDLE_NONE; uint8_t fastAdvCount = 0; + uint8_t bondId[16] = {0}; ble_uuid128_t dfuServiceUuid { .u {.type = BLE_UUID_TYPE_128}, .value = {0x23, 0xD1, 0xBC, 0xEA, 0x5F, 0x78, 0x23, 0x15, 0xDE, 0xEF, 0x12, 0x12, 0x30, 0x15, 0x00, 0x00}}; - - ServiceDiscovery serviceDiscovery; }; - static NimbleController* nptr; + static NimbleController* nptr; } } diff --git a/src/components/ble/NotificationManager.cpp b/src/components/ble/NotificationManager.cpp index 7ffed300..ec99c4ed 100644 --- a/src/components/ble/NotificationManager.cpp +++ b/src/components/ble/NotificationManager.cpp @@ -1,4 +1,4 @@ -#include "NotificationManager.h" +#include "components/ble/NotificationManager.h" #include #include diff --git a/src/components/ble/ServiceDiscovery.cpp b/src/components/ble/ServiceDiscovery.cpp index b36b241c..03bcfeb4 100644 --- a/src/components/ble/ServiceDiscovery.cpp +++ b/src/components/ble/ServiceDiscovery.cpp @@ -1,6 +1,6 @@ -#include "ServiceDiscovery.h" +#include "components/ble/ServiceDiscovery.h" #include -#include "BleClient.h" +#include "components/ble/BleClient.h" using namespace Pinetime::Controllers; diff --git a/src/components/ble/weather/WeatherData.h b/src/components/ble/weather/WeatherData.h new file mode 100644 index 00000000..613d5acb --- /dev/null +++ b/src/components/ble/weather/WeatherData.h @@ -0,0 +1,385 @@ +/* Copyright (C) 2021 Avamander + + This file is part of InfiniTime. + + InfiniTime is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + InfiniTime is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +#pragma once + +/** + * Different weather events, weather data structures used by {@link WeatherService.h} + * + * How to upload events to the timeline? + * + * All timeline write payloads are simply CBOR-encoded payloads of the structs described below. + * + * All payloads have a mandatory header part and the dynamic part that + * depends on the event type specified in the header. If you don't, + * you'll get an error returned. Data is relatively well-validated, + * so keep in the bounds of the data types given. + * + * Write all struct members (CamelCase keys) into a single finite-sized map, and write it to the characteristic. + * Mind the MTU. + * + * How to debug? + * + * There's a Screen that you can compile into your firmware that shows currently valid events. + * You can adapt that to display something else. That part right now is very much work in progress + * because the exact requirements are not yet known. + * + * + * Implemented based on and other material: + * https://en.wikipedia.org/wiki/METAR + * https://www.weather.gov/jetstream/obscurationtypes + * http://www.faraim.org/aim/aim-4-03-14-493.html + */ + +namespace Pinetime { + namespace Controllers { + class WeatherData { + public: + /** + * Visibility obscuration types + */ + enum class obscurationtype { + /** No obscuration */ + None = 0, + /** Water particles suspended in the air; low visibility; does not fall */ + Fog = 1, + /** Tiny, dry particles in the air; invisible to the eye; opalescent */ + Haze = 2, + /** Small fire-created particles suspended in the air */ + Smoke = 3, + /** Fine rock powder, from for example volcanoes */ + Ash = 4, + /** Fine particles of earth suspended in the air by the wind */ + Dust = 5, + /** Fine particles of sand suspended in the air by the wind */ + Sand = 6, + /** Water particles suspended in the air; low-ish visibility; temperature is near dewpoint */ + Mist = 7, + /** This is SPECIAL in the sense that the thing raining down is doing the obscuration */ + Precipitation = 8, + Length + }; + + /** + * Types of precipitation + */ + enum class precipitationtype { + /** + * No precipitation + * + * Theoretically we could just _not_ send the event, but then + * how do we differentiate between no precipitation and + * no information about precipitation + */ + None = 0, + /** Drops larger than a drizzle; also widely separated drizzle */ + Rain = 1, + /** Fairly uniform rain consisting of fine drops */ + Drizzle = 2, + /** Rain that freezes upon contact with objects and ground */ + FreezingRain = 3, + /** Rain + hail; ice pellets; small translucent frozen raindrops */ + Sleet = 4, + /** Larger ice pellets; falling separately or in irregular clumps */ + Hail = 5, + /** Hail with smaller grains of ice; mini-snowballs */ + SmallHail = 6, + /** Snow... */ + Snow = 7, + /** Frozen drizzle; very small snow crystals */ + SnowGrains = 8, + /** Needles; columns or plates of ice. Sometimes described as "diamond dust". In very cold regions */ + IceCrystals = 9, + /** It's raining down ash, e.g. from a volcano */ + Ash = 10, + Length + }; + + /** + * These are special events that can "enhance" the "experience" of existing weather events + */ + enum class specialtype { + /** Strong wind with a sudden onset that lasts at least a minute */ + Squall = 0, + /** Series of waves in a water body caused by the displacement of a large volume of water */ + Tsunami = 1, + /** Violent; rotating column of air */ + Tornado = 2, + /** Unplanned; unwanted; uncontrolled fire in an area */ + Fire = 3, + /** Thunder and/or lightning */ + Thunder = 4, + Length + }; + + /** + * These are used for weather timeline manipulation + * that isn't just adding to the stack of weather events + */ + enum class controlcodes { + /** How much is stored already */ + GetLength = 0, + /** This wipes the entire timeline */ + DelTimeline = 1, + /** There's a currently valid timeline event with the given type */ + HasValidEvent = 3, + Length + }; + + /** + * Events have types + * then they're easier to parse after sending them over the air + */ + enum class eventtype : uint8_t { + /** @see obscuration */ + Obscuration = 0, + /** @see precipitation */ + Precipitation = 1, + /** @see wind */ + Wind = 2, + /** @see temperature */ + Temperature = 3, + /** @see airquality */ + AirQuality = 4, + /** @see special */ + Special = 5, + /** @see pressure */ + Pressure = 6, + /** @see location */ + Location = 7, + /** @see cloud */ + Clouds = 8, + /** @see humidity */ + Humidity = 9, + Length + }; + + /** + * Valid event query + * + * NOTE: Not currently available, until needs are better known + */ + class ValidEventQuery { + public: + static constexpr controlcodes code = controlcodes::HasValidEvent; + eventtype eventType; + }; + + /** The header used for further parsing */ + class TimelineHeader { + public: + /** + * UNIX timestamp + * TODO: This is currently WITH A TIMEZONE OFFSET! + * Please send events with the timestamp offset by the timezone. + **/ + uint64_t timestamp; + /** + * Time in seconds until the event expires + * + * 32 bits ought to be enough for everyone + * + * If there's a newer event of the same type then it overrides this one, even if it hasn't expired + */ + uint32_t expires; + /** + * What type of weather-related event + */ + eventtype eventType; + }; + + /** Specifies how cloudiness is stored */ + class Clouds : public TimelineHeader { + public: + /** Cloud coverage in percentage, 0-100% */ + uint8_t amount; + }; + + /** Specifies how obscuration is stored */ + class Obscuration : public TimelineHeader { + public: + /** Type of precipitation */ + obscurationtype type; + /** + * Visibility distance in meters + * 65535 is reserved for unspecified + */ + uint16_t amount; + }; + + /** Specifies how precipitation is stored */ + class Precipitation : public TimelineHeader { + public: + /** Type of precipitation */ + precipitationtype type; + /** + * How much is it going to rain? In millimeters + * 255 is reserved for unspecified + **/ + uint8_t amount; + }; + + /** + * How wind speed is stored + * + * In order to represent bursts of wind instead of constant wind, + * you have minimum and maximum speeds. + * + * As direction can fluctuate wildly and some watchfaces might wish to display it nicely, + * we're following the aerospace industry weather report option of specifying a range. + */ + class Wind : public TimelineHeader { + public: + /** Meters per second */ + uint8_t speedMin; + /** Meters per second */ + uint8_t speedMax; + /** Unitless direction between 0-255; approximately 1 unit per 0.71 degrees */ + uint8_t directionMin; + /** Unitless direction between 0-255; approximately 1 unit per 0.71 degrees */ + uint8_t directionMax; + }; + + /** + * How temperature is stored + * + * As it's annoying to figure out the dewpoint on the watch, + * please send it from the companion + * + * We don't do floats, picodegrees are not useful. Make sure to multiply. + */ + class Temperature : public TimelineHeader { + public: + /** + * Temperature °C but multiplied by 100 (e.g. -12.50°C becomes -1250) + * -32768 is reserved for "no data" + */ + int16_t temperature; + /** + * Dewpoint °C but multiplied by 100 (e.g. -12.50°C becomes -1250) + * -32768 is reserved for "no data" + */ + int16_t dewPoint; + }; + + /** + * How location info is stored + * + * This can be mostly static with long expiration, + * as it usually is, but it could change during a trip for ex. + * so we allow changing it dynamically. + * + * Location info can be for some kind of map watchface + * or daylight calculations, should those be required. + * + */ + class Location : public TimelineHeader { + public: + /** Location name */ + std::string location; + /** Altitude relative to sea level in meters */ + int16_t altitude; + /** Latitude, EPSG:3857 (Google Maps, Openstreetmaps datum) */ + int32_t latitude; + /** Longitude, EPSG:3857 (Google Maps, Openstreetmaps datum) */ + int32_t longitude; + }; + + /** + * How humidity is stored + */ + class Humidity : public TimelineHeader { + public: + /** Relative humidity, 0-100% */ + uint8_t humidity; + }; + + /** + * How air pressure is stored + */ + class Pressure : public TimelineHeader { + public: + /** Air pressure in hectopascals (hPa) */ + int16_t pressure; + }; + + /** + * How special events are stored + */ + class Special : public TimelineHeader { + public: + /** Special event's type */ + specialtype type; + }; + + /** + * How air quality is stored + * + * These events are a bit more complex because the topic is not simple, + * the intention is to heavy-lift the annoying preprocessing from the watch + * this allows watchface or watchapp makers to generate accurate alerts and graphics + * + * If this needs further enforced standardization, pull requests are welcome + */ + class AirQuality : public TimelineHeader { + public: + /** + * The name of the pollution + * + * for the sake of better compatibility with watchapps + * that might want to use this data for say visuals + * don't localize the name. + * + * Ideally watchapp itself localizes the name, if it's at all needed. + * + * E.g. + * For generic ones use "PM0.1", "PM5", "PM10" + * For chemical compounds use the molecular formula e.g. "NO2", "CO2", "O3" + * For pollen use the genus, e.g. "Betula" for birch or "Alternaria" for that mold's spores + */ + std::string polluter; + /** + * Amount of the pollution in SI units, + * otherwise it's going to be difficult to create UI, alerts + * and so on and for. + * + * See more: + * https://ec.europa.eu/environment/air/quality/standards.htm + * http://www.ourair.org/wp-content/uploads/2012-aaqs2.pdf + * + * Example units: + * count/mÂł for pollen + * µgC/mÂł for micrograms of organic carbon + * µg/mÂł sulfates, PM0.1, PM1, PM2, PM10 and so on, dust + * mg/mÂł CO2, CO + * ng/mÂł for heavy metals + * + * List is not comprehensive, should be improved. + * The current ones are what watchapps assume! + * + * Note: ppb and ppm to concentration should be calculated on the companion, using + * the correct formula (taking into account temperature and air pressure) + * + * Note2: The amount is off by times 100, for two decimal places of precision. + * E.g. 54.32µg/mÂł is 5432 + * + */ + uint32_t amount; + }; + }; + } +} diff --git a/src/components/ble/weather/WeatherService.cpp b/src/components/ble/weather/WeatherService.cpp new file mode 100644 index 00000000..23f53b74 --- /dev/null +++ b/src/components/ble/weather/WeatherService.cpp @@ -0,0 +1,604 @@ +/* Copyright (C) 2021 Avamander + + This file is part of InfiniTime. + + InfiniTime is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + InfiniTime is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +#include +#include "WeatherService.h" +#include "libs/QCBOR/inc/qcbor/qcbor.h" +#include "systemtask/SystemTask.h" + +int WeatherCallback(uint16_t connHandle, uint16_t attrHandle, struct ble_gatt_access_ctxt* ctxt, void* arg) { + return static_cast(arg)->OnCommand(connHandle, attrHandle, ctxt); +} + +namespace Pinetime { + namespace Controllers { + WeatherService::WeatherService(System::SystemTask& system, DateTime& dateTimeController) + : system(system), dateTimeController(dateTimeController) { + nullHeader = &nullTimelineheader; + nullTimelineheader->timestamp = 0; + } + + void WeatherService::Init() { + uint8_t res = 0; + res = ble_gatts_count_cfg(serviceDefinition); + ASSERT(res == 0); + + res = ble_gatts_add_svcs(serviceDefinition); + ASSERT(res == 0); + } + + int WeatherService::OnCommand(uint16_t connHandle, uint16_t attrHandle, struct ble_gatt_access_ctxt* ctxt) { + if (ctxt->op == BLE_GATT_ACCESS_OP_WRITE_CHR) { + const uint8_t packetLen = OS_MBUF_PKTLEN(ctxt->om); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) + if (packetLen <= 0) { + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + // Decode + QCBORDecodeContext decodeContext; + UsefulBufC encodedCbor = {ctxt->om->om_data, OS_MBUF_PKTLEN(ctxt->om)}; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) + + QCBORDecode_Init(&decodeContext, encodedCbor, QCBOR_DECODE_MODE_NORMAL); + // KINDLY provide us a fixed-length map + QCBORDecode_EnterMap(&decodeContext, nullptr); + // Always encodes to the smallest number of bytes based on the value + int64_t tmpTimestamp = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Timestamp", &tmpTimestamp); + if (QCBORDecode_GetError(&decodeContext) != QCBOR_SUCCESS) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + int64_t tmpExpires = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Expires", &tmpExpires); + if (QCBORDecode_GetError(&decodeContext) != QCBOR_SUCCESS || tmpExpires < 0 || tmpExpires > 4294967295) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + int64_t tmpEventType = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "EventType", &tmpEventType); + if (QCBORDecode_GetError(&decodeContext) != QCBOR_SUCCESS || tmpEventType < 0 || + tmpEventType >= static_cast(WeatherData::eventtype::Length)) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + + switch (static_cast(tmpEventType)) { + case WeatherData::eventtype::AirQuality: { + std::unique_ptr airquality = std::make_unique(); + airquality->timestamp = tmpTimestamp; + airquality->eventType = static_cast(tmpEventType); + airquality->expires = tmpExpires; + + UsefulBufC stringBuf; // TODO: Everything ok with lifecycle here? + QCBORDecode_GetTextStringInMapSZ(&decodeContext, "Polluter", &stringBuf); + if (UsefulBuf_IsNULLOrEmptyC(stringBuf) != 0) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + airquality->polluter = std::string(static_cast(stringBuf.ptr), stringBuf.len); + + int64_t tmpAmount = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Amount", &tmpAmount); + if (tmpAmount < 0 || tmpAmount > 4294967295) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + airquality->amount = tmpAmount; // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + + if (!AddEventToTimeline(std::move(airquality))) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + break; + } + case WeatherData::eventtype::Obscuration: { + std::unique_ptr obscuration = std::make_unique(); + obscuration->timestamp = tmpTimestamp; + obscuration->eventType = static_cast(tmpEventType); + obscuration->expires = tmpExpires; + + int64_t tmpType = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Type", &tmpType); + if (tmpType < 0 || tmpType >= static_cast(WeatherData::obscurationtype::Length)) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + obscuration->type = static_cast(tmpType); + + int64_t tmpAmount = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Amount", &tmpAmount); + if (tmpAmount < 0 || tmpAmount > 65535) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + obscuration->amount = tmpAmount; // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + + if (!AddEventToTimeline(std::move(obscuration))) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + break; + } + case WeatherData::eventtype::Precipitation: { + std::unique_ptr precipitation = std::make_unique(); + precipitation->timestamp = tmpTimestamp; + precipitation->eventType = static_cast(tmpEventType); + precipitation->expires = tmpExpires; + + int64_t tmpType = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Type", &tmpType); + if (tmpType < 0 || tmpType >= static_cast(WeatherData::precipitationtype::Length)) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + precipitation->type = static_cast(tmpType); + + int64_t tmpAmount = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Amount", &tmpAmount); + if (tmpAmount < 0 || tmpAmount > 255) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + precipitation->amount = tmpAmount; // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + + if (!AddEventToTimeline(std::move(precipitation))) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + break; + } + case WeatherData::eventtype::Wind: { + std::unique_ptr wind = std::make_unique(); + wind->timestamp = tmpTimestamp; + wind->eventType = static_cast(tmpEventType); + wind->expires = tmpExpires; + + int64_t tmpMin = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "SpeedMin", &tmpMin); + if (tmpMin < 0 || tmpMin > 255) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + wind->speedMin = tmpMin; // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + + int64_t tmpMax = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "SpeedMin", &tmpMax); + if (tmpMax < 0 || tmpMax > 255) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + wind->speedMax = tmpMax; // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + + int64_t tmpDMin = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "DirectionMin", &tmpDMin); + if (tmpDMin < 0 || tmpDMin > 255) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + wind->directionMin = tmpDMin; // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + + int64_t tmpDMax = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "DirectionMax", &tmpDMax); + if (tmpDMax < 0 || tmpDMax > 255) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + wind->directionMax = tmpDMax; // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + + if (!AddEventToTimeline(std::move(wind))) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + break; + } + case WeatherData::eventtype::Temperature: { + std::unique_ptr temperature = std::make_unique(); + temperature->timestamp = tmpTimestamp; + temperature->eventType = static_cast(tmpEventType); + temperature->expires = tmpExpires; + + int64_t tmpTemperature = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Temperature", &tmpTemperature); + if (tmpTemperature < -32768 || tmpTemperature > 32767) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + temperature->temperature = + static_cast(tmpTemperature); // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + + int64_t tmpDewPoint = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "DewPoint", &tmpDewPoint); + if (tmpDewPoint < -32768 || tmpDewPoint > 32767) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + temperature->dewPoint = + static_cast(tmpDewPoint); // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + + if (!AddEventToTimeline(std::move(temperature))) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + break; + } + case WeatherData::eventtype::Special: { + std::unique_ptr special = std::make_unique(); + special->timestamp = tmpTimestamp; + special->eventType = static_cast(tmpEventType); + special->expires = tmpExpires; + + int64_t tmpType = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Type", &tmpType); + if (tmpType < 0 || tmpType >= static_cast(WeatherData::specialtype::Length)) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + special->type = static_cast(tmpType); + + if (!AddEventToTimeline(std::move(special))) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + break; + } + case WeatherData::eventtype::Pressure: { + std::unique_ptr pressure = std::make_unique(); + pressure->timestamp = tmpTimestamp; + pressure->eventType = static_cast(tmpEventType); + pressure->expires = tmpExpires; + + int64_t tmpPressure = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Pressure", &tmpPressure); + if (tmpPressure < 0 || tmpPressure >= 65535) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + pressure->pressure = tmpPressure; // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + + if (!AddEventToTimeline(std::move(pressure))) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + break; + } + case WeatherData::eventtype::Location: { + std::unique_ptr location = std::make_unique(); + location->timestamp = tmpTimestamp; + location->eventType = static_cast(tmpEventType); + location->expires = tmpExpires; + + UsefulBufC stringBuf; // TODO: Everything ok with lifecycle here? + QCBORDecode_GetTextStringInMapSZ(&decodeContext, "Location", &stringBuf); + if (UsefulBuf_IsNULLOrEmptyC(stringBuf) != 0) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + location->location = std::string(static_cast(stringBuf.ptr), stringBuf.len); + + int64_t tmpAltitude = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Altitude", &tmpAltitude); + if (tmpAltitude < -32768 || tmpAltitude >= 32767) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + location->altitude = static_cast(tmpAltitude); + + int64_t tmpLatitude = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Latitude", &tmpLatitude); + if (tmpLatitude < -2147483648 || tmpLatitude >= 2147483647) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + location->latitude = static_cast(tmpLatitude); + + int64_t tmpLongitude = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Longitude", &tmpLongitude); + if (tmpLongitude < -2147483648 || tmpLongitude >= 2147483647) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + location->latitude = static_cast(tmpLongitude); + + if (!AddEventToTimeline(std::move(location))) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + break; + } + case WeatherData::eventtype::Clouds: { + std::unique_ptr clouds = std::make_unique(); + clouds->timestamp = tmpTimestamp; + clouds->eventType = static_cast(tmpEventType); + clouds->expires = tmpExpires; + + int64_t tmpAmount = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Amount", &tmpAmount); + if (tmpAmount < 0 || tmpAmount > 255) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + clouds->amount = static_cast(tmpAmount); + + if (!AddEventToTimeline(std::move(clouds))) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + break; + } + case WeatherData::eventtype::Humidity: { + std::unique_ptr humidity = std::make_unique(); + humidity->timestamp = tmpTimestamp; + humidity->eventType = static_cast(tmpEventType); + humidity->expires = tmpExpires; + + int64_t tmpType = 0; + QCBORDecode_GetInt64InMapSZ(&decodeContext, "Humidity", &tmpType); + if (tmpType < 0 || tmpType >= 255) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + humidity->humidity = static_cast(tmpType); + + if (!AddEventToTimeline(std::move(humidity))) { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + break; + } + default: { + CleanUpQcbor(&decodeContext); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + } + + QCBORDecode_ExitMap(&decodeContext); + GetTimelineLength(); + TidyTimeline(); + + if (QCBORDecode_Finish(&decodeContext) != QCBOR_SUCCESS) { + return BLE_ATT_ERR_INSUFFICIENT_RES; + } + } else if (ctxt->op == BLE_GATT_ACCESS_OP_READ_CHR) { + // Encode + uint8_t buffer[64]; + QCBOREncodeContext encodeContext; + /* TODO: This is very much still a test endpoint + * it needs a characteristic UUID check + * and actual implementations that show + * what actually has to be read. + * WARN: Consider commands not part of the API for now! + */ + QCBOREncode_Init(&encodeContext, UsefulBuf_FROM_BYTE_ARRAY(buffer)); + QCBOREncode_OpenMap(&encodeContext); + QCBOREncode_AddTextToMap(&encodeContext, "test", UsefulBuf_FROM_SZ_LITERAL("test")); + QCBOREncode_AddInt64ToMap(&encodeContext, "test", 1ul); + QCBOREncode_CloseMap(&encodeContext); + + UsefulBufC encodedEvent; + auto uErr = QCBOREncode_Finish(&encodeContext, &encodedEvent); + if (uErr != 0) { + return BLE_ATT_ERR_INSUFFICIENT_RES; + } + auto res = os_mbuf_append(ctxt->om, &buffer, sizeof(buffer)); + if (res == 0) { + return BLE_ATT_ERR_INSUFFICIENT_RES; + } + + return 0; + } + return 0; + } + + std::unique_ptr& WeatherService::GetCurrentClouds() { + uint64_t currentTimestamp = GetCurrentUnixTimestamp(); + for (auto&& header : this->timeline) { + if (header->eventType == WeatherData::eventtype::Clouds && IsEventStillValid(header, currentTimestamp)) { + return reinterpret_cast&>(header); + } + } + + return reinterpret_cast&>(*this->nullHeader); + } + + std::unique_ptr& WeatherService::GetCurrentObscuration() { + uint64_t currentTimestamp = GetCurrentUnixTimestamp(); + for (auto&& header : this->timeline) { + if (header->eventType == WeatherData::eventtype::Obscuration && IsEventStillValid(header, currentTimestamp)) { + return reinterpret_cast&>(header); + } + } + + return reinterpret_cast&>(*this->nullHeader); + } + + std::unique_ptr& WeatherService::GetCurrentPrecipitation() { + uint64_t currentTimestamp = GetCurrentUnixTimestamp(); + for (auto&& header : this->timeline) { + if (header->eventType == WeatherData::eventtype::Precipitation && IsEventStillValid(header, currentTimestamp)) { + return reinterpret_cast&>(header); + } + } + + return reinterpret_cast&>(*this->nullHeader); + } + + std::unique_ptr& WeatherService::GetCurrentWind() { + uint64_t currentTimestamp = GetCurrentUnixTimestamp(); + for (auto&& header : this->timeline) { + if (header->eventType == WeatherData::eventtype::Wind && IsEventStillValid(header, currentTimestamp)) { + return reinterpret_cast&>(header); + } + } + + return reinterpret_cast&>(*this->nullHeader); + } + + std::unique_ptr& WeatherService::GetCurrentTemperature() { + uint64_t currentTimestamp = GetCurrentUnixTimestamp(); + for (auto&& header : this->timeline) { + if (header->eventType == WeatherData::eventtype::Temperature && IsEventStillValid(header, currentTimestamp)) { + return reinterpret_cast&>(header); + } + } + + return reinterpret_cast&>(*this->nullHeader); + } + + std::unique_ptr& WeatherService::GetCurrentHumidity() { + uint64_t currentTimestamp = GetCurrentUnixTimestamp(); + for (auto&& header : this->timeline) { + if (header->eventType == WeatherData::eventtype::Humidity && IsEventStillValid(header, currentTimestamp)) { + return reinterpret_cast&>(header); + } + } + + return reinterpret_cast&>(*this->nullHeader); + } + + std::unique_ptr& WeatherService::GetCurrentPressure() { + uint64_t currentTimestamp = GetCurrentUnixTimestamp(); + for (auto&& header : this->timeline) { + if (header->eventType == WeatherData::eventtype::Pressure && IsEventStillValid(header, currentTimestamp)) { + return reinterpret_cast&>(header); + } + } + + return reinterpret_cast&>(*this->nullHeader); + } + + std::unique_ptr& WeatherService::GetCurrentLocation() { + uint64_t currentTimestamp = GetCurrentUnixTimestamp(); + for (auto&& header : this->timeline) { + if (header->eventType == WeatherData::eventtype::Location && IsEventStillValid(header, currentTimestamp)) { + return reinterpret_cast&>(header); + } + } + + return reinterpret_cast&>(*this->nullHeader); + } + + std::unique_ptr& WeatherService::GetCurrentQuality() { + uint64_t currentTimestamp = GetCurrentUnixTimestamp(); + for (auto&& header : this->timeline) { + if (header->eventType == WeatherData::eventtype::AirQuality && IsEventStillValid(header, currentTimestamp)) { + return reinterpret_cast&>(header); + } + } + + return reinterpret_cast&>(*this->nullHeader); + } + + size_t WeatherService::GetTimelineLength() const { + return timeline.size(); + } + + bool WeatherService::AddEventToTimeline(std::unique_ptr event) { + if (timeline.size() == timeline.max_size()) { + return false; + } + + timeline.push_back(std::move(event)); + return true; + } + + bool WeatherService::HasTimelineEventOfType(const WeatherData::eventtype type) const { + uint64_t currentTimestamp = GetCurrentUnixTimestamp(); + for (auto&& header : timeline) { + if (header->eventType == type && IsEventStillValid(header, currentTimestamp)) { + return true; + } + } + return false; + } + + void WeatherService::TidyTimeline() { + uint64_t timeCurrent = GetCurrentUnixTimestamp(); + timeline.erase(std::remove_if(std::begin(timeline), + std::end(timeline), + [&](std::unique_ptr const& header) { + return !IsEventStillValid(header, timeCurrent); + }), + std::end(timeline)); + + std::sort(std::begin(timeline), std::end(timeline), CompareTimelineEvents); + } + + bool WeatherService::CompareTimelineEvents(const std::unique_ptr& first, + const std::unique_ptr& second) { + return first->timestamp > second->timestamp; + } + + bool WeatherService::IsEventStillValid(const std::unique_ptr& uniquePtr, const uint64_t timestamp) { + // Not getting timestamp in isEventStillValid for more speed + return uniquePtr->timestamp + uniquePtr->expires >= timestamp; + } + + uint64_t WeatherService::GetCurrentUnixTimestamp() const { + return std::chrono::duration_cast(dateTimeController.CurrentDateTime().time_since_epoch()).count(); + } + + int16_t WeatherService::GetTodayMinTemp() const { + uint64_t currentTimestamp = GetCurrentUnixTimestamp(); + uint64_t currentDayEnd = currentTimestamp - ((24 - dateTimeController.Hours()) * 60 * 60) - + ((60 - dateTimeController.Minutes()) * 60) - (60 - dateTimeController.Seconds()); + int16_t result = -32768; + for (auto&& header : this->timeline) { + if (header->eventType == WeatherData::eventtype::Temperature && IsEventStillValid(header, currentTimestamp) && + header->timestamp < currentDayEnd && + reinterpret_cast&>(header)->temperature != -32768) { + int16_t temperature = reinterpret_cast&>(header)->temperature; + if (result == -32768) { + result = temperature; + } else if (result > temperature) { + result = temperature; + } else { + // The temperature in this item is higher than the lowest we've found + } + } + } + + return result; + } + + int16_t WeatherService::GetTodayMaxTemp() const { + uint64_t currentTimestamp = GetCurrentUnixTimestamp(); + uint64_t currentDayEnd = currentTimestamp - ((24 - dateTimeController.Hours()) * 60 * 60) - + ((60 - dateTimeController.Minutes()) * 60) - (60 - dateTimeController.Seconds()); + int16_t result = -32768; + for (auto&& header : this->timeline) { + if (header->eventType == WeatherData::eventtype::Temperature && IsEventStillValid(header, currentTimestamp) && + header->timestamp < currentDayEnd && + reinterpret_cast&>(header)->temperature != -32768) { + int16_t temperature = reinterpret_cast&>(header)->temperature; + if (result == -32768) { + result = temperature; + } else if (result < temperature) { + result = temperature; + } else { + // The temperature in this item is lower than the highest we've found + } + } + } + + return result; + } + + void WeatherService::CleanUpQcbor(QCBORDecodeContext* decodeContext) { + QCBORDecode_ExitMap(decodeContext); + QCBORDecode_Finish(decodeContext); + } + } +} diff --git a/src/components/ble/weather/WeatherService.h b/src/components/ble/weather/WeatherService.h new file mode 100644 index 00000000..eca70cbd --- /dev/null +++ b/src/components/ble/weather/WeatherService.h @@ -0,0 +1,172 @@ +/* Copyright (C) 2021 Avamander + + This file is part of InfiniTime. + + InfiniTime is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + InfiniTime is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +#pragma once + +#include +#include +#include +#include + +#define min // workaround: nimble's min/max macros conflict with libstdc++ +#define max +#include +#include +#undef max +#undef min + +#include "WeatherData.h" +#include "libs/QCBOR/inc/qcbor/qcbor.h" +#include "components/datetime/DateTimeController.h" + +int WeatherCallback(uint16_t connHandle, uint16_t attrHandle, struct ble_gatt_access_ctxt* ctxt, void* arg); + +namespace Pinetime { + namespace System { + class SystemTask; + } + namespace Controllers { + + class WeatherService { + public: + explicit WeatherService(System::SystemTask& system, DateTime& dateTimeController); + + void Init(); + + int OnCommand(uint16_t connHandle, uint16_t attrHandle, struct ble_gatt_access_ctxt* ctxt); + + /* + * Helper functions for quick access to currently valid data + */ + std::unique_ptr& GetCurrentLocation(); + std::unique_ptr& GetCurrentClouds(); + std::unique_ptr& GetCurrentObscuration(); + std::unique_ptr& GetCurrentPrecipitation(); + std::unique_ptr& GetCurrentWind(); + std::unique_ptr& GetCurrentTemperature(); + std::unique_ptr& GetCurrentHumidity(); + std::unique_ptr& GetCurrentPressure(); + std::unique_ptr& GetCurrentQuality(); + + /** + * Searches for the current day's maximum temperature + * @return -32768 if there's no data, degrees Celsius times 100 otherwise + */ + int16_t GetTodayMaxTemp() const; + /** + * Searches for the current day's minimum temperature + * @return -32768 if there's no data, degrees Celsius times 100 otherwise + */ + int16_t GetTodayMinTemp() const; + + /* + * Management functions + */ + /** + * Adds an event to the timeline + * @return + */ + bool AddEventToTimeline(std::unique_ptr event); + /** + * Gets the current timeline length + */ + size_t GetTimelineLength() const; + /** + * Checks if an event of a certain type exists in the timeline + */ + bool HasTimelineEventOfType(WeatherData::eventtype type) const; + + private: + // 00040000-78fc-48fe-8e23-433b3a1942d0 + static constexpr ble_uuid128_t BaseUuid() { + return CharUuid(0x00, 0x00); + } + + // 0004yyxx-78fc-48fe-8e23-433b3a1942d0 + static constexpr ble_uuid128_t CharUuid(uint8_t x, uint8_t y) { + return ble_uuid128_t {.u = {.type = BLE_UUID_TYPE_128}, + .value = {0xd0, 0x42, 0x19, 0x3a, 0x3b, 0x43, 0x23, 0x8e, 0xfe, 0x48, 0xfc, 0x78, y, x, 0x04, 0x00}}; + } + + ble_uuid128_t weatherUuid {BaseUuid()}; + + /** + * Just write timeline data here. + * + * See {@link WeatherData.h} for more information. + */ + ble_uuid128_t weatherDataCharUuid {CharUuid(0x00, 0x01)}; + /** + * This doesn't take timeline data, provides some control over it. + * + * NOTE: Currently not supported. Companion app implementer feedback required. + * There's very little point in solidifying an API before we know the needs. + */ + ble_uuid128_t weatherControlCharUuid {CharUuid(0x00, 0x02)}; + + const struct ble_gatt_chr_def characteristicDefinition[3] = { + {.uuid = &weatherDataCharUuid.u, + .access_cb = WeatherCallback, + .arg = this, + .flags = BLE_GATT_CHR_F_WRITE, + .val_handle = &eventHandle}, + {.uuid = &weatherControlCharUuid.u, .access_cb = WeatherCallback, .arg = this, .flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_READ}, + {nullptr}}; + const struct ble_gatt_svc_def serviceDefinition[2] = { + {.type = BLE_GATT_SVC_TYPE_PRIMARY, .uuid = &weatherUuid.u, .characteristics = characteristicDefinition}, {0}}; + + uint16_t eventHandle {}; + + Pinetime::System::SystemTask& system; + Pinetime::Controllers::DateTime& dateTimeController; + + std::vector> timeline; + std::unique_ptr nullTimelineheader = std::make_unique(); + std::unique_ptr* nullHeader; + + /** + * Cleans up the timeline of expired events + */ + void TidyTimeline(); + + /** + * Compares two timeline events + */ + static bool CompareTimelineEvents(const std::unique_ptr& first, + const std::unique_ptr& second); + + /** + * Returns current UNIX timestamp + */ + uint64_t GetCurrentUnixTimestamp() const; + + /** + * Checks if the event hasn't gone past and expired + * + * @param header timeline event to check + * @param currentTimestamp what's the time right now + * @return if the event is valid + */ + static bool IsEventStillValid(const std::unique_ptr& uniquePtr, const uint64_t timestamp); + + /** + * This is a helper function that closes a QCBOR map and decoding context cleanly + */ + void CleanUpQcbor(QCBORDecodeContext* decodeContext); + }; + } +} diff --git a/src/components/brightness/BrightnessController.cpp b/src/components/brightness/BrightnessController.cpp index 6c524679..2d9f980a 100644 --- a/src/components/brightness/BrightnessController.cpp +++ b/src/components/brightness/BrightnessController.cpp @@ -1,4 +1,4 @@ -#include "BrightnessController.h" +#include "components/brightness/BrightnessController.h" #include #include "displayapp/screens/Symbols.h" #include "drivers/PinMap.h" diff --git a/src/components/datetime/DateTimeController.cpp b/src/components/datetime/DateTimeController.cpp index 762cded4..673903cb 100644 --- a/src/components/datetime/DateTimeController.cpp +++ b/src/components/datetime/DateTimeController.cpp @@ -1,4 +1,4 @@ -#include "DateTimeController.h" +#include "components/datetime/DateTimeController.h" #include #include #include diff --git a/src/components/firmwarevalidator/FirmwareValidator.cpp b/src/components/firmwarevalidator/FirmwareValidator.cpp index 68e66d37..5a63b6b4 100644 --- a/src/components/firmwarevalidator/FirmwareValidator.cpp +++ b/src/components/firmwarevalidator/FirmwareValidator.cpp @@ -1,4 +1,4 @@ -#include "FirmwareValidator.h" +#include "components/firmwarevalidator/FirmwareValidator.h" #include #include "drivers/InternalFlash.h" diff --git a/src/components/fs/FS.cpp b/src/components/fs/FS.cpp index 857e6bf9..8c98ae34 100644 --- a/src/components/fs/FS.cpp +++ b/src/components/fs/FS.cpp @@ -1,33 +1,32 @@ -#include "FS.h" +#include "components/fs/FS.h" #include #include #include using namespace Pinetime::Controllers; -FS::FS(Pinetime::Drivers::SpiNorFlash& driver) : - flashDriver{ driver }, - lfsConfig{ - .context = this, - .read = SectorRead, - .prog = SectorProg, - .erase = SectorErase, - .sync = SectorSync, +FS::FS(Pinetime::Drivers::SpiNorFlash& driver) + : flashDriver {driver}, + lfsConfig { + .context = this, + .read = SectorRead, + .prog = SectorProg, + .erase = SectorErase, + .sync = SectorSync, - .read_size = 16, - .prog_size = 8, - .block_size = blockSize, - .block_count = size / blockSize, - .block_cycles = 1000u, + .read_size = 16, + .prog_size = 8, + .block_size = blockSize, + .block_count = size / blockSize, + .block_cycles = 1000u, - .cache_size = 16, - .lookahead_size = 16, - - .name_max = 50, - .attr_max = 50, - } -{ } + .cache_size = 16, + .lookahead_size = 16, + .name_max = 50, + .attr_max = 50, + } { +} void FS::Init() { @@ -48,7 +47,6 @@ void FS::Init() { VerifyResource(); LVGLFileSystemInit(); #endif - } void FS::VerifyResource() { @@ -56,7 +54,7 @@ void FS::VerifyResource() { resourcesValid = true; } -int FS::FileOpen(lfs_file_t* file_p, const char* fileName, const int flags) { +int FS::FileOpen(lfs_file_t* file_p, const char* fileName, const int flags) { return lfs_file_open(&lfs, file_p, fileName, flags); } @@ -80,27 +78,31 @@ int FS::FileDelete(const char* fileName) { return lfs_remove(&lfs, fileName); } +int FS::DirOpen(const char* path, lfs_dir_t* lfs_dir) { + return lfs_dir_open(&lfs, lfs_dir, path); +} +int FS::DirClose(lfs_dir_t* lfs_dir) { + return lfs_dir_close(&lfs, lfs_dir); +} + +int FS::DirRead(lfs_dir_t* dir, lfs_info* info) { + return lfs_dir_read(&lfs, dir, info); +} +int FS::DirRewind(lfs_dir_t* dir) { + return lfs_dir_rewind(&lfs, dir); +} int FS::DirCreate(const char* path) { return lfs_mkdir(&lfs, path); } - -// Delete directory and all files inside -int FS::DirDelete(const char* path) { - - lfs_dir_t lfs_dir; - lfs_info entryInfo; - - int err; - err = lfs_dir_open(&lfs, &lfs_dir, path); - if (err) { - return err; - } - while (lfs_dir_read(&lfs, &lfs_dir, &entryInfo)) { - lfs_remove(&lfs, entryInfo.name); - } - lfs_dir_close(&lfs, &lfs_dir); - return LFS_ERR_OK; +int FS::Rename(const char* oldPath, const char* newPath){ + return lfs_rename(&lfs,oldPath,newPath); +} +int FS::Stat(const char* path, lfs_info* info) { + return lfs_stat(&lfs, path, info); +} +lfs_ssize_t FS::GetFSSize() { + return lfs_fs_size(&lfs); } /* @@ -141,17 +143,17 @@ int FS::SectorRead(const struct lfs_config* c, lfs_block_t block, lfs_off_t off, namespace { lv_fs_res_t lvglOpen(lv_fs_drv_t* drv, void* file_p, const char* path, lv_fs_mode_t mode) { - lfs_file_t* file = static_cast(file_p); FS* filesys = static_cast(drv->user_data); - filesys->FileOpen(file, path, LFS_O_RDONLY); - - if (file->type == 0) { - return LV_FS_RES_FS_ERR; - } - else { - return LV_FS_RES_OK; + int res = filesys->FileOpen(file, path, LFS_O_RDONLY); + if (res == 0) { + if (file->type == 0) { + return LV_FS_RES_FS_ERR; + } else { + return LV_FS_RES_OK; + } } + return LV_FS_RES_NOT_EX; } lv_fs_res_t lvglClose(lv_fs_drv_t* drv, void* file_p) { @@ -193,5 +195,4 @@ void FS::LVGLFileSystemInit() { fs_drv.user_data = this; lv_fs_drv_register(&fs_drv); - } \ No newline at end of file diff --git a/src/components/fs/FS.h b/src/components/fs/FS.h index 75ba16c8..2b27ae5d 100644 --- a/src/components/fs/FS.h +++ b/src/components/fs/FS.h @@ -21,37 +21,49 @@ namespace Pinetime { int FileDelete(const char* fileName); + int DirOpen(const char* path, lfs_dir_t* lfs_dir); + int DirClose(lfs_dir_t* lfs_dir); + int DirRead(lfs_dir_t* dir, lfs_info* info); + int DirRewind(lfs_dir_t* dir); int DirCreate(const char* path); - int DirDelete(const char* path); - + + lfs_ssize_t GetFSSize(); + int Rename(const char* oldPath, const char* newPath); + int Stat(const char* path, lfs_info* info); void VerifyResource(); - private: + static size_t getSize() { + return size; + } + static size_t getBlockSize() { + return blockSize; + } + private: Pinetime::Drivers::SpiNorFlash& flashDriver; /* - * External Flash MAP (4 MBytes) - * - * 0x000000 +---------------------------------------+ - * | Bootloader Assets | - * | 256 KBytes | - * | | - * 0x040000 +---------------------------------------+ - * | OTA | - * | 464 KBytes | - * | | - * | | - * | | - * 0x0B4000 +---------------------------------------+ - * | File System | - * | | - * | | - * | | - * | | - * 0x400000 +---------------------------------------+ - * - */ + * External Flash MAP (4 MBytes) + * + * 0x000000 +---------------------------------------+ + * | Bootloader Assets | + * | 256 KBytes | + * | | + * 0x040000 +---------------------------------------+ + * | OTA | + * | 464 KBytes | + * | | + * | | + * | | + * 0x0B4000 +---------------------------------------+ + * | File System | + * | | + * | | + * | | + * | | + * 0x400000 +---------------------------------------+ + * + */ static constexpr size_t startAddress = 0x0B4000; static constexpr size_t size = 0x34C000; static constexpr size_t blockSize = 4096; @@ -65,7 +77,6 @@ namespace Pinetime { static int SectorErase(const struct lfs_config* c, lfs_block_t block); static int SectorProg(const struct lfs_config* c, lfs_block_t block, lfs_off_t off, const void* buffer, lfs_size_t size); static int SectorRead(const struct lfs_config* c, lfs_block_t block, lfs_off_t off, void* buffer, lfs_size_t size); - }; } } diff --git a/src/components/gfx/Gfx.cpp b/src/components/gfx/Gfx.cpp index cf271032..3eaaa3fe 100644 --- a/src/components/gfx/Gfx.cpp +++ b/src/components/gfx/Gfx.cpp @@ -1,4 +1,4 @@ -#include "Gfx.h" +#include "components/gfx/Gfx.h" #include "drivers/St7789.h" using namespace Pinetime::Components; diff --git a/src/components/heartrate/Biquad.cpp b/src/components/heartrate/Biquad.cpp index 0341eda6..b7edd403 100644 --- a/src/components/heartrate/Biquad.cpp +++ b/src/components/heartrate/Biquad.cpp @@ -4,7 +4,7 @@ C++ port Copyright (C) 2021 Jean-François Milants */ -#include "Biquad.h" +#include "components/heartrate/Biquad.h" using namespace Pinetime::Controllers; diff --git a/src/components/heartrate/HeartRateController.cpp b/src/components/heartrate/HeartRateController.cpp index 716813b3..e0d69272 100644 --- a/src/components/heartrate/HeartRateController.cpp +++ b/src/components/heartrate/HeartRateController.cpp @@ -1,4 +1,4 @@ -#include "HeartRateController.h" +#include "components/heartrate/HeartRateController.h" #include #include diff --git a/src/components/heartrate/Ppg.cpp b/src/components/heartrate/Ppg.cpp index fcba3815..a5d83696 100644 --- a/src/components/heartrate/Ppg.cpp +++ b/src/components/heartrate/Ppg.cpp @@ -4,9 +4,9 @@ C++ port Copyright (C) 2021 Jean-François Milants */ +#include "components/heartrate/Ppg.h" #include #include -#include "Ppg.h" using namespace Pinetime::Controllers; /** Original implementation from wasp-os : https://github.com/daniel-thompson/wasp-os/blob/master/wasp/ppg.py */ diff --git a/src/components/heartrate/Ppg.h b/src/components/heartrate/Ppg.h index 00014162..ed79b082 100644 --- a/src/components/heartrate/Ppg.h +++ b/src/components/heartrate/Ppg.h @@ -1,8 +1,8 @@ #pragma once #include -#include "Biquad.h" -#include "Ptagc.h" +#include "components/heartrate/Biquad.h" +#include "components/heartrate/Ptagc.h" namespace Pinetime { namespace Controllers { diff --git a/src/components/heartrate/Ptagc.cpp b/src/components/heartrate/Ptagc.cpp index e358371e..1c60bc23 100644 --- a/src/components/heartrate/Ptagc.cpp +++ b/src/components/heartrate/Ptagc.cpp @@ -4,8 +4,8 @@ C++ port Copyright (C) 2021 Jean-François Milants */ +#include "components/heartrate/Ptagc.h" #include -#include "Ptagc.h" using namespace Pinetime::Controllers; diff --git a/src/components/motion/MotionController.cpp b/src/components/motion/MotionController.cpp index a2384d79..97a8feb2 100644 --- a/src/components/motion/MotionController.cpp +++ b/src/components/motion/MotionController.cpp @@ -1,4 +1,4 @@ -#include "MotionController.h" +#include "components/motion/MotionController.h" using namespace Pinetime::Controllers; @@ -14,7 +14,11 @@ void MotionController::Update(int16_t x, int16_t y, int16_t z, uint32_t nbSteps) this->x = x; this->y = y; this->z = z; + int32_t deltaSteps = nbSteps - this->nbSteps; this->nbSteps = nbSteps; + if (deltaSteps > 0) { + currentTripSteps += deltaSteps; + } } bool MotionController::ShouldWakeUp(bool isSleeping) { @@ -43,10 +47,16 @@ void MotionController::IsSensorOk(bool isOk) { isSensorOk = isOk; } void MotionController::Init(Pinetime::Drivers::Bma421::DeviceTypes types) { - switch(types){ - case Drivers::Bma421::DeviceTypes::BMA421: this->deviceType = DeviceTypes::BMA421; break; - case Drivers::Bma421::DeviceTypes::BMA425: this->deviceType = DeviceTypes::BMA425; break; - default: this->deviceType = DeviceTypes::Unknown; break; + switch (types) { + case Drivers::Bma421::DeviceTypes::BMA421: + this->deviceType = DeviceTypes::BMA421; + break; + case Drivers::Bma421::DeviceTypes::BMA425: + this->deviceType = DeviceTypes::BMA425; + break; + default: + this->deviceType = DeviceTypes::Unknown; + break; } } void MotionController::SetService(Pinetime::Controllers::MotionService* service) { diff --git a/src/components/motion/MotionController.h b/src/components/motion/MotionController.h index c72d8a4a..3eac7176 100644 --- a/src/components/motion/MotionController.h +++ b/src/components/motion/MotionController.h @@ -8,7 +8,7 @@ namespace Pinetime { namespace Controllers { class MotionController { public: - enum class DeviceTypes{ + enum class DeviceTypes { Unknown, BMA421, BMA425, @@ -28,6 +28,13 @@ namespace Pinetime { uint32_t NbSteps() const { return nbSteps; } + + void ResetTrip() { + currentTripSteps = 0; + } + uint32_t GetTripSteps() const { + return currentTripSteps; + } bool ShouldWakeUp(bool isSleeping); void IsSensorOk(bool isOk); @@ -44,6 +51,7 @@ namespace Pinetime { private: uint32_t nbSteps; + uint32_t currentTripSteps = 0; int16_t x; int16_t y; int16_t z; diff --git a/src/components/motor/MotorController.cpp b/src/components/motor/MotorController.cpp index f596c718..c794a02c 100644 --- a/src/components/motor/MotorController.cpp +++ b/src/components/motor/MotorController.cpp @@ -1,4 +1,4 @@ -#include "MotorController.h" +#include "components/motor/MotorController.h" #include #include "systemtask/SystemTask.h" #include "app_timer.h" diff --git a/src/components/rle/RleDecoder.cpp b/src/components/rle/RleDecoder.cpp index df2bcb6b..19ebfec0 100644 --- a/src/components/rle/RleDecoder.cpp +++ b/src/components/rle/RleDecoder.cpp @@ -1,4 +1,4 @@ -#include "RleDecoder.h" +#include "components/rle/RleDecoder.h" using namespace Pinetime::Tools; diff --git a/src/components/settings/Settings.cpp b/src/components/settings/Settings.cpp index 37c09f91..ef73ad1c 100644 --- a/src/components/settings/Settings.cpp +++ b/src/components/settings/Settings.cpp @@ -1,4 +1,4 @@ -#include "Settings.h" +#include "components/settings/Settings.h" #include #include diff --git a/src/components/settings/Settings.h b/src/components/settings/Settings.h index 09886011..f87b6938 100644 --- a/src/components/settings/Settings.h +++ b/src/components/settings/Settings.h @@ -4,7 +4,6 @@ #include "components/datetime/DateTimeController.h" #include "components/brightness/BrightnessController.h" #include "components/fs/FS.h" -#include "drivers/Cst816s.h" namespace Pinetime { namespace Controllers { diff --git a/src/components/timer/TimerController.cpp b/src/components/timer/TimerController.cpp index 8d5f5c33..79e44d6f 100644 --- a/src/components/timer/TimerController.cpp +++ b/src/components/timer/TimerController.cpp @@ -2,7 +2,7 @@ // Created by florian on 16.05.21. // -#include "TimerController.h" +#include "components/timer/TimerController.h" #include "systemtask/SystemTask.h" #include "app_timer.h" #include "task.h" diff --git a/src/displayapp/Apps.h b/src/displayapp/Apps.h index 71166e42..79485d62 100644 --- a/src/displayapp/Apps.h +++ b/src/displayapp/Apps.h @@ -25,6 +25,8 @@ namespace Pinetime { Metronome, Motion, Steps, + Weather, + PassKey, QuickSettings, Settings, SettingWatchFace, @@ -32,7 +34,6 @@ namespace Pinetime { SettingDisplay, SettingWakeUp, SettingSteps, - SettingPineTimeStyle, SettingSetDate, SettingSetTime, SettingChimes, diff --git a/src/displayapp/Colors.cpp b/src/displayapp/Colors.cpp index f45f0722..93b1aa06 100644 --- a/src/displayapp/Colors.cpp +++ b/src/displayapp/Colors.cpp @@ -1,4 +1,4 @@ -#include "Colors.h" +#include "displayapp/Colors.h" using namespace Pinetime::Applications; using namespace Pinetime::Controllers; diff --git a/src/displayapp/Colors.h b/src/displayapp/Colors.h index 9db7dd20..43e2b801 100644 --- a/src/displayapp/Colors.h +++ b/src/displayapp/Colors.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include "components/settings/Settings.h" namespace Pinetime { namespace Applications { diff --git a/src/displayapp/DisplayApp.cpp b/src/displayapp/DisplayApp.cpp index be1dad12..6eb45645 100644 --- a/src/displayapp/DisplayApp.cpp +++ b/src/displayapp/DisplayApp.cpp @@ -1,9 +1,9 @@ -#include "DisplayApp.h" +#include "displayapp/DisplayApp.h" #include -#include -#include -#include -#include +#include "displayapp/screens/HeartRate.h" +#include "displayapp/screens/Motion.h" +#include "displayapp/screens/Timer.h" +#include "displayapp/screens/Alarm.h" #include "components/battery/BatteryController.h" #include "components/ble/BleController.h" #include "components/datetime/DateTimeController.h" @@ -29,6 +29,7 @@ #include "displayapp/screens/FlashLight.h" #include "displayapp/screens/BatteryInfo.h" #include "displayapp/screens/Steps.h" +#include "displayapp/screens/PassKey.h" #include "displayapp/screens/Error.h" #include "drivers/Cst816s.h" @@ -214,6 +215,10 @@ void DisplayApp::Refresh() { } else { LoadApp(Apps::Alarm, DisplayApp::FullRefreshDirections::None); } + break; + case Messages::ShowPairingKey: + LoadApp(Apps::PassKey, DisplayApp::FullRefreshDirections::Up); + break; case Messages::TouchEvent: { if (state != States::Running) { break; @@ -250,16 +255,36 @@ void DisplayApp::Refresh() { } } break; case Messages::ButtonPushed: - if (currentApp == Apps::Clock) { - PushMessageToSystemTask(System::Messages::GoToSleep); - } else { - if (!currentScreen->OnButtonPushed()) { + if (!currentScreen->OnButtonPushed()) { + if (currentApp == Apps::Clock) { + PushMessageToSystemTask(System::Messages::GoToSleep); + } else { LoadApp(returnToApp, returnDirection); brightnessController.Set(settingsController.GetBrightness()); brightnessController.Backup(); } } break; + case Messages::ButtonLongPressed: + if (currentApp != Apps::Clock) { + if (currentApp == Apps::Notifications) { + LoadApp(Apps::Clock, DisplayApp::FullRefreshDirections::Up); + } else if (currentApp == Apps::QuickSettings) { + LoadApp(Apps::Clock, DisplayApp::FullRefreshDirections::LeftAnim); + } else { + LoadApp(Apps::Clock, DisplayApp::FullRefreshDirections::Down); + } + } + break; + case Messages::ButtonLongerPressed: + // Create reboot app and open it instead + LoadApp(Apps::SysInfo, DisplayApp::FullRefreshDirections::Up); + break; + case Messages::ButtonDoubleClicked: + if (currentApp != Apps::Notifications && currentApp != Apps::NotificationsPreview) { + LoadApp(Apps::Notifications, DisplayApp::FullRefreshDirections::Down); + } + break; case Messages::BleFirmwareUpdateStarted: LoadApp(Apps::FirmwareUpdate, DisplayApp::FullRefreshDirections::Down); @@ -334,6 +359,11 @@ void DisplayApp::LoadApp(Apps app, DisplayApp::FullRefreshDirections direction) ReturnApp(Apps::Clock, FullRefreshDirections::Down, TouchEvents::None); break; + case Apps::PassKey: + currentScreen = std::make_unique(this, bleController.GetPairingKey()); + ReturnApp(Apps::Clock, FullRefreshDirections::Down, TouchEvents::SwipeDown); + break; + case Apps::Notifications: currentScreen = std::make_unique( this, notificationManager, systemTask->nimble().alertService(), motorController, Screens::Notifications::Modes::Normal); @@ -389,10 +419,13 @@ void DisplayApp::LoadApp(Apps app, DisplayApp::FullRefreshDirections direction) currentScreen = std::make_unique(this, dateTimeController); ReturnApp(Apps::Settings, FullRefreshDirections::Down, TouchEvents::SwipeDown); break; +<<<<<<< HEAD case Apps::SettingChimes: currentScreen = std::make_unique(this, settingsController); ReturnApp(Apps::Settings, FullRefreshDirections::Down, TouchEvents::SwipeDown); break; +======= +>>>>>>> develop case Apps::BatteryInfo: currentScreen = std::make_unique(this, batteryController); ReturnApp(Apps::Settings, FullRefreshDirections::Down, TouchEvents::SwipeDown); @@ -413,7 +446,7 @@ void DisplayApp::LoadApp(Apps app, DisplayApp::FullRefreshDirections direction) currentScreen = std::make_unique(this); break; case Apps::Paint: - currentScreen = std::make_unique(this, lvgl); + currentScreen = std::make_unique(this, lvgl, motorController); break; case Apps::Paddle: currentScreen = std::make_unique(this, lvgl); @@ -480,8 +513,9 @@ void DisplayApp::SetFullRefresh(DisplayApp::FullRefreshDirections direction) { } void DisplayApp::PushMessageToSystemTask(Pinetime::System::Messages message) { - if (systemTask != nullptr) + if (systemTask != nullptr) { systemTask->PushMessage(message); + } } void DisplayApp::Register(Pinetime::System::SystemTask* systemTask) { diff --git a/src/displayapp/DisplayApp.h b/src/displayapp/DisplayApp.h index a87cab0b..39fe6314 100644 --- a/src/displayapp/DisplayApp.h +++ b/src/displayapp/DisplayApp.h @@ -5,9 +5,9 @@ #include #include #include -#include "Apps.h" -#include "LittleVgl.h" -#include "TouchEvents.h" +#include "displayapp/Apps.h" +#include "displayapp/LittleVgl.h" +#include "displayapp/TouchEvents.h" #include "components/brightness/BrightnessController.h" #include "components/motor/MotorController.h" #include "components/firmwarevalidator/FirmwareValidator.h" @@ -17,7 +17,7 @@ #include "components/alarm/AlarmController.h" #include "touchhandler/TouchHandler.h" -#include "Messages.h" +#include "displayapp/Messages.h" #include "BootErrors.h" namespace Pinetime { diff --git a/src/displayapp/DisplayAppRecovery.cpp b/src/displayapp/DisplayAppRecovery.cpp index a42d81a2..fd7017a4 100644 --- a/src/displayapp/DisplayAppRecovery.cpp +++ b/src/displayapp/DisplayAppRecovery.cpp @@ -1,9 +1,9 @@ -#include "DisplayAppRecovery.h" +#include "displayapp/DisplayAppRecovery.h" #include #include #include -#include -#include +#include "components/rle/RleDecoder.h" +#include "touchhandler/TouchHandler.h" #include "displayapp/icons/infinitime/infinitime-nb.c" #include "components/ble/BleController.h" diff --git a/src/displayapp/DisplayAppRecovery.h b/src/displayapp/DisplayAppRecovery.h index 72868159..86e956d1 100644 --- a/src/displayapp/DisplayAppRecovery.h +++ b/src/displayapp/DisplayAppRecovery.h @@ -11,10 +11,10 @@ #include #include #include "BootErrors.h" -#include "TouchEvents.h" -#include "Apps.h" -#include "Messages.h" -#include "DummyLittleVgl.h" +#include "displayapp/TouchEvents.h" +#include "displayapp/Apps.h" +#include "displayapp/Messages.h" +#include "displayapp/DummyLittleVgl.h" namespace Pinetime { namespace Drivers { diff --git a/src/displayapp/DummyLittleVgl.h b/src/displayapp/DummyLittleVgl.h index 1db51343..47c9e021 100644 --- a/src/displayapp/DummyLittleVgl.h +++ b/src/displayapp/DummyLittleVgl.h @@ -1,8 +1,8 @@ #pragma once -#include -#include -#include +#include +#include +#include #include #include diff --git a/src/displayapp/LittleVgl.cpp b/src/displayapp/LittleVgl.cpp index 2bd5e57b..e7b58c16 100644 --- a/src/displayapp/LittleVgl.cpp +++ b/src/displayapp/LittleVgl.cpp @@ -1,5 +1,5 @@ -#include "LittleVgl.h" -#include "lv_pinetime_theme.h" +#include "displayapp/LittleVgl.h" +#include "displayapp/lv_pinetime_theme.h" #include #include diff --git a/src/displayapp/Messages.h b/src/displayapp/Messages.h index 19d2c4d3..a3a78cc9 100644 --- a/src/displayapp/Messages.h +++ b/src/displayapp/Messages.h @@ -1,4 +1,5 @@ #pragma once +#include namespace Pinetime { namespace Applications { namespace Display { @@ -9,6 +10,9 @@ namespace Pinetime { UpdateBleConnection, TouchEvent, ButtonPushed, + ButtonLongPressed, + ButtonLongerPressed, + ButtonDoubleClicked, NewNotification, TimerDone, BleFirmwareUpdateStarted, diff --git a/src/displayapp/lv_pinetime_theme.c b/src/displayapp/lv_pinetime_theme.c index 1b8b1980..b74b2fd7 100644 --- a/src/displayapp/lv_pinetime_theme.c +++ b/src/displayapp/lv_pinetime_theme.c @@ -6,7 +6,7 @@ /********************* * INCLUDES *********************/ -#include "lv_pinetime_theme.h" +#include "displayapp/lv_pinetime_theme.h" /********************* * DEFINES @@ -119,7 +119,6 @@ static void basic_init(void) { lv_style_set_bg_color(&style_btn, LV_STATE_DISABLED | LV_STATE_CHECKED, lv_color_hex3(0x888)); lv_style_set_border_color(&style_btn, LV_STATE_DEFAULT, theme.color_primary); lv_style_set_border_width(&style_btn, LV_STATE_DEFAULT, 0); - lv_style_set_border_opa(&style_btn, LV_STATE_CHECKED, LV_OPA_TRANSP); lv_style_set_text_color(&style_btn, LV_STATE_DEFAULT, lv_color_hex(0xffffff)); lv_style_set_text_color(&style_btn, LV_STATE_CHECKED, lv_color_hex(0xffffff)); diff --git a/src/displayapp/screens/Alarm.cpp b/src/displayapp/screens/Alarm.cpp index 6b45a36e..537ac0e0 100644 --- a/src/displayapp/screens/Alarm.cpp +++ b/src/displayapp/screens/Alarm.cpp @@ -15,9 +15,9 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . */ -#include "Alarm.h" -#include "Screen.h" -#include "Symbols.h" +#include "displayapp/screens/Alarm.h" +#include "displayapp/screens/Screen.h" +#include "displayapp/screens/Symbols.h" using namespace Pinetime::Applications::Screens; using Pinetime::Controllers::AlarmController; @@ -36,7 +36,7 @@ Alarm::Alarm(DisplayApp* app, Controllers::AlarmController& alarmController) alarmHours = alarmController.Hours(); alarmMinutes = alarmController.Minutes(); - lv_label_set_text_fmt(time, "%02lu:%02lu", alarmHours, alarmMinutes); + lv_label_set_text_fmt(time, "%02hhu:%02hhu", alarmHours, alarmMinutes); lv_obj_align(time, lv_scr_act(), LV_ALIGN_CENTER, 0, -25); @@ -223,7 +223,7 @@ void Alarm::ShowInfo() { auto secToAlarm = timeToAlarm % 60; lv_label_set_text_fmt( - txtMessage, "Time to\nalarm:\n%2d Days\n%2d Hours\n%2d Minutes\n%2d Seconds", daysToAlarm, hrsToAlarm, minToAlarm, secToAlarm); + txtMessage, "Time to\nalarm:\n%2lu Days\n%2lu Hours\n%2lu Minutes\n%2lu Seconds", daysToAlarm, hrsToAlarm, minToAlarm, secToAlarm); } else { lv_label_set_text(txtMessage, "Alarm\nis not\nset."); } diff --git a/src/displayapp/screens/Alarm.h b/src/displayapp/screens/Alarm.h index 32a14d2f..4b301ce1 100644 --- a/src/displayapp/screens/Alarm.h +++ b/src/displayapp/screens/Alarm.h @@ -17,9 +17,9 @@ */ #pragma once -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include "systemtask/SystemTask.h" -#include "../LittleVgl.h" +#include "displayapp/LittleVgl.h" #include "components/alarm/AlarmController.h" namespace Pinetime { @@ -40,7 +40,9 @@ namespace Pinetime { Controllers::AlarmController& alarmController; lv_obj_t *time, *btnEnable, *txtEnable, *btnMinutesUp, *btnMinutesDown, *btnHoursUp, *btnHoursDown, *txtMinUp, *txtMinDown, - *txtHrUp, *txtHrDown, *btnRecur, *txtRecur, *btnMessage, *txtMessage, *btnInfo, *txtInfo; + *txtHrUp, *txtHrDown, *btnRecur, *txtRecur, *btnInfo, *txtInfo; + lv_obj_t* txtMessage = nullptr; + lv_obj_t* btnMessage = nullptr; enum class EnableButtonState { On, Off, Alerting }; void SetEnableButtonState(); diff --git a/src/displayapp/screens/ApplicationList.cpp b/src/displayapp/screens/ApplicationList.cpp index 5c582f60..29c8affb 100644 --- a/src/displayapp/screens/ApplicationList.cpp +++ b/src/displayapp/screens/ApplicationList.cpp @@ -1,10 +1,10 @@ -#include "ApplicationList.h" +#include "displayapp/screens/ApplicationList.h" #include #include -#include "Symbols.h" -#include "Tile.h" +#include "displayapp/screens/Symbols.h" +#include "displayapp/screens/Tile.h" #include "displayapp/Apps.h" -#include "../DisplayApp.h" +#include "displayapp/DisplayApp.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/ApplicationList.h b/src/displayapp/screens/ApplicationList.h index 103c38ae..f430a89e 100644 --- a/src/displayapp/screens/ApplicationList.h +++ b/src/displayapp/screens/ApplicationList.h @@ -2,8 +2,8 @@ #include -#include "Screen.h" -#include "ScreenList.h" +#include "displayapp/screens/Screen.h" +#include "displayapp/screens/ScreenList.h" #include "components/datetime/DateTimeController.h" #include "components/settings/Settings.h" #include "components/battery/BatteryController.h" diff --git a/src/displayapp/screens/BatteryIcon.cpp b/src/displayapp/screens/BatteryIcon.cpp index c67bcb23..08aaab70 100644 --- a/src/displayapp/screens/BatteryIcon.cpp +++ b/src/displayapp/screens/BatteryIcon.cpp @@ -1,6 +1,6 @@ +#include "displayapp/screens/BatteryIcon.h" #include -#include "BatteryIcon.h" -#include "Symbols.h" +#include "displayapp/screens/Symbols.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/BatteryIcon.h b/src/displayapp/screens/BatteryIcon.h index b370b331..bec2e4e0 100644 --- a/src/displayapp/screens/BatteryIcon.h +++ b/src/displayapp/screens/BatteryIcon.h @@ -1,4 +1,5 @@ #pragma once +#include namespace Pinetime { namespace Applications { diff --git a/src/displayapp/screens/BatteryInfo.cpp b/src/displayapp/screens/BatteryInfo.cpp index 44ea7f51..e17de9ab 100644 --- a/src/displayapp/screens/BatteryInfo.cpp +++ b/src/displayapp/screens/BatteryInfo.cpp @@ -1,5 +1,5 @@ -#include "BatteryInfo.h" -#include "../DisplayApp.h" +#include "displayapp/screens/BatteryInfo.h" +#include "displayapp/DisplayApp.h" #include "components/battery/BatteryController.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/BatteryInfo.h b/src/displayapp/screens/BatteryInfo.h index 63454a26..de34cdff 100644 --- a/src/displayapp/screens/BatteryInfo.h +++ b/src/displayapp/screens/BatteryInfo.h @@ -1,9 +1,7 @@ #pragma once #include -#include -#include -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include namespace Pinetime { diff --git a/src/displayapp/screens/BleIcon.cpp b/src/displayapp/screens/BleIcon.cpp index da3d15e7..5058f3eb 100644 --- a/src/displayapp/screens/BleIcon.cpp +++ b/src/displayapp/screens/BleIcon.cpp @@ -1,5 +1,5 @@ -#include "BleIcon.h" -#include "Symbols.h" +#include "displayapp/screens/BleIcon.h" +#include "displayapp/screens/Symbols.h" using namespace Pinetime::Applications::Screens; const char* BleIcon::GetIcon(bool isConnected) { diff --git a/src/displayapp/screens/Brightness.cpp b/src/displayapp/screens/Brightness.cpp index 1278cd62..d9901ae8 100644 --- a/src/displayapp/screens/Brightness.cpp +++ b/src/displayapp/screens/Brightness.cpp @@ -1,4 +1,4 @@ -#include "Brightness.h" +#include "displayapp/screens/Brightness.h" #include using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/Brightness.h b/src/displayapp/screens/Brightness.h index 14e48592..693570c7 100644 --- a/src/displayapp/screens/Brightness.h +++ b/src/displayapp/screens/Brightness.h @@ -2,7 +2,7 @@ #include #include -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include "components/brightness/BrightnessController.h" namespace Pinetime { diff --git a/src/displayapp/screens/Clock.cpp b/src/displayapp/screens/Clock.cpp index 5a5cd18b..1415e8ec 100644 --- a/src/displayapp/screens/Clock.cpp +++ b/src/displayapp/screens/Clock.cpp @@ -1,4 +1,4 @@ -#include "Clock.h" +#include "displayapp/screens/Clock.h" #include #include @@ -6,10 +6,11 @@ #include "components/motion/MotionController.h" #include "components/ble/BleController.h" #include "components/ble/NotificationManager.h" -#include "../DisplayApp.h" -#include "WatchFaceDigital.h" -#include "WatchFaceAnalog.h" -#include "PineTimeStyle.h" +#include "components/settings/Settings.h" +#include "displayapp/DisplayApp.h" +#include "displayapp/screens/WatchFaceDigital.h" +#include "displayapp/screens/WatchFaceAnalog.h" +#include "displayapp/screens/PineTimeStyle.h" using namespace Pinetime::Applications::Screens; @@ -54,6 +55,10 @@ bool Clock::OnTouchEvent(Pinetime::Applications::TouchEvents event) { return screen->OnTouchEvent(event); } +bool Clock::OnButtonPushed() { + return screen->OnButtonPushed(); +} + std::unique_ptr Clock::WatchFaceDigitalScreen() { return std::make_unique(app, dateTimeController, diff --git a/src/displayapp/screens/Clock.h b/src/displayapp/screens/Clock.h index 648f72da..fcecc6b3 100644 --- a/src/displayapp/screens/Clock.h +++ b/src/displayapp/screens/Clock.h @@ -5,7 +5,7 @@ #include #include #include -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include "components/datetime/DateTimeController.h" namespace Pinetime { @@ -32,6 +32,7 @@ namespace Pinetime { ~Clock() override; bool OnTouchEvent(TouchEvents event) override; + bool OnButtonPushed() override; private: Controllers::DateTime& dateTimeController; diff --git a/src/displayapp/screens/DropDownDemo.cpp b/src/displayapp/screens/DropDownDemo.cpp index 9043c20d..cf239a2f 100644 --- a/src/displayapp/screens/DropDownDemo.cpp +++ b/src/displayapp/screens/DropDownDemo.cpp @@ -1,7 +1,7 @@ -#include "DropDownDemo.h" +#include "displayapp/screens/DropDownDemo.h" #include #include -#include "../DisplayApp.h" +#include "displayapp/DisplayApp.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/DropDownDemo.h b/src/displayapp/screens/DropDownDemo.h index ff388c57..bcf0f45c 100644 --- a/src/displayapp/screens/DropDownDemo.h +++ b/src/displayapp/screens/DropDownDemo.h @@ -1,7 +1,7 @@ #pragma once #include -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include namespace Pinetime { diff --git a/src/displayapp/screens/Error.cpp b/src/displayapp/screens/Error.cpp index 75946aba..1dbc3447 100644 --- a/src/displayapp/screens/Error.cpp +++ b/src/displayapp/screens/Error.cpp @@ -1,4 +1,4 @@ -#include "Error.h" +#include "displayapp/screens/Error.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/Error.h b/src/displayapp/screens/Error.h index 20dde7ee..23167545 100644 --- a/src/displayapp/screens/Error.h +++ b/src/displayapp/screens/Error.h @@ -1,6 +1,6 @@ #pragma once -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include "BootErrors.h" #include diff --git a/src/displayapp/screens/FirmwareUpdate.cpp b/src/displayapp/screens/FirmwareUpdate.cpp index 79bda0ba..373fcae4 100644 --- a/src/displayapp/screens/FirmwareUpdate.cpp +++ b/src/displayapp/screens/FirmwareUpdate.cpp @@ -1,7 +1,7 @@ -#include "FirmwareUpdate.h" +#include "displayapp/screens/FirmwareUpdate.h" #include #include "components/ble/BleController.h" -#include "../DisplayApp.h" +#include "displayapp/DisplayApp.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/FirmwareUpdate.h b/src/displayapp/screens/FirmwareUpdate.h index 8fc86d8c..a61178ce 100644 --- a/src/displayapp/screens/FirmwareUpdate.h +++ b/src/displayapp/screens/FirmwareUpdate.h @@ -1,6 +1,6 @@ #pragma once -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include #include "FreeRTOS.h" diff --git a/src/displayapp/screens/FirmwareValidation.cpp b/src/displayapp/screens/FirmwareValidation.cpp index eef8f919..c7a5b27e 100644 --- a/src/displayapp/screens/FirmwareValidation.cpp +++ b/src/displayapp/screens/FirmwareValidation.cpp @@ -1,8 +1,8 @@ -#include "FirmwareValidation.h" +#include "displayapp/screens/FirmwareValidation.h" #include #include "Version.h" #include "components/firmwarevalidator/FirmwareValidator.h" -#include "../DisplayApp.h" +#include "displayapp/DisplayApp.h" using namespace Pinetime::Applications::Screens; @@ -18,7 +18,7 @@ FirmwareValidation::FirmwareValidation(Pinetime::Applications::DisplayApp* app, : Screen {app}, validator {validator} { labelVersion = lv_label_create(lv_scr_act(), nullptr); lv_label_set_text_fmt(labelVersion, - "Version : %d.%d.%d\n" + "Version : %lu.%lu.%lu\n" "ShortRef : %s", Version::Major(), Version::Minor(), diff --git a/src/displayapp/screens/FirmwareValidation.h b/src/displayapp/screens/FirmwareValidation.h index bfdb096d..278c4adf 100644 --- a/src/displayapp/screens/FirmwareValidation.h +++ b/src/displayapp/screens/FirmwareValidation.h @@ -1,6 +1,6 @@ #pragma once -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include namespace Pinetime { diff --git a/src/displayapp/screens/FlashLight.cpp b/src/displayapp/screens/FlashLight.cpp index dcb31a7f..c4d02643 100644 --- a/src/displayapp/screens/FlashLight.cpp +++ b/src/displayapp/screens/FlashLight.cpp @@ -1,6 +1,6 @@ -#include "FlashLight.h" -#include "../DisplayApp.h" -#include "Symbols.h" +#include "displayapp/screens/FlashLight.h" +#include "displayapp/DisplayApp.h" +#include "displayapp/screens/Symbols.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/FlashLight.h b/src/displayapp/screens/FlashLight.h index f2c65bbe..e91a1032 100644 --- a/src/displayapp/screens/FlashLight.h +++ b/src/displayapp/screens/FlashLight.h @@ -1,6 +1,6 @@ #pragma once -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include "components/brightness/BrightnessController.h" #include "systemtask/SystemTask.h" #include diff --git a/src/displayapp/screens/HeartRate.cpp b/src/displayapp/screens/HeartRate.cpp index b6ece27f..513c40bf 100644 --- a/src/displayapp/screens/HeartRate.cpp +++ b/src/displayapp/screens/HeartRate.cpp @@ -1,8 +1,8 @@ -#include -#include "HeartRate.h" +#include "displayapp/screens/HeartRate.h" +#include #include -#include "../DisplayApp.h" +#include "displayapp/DisplayApp.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/HeartRate.h b/src/displayapp/screens/HeartRate.h index 7f7d3ad3..baa0ccdd 100644 --- a/src/displayapp/screens/HeartRate.h +++ b/src/displayapp/screens/HeartRate.h @@ -2,11 +2,11 @@ #include #include -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include #include "systemtask/SystemTask.h" -#include -#include +#include +#include namespace Pinetime { namespace Controllers { diff --git a/src/displayapp/screens/InfiniPaint.cpp b/src/displayapp/screens/InfiniPaint.cpp index 85a5e826..d279fafc 100644 --- a/src/displayapp/screens/InfiniPaint.cpp +++ b/src/displayapp/screens/InfiniPaint.cpp @@ -1,10 +1,15 @@ -#include "InfiniPaint.h" -#include "../DisplayApp.h" -#include "../LittleVgl.h" +#include "displayapp/screens/InfiniPaint.h" +#include "displayapp/DisplayApp.h" +#include "displayapp/LittleVgl.h" + +#include // std::fill using namespace Pinetime::Applications::Screens; -InfiniPaint::InfiniPaint(Pinetime::Applications::DisplayApp* app, Pinetime::Components::LittleVgl& lvgl) : Screen(app), lvgl {lvgl} { +InfiniPaint::InfiniPaint(Pinetime::Applications::DisplayApp* app, + Pinetime::Components::LittleVgl& lvgl, + Pinetime::Controllers::MotorController& motor) + : Screen(app), lvgl {lvgl}, motor {motor} { std::fill(b, b + bufferSize, selectColor); } @@ -15,6 +20,7 @@ InfiniPaint::~InfiniPaint() { bool InfiniPaint::OnTouchEvent(Pinetime::Applications::TouchEvents event) { switch (event) { case Pinetime::Applications::TouchEvents::LongTap: + color = (color + 1) % 8; switch (color) { case 0: selectColor = LV_COLOR_MAGENTA; @@ -47,7 +53,7 @@ bool InfiniPaint::OnTouchEvent(Pinetime::Applications::TouchEvents event) { } std::fill(b, b + bufferSize, selectColor); - color++; + motor.RunForDuration(35); return true; default: return true; diff --git a/src/displayapp/screens/InfiniPaint.h b/src/displayapp/screens/InfiniPaint.h index 0a70e033..8c427402 100644 --- a/src/displayapp/screens/InfiniPaint.h +++ b/src/displayapp/screens/InfiniPaint.h @@ -2,7 +2,9 @@ #include #include -#include "Screen.h" +#include // std::fill +#include "displayapp/screens/Screen.h" +#include "components/motor/MotorController.h" namespace Pinetime { namespace Components { @@ -13,7 +15,7 @@ namespace Pinetime { class InfiniPaint : public Screen { public: - InfiniPaint(DisplayApp* app, Pinetime::Components::LittleVgl& lvgl); + InfiniPaint(DisplayApp* app, Pinetime::Components::LittleVgl& lvgl, Controllers::MotorController& motor); ~InfiniPaint() override; @@ -23,6 +25,7 @@ namespace Pinetime { private: Pinetime::Components::LittleVgl& lvgl; + Controllers::MotorController& motor; static constexpr uint16_t width = 10; static constexpr uint16_t height = 10; static constexpr uint16_t bufferSize = width * height; diff --git a/src/displayapp/screens/Label.cpp b/src/displayapp/screens/Label.cpp index 1761a7b5..62ec1f0a 100644 --- a/src/displayapp/screens/Label.cpp +++ b/src/displayapp/screens/Label.cpp @@ -1,4 +1,4 @@ -#include "Label.h" +#include "displayapp/screens/Label.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/Label.h b/src/displayapp/screens/Label.h index f1e49079..3fe5111f 100644 --- a/src/displayapp/screens/Label.h +++ b/src/displayapp/screens/Label.h @@ -1,6 +1,6 @@ #pragma once -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include namespace Pinetime { diff --git a/src/displayapp/screens/List.cpp b/src/displayapp/screens/List.cpp index 064b47a6..af3f30f6 100644 --- a/src/displayapp/screens/List.cpp +++ b/src/displayapp/screens/List.cpp @@ -1,6 +1,6 @@ -#include "List.h" -#include "../DisplayApp.h" -#include "Symbols.h" +#include "displayapp/screens/List.h" +#include "displayapp/DisplayApp.h" +#include "displayapp/screens/Symbols.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/List.h b/src/displayapp/screens/List.h index d9f61f29..023de3aa 100644 --- a/src/displayapp/screens/List.h +++ b/src/displayapp/screens/List.h @@ -3,8 +3,8 @@ #include #include #include -#include "Screen.h" -#include "../Apps.h" +#include "displayapp/screens/Screen.h" +#include "displayapp/Apps.h" #include "components/settings/Settings.h" #define MAXLISTITEMS 4 diff --git a/src/displayapp/screens/Meter.cpp b/src/displayapp/screens/Meter.cpp index 57cde9cf..9c853109 100644 --- a/src/displayapp/screens/Meter.cpp +++ b/src/displayapp/screens/Meter.cpp @@ -1,6 +1,6 @@ -#include "Meter.h" +#include "displayapp/screens/Meter.h" #include -#include "../DisplayApp.h" +#include "displayapp/DisplayApp.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/Meter.h b/src/displayapp/screens/Meter.h index 9b3d1d48..50d9f83c 100644 --- a/src/displayapp/screens/Meter.h +++ b/src/displayapp/screens/Meter.h @@ -1,7 +1,7 @@ #pragma once #include -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include #include diff --git a/src/displayapp/screens/Metronome.cpp b/src/displayapp/screens/Metronome.cpp index 52cb8519..f6f269dc 100644 --- a/src/displayapp/screens/Metronome.cpp +++ b/src/displayapp/screens/Metronome.cpp @@ -1,5 +1,5 @@ -#include "Metronome.h" -#include "Symbols.h" +#include "displayapp/screens/Metronome.h" +#include "displayapp/screens/Symbols.h" using namespace Pinetime::Applications::Screens; @@ -113,9 +113,16 @@ void Metronome::OnEvent(lv_obj_t* obj, lv_event_t event) { lv_label_set_text_fmt(bpmValue, "%03d", bpm); } tappedTime = xTaskGetTickCount(); + allowExit = true; } break; } + case LV_EVENT_RELEASED: + case LV_EVENT_PRESS_LOST: + if (obj == bpmTap) { + allowExit = false; + } + break; case LV_EVENT_CLICKED: { if (obj == playPause) { metronomeStarted = !metronomeStarted; @@ -135,3 +142,11 @@ void Metronome::OnEvent(lv_obj_t* obj, lv_event_t event) { break; } } + +bool Metronome::OnTouchEvent(TouchEvents event) { + if (event == TouchEvents::SwipeDown && allowExit) { + running = false; + return true; + } + return false; +} diff --git a/src/displayapp/screens/Metronome.h b/src/displayapp/screens/Metronome.h index f3a84dc8..6e6589fe 100644 --- a/src/displayapp/screens/Metronome.h +++ b/src/displayapp/screens/Metronome.h @@ -2,6 +2,7 @@ #include "systemtask/SystemTask.h" #include "components/motor/MotorController.h" +#include "displayapp/screens/Screen.h" namespace Pinetime { namespace Applications { @@ -13,6 +14,7 @@ namespace Pinetime { ~Metronome() override; void Refresh() override; void OnEvent(lv_obj_t* obj, lv_event_t event); + bool OnTouchEvent(TouchEvents event) override; private: TickType_t startTime = 0; @@ -24,6 +26,7 @@ namespace Pinetime { uint8_t counter = 1; bool metronomeStarted = false; + bool allowExit = false; lv_obj_t *bpmArc, *bpmTap, *bpmValue; lv_obj_t *bpbDropdown, *currentBpbText; diff --git a/src/displayapp/screens/Motion.cpp b/src/displayapp/screens/Motion.cpp index 2f1f7c21..23eb2765 100644 --- a/src/displayapp/screens/Motion.cpp +++ b/src/displayapp/screens/Motion.cpp @@ -1,6 +1,6 @@ -#include -#include "Motion.h" -#include "../DisplayApp.h" +#include "displayapp/screens/Motion.h" +#include +#include "displayapp/DisplayApp.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/Motion.h b/src/displayapp/screens/Motion.h index 20a18d02..d6997409 100644 --- a/src/displayapp/screens/Motion.h +++ b/src/displayapp/screens/Motion.h @@ -2,10 +2,10 @@ #include #include -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include -#include -#include +#include +#include #include namespace Pinetime { diff --git a/src/displayapp/screens/Music.cpp b/src/displayapp/screens/Music.cpp index 47ddb655..9f17b956 100644 --- a/src/displayapp/screens/Music.cpp +++ b/src/displayapp/screens/Music.cpp @@ -15,10 +15,10 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . */ -#include "Music.h" -#include "Symbols.h" +#include "displayapp/screens/Music.h" +#include "displayapp/screens/Symbols.h" #include -#include "../DisplayApp.h" +#include "displayapp/DisplayApp.h" #include "components/ble/MusicService.h" #include "displayapp/icons/music/disc.cpp" #include "displayapp/icons/music/disc_f_1.cpp" @@ -277,12 +277,14 @@ bool Music::OnTouchEvent(Pinetime::Applications::TouchEvents event) { return true; } case TouchEvents::SwipeDown: { - lv_obj_set_hidden(btnNext, false); - lv_obj_set_hidden(btnPrev, false); - - lv_obj_set_hidden(btnVolDown, true); - lv_obj_set_hidden(btnVolUp, true); - return true; + if (lv_obj_get_hidden(btnNext)) { + lv_obj_set_hidden(btnNext, false); + lv_obj_set_hidden(btnPrev, false); + lv_obj_set_hidden(btnVolDown, true); + lv_obj_set_hidden(btnVolUp, true); + return true; + } + return false; } case TouchEvents::SwipeLeft: { musicService.event(Controllers::MusicService::EVENT_MUSIC_NEXT); diff --git a/src/displayapp/screens/Music.h b/src/displayapp/screens/Music.h index 6f2d80a0..f9b4eaab 100644 --- a/src/displayapp/screens/Music.h +++ b/src/displayapp/screens/Music.h @@ -20,7 +20,7 @@ #include #include #include -#include "Screen.h" +#include "displayapp/screens/Screen.h" namespace Pinetime { namespace Controllers { diff --git a/src/displayapp/screens/Navigation.cpp b/src/displayapp/screens/Navigation.cpp index d437cc6d..674362a6 100644 --- a/src/displayapp/screens/Navigation.cpp +++ b/src/displayapp/screens/Navigation.cpp @@ -15,9 +15,9 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . */ -#include "Navigation.h" +#include "displayapp/screens/Navigation.h" #include -#include "../DisplayApp.h" +#include "displayapp/DisplayApp.h" #include "components/ble/NavigationService.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/Navigation.h b/src/displayapp/screens/Navigation.h index 48f00a76..07674ef1 100644 --- a/src/displayapp/screens/Navigation.h +++ b/src/displayapp/screens/Navigation.h @@ -20,7 +20,7 @@ #include #include #include -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include namespace Pinetime { diff --git a/src/displayapp/screens/NotificationIcon.cpp b/src/displayapp/screens/NotificationIcon.cpp index d8792f9d..0e913ae7 100644 --- a/src/displayapp/screens/NotificationIcon.cpp +++ b/src/displayapp/screens/NotificationIcon.cpp @@ -1,5 +1,5 @@ -#include "NotificationIcon.h" -#include "Symbols.h" +#include "displayapp/screens/NotificationIcon.h" +#include "displayapp/screens/Symbols.h" using namespace Pinetime::Applications::Screens; const char* NotificationIcon::GetIcon(bool newNotificationAvailable) { diff --git a/src/displayapp/screens/Notifications.cpp b/src/displayapp/screens/Notifications.cpp index 4f475813..569c422b 100644 --- a/src/displayapp/screens/Notifications.cpp +++ b/src/displayapp/screens/Notifications.cpp @@ -1,8 +1,8 @@ -#include "Notifications.h" -#include +#include "displayapp/screens/Notifications.h" +#include "displayapp/DisplayApp.h" #include "components/ble/MusicService.h" #include "components/ble/AlertNotificationService.h" -#include "Symbols.h" +#include "displayapp/screens/Symbols.h" using namespace Pinetime::Applications::Screens; extern lv_font_t jetbrains_mono_extrabold_compressed; diff --git a/src/displayapp/screens/Notifications.h b/src/displayapp/screens/Notifications.h index 0b5271e7..cbb7af6c 100644 --- a/src/displayapp/screens/Notifications.h +++ b/src/displayapp/screens/Notifications.h @@ -3,7 +3,7 @@ #include #include #include -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include "components/ble/NotificationManager.h" #include "components/motor/MotorController.h" diff --git a/src/displayapp/screens/Paddle.cpp b/src/displayapp/screens/Paddle.cpp index 26c2368b..608eb644 100644 --- a/src/displayapp/screens/Paddle.cpp +++ b/src/displayapp/screens/Paddle.cpp @@ -1,6 +1,8 @@ -#include "Paddle.h" -#include "../DisplayApp.h" -#include "../LittleVgl.h" +#include "displayapp/screens/Paddle.h" +#include "displayapp/DisplayApp.h" +#include "displayapp/LittleVgl.h" + +#include // for rand() using namespace Pinetime::Applications::Screens; @@ -50,6 +52,13 @@ void Paddle::Refresh() { // checks if it has touched the side (right side) if (ballX >= LV_HOR_RES - ballSize - 1) { dx *= -1; + dy += rand() % 3 - 1; // add a little randomization in wall bounce direction, one of [-1, 0, 1] + if (dy > 5) { // limit dy to be in range [-5 to 5] + dy = 5; + } + if (dy < -5) { + dy = -5; + } } // checks if it is in the position of the paddle diff --git a/src/displayapp/screens/Paddle.h b/src/displayapp/screens/Paddle.h index fc2131a1..3a30eee6 100644 --- a/src/displayapp/screens/Paddle.h +++ b/src/displayapp/screens/Paddle.h @@ -2,7 +2,7 @@ #include #include -#include "Screen.h" +#include "displayapp/screens/Screen.h" namespace Pinetime { namespace Components { diff --git a/src/displayapp/screens/PassKey.cpp b/src/displayapp/screens/PassKey.cpp new file mode 100644 index 00000000..9e43a541 --- /dev/null +++ b/src/displayapp/screens/PassKey.cpp @@ -0,0 +1,24 @@ +#include "PassKey.h" +#include "displayapp/DisplayApp.h" + +using namespace Pinetime::Applications::Screens; + +PassKey::PassKey(Pinetime::Applications::DisplayApp* app, uint32_t key) : Screen(app) { + passkeyLabel = lv_label_create(lv_scr_act(), nullptr); + lv_obj_set_style_local_text_color(passkeyLabel, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0xFFFF00)); + lv_obj_set_style_local_text_font(passkeyLabel, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, &jetbrains_mono_42); + lv_label_set_text_fmt(passkeyLabel, "%06u", key); + lv_obj_align(passkeyLabel, nullptr, LV_ALIGN_CENTER, 0, -20); + + backgroundLabel = lv_label_create(lv_scr_act(), nullptr); + lv_obj_set_click(backgroundLabel, true); + lv_label_set_long_mode(backgroundLabel, LV_LABEL_LONG_CROP); + lv_obj_set_size(backgroundLabel, 240, 240); + lv_obj_set_pos(backgroundLabel, 0, 0); + lv_label_set_text(backgroundLabel, ""); +} + +PassKey::~PassKey() { + lv_obj_clean(lv_scr_act()); +} + diff --git a/src/displayapp/screens/PassKey.h b/src/displayapp/screens/PassKey.h new file mode 100644 index 00000000..16e72a3c --- /dev/null +++ b/src/displayapp/screens/PassKey.h @@ -0,0 +1,21 @@ +#pragma once + +#include "Screen.h" +#include + +namespace Pinetime { + namespace Applications { + namespace Screens { + + class PassKey : public Screen { + public: + PassKey(DisplayApp* app, uint32_t key); + ~PassKey() override; + + private: + lv_obj_t* passkeyLabel; + lv_obj_t* backgroundLabel; + }; + } + } +} diff --git a/src/displayapp/screens/PineTimeStyle.cpp b/src/displayapp/screens/PineTimeStyle.cpp index fa88d459..b2b972dc 100644 --- a/src/displayapp/screens/PineTimeStyle.cpp +++ b/src/displayapp/screens/PineTimeStyle.cpp @@ -19,24 +19,31 @@ * Style/layout copied from TimeStyle for Pebble by Dan Tilden (github.com/tilden) */ -#include "PineTimeStyle.h" +#include "displayapp/screens/PineTimeStyle.h" #include #include #include #include -#include "BatteryIcon.h" -#include "BleIcon.h" -#include "NotificationIcon.h" -#include "Symbols.h" +#include "displayapp/screens/BatteryIcon.h" +#include "displayapp/screens/BleIcon.h" +#include "displayapp/screens/NotificationIcon.h" +#include "displayapp/screens/Symbols.h" #include "components/battery/BatteryController.h" #include "components/ble/BleController.h" #include "components/ble/NotificationManager.h" #include "components/motion/MotionController.h" #include "components/settings/Settings.h" -#include "../DisplayApp.h" +#include "displayapp/DisplayApp.h" using namespace Pinetime::Applications::Screens; +namespace { + void event_handler(lv_obj_t* obj, lv_event_t event) { + auto* screen = static_cast(obj->user_data); + screen->UpdateSelected(obj, event); + } +} + PineTimeStyle::PineTimeStyle(DisplayApp* app, Controllers::DateTime& dateTimeController, Controllers::Battery& batteryController, @@ -53,33 +60,30 @@ PineTimeStyle::PineTimeStyle(DisplayApp* app, settingsController {settingsController}, motionController {motionController} { - // This sets the watchface number to return to after leaving the menu - settingsController.SetClockFace(2); - displayedChar[0] = 0; displayedChar[1] = 0; displayedChar[2] = 0; displayedChar[3] = 0; displayedChar[4] = 0; - //Create a 200px wide background rectangle + // Create a 200px wide background rectangle timebar = lv_obj_create(lv_scr_act(), nullptr); lv_obj_set_style_local_bg_color(timebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(settingsController.GetPTSColorBG())); lv_obj_set_style_local_radius(timebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); lv_obj_set_size(timebar, 200, 240); - lv_obj_align(timebar, lv_scr_act(), LV_ALIGN_IN_TOP_LEFT, 5, 0); + lv_obj_align(timebar, lv_scr_act(), LV_ALIGN_IN_TOP_LEFT, 0, 0); // Display the time timeDD1 = lv_label_create(lv_scr_act(), nullptr); lv_obj_set_style_local_text_font(timeDD1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, &open_sans_light); lv_obj_set_style_local_text_color(timeDD1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(settingsController.GetPTSColorTime())); - lv_label_set_text(timeDD1, "12"); + lv_label_set_text(timeDD1, "00"); lv_obj_align(timeDD1, timebar, LV_ALIGN_IN_TOP_MID, 5, 5); timeDD2 = lv_label_create(lv_scr_act(), nullptr); lv_obj_set_style_local_text_font(timeDD2, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, &open_sans_light); lv_obj_set_style_local_text_color(timeDD2, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(settingsController.GetPTSColorTime())); - lv_label_set_text(timeDD2, "34"); + lv_label_set_text(timeDD2, "00"); lv_obj_align(timeDD2, timebar, LV_ALIGN_IN_BOTTOM_MID, 5, -5); timeAMPM = lv_label_create(lv_scr_act(), nullptr); @@ -97,74 +101,78 @@ PineTimeStyle::PineTimeStyle(DisplayApp* app, // Display icons batteryIcon = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_text_color(batteryIcon, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); + lv_obj_set_style_local_text_color(batteryIcon, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK); lv_label_set_text(batteryIcon, Symbols::batteryFull); lv_obj_align(batteryIcon, sidebar, LV_ALIGN_IN_TOP_MID, 0, 2); lv_obj_set_auto_realign(batteryIcon, true); bleIcon = lv_label_create(lv_scr_act(), nullptr); lv_obj_set_style_local_text_color(bleIcon, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); - lv_obj_align(bleIcon, sidebar, LV_ALIGN_IN_TOP_MID, 0, 25); + lv_label_set_text(bleIcon, ""); notificationIcon = lv_label_create(lv_scr_act(), nullptr); lv_obj_set_style_local_text_color(notificationIcon, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); - lv_obj_align(notificationIcon, sidebar, LV_ALIGN_IN_TOP_MID, 0, 40); + lv_label_set_text(notificationIcon, ""); // Calendar icon calendarOuter = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(calendarOuter, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); + lv_obj_set_style_local_bg_color(calendarOuter, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK); lv_obj_set_style_local_radius(calendarOuter, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); lv_obj_set_size(calendarOuter, 34, 34); lv_obj_align(calendarOuter, sidebar, LV_ALIGN_CENTER, 0, 0); calendarInner = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(calendarInner, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0xffffff)); + lv_obj_set_style_local_bg_color(calendarInner, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_WHITE); lv_obj_set_style_local_radius(calendarInner, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); lv_obj_set_size(calendarInner, 27, 27); lv_obj_align(calendarInner, calendarOuter, LV_ALIGN_CENTER, 0, 0); calendarBar1 = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(calendarBar1, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); + lv_obj_set_style_local_bg_color(calendarBar1, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK); lv_obj_set_style_local_radius(calendarBar1, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); lv_obj_set_size(calendarBar1, 3, 12); lv_obj_align(calendarBar1, calendarOuter, LV_ALIGN_IN_TOP_MID, -6, -3); calendarBar2 = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(calendarBar2, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); + lv_obj_set_style_local_bg_color(calendarBar2, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK); lv_obj_set_style_local_radius(calendarBar2, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); lv_obj_set_size(calendarBar2, 3, 12); lv_obj_align(calendarBar2, calendarOuter, LV_ALIGN_IN_TOP_MID, 6, -3); calendarCrossBar1 = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(calendarCrossBar1, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); + lv_obj_set_style_local_bg_color(calendarCrossBar1, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK); lv_obj_set_style_local_radius(calendarCrossBar1, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); lv_obj_set_size(calendarCrossBar1, 8, 3); lv_obj_align(calendarCrossBar1, calendarBar1, LV_ALIGN_IN_BOTTOM_MID, 0, 0); calendarCrossBar2 = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(calendarCrossBar2, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); + lv_obj_set_style_local_bg_color(calendarCrossBar2, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK); lv_obj_set_style_local_radius(calendarCrossBar2, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); lv_obj_set_size(calendarCrossBar2, 8, 3); lv_obj_align(calendarCrossBar2, calendarBar2, LV_ALIGN_IN_BOTTOM_MID, 0, 0); // Display date dateDayOfWeek = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_text_color(dateDayOfWeek, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); + lv_obj_set_style_local_text_color(dateDayOfWeek, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK); lv_label_set_text(dateDayOfWeek, "THU"); lv_obj_align(dateDayOfWeek, sidebar, LV_ALIGN_CENTER, 0, -34); dateDay = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_text_color(dateDay, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); + lv_obj_set_style_local_text_color(dateDay, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK); lv_label_set_text(dateDay, "25"); lv_obj_align(dateDay, sidebar, LV_ALIGN_CENTER, 0, 3); dateMonth = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_text_color(dateMonth, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); + lv_obj_set_style_local_text_color(dateMonth, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK); lv_label_set_text(dateMonth, "MAR"); lv_obj_align(dateMonth, sidebar, LV_ALIGN_CENTER, 0, 32); // Step count gauge - needle_colors[0] = LV_COLOR_WHITE; + if (settingsController.GetPTSColorBar() == Pinetime::Controllers::Settings::Colors::White) { + needle_colors[0] = LV_COLOR_BLACK; + } else { + needle_colors[0] = LV_COLOR_WHITE; + } stepGauge = lv_gauge_create(lv_scr_act(), nullptr); lv_gauge_set_needle_count(stepGauge, 1, needle_colors); lv_obj_set_size(stepGauge, 40, 40); @@ -193,6 +201,100 @@ PineTimeStyle::PineTimeStyle(DisplayApp* app, lv_obj_set_pos(backgroundLabel, 0, 0); lv_label_set_text(backgroundLabel, ""); + btnNextTime = lv_btn_create(lv_scr_act(), nullptr); + btnNextTime->user_data = this; + lv_obj_set_size(btnNextTime, 60, 60); + lv_obj_align(btnNextTime, lv_scr_act(), LV_ALIGN_IN_RIGHT_MID, -15, -80); + lv_obj_set_style_local_bg_opa(btnNextTime, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_50); + lv_obj_set_style_local_value_str(btnNextTime, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, ">"); + lv_obj_set_event_cb(btnNextTime, event_handler); + lv_obj_set_hidden(btnNextTime, true); + + btnPrevTime = lv_btn_create(lv_scr_act(), nullptr); + btnPrevTime->user_data = this; + lv_obj_set_size(btnPrevTime, 60, 60); + lv_obj_align(btnPrevTime, lv_scr_act(), LV_ALIGN_IN_LEFT_MID, 15, -80); + lv_obj_set_style_local_bg_opa(btnPrevTime, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_50); + lv_obj_set_style_local_value_str(btnPrevTime, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, "<"); + lv_obj_set_event_cb(btnPrevTime, event_handler); + lv_obj_set_hidden(btnPrevTime, true); + + btnNextBar = lv_btn_create(lv_scr_act(), nullptr); + btnNextBar->user_data = this; + lv_obj_set_size(btnNextBar, 60, 60); + lv_obj_align(btnNextBar, lv_scr_act(), LV_ALIGN_IN_RIGHT_MID, -15, 0); + lv_obj_set_style_local_bg_opa(btnNextBar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_50); + lv_obj_set_style_local_value_str(btnNextBar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, ">"); + lv_obj_set_event_cb(btnNextBar, event_handler); + lv_obj_set_hidden(btnNextBar, true); + + btnPrevBar = lv_btn_create(lv_scr_act(), nullptr); + btnPrevBar->user_data = this; + lv_obj_set_size(btnPrevBar, 60, 60); + lv_obj_align(btnPrevBar, lv_scr_act(), LV_ALIGN_IN_LEFT_MID, 15, 0); + lv_obj_set_style_local_bg_opa(btnPrevBar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_50); + lv_obj_set_style_local_value_str(btnPrevBar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, "<"); + lv_obj_set_event_cb(btnPrevBar, event_handler); + lv_obj_set_hidden(btnPrevBar, true); + + btnNextBG = lv_btn_create(lv_scr_act(), nullptr); + btnNextBG->user_data = this; + lv_obj_set_size(btnNextBG, 60, 60); + lv_obj_align(btnNextBG, lv_scr_act(), LV_ALIGN_IN_RIGHT_MID, -15, 80); + lv_obj_set_style_local_bg_opa(btnNextBG, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_50); + lv_obj_set_style_local_value_str(btnNextBG, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, ">"); + lv_obj_set_event_cb(btnNextBG, event_handler); + lv_obj_set_hidden(btnNextBG, true); + + btnPrevBG = lv_btn_create(lv_scr_act(), nullptr); + btnPrevBG->user_data = this; + lv_obj_set_size(btnPrevBG, 60, 60); + lv_obj_align(btnPrevBG, lv_scr_act(), LV_ALIGN_IN_LEFT_MID, 15, 80); + lv_obj_set_style_local_bg_opa(btnPrevBG, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_50); + lv_obj_set_style_local_value_str(btnPrevBG, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, "<"); + lv_obj_set_event_cb(btnPrevBG, event_handler); + lv_obj_set_hidden(btnPrevBG, true); + + btnReset = lv_btn_create(lv_scr_act(), nullptr); + btnReset->user_data = this; + lv_obj_set_size(btnReset, 60, 60); + lv_obj_align(btnReset, lv_scr_act(), LV_ALIGN_CENTER, 0, 80); + lv_obj_set_style_local_bg_opa(btnReset, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_50); + lv_obj_set_style_local_value_str(btnReset, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, "Rst"); + lv_obj_set_event_cb(btnReset, event_handler); + lv_obj_set_hidden(btnReset, true); + + btnRandom = lv_btn_create(lv_scr_act(), nullptr); + btnRandom->user_data = this; + lv_obj_set_size(btnRandom, 60, 60); + lv_obj_align(btnRandom, lv_scr_act(), LV_ALIGN_CENTER, 0, 0); + lv_obj_set_style_local_bg_opa(btnRandom, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_50); + lv_obj_set_style_local_value_str(btnRandom, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, "Rnd"); + lv_obj_set_event_cb(btnRandom, event_handler); + lv_obj_set_hidden(btnRandom, true); + + btnClose = lv_btn_create(lv_scr_act(), nullptr); + btnClose->user_data = this; + lv_obj_set_size(btnClose, 60, 60); + lv_obj_align(btnClose, lv_scr_act(), LV_ALIGN_CENTER, 0, -80); + lv_obj_set_style_local_bg_opa(btnClose, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_50); + lv_obj_set_style_local_value_str(btnClose, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, "X"); + lv_obj_set_event_cb(btnClose, event_handler); + lv_obj_set_hidden(btnClose, true); + + btnSet = lv_btn_create(lv_scr_act(), nullptr); + btnSet->user_data = this; + lv_obj_set_height(btnSet, 150); + lv_obj_set_width(btnSet, 150); + lv_obj_align(btnSet, lv_scr_act(), LV_ALIGN_CENTER, 0, 0); + lv_obj_set_style_local_radius(btnSet, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 30); + lv_obj_set_style_local_bg_opa(btnSet, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_50); + lv_obj_set_event_cb(btnSet, event_handler); + lbl_btnSet = lv_label_create(btnSet, nullptr); + lv_obj_set_style_local_text_font(lbl_btnSet, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, &lv_font_sys_48); + lv_label_set_text_static(lbl_btnSet, Symbols::settings); + lv_obj_set_hidden(btnSet, true); + taskRefresh = lv_task_create(RefreshTaskCallback, LV_DISP_DEF_REFR_PERIOD, LV_TASK_PRIO_MID, this); Refresh(); } @@ -202,11 +304,55 @@ PineTimeStyle::~PineTimeStyle() { lv_obj_clean(lv_scr_act()); } +bool PineTimeStyle::OnTouchEvent(Pinetime::Applications::TouchEvents event) { + if ((event == Pinetime::Applications::TouchEvents::LongTap) && lv_obj_get_hidden(btnRandom)) { + lv_obj_set_hidden(btnSet, false); + savedTick = lv_tick_get(); + return true; + } + if ((event == Pinetime::Applications::TouchEvents::DoubleTap) && (lv_obj_get_hidden(btnRandom) == false)) { + return true; + } + return false; +} + +void PineTimeStyle::CloseMenu() { + settingsController.SaveSettings(); + lv_obj_set_hidden(btnNextTime, true); + lv_obj_set_hidden(btnPrevTime, true); + lv_obj_set_hidden(btnNextBar, true); + lv_obj_set_hidden(btnPrevBar, true); + lv_obj_set_hidden(btnNextBG, true); + lv_obj_set_hidden(btnPrevBG, true); + lv_obj_set_hidden(btnReset, true); + lv_obj_set_hidden(btnRandom, true); + lv_obj_set_hidden(btnClose, true); +} + +bool PineTimeStyle::OnButtonPushed() { + if (!lv_obj_get_hidden(btnClose)) { + CloseMenu(); + return true; + } + return false; +} + void PineTimeStyle::SetBatteryIcon() { auto batteryPercent = batteryPercentRemaining.Get(); lv_label_set_text(batteryIcon, BatteryIcon::GetBatteryIcon(batteryPercent)); } +void PineTimeStyle::AlignIcons() { + if (notificationState.Get() && bleState.Get()) { + lv_obj_align(bleIcon, sidebar, LV_ALIGN_IN_TOP_MID, 8, 25); + lv_obj_align(notificationIcon, sidebar, LV_ALIGN_IN_TOP_MID, -8, 25); + } else if (notificationState.Get() && !bleState.Get()) { + lv_obj_align(notificationIcon, sidebar, LV_ALIGN_IN_TOP_MID, 0, 25); + } else { + lv_obj_align(bleIcon, sidebar, LV_ALIGN_IN_TOP_MID, 0, 25); + } +} + void PineTimeStyle::Refresh() { isCharging = batteryController.IsCharging(); if (isCharging.IsUpdated()) { @@ -226,13 +372,13 @@ void PineTimeStyle::Refresh() { bleState = bleController.IsConnected(); if (bleState.IsUpdated()) { lv_label_set_text(bleIcon, BleIcon::GetIcon(bleState.Get())); - lv_obj_realign(bleIcon); + AlignIcons(); } notificationState = notificatioManager.AreNewNotificationsAvailable(); if (notificationState.IsUpdated()) { lv_label_set_text(notificationIcon, NotificationIcon::GetIcon(notificationState.Get())); - lv_obj_realign(notificationIcon); + AlignIcons(); } currentDateTime = dateTimeController.CurrentDateTime(); @@ -257,7 +403,7 @@ void PineTimeStyle::Refresh() { char hoursChar[3]; char ampmChar[5]; if (settingsController.GetClockType() == Controllers::Settings::ClockType::H24) { - sprintf(hoursChar, "%02d", hour); + sprintf(hoursChar, "%02d", hour); } else { if (hour == 0 && hour != 12) { hour = 12; @@ -312,4 +458,154 @@ void PineTimeStyle::Refresh() { lv_obj_set_style_local_scale_grad_color(stepGauge, LV_GAUGE_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_WHITE); } } + if (!lv_obj_get_hidden(btnSet)) { + if ((savedTick > 0) && (lv_tick_get() - savedTick > 3000)) { + lv_obj_set_hidden(btnSet, true); + savedTick = 0; + } + } +} + +void PineTimeStyle::UpdateSelected(lv_obj_t* object, lv_event_t event) { + auto valueTime = settingsController.GetPTSColorTime(); + auto valueBar = settingsController.GetPTSColorBar(); + auto valueBG = settingsController.GetPTSColorBG(); + + if (event == LV_EVENT_CLICKED) { + if (object == btnNextTime) { + valueTime = GetNext(valueTime); + if (valueTime == valueBG) { + valueTime = GetNext(valueTime); + } + settingsController.SetPTSColorTime(valueTime); + lv_obj_set_style_local_text_color(timeDD1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); + lv_obj_set_style_local_text_color(timeDD2, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); + lv_obj_set_style_local_text_color(timeAMPM, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); + } + if (object == btnPrevTime) { + valueTime = GetPrevious(valueTime); + if (valueTime == valueBG) { + valueTime = GetPrevious(valueTime); + } + settingsController.SetPTSColorTime(valueTime); + lv_obj_set_style_local_text_color(timeDD1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); + lv_obj_set_style_local_text_color(timeDD2, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); + lv_obj_set_style_local_text_color(timeAMPM, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); + } + if (object == btnNextBar) { + valueBar = GetNext(valueBar); + if (valueBar == Controllers::Settings::Colors::Black) { + valueBar = GetNext(valueBar); + } + if (valueBar == Controllers::Settings::Colors::White) { + needle_colors[0] = LV_COLOR_BLACK; + } else { + needle_colors[0] = LV_COLOR_WHITE; + } + settingsController.SetPTSColorBar(valueBar); + lv_obj_set_style_local_bg_color(sidebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(valueBar)); + } + if (object == btnPrevBar) { + valueBar = GetPrevious(valueBar); + if (valueBar == Controllers::Settings::Colors::Black) { + valueBar = GetPrevious(valueBar); + } + if (valueBar == Controllers::Settings::Colors::White) { + needle_colors[0] = LV_COLOR_BLACK; + } else { + needle_colors[0] = LV_COLOR_WHITE; + } + settingsController.SetPTSColorBar(valueBar); + lv_obj_set_style_local_bg_color(sidebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(valueBar)); + } + if (object == btnNextBG) { + valueBG = GetNext(valueBG); + if (valueBG == valueTime) { + valueBG = GetNext(valueBG); + } + settingsController.SetPTSColorBG(valueBG); + lv_obj_set_style_local_bg_color(timebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(valueBG)); + } + if (object == btnPrevBG) { + valueBG = GetPrevious(valueBG); + if (valueBG == valueTime) { + valueBG = GetPrevious(valueBG); + } + settingsController.SetPTSColorBG(valueBG); + lv_obj_set_style_local_bg_color(timebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(valueBG)); + } + if (object == btnReset) { + needle_colors[0] = LV_COLOR_WHITE; + settingsController.SetPTSColorTime(Controllers::Settings::Colors::Teal); + lv_obj_set_style_local_text_color(timeDD1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(Controllers::Settings::Colors::Teal)); + lv_obj_set_style_local_text_color(timeDD2, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(Controllers::Settings::Colors::Teal)); + lv_obj_set_style_local_text_color(timeAMPM, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(Controllers::Settings::Colors::Teal)); + settingsController.SetPTSColorBar(Controllers::Settings::Colors::Teal); + lv_obj_set_style_local_bg_color(sidebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(Controllers::Settings::Colors::Teal)); + settingsController.SetPTSColorBG(Controllers::Settings::Colors::Black); + lv_obj_set_style_local_bg_color(timebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(Controllers::Settings::Colors::Black)); + } + if (object == btnRandom) { + valueTime = static_cast(rand() % 17); + valueBar = static_cast(rand() % 17); + valueBG = static_cast(rand() % 17); + if (valueTime == valueBG) { + valueBG = GetNext(valueBG); + } + if (valueBar == Controllers::Settings::Colors::Black) { + valueBar = GetPrevious(valueBar); + } + if (valueBar == Controllers::Settings::Colors::White) { + needle_colors[0] = LV_COLOR_BLACK; + } else { + needle_colors[0] = LV_COLOR_WHITE; + } + settingsController.SetPTSColorTime(static_cast(valueTime)); + lv_obj_set_style_local_text_color(timeDD1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); + lv_obj_set_style_local_text_color(timeDD2, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); + lv_obj_set_style_local_text_color(timeAMPM, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); + settingsController.SetPTSColorBar(static_cast(valueBar)); + lv_obj_set_style_local_bg_color(sidebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(valueBar)); + settingsController.SetPTSColorBG(static_cast(valueBG)); + lv_obj_set_style_local_bg_color(timebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(valueBG)); + } + if (object == btnClose) { + CloseMenu(); + } + if (object == btnSet) { + lv_obj_set_hidden(btnSet, true); + lv_obj_set_hidden(btnNextTime, false); + lv_obj_set_hidden(btnPrevTime, false); + lv_obj_set_hidden(btnNextBar, false); + lv_obj_set_hidden(btnPrevBar, false); + lv_obj_set_hidden(btnNextBG, false); + lv_obj_set_hidden(btnPrevBG, false); + lv_obj_set_hidden(btnReset, false); + lv_obj_set_hidden(btnRandom, false); + lv_obj_set_hidden(btnClose, false); + } + } +} + +Pinetime::Controllers::Settings::Colors PineTimeStyle::GetNext(Pinetime::Controllers::Settings::Colors color) { + auto colorAsInt = static_cast(color); + Pinetime::Controllers::Settings::Colors nextColor; + if (colorAsInt < 16) { + nextColor = static_cast(colorAsInt + 1); + } else { + nextColor = static_cast(0); + } + return nextColor; +} + +Pinetime::Controllers::Settings::Colors PineTimeStyle::GetPrevious(Pinetime::Controllers::Settings::Colors color) { + auto colorAsInt = static_cast(color); + Pinetime::Controllers::Settings::Colors prevColor; + + if (colorAsInt > 0) { + prevColor = static_cast(colorAsInt - 1); + } else { + prevColor = static_cast(16); + } + return prevColor; } diff --git a/src/displayapp/screens/PineTimeStyle.h b/src/displayapp/screens/PineTimeStyle.h index ba473806..df8b7d5a 100644 --- a/src/displayapp/screens/PineTimeStyle.h +++ b/src/displayapp/screens/PineTimeStyle.h @@ -4,8 +4,8 @@ #include #include #include -#include "Screen.h" -#include "ScreenList.h" +#include "displayapp/screens/Screen.h" +#include "displayapp/Colors.h" #include "components/datetime/DateTimeController.h" namespace Pinetime { @@ -15,6 +15,7 @@ namespace Pinetime { class Ble; class NotificationManager; class HeartRateController; + class MotionController; } namespace Applications { @@ -30,8 +31,13 @@ namespace Pinetime { Controllers::MotionController& motionController); ~PineTimeStyle() override; + bool OnTouchEvent(TouchEvents event) override; + bool OnButtonPushed() override; + void Refresh() override; + void UpdateSelected(lv_obj_t *object, lv_event_t event); + private: char displayedChar[5]; @@ -39,6 +45,7 @@ namespace Pinetime { Pinetime::Controllers::DateTime::Months currentMonth = Pinetime::Controllers::DateTime::Months::Unknown; Pinetime::Controllers::DateTime::Days currentDayOfWeek = Pinetime::Controllers::DateTime::Days::Unknown; uint8_t currentDay = 0; + uint32_t savedTick = 0; DirtyValue batteryPercentRemaining {}; DirtyValue isCharging {}; @@ -48,6 +55,18 @@ namespace Pinetime { DirtyValue stepCount {}; DirtyValue notificationState {}; + static Pinetime::Controllers::Settings::Colors GetNext(Controllers::Settings::Colors color); + static Pinetime::Controllers::Settings::Colors GetPrevious(Controllers::Settings::Colors color); + + lv_obj_t* btnNextTime; + lv_obj_t* btnPrevTime; + lv_obj_t* btnNextBar; + lv_obj_t* btnPrevBar; + lv_obj_t* btnNextBG; + lv_obj_t* btnPrevBG; + lv_obj_t* btnReset; + lv_obj_t* btnRandom; + lv_obj_t* btnClose; lv_obj_t* timebar; lv_obj_t* sidebar; lv_obj_t* timeDD1; @@ -67,6 +86,8 @@ namespace Pinetime { lv_obj_t* calendarCrossBar2; lv_obj_t* notificationIcon; lv_obj_t* stepGauge; + lv_obj_t* btnSet; + lv_obj_t* lbl_btnSet; lv_color_t needle_colors[1]; Controllers::DateTime& dateTimeController; @@ -77,6 +98,8 @@ namespace Pinetime { Controllers::MotionController& motionController; void SetBatteryIcon(); + void CloseMenu(); + void AlignIcons(); lv_task_t* taskRefresh; }; diff --git a/src/displayapp/screens/Screen.cpp b/src/displayapp/screens/Screen.cpp index 6ae5b7bb..bc4cc438 100644 --- a/src/displayapp/screens/Screen.cpp +++ b/src/displayapp/screens/Screen.cpp @@ -1,4 +1,4 @@ -#include "Screen.h" +#include "displayapp/screens/Screen.h" using namespace Pinetime::Applications::Screens; void Screen::RefreshTaskCallback(lv_task_t* task) { diff --git a/src/displayapp/screens/Screen.h b/src/displayapp/screens/Screen.h index ce5741b2..04bb152c 100644 --- a/src/displayapp/screens/Screen.h +++ b/src/displayapp/screens/Screen.h @@ -1,7 +1,7 @@ #pragma once #include -#include "../TouchEvents.h" +#include "displayapp/TouchEvents.h" #include namespace Pinetime { diff --git a/src/displayapp/screens/ScreenList.h b/src/displayapp/screens/ScreenList.h index a9d747aa..e316e360 100644 --- a/src/displayapp/screens/ScreenList.h +++ b/src/displayapp/screens/ScreenList.h @@ -3,8 +3,8 @@ #include #include #include -#include "Screen.h" -#include "../DisplayApp.h" +#include "displayapp/screens/Screen.h" +#include "displayapp/DisplayApp.h" namespace Pinetime { namespace Applications { diff --git a/src/displayapp/screens/Steps.cpp b/src/displayapp/screens/Steps.cpp index c41163ab..3e7f8201 100644 --- a/src/displayapp/screens/Steps.cpp +++ b/src/displayapp/screens/Steps.cpp @@ -1,10 +1,15 @@ -#include "Steps.h" +#include "displayapp/screens/Steps.h" #include -#include "../DisplayApp.h" -#include "Symbols.h" +#include "displayapp/DisplayApp.h" +#include "displayapp/screens/Symbols.h" using namespace Pinetime::Applications::Screens; +static void lap_event_handler(lv_obj_t* obj, lv_event_t event) { + auto* steps = static_cast(obj->user_data); + steps->lapBtnEventHandler(event); +} + Steps::Steps(Pinetime::Applications::DisplayApp* app, Controllers::MotionController& motionController, Controllers::Settings& settingsController) @@ -17,11 +22,12 @@ Steps::Steps(Pinetime::Applications::DisplayApp* app, lv_obj_set_style_local_radius(stepsArc, LV_ARC_PART_BG, LV_STATE_DEFAULT, 0); lv_obj_set_style_local_line_color(stepsArc, LV_ARC_PART_INDIC, LV_STATE_DEFAULT, lv_color_hex(0x0000FF)); lv_arc_set_end_angle(stepsArc, 200); - lv_obj_set_size(stepsArc, 220, 220); + lv_obj_set_size(stepsArc, 240, 240); lv_arc_set_range(stepsArc, 0, 500); lv_obj_align(stepsArc, nullptr, LV_ALIGN_CENTER, 0, 0); stepsCount = motionController.NbSteps(); + currentTripSteps = stepsCount - motionController.GetTripSteps(); lv_arc_set_value(stepsArc, int16_t(500 * stepsCount / settingsController.GetStepsGoal())); @@ -29,18 +35,18 @@ Steps::Steps(Pinetime::Applications::DisplayApp* app, lv_obj_set_style_local_text_color(lSteps, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x00FF00)); lv_obj_set_style_local_text_font(lSteps, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, &jetbrains_mono_42); lv_label_set_text_fmt(lSteps, "%li", stepsCount); - lv_obj_align(lSteps, nullptr, LV_ALIGN_CENTER, 0, -20); + lv_obj_align(lSteps, nullptr, LV_ALIGN_CENTER, 0, -40); lv_obj_t* lstepsL = lv_label_create(lv_scr_act(), nullptr); lv_obj_set_style_local_text_color(lstepsL, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x111111)); lv_label_set_text_static(lstepsL, "Steps"); - lv_obj_align(lstepsL, lSteps, LV_ALIGN_OUT_BOTTOM_MID, 0, 10); + lv_obj_align(lstepsL, lSteps, LV_ALIGN_OUT_BOTTOM_MID, 0, 5); lv_obj_t* lstepsGoal = lv_label_create(lv_scr_act(), nullptr); lv_obj_set_style_local_text_color(lstepsGoal, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_CYAN); - lv_label_set_text_fmt(lstepsGoal, "Goal\n%lu", settingsController.GetStepsGoal()); + lv_label_set_text_fmt(lstepsGoal, "Goal: %5lu", settingsController.GetStepsGoal()); lv_label_set_align(lstepsGoal, LV_LABEL_ALIGN_CENTER); - lv_obj_align(lstepsGoal, lSteps, LV_ALIGN_OUT_BOTTOM_MID, 0, 60); + lv_obj_align(lstepsGoal, lSteps, LV_ALIGN_OUT_BOTTOM_MID, 0, 40); lv_obj_t* backgroundLabel = lv_label_create(lv_scr_act(), nullptr); lv_label_set_long_mode(backgroundLabel, LV_LABEL_LONG_CROP); @@ -48,6 +54,22 @@ Steps::Steps(Pinetime::Applications::DisplayApp* app, lv_obj_set_pos(backgroundLabel, 0, 0); lv_label_set_text_static(backgroundLabel, ""); + resetBtn = lv_btn_create(lv_scr_act(), nullptr); + resetBtn->user_data = this; + lv_obj_set_event_cb(resetBtn, lap_event_handler); + lv_obj_set_height(resetBtn, 50); + lv_obj_set_width(resetBtn, 115); + lv_obj_align(resetBtn, lv_scr_act(), LV_ALIGN_IN_BOTTOM_MID, 0, 0); + resetButtonLabel = lv_label_create(resetBtn, nullptr); + lv_label_set_text(resetButtonLabel, "Reset"); + + currentTripSteps = motionController.GetTripSteps(); + + tripLabel = lv_label_create(lv_scr_act(), nullptr); + lv_obj_set_style_local_text_color(tripLabel, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_YELLOW); + lv_label_set_text_fmt(tripLabel, "Trip: %5li", currentTripSteps); + lv_obj_align(tripLabel, lstepsGoal, LV_ALIGN_IN_LEFT_MID, 0, 20); + taskRefresh = lv_task_create(RefreshTaskCallback, 100, LV_TASK_PRIO_MID, this); } @@ -58,9 +80,24 @@ Steps::~Steps() { void Steps::Refresh() { stepsCount = motionController.NbSteps(); + currentTripSteps = motionController.GetTripSteps(); lv_label_set_text_fmt(lSteps, "%li", stepsCount); - lv_obj_align(lSteps, nullptr, LV_ALIGN_CENTER, 0, -20); + lv_obj_align(lSteps, nullptr, LV_ALIGN_CENTER, 0, -40); + if (currentTripSteps < 100000) { + lv_label_set_text_fmt(tripLabel, "Trip: %5li", currentTripSteps); + } else { + lv_label_set_text_fmt(tripLabel, "Trip: 99999+"); + } lv_arc_set_value(stepsArc, int16_t(500 * stepsCount / settingsController.GetStepsGoal())); } + +void Steps::lapBtnEventHandler(lv_event_t event) { + if (event != LV_EVENT_CLICKED) { + return; + } + stepsCount = motionController.NbSteps(); + motionController.ResetTrip(); + Refresh(); +} diff --git a/src/displayapp/screens/Steps.h b/src/displayapp/screens/Steps.h index d7cf31e1..f109e0f2 100644 --- a/src/displayapp/screens/Steps.h +++ b/src/displayapp/screens/Steps.h @@ -2,7 +2,7 @@ #include #include -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include namespace Pinetime { @@ -20,14 +20,20 @@ namespace Pinetime { ~Steps() override; void Refresh() override; + void lapBtnEventHandler(lv_event_t event); private: Controllers::MotionController& motionController; Controllers::Settings& settingsController; + uint32_t currentTripSteps = 0; + lv_obj_t* lSteps; lv_obj_t* lStepsIcon; lv_obj_t* stepsArc; + lv_obj_t* resetBtn; + lv_obj_t* resetButtonLabel; + lv_obj_t* tripLabel; uint32_t stepsCount; diff --git a/src/displayapp/screens/StopWatch.cpp b/src/displayapp/screens/StopWatch.cpp index 9b27a89d..a260d293 100644 --- a/src/displayapp/screens/StopWatch.cpp +++ b/src/displayapp/screens/StopWatch.cpp @@ -1,8 +1,8 @@ #include "StopWatch.h" -#include "Screen.h" -#include "Symbols.h" -#include "lvgl/lvgl.h" +#include "displayapp/screens/Screen.h" +#include "displayapp/screens/Symbols.h" +#include #include "projdefs.h" #include "FreeRTOSConfig.h" #include "task.h" diff --git a/src/displayapp/screens/StopWatch.h b/src/displayapp/screens/StopWatch.h index 25634e92..0720a586 100644 --- a/src/displayapp/screens/StopWatch.h +++ b/src/displayapp/screens/StopWatch.h @@ -1,8 +1,8 @@ #pragma once -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include "components/datetime/DateTimeController.h" -#include "../LittleVgl.h" +#include "displayapp/LittleVgl.h" #include "FreeRTOS.h" #include "portmacro_cmsis.h" diff --git a/src/displayapp/screens/Styles.cpp b/src/displayapp/screens/Styles.cpp new file mode 100644 index 00000000..7f43fb99 --- /dev/null +++ b/src/displayapp/screens/Styles.cpp @@ -0,0 +1,8 @@ +#include "Styles.h" + +void Pinetime::Applications::Screens::SetRadioButtonStyle(lv_obj_t* checkbox) { + lv_obj_set_style_local_radius(checkbox, LV_CHECKBOX_PART_BULLET, LV_STATE_DEFAULT, LV_RADIUS_CIRCLE); + lv_obj_set_style_local_border_width(checkbox, LV_CHECKBOX_PART_BULLET, LV_STATE_CHECKED, 9); + lv_obj_set_style_local_border_color(checkbox, LV_CHECKBOX_PART_BULLET, LV_STATE_CHECKED, LV_COLOR_GREEN); + lv_obj_set_style_local_bg_color(checkbox, LV_CHECKBOX_PART_BULLET, LV_STATE_CHECKED, LV_COLOR_WHITE); +} diff --git a/src/displayapp/screens/Styles.h b/src/displayapp/screens/Styles.h new file mode 100644 index 00000000..a5fbb9f6 --- /dev/null +++ b/src/displayapp/screens/Styles.h @@ -0,0 +1,9 @@ +#include + +namespace Pinetime { + namespace Applications { + namespace Screens { + void SetRadioButtonStyle(lv_obj_t* checkbox); + } + } +} diff --git a/src/displayapp/screens/SystemInfo.cpp b/src/displayapp/screens/SystemInfo.cpp index 343b72bf..e0138f86 100644 --- a/src/displayapp/screens/SystemInfo.cpp +++ b/src/displayapp/screens/SystemInfo.cpp @@ -1,7 +1,9 @@ -#include "SystemInfo.h" +#include +#include +#include "displayapp/screens/SystemInfo.h" #include -#include "../DisplayApp.h" -#include "Label.h" +#include "displayapp/DisplayApp.h" +#include "displayapp/screens/Label.h" #include "Version.h" #include "BootloaderVersion.h" #include "components/battery/BatteryController.h" @@ -41,8 +43,8 @@ SystemInfo::SystemInfo(Pinetime::Applications::DisplayApp* app, brightnessController {brightnessController}, bleController {bleController}, watchdog {watchdog}, - motionController{motionController}, - touchPanel{touchPanel}, + motionController {motionController}, + touchPanel {touchPanel}, screens {app, 0, {[this]() -> std::unique_ptr { @@ -182,9 +184,7 @@ std::unique_ptr SystemInfo::CreateScreen3() { " #444444 used# %d (%d%%)\n" " #444444 max used# %lu\n" " #444444 frag# %d%%\n" - " #444444 free# %d" - "\n" - "#444444 Steps# %i", + " #444444 free# %d", bleAddr[5], bleAddr[4], bleAddr[3], @@ -195,8 +195,7 @@ std::unique_ptr SystemInfo::CreateScreen3() { mon.used_pct, mon.max_used, mon.frag_pct, - static_cast(mon.free_biggest_size), - 0); + static_cast(mon.free_biggest_size)); lv_obj_align(label, lv_scr_act(), LV_ALIGN_CENTER, 0, 0); return std::make_unique(2, 5, app, label); } @@ -209,7 +208,7 @@ std::unique_ptr SystemInfo::CreateScreen4() { static constexpr uint8_t maxTaskCount = 9; TaskStatus_t tasksStatus[maxTaskCount]; - lv_obj_t* infoTask = lv_table_create(lv_scr_act(), NULL); + lv_obj_t* infoTask = lv_table_create(lv_scr_act(), nullptr); lv_table_set_col_cnt(infoTask, 4); lv_table_set_row_cnt(infoTask, maxTaskCount + 1); lv_obj_set_style_local_pad_all(infoTask, LV_TABLE_PART_CELL1, LV_STATE_DEFAULT, 0); @@ -227,35 +226,37 @@ std::unique_ptr SystemInfo::CreateScreen4() { auto nb = uxTaskGetSystemState(tasksStatus, maxTaskCount, nullptr); std::sort(tasksStatus, tasksStatus + nb, sortById); for (uint8_t i = 0; i < nb && i < maxTaskCount; i++) { + char buffer[7] = {0}; - lv_table_set_cell_value(infoTask, i + 1, 0, std::to_string(tasksStatus[i].xTaskNumber).c_str()); - char state[2] = {0}; + sprintf(buffer, "%lu", tasksStatus[i].xTaskNumber); + lv_table_set_cell_value(infoTask, i + 1, 0, buffer); switch (tasksStatus[i].eCurrentState) { case eReady: case eRunning: - state[0] = 'R'; + buffer[0] = 'R'; break; case eBlocked: - state[0] = 'B'; + buffer[0] = 'B'; break; case eSuspended: - state[0] = 'S'; + buffer[0] = 'S'; break; case eDeleted: - state[0] = 'D'; + buffer[0] = 'D'; break; default: - state[0] = 'I'; // Invalid + buffer[0] = 'I'; // Invalid break; } - lv_table_set_cell_value(infoTask, i + 1, 1, state); + buffer[1] = '\0'; + lv_table_set_cell_value(infoTask, i + 1, 1, buffer); lv_table_set_cell_value(infoTask, i + 1, 2, tasksStatus[i].pcTaskName); if (tasksStatus[i].usStackHighWaterMark < 20) { - std::string str1 = std::to_string(tasksStatus[i].usStackHighWaterMark) + " low"; - lv_table_set_cell_value(infoTask, i + 1, 3, str1.c_str()); + sprintf(buffer, "%d low", tasksStatus[i].usStackHighWaterMark); } else { - lv_table_set_cell_value(infoTask, i + 1, 3, std::to_string(tasksStatus[i].usStackHighWaterMark).c_str()); + sprintf(buffer, "%d", tasksStatus[i].usStackHighWaterMark); } + lv_table_set_cell_value(infoTask, i + 1, 3, buffer); } return std::make_unique(3, 5, app, infoTask); } @@ -275,4 +276,4 @@ std::unique_ptr SystemInfo::CreateScreen5() { lv_label_set_align(label, LV_LABEL_ALIGN_CENTER); lv_obj_align(label, lv_scr_act(), LV_ALIGN_CENTER, 0, 0); return std::make_unique(4, 5, app, label); -} +} \ No newline at end of file diff --git a/src/displayapp/screens/SystemInfo.h b/src/displayapp/screens/SystemInfo.h index bfcc3aa4..a382ed8f 100644 --- a/src/displayapp/screens/SystemInfo.h +++ b/src/displayapp/screens/SystemInfo.h @@ -1,8 +1,8 @@ #pragma once #include -#include "Screen.h" -#include "ScreenList.h" +#include "displayapp/screens/Screen.h" +#include "displayapp/screens/ScreenList.h" namespace Pinetime { namespace Controllers { diff --git a/src/displayapp/screens/Tile.cpp b/src/displayapp/screens/Tile.cpp index 1d4f0d0e..ba764a2e 100644 --- a/src/displayapp/screens/Tile.cpp +++ b/src/displayapp/screens/Tile.cpp @@ -1,6 +1,6 @@ -#include "Tile.h" -#include "../DisplayApp.h" -#include "BatteryIcon.h" +#include "displayapp/screens/Tile.h" +#include "displayapp/DisplayApp.h" +#include "displayapp/screens/BatteryIcon.h" using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/Tile.h b/src/displayapp/screens/Tile.h index 83d3fdf5..4869fef9 100644 --- a/src/displayapp/screens/Tile.h +++ b/src/displayapp/screens/Tile.h @@ -3,8 +3,8 @@ #include #include #include -#include "Screen.h" -#include "../Apps.h" +#include "displayapp/screens/Screen.h" +#include "displayapp/Apps.h" #include "components/datetime/DateTimeController.h" #include "components/settings/Settings.h" #include "components/datetime/DateTimeController.h" diff --git a/src/displayapp/screens/Timer.cpp b/src/displayapp/screens/Timer.cpp index ff3099d5..a5e40195 100644 --- a/src/displayapp/screens/Timer.cpp +++ b/src/displayapp/screens/Timer.cpp @@ -1,8 +1,8 @@ -#include "Timer.h" +#include "displayapp/screens/Timer.h" -#include "Screen.h" -#include "Symbols.h" -#include "lvgl/lvgl.h" +#include "displayapp/screens/Screen.h" +#include "displayapp/screens/Symbols.h" +#include using namespace Pinetime::Applications::Screens; diff --git a/src/displayapp/screens/Timer.h b/src/displayapp/screens/Timer.h index d0fc8ed1..23c87345 100644 --- a/src/displayapp/screens/Timer.h +++ b/src/displayapp/screens/Timer.h @@ -1,9 +1,9 @@ #pragma once -#include "Screen.h" +#include "displayapp/screens/Screen.h" #include "components/datetime/DateTimeController.h" #include "systemtask/SystemTask.h" -#include "../LittleVgl.h" +#include "displayapp/LittleVgl.h" #include "components/timer/TimerController.h" diff --git a/src/displayapp/screens/Twos.cpp b/src/displayapp/screens/Twos.cpp index 4201d501..b15332f1 100644 --- a/src/displayapp/screens/Twos.cpp +++ b/src/displayapp/screens/Twos.cpp @@ -1,10 +1,10 @@ -#include "Twos.h" -#include -#include -#include +#include "displayapp/screens/Twos.h" #include -#include +#include +#include +#include #include +#include using namespace Pinetime::Applications::Screens; @@ -129,7 +129,7 @@ bool Twos::placeNewTile() { return true; } -bool Twos::tryMerge(Tile grid[][4], int& newRow, int& newCol, int oldRow, int oldCol) { +bool Twos::tryMerge(TwosTile grid[][4], int& newRow, int& newCol, int oldRow, int oldCol) { if ((grid[newRow][newCol].value == grid[oldRow][oldCol].value)) { if ((newCol != oldCol) || (newRow != oldRow)) { if (!grid[newRow][newCol].merged) { @@ -146,7 +146,7 @@ bool Twos::tryMerge(Tile grid[][4], int& newRow, int& newCol, int oldRow, int ol return false; } -bool Twos::tryMove(Tile grid[][4], int newRow, int newCol, int oldRow, int oldCol) { +bool Twos::tryMove(TwosTile grid[][4], int newRow, int newCol, int oldRow, int oldCol) { if (((newCol >= 0) && (newCol != oldCol)) || ((newRow >= 0) && (newRow != oldRow))) { grid[newRow][newCol].value = grid[oldRow][oldCol].value; grid[oldRow][oldCol].value = 0; @@ -261,11 +261,13 @@ bool Twos::OnTouchEvent(Pinetime::Applications::TouchEvents event) { return false; } -void Twos::updateGridDisplay(Tile grid[][4]) { +void Twos::updateGridDisplay(TwosTile grid[][4]) { for (int row = 0; row < 4; row++) { for (int col = 0; col < 4; col++) { if (grid[row][col].value) { - lv_table_set_cell_value(gridDisplay, row, col, (std::to_string(grid[row][col].value)).c_str()); + char buffer[7]; + sprintf(buffer, "%d", grid[row][col].value); + lv_table_set_cell_value(gridDisplay, row, col, buffer); } else { lv_table_set_cell_value(gridDisplay, row, col, ""); } diff --git a/src/displayapp/screens/Twos.h b/src/displayapp/screens/Twos.h index 6d85cff6..5a0c4350 100644 --- a/src/displayapp/screens/Twos.h +++ b/src/displayapp/screens/Twos.h @@ -1,11 +1,11 @@ #pragma once #include -#include "Screen.h" +#include "displayapp/screens/Screen.h" namespace Pinetime { namespace Applications { - struct Tile { + struct TwosTile { bool merged = false; unsigned int value = 0; }; @@ -26,11 +26,11 @@ namespace Pinetime { lv_obj_t* scoreText; lv_obj_t* gridDisplay; - Tile grid[4][4]; + TwosTile grid[4][4]; unsigned int score = 0; - void updateGridDisplay(Tile grid[][4]); - bool tryMerge(Tile grid[][4], int& newRow, int& newCol, int oldRow, int oldCol); - bool tryMove(Tile grid[][4], int newRow, int newCol, int oldRow, int oldCol); + void updateGridDisplay(TwosTile grid[][4]); + bool tryMerge(TwosTile grid[][4], int& newRow, int& newCol, int oldRow, int oldCol); + bool tryMove(TwosTile grid[][4], int newRow, int newCol, int oldRow, int oldCol); bool placeNewTile(); }; } diff --git a/src/displayapp/screens/WatchFaceAnalog.cpp b/src/displayapp/screens/WatchFaceAnalog.cpp index 53e7faf7..f027a744 100644 --- a/src/displayapp/screens/WatchFaceAnalog.cpp +++ b/src/displayapp/screens/WatchFaceAnalog.cpp @@ -1,9 +1,11 @@ -#include -#include "WatchFaceAnalog.h" -#include "BatteryIcon.h" -#include "BleIcon.h" -#include "Symbols.h" -#include "NotificationIcon.h" +#include "displayapp/screens/WatchFaceAnalog.h" +#include +#include +#include "displayapp/screens/BatteryIcon.h" +#include "displayapp/screens/BleIcon.h" +#include "displayapp/screens/Symbols.h" +#include "displayapp/screens/NotificationIcon.h" +#include "components/settings/Settings.h" LV_IMG_DECLARE(bg_clock); @@ -73,7 +75,7 @@ WatchFaceAnalog::WatchFaceAnalog(Pinetime::Applications::DisplayApp* app, notificationIcon = lv_label_create(lv_scr_act(), NULL); lv_obj_set_style_local_text_color(notificationIcon, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x00FF00)); lv_label_set_text(notificationIcon, NotificationIcon::GetIcon(false)); - lv_obj_align(notificationIcon, NULL, LV_ALIGN_IN_BOTTOM_LEFT, 0, 0); + lv_obj_align(notificationIcon, NULL, LV_ALIGN_IN_TOP_LEFT, 0, 0); // Date - Day / Week day diff --git a/src/displayapp/screens/WatchFaceAnalog.h b/src/displayapp/screens/WatchFaceAnalog.h index 001414a6..a18eb299 100644 --- a/src/displayapp/screens/WatchFaceAnalog.h +++ b/src/displayapp/screens/WatchFaceAnalog.h @@ -4,8 +4,7 @@ #include #include #include -#include "Screen.h" -#include "ScreenList.h" +#include "displayapp/screens/Screen.h" #include "components/datetime/DateTimeController.h" #include "components/battery/BatteryController.h" #include "components/ble/BleController.h" diff --git a/src/displayapp/screens/WatchFaceDigital.cpp b/src/displayapp/screens/WatchFaceDigital.cpp index 2ecab609..4d9eaf37 100644 --- a/src/displayapp/screens/WatchFaceDigital.cpp +++ b/src/displayapp/screens/WatchFaceDigital.cpp @@ -1,17 +1,18 @@ -#include "WatchFaceDigital.h" +#include "displayapp/screens/WatchFaceDigital.h" #include #include #include -#include "BatteryIcon.h" -#include "BleIcon.h" -#include "NotificationIcon.h" -#include "Symbols.h" +#include "displayapp/screens/BatteryIcon.h" +#include "displayapp/screens/BleIcon.h" +#include "displayapp/screens/NotificationIcon.h" +#include "displayapp/screens/Symbols.h" #include "components/battery/BatteryController.h" #include "components/ble/BleController.h" #include "components/ble/NotificationManager.h" #include "components/heartrate/HeartRateController.h" #include "components/motion/MotionController.h" +#include "components/settings/Settings.h" using namespace Pinetime::Applications::Screens; WatchFaceDigital::WatchFaceDigital(DisplayApp* app, @@ -43,7 +44,7 @@ WatchFaceDigital::WatchFaceDigital(DisplayApp* app, lv_obj_align(batteryPlug, batteryIcon, LV_ALIGN_OUT_LEFT_MID, -5, 0); bleIcon = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_text_color(bleIcon, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x0000FF)); + lv_obj_set_style_local_text_color(bleIcon, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x0082FC)); lv_label_set_text(bleIcon, Symbols::bluetooth); lv_obj_align(bleIcon, batteryPlug, LV_ALIGN_OUT_LEFT_MID, -5, 0); diff --git a/src/displayapp/screens/WatchFaceDigital.h b/src/displayapp/screens/WatchFaceDigital.h index e27545f3..627154c8 100644 --- a/src/displayapp/screens/WatchFaceDigital.h +++ b/src/displayapp/screens/WatchFaceDigital.h @@ -4,8 +4,7 @@ #include #include #include -#include "Screen.h" -#include "ScreenList.h" +#include "displayapp/screens/Screen.h" #include "components/datetime/DateTimeController.h" namespace Pinetime { diff --git a/src/displayapp/screens/Weather.cpp b/src/displayapp/screens/Weather.cpp new file mode 100644 index 00000000..1d0a83bd --- /dev/null +++ b/src/displayapp/screens/Weather.cpp @@ -0,0 +1,222 @@ +/* Copyright (C) 2021 Avamander + + This file is part of InfiniTime. + + InfiniTime is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + InfiniTime is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +#include "Weather.h" +#include +#include +#include "Label.h" +#include "components/battery/BatteryController.h" +#include "components/ble/BleController.h" +#include "components/ble/weather/WeatherData.h" + +using namespace Pinetime::Applications::Screens; + +Weather::Weather(Pinetime::Applications::DisplayApp* app, Pinetime::Controllers::WeatherService& weather) + : Screen(app), + dateTimeController {dateTimeController}, + weatherService(weather), + screens {app, + 0, + {[this]() -> std::unique_ptr { + return CreateScreenTemperature(); + }, + [this]() -> std::unique_ptr { + return CreateScreenAir(); + }, + [this]() -> std::unique_ptr { + return CreateScreenClouds(); + }, + [this]() -> std::unique_ptr { + return CreateScreenPrecipitation(); + }, + [this]() -> std::unique_ptr { + return CreateScreenHumidity(); + }}, + Screens::ScreenListModes::UpDown} { +} + +Weather::~Weather() { + lv_obj_clean(lv_scr_act()); +} + +void Weather::Refresh() { + if (running) { + // screens.Refresh(); + } +} + +bool Weather::OnButtonPushed() { + running = false; + return true; +} + +bool Weather::OnTouchEvent(Pinetime::Applications::TouchEvents event) { + return screens.OnTouchEvent(event); +} + +std::unique_ptr Weather::CreateScreenTemperature() { + lv_obj_t* label = lv_label_create(lv_scr_act(), nullptr); + lv_label_set_recolor(label, true); + std::unique_ptr& current = weatherService.GetCurrentTemperature(); + if (current->timestamp == 0) { + // Do not use the data, it's invalid + lv_label_set_text_fmt(label, + "#FFFF00 Temperature#\n\n" + "#444444 %d#°C \n\n" + "#444444 %d#\n\n" + "%d\n" + "%d\n", + 0, + 0, + 0, + 0); + } else { + lv_label_set_text_fmt(label, + "#FFFF00 Temperature#\n\n" + "#444444 %d#°C \n\n" + "#444444 %hd#\n\n" + "%llu\n" + "%lu\n", + current->temperature / 100, + current->dewPoint, + current->timestamp, + current->expires); + } + lv_label_set_align(label, LV_LABEL_ALIGN_CENTER); + lv_obj_align(label, lv_scr_act(), LV_ALIGN_CENTER, 0, 0); + return std::unique_ptr(new Screens::Label(0, 5, app, label)); +} + +std::unique_ptr Weather::CreateScreenAir() { + lv_obj_t* label = lv_label_create(lv_scr_act(), nullptr); + lv_label_set_recolor(label, true); + std::unique_ptr& current = weatherService.GetCurrentQuality(); + if (current->timestamp == 0) { + // Do not use the data, it's invalid + lv_label_set_text_fmt(label, + "#FFFF00 Air quality#\n\n" + "#444444 %s#\n" + "#444444 %d#\n\n" + "%d\n" + "%d\n", + "", + 0, + 0, + 0); + } else { + lv_label_set_text_fmt(label, + "#FFFF00 Air quality#\n\n" + "#444444 %s#\n" + "#444444 %lu#\n\n" + "%llu\n" + "%lu\n", + current->polluter.c_str(), + (current->amount / 100), + current->timestamp, + current->expires); + } + lv_label_set_align(label, LV_LABEL_ALIGN_CENTER); + lv_obj_align(label, lv_scr_act(), LV_ALIGN_CENTER, 0, 0); + return std::unique_ptr(new Screens::Label(0, 5, app, label)); +} + +std::unique_ptr Weather::CreateScreenClouds() { + lv_obj_t* label = lv_label_create(lv_scr_act(), nullptr); + lv_label_set_recolor(label, true); + std::unique_ptr& current = weatherService.GetCurrentClouds(); + if (current->timestamp == 0) { + // Do not use the data, it's invalid + lv_label_set_text_fmt(label, + "#FFFF00 Clouds#\n\n" + "#444444 %d%%#\n\n" + "%d\n" + "%d\n", + 0, + 0, + 0); + } else { + lv_label_set_text_fmt(label, + "#FFFF00 Clouds#\n\n" + "#444444 %hhu%%#\n\n" + "%llu\n" + "%lu\n", + current->amount, + current->timestamp, + current->expires); + } + lv_label_set_align(label, LV_LABEL_ALIGN_CENTER); + lv_obj_align(label, lv_scr_act(), LV_ALIGN_CENTER, 0, 0); + return std::unique_ptr(new Screens::Label(0, 5, app, label)); +} + +std::unique_ptr Weather::CreateScreenPrecipitation() { + lv_obj_t* label = lv_label_create(lv_scr_act(), nullptr); + lv_label_set_recolor(label, true); + std::unique_ptr& current = weatherService.GetCurrentPrecipitation(); + if (current->timestamp == 0) { + // Do not use the data, it's invalid + lv_label_set_text_fmt(label, + "#FFFF00 Precipitation#\n\n" + "#444444 %d%%#\n\n" + "%d\n" + "%d\n", + 0, + 0, + 0); + } else { + lv_label_set_text_fmt(label, + "#FFFF00 Precipitation#\n\n" + "#444444 %hhu%%#\n\n" + "%llu\n" + "%lu\n", + current->amount, + current->timestamp, + current->expires); + } + lv_label_set_align(label, LV_LABEL_ALIGN_CENTER); + lv_obj_align(label, lv_scr_act(), LV_ALIGN_CENTER, 0, 0); + return std::unique_ptr(new Screens::Label(0, 5, app, label)); +} + +std::unique_ptr Weather::CreateScreenHumidity() { + lv_obj_t* label = lv_label_create(lv_scr_act(), nullptr); + lv_label_set_recolor(label, true); + std::unique_ptr& current = weatherService.GetCurrentHumidity(); + if (current->timestamp == 0) { + // Do not use the data, it's invalid + lv_label_set_text_fmt(label, + "#FFFF00 Humidity#\n\n" + "#444444 %d%%#\n\n" + "%d\n" + "%d\n", + 0, + 0, + 0); + } else { + lv_label_set_text_fmt(label, + "#FFFF00 Humidity#\n\n" + "#444444 %hhu%%#\n\n" + "%llu\n" + "%lu\n", + current->humidity, + current->timestamp, + current->expires); + } + lv_label_set_align(label, LV_LABEL_ALIGN_CENTER); + lv_obj_align(label, lv_scr_act(), LV_ALIGN_CENTER, 0, 0); + return std::unique_ptr(new Screens::Label(0, 5, app, label)); +} diff --git a/src/displayapp/screens/Weather.h b/src/displayapp/screens/Weather.h new file mode 100644 index 00000000..34f95fce --- /dev/null +++ b/src/displayapp/screens/Weather.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include "Screen.h" +#include "ScreenList.h" + +namespace Pinetime { + namespace Applications { + class DisplayApp; + + namespace Screens { + class Weather : public Screen { + public: + explicit Weather(DisplayApp* app, Pinetime::Controllers::WeatherService& weather); + + ~Weather() override; + + void Refresh() override; + + bool OnButtonPushed() override; + + bool OnTouchEvent(TouchEvents event) override; + + private: + bool running = true; + + Pinetime::Controllers::DateTime& dateTimeController; + Controllers::WeatherService& weatherService; + + ScreenList<5> screens; + + std::unique_ptr CreateScreenTemperature(); + + std::unique_ptr CreateScreenAir(); + + std::unique_ptr CreateScreenClouds(); + + std::unique_ptr CreateScreenPrecipitation(); + + std::unique_ptr CreateScreenHumidity(); + }; + } + } +} diff --git a/src/displayapp/screens/settings/QuickSettings.cpp b/src/displayapp/screens/settings/QuickSettings.cpp index dd626072..5d3a9834 100644 --- a/src/displayapp/screens/settings/QuickSettings.cpp +++ b/src/displayapp/screens/settings/QuickSettings.cpp @@ -1,4 +1,4 @@ -#include "QuickSettings.h" +#include "displayapp/screens/settings/QuickSettings.h" #include "displayapp/DisplayApp.h" #include "displayapp/screens/Symbols.h" #include "displayapp/screens/BatteryIcon.h" diff --git a/src/displayapp/screens/settings/QuickSettings.h b/src/displayapp/screens/settings/QuickSettings.h index c036fa5c..7913898d 100644 --- a/src/displayapp/screens/settings/QuickSettings.h +++ b/src/displayapp/screens/settings/QuickSettings.h @@ -1,8 +1,6 @@ #pragma once #include -#include -#include #include "displayapp/screens/Screen.h" #include #include "components/datetime/DateTimeController.h" diff --git a/src/displayapp/screens/settings/SettingDisplay.cpp b/src/displayapp/screens/settings/SettingDisplay.cpp index d8d6c767..9e972afc 100644 --- a/src/displayapp/screens/settings/SettingDisplay.cpp +++ b/src/displayapp/screens/settings/SettingDisplay.cpp @@ -1,7 +1,8 @@ -#include "SettingDisplay.h" +#include "displayapp/screens/settings/SettingDisplay.h" #include #include "displayapp/DisplayApp.h" #include "displayapp/Messages.h" +#include "displayapp/screens/Styles.h" #include "displayapp/screens/Screen.h" #include "displayapp/screens/Symbols.h" @@ -14,6 +15,8 @@ namespace { } } +constexpr std::array SettingDisplay::options; + SettingDisplay::SettingDisplay(Pinetime::Applications::DisplayApp* app, Pinetime::Controllers::Settings& settingsController) : Screen(app), settingsController {settingsController} { @@ -40,39 +43,19 @@ SettingDisplay::SettingDisplay(Pinetime::Applications::DisplayApp* app, Pinetime lv_label_set_align(icon, LV_LABEL_ALIGN_CENTER); lv_obj_align(icon, title, LV_ALIGN_OUT_LEFT_MID, -10, 0); - optionsTotal = 0; - cbOption[optionsTotal] = lv_checkbox_create(container1, nullptr); - lv_checkbox_set_text_static(cbOption[optionsTotal], " 5 seconds"); - cbOption[optionsTotal]->user_data = this; - lv_obj_set_event_cb(cbOption[optionsTotal], event_handler); - if (settingsController.GetScreenTimeOut() == 5000) { - lv_checkbox_set_checked(cbOption[optionsTotal], true); + char buffer[12]; + for (unsigned int i = 0; i < options.size(); i++) { + cbOption[i] = lv_checkbox_create(container1, nullptr); + sprintf(buffer, "%3d seconds", options[i] / 1000); + lv_checkbox_set_text(cbOption[i], buffer); + cbOption[i]->user_data = this; + lv_obj_set_event_cb(cbOption[i], event_handler); + SetRadioButtonStyle(cbOption[i]); + + if (settingsController.GetScreenTimeOut() == options[i]) { + lv_checkbox_set_checked(cbOption[i], true); + } } - optionsTotal++; - cbOption[optionsTotal] = lv_checkbox_create(container1, nullptr); - lv_checkbox_set_text_static(cbOption[optionsTotal], " 15 seconds"); - cbOption[optionsTotal]->user_data = this; - lv_obj_set_event_cb(cbOption[optionsTotal], event_handler); - if (settingsController.GetScreenTimeOut() == 15000) { - lv_checkbox_set_checked(cbOption[optionsTotal], true); - } - optionsTotal++; - cbOption[optionsTotal] = lv_checkbox_create(container1, nullptr); - lv_checkbox_set_text_static(cbOption[optionsTotal], " 20 seconds"); - cbOption[optionsTotal]->user_data = this; - lv_obj_set_event_cb(cbOption[optionsTotal], event_handler); - if (settingsController.GetScreenTimeOut() == 20000) { - lv_checkbox_set_checked(cbOption[optionsTotal], true); - } - optionsTotal++; - cbOption[optionsTotal] = lv_checkbox_create(container1, nullptr); - lv_checkbox_set_text_static(cbOption[optionsTotal], " 30 seconds"); - cbOption[optionsTotal]->user_data = this; - lv_obj_set_event_cb(cbOption[optionsTotal], event_handler); - if (settingsController.GetScreenTimeOut() == 30000) { - lv_checkbox_set_checked(cbOption[optionsTotal], true); - } - optionsTotal++; } SettingDisplay::~SettingDisplay() { @@ -82,25 +65,11 @@ SettingDisplay::~SettingDisplay() { void SettingDisplay::UpdateSelected(lv_obj_t* object, lv_event_t event) { if (event == LV_EVENT_CLICKED) { - for (int i = 0; i < optionsTotal; i++) { + for (unsigned int i = 0; i < options.size(); i++) { if (object == cbOption[i]) { lv_checkbox_set_checked(cbOption[i], true); - - if (i == 0) { - settingsController.SetScreenTimeOut(5000); - }; - if (i == 1) { - settingsController.SetScreenTimeOut(15000); - }; - if (i == 2) { - settingsController.SetScreenTimeOut(20000); - }; - if (i == 3) { - settingsController.SetScreenTimeOut(30000); - }; - + settingsController.SetScreenTimeOut(options[i]); app->PushMessage(Applications::Display::Messages::UpdateTimeOut); - } else { lv_checkbox_set_checked(cbOption[i], false); } diff --git a/src/displayapp/screens/settings/SettingDisplay.h b/src/displayapp/screens/settings/SettingDisplay.h index 51b23aca..dc56419d 100644 --- a/src/displayapp/screens/settings/SettingDisplay.h +++ b/src/displayapp/screens/settings/SettingDisplay.h @@ -1,7 +1,9 @@ #pragma once +#include #include #include + #include "components/settings/Settings.h" #include "displayapp/screens/Screen.h" @@ -18,9 +20,10 @@ namespace Pinetime { void UpdateSelected(lv_obj_t* object, lv_event_t event); private: + static constexpr std::array options = {5000, 15000, 20000, 30000}; + Controllers::Settings& settingsController; - uint8_t optionsTotal; - lv_obj_t* cbOption[4]; + lv_obj_t* cbOption[options.size()]; }; } } diff --git a/src/displayapp/screens/settings/SettingPineTimeStyle.cpp b/src/displayapp/screens/settings/SettingPineTimeStyle.cpp deleted file mode 100644 index c9af19b6..00000000 --- a/src/displayapp/screens/settings/SettingPineTimeStyle.cpp +++ /dev/null @@ -1,318 +0,0 @@ -#include "SettingPineTimeStyle.h" -#include -#include -#include "displayapp/DisplayApp.h" -#include "displayapp/screens/Symbols.h" - -using namespace Pinetime::Applications::Screens; - -namespace { - static void event_handler(lv_obj_t* obj, lv_event_t event) { - SettingPineTimeStyle* screen = static_cast(obj->user_data); - screen->UpdateSelected(obj, event); - } -} - -SettingPineTimeStyle::SettingPineTimeStyle(Pinetime::Applications::DisplayApp* app, Pinetime::Controllers::Settings& settingsController) - : Screen(app), settingsController {settingsController} { - timebar = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(timebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(settingsController.GetPTSColorBG())); - lv_obj_set_style_local_radius(timebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); - lv_obj_set_size(timebar, 200, 240); - lv_obj_align(timebar, lv_scr_act(), LV_ALIGN_IN_TOP_LEFT, 5, 0); - - // Display the time - - timeDD1 = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_text_font(timeDD1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, &open_sans_light); - lv_obj_set_style_local_text_color(timeDD1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(settingsController.GetPTSColorTime())); - lv_label_set_text(timeDD1, "12"); - lv_obj_align(timeDD1, timebar, LV_ALIGN_IN_TOP_MID, 5, 5); - - timeDD2 = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_text_font(timeDD2, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, &open_sans_light); - lv_obj_set_style_local_text_color(timeDD2, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(settingsController.GetPTSColorTime())); - lv_label_set_text(timeDD2, "34"); - lv_obj_align(timeDD2, timebar, LV_ALIGN_IN_BOTTOM_MID, 5, -5); - - timeAMPM = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_text_color(timeAMPM, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(settingsController.GetPTSColorTime())); - lv_obj_set_style_local_text_line_space(timeAMPM, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, -3); - lv_label_set_text(timeAMPM, "A\nM"); - lv_obj_align(timeAMPM, timebar, LV_ALIGN_IN_BOTTOM_LEFT, 2, -20); - - // Create a 40px wide bar down the right side of the screen - - sidebar = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(sidebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(settingsController.GetPTSColorBar())); - lv_obj_set_style_local_radius(sidebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); - lv_obj_set_size(sidebar, 40, 240); - lv_obj_align(sidebar, lv_scr_act(), LV_ALIGN_IN_TOP_RIGHT, 0, 0); - - // Display icons - - batteryIcon = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_text_color(batteryIcon, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); - lv_label_set_text(batteryIcon, Symbols::batteryFull); - lv_obj_align(batteryIcon, sidebar, LV_ALIGN_IN_TOP_MID, 0, 2); - - bleIcon = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_text_color(bleIcon, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); - lv_label_set_text(bleIcon, Symbols::bluetooth); - lv_obj_align(bleIcon, sidebar, LV_ALIGN_IN_TOP_MID, 0, 25); - - // Calendar icon - - calendarOuter = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(calendarOuter, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); - lv_obj_set_style_local_radius(calendarOuter, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); - lv_obj_set_size(calendarOuter, 34, 34); - lv_obj_align(calendarOuter, sidebar, LV_ALIGN_CENTER, 0, 0); - - calendarInner = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(calendarInner, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0xffffff)); - lv_obj_set_style_local_radius(calendarInner, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); - lv_obj_set_size(calendarInner, 27, 27); - lv_obj_align(calendarInner, calendarOuter, LV_ALIGN_CENTER, 0, 0); - - calendarBar1 = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(calendarBar1, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); - lv_obj_set_style_local_radius(calendarBar1, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); - lv_obj_set_size(calendarBar1, 3, 12); - lv_obj_align(calendarBar1, calendarOuter, LV_ALIGN_IN_TOP_MID, -6, -3); - - calendarBar2 = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(calendarBar2, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); - lv_obj_set_style_local_radius(calendarBar2, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); - lv_obj_set_size(calendarBar2, 3, 12); - lv_obj_align(calendarBar2, calendarOuter, LV_ALIGN_IN_TOP_MID, 6, -3); - - calendarCrossBar1 = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(calendarCrossBar1, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); - lv_obj_set_style_local_radius(calendarCrossBar1, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); - lv_obj_set_size(calendarCrossBar1, 8, 3); - lv_obj_align(calendarCrossBar1, calendarBar1, LV_ALIGN_IN_BOTTOM_MID, 0, 0); - - calendarCrossBar2 = lv_obj_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_bg_color(calendarCrossBar2, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); - lv_obj_set_style_local_radius(calendarCrossBar2, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, 0); - lv_obj_set_size(calendarCrossBar2, 8, 3); - lv_obj_align(calendarCrossBar2, calendarBar2, LV_ALIGN_IN_BOTTOM_MID, 0, 0); - - // Display date - - dateDayOfWeek = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_text_color(dateDayOfWeek, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); - lv_label_set_text(dateDayOfWeek, "THU"); - lv_obj_align(dateDayOfWeek, sidebar, LV_ALIGN_CENTER, 0, -34); - - dateDay = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_text_color(dateDay, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); - lv_label_set_text(dateDay, "25"); - lv_obj_align(dateDay, sidebar, LV_ALIGN_CENTER, 0, 3); - - dateMonth = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_style_local_text_color(dateMonth, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000)); - lv_label_set_text(dateMonth, "MAR"); - lv_obj_align(dateMonth, sidebar, LV_ALIGN_CENTER, 0, 32); - - // Step count gauge - needle_colors[0] = LV_COLOR_WHITE; - stepGauge = lv_gauge_create(lv_scr_act(), nullptr); - lv_gauge_set_needle_count(stepGauge, 1, needle_colors); - lv_obj_set_size(stepGauge, 40, 40); - lv_obj_align(stepGauge, sidebar, LV_ALIGN_IN_BOTTOM_MID, 0, 0); - lv_gauge_set_scale(stepGauge, 360, 11, 0); - lv_gauge_set_angle_offset(stepGauge, 180); - lv_gauge_set_critical_value(stepGauge, (100)); - lv_gauge_set_range(stepGauge, 0, (100)); - lv_gauge_set_value(stepGauge, 0, 0); - - lv_obj_set_style_local_pad_right(stepGauge, LV_GAUGE_PART_MAIN, LV_STATE_DEFAULT, 3); - lv_obj_set_style_local_pad_left(stepGauge, LV_GAUGE_PART_MAIN, LV_STATE_DEFAULT, 3); - lv_obj_set_style_local_pad_bottom(stepGauge, LV_GAUGE_PART_MAIN, LV_STATE_DEFAULT, 3); - lv_obj_set_style_local_line_opa(stepGauge, LV_GAUGE_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_COVER); - lv_obj_set_style_local_scale_width(stepGauge, LV_GAUGE_PART_MAIN, LV_STATE_DEFAULT, 4); - lv_obj_set_style_local_line_width(stepGauge, LV_GAUGE_PART_MAIN, LV_STATE_DEFAULT, 4); - lv_obj_set_style_local_line_color(stepGauge, LV_GAUGE_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK); - lv_obj_set_style_local_line_opa(stepGauge, LV_GAUGE_PART_NEEDLE, LV_STATE_DEFAULT, LV_OPA_COVER); - lv_obj_set_style_local_line_width(stepGauge, LV_GAUGE_PART_NEEDLE, LV_STATE_DEFAULT, 3); - lv_obj_set_style_local_pad_inner(stepGauge, LV_GAUGE_PART_NEEDLE, LV_STATE_DEFAULT, 4); - - backgroundLabel = lv_label_create(lv_scr_act(), nullptr); - lv_obj_set_click(backgroundLabel, true); - lv_label_set_long_mode(backgroundLabel, LV_LABEL_LONG_CROP); - lv_obj_set_size(backgroundLabel, 240, 240); - lv_obj_set_pos(backgroundLabel, 0, 0); - lv_label_set_text(backgroundLabel, ""); - - btnNextTime = lv_btn_create(lv_scr_act(), nullptr); - btnNextTime->user_data = this; - lv_obj_set_size(btnNextTime, 60, 60); - lv_obj_align(btnNextTime, lv_scr_act(), LV_ALIGN_IN_RIGHT_MID, -15, -80); - lv_obj_set_style_local_bg_opa(btnNextTime, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_30); - lv_obj_set_style_local_value_str(btnNextTime, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, ">"); - lv_obj_set_event_cb(btnNextTime, event_handler); - - btnPrevTime = lv_btn_create(lv_scr_act(), nullptr); - btnPrevTime->user_data = this; - lv_obj_set_size(btnPrevTime, 60, 60); - lv_obj_align(btnPrevTime, lv_scr_act(), LV_ALIGN_IN_LEFT_MID, 15, -80); - lv_obj_set_style_local_bg_opa(btnPrevTime, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_30); - lv_obj_set_style_local_value_str(btnPrevTime, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, "<"); - lv_obj_set_event_cb(btnPrevTime, event_handler); - - btnNextBar = lv_btn_create(lv_scr_act(), nullptr); - btnNextBar->user_data = this; - lv_obj_set_size(btnNextBar, 60, 60); - lv_obj_align(btnNextBar, lv_scr_act(), LV_ALIGN_IN_RIGHT_MID, -15, 0); - lv_obj_set_style_local_bg_opa(btnNextBar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_30); - lv_obj_set_style_local_value_str(btnNextBar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, ">"); - lv_obj_set_event_cb(btnNextBar, event_handler); - - btnPrevBar = lv_btn_create(lv_scr_act(), nullptr); - btnPrevBar->user_data = this; - lv_obj_set_size(btnPrevBar, 60, 60); - lv_obj_align(btnPrevBar, lv_scr_act(), LV_ALIGN_IN_LEFT_MID, 15, 0); - lv_obj_set_style_local_bg_opa(btnPrevBar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_30); - lv_obj_set_style_local_value_str(btnPrevBar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, "<"); - lv_obj_set_event_cb(btnPrevBar, event_handler); - - btnNextBG = lv_btn_create(lv_scr_act(), nullptr); - btnNextBG->user_data = this; - lv_obj_set_size(btnNextBG, 60, 60); - lv_obj_align(btnNextBG, lv_scr_act(), LV_ALIGN_IN_RIGHT_MID, -15, 80); - lv_obj_set_style_local_bg_opa(btnNextBG, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_30); - lv_obj_set_style_local_value_str(btnNextBG, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, ">"); - lv_obj_set_event_cb(btnNextBG, event_handler); - - btnPrevBG = lv_btn_create(lv_scr_act(), nullptr); - btnPrevBG->user_data = this; - lv_obj_set_size(btnPrevBG, 60, 60); - lv_obj_align(btnPrevBG, lv_scr_act(), LV_ALIGN_IN_LEFT_MID, 15, 80); - lv_obj_set_style_local_bg_opa(btnPrevBG, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_30); - lv_obj_set_style_local_value_str(btnPrevBG, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, "<"); - lv_obj_set_event_cb(btnPrevBG, event_handler); - - btnReset = lv_btn_create(lv_scr_act(), nullptr); - btnReset->user_data = this; - lv_obj_set_size(btnReset, 60, 60); - lv_obj_align(btnReset, lv_scr_act(), LV_ALIGN_CENTER, 0, 80); - lv_obj_set_style_local_bg_opa(btnReset, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_30); - lv_obj_set_style_local_value_str(btnReset, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, "Rst"); - lv_obj_set_event_cb(btnReset, event_handler); - - btnRandom = lv_btn_create(lv_scr_act(), nullptr); - btnRandom->user_data = this; - lv_obj_set_size(btnRandom, 60, 60); - lv_obj_align(btnRandom, lv_scr_act(), LV_ALIGN_CENTER, 0, 0); - lv_obj_set_style_local_bg_opa(btnRandom, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_30); - lv_obj_set_style_local_value_str(btnRandom, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, "Rnd"); - lv_obj_set_event_cb(btnRandom, event_handler); -} - -SettingPineTimeStyle::~SettingPineTimeStyle() { - lv_obj_clean(lv_scr_act()); - settingsController.SaveSettings(); -} - -void SettingPineTimeStyle::UpdateSelected(lv_obj_t* object, lv_event_t event) { - auto valueTime = settingsController.GetPTSColorTime(); - auto valueBar = settingsController.GetPTSColorBar(); - auto valueBG = settingsController.GetPTSColorBG(); - - if (event == LV_EVENT_CLICKED) { - if (object == btnNextTime) { - valueTime = GetNext(valueTime); - - settingsController.SetPTSColorTime(valueTime); - lv_obj_set_style_local_text_color(timeDD1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); - lv_obj_set_style_local_text_color(timeDD2, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); - lv_obj_set_style_local_text_color(timeAMPM, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); - } - if (object == btnPrevTime) { - valueTime = GetPrevious(valueTime); - settingsController.SetPTSColorTime(valueTime); - lv_obj_set_style_local_text_color(timeDD1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); - lv_obj_set_style_local_text_color(timeDD2, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); - lv_obj_set_style_local_text_color(timeAMPM, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(valueTime)); - } - if (object == btnNextBar) { - valueBar = GetNext(valueBar); - if(valueBar == Controllers::Settings::Colors::Black) - valueBar = GetNext(valueBar); - settingsController.SetPTSColorBar(valueBar); - lv_obj_set_style_local_bg_color(sidebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(valueBar)); - } - if (object == btnPrevBar) { - valueBar = GetPrevious(valueBar); - if(valueBar == Controllers::Settings::Colors::Black) - valueBar = GetPrevious(valueBar); - settingsController.SetPTSColorBar(valueBar); - lv_obj_set_style_local_bg_color(sidebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(valueBar)); - } - if (object == btnNextBG) { - valueBG = GetNext(valueBG); - settingsController.SetPTSColorBG(valueBG); - lv_obj_set_style_local_bg_color(timebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(valueBG)); - } - if (object == btnPrevBG) { - valueBG = GetPrevious(valueBG); - settingsController.SetPTSColorBG(valueBG); - lv_obj_set_style_local_bg_color(timebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(valueBG)); - } - if (object == btnReset) { - settingsController.SetPTSColorTime(Controllers::Settings::Colors::Teal); - lv_obj_set_style_local_text_color(timeDD1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(Controllers::Settings::Colors::Teal)); - lv_obj_set_style_local_text_color(timeDD2, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(Controllers::Settings::Colors::Teal)); - lv_obj_set_style_local_text_color(timeAMPM, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(Controllers::Settings::Colors::Teal)); - settingsController.SetPTSColorBar(Controllers::Settings::Colors::Teal); - lv_obj_set_style_local_bg_color(sidebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(Controllers::Settings::Colors::Teal)); - settingsController.SetPTSColorBG(Controllers::Settings::Colors::Black); - lv_obj_set_style_local_bg_color(timebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(Controllers::Settings::Colors::Black)); - } - if (object == btnRandom) { - uint8_t randTime = rand() % 17; - uint8_t randBar = rand() % 17; - uint8_t randBG = rand() % 17; - // Check if the time color is the same as its background, or if the sidebar is black. If so, change them to more useful values. - if (randTime == randBG) { - randBG += 1; - } - if (randBar == 3) { - randBar -= 1; - } - settingsController.SetPTSColorTime(static_cast(randTime)); - lv_obj_set_style_local_text_color(timeDD1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(static_cast(randTime))); - lv_obj_set_style_local_text_color(timeDD2, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(static_cast(randTime))); - lv_obj_set_style_local_text_color(timeAMPM, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, Convert(static_cast(randTime))); - settingsController.SetPTSColorBar(static_cast(randBar)); - lv_obj_set_style_local_bg_color(sidebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(static_cast(randBar))); - settingsController.SetPTSColorBG(static_cast(randBG)); - lv_obj_set_style_local_bg_color(timebar, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, Convert(static_cast(randBG))); - } - } -} - -Pinetime::Controllers::Settings::Colors SettingPineTimeStyle::GetNext(Pinetime::Controllers::Settings::Colors color) { - auto colorAsInt = static_cast(color); - Pinetime::Controllers::Settings::Colors nextColor; - if (colorAsInt < 16) { - nextColor = static_cast(colorAsInt + 1); - } else { - nextColor = static_cast(0); - } - return nextColor; -} - -Pinetime::Controllers::Settings::Colors SettingPineTimeStyle::GetPrevious(Pinetime::Controllers::Settings::Colors color) { - auto colorAsInt = static_cast(color); - Pinetime::Controllers::Settings::Colors prevColor; - - if (colorAsInt > 0) { - prevColor = static_cast(colorAsInt - 1); - } else { - prevColor = static_cast(16); - } - return prevColor; -} diff --git a/src/displayapp/screens/settings/SettingPineTimeStyle.h b/src/displayapp/screens/settings/SettingPineTimeStyle.h deleted file mode 100644 index 397bd86d..00000000 --- a/src/displayapp/screens/settings/SettingPineTimeStyle.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once - -#include -#include -#include "components/settings/Settings.h" -#include "displayapp/screens/Screen.h" - -namespace Pinetime { - - namespace Applications { - namespace Screens { - - class SettingPineTimeStyle : public Screen{ - public: - SettingPineTimeStyle(DisplayApp* app, Pinetime::Controllers::Settings &settingsController); - ~SettingPineTimeStyle() override; - - void UpdateSelected(lv_obj_t *object, lv_event_t event); - - private: - Controllers::Settings& settingsController; - - Pinetime::Controllers::Settings::Colors GetNext(Controllers::Settings::Colors color); - Pinetime::Controllers::Settings::Colors GetPrevious(Controllers::Settings::Colors color); - - lv_obj_t * btnNextTime; - lv_obj_t * btnPrevTime; - lv_obj_t * btnNextBar; - lv_obj_t * btnPrevBar; - lv_obj_t * btnNextBG; - lv_obj_t * btnPrevBG; - lv_obj_t * btnReset; - lv_obj_t * btnRandom; - lv_obj_t * timebar; - lv_obj_t * sidebar; - lv_obj_t * timeDD1; - lv_obj_t * timeDD2; - lv_obj_t * timeAMPM; - lv_obj_t * dateDayOfWeek; - lv_obj_t * dateDay; - lv_obj_t * dateMonth; - lv_obj_t * backgroundLabel; - lv_obj_t * batteryIcon; - lv_obj_t * bleIcon; - lv_obj_t * calendarOuter; - lv_obj_t * calendarInner; - lv_obj_t * calendarBar1; - lv_obj_t * calendarBar2; - lv_obj_t * calendarCrossBar1; - lv_obj_t * calendarCrossBar2; - lv_obj_t * stepGauge; - lv_color_t needle_colors[1]; - }; - } - } -} diff --git a/src/displayapp/screens/settings/SettingSetDate.cpp b/src/displayapp/screens/settings/SettingSetDate.cpp index ba3413ef..8bfded34 100644 --- a/src/displayapp/screens/settings/SettingSetDate.cpp +++ b/src/displayapp/screens/settings/SettingSetDate.cpp @@ -1,4 +1,4 @@ -#include "SettingSetDate.h" +#include "displayapp/screens/settings/SettingSetDate.h" #include #include #include diff --git a/src/displayapp/screens/settings/SettingSetTime.cpp b/src/displayapp/screens/settings/SettingSetTime.cpp index 194bf5eb..5351adeb 100644 --- a/src/displayapp/screens/settings/SettingSetTime.cpp +++ b/src/displayapp/screens/settings/SettingSetTime.cpp @@ -1,4 +1,4 @@ -#include "SettingSetTime.h" +#include "displayapp/screens/settings/SettingSetTime.h" #include #include #include diff --git a/src/displayapp/screens/settings/SettingSteps.cpp b/src/displayapp/screens/settings/SettingSteps.cpp index bec7972b..5ca3eecd 100644 --- a/src/displayapp/screens/settings/SettingSteps.cpp +++ b/src/displayapp/screens/settings/SettingSteps.cpp @@ -1,4 +1,4 @@ -#include "SettingSteps.h" +#include "displayapp/screens/settings/SettingSteps.h" #include #include "displayapp/DisplayApp.h" #include "displayapp/screens/Symbols.h" @@ -6,8 +6,8 @@ using namespace Pinetime::Applications::Screens; namespace { - static void event_handler(lv_obj_t * obj, lv_event_t event) { - SettingSteps* screen = static_cast(obj->user_data); + void event_handler(lv_obj_t* obj, lv_event_t event) { + SettingSteps* screen = static_cast(obj->user_data); screen->UpdateSelected(obj, event); } } @@ -30,33 +30,32 @@ SettingSteps::SettingSteps( lv_obj_set_height(container1, LV_VER_RES - 60); lv_cont_set_layout(container1, LV_LAYOUT_COLUMN_LEFT); - lv_obj_t * title = lv_label_create(lv_scr_act(), NULL); + lv_obj_t* title = lv_label_create(lv_scr_act(), nullptr); lv_label_set_text_static(title,"Daily steps goal"); lv_label_set_align(title, LV_LABEL_ALIGN_CENTER); lv_obj_align(title, lv_scr_act(), LV_ALIGN_IN_TOP_MID, 15, 15); - lv_obj_t * icon = lv_label_create(lv_scr_act(), NULL); + lv_obj_t* icon = lv_label_create(lv_scr_act(), nullptr); lv_obj_set_style_local_text_color(icon, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_ORANGE); lv_label_set_text_static(icon, Symbols::shoe); lv_label_set_align(icon, LV_LABEL_ALIGN_CENTER); lv_obj_align(icon, title, LV_ALIGN_OUT_LEFT_MID, -10, 0); - - stepValue = lv_label_create(lv_scr_act(), NULL); + stepValue = lv_label_create(lv_scr_act(), nullptr); lv_obj_set_style_local_text_font(stepValue, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, &jetbrains_mono_42); lv_label_set_text_fmt(stepValue, "%lu", settingsController.GetStepsGoal()); lv_label_set_align(stepValue, LV_LABEL_ALIGN_CENTER); lv_obj_align(stepValue, lv_scr_act(), LV_ALIGN_CENTER, 0, -10); - btnPlus = lv_btn_create(lv_scr_act(), NULL); + btnPlus = lv_btn_create(lv_scr_act(), nullptr); btnPlus->user_data = this; lv_obj_set_size(btnPlus, 80, 50); lv_obj_align(btnPlus, lv_scr_act(), LV_ALIGN_CENTER, 55, 80); lv_obj_set_style_local_value_str(btnPlus, LV_BTN_PART_MAIN, LV_STATE_DEFAULT, "+"); lv_obj_set_event_cb(btnPlus, event_handler); - btnMinus = lv_btn_create(lv_scr_act(), NULL); + btnMinus = lv_btn_create(lv_scr_act(), nullptr); btnMinus->user_data = this; lv_obj_set_size(btnMinus, 80, 50); lv_obj_set_event_cb(btnMinus, event_handler); diff --git a/src/displayapp/screens/settings/SettingTimeFormat.cpp b/src/displayapp/screens/settings/SettingTimeFormat.cpp index c99e3a0e..bd9af156 100644 --- a/src/displayapp/screens/settings/SettingTimeFormat.cpp +++ b/src/displayapp/screens/settings/SettingTimeFormat.cpp @@ -1,6 +1,7 @@ -#include "SettingTimeFormat.h" +#include "displayapp/screens/settings/SettingTimeFormat.h" #include #include "displayapp/DisplayApp.h" +#include "displayapp/screens/Styles.h" #include "displayapp/screens/Screen.h" #include "displayapp/screens/Symbols.h" @@ -13,6 +14,8 @@ namespace { } } +constexpr std::array SettingTimeFormat::options; + SettingTimeFormat::SettingTimeFormat(Pinetime::Applications::DisplayApp* app, Pinetime::Controllers::Settings& settingsController) : Screen(app), settingsController {settingsController} { @@ -39,24 +42,19 @@ SettingTimeFormat::SettingTimeFormat(Pinetime::Applications::DisplayApp* app, Pi lv_label_set_align(icon, LV_LABEL_ALIGN_CENTER); lv_obj_align(icon, title, LV_ALIGN_OUT_LEFT_MID, -10, 0); - optionsTotal = 0; - cbOption[optionsTotal] = lv_checkbox_create(container1, nullptr); - lv_checkbox_set_text_static(cbOption[optionsTotal], " 12-hour"); - cbOption[optionsTotal]->user_data = this; - lv_obj_set_event_cb(cbOption[optionsTotal], event_handler); - if (settingsController.GetClockType() == Controllers::Settings::ClockType::H12) { - lv_checkbox_set_checked(cbOption[optionsTotal], true); + for (unsigned int i = 0; i < options.size(); i++) { + cbOption[i] = lv_checkbox_create(container1, nullptr); + lv_checkbox_set_text(cbOption[i], options[i]); + cbOption[i]->user_data = this; + lv_obj_set_event_cb(cbOption[i], event_handler); + SetRadioButtonStyle(cbOption[i]); } - optionsTotal++; - cbOption[optionsTotal] = lv_checkbox_create(container1, nullptr); - lv_checkbox_set_text_static(cbOption[optionsTotal], " 24-hour"); - cbOption[optionsTotal]->user_data = this; - lv_obj_set_event_cb(cbOption[optionsTotal], event_handler); - if (settingsController.GetClockType() == Controllers::Settings::ClockType::H24) { - lv_checkbox_set_checked(cbOption[optionsTotal], true); + if (settingsController.GetClockType() == Controllers::Settings::ClockType::H12) { + lv_checkbox_set_checked(cbOption[0], true); + } else if (settingsController.GetClockType() == Controllers::Settings::ClockType::H24) { + lv_checkbox_set_checked(cbOption[1], true); } - optionsTotal++; } SettingTimeFormat::~SettingTimeFormat() { @@ -66,7 +64,7 @@ SettingTimeFormat::~SettingTimeFormat() { void SettingTimeFormat::UpdateSelected(lv_obj_t* object, lv_event_t event) { if (event == LV_EVENT_VALUE_CHANGED) { - for (int i = 0; i < optionsTotal; i++) { + for (unsigned int i = 0; i < options.size(); i++) { if (object == cbOption[i]) { lv_checkbox_set_checked(cbOption[i], true); diff --git a/src/displayapp/screens/settings/SettingTimeFormat.h b/src/displayapp/screens/settings/SettingTimeFormat.h index eac4bdc9..818edf0c 100644 --- a/src/displayapp/screens/settings/SettingTimeFormat.h +++ b/src/displayapp/screens/settings/SettingTimeFormat.h @@ -1,7 +1,9 @@ #pragma once +#include #include #include + #include "components/settings/Settings.h" #include "displayapp/screens/Screen.h" @@ -18,9 +20,9 @@ namespace Pinetime { void UpdateSelected(lv_obj_t* object, lv_event_t event); private: + static constexpr std::array options = {" 12-hour", " 24-hour"}; Controllers::Settings& settingsController; - uint8_t optionsTotal; - lv_obj_t* cbOption[2]; + lv_obj_t* cbOption[options.size()]; }; } } diff --git a/src/displayapp/screens/settings/SettingWakeUp.cpp b/src/displayapp/screens/settings/SettingWakeUp.cpp index d999004b..8339d9ad 100644 --- a/src/displayapp/screens/settings/SettingWakeUp.cpp +++ b/src/displayapp/screens/settings/SettingWakeUp.cpp @@ -1,4 +1,4 @@ -#include "SettingWakeUp.h" +#include "displayapp/screens/settings/SettingWakeUp.h" #include #include "displayapp/DisplayApp.h" #include "displayapp/screens/Screen.h" diff --git a/src/displayapp/screens/settings/SettingWatchFace.cpp b/src/displayapp/screens/settings/SettingWatchFace.cpp index cdec704c..a24eaa15 100644 --- a/src/displayapp/screens/settings/SettingWatchFace.cpp +++ b/src/displayapp/screens/settings/SettingWatchFace.cpp @@ -1,7 +1,8 @@ -#include "SettingWatchFace.h" +#include "displayapp/screens/settings/SettingWatchFace.h" #include #include "displayapp/DisplayApp.h" #include "displayapp/screens/Screen.h" +#include "displayapp/screens/Styles.h" #include "displayapp/screens/Symbols.h" using namespace Pinetime::Applications::Screens; @@ -13,6 +14,8 @@ namespace { } } +constexpr std::array SettingWatchFace::options; + SettingWatchFace::SettingWatchFace(Pinetime::Applications::DisplayApp* app, Pinetime::Controllers::Settings& settingsController) : Screen(app), settingsController {settingsController} { @@ -40,34 +43,17 @@ SettingWatchFace::SettingWatchFace(Pinetime::Applications::DisplayApp* app, Pine lv_label_set_align(icon, LV_LABEL_ALIGN_CENTER); lv_obj_align(icon, title, LV_ALIGN_OUT_LEFT_MID, -10, 0); - optionsTotal = 0; - cbOption[optionsTotal] = lv_checkbox_create(container1, nullptr); - lv_checkbox_set_text_static(cbOption[optionsTotal], " Digital face"); - cbOption[optionsTotal]->user_data = this; - lv_obj_set_event_cb(cbOption[optionsTotal], event_handler); - if (settingsController.GetClockFace() == 0) { - lv_checkbox_set_checked(cbOption[optionsTotal], true); - } + for (unsigned int i = 0; i < options.size(); i++) { + cbOption[i] = lv_checkbox_create(container1, nullptr); + lv_checkbox_set_text(cbOption[i], options[i]); + cbOption[i]->user_data = this; + lv_obj_set_event_cb(cbOption[i], event_handler); + SetRadioButtonStyle(cbOption[i]); - optionsTotal++; - cbOption[optionsTotal] = lv_checkbox_create(container1, nullptr); - lv_checkbox_set_text_static(cbOption[optionsTotal], " Analog face"); - cbOption[optionsTotal]->user_data = this; - lv_obj_set_event_cb(cbOption[optionsTotal], event_handler); - if (settingsController.GetClockFace() == 1) { - lv_checkbox_set_checked(cbOption[optionsTotal], true); + if (settingsController.GetClockFace() == i) { + lv_checkbox_set_checked(cbOption[i], true); + } } - - optionsTotal++; - cbOption[optionsTotal] = lv_checkbox_create(container1, nullptr); - lv_checkbox_set_text_static(cbOption[optionsTotal], " PineTimeStyle"); - cbOption[optionsTotal]->user_data = this; - lv_obj_set_event_cb(cbOption[optionsTotal], event_handler); - if (settingsController.GetClockFace() == 2) { - lv_checkbox_set_checked(cbOption[optionsTotal], true); - } - - optionsTotal++; } SettingWatchFace::~SettingWatchFace() { @@ -77,7 +63,7 @@ SettingWatchFace::~SettingWatchFace() { void SettingWatchFace::UpdateSelected(lv_obj_t* object, lv_event_t event) { if (event == LV_EVENT_VALUE_CHANGED) { - for (uint8_t i = 0; i < optionsTotal; i++) { + for (unsigned int i = 0; i < options.size(); i++) { if (object == cbOption[i]) { lv_checkbox_set_checked(cbOption[i], true); settingsController.SetClockFace(i); diff --git a/src/displayapp/screens/settings/SettingWatchFace.h b/src/displayapp/screens/settings/SettingWatchFace.h index d4a96c6d..ccba7d13 100644 --- a/src/displayapp/screens/settings/SettingWatchFace.h +++ b/src/displayapp/screens/settings/SettingWatchFace.h @@ -1,7 +1,9 @@ #pragma once +#include #include #include + #include "components/settings/Settings.h" #include "displayapp/screens/Screen.h" @@ -18,9 +20,10 @@ namespace Pinetime { void UpdateSelected(lv_obj_t* object, lv_event_t event); private: + static constexpr std::array options = {" Digital face", " Analog face", " PineTimeStyle"}; Controllers::Settings& settingsController; - uint8_t optionsTotal; - lv_obj_t* cbOption[2]; + + lv_obj_t* cbOption[options.size()]; }; } } diff --git a/src/displayapp/screens/settings/Settings.cpp b/src/displayapp/screens/settings/Settings.cpp index 678ad82e..3bc1372c 100644 --- a/src/displayapp/screens/settings/Settings.cpp +++ b/src/displayapp/screens/settings/Settings.cpp @@ -1,4 +1,4 @@ -#include "Settings.h" +#include "displayapp/screens/settings/Settings.h" #include #include #include "displayapp/screens/List.h" @@ -60,6 +60,7 @@ std::unique_ptr Settings::CreateScreen2() { std::unique_ptr Settings::CreateScreen3() { std::array applications {{ + {Symbols::clock, "Chimes", Apps::SettingChimes}, {Symbols::check, "Firmware", Apps::FirmwareValidation}, {Symbols::list, "About", Apps::SysInfo}, diff --git a/src/drivers/Bma421.cpp b/src/drivers/Bma421.cpp index dd284000..2f60f42f 100644 --- a/src/drivers/Bma421.cpp +++ b/src/drivers/Bma421.cpp @@ -1,7 +1,7 @@ +#include "drivers/Bma421.h" #include #include -#include "Bma421.h" -#include "TwiMaster.h" +#include "drivers/TwiMaster.h" #include using namespace Pinetime::Drivers; diff --git a/src/drivers/Cst816s.cpp b/src/drivers/Cst816s.cpp index 7fc8eca4..e9573df1 100644 --- a/src/drivers/Cst816s.cpp +++ b/src/drivers/Cst816s.cpp @@ -1,4 +1,4 @@ -#include "Cst816s.h" +#include "drivers/Cst816s.h" #include #include #include @@ -32,6 +32,12 @@ bool Cst816S::Init() { twiMaster.Read(twiAddress, 0xa7, &dummy, 1); vTaskDelay(5); + // TODO This function check that the device IDs from the controller are equal to the ones + // we expect. However, it seems to return false positive (probably in case of communication issue). + // Also, it seems that some users have pinetimes that works correctly but that report different device IDs + // Until we know more about this, we'll just read the IDs but not take any action in case they are not 'valid' + CheckDeviceIds(); + /* [2] EnConLR - Continuous operation can slide around [1] EnConUD - Slide up and down to enable continuous operation @@ -50,21 +56,7 @@ bool Cst816S::Init() { static constexpr uint8_t irqCtl = 0b01110000; twiMaster.Write(twiAddress, 0xFA, &irqCtl, 1); - // There's mixed information about which register contains which information - if (twiMaster.Read(twiAddress, 0xA7, &chipId, 1) == TwiMaster::ErrorCodes::TransactionFailed) { - chipId = 0xFF; - return false; - } - if (twiMaster.Read(twiAddress, 0xA8, &vendorId, 1) == TwiMaster::ErrorCodes::TransactionFailed) { - vendorId = 0xFF; - return false; - } - if (twiMaster.Read(twiAddress, 0xA9, &fwVersion, 1) == TwiMaster::ErrorCodes::TransactionFailed) { - fwVersion = 0xFF; - return false; - } - - return chipId == 0xb4 && vendorId == 0 && fwVersion == 1; + return true; } Cst816S::TouchInfos Cst816S::GetTouchInfo() { @@ -79,18 +71,33 @@ Cst816S::TouchInfos Cst816S::GetTouchInfo() { // This can only be 0 or 1 uint8_t nbTouchPoints = touchData[touchPointNumIndex] & 0x0f; - uint8_t xHigh = touchData[touchXHighIndex] & 0x0f; uint8_t xLow = touchData[touchXLowIndex]; - info.x = (xHigh << 8) | xLow; - + uint16_t x = (xHigh << 8) | xLow; uint8_t yHigh = touchData[touchYHighIndex] & 0x0f; uint8_t yLow = touchData[touchYLowIndex]; - info.y = (yHigh << 8) | yLow; + uint16_t y = (yHigh << 8) | yLow; + Gestures gesture = static_cast(touchData[gestureIndex]); + // Validity check + if(x >= maxX || y >= maxY || + (gesture != Gestures::None && + gesture != Gestures::SlideDown && + gesture != Gestures::SlideUp && + gesture != Gestures::SlideLeft && + gesture != Gestures::SlideRight && + gesture != Gestures::SingleTap && + gesture != Gestures::DoubleTap && + gesture != Gestures::LongPress)) { + info.isValid = false; + return info; + } + + info.x = x; + info.y = y; info.touching = (nbTouchPoints > 0); - info.gesture = static_cast(touchData[gestureIndex]); - + info.gesture = gesture; + info.isValid = true; return info; } @@ -108,3 +115,21 @@ void Cst816S::Wakeup() { Init(); NRF_LOG_INFO("[TOUCHPANEL] Wakeup"); } + +bool Cst816S::CheckDeviceIds() { + // There's mixed information about which register contains which information + if (twiMaster.Read(twiAddress, 0xA7, &chipId, 1) == TwiMaster::ErrorCodes::TransactionFailed) { + chipId = 0xFF; + return false; + } + if (twiMaster.Read(twiAddress, 0xA8, &vendorId, 1) == TwiMaster::ErrorCodes::TransactionFailed) { + vendorId = 0xFF; + return false; + } + if (twiMaster.Read(twiAddress, 0xA9, &fwVersion, 1) == TwiMaster::ErrorCodes::TransactionFailed) { + fwVersion = 0xFF; + return false; + } + + return chipId == 0xb4 && vendorId == 0 && fwVersion == 1; +} diff --git a/src/drivers/Cst816s.h b/src/drivers/Cst816s.h index 0fec8419..4a548d45 100644 --- a/src/drivers/Cst816s.h +++ b/src/drivers/Cst816s.h @@ -1,6 +1,6 @@ #pragma once -#include "TwiMaster.h" +#include "drivers/TwiMaster.h" namespace Pinetime { namespace Drivers { @@ -21,7 +21,7 @@ namespace Pinetime { uint16_t y = 0; Gestures gesture = Gestures::None; bool touching = false; - bool isValid = true; + bool isValid = false; }; Cst816S(TwiMaster& twiMaster, uint8_t twiAddress); @@ -45,6 +45,8 @@ namespace Pinetime { return fwVersion; } private: + bool CheckDeviceIds(); + // Unused/Unavailable commented out static constexpr uint8_t gestureIndex = 1; static constexpr uint8_t touchPointNumIndex = 2; @@ -58,6 +60,9 @@ namespace Pinetime { //static constexpr uint8_t touchXYIndex = 7; //static constexpr uint8_t touchMiscIndex = 8; + static constexpr uint8_t maxX = 240; + static constexpr uint8_t maxY = 240; + TwiMaster& twiMaster; uint8_t twiAddress; diff --git a/src/drivers/DebugPins.cpp b/src/drivers/DebugPins.cpp index 56fd1458..92091280 100644 --- a/src/drivers/DebugPins.cpp +++ b/src/drivers/DebugPins.cpp @@ -1,4 +1,4 @@ -#include "DebugPins.h" +#include "drivers/DebugPins.h" #include #ifdef USE_DEBUG_PINS diff --git a/src/drivers/Hrs3300.cpp b/src/drivers/Hrs3300.cpp index edb9e81d..c14fe7aa 100644 --- a/src/drivers/Hrs3300.cpp +++ b/src/drivers/Hrs3300.cpp @@ -4,9 +4,9 @@ C++ port Copyright (C) 2021 Jean-François Milants */ +#include "drivers/Hrs3300.h" #include #include -#include "Hrs3300.h" #include #include diff --git a/src/drivers/Hrs3300.h b/src/drivers/Hrs3300.h index c4f28900..01310c62 100644 --- a/src/drivers/Hrs3300.h +++ b/src/drivers/Hrs3300.h @@ -1,6 +1,6 @@ #pragma once -#include "TwiMaster.h" +#include "drivers/TwiMaster.h" namespace Pinetime { namespace Drivers { diff --git a/src/drivers/InternalFlash.cpp b/src/drivers/InternalFlash.cpp index 0840c6e5..ec5885d5 100644 --- a/src/drivers/InternalFlash.cpp +++ b/src/drivers/InternalFlash.cpp @@ -1,4 +1,4 @@ -#include "InternalFlash.h" +#include "drivers/InternalFlash.h" #include using namespace Pinetime::Drivers; diff --git a/src/drivers/PinMap.h b/src/drivers/PinMap.h index 57964020..579bf38a 100644 --- a/src/drivers/PinMap.h +++ b/src/drivers/PinMap.h @@ -1,4 +1,5 @@ #pragma once +#include namespace Pinetime { namespace PinMap { diff --git a/src/drivers/Spi.cpp b/src/drivers/Spi.cpp index a55d2888..e477622b 100644 --- a/src/drivers/Spi.cpp +++ b/src/drivers/Spi.cpp @@ -1,4 +1,4 @@ -#include "Spi.h" +#include "drivers/Spi.h" #include #include diff --git a/src/drivers/Spi.h b/src/drivers/Spi.h index 6875710d..9b6a30f4 100644 --- a/src/drivers/Spi.h +++ b/src/drivers/Spi.h @@ -1,7 +1,7 @@ #pragma once #include #include -#include "SpiMaster.h" +#include "drivers/SpiMaster.h" namespace Pinetime { namespace Drivers { diff --git a/src/drivers/SpiMaster.cpp b/src/drivers/SpiMaster.cpp index c45e1294..747dbc84 100644 --- a/src/drivers/SpiMaster.cpp +++ b/src/drivers/SpiMaster.cpp @@ -1,4 +1,4 @@ -#include "SpiMaster.h" +#include "drivers/SpiMaster.h" #include #include #include diff --git a/src/drivers/SpiNorFlash.cpp b/src/drivers/SpiNorFlash.cpp index 068d1d02..ebe3174c 100644 --- a/src/drivers/SpiNorFlash.cpp +++ b/src/drivers/SpiNorFlash.cpp @@ -1,8 +1,8 @@ -#include "SpiNorFlash.h" +#include "drivers/SpiNorFlash.h" #include #include #include -#include "Spi.h" +#include "drivers/Spi.h" using namespace Pinetime::Drivers; diff --git a/src/drivers/St7789.cpp b/src/drivers/St7789.cpp index 4d81cf27..fd1366f8 100644 --- a/src/drivers/St7789.cpp +++ b/src/drivers/St7789.cpp @@ -1,8 +1,8 @@ -#include "St7789.h" +#include "drivers/St7789.h" #include #include #include -#include "Spi.h" +#include "drivers/Spi.h" using namespace Pinetime::Drivers; diff --git a/src/drivers/TwiMaster.cpp b/src/drivers/TwiMaster.cpp index 76009278..9b456d5f 100644 --- a/src/drivers/TwiMaster.cpp +++ b/src/drivers/TwiMaster.cpp @@ -1,4 +1,4 @@ -#include "TwiMaster.h" +#include "drivers/TwiMaster.h" #include #include #include diff --git a/src/drivers/Watchdog.cpp b/src/drivers/Watchdog.cpp index a6ad263a..d0907a65 100644 --- a/src/drivers/Watchdog.cpp +++ b/src/drivers/Watchdog.cpp @@ -1,4 +1,4 @@ -#include "Watchdog.h" +#include "drivers/Watchdog.h" #include using namespace Pinetime::Drivers; diff --git a/src/heartratetask/HeartRateTask.cpp b/src/heartratetask/HeartRateTask.cpp index fddc05d7..213ab4a7 100644 --- a/src/heartratetask/HeartRateTask.cpp +++ b/src/heartratetask/HeartRateTask.cpp @@ -1,4 +1,4 @@ -#include "HeartRateTask.h" +#include "heartratetask/HeartRateTask.h" #include #include #include diff --git a/src/libs/QCBOR b/src/libs/QCBOR new file mode 160000 index 00000000..9e2f7080 --- /dev/null +++ b/src/libs/QCBOR @@ -0,0 +1 @@ +Subproject commit 9e2f70804393823cc6d16f9f1035ef7223faca04 diff --git a/src/libs/mynewt-nimble/porting/nimble/include/syscfg/syscfg.h b/src/libs/mynewt-nimble/porting/nimble/include/syscfg/syscfg.h index 94b72cb6..b3f23411 100644 --- a/src/libs/mynewt-nimble/porting/nimble/include/syscfg/syscfg.h +++ b/src/libs/mynewt-nimble/porting/nimble/include/syscfg/syscfg.h @@ -699,11 +699,11 @@ #endif #ifndef MYNEWT_VAL_BLE_SM_BONDING -#define MYNEWT_VAL_BLE_SM_BONDING (0) +#define MYNEWT_VAL_BLE_SM_BONDING (1) #endif #ifndef MYNEWT_VAL_BLE_SM_IO_CAP -#define MYNEWT_VAL_BLE_SM_IO_CAP (BLE_HS_IO_NO_INPUT_OUTPUT) +#define MYNEWT_VAL_BLE_SM_IO_CAP (BLE_HS_IO_DISPLAY_ONLY) #endif #ifndef MYNEWT_VAL_BLE_SM_KEYPRESS @@ -711,7 +711,7 @@ #endif #ifndef MYNEWT_VAL_BLE_SM_LEGACY -#define MYNEWT_VAL_BLE_SM_LEGACY (1) +#define MYNEWT_VAL_BLE_SM_LEGACY (0) #endif #ifndef MYNEWT_VAL_BLE_SM_MAX_PROCS @@ -719,7 +719,7 @@ #endif #ifndef MYNEWT_VAL_BLE_SM_MITM -#define MYNEWT_VAL_BLE_SM_MITM (0) +#define MYNEWT_VAL_BLE_SM_MITM (1) #endif #ifndef MYNEWT_VAL_BLE_SM_OOB_DATA_FLAG @@ -727,11 +727,11 @@ #endif #ifndef MYNEWT_VAL_BLE_SM_OUR_KEY_DIST -#define MYNEWT_VAL_BLE_SM_OUR_KEY_DIST (0) +#define MYNEWT_VAL_BLE_SM_OUR_KEY_DIST (7) #endif #ifndef MYNEWT_VAL_BLE_SM_SC -#define MYNEWT_VAL_BLE_SM_SC (0) +#define MYNEWT_VAL_BLE_SM_SC (1) #endif #ifndef MYNEWT_VAL_BLE_SM_SC_DEBUG_KEYS @@ -739,7 +739,7 @@ #endif #ifndef MYNEWT_VAL_BLE_SM_THEIR_KEY_DIST -#define MYNEWT_VAL_BLE_SM_THEIR_KEY_DIST (0) +#define MYNEWT_VAL_BLE_SM_THEIR_KEY_DIST (3) #endif #ifndef MYNEWT_VAL_BLE_STORE_MAX_BONDS @@ -1089,7 +1089,7 @@ /* Overridden by @apache-mynewt-nimble/targets/riot (defined by @apache-mynewt-nimble/nimble/controller) */ #ifndef MYNEWT_VAL_BLE_LL_CFG_FEAT_LL_PRIVACY -#define MYNEWT_VAL_BLE_LL_CFG_FEAT_LL_PRIVACY (0) +#define MYNEWT_VAL_BLE_LL_CFG_FEAT_LL_PRIVACY (1) #endif #ifndef MYNEWT_VAL_BLE_LL_CFG_FEAT_SLAVE_INIT_FEAT_XCHG diff --git a/src/libs/mynewt-nimble/porting/npl/freertos/src/nimble_port_freertos.c b/src/libs/mynewt-nimble/porting/npl/freertos/src/nimble_port_freertos.c index 8ee3475a..b9902781 100644 --- a/src/libs/mynewt-nimble/porting/npl/freertos/src/nimble_port_freertos.c +++ b/src/libs/mynewt-nimble/porting/npl/freertos/src/nimble_port_freertos.c @@ -37,7 +37,7 @@ nimble_port_freertos_init(TaskFunction_t host_task_fn) * provided by NimBLE and in case of FreeRTOS it does not need to be wrapped * since it has compatible prototype. */ - xTaskCreate(nimble_port_ll_task_func, "ll", configMINIMAL_STACK_SIZE + 400, + xTaskCreate(nimble_port_ll_task_func, "ll", configMINIMAL_STACK_SIZE + 200, NULL, configMAX_PRIORITIES - 1, &ll_task_h); #endif @@ -46,6 +46,6 @@ nimble_port_freertos_init(TaskFunction_t host_task_fn) * have separate task for NimBLE host, but since something needs to handle * default queue it is just easier to make separate task which does this. */ - xTaskCreate(host_task_fn, "ble", configMINIMAL_STACK_SIZE + 400, + xTaskCreate(host_task_fn, "ble", configMINIMAL_STACK_SIZE + 600, NULL, tskIDLE_PRIORITY + 1, &host_task_h); } diff --git a/src/logging/DummyLogger.h b/src/logging/DummyLogger.h index 8732dff5..1b050b37 100644 --- a/src/logging/DummyLogger.h +++ b/src/logging/DummyLogger.h @@ -1,5 +1,5 @@ #pragma once -#include "Logger.h" +#include "logging/Logger.h" namespace Pinetime { namespace Logging { diff --git a/src/logging/NrfLogger.cpp b/src/logging/NrfLogger.cpp index 1c048f2c..f8d95a63 100644 --- a/src/logging/NrfLogger.cpp +++ b/src/logging/NrfLogger.cpp @@ -1,4 +1,4 @@ -#include "NrfLogger.h" +#include "logging/NrfLogger.h" #include #include @@ -19,14 +19,13 @@ void NrfLogger::Init() { void NrfLogger::Process(void*) { NRF_LOG_INFO("Logger task started!"); -// Suppress endless loop diagnostic + #pragma clang diagnostic push #pragma ide diagnostic ignored "EndlessLoop" while (true) { NRF_LOG_FLUSH(); vTaskDelay(100); // Not good for power consumption, it will wake up every 100ms... } -// Clear diagnostic suppression #pragma clang diagnostic pop } diff --git a/src/logging/NrfLogger.h b/src/logging/NrfLogger.h index 060c4e76..21183a3d 100644 --- a/src/logging/NrfLogger.h +++ b/src/logging/NrfLogger.h @@ -1,5 +1,5 @@ #pragma once -#include "Logger.h" +#include "logging/Logger.h" #include #include diff --git a/src/main.cpp b/src/main.cpp index fc772355..53f78ce8 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -47,6 +47,7 @@ #include "systemtask/SystemTask.h" #include "drivers/PinMap.h" #include "touchhandler/TouchHandler.h" +#include "buttonhandler/ButtonHandler.h" #if NRF_LOG_ENABLED #include "logging/NrfLogger.h" @@ -96,8 +97,6 @@ TimerHandle_t debounceTimer; TimerHandle_t debounceChargeTimer; Pinetime::Controllers::Battery batteryController; Pinetime::Controllers::Ble bleController; -static constexpr uint8_t pinTouchIrq = Pinetime::PinMap::Cst816sIrq; -static constexpr uint8_t pinPowerPresentIrq = Pinetime::PinMap::PowerPresent; Pinetime::Controllers::HeartRateController heartRateController; Pinetime::Applications::HeartRateTask heartRateApp(heartRateSensor, heartRateController); @@ -110,6 +109,7 @@ Pinetime::Controllers::MotionController motionController; Pinetime::Controllers::TimerController timerController; Pinetime::Controllers::AlarmController alarmController {dateTimeController}; Pinetime::Controllers::TouchHandler touchHandler(touchPanel, lvgl); +Pinetime::Controllers::ButtonHandler buttonHandler; Pinetime::Controllers::FS fs {spiNorFlash}; Pinetime::Controllers::Settings settingsController {fs}; @@ -153,7 +153,8 @@ Pinetime::System::SystemTask systemTask(spi, displayApp, heartRateApp, fs, - touchHandler); + touchHandler, + buttonHandler); /* Variable Declarations for variables in noinit SRAM Increment NoInit_MagicValue upon adding variables to this area @@ -176,11 +177,10 @@ void nrfx_gpiote_evt_handler(nrfx_gpiote_pin_t pin, nrf_gpiote_polarity_t action if (pin == Pinetime::PinMap::PowerPresent and action == NRF_GPIOTE_POLARITY_TOGGLE) { xTimerStartFromISR(debounceChargeTimer, &xHigherPriorityTaskWoken); portYIELD_FROM_ISR(xHigherPriorityTaskWoken); - return; + } else if (pin == Pinetime::PinMap::Button) { + xTimerStartFromISR(debounceTimer, &xHigherPriorityTaskWoken); + portYIELD_FROM_ISR(xHigherPriorityTaskWoken); } - - xTimerStartFromISR(debounceTimer, &xHigherPriorityTaskWoken); - portYIELD_FROM_ISR(xHigherPriorityTaskWoken); } void DebounceTimerChargeCallback(TimerHandle_t xTimer) { @@ -188,9 +188,8 @@ void DebounceTimerChargeCallback(TimerHandle_t xTimer) { systemTask.PushMessage(Pinetime::System::Messages::OnChargingEvent); } -void DebounceTimerCallback(TimerHandle_t xTimer) { - xTimerStop(xTimer, 0); - systemTask.OnButtonPushed(); +void DebounceTimerCallback(TimerHandle_t /*unused*/) { + systemTask.PushMessage(Pinetime::System::Messages::HandleButtonEvent); } void SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQHandler(void) { @@ -319,8 +318,8 @@ int main(void) { } nrf_gpio_cfg_default(Pinetime::PinMap::TwiScl); - debounceTimer = xTimerCreate("debounceTimer", 200, pdFALSE, (void*) 0, DebounceTimerCallback); - debounceChargeTimer = xTimerCreate("debounceTimerCharge", 200, pdFALSE, (void*) 0, DebounceTimerChargeCallback); + debounceTimer = xTimerCreate("debounceTimer", 10, pdFALSE, nullptr, DebounceTimerCallback); + debounceChargeTimer = xTimerCreate("debounceTimerCharge", 200, pdFALSE, nullptr, DebounceTimerChargeCallback); // retrieve version stored by bootloader Pinetime::BootloaderVersion::SetVersion(NRF_TIMER2->CC[0]); diff --git a/src/sdk_config.h b/src/sdk_config.h index 38d47a7f..7634dca1 100644 --- a/src/sdk_config.h +++ b/src/sdk_config.h @@ -12580,4 +12580,4 @@ #endif // <<< end of configuration section >>> -#endif // SDK_CONFIG_H \ No newline at end of file +#endif // SDK_CONFIG_H diff --git a/src/systemtask/Messages.h b/src/systemtask/Messages.h index 1a9ad542..4d5ab4ce 100644 --- a/src/systemtask/Messages.h +++ b/src/systemtask/Messages.h @@ -15,7 +15,8 @@ namespace Pinetime { BleFirmwareUpdateStarted, BleFirmwareUpdateFinished, OnTouchEvent, - OnButtonEvent, + HandleButtonEvent, + HandleButtonTimerEvent, OnDisplayTaskSleeping, EnableSleeping, DisableSleeping, @@ -23,10 +24,13 @@ namespace Pinetime { OnNewHour, OnNewHalfHour, OnChargingEvent, + OnPairing, SetOffAlarm, StopRinging, MeasureBatteryTimerExpired, BatteryPercentageUpdated, + StartFileTransfer, + StopFileTransfer, }; } } diff --git a/src/systemtask/SystemTask.cpp b/src/systemtask/SystemTask.cpp index c48307af..b2926936 100644 --- a/src/systemtask/SystemTask.cpp +++ b/src/systemtask/SystemTask.cpp @@ -1,4 +1,4 @@ -#include "SystemTask.h" +#include "systemtask/SystemTask.h" #define min // workaround: nimble's min/max macros conflict with libstdc++ #define max #include @@ -25,7 +25,6 @@ #include "main.h" #include "BootErrors.h" - #include using namespace Pinetime::System; @@ -77,7 +76,8 @@ SystemTask::SystemTask(Drivers::SpiMaster& spi, Pinetime::Applications::DisplayApp& displayApp, Pinetime::Applications::HeartRateTask& heartRateApp, Pinetime::Controllers::FS& fs, - Pinetime::Controllers::TouchHandler& touchHandler) + Pinetime::Controllers::TouchHandler& touchHandler, + Pinetime::Controllers::ButtonHandler& buttonHandler) : spi {spi}, lcd {lcd}, spiNorFlash {spiNorFlash}, @@ -101,14 +101,23 @@ SystemTask::SystemTask(Drivers::SpiMaster& spi, heartRateApp(heartRateApp), fs {fs}, touchHandler {touchHandler}, - nimbleController(*this, bleController, dateTimeController, notificationManager, - batteryController, spiNorFlash, heartRateController, motionController) { + buttonHandler {buttonHandler}, + nimbleController(*this, + bleController, + dateTimeController, + notificationManager, + batteryController, + spiNorFlash, + heartRateController, + motionController, + fs) { } void SystemTask::Start() { systemTasksMsgQueue = xQueueCreate(10, 1); - if (pdPASS != xTaskCreate(SystemTask::Process, "MAIN", 350, this, 0, &taskHandle)) + if (pdPASS != xTaskCreate(SystemTask::Process, "MAIN", 350, this, 0, &taskHandle)) { APP_ERROR_HANDLER(NRF_ERROR_NO_MEM); + } } void SystemTask::Process(void* instance) { @@ -137,9 +146,15 @@ void SystemTask::Work() { lcd.Init(); twiMaster.Init(); + /* + * TODO We disable this warning message until we ensure it won't be displayed + * on legitimate PineTime equipped with a compatible touch controller. + * (some users reported false positive). See https://github.com/InfiniTimeOrg/InfiniTime/issues/763 if (!touchPanel.Init()) { bootError = BootErrors::TouchController; } + */ + touchPanel.Init(); dateTimeController.Register(this); batteryController.Register(this); motorController.Init(); @@ -163,6 +178,8 @@ void SystemTask::Work() { heartRateSensor.Disable(); heartRateApp.Start(); + buttonHandler.Init(this); + // Button nrf_gpio_cfg_output(15); nrf_gpio_pin_set(15); @@ -171,20 +188,22 @@ void SystemTask::Work() { pinConfig.skip_gpio_setup = false; pinConfig.hi_accuracy = false; pinConfig.is_watcher = false; - pinConfig.sense = (nrf_gpiote_polarity_t) NRF_GPIOTE_POLARITY_TOGGLE; - pinConfig.pull = (nrf_gpio_pin_pull_t) GPIO_PIN_CNF_PULL_Pulldown; + pinConfig.sense = static_cast(NRF_GPIOTE_POLARITY_TOGGLE); + pinConfig.pull = static_cast(GPIO_PIN_CNF_PULL_Pulldown); nrfx_gpiote_in_init(PinMap::Button, &pinConfig, nrfx_gpiote_evt_handler); nrfx_gpiote_in_event_enable(PinMap::Button, true); // Touchscreen - nrf_gpio_cfg_sense_input(PinMap::Cst816sIrq, (nrf_gpio_pin_pull_t) GPIO_PIN_CNF_PULL_Pullup, (nrf_gpio_pin_sense_t) GPIO_PIN_CNF_SENSE_Low); + nrf_gpio_cfg_sense_input(PinMap::Cst816sIrq, + static_cast(GPIO_PIN_CNF_PULL_Pullup), + static_cast GPIO_PIN_CNF_SENSE_Low); pinConfig.skip_gpio_setup = true; pinConfig.hi_accuracy = false; pinConfig.is_watcher = false; - pinConfig.sense = (nrf_gpiote_polarity_t) NRF_GPIOTE_POLARITY_HITOLO; - pinConfig.pull = (nrf_gpio_pin_pull_t) GPIO_PIN_CNF_PULL_Pullup; + pinConfig.sense = static_cast(NRF_GPIOTE_POLARITY_HITOLO); + pinConfig.pull = static_cast GPIO_PIN_CNF_PULL_Pullup; nrfx_gpiote_in_init(PinMap::Cst816sIrq, &pinConfig, nrfx_gpiote_evt_handler); @@ -205,7 +224,6 @@ void SystemTask::Work() { xTimerStart(dimTimer, 0); xTimerStart(measureBatteryTimer, portMAX_DELAY); -// Suppress endless loop diagnostic #pragma clang diagnostic push #pragma ide diagnostic ignored "EndlessLoop" while (true) { @@ -243,8 +261,9 @@ void SystemTask::Work() { displayApp.PushMessage(Pinetime::Applications::Display::Messages::GoToRunning); heartRateApp.PushMessage(Pinetime::Applications::HeartRateTask::Messages::WakeUp); - if (!bleController.IsConnected()) + if (!bleController.IsConnected()) { nimbleController.RestartFastAdv(); + } isSleeping = false; isWakingUp = false; @@ -263,6 +282,9 @@ void SystemTask::Work() { } } break; case Messages::GoToSleep: + if (doNotGoToSleep) { + break; + } isGoingToSleep = true; NRF_LOG_INFO("[systemtask] Going to sleep"); xTimerStop(idleTimer, 0); @@ -308,8 +330,9 @@ void SystemTask::Work() { break; case Messages::BleFirmwareUpdateStarted: doNotGoToSleep = true; - if (isSleeping && !isWakingUp) + if (isSleeping && !isWakingUp) { GoToRunning(); + } displayApp.PushMessage(Pinetime::Applications::Display::Messages::BleFirmwareUpdateStarted); break; case Messages::BleFirmwareUpdateFinished: @@ -319,6 +342,19 @@ void SystemTask::Work() { doNotGoToSleep = false; xTimerStart(dimTimer, 0); break; + case Messages::StartFileTransfer: + NRF_LOG_INFO("[systemtask] FS Started"); + doNotGoToSleep = true; + if (isSleeping && !isWakingUp) + GoToRunning(); + //TODO add intent of fs access icon or something + break; + case Messages::StopFileTransfer: + NRF_LOG_INFO("[systemtask] FS Stopped"); + doNotGoToSleep = false; + xTimerStart(dimTimer, 0); + //TODO add intent of fs access icon or something + break; case Messages::OnTouchEvent: if (touchHandler.GetNewTouchInfo()) { touchHandler.UpdateLvglTouchPoint(); @@ -326,10 +362,25 @@ void SystemTask::Work() { ReloadIdleTimer(); displayApp.PushMessage(Pinetime::Applications::Display::Messages::TouchEvent); break; - case Messages::OnButtonEvent: - ReloadIdleTimer(); - displayApp.PushMessage(Pinetime::Applications::Display::Messages::ButtonPushed); - break; + case Messages::HandleButtonEvent: { + Controllers::ButtonActions action; + if (nrf_gpio_pin_read(Pinetime::PinMap::Button) == 0) { + action = buttonHandler.HandleEvent(Controllers::ButtonHandler::Events::Release); + } else { + action = buttonHandler.HandleEvent(Controllers::ButtonHandler::Events::Press); + // This is for faster wakeup, sacrificing special longpress and doubleclick handling while sleeping + if (IsSleeping()) { + fastWakeUpDone = true; + GoToRunning(); + break; + } + } + HandleButtonAction(action); + } break; + case Messages::HandleButtonTimerEvent: { + auto action = buttonHandler.HandleEvent(Controllers::ButtonHandler::Events::Timer); + HandleButtonAction(action); + } break; case Messages::OnDisplayTaskSleeping: if (BootloaderVersion::IsValid()) { // First versions of the bootloader do not expose their version and cannot initialize the SPI NOR FLASH @@ -386,6 +437,13 @@ void SystemTask::Work() { case Messages::BatteryPercentageUpdated: nimbleController.NotifyBatteryLevel(batteryController.PercentRemaining()); break; + case Messages::OnPairing: + if (isSleeping && !isWakingUp) { + GoToRunning(); + } + motorController.RunForDuration(35); + displayApp.PushMessage(Pinetime::Applications::Display::Messages::ShowPairingKey); + break; default: break; @@ -407,18 +465,21 @@ void SystemTask::Work() { uint32_t systick_counter = nrf_rtc_counter_get(portNRF_RTC_REG); dateTimeController.UpdateTime(systick_counter); NoInit_BackUpTime = dateTimeController.CurrentDateTime(); - if (!nrf_gpio_pin_read(PinMap::Button)) + if (!nrf_gpio_pin_read(PinMap::Button)) { watchdog.Kick(); + } } -// Clear diagnostic suppression #pragma clang diagnostic pop } -void SystemTask::UpdateMotion() { - if (isGoingToSleep or isWakingUp) - return; - if (isSleeping && !settingsController.isWakeUpModeOn(Pinetime::Controllers::Settings::WakeUpMode::RaiseWrist)) +void SystemTask::UpdateMotion() { + if (isGoingToSleep or isWakingUp) { return; + } + + if (isSleeping && !settingsController.isWakeUpModeOn(Pinetime::Controllers::Settings::WakeUpMode::RaiseWrist)) { + return; + } if (stepCounterMustBeReset) { motionSensor.ResetStepCounter(); @@ -434,30 +495,50 @@ void SystemTask::UpdateMotion() { } } -void SystemTask::OnButtonPushed() { - if (isGoingToSleep) +void SystemTask::HandleButtonAction(Controllers::ButtonActions action) { + if (IsSleeping()) { return; - if (!isSleeping) { - NRF_LOG_INFO("[systemtask] Button pushed"); - PushMessage(Messages::OnButtonEvent); - } else { - if (!isWakingUp) { - NRF_LOG_INFO("[systemtask] Button pushed, waking up"); - GoToRunning(); - } } + + ReloadIdleTimer(); + + using Actions = Controllers::ButtonActions; + + switch (action) { + case Actions::Click: + // If the first action after fast wakeup is a click, it should be ignored. + if (!fastWakeUpDone && !isGoingToSleep) { + displayApp.PushMessage(Applications::Display::Messages::ButtonPushed); + } + break; + case Actions::DoubleClick: + displayApp.PushMessage(Applications::Display::Messages::ButtonDoubleClicked); + break; + case Actions::LongPress: + displayApp.PushMessage(Applications::Display::Messages::ButtonLongPressed); + break; + case Actions::LongerPress: + displayApp.PushMessage(Applications::Display::Messages::ButtonLongerPressed); + break; + default: + return; + } + + fastWakeUpDone = false; } void SystemTask::GoToRunning() { - if (isGoingToSleep or (not isSleeping) or isWakingUp) + if (isGoingToSleep or (not isSleeping) or isWakingUp) { return; + } isWakingUp = true; PushMessage(Messages::GoToRunning); } void SystemTask::OnTouchEvent() { - if (isGoingToSleep) + if (isGoingToSleep) { return; + } if (!isSleeping) { PushMessage(Messages::OnTouchEvent); } else if (!isWakingUp) { @@ -469,7 +550,7 @@ void SystemTask::OnTouchEvent() { } void SystemTask::PushMessage(System::Messages msg) { - if (msg == Messages::GoToSleep) { + if (msg == Messages::GoToSleep && !doNotGoToSleep) { isGoingToSleep = true; } @@ -487,8 +568,9 @@ void SystemTask::PushMessage(System::Messages msg) { } void SystemTask::OnDim() { - if (doNotGoToSleep) + if (doNotGoToSleep) { return; + } NRF_LOG_INFO("Dim timeout -> Dim screen") displayApp.PushMessage(Pinetime::Applications::Display::Messages::DimScreen); xTimerStart(idleTimer, 0); @@ -496,15 +578,17 @@ void SystemTask::OnDim() { } void SystemTask::OnIdle() { - if (doNotGoToSleep) + if (doNotGoToSleep) { return; + } NRF_LOG_INFO("Idle timeout -> Going to sleep") PushMessage(Messages::GoToSleep); } void SystemTask::ReloadIdleTimer() { - if (isSleeping || isGoingToSleep) + if (isSleeping || isGoingToSleep) { return; + } if (isDimmed) { displayApp.PushMessage(Pinetime::Applications::Display::Messages::RestoreBrightness); isDimmed = false; diff --git a/src/systemtask/SystemTask.h b/src/systemtask/SystemTask.h index 879c1be8..e2e6de7f 100644 --- a/src/systemtask/SystemTask.h +++ b/src/systemtask/SystemTask.h @@ -11,7 +11,7 @@ #include #include -#include "SystemMonitor.h" +#include "systemtask/SystemMonitor.h" #include "components/battery/BatteryController.h" #include "components/ble/NimbleController.h" #include "components/ble/NotificationManager.h" @@ -20,6 +20,8 @@ #include "components/alarm/AlarmController.h" #include "components/fs/FS.h" #include "touchhandler/TouchHandler.h" +#include "buttonhandler/ButtonHandler.h" +#include "buttonhandler/ButtonActions.h" #ifdef PINETIME_IS_RECOVERY #include "displayapp/DisplayAppRecovery.h" @@ -31,7 +33,7 @@ #endif #include "drivers/Watchdog.h" -#include "Messages.h" +#include "systemtask/Messages.h" extern std::chrono::time_point NoInit_BackUpTime; namespace Pinetime { @@ -45,6 +47,7 @@ namespace Pinetime { } namespace Controllers { class TouchHandler; + class ButtonHandler; } namespace System { class SystemTask { @@ -71,12 +74,12 @@ namespace Pinetime { Pinetime::Applications::DisplayApp& displayApp, Pinetime::Applications::HeartRateTask& heartRateApp, Pinetime::Controllers::FS& fs, - Pinetime::Controllers::TouchHandler& touchHandler); + Pinetime::Controllers::TouchHandler& touchHandler, + Pinetime::Controllers::ButtonHandler& buttonHandler); void Start(); void PushMessage(Messages msg); - void OnButtonPushed(); void OnTouchEvent(); void OnIdle(); @@ -123,6 +126,7 @@ namespace Pinetime { Pinetime::Applications::HeartRateTask& heartRateApp; Pinetime::Controllers::FS& fs; Pinetime::Controllers::TouchHandler& touchHandler; + Pinetime::Controllers::ButtonHandler& buttonHandler; Pinetime::Controllers::NimbleController nimbleController; static void Process(void* instance); @@ -135,6 +139,9 @@ namespace Pinetime { TimerHandle_t measureBatteryTimer; bool doNotGoToSleep = false; + void HandleButtonAction(Controllers::ButtonActions action); + bool fastWakeUpDone = false; + void GoToRunning(); void UpdateMotion(); bool stepCounterMustBeReset = false; diff --git a/src/touchhandler/TouchHandler.cpp b/src/touchhandler/TouchHandler.cpp index 735b311a..0be33476 100644 --- a/src/touchhandler/TouchHandler.cpp +++ b/src/touchhandler/TouchHandler.cpp @@ -1,4 +1,4 @@ -#include "TouchHandler.h" +#include "touchhandler/TouchHandler.h" using namespace Pinetime::Controllers; diff --git a/src/touchhandler/TouchHandler.h b/src/touchhandler/TouchHandler.h index f5442939..ed452b3a 100644 --- a/src/touchhandler/TouchHandler.h +++ b/src/touchhandler/TouchHandler.h @@ -1,8 +1,6 @@ #pragma once #include "drivers/Cst816s.h" #include "systemtask/SystemTask.h" -#include -#include namespace Pinetime { namespace Components { @@ -11,9 +9,6 @@ namespace Pinetime { namespace Drivers { class Cst816S; } - namespace System { - class SystemTask; - } namespace Controllers { class TouchHandler { public: