Compare commits

..

7 commits

Author SHA1 Message Date
Djuri Baars
684cd7e05c Restore all variants
Some checks failed
/ build (push) Successful in 14m46s
/ merge (map[name:btclock_rev_b version:esp32s3], 213epd) (push) Successful in 28s
/ merge (map[name:btclock_v8 version:esp32s3], 213epd) (push) Successful in 26s
/ merge (map[name:lolin_s3_mini version:esp32s3], 213epd) (push) Successful in 25s
/ merge (map[name:lolin_s3_mini version:esp32s3], 29epd) (push) Successful in 25s
/ release (push) Failing after 24s
2024-11-26 19:58:10 +01:00
Djuri Baars
d3725d6ae1 Disable more
Some checks failed
/ build (push) Successful in 9m30s
/ merge (map[name:lolin_s3_mini version:esp32s3], 213epd) (push) Successful in 26s
/ merge (map[name:lolin_s3_mini version:esp32s3], 29epd) (push) Successful in 24s
/ release (push) Failing after 19s
2024-11-26 19:42:36 +01:00
Djuri Baars
b26ca1e760 Try with less targets
Some checks failed
/ build (push) Successful in 9m31s
/ merge (map[name:btclock_rev_b version:esp32s3], 213epd) (push) Failing after 25s
/ merge (map[name:btclock_v8 version:esp32s3], 213epd) (push) Failing after 21s
/ merge (map[name:lolin_s3_mini version:esp32s3], 213epd) (push) Successful in 25s
/ merge (map[name:lolin_s3_mini version:esp32s3], 29epd) (push) Successful in 25s
/ release (push) Has been skipped
2024-11-26 19:29:37 +01:00
Djuri Baars
25dcf444c2 Add platformio and node_modules cache
Some checks failed
/ build (push) Successful in 18m40s
/ merge (map[name:btclock_rev_b version:esp32s3], 213epd) (push) Successful in 27s
/ merge (map[name:btclock_v8 version:esp32s3], 213epd) (push) Successful in 25s
/ merge (map[name:lolin_s3_mini version:esp32s3], 213epd) (push) Successful in 25s
/ merge (map[name:lolin_s3_mini version:esp32s3], 29epd) (push) Successful in 25s
/ release (push) Failing after 3s
2024-11-26 19:03:48 +01:00
Djuri Baars
e44d686218 Fix release step
Some checks failed
/ build (push) Successful in 19m48s
/ merge (map[name:btclock_rev_b version:esp32s3], 213epd) (push) Successful in 24s
/ merge (map[name:btclock_v8 version:esp32s3], 213epd) (push) Successful in 25s
/ merge (map[name:lolin_s3_mini version:esp32s3], 213epd) (push) Successful in 25s
/ merge (map[name:lolin_s3_mini version:esp32s3], 29epd) (push) Successful in 25s
/ release (push) Failing after 37s
2024-11-26 18:37:50 +01:00
Djuri Baars
44a6c44e7a Remove report action
Some checks failed
/ build (push) Successful in 20m46s
/ merge (map[name:btclock_rev_b version:esp32s3], 213epd) (push) Successful in 2m16s
/ merge (map[name:btclock_v8 version:esp32s3], 213epd) (push) Successful in 25s
/ merge (map[name:lolin_s3_mini version:esp32s3], 213epd) (push) Successful in 20s
/ merge (map[name:lolin_s3_mini version:esp32s3], 29epd) (push) Successful in 20s
/ release (push) Failing after 8s
2024-11-26 18:08:54 +01:00
Djuri Baars
2a3c0a7911 Add Forgejo CI action
Some checks failed
/ build (push) Failing after 3s
/ merge (map[name:btclock_rev_b version:esp32s3], 213epd) (push) Has been skipped
/ merge (map[name:btclock_v8 version:esp32s3], 213epd) (push) Has been skipped
/ merge (map[name:lolin_s3_mini version:esp32s3], 213epd) (push) Has been skipped
/ merge (map[name:lolin_s3_mini version:esp32s3], 29epd) (push) Has been skipped
/ release (push) Has been skipped
2024-11-26 18:07:47 +01:00
61 changed files with 1444 additions and 2309 deletions

View file

@ -1,9 +1,9 @@
name: "BTClock CI"
on:
push:
tags:
- "*"
branches:
- 'feature/forgejo-ci'
workflow_dispatch:
jobs:
@ -22,7 +22,7 @@ jobs:
with:
node-version: lts/*
cache: yarn
cache-dependency-path: "**/yarn.lock"
cache-dependency-path: '**/yarn.lock'
- uses: actions/cache@v4
with:
path: |
@ -34,8 +34,8 @@ jobs:
key: ${{ runner.os }}-pio
- uses: actions/setup-python@v5
with:
python-version: "3.9"
cache: "pip"
python-version: '3.9'
cache: 'pip'
- name: Get current date
id: dateAndTime
shell: bash
@ -48,7 +48,7 @@ jobs:
run: mkdir -p junit-reports && pio test -e native_test_only --junit-output-path junit-reports/
- name: Build BTClock firmware
shell: bash
run: pio run
run: pio run
- name: Build BTClock filesystem
shell: bash
run: pio run --target buildfs
@ -81,9 +81,9 @@ jobs:
version: esp32s3
epd_variant: [213epd, 29epd]
exclude:
- chip: { name: btclock_rev_b, version: esp32s3 }
- chip: {name: btclock_rev_b, version: esp32s3}
epd_variant: 29epd
- chip: { name: btclock_v8, version: esp32s3 }
- chip: {name: btclock_v8, version: esp32s3}
epd_variant: 29epd
steps:
- uses: https://code.forgejo.org/forgejo/download-artifact@v4
@ -93,10 +93,9 @@ jobs:
- name: Install esptools.py
run: pip install --upgrade esptool
- name: Create merged firmware binary
shell: bash
run: |
mkdir -p ${{ matrix.chip.name }}_${{ matrix.epd_variant }}
if [ "${{ matrix.chip.name }}" == "btclock_v8" ]; then
mkdir -p ${{ matrix.chip.name }}_${{ matrix.epd_variant }} && \
esptool.py --chip ${{ matrix.chip.version }} merge_bin \
-o ${{ matrix.chip.name }}_${{ matrix.epd_variant }}/${{ matrix.chip.name }}_${{ matrix.epd_variant }}.bin \
--flash_mode dio \
@ -106,19 +105,10 @@ jobs:
0x8000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/partitions.bin \
0xe000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/ota_data_initial.bin \
0x10000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/firmware.bin \
0xDF0000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/littlefs_16MB.bin
elif [ "${{ matrix.chip.name }}" == "btclock_rev_b" ]; then
esptool.py --chip ${{ matrix.chip.version }} merge_bin \
-o ${{ matrix.chip.name }}_${{ matrix.epd_variant }}/${{ matrix.chip.name }}_${{ matrix.epd_variant }}.bin \
--flash_mode dio \
--flash_freq 80m \
--flash_size 8MB \
0x0000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/bootloader.bin \
0x8000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/partitions.bin \
0xe000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/ota_data_initial.bin \
0x10000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/firmware.bin \
0x6F0000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/littlefs_8MB.bin;
0x810000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/littlefs.bin;
else
# Original command for other cases
mkdir -p ${{ matrix.chip.name }}_${{ matrix.epd_variant }} && \
esptool.py --chip ${{ matrix.chip.version }} merge_bin \
-o ${{ matrix.chip.name }}_${{ matrix.epd_variant }}/${{ matrix.chip.name }}_${{ matrix.epd_variant }}.bin \
--flash_mode dio \
@ -126,26 +116,19 @@ jobs:
0x8000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/partitions.bin \
0xe000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/ota_data_initial.bin \
0x10000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/firmware.bin \
0x380000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/littlefs_4MB.bin
0x369000 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/littlefs.bin
# Adjust the offset for littlefs or other files as needed for the original case
fi
- name: Create checksum for firmware
shell: bash
run: shasum -a 256 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/firmware.bin | awk '{print $1}' > ${{ matrix.chip.name }}_${{ matrix.epd_variant }}/${{ matrix.chip.name }}_${{ matrix.epd_variant }}_firmware.bin.sha256
- name: Create checksum for merged binary
shell: bash
run: shasum -a 256 ${{ matrix.chip.name }}_${{ matrix.epd_variant }}/${{ matrix.chip.name }}_${{ matrix.epd_variant }}.bin | awk '{print $1}' > ${{ matrix.chip.name }}_${{ matrix.epd_variant }}/${{ matrix.chip.name }}_${{ matrix.epd_variant }}.bin.sha256
- name: Create checksum for littlefs partition
shell: bash
run: |
fs_file=$(find .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }} -name "littlefs*.bin")
echo $fs_file
fs_name=$(basename "$fs_file")
shasum -a 256 "$fs_file" | awk '{print $1}' > "${{ matrix.chip.name }}_${{ matrix.epd_variant }}/${fs_name}.sha256"
cat "${{ matrix.chip.name }}_${{ matrix.epd_variant }}/${fs_name}.sha256"
run: shasum -a 256 .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/littlefs.bin | awk '{print $1}' > ${{ matrix.chip.name }}_${{ matrix.epd_variant }}/littlefs.bin.sha256
- name: Copy all artifacts to output folder
run: cp .pio/build/${{ matrix.chip.name }}_${{ matrix.epd_variant }}/*.bin .pio/boot_app0.bin ${{ matrix.chip.name }}_${{ matrix.epd_variant }}
@ -178,13 +161,14 @@ jobs:
- name: Create release
uses: https://code.forgejo.org/actions/forgejo-release@v2.4.0
with:
url: "https://git.btclock.dev"
repo: "${{ github.repository }}"
url: 'https://git.btclock.dev'
repo: '${{ github.repository }}'
direction: upload
tag: "${{ github.ref_name }}"
sha: "${{ github.sha }}"
tag: '${{ github.ref_name }}'
sha: '${{ github.sha }}'
release-dir: release
token: ${{ secrets.TOKEN }}
override: ${{ github.ref_type != 'tag' && github.ref_name != 'main' }}
verbose: ${{ vars.VERBOSE || "false" }}
prerelease: ${{ github.ref_type != 'tag' && github.ref_name != 'main' }}
release-notes-assistant: false
release-notes-assistant: false

View file

@ -1,8 +1,6 @@
# BTClock v3
[![Latest release](https://git.btclock.dev/btclock/btclock_v3/badges/release.svg)](https://git.btclock.dev/btclock/btclock_v3/releases/latest)
[![BTClock CI](https://git.btclock.dev/btclock/btclock_v3/badges/workflows/push.yaml/badge.svg)](https://git.btclock.dev/btclock/btclock_v3/actions?workflow=push.yaml&actor=0&status=0)
[![BTClock CI](https://github.com/btclock/btclock_v3/actions/workflows/tagging.yml/badge.svg)](https://github.com/btclock/btclock_v3/actions/workflows/tagging.yml)
Software for the BTClock project.
@ -16,44 +14,15 @@ Biggest differences with v2 are:
New features:
- BitAxe integration
- Nostr Zap notifier
- Multiple mining pool stats integrations
- Zap notifier
-
"Steal focus on new block" means that when a new block is mined, the display will switch to the block height screen if it's not on it already.
See the [docs](https://git.btclock.dev/btclock/docs) repo for more information and building instructions.
Most [information](https://github.com/btclock/btclock_v2/wiki) about BTClock v2 is still valid for this version.
**NOTE**: The software assumes that the hardware is run in a controlled private network. ~~The Web UI and the OTA update mechanism are not password protected and accessible to anyone in the network. Also, since the device only fetches numbers through WebSockets it will skip server certificate verification to save resources.~~ Since 3.2.0 the WebUI is password protectable and all certificates are verified. OTA update mechanism is not password-protected.
## Building
Use PlatformIO to build it yourself. Make sure you fetch the [WebUI](https://git.btclock.dev/btclock/webui) submodule.
## Mining pool stats
Enable mining pool stats by accessing your btclock's web UI (point a web browser at the device's IP address).
Under Settings -> Extra Features: toggle Enable Mining Pool Stats.
New options will appear. Select your mining pool and enter your pool username (Ocean) or api key (Braiins).
The Mining Pool Earnings screen displays:
* Braiins: Today's mining reward thus far
* Ocean: Your estimated earnings if the pool were to find a block right now
For solo mining pools, there are no earning estimations. Your username is the onchain withdrawal address, without the worker name.
### Braiins Pool integration
Create an API key based on the steps [here](https://academy.braiins.com/en/braiins-pool/monitoring/#api-configuration).
The key's permissions should be:
* Web Access: no
* API Access: yes
* Access Permissions: Read-only
Copy the token that is created for the new key. Enter this as your "Mining Pool username or api key" in the btclock web UI.
### Ocean integration
Your "Mining Pool username" is just the onchain withdrawal address that you specify when pointing your miners at Ocean.
Use PlatformIO to build it yourself. Make sure you fetch the [WebUI](https://github.com/btclock/webui) submodule.

2
data

@ -1 +1 @@
Subproject commit 924be8fc2eb02fe384a20b53da1a9fa3d8db8a05
Subproject commit 5066032a55b5436ec5c888cf0eb91bdc9e71bea0

View file

@ -4,6 +4,6 @@ dependencies:
source:
type: idf
version: 4.4.7
manifest_hash: cd2f3ee15e776d949eb4ea4eddc8f39b30c2a7905050850eed01ab4928143cff
manifest_hash: 841ba2a95f4b32d39636bf4fdf07c48a2052f71c9728a5b7f263083a3b430a4f
target: esp32s3
version: 1.0.0

View file

@ -24,7 +24,7 @@ std::array<std::string, NUM_SCREENS> parseBitaxeHashRate(std::string text)
}
ret[NUM_SCREENS - 1] = "GH/S";
ret[0] = "mdi:bitaxe";
ret[0] = "BIT/AXE";
return ret;
}
@ -37,7 +37,7 @@ std::array<std::string, NUM_SCREENS> parseBitaxeBestDiff(std::string text)
if (text.length() < NUM_SCREENS)
{
text.insert(text.begin(), NUM_SCREENS - text.length(), ' ');
ret[0] = "mdi:bitaxe";
ret[0] = "BIT/AXE";
ret[1] = "mdi:rocket";
firstIndex = 2;
}

View file

@ -67,72 +67,33 @@ char getCurrencyChar(const std::string& input)
return CURRENCY_USD; // Assuming USD is the default for unknown inputs
}
std::array<std::string, NUM_SCREENS> parsePriceData(std::uint32_t price, char currencySymbol, bool useSuffixFormat, bool mowMode, bool shareDot)
std::array<std::string, NUM_SCREENS> parsePriceData(std::uint32_t price, char currencySymbol, bool useSuffixFormat)
{
std::array<std::string, NUM_SCREENS> ret;
std::string priceString;
if (std::to_string(price).length() >= NUM_SCREENS || useSuffixFormat)
{
int numScreens = shareDot || mowMode ? NUM_SCREENS - 1 : NUM_SCREENS - 2;
priceString = getCurrencySymbol(currencySymbol) + formatNumberWithSuffix(price, numScreens, mowMode);
priceString = getCurrencySymbol(currencySymbol) + formatNumberWithSuffix(price, NUM_SCREENS - 2);
}
else
{
priceString = getCurrencySymbol(currencySymbol) + std::to_string(price);
}
std::uint32_t firstIndex = 0;
if ((shareDot && priceString.length() <= (NUM_SCREENS)) || priceString.length() < (NUM_SCREENS))
if (priceString.length() < (NUM_SCREENS))
{
priceString.insert(priceString.begin(), NUM_SCREENS - priceString.length(), ' ');
if (mowMode)
{
ret[0] = "MOW/UNITS";
}
else
{
ret[0] = "BTC/" + getCurrencyCode(currencySymbol);
}
ret[0] = "BTC/" + getCurrencyCode(currencySymbol);
firstIndex = 1;
}
size_t dotPosition = priceString.find('.');
if (shareDot && dotPosition != std::string::npos && dotPosition > 0)
for (std::uint32_t i = firstIndex; i < NUM_SCREENS; i++)
{
std::vector<std::string> tempArray;
if (dotPosition != std::string::npos && dotPosition > 0)
{
for (size_t i = 0; i < priceString.length(); ++i)
{
if (i == dotPosition - 1)
{
tempArray.push_back(std::string(1, priceString[i]) + ".");
++i; // Skip the dot in the next iteration
}
else
{
tempArray.push_back(std::string(1, priceString[i]));
}
}
// Copy from tempArray to ret
for (std::uint32_t i = firstIndex; i < NUM_SCREENS && i - firstIndex < tempArray.size(); ++i)
{
ret[i] = tempArray[i - firstIndex];
}
}
ret[i] = priceString[i];
}
else
{
for (std::uint32_t i = firstIndex; i < NUM_SCREENS; i++)
{
ret[i] = std::string(1, priceString[i]);
}
}
return ret;
}
@ -146,26 +107,9 @@ std::array<std::string, NUM_SCREENS> parseSatsPerCurrency(std::uint32_t price,ch
if (priceString.length() < (NUM_SCREENS))
{
// Check if price is greater than 1 billion
if (price >= 100000000)
{
double satsPerCurrency = (1.0 / static_cast<double>(price)) * 1e8; // Calculate satoshis
std::ostringstream oss;
oss << std::fixed << std::setprecision(3) << satsPerCurrency; // Format with 3 decimal places
priceString = oss.str();
}
else
{
priceString = std::to_string(static_cast<int>(round(1.0 / static_cast<double>(price) * 1e8))); // Default formatting
}
priceString.insert(priceString.begin(), NUM_SCREENS - priceString.length(), ' ');
// Pad the string with spaces if necessary
if (priceString.length() < NUM_SCREENS)
{
priceString.insert(priceString.begin(), NUM_SCREENS - priceString.length(), ' ');
}
if (currencySymbol != CURRENCY_USD || price >= 100000000) // no time anymore when earlier than 1
if (currencySymbol != CURRENCY_USD)
ret[0] = "SATS/" + getCurrencyCode(currencySymbol);
else
ret[0] = "MSCW/TIME";
@ -348,9 +292,9 @@ emscripten::val parseBlockHeightArray(std::uint32_t blockHeight)
return arrayToStringArray(parseBlockHeight(blockHeight));
}
emscripten::val parsePriceDataArray(std::uint32_t price, const std::string &currencySymbol, bool useSuffixFormat = false, bool mowMode = false, bool shareDot = false)
emscripten::val parsePriceDataArray(std::uint32_t price, const std::string &currencySymbol, bool useSuffixFormat = false)
{
return arrayToStringArray(parsePriceData(price, currencySymbol[0], useSuffixFormat, mowMode, shareDot));
return arrayToStringArray(parsePriceData(price, currencySymbol[0], useSuffixFormat));
}
emscripten::val parseHalvingCountdownArray(std::uint32_t blockHeight, bool asBlocks)

View file

@ -2,7 +2,6 @@
#include <string>
#include <cmath>
#include <cstdint>
#include <vector>
#include "utils.hpp"
@ -20,7 +19,7 @@ const std::string CURRENCY_CODE_JPY = "JPY";
const std::string CURRENCY_CODE_AUD = "AUD";
const std::string CURRENCY_CODE_CAD = "CAD";
std::array<std::string, NUM_SCREENS> parsePriceData(std::uint32_t price, char currency, bool useSuffixFormat = false, bool mowMode = false, bool shareDot = false);
std::array<std::string, NUM_SCREENS> parsePriceData(std::uint32_t price, char currency, bool useSuffixFormat = false);
std::array<std::string, NUM_SCREENS> parseSatsPerCurrency(std::uint32_t price, char currencySymbol, bool withSatsSymbol);
std::array<std::string, NUM_SCREENS> parseBlockHeight(std::uint32_t blockHeight);
std::array<std::string, NUM_SCREENS> parseHalvingCountdown(std::uint32_t blockHeight, bool asBlocks);

View file

@ -28,12 +28,7 @@ double getSupplyAtBlock(std::uint32_t blockNr)
return totalBitcoinInCirculation;
}
std::string formatNumberWithSuffix(std::uint64_t num, int numCharacters)
{
return formatNumberWithSuffix(num, numCharacters, false);
}
std::string formatNumberWithSuffix(std::uint64_t num, int numCharacters, bool mowMode)
std::string formatNumberWithSuffix(std::uint64_t num, int numCharacters)
{
static char result[20]; // Adjust size as needed
const long long quadrillion = 1000000000000000LL;
@ -61,53 +56,30 @@ std::string formatNumberWithSuffix(std::uint64_t num, int numCharacters, bool mo
numDouble /= billion;
suffix = 'B';
}
else if (num >= million || numDigits > 6 || (mowMode && num >= thousand))
else if (num >= million || numDigits > 6)
{
numDouble /= million;
suffix = 'M';
}
else if (!mowMode && (num >= thousand || numDigits > 3))
else if (num >= thousand || numDigits > 3)
{
numDouble /= thousand;
suffix = 'K';
}
else if (!mowMode)
else
{
snprintf(result, sizeof(result), "%llu", (unsigned long long)num);
// sprintf(result, "%llu", (unsigned long long)num);
return result;
}
else // mowMode is true and num < 1000
{
numDouble /= million;
suffix = 'M';
}
// Add suffix
int len;
int len = snprintf(result, sizeof(result), "%.0f%c", numDouble, suffix);
// Mow Mode always uses string truncation to avoid rounding
std::string mowAsString = std::to_string(numDouble);
if (mowMode) {
// Default to one decimal place
len = snprintf(result, sizeof(result), "%s%c", mowAsString.substr(0, mowAsString.find(".") + 2).c_str(), suffix);
}
else
{
len = snprintf(result, sizeof(result), "%.0f%c", numDouble, suffix);
}
// If there's room, add more decimal places
// If there's room, add decimal places
if (len < numCharacters)
{
int restLen = mowMode ? numCharacters - len : numCharacters - len - 1;
if (mowMode) {
snprintf(result, sizeof(result), "%s%c", mowAsString.substr(0, mowAsString.find(".") + 2 + restLen).c_str(), suffix);
}
else
{
snprintf(result, sizeof(result), "%.*f%c", restLen, numDouble, suffix);
}
snprintf(result, sizeof(result), "%.*f%c", numCharacters - len - 1, numDouble, suffix);
}
return result;
@ -164,82 +136,3 @@ int64_t getAmountInSatoshis(std::string bolt11) {
return satoshis;
}
void parseHashrateString(const std::string& hashrate, std::string& label, std::string& output, unsigned int maxCharacters) {
// Handle empty string or "0" cases
if (hashrate.empty() || hashrate == "0") {
label = "H/S";
output = "0";
return;
}
size_t suffixLength = 0;
if (hashrate.length() > 21) {
label = "ZH/S";
suffixLength = 21;
} else if (hashrate.length() > 18) {
label = "EH/S";
suffixLength = 18;
} else if (hashrate.length() > 15) {
label = "PH/S";
suffixLength = 15;
} else if (hashrate.length() > 12) {
label = "TH/S";
suffixLength = 12;
} else if (hashrate.length() > 9) {
label = "GH/S";
suffixLength = 9;
} else if (hashrate.length() > 6) {
label = "MH/S";
suffixLength = 6;
} else if (hashrate.length() > 3) {
label = "KH/S";
suffixLength = 3;
} else {
label = "H/S";
suffixLength = 0;
}
double value = std::stod(hashrate) / std::pow(10, suffixLength);
// Calculate integer part length
int integerPartLength = std::to_string(static_cast<int>(value)).length();
// Calculate remaining space for decimals
int remainingSpace = maxCharacters - integerPartLength;
char buffer[32];
if (remainingSpace <= 0)
{
// No space for decimals, just round to integer
snprintf(buffer, sizeof(buffer), "%.0f", value);
}
else
{
// Space for decimal point and some decimals
snprintf(buffer, sizeof(buffer), "%.*f", remainingSpace - 1, value);
}
// Remove trailing zeros and decimal point if necessary
output = buffer;
if (output.find('.') != std::string::npos)
{
output = output.substr(0, output.find_last_not_of('0') + 1);
if (output.back() == '.')
{
output.pop_back();
}
}
}
int getHashrateMultiplier(char unit) {
if (unit == '0')
return 0;
static const std::unordered_map<char, int> multipliers = {
{'Z', 21}, {'E', 18}, {'P', 15}, {'T', 12},
{'G', 9}, {'M', 6}, {'K', 3}
};
return multipliers.at(unit);
}

View file

@ -5,15 +5,10 @@
#include <cstdint>
#include <sstream>
#include <iomanip>
#include <unordered_map>
int modulo(int x,int N);
double getSupplyAtBlock(std::uint32_t blockNr);
std::string formatNumberWithSuffix(std::uint64_t num, int numCharacters = 4);
std::string formatNumberWithSuffix(std::uint64_t num, int numCharacters, bool mowMode);
int64_t getAmountInSatoshis(std::string bolt11);
void parseHashrateString(const std::string& hashrate, std::string& label, std::string& output, unsigned int maxCharacters);
int getHashrateMultiplier(char unit);
int64_t getAmountInSatoshis(std::string bolt11);

View file

@ -1,20 +0,0 @@
identifier: BTClock
maintainers:
- npub1k5f85zx0xdskyayqpfpc0zq6n7vwqjuuxugkayk72fgynp34cs3qfcvqg2
relays:
- wss://relay.noderunners.network/
- wss://nostr.sathoarder.com/
- wss://offchain.pub/
- wss://nostr3.daedaluslabs.io/
- wss://nostr4.daedaluslabs.io/
- wss://nostr.dbtc.link/
- wss://purplepag.es/
- wss://nos.lol/
- wss://nostr1.daedaluslabs.io/
- wss://nostr.noderunners.network/
- wss://nostr.lnbitcoin.cz/
- wss://relay.primal.net/
- wss://relay.damus.io
- wss://nostr-relay.derekross.me/
- wss://nostr2.azzamo.net/
- wss://nostr2.daedaluslabs.io/

View file

@ -1,7 +1,7 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x1b8000,
app1, app, ota_1, , 0x1b8000,
spiffs, data, spiffs, , 0x66C00,
coredump, data, coredump,, 0x10000,
nvs, data, nvs, 36K, 20K,
otadata, data, ota, 56K, 8K,
app0, app, ota_0, 64K, 1740K,
app1, app, ota_1, , 1740K,
spiffs, data, spiffs, , 400K,
coredump, data, coredump,, 64K,

1 # Name Type SubType Offset Size Flags
2 nvs data nvs 0x9000 36K 0x5000 20K
3 otadata data ota 0xe000 56K 0x2000 8K
4 app0 app ota_0 0x10000 64K 0x1b8000 1740K
5 app1 app ota_1 0x1b8000 1740K
6 spiffs data spiffs 0x66C00 400K
7 coredump data coredump 0x10000 64K

View file

@ -1,7 +1,7 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x6F0000,
app1, app, ota_1, , 0x6F0000,
spiffs, data, spiffs, , 0x200000,
coredump, data, coredump,, 0x10000,
nvs, data, nvs, 36K, 20K,
otadata, data, ota, 56K, 8K,
app0, app, ota_0, 64K, 4096K,
app1, app, ota_1, , 4096K,
spiffs, data, spiffs, , 400K,
coredump, data, coredump,, 64K,

1 # Name Type SubType Offset Size Flags
2 nvs data nvs 0x9000 36K 0x5000 20K
3 otadata data ota 0xe000 56K 0x2000 8K
4 app0 app ota_0 0x10000 64K 0x6F0000 4096K
5 app1 app ota_1 0x6F0000 4096K
6 spiffs data spiffs 0x200000 400K
7 coredump data coredump 0x10000 64K

View file

@ -1,7 +1,7 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x370000,
app1, app, ota_1, , 0x370000,
spiffs, data, spiffs, , 0xCD000,
coredump, data, coredump,, 0x10000,
nvs, data, nvs, 36K, 20K,
otadata, data, ota, 56K, 8K,
app0, app, ota_0, 64K, 1700K,
app1, app, ota_1, , 1700K,
spiffs, data, spiffs, , 400K,
coredump, data, coredump,, 64K,

1 # Name Type SubType Offset Size Flags
2 nvs data nvs 0x9000 36K 0x5000 20K
3 otadata data ota 0xe000 56K 0x2000 8K
4 app0 app ota_0 0x10000 64K 0x370000 1700K
5 app1 app ota_1 0x370000 1700K
6 spiffs data spiffs 0xCD000 400K
7 coredump data coredump 0x10000 64K

View file

@ -7,137 +7,119 @@
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[platformio]
data_dir = data/build_gz
default_envs = lolin_s3_mini_213epd, lolin_s3_mini_29epd, btclock_rev_b_213epd, btclock_v8_213epd
[env]
[btclock_base]
platform = espressif32 @ ^6.9.0
framework = arduino, espidf
framework = arduino, espidf
monitor_speed = 115200
monitor_filters = esp32_exception_decoder, colorize
board_build.filesystem = littlefs
extra_scripts = pre:scripts/pre_script.py, post:scripts/extra_script.py
platform_packages =
earlephilhower/tool-mklittlefs-rp2040-earlephilhower
board_build.embed_files =
x509_crt_bundle
build_flags =
!python scripts/git_rev.py
-DLAST_BUILD_TIME=$UNIX_TIME
-DARDUINO_USB_CDC_ON_BOOT
-DCORE_DEBUG_LEVEL=0
-fexceptions
extra_scripts = post:scripts/extra_script.py
board_build.embed_files = x509_crt_bundle
build_flags =
!python scripts/git_rev.py
-DLAST_BUILD_TIME=$UNIX_TIME
-DARDUINO_USB_CDC_ON_BOOT
-DCORE_DEBUG_LEVEL=0
-fexceptions
build_unflags =
-Werror=all
-fno-exceptions
-Werror=all
-fno-exceptions
lib_deps =
https://github.com/joltwallet/esp_littlefs.git
bblanchon/ArduinoJson@^7.2.1
mathieucarbou/ESPAsyncWebServer @ 3.3.23
robtillaart/MCP23017@^0.8.0
adafruit/Adafruit NeoPixel@^1.12.3
https://github.com/dsbaars/universal_pin#feature/mcp23017_rt
https://github.com/dsbaars/GxEPD2#universal_pin
https://github.com/tzapu/WiFiManager.git#v2.0.17
rblb/Nostrduino@1.2.8
https://github.com/joltwallet/esp_littlefs.git
bblanchon/ArduinoJson@^7.2.0
mathieucarbou/ESPAsyncWebServer @ 3.3.7
adafruit/Adafruit BusIO@^1.16.1
adafruit/Adafruit MCP23017 Arduino Library@^2.3.2
adafruit/Adafruit NeoPixel@^1.12.3
https://github.com/dsbaars/universal_pin
https://github.com/dsbaars/GxEPD2#universal_pin
https://github.com/tzapu/WiFiManager.git#v2.0.17
rblb/Nostrduino@1.2.8
[env:lolin_s3_mini]
extends = btclock_base
board = lolin_s3_mini
board_build.partitions = partition.csv
build_flags =
${btclock_base.build_flags}
-D MCP_INT_PIN=8
-D NEOPIXEL_PIN=34
-D NEOPIXEL_COUNT=4
-D NUM_SCREENS=7
-D I2C_SDA_PIN=35
-D I2C_SCK_PIN=36
-DARDUINO_USB_CDC_ON_BOOT=1
-D IS_HW_REV_A
build_flags =
${btclock_base.build_flags}
-D MCP_INT_PIN=8
-D NEOPIXEL_PIN=34
-D NEOPIXEL_COUNT=4
-D NUM_SCREENS=7
-D I2C_SDA_PIN=35
-D I2C_SCK_PIN=36
-DARDUINO_USB_CDC_ON_BOOT=1
-D IS_HW_REV_A
build_unflags =
${btclock_base.build_unflags}
platform_packages =
platformio/tool-mklittlefs@^1.203.210628
earlephilhower/tool-mklittlefs-rp2040-earlephilhower@^5.100300.230216
${btclock_base.build_unflags}
[env:btclock_rev_b]
extends = btclock_base
board = btclock_rev_b
board_build.partitions = partition_8mb.csv
build_flags =
${btclock_base.build_flags}
-D MCP_INT_PIN=8
-D NEOPIXEL_PIN=15
-D NEOPIXEL_COUNT=4
-D NUM_SCREENS=7
-D I2C_SDA_PIN=35
-D I2C_SCK_PIN=36
-D HAS_FRONTLIGHT
-D PCA_OE_PIN=45
-D PCA_I2C_ADDR=0x42
-D IS_HW_REV_B
board_build.partitions = partition.csv
build_flags =
${btclock_base.build_flags}
-D MCP_INT_PIN=8
-D NEOPIXEL_PIN=15
-D NEOPIXEL_COUNT=4
-D NUM_SCREENS=7
-D I2C_SDA_PIN=35
-D I2C_SCK_PIN=36
-D HAS_FRONTLIGHT
-D PCA_OE_PIN=45
-D PCA_I2C_ADDR=0x42
-D IS_HW_REV_B
lib_deps =
${btclock_base.lib_deps}
robtillaart/PCA9685@^0.7.1
claws/BH1750@^1.3.0
${btclock_base.lib_deps}
robtillaart/PCA9685@^0.7.1
claws/BH1750@^1.3.0
build_unflags =
${btclock_base.build_unflags}
platform_packages =
platformio/tool-mklittlefs@^1.203.210628
earlephilhower/tool-mklittlefs-rp2040-earlephilhower@^5.100300.230216
${btclock_base.build_unflags}
[env:lolin_s3_mini_213epd]
extends = env:lolin_s3_mini
test_framework = unity
build_flags =
${env:lolin_s3_mini.build_flags}
-D USE_QR
-D VERSION_EPD_2_13
-D HW_REV=\"REV_A_EPD_2_13\"
platform_packages =
platformio/tool-mklittlefs@^1.203.210628
earlephilhower/tool-mklittlefs-rp2040-earlephilhower@^5.100300.230216
build_flags =
${env:lolin_s3_mini.build_flags}
-D USE_QR
-D VERSION_EPD_2_13
-D HW_REV=\"REV_A_EPD_2_13\"
[env:btclock_rev_b_213epd]
extends = env:btclock_rev_b
test_framework = unity
build_flags =
${env:btclock_rev_b.build_flags}
-D USE_QR
-D VERSION_EPD_2_13
-D HW_REV=\"REV_B_EPD_2_13\"
platform_packages =
platformio/tool-mklittlefs@^1.203.210628
earlephilhower/tool-mklittlefs-rp2040-earlephilhower@^5.100300.230216
build_flags =
${env:btclock_rev_b.build_flags}
-D USE_QR
-D VERSION_EPD_2_13
-D HW_REV=\"REV_B_EPD_2_13\"
[env:lolin_s3_mini_29epd]
extends = env:lolin_s3_mini
test_framework = unity
build_flags =
${env:lolin_s3_mini.build_flags}
-D USE_QR
-D VERSION_EPD_2_9
-D HW_REV=\"REV_A_EPD_2_9\"
platform_packages =
platformio/tool-mklittlefs@^1.203.210628
earlephilhower/tool-mklittlefs-rp2040-earlephilhower@^5.100300.230216
build_flags =
${env:lolin_s3_mini.build_flags}
-D USE_QR
-D VERSION_EPD_2_9
-D HW_REV=\"REV_A_EPD_2_9\"
[env:btclock_rev_b_29epd]
extends = env:btclock_rev_b
test_framework = unity
build_flags =
${env:btclock_rev_b.build_flags}
-D USE_QR
-D VERSION_EPD_2_9
-D HW_REV=\"REV_B_EPD_2_9\"
platform_packages =
platformio/tool-mklittlefs@^1.203.210628
earlephilhower/tool-mklittlefs-rp2040-earlephilhower@^5.100300.230216
build_flags =
${env:btclock_rev_b.build_flags}
-D USE_QR
-D VERSION_EPD_2_9
-D HW_REV=\"REV_B_EPD_2_9\"
[env:btclock_v8]
extends = btclock_base
@ -145,52 +127,41 @@ board = btclock_v8
board_build.partitions = partition_16mb.csv
board_build.flash_mode = qio
test_framework = unity
build_flags =
${btclock_base.build_flags}
-D MCP_INT_PIN=4
-D NEOPIXEL_PIN=5
-D NEOPIXEL_COUNT=4
-D NUM_SCREENS=8
-D SPI_SDA_PIN=11
-D SPI_SCK_PIN=12
-D I2C_SDA_PIN=1
-D I2C_SCK_PIN=2
-D MCP_RESET_PIN=21
-D MCP1_A0_PIN=6
-D MCP1_A1_PIN=7
-D MCP1_A2_PIN=8
-D MCP2_A0_PIN=9
-D MCP2_A1_PIN=10
-D MCP2_A2_PIN=14
build_flags =
${btclock_base.build_flags}
-D MCP_INT_PIN=4
-D NEOPIXEL_PIN=5
-D NEOPIXEL_COUNT=4
-D NUM_SCREENS=8
-D SPI_SDA_PIN=11
-D SPI_SCK_PIN=12
-D I2C_SDA_PIN=1
-D I2C_SCK_PIN=2
-D MCP_RESET_PIN=21
-D MCP1_A0_PIN=6
-D MCP1_A1_PIN=7
-D MCP1_A2_PIN=8
-D MCP2_A0_PIN=9
-D MCP2_A1_PIN=10
-D MCP2_A2_PIN=14
build_unflags =
${btclock_base.build_unflags}
platform_packages =
platformio/tool-mklittlefs@^1.203.210628
earlephilhower/tool-mklittlefs-rp2040-earlephilhower@^5.100300.230216
${btclock_base.build_unflags}
[env:btclock_v8_213epd]
extends = env:btclock_v8
test_framework = unity
build_flags =
${env:btclock_v8.build_flags}
-D USE_QR
-D VERSION_EPD_2_13
-D HW_REV=\"REV_V8_EPD_2_13\"
platform_packages =
platformio/tool-mklittlefs@^1.203.210628
earlephilhower/tool-mklittlefs-rp2040-earlephilhower@^5.100300.230216
build_flags =
${env:btclock_v8.build_flags}
-D USE_QR
-D VERSION_EPD_2_13
-D HW_REV=\"REV_V8_EPD_2_13\"
[env:native_test_only]
platform = native
test_framework = unity
build_flags =
${btclock_base.build_flags}
-D MCP_INT_PIN=8
-D NEOPIXEL_PIN=34
-D NEOPIXEL_COUNT=4
-D NUM_SCREENS=7
-D UNITY_TEST
-std=gnu++17
platform_packages =
platformio/tool-mklittlefs@^1.203.210628
earlephilhower/tool-mklittlefs-rp2040-earlephilhower@^5.100300.230216
build_flags =
${btclock_base.build_flags}
-D MCP_INT_PIN=8
-D NEOPIXEL_PIN=34
-D NEOPIXEL_COUNT=4
-D NUM_SCREENS=7

View file

@ -1 +0,0 @@
platformio

View file

@ -1,13 +1,10 @@
Import("env")
import os
import gzip
from shutil import copyfileobj, rmtree, copyfile, copytree
from shutil import copyfileobj, rmtree
from pathlib import Path
import subprocess
revision = (
subprocess.check_output(["git", "rev-parse", "HEAD"])
.strip()
@ -29,7 +26,7 @@ def process_directory(input_dir, output_dir):
Path(output_root).mkdir(parents=True, exist_ok=True)
for file in files:
# if not file.endswith(('.bin')):
# if file.endswith(('.html', '.css', '.js')):
input_file_path = os.path.join(root, file)
output_file_path = os.path.join(output_root, file + '.gz')
gzip_file(input_file_path, output_file_path)
@ -41,85 +38,10 @@ def process_directory(input_dir, output_dir):
# Build web interface before building FS
def before_buildfs(source, target, env):
env.Execute("cd data && yarn && yarn postinstall && yarn build")
input_directory = 'data/dist'
output_directory = 'data/build_gz'
# copytree("assets", "data/dist/assets")
process_directory(input_directory, output_directory)
def get_fs_partition_size(env):
import csv
# Get partition table path - first try custom, then default
board_config = env.BoardConfig()
partition_table = board_config.get("build.partitions", "default.csv")
# Handle default partition table path
if partition_table == "default.csv" or partition_table == "huge_app.csv":
partition_table = os.path.join(env.PioPlatform().get_package_dir("framework-arduinoespressif32"),
"tools", "partitions", partition_table)
# Parse CSV to find spiffs/littlefs partition
with open(partition_table, 'r') as f:
for row in csv.reader(f):
if len(row) < 5:
continue
# Remove comments and whitespace
row = [cell.strip().split('#')[0] for cell in row]
# Check if this is a spiffs or littlefs partition
if row[0].startswith(('spiffs', 'littlefs')):
# Size is in hex format
return int(row[4], 16)
return 0
def get_littlefs_used_size(binary_path):
mklittlefs_path = os.path.join(env.PioPlatform().get_package_dir("tool-mklittlefs-rp2040-earlephilhower"), "mklittlefs")
try:
result = subprocess.run([mklittlefs_path, '-l', binary_path], capture_output=True, text=True)
if result.returncode == 0:
# Parse the output to sum up file sizes
total_size = 0
for line in result.stdout.splitlines():
if line.strip() and not line.startswith('<dir>') and not line.startswith('Creation'):
# Each line format: size filename
size = line.split()[0]
total_size += int(size)
return total_size
except Exception as e:
print(f"Error getting filesystem size: {e}")
return 0
def after_littlefs(source, target, env):
binary_path = str(target[0])
partition_size = get_fs_partition_size(env)
used_size = get_littlefs_used_size(binary_path)
percentage = (used_size / partition_size) * 100
bar_width = 50
filled = int(bar_width * percentage / 100)
bar = '=' * filled + '-' * (bar_width - filled)
print(f"\nLittleFS Actual Usage: [{bar}] {percentage:.1f}% ({used_size}/{partition_size} bytes)")
flash_size = env.BoardConfig().get("upload.flash_size", "4MB")
fs_image_name = f"littlefs_{flash_size}"
env.Replace(ESP32_FS_IMAGE_NAME=fs_image_name)
env.Replace(ESP8266_FS_IMAGE_NAME=fs_image_name)
os.environ["PUBLIC_BASE_URL"] = ""
fs_name = env.get("ESP32_FS_IMAGE_NAME", "littlefs.bin")
# Or alternatively:
# fs_name = env.get("FSTOOLNAME", "littlefs.bin")
# Use the variable in the pre-action
env.AddPreAction(f"$BUILD_DIR/{fs_name}.bin", before_buildfs)
env.AddPostAction(f"$BUILD_DIR/{fs_name}.bin", after_littlefs)
# LittleFS Actual Usage: [==============================--------------------] 60.4% (254165/420864 bytes)
# LittleFS Actual Usage: [==============================--------------------] 60.2% (253476/420864 bytes)
# 372736 used
env.AddPreAction("$BUILD_DIR/littlefs.bin", before_buildfs)

View file

@ -1,7 +0,0 @@
Import("env")
flash_size = env.BoardConfig().get("upload.flash_size", "4MB")
fs_image_name = f"littlefs_{flash_size}"
env.Replace(ESP32_FS_IMAGE_NAME=fs_image_name)
env.Replace(ESP8266_FS_IMAGE_NAME=fs_image_name)

File diff suppressed because it is too large Load diff

View file

@ -2,7 +2,7 @@
char *wsServer;
esp_websocket_client_handle_t blockNotifyClient = NULL;
uint currentBlockHeight = 873400;
uint currentBlockHeight = 860000;
uint blockMedianFee = 1;
bool blockNotifyInit = false;
unsigned long int lastBlockUpdate;
@ -296,27 +296,45 @@ void restartBlockNotify()
}
int getBlockFetch() {
try {
String mempoolInstance = preferences.getString("mempoolInstance", DEFAULT_MEMPOOL_INSTANCE);
const String protocol = preferences.getBool("mempoolSecure", DEFAULT_MEMPOOL_SECURE) ? "https" : "http";
String url = protocol + "://" + mempoolInstance + "/api/blocks/tip/height";
int getBlockFetch()
{
try {
WiFiClientSecure client;
HTTPClient* http = HttpHelper::begin(url);
Serial.println("Fetching block height from " + url);
int httpCode = http->GET();
if (httpCode > 0 && httpCode == HTTP_CODE_OK) {
String blockHeightStr = http->getString();
HttpHelper::end(http);
return blockHeightStr.toInt();
}
HttpHelper::end(http);
Serial.println("HTTP code" + String(httpCode));
} catch (...) {
Serial.println(F("An exception occurred while trying to get the latest block"));
if (preferences.getBool("mempoolSecure", DEFAULT_MEMPOOL_SECURE)) {
client.setCACertBundle(rootca_crt_bundle_start);
}
return 2203; // B-T-C
String mempoolInstance =
preferences.getString("mempoolInstance", DEFAULT_MEMPOOL_INSTANCE);
// Get current block height through regular API
HTTPClient http;
const String protocol = preferences.getBool("mempoolSecure", DEFAULT_MEMPOOL_SECURE) ? "https" : "http";
if (preferences.getBool("mempoolSecure", DEFAULT_MEMPOOL_SECURE))
http.begin(client, protocol + "://" + mempoolInstance + "/api/blocks/tip/height");
else
http.begin(protocol + "://" + mempoolInstance + "/api/blocks/tip/height");
Serial.println("Fetching block height from " + protocol + "://" + mempoolInstance + "/api/blocks/tip/height");
int httpCode = http.GET();
if (httpCode > 0 && httpCode == HTTP_CODE_OK)
{
String blockHeightStr = http.getString();
return blockHeightStr.toInt();
} else {
Serial.println("HTTP code" + String(httpCode));
return 0;
}
}
catch (...) {
Serial.println(F("An exception occured while trying to get the latest block"));
}
return 2203; // B-T-C
}
uint getLastBlockUpdate()

View file

@ -5,15 +5,15 @@ const TickType_t debounceDelay = pdMS_TO_TICKS(50);
TickType_t lastDebounceTime = 0;
#ifdef IS_BTCLOCK_V8
#define BTN_1 256
#define BTN_2 512
#define BTN_3 1024
#define BTN_4 2048
#define BTN_1 0
#define BTN_2 1
#define BTN_3 2
#define BTN_4 3
#else
#define BTN_1 2048
#define BTN_2 1024
#define BTN_3 512
#define BTN_4 256
#define BTN_1 3
#define BTN_2 2
#define BTN_3 1
#define BTN_4 0
#endif
void buttonTask(void *parameter) {
@ -22,12 +22,11 @@ void buttonTask(void *parameter) {
std::lock_guard<std::mutex> lock(mcpMutex);
TickType_t currentTime = xTaskGetTickCount();
if ((currentTime - lastDebounceTime) >= debounceDelay) {
lastDebounceTime = currentTime;
if (!digitalRead(MCP_INT_PIN)) {
uint pin = mcp1.getInterruptFlagRegister();
uint pin = mcp1.getLastInterruptPin();
switch (pin) {
case BTN_1:
@ -44,12 +43,12 @@ void buttonTask(void *parameter) {
break;
}
}
mcp1.getInterruptCaptureRegister();
mcp1.clearInterrupts();
} else {
}
// Very ugly, but for some reason this is necessary
while (!digitalRead(MCP_INT_PIN)) {
mcp1.getInterruptCaptureRegister();
mcp1.clearInterrupts();
}
}
}

View file

@ -2,12 +2,10 @@
#define MAX_ATTEMPTS_WIFI_CONNECTION 20
// zlib_turbo zt;
Preferences preferences;
MCP23017 mcp1(0x20);
Adafruit_MCP23X17 mcp1;
#ifdef IS_BTCLOCK_V8
MCP23017 mcp2(0x21);
Adafruit_MCP23X17 mcp2;
#endif
#ifdef HAS_FRONTLIGHT
@ -37,7 +35,7 @@ void setup()
}
{
std::lock_guard<std::mutex> lockMcp(mcpMutex);
if (mcp1.read1(3) == LOW)
if (mcp1.digitalRead(3) == LOW)
{
preferences.putBool("wifiConfigured", false);
preferences.remove("txPower");
@ -48,7 +46,7 @@ void setup()
}
{
if (mcp1.read1(0) == LOW)
if (mcp1.digitalRead(0) == LOW)
{
// Then loop forever to prevent anything else from writing to the screen
while (true)
@ -56,7 +54,7 @@ void setup()
delay(1000);
}
}
else if (mcp1.read1(1) == LOW)
else if (mcp1.digitalRead(1) == LOW)
{
preferences.clear();
queueLedEffect(LED_EFFECT_WIFI_ERASE_SETTINGS);
@ -68,7 +66,6 @@ void setup()
}
setupWifi();
// loadIcons();
setupWebserver();
@ -95,11 +92,6 @@ void setup()
setupBitaxeFetchTask();
}
if (preferences.getBool("miningPoolStats", DEFAULT_MINING_POOL_STATS_ENABLED))
{
setupMiningPoolStatsFetchTask();
}
setupButtonTask();
setupOTA();
@ -114,7 +106,6 @@ void setup()
#endif
forceFullRefresh();
}
void setupWifi()
@ -141,7 +132,7 @@ void setupWifi()
bool buttonPress = false;
{
std::lock_guard<std::mutex> lockMcp(mcpMutex);
buttonPress = (mcp1.read1(2) == LOW);
buttonPress = (mcp1.digitalRead(2) == LOW);
}
{
@ -336,14 +327,6 @@ void setupPreferences()
addScreenMapping(SCREEN_BITAXE_HASHRATE, "BitAxe Hashrate");
addScreenMapping(SCREEN_BITAXE_BESTDIFF, "BitAxe Best Difficulty");
}
if (preferences.getBool("miningPoolStats", DEFAULT_MINING_POOL_STATS_ENABLED))
{
addScreenMapping(SCREEN_MINING_POOL_STATS_HASHRATE, "Mining Pool Hashrate");
if (getMiningPool()->supportsDailyEarnings()) {
addScreenMapping(SCREEN_MINING_POOL_STATS_EARNINGS, "Mining Pool Earnings");
}
}
}
String replaceAmbiguousChars(String input)
@ -359,6 +342,68 @@ String replaceAmbiguousChars(String input)
return input;
}
// void addCurrencyMappings(const std::vector<std::string>& currencies)
// {
// for (const auto& currency : currencies)
// {
// int satsPerCurrencyScreen;
// int btcTickerScreen;
// int marketCapScreen;
// // Determine the corresponding screen IDs based on the currency code
// if (currency == "USD")
// {
// satsPerCurrencyScreen = SCREEN_SATS_PER_CURRENCY_USD;
// btcTickerScreen = SCREEN_BTC_TICKER_USD;
// marketCapScreen = SCREEN_MARKET_CAP_USD;
// }
// else if (currency == "EUR")
// {
// satsPerCurrencyScreen = SCREEN_SATS_PER_CURRENCY_EUR;
// btcTickerScreen = SCREEN_BTC_TICKER_EUR;
// marketCapScreen = SCREEN_MARKET_CAP_EUR;
// }
// else if (currency == "GBP")
// {
// satsPerCurrencyScreen = SCREEN_SATS_PER_CURRENCY_GBP;
// btcTickerScreen = SCREEN_BTC_TICKER_GBP;
// marketCapScreen = SCREEN_MARKET_CAP_GBP;
// }
// else if (currency == "JPY")
// {
// satsPerCurrencyScreen = SCREEN_SATS_PER_CURRENCY_JPY;
// btcTickerScreen = SCREEN_BTC_TICKER_JPY;
// marketCapScreen = SCREEN_MARKET_CAP_JPY;
// }
// else if (currency == "AUD")
// {
// satsPerCurrencyScreen = SCREEN_SATS_PER_CURRENCY_AUD;
// btcTickerScreen = SCREEN_BTC_TICKER_AUD;
// marketCapScreen = SCREEN_MARKET_CAP_AUD;
// }
// else if (currency == "CAD")
// {
// satsPerCurrencyScreen = SCREEN_SATS_PER_CURRENCY_CAD;
// btcTickerScreen = SCREEN_BTC_TICKER_CAD;
// marketCapScreen = SCREEN_MARKET_CAP_CAD;
// }
// else
// {
// continue; // Unknown currency, skip it
// }
// // Create the string locally to ensure it persists
// std::string satsPerCurrencyString = "Sats per " + currency;
// std::string btcTickerString = "Ticker " + currency;
// std::string marketCapString = "Market Cap " + currency;
// // Pass the c_str() to the function
// addScreenMapping(satsPerCurrencyScreen, satsPerCurrencyString.c_str());
// addScreenMapping(btcTickerScreen, btcTickerString.c_str());
// addScreenMapping(marketCapScreen, marketCapString.c_str());
// }
// }
void setupWebsocketClients(void *pvParameters)
{
if (preferences.getBool("ownDataSource", DEFAULT_OWN_DATA_SOURCE))
@ -439,19 +484,15 @@ void setupHardware()
Serial.println(F("Error loading WebUI"));
}
// if (!LittleFS.exists("/qr.txt"))
// {
// File f = LittleFS.open("/qr.txt", "w");
// if(f) {
// if (f.print("Hello")) {
// Serial.println(F("Written QR to FS"));
// Serial.printf("\nLittleFS free: %zu\n", LittleFS.totalBytes() - LittleFS.usedBytes());
// }
// } else {
// Serial.println(F("Can't write QR to FS"));
// }
// f.close();
// }
setupLeds();
@ -466,7 +507,7 @@ void setupHardware()
Wire.begin(I2C_SDA_PIN, I2C_SCK_PIN, 400000);
if (!mcp1.begin())
if (!mcp1.begin_I2C(0x20))
{
Serial.println(F("Error MCP23017 1"));
@ -476,20 +517,17 @@ void setupHardware()
else
{
pinMode(MCP_INT_PIN, INPUT_PULLUP);
// mcp1.setupInterrupts(false, false, LOW);
mcp1.enableControlRegister(MCP23x17_IOCR_ODR);
mcp1.mirrorInterrupts(true);
mcp1.setupInterrupts(false, false, LOW);
for (int i = 0; i < 4; i++)
{
mcp1.pinMode1(i, INPUT_PULLUP);
mcp1.enableInterrupt(i, LOW);
mcp1.pinMode(i, INPUT_PULLUP);
mcp1.setupInterruptPin(i, LOW);
}
#ifndef IS_BTCLOCK_V8
for (int i = 8; i <= 14; i++)
{
mcp1.pinMode1(i, OUTPUT);
mcp1.pinMode(i, OUTPUT);
}
#endif
}
@ -500,7 +538,7 @@ void setupHardware()
#endif
#ifdef IS_BTCLOCK_V8
if (!mcp2.begin())
if (!mcp2.begin_I2C(0x21))
{
Serial.println(F("Error MCP23017 2"));
@ -752,16 +790,4 @@ const char* getFirmwareFilename() {
} else {
return "";
}
}
const char* getWebUiFilename() {
if (HW_REV == "REV_B_EPD_2_13") {
return "littlefs_8MB.bin";
} else if (HW_REV == "REV_A_EPD_2_13") {
return "littlefs_4MB.bin";
} else if (HW_REV == "REV_A_EPD_2_9") {
return "littlefs_4MB.bin";
} else {
return "littlefs_4MB.bin";
}
}
}

View file

@ -1,6 +1,6 @@
#pragma once
#include <MCP23017.h>
#include <Adafruit_MCP23X17.h>
#include <Arduino.h>
#include <Preferences.h>
#include <WiFiClientSecure.h>
@ -18,7 +18,6 @@
#include "lib/ota.hpp"
#include "lib/nostr_notify.hpp"
#include "lib/bitaxe_fetch.hpp"
#include "lib/mining_pool_stats_fetch.hpp"
#include "lib/v2_notify.hpp"
@ -33,6 +32,7 @@
#define NTP_SERVER "pool.ntp.org"
#define DEFAULT_TIME_OFFSET_SECONDS 3600
#define USER_AGENT "BTClock/3.0"
#ifndef MCP_DEV_ADDR
#define MCP_DEV_ADDR 0x20
#endif
@ -83,6 +83,4 @@ void addScreenMapping(int value, const char* name);
int findScreenIndexByValue(int value);
String replaceAmbiguousChars(String input);
const char* getFirmwareFilename();
const char* getWebUiFilename();
// void loadIcons();
const char* getFirmwareFilename();

View file

@ -18,9 +18,6 @@
#define DEFAULT_DISABLE_FL false
#define DEFAULT_OWN_DATA_SOURCE true
#define DEFAULT_STAGING_SOURCE false
#define DEFAULT_MOW_MODE false
#define DEFAULT_SUFFIX_SHARE_DOT false
#define DEFAULT_V2_SOURCE_CURRENCY CURRENCY_USD
@ -45,8 +42,6 @@
#define DEFAULT_FL_EFFECT_DELAY 15
#define DEFAULT_LUX_LIGHT_TOGGLE 128
#define DEFAULT_FL_OFF_WHEN_DARK true
#define DEFAULT_FL_ALWAYS_ON false
#define DEFAULT_FL_FLASH_ON_UPDATE false
@ -58,14 +53,8 @@
#define DEFAULT_BITAXE_ENABLED false
#define DEFAULT_BITAXE_HOSTNAME "bitaxe1"
#define DEFAULT_MINING_POOL_STATS_ENABLED false
#define DEFAULT_MINING_POOL_NAME "ocean"
#define DEFAULT_MINING_POOL_USER "38Qkkei3SuF1Eo45BaYmRHUneRD54yyTFy" // Random actual Ocean hasher
#define DEFAULT_ZAP_NOTIFY_ENABLED false
#define DEFAULT_ZAP_NOTIFY_PUBKEY "b5127a08cf33616274800a4387881a9f98e04b9c37116e92de5250498635c422"
#define DEFAULT_LED_FLASH_ON_ZAP true
#define DEFAULT_FL_FLASH_ON_ZAP true
#define DEFAULT_HTTP_AUTH_ENABLED false
#define DEFAULT_HTTP_AUTH_USERNAME "btclock"
@ -74,6 +63,3 @@
#define DEFAULT_ACTIVE_CURRENCIES "USD,EUR,JPY"
#define DEFAULT_GIT_RELEASE_URL "https://git.btclock.dev/api/v1/repos/btclock/btclock_v3/releases/latest"
#define DEFAULT_VERTICAL_DESC true
#define DEFAULT_MINING_POOL_LOGOS_URL "https://git.btclock.dev/btclock/mining-pool-logos/raw/branch/main"

View file

@ -138,9 +138,6 @@ uint8_t qrcode[800];
#define EPD_TASK_STACK_SIZE 2048
#endif
#define BUSY_TIMEOUT_COUNT 200
#define BUSY_RETRY_DELAY pdMS_TO_TICKS(10)
void forceFullRefresh()
{
for (uint i = 0; i < NUM_SCREENS; i++)
@ -179,7 +176,7 @@ void setupDisplays()
updateQueue = xQueueCreate(UPDATE_QUEUE_SIZE, sizeof(UpdateDisplayTaskItem));
xTaskCreate(prepareDisplayUpdateTask, "PrepareUpd", EPD_TASK_STACK_SIZE*2, NULL, 11, NULL);
xTaskCreate(prepareDisplayUpdateTask, "PrepareUpd", EPD_TASK_STACK_SIZE, NULL, 11, NULL);
for (uint i = 0; i < NUM_SCREENS; i++)
{
@ -194,7 +191,7 @@ void setupDisplays()
}
// Hold lower button to enable "storage mode" (prevents burn-in of ePaper displays)
if (mcp1.read1(0) == LOW)
if (mcp1.digitalRead(0) == LOW)
{
setFgColor(GxEPD_BLACK);
setBgColor(GxEPD_WHITE);
@ -278,10 +275,7 @@ void prepareDisplayUpdateTask(void *pvParameters)
}
else if (epdContent[epdIndex].startsWith(F("mdi")))
{
bool updated = renderIcon(epdIndex, epdContent[epdIndex], updatePartial);
if (!updated) {
continue;
}
renderIcon(epdIndex, epdContent[epdIndex], updatePartial);
}
else if (epdContent[epdIndex].length() > 5)
{
@ -289,10 +283,7 @@ void prepareDisplayUpdateTask(void *pvParameters)
}
else
{
if (epdContent[epdIndex].length() == 2) {
showChars(epdIndex, epdContent[epdIndex], updatePartial, &FONT_BIG);
}
else if (epdContent[epdIndex].length() > 1 && epdContent[epdIndex].indexOf(".") == -1)
if (epdContent[epdIndex].length() > 1 && epdContent[epdIndex].indexOf(".") == -1)
{
if (epdContent[epdIndex].equals("STS"))
{
@ -379,11 +370,7 @@ extern "C" void updateDisplay(void *pvParameters) noexcept
void splitText(const uint dispNum, const String &top, const String &bottom,
bool partial)
{
if(preferences.getBool("verticalDesc", DEFAULT_VERTICAL_DESC) && dispNum == 0) {
displays[dispNum].setRotation(1);
} else {
displays[dispNum].setRotation(2);
}
displays[dispNum].setRotation(2);
displays[dispNum].setFont(&FONT_SMALL);
displays[dispNum].setTextColor(getFgColor());
@ -420,83 +407,80 @@ void splitText(const uint dispNum, const String &top, const String &bottom,
displays[dispNum].print(bottom);
}
// Consolidate common display setup code into a helper function
void setupDisplay(const uint dispNum, const GFXfont *font) {
displays[dispNum].setRotation(2);
displays[dispNum].setFont(font);
displays[dispNum].setTextColor(getFgColor());
displays[dispNum].fillScreen(getBgColor());
}
void showDigit(const uint dispNum, char chr, bool partial, const GFXfont *font) {
String str(chr);
if (chr == '.') {
str = "!";
}
setupDisplay(dispNum, font);
int16_t tbx, tby;
uint16_t tbw, tbh;
displays[dispNum].getTextBounds(str, 0, 0, &tbx, &tby, &tbw, &tbh);
uint16_t x = ((displays[dispNum].width() - tbw) / 2) - tbx;
uint16_t y = ((displays[dispNum].height() - tbh) / 2) - tby;
displays[dispNum].setCursor(x, y);
displays[dispNum].print(str);
if (chr == '.') {
displays[dispNum].fillRect(x, y, displays[dispNum].width(),
round(displays[dispNum].height() * 0.9), getBgColor());
}
}
int16_t calculateDescent(const GFXfont *font) {
int16_t maxDescent = 0;
for (uint16_t i = font->first; i <= font->last; i++) {
GFXglyph *glyph = &font->glyph[i - font->first];
int16_t descent = glyph->yOffset;
if (descent > maxDescent) {
maxDescent = descent;
}
}
return maxDescent;
}
void showChars(const uint dispNum, const String &chars, bool partial,
void showDigit(const uint dispNum, char chr, bool partial,
const GFXfont *font)
{
setupDisplay(dispNum, font);
String str(chr);
if (chr == '.')
{
str = "!";
}
displays[dispNum].setRotation(2);
displays[dispNum].setFont(font);
displays[dispNum].setTextColor(getFgColor());
int16_t tbx, tby;
uint16_t tbw, tbh;
displays[dispNum].getTextBounds(chars, 0, 0, &tbx, &tby, &tbw, &tbh);
displays[dispNum].getTextBounds(str, 0, 0, &tbx, &tby, &tbw, &tbh);
// center the bounding box by transposition of the origin:
uint16_t x = ((displays[dispNum].width() - tbw) / 2) - tbx;
uint16_t y = ((displays[dispNum].height() - tbh) / 2) - tby;
for (int i = 0; i < chars.length(); i++) {
char c = chars[i];
if (c == '.' || c == ',') {
// For the dot, calculate its specific descent
GFXglyph *dotGlyph = &font->glyph[c -font->first];
int16_t dotDescent = dotGlyph->yOffset;
// Draw the dot with adjusted y-position
displays[dispNum].setCursor(x, y + dotDescent + dotGlyph->height + 8);
displays[dispNum].print(c);
} else {
// For other characters, use the original y-position
displays[dispNum].setCursor(x, y);
displays[dispNum].print(c);
}
// Move x-position for the next character
x += font->glyph[c - font->first].xAdvance;
// if (str.equals("."))
// {
// // int16_t yAdvance = font->yAdvance;
// // uint8_t charIndex = 46 - font->first;
// // GFXglyph *glyph = (&font->glyph)[charIndex];
// int16_t tbx2, tby2;
// uint16_t tbw2, tbh2;
// displays[dispNum].getTextBounds(".!", 0, 0, &tbx2, &tby2, &tbw2, &tbh2);
// y = ((displays[dispNum].height() - tbh2) / 2) - tby2;
// // Serial.print("yAdvance");
// // Serial.println(yAdvance);
// // if (glyph != nullptr) {
// // Serial.print("height");
// // Serial.println(glyph->height);
// // Serial.print("yOffset");
// // Serial.println(glyph->yOffset);
// // }
// // y = 250-99+18+19;
// }
displays[dispNum].fillScreen(getBgColor());
displays[dispNum].setCursor(x, y);
displays[dispNum].print(str);
if (chr == '.')
{
displays[dispNum].fillRect(x, y, displays[dispNum].width(), round(displays[dispNum].height() * 0.9), getBgColor());
}
// displays[dispNum].setCursor(10, 3);
// displays[dispNum].setFont(&FONT_SMALL);
// displays[dispNum].setTextColor(getFgColor());
// displays[dispNum].println("Y = " + y);
}
void showChars(const uint dispNum, const String &chars, bool partial,
const GFXfont *font)
{
displays[dispNum].setRotation(2);
displays[dispNum].setFont(font);
displays[dispNum].setTextColor(getFgColor());
int16_t tbx, tby;
uint16_t tbw, tbh;
displays[dispNum].getTextBounds(chars, 0, 0, &tbx, &tby, &tbw, &tbh);
// center the bounding box by transposition of the origin:
uint16_t x = ((displays[dispNum].width() - tbw) / 2) - tbx;
uint16_t y = ((displays[dispNum].height() - tbh) / 2) - tby;
displays[dispNum].fillScreen(getBgColor());
displays[dispNum].setCursor(x, y);
displays[dispNum].print(chars);
}
int getBgColor() { return bgColor; }
@ -542,55 +526,25 @@ void renderText(const uint dispNum, const String &text, bool partial)
}
}
bool renderIcon(const uint dispNum, const String &text, bool partial)
void renderIcon(const uint dispNum, const String &text, bool partial)
{
displays[dispNum].setRotation(2);
displays[dispNum].setPartialWindow(0, 0, displays[dispNum].width(),
displays[dispNum].height());
displays[dispNum].fillScreen(getBgColor());
displays[dispNum].setTextColor(getFgColor());
displays[dispNum].fillScreen(getBgColor());
displays[dispNum].setTextColor(getFgColor());
uint iconIndex = 0;
uint width = 122;
uint height = 122;
if (text.endsWith("rocket")) {
iconIndex = 1;
}
else if (text.endsWith("lnbolt")) {
iconIndex = 2;
}
else if (text.endsWith("bitaxe")) {
width = 88;
height = 220;
if (text.endsWith("lnbolt")) {
iconIndex = 3;
}
else if (text.endsWith("miningpool")) {
LogoData logo = getMiningPoolLogo();
if (logo.size == 0) {
Serial.println("No logo found");
return false;
}
int x_offset = (displays[dispNum].width() - logo.width) / 2;
int y_offset = (displays[dispNum].height() - logo.height) / 2;
// Close the file
displays[dispNum].drawInvertedBitmap(x_offset,y_offset, logo.data, logo.width, logo.height, getFgColor());
return true;
}
int x_offset = (displays[dispNum].width() - width) / 2;
int y_offset = (displays[dispNum].height() - height) / 2;
displays[dispNum].drawInvertedBitmap(x_offset,y_offset, epd_icons_allArray[iconIndex], width, height, getFgColor());
return true;
// displays[dispNum].drawInvertedBitmap(0,0, getOceanIcon(), 122, 250, getFgColor());
displays[dispNum].drawInvertedBitmap(0,0, epd_icons_allArray[iconIndex], 122, 250, getFgColor());
}
@ -637,12 +591,15 @@ void waitUntilNoneBusy()
while (EPD_BUSY[i].digitalRead())
{
count++;
vTaskDelay(BUSY_RETRY_DELAY);
if (count == BUSY_TIMEOUT_COUNT) {
vTaskDelay(pdMS_TO_TICKS(100));
} else if (count > BUSY_TIMEOUT_COUNT + 5) {
log_e("Display %d busy timeout", i);
vTaskDelay(10);
if (count == 200)
{
// displays[i].init(0, false);
vTaskDelay(100);
}
else if (count > 205)
{
Serial.printf("Busy timeout %d", i);
break;
}
}

View file

@ -4,7 +4,6 @@
#include <Fonts/FreeSansBold9pt7b.h>
#include <GxEPD2_BW.h>
#include <mcp23x17_pin.hpp>
#include <mutex>
#include <native_pin.hpp>
@ -14,7 +13,6 @@
#include "lib/config.hpp"
#include "lib/shared.hpp"
#include "icons/icons.h"
#include "mining_pool_stats_fetch.hpp"
#ifdef USE_QR
#include "qrcodegen.h"
@ -45,7 +43,7 @@ int getFgColor();
void setBgColor(int color);
void setFgColor(int color);
bool renderIcon(const uint dispNum, const String &text, bool partial);
void renderIcon(const uint dispNum, const String &text, bool partial);
void renderText(const uint dispNum, const String &text, bool partial);
void renderQr(const uint dispNum, const String &text, bool partial);

View file

@ -285,7 +285,7 @@ void ledTask(void *parameter)
#ifdef HAS_FRONTLIGHT
bool frontlightWasOn = false;
if (preferences.getBool("flFlashOnZap", DEFAULT_FL_FLASH_ON_ZAP))
if (preferences.getBool("flFlashOnUpd", DEFAULT_FL_FLASH_ON_UPDATE))
{
if (frontlightOn)
{
@ -307,7 +307,7 @@ void ledTask(void *parameter)
// blinkDelayTwoColor(250, 3, pixels.Color(142, 48, 235),
// pixels.Color(169, 21, 255));
#ifdef HAS_FRONTLIGHT
if (preferences.getBool("flFlashOnZap", DEFAULT_FL_FLASH_ON_ZAP))
if (preferences.getBool("flFlashOnUpd", DEFAULT_FL_FLASH_ON_UPDATE))
{
vTaskDelay(pdMS_TO_TICKS(10));
if (frontlightWasOn)

View file

@ -1,32 +0,0 @@
#include "brains_pool.hpp"
void BraiinsPool::prepareRequest(HTTPClient& http) const {
http.addHeader("Pool-Auth-Token", poolUser.c_str());
}
std::string BraiinsPool::getApiUrl() const {
return "https://pool.braiins.com/accounts/profile/json/btc/";
}
PoolStats BraiinsPool::parseResponse(const JsonDocument &doc) const
{
if (doc["btc"].isNull()) {
return PoolStats{
.hashrate = "0",
.dailyEarnings = 0
};
}
std::string unit = doc["btc"]["hash_rate_unit"].as<std::string>();
static const std::unordered_map<std::string, int> multipliers = {
{"Zh/s", 21}, {"Eh/s", 18}, {"Ph/s", 15}, {"Th/s", 12}, {"Gh/s", 9}, {"Mh/s", 6}, {"Kh/s", 3}};
int multiplier = multipliers.at(unit);
float hashValue = doc["btc"]["hash_rate_5m"].as<float>();
return PoolStats{
.hashrate = std::to_string(static_cast<int>(std::round(hashValue))) + std::string(multiplier, '0'),
.dailyEarnings = static_cast<int64_t>(doc["btc"]["today_reward"].as<float>() * 100000000)};
}

View file

@ -1,33 +0,0 @@
#pragma once
#include "lib/mining_pool/mining_pool_interface.hpp"
#include <icons/icons.h>
#include <utils.hpp>
class BraiinsPool : public MiningPoolInterface
{
public:
void setPoolUser(const std::string &user) override { poolUser = user; }
void prepareRequest(HTTPClient &http) const override;
std::string getApiUrl() const override;
PoolStats parseResponse(const JsonDocument &doc) const override;
bool supportsDailyEarnings() const override { return true; }
bool hasLogo() const override { return true; }
std::string getDisplayLabel() const override { return "BRAIINS/POOL"; } // Fallback if needed
std::string getDailyEarningsLabel() const override { return "sats/earned"; }
std::string getLogoFilename() const override {
return "braiins.bin";
}
std::string getPoolName() const override {
return "braiins";
}
int getLogoWidth() const override {
return 37;
}
int getLogoHeight() const override {
return 230;
}
};

View file

@ -1,6 +0,0 @@
// src/noderunners/noderunners_pool.cpp
#include "gobrrr_pool.hpp"
std::string GoBrrrPool::getApiUrl() const {
return "https://pool.gobrrr.me/api/client/" + poolUser;
}

View file

@ -1,30 +0,0 @@
#pragma once
#include "lib/mining_pool/mining_pool_interface.hpp"
#include "lib/mining_pool/public_pool/public_pool.hpp"
#include <icons/icons.h>
class GoBrrrPool : public PublicPool {
public:
std::string getApiUrl() const override;
bool hasLogo() const override { return true; }
std::string getDisplayLabel() const override { return "GOBRRR/POOL"; }
std::string getLogoFilename() const override {
return "gobrrr.bin";
}
std::string getPoolName() const override {
return "gobrrr_pool";
}
int getLogoWidth() const override {
return 122;
}
int getLogoHeight() const override {
return 122;
}
};

View file

@ -1,11 +0,0 @@
#pragma once
#include <cstdint>
#include <stddef.h>
struct LogoData {
const uint8_t* data;
size_t width;
size_t height;
size_t size;
};

View file

@ -1,18 +0,0 @@
#include "mining_pool_interface.hpp"
#include "pool_factory.hpp"
LogoData MiningPoolInterface::getLogo() const {
if (!hasLogo()) {
return LogoData{nullptr, 0, 0, 0};
}
// Check if logo exists
String logoPath = String(PoolFactory::getLogosDir()) + "/" + String(getPoolName().c_str()) + "_logo.bin";
if (!LittleFS.exists(logoPath)) {
return LogoData{nullptr, 0, 0, 0};
}
// Now load the logo (whether it was just downloaded or already existed)
return PoolFactory::loadLogoFromFS(getPoolName(), this);
}

View file

@ -1,35 +0,0 @@
#pragma once
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include "pool_stats.hpp"
#include "logo_data.hpp"
#include "lib/shared.hpp"
class MiningPoolInterface {
public:
virtual ~MiningPoolInterface() = default;
virtual void setPoolUser(const std::string& user) = 0;
virtual void prepareRequest(HTTPClient& http) const = 0;
virtual std::string getApiUrl() const = 0;
virtual PoolStats parseResponse(const JsonDocument& doc) const = 0;
virtual bool hasLogo() const = 0;
virtual LogoData getLogo() const;
virtual std::string getDisplayLabel() const = 0;
virtual bool supportsDailyEarnings() const = 0;
virtual std::string getDailyEarningsLabel() const = 0;
virtual std::string getLogoFilename() const { return ""; }
virtual std::string getPoolName() const = 0;
virtual int getLogoWidth() const { return 0; }
virtual int getLogoHeight() const { return 0; }
std::string getLogoUrl() const {
if (!hasLogo() || getLogoFilename().empty()) {
return "";
}
std::string baseUrl = preferences.getString("poolLogosUrl", DEFAULT_MINING_POOL_LOGOS_URL).c_str();
return baseUrl + "/" + getLogoFilename().c_str();
}
protected:
std::string poolUser;
};

View file

@ -1,95 +0,0 @@
#include "mining_pool_stats_handler.hpp"
std::array<std::string, NUM_SCREENS> parseMiningPoolStatsHashRate(const std::string& hashrate, const MiningPoolInterface& pool)
{
std::array<std::string, NUM_SCREENS> ret;
ret.fill(""); // Initialize all elements to empty strings
std::string label;
std::string output;
parseHashrateString(hashrate, label, output, 4);
std::size_t textLength = output.length();
// Calculate the position where the digits should start
// Account for the position of the mining pool logo and the hashrate label
std::size_t startIndex = NUM_SCREENS - 1 - textLength;
// Insert the pickaxe icon just before the digits
if (startIndex > 0)
{
ret[startIndex - 1] = "mdi:pickaxe";
}
// Place the digits
for (std::size_t i = 0; i < textLength; ++i)
{
ret[startIndex + i] = output.substr(i, 1);
}
ret[NUM_SCREENS - 1] = label;
if (pool.hasLogo()) {
ret[0] = "mdi:miningpool";
} else {
ret[0] = pool.getDisplayLabel();
}
return ret;
}
std::array<std::string, NUM_SCREENS> parseMiningPoolStatsDailyEarnings(int sats, std::string label, const MiningPoolInterface& pool)
{
std::array<std::string, NUM_SCREENS> ret;
ret.fill(""); // Initialize all elements to empty strings
std::string satsDisplay = std::to_string(sats);
if (sats >= 100000000) {
// A whale mining 1+ BTC per day! No decimal points; whales scoff at such things.
label = "BTC" + label.substr(4);
satsDisplay = satsDisplay.substr(0, satsDisplay.length() - 8);
} else if (sats >= 10000000) {
// 10.0M to 99.9M you get one decimal point
satsDisplay = satsDisplay.substr(0, satsDisplay.length() - 6) + "." + satsDisplay[2] + "M";
} else if (sats >= 1000000) {
// 1.00M to 9.99M you get two decimal points
satsDisplay = satsDisplay.substr(0, satsDisplay.length() - 6) + "." + satsDisplay.substr(2, 2) + "M";
} else if (sats >= 100000) {
// 100K to 999K you get no extra precision
satsDisplay = satsDisplay.substr(0, satsDisplay.length() - 3) + "K";
} else if (sats >= 10000) {
// 10.0K to 99.9K you get one decimal point
satsDisplay = satsDisplay.substr(0, satsDisplay.length() - 3) + "." + satsDisplay[2] + "K";
} else {
// Pleb miner! 4 digit or fewer sats will fit as-is. no-op.
}
std::size_t textLength = satsDisplay.length();
// Calculate the position where the digits should start
// Account for the position of the mining pool logo
std::size_t startIndex = NUM_SCREENS - 1 - textLength;
// Insert the pickaxe icon just before the digits if there's room
if (startIndex > 0)
{
ret[startIndex - 1] = "mdi:pickaxe";
}
// Place the digits
for (std::size_t i = 0; i < textLength; ++i)
{
ret[startIndex + i] = satsDisplay.substr(i, 1);
}
ret[NUM_SCREENS - 1] = label;
if (pool.hasLogo()) {
ret[0] = "mdi:miningpool";
} else {
ret[0] = pool.getDisplayLabel();
}
return ret;
}

View file

@ -1,11 +0,0 @@
#include <array>
#include <string>
#include <iostream>
#include <utils.hpp>
#ifndef UNITY_TEST
#include "lib/mining_pool/mining_pool_interface.hpp"
#endif
std::array<std::string, NUM_SCREENS> parseMiningPoolStatsHashRate(const std::string& hashrate, const MiningPoolInterface& pool);
std::array<std::string, NUM_SCREENS> parseMiningPoolStatsDailyEarnings(int sats, std::string label, const MiningPoolInterface& pool);

View file

@ -1,27 +0,0 @@
// src/noderunners/noderunners_pool.cpp
#include "noderunners_pool.hpp"
void NoderunnersPool::prepareRequest(HTTPClient& http) const {
// Empty as NodeRunners doesn't need special headers
}
std::string NoderunnersPool::getApiUrl() const {
return "https://pool.noderunners.network/api/v1/users/" + poolUser;
}
PoolStats NoderunnersPool::parseResponse(const JsonDocument& doc) const {
std::string hashrateStr = doc["hashrate1m"].as<std::string>();
char unit = hashrateStr.back();
std::string value = hashrateStr.substr(0, hashrateStr.size() - 1);
int multiplier = getHashrateMultiplier(unit);
double hashrate = std::stod(value) * std::pow(10, multiplier);
char buffer[32];
snprintf(buffer, sizeof(buffer), "%.0f", hashrate);
return PoolStats{
.hashrate = buffer,
.dailyEarnings = std::nullopt
};
}

View file

@ -1,33 +0,0 @@
#pragma once
#include "lib/mining_pool/mining_pool_interface.hpp"
#include <icons/icons.h>
#include <utils.hpp>
class NoderunnersPool : public MiningPoolInterface {
public:
void setPoolUser(const std::string& user) override { poolUser = user; }
void prepareRequest(HTTPClient& http) const override;
std::string getApiUrl() const override;
PoolStats parseResponse(const JsonDocument& doc) const override;
bool supportsDailyEarnings() const override { return false; }
std::string getDailyEarningsLabel() const override { return ""; }
bool hasLogo() const override { return true; }
std::string getDisplayLabel() const override { return "NODE/RUNNERS"; } // Fallback if needed
std::string getLogoFilename() const override {
return "noderunners.bin";
}
std::string getPoolName() const override {
return "noderunners";
}
int getLogoWidth() const override {
return 122;
}
int getLogoHeight() const override {
return 122;
}
};

View file

@ -1,18 +0,0 @@
#include "ocean_pool.hpp"
void OceanPool::prepareRequest(HTTPClient& http) const {
// Empty as Ocean doesn't need special headers
}
std::string OceanPool::getApiUrl() const {
return "https://api.ocean.xyz/v1/statsnap/" + poolUser;
}
PoolStats OceanPool::parseResponse(const JsonDocument& doc) const {
return PoolStats{
.hashrate = doc["result"]["hashrate_300s"].as<std::string>(),
.dailyEarnings = static_cast<int64_t>(
doc["result"]["estimated_earn_next_block"].as<float>() * 100000000
)
};
}

View file

@ -1,31 +0,0 @@
#pragma once
#include "lib/mining_pool/mining_pool_interface.hpp"
#include <icons/icons.h>
class OceanPool : public MiningPoolInterface {
public:
void setPoolUser(const std::string& user) override { poolUser = user; }
void prepareRequest(HTTPClient& http) const override;
std::string getApiUrl() const override;
PoolStats parseResponse(const JsonDocument& doc) const override;
bool hasLogo() const override { return true; }
std::string getDisplayLabel() const override { return "OCEAN/POOL"; } // Fallback if needed
bool supportsDailyEarnings() const override { return true; }
std::string getDailyEarningsLabel() const override { return "sats/block"; }
std::string getLogoFilename() const override {
return "ocean.bin";
}
std::string getPoolName() const override {
return "ocean";
}
int getLogoWidth() const override {
return 122;
}
int getLogoHeight() const override {
return 122;
}
};

View file

@ -1,134 +0,0 @@
#include "pool_factory.hpp"
const char* PoolFactory::MINING_POOL_NAME_OCEAN = "ocean";
const char* PoolFactory::MINING_POOL_NAME_NODERUNNERS = "noderunners";
const char* PoolFactory::MINING_POOL_NAME_BRAIINS = "braiins";
const char* PoolFactory::MINING_POOL_NAME_SATOSHI_RADIO = "satoshi_radio";
const char* PoolFactory::MINING_POOL_NAME_PUBLIC_POOL = "public_pool";
const char* PoolFactory::MINING_POOL_NAME_GOBRRR_POOL = "gobrrr_pool";
const char* PoolFactory::LOGOS_DIR = "/logos";
std::unique_ptr<MiningPoolInterface> PoolFactory::createPool(const std::string& poolName) {
static const std::unordered_map<std::string, std::function<std::unique_ptr<MiningPoolInterface>()>> poolFactories = {
{MINING_POOL_NAME_OCEAN, []() { return std::make_unique<OceanPool>(); }},
{MINING_POOL_NAME_NODERUNNERS, []() { return std::make_unique<NoderunnersPool>(); }},
{MINING_POOL_NAME_BRAIINS, []() { return std::make_unique<BraiinsPool>(); }},
{MINING_POOL_NAME_SATOSHI_RADIO, []() { return std::make_unique<SatoshiRadioPool>(); }},
{MINING_POOL_NAME_PUBLIC_POOL, []() { return std::make_unique<PublicPool>(); }},
{MINING_POOL_NAME_GOBRRR_POOL, []() { return std::make_unique<GoBrrrPool>(); }}
};
auto it = poolFactories.find(poolName);
if (it == poolFactories.end()) {
return nullptr;
}
return it->second();
}
void PoolFactory::downloadPoolLogo(const std::string& poolName, const MiningPoolInterface* poolInterface)
{
const int MAX_RETRIES = 5;
const int RETRY_DELAY_MS = 1000; // 1 second between retries
if (!poolInterface || !poolInterface->hasLogo()) {
Serial.println(F("No pool interface or logo"));
return;
}
// Ensure logos directory exists
if (!LittleFS.exists(LOGOS_DIR)) {
LittleFS.mkdir(LOGOS_DIR);
}
String logoPath = String(LOGOS_DIR) + "/" + String(poolName.c_str()) + "_logo.bin";
// Only download if the logo doesn't exist
if (!LittleFS.exists(logoPath)) {
// Clean up logos directory first
File root = LittleFS.open(LOGOS_DIR, "r");
if (root) {
File file = root.openNextFile();
while (file) {
String path = file.path();
file.close();
LittleFS.remove(path);
file = root.openNextFile();
}
root.close();
}
// Download new logo with retries
std::string logoUrl = poolInterface->getLogoUrl();
if (!logoUrl.empty()) {
for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
Serial.printf("Downloading pool logo (attempt %d of %d)...\n", attempt, MAX_RETRIES);
HTTPClient http;
http.setUserAgent(USER_AGENT);
http.begin(logoUrl.c_str());
int httpCode = http.GET();
if (httpCode == 200) {
File file = LittleFS.open(logoPath, "w");
if (file) {
http.writeToStream(&file);
file.close();
Serial.println(F("Logo downloaded successfully"));
http.end();
return; // Success!
}
}
http.end();
if (attempt < MAX_RETRIES) {
Serial.printf("Failed to download logo, HTTP code: %d. Retrying...\n", httpCode);
vTaskDelay(pdMS_TO_TICKS(RETRY_DELAY_MS));
} else {
Serial.printf("Failed to download logo after %d attempts\n", MAX_RETRIES);
}
}
}
} else {
Serial.println(F("Logo already exists"));
}
}
LogoData PoolFactory::loadLogoFromFS(const std::string& poolName, const MiningPoolInterface* poolInterface)
{
// Initialize with dimensions from the pool interface
LogoData logo = {nullptr,
0,
0,
0};
String logoPath = String(LOGOS_DIR) + "/" + String(poolName.c_str()) + "_logo.bin";
if (!LittleFS.exists(logoPath)) {
return logo;
}
// Only set dimensions if file exists
logo.width = static_cast<size_t>(poolInterface->getLogoWidth());
logo.height = static_cast<size_t>(poolInterface->getLogoHeight());
File file = LittleFS.open(logoPath, "r");
if (!file) {
return logo;
}
size_t size = file.size();
uint8_t* buffer = new uint8_t[size];
if (file.read(buffer, size) == size) {
logo.data = buffer;
logo.size = size;
} else {
delete[] buffer;
logo.data = nullptr;
logo.size = 0;
}
file.close();
return logo;
}

View file

@ -1,56 +0,0 @@
#pragma once
#include "mining_pool_interface.hpp"
#include <memory>
#include <string>
#include "lib/shared.hpp"
#include "lib/config.hpp"
#include "noderunners/noderunners_pool.hpp"
#include "braiins/brains_pool.hpp"
#include "ocean/ocean_pool.hpp"
#include "satoshi_radio/satoshi_radio_pool.hpp"
#include "public_pool/public_pool.hpp"
#include "gobrrr_pool/gobrrr_pool.hpp"
#include <LittleFS.h>
#include <HTTPClient.h>
class PoolFactory {
public:
static const char* getLogosDir() { return LOGOS_DIR; }
static std::unique_ptr<MiningPoolInterface> createPool(const std::string& poolName);
static std::vector<std::string> getAvailablePools() {
return {
MINING_POOL_NAME_OCEAN,
MINING_POOL_NAME_NODERUNNERS,
MINING_POOL_NAME_SATOSHI_RADIO,
MINING_POOL_NAME_BRAIINS,
MINING_POOL_NAME_PUBLIC_POOL,
MINING_POOL_NAME_GOBRRR_POOL
};
}
static std::string getAvailablePoolsAsString() {
const auto pools = getAvailablePools();
std::string result;
for (size_t i = 0; i < pools.size(); ++i) {
result += pools[i];
if (i < pools.size() - 1) {
result += ", ";
}
}
return result;
}
static void downloadPoolLogo(const std::string& poolName, const MiningPoolInterface* poolInterface);
static LogoData loadLogoFromFS(const std::string& poolName, const MiningPoolInterface* poolInterface);
private:
static const char* MINING_POOL_NAME_OCEAN;
static const char* MINING_POOL_NAME_NODERUNNERS;
static const char* MINING_POOL_NAME_BRAIINS;
static const char* MINING_POOL_NAME_SATOSHI_RADIO;
static const char* MINING_POOL_NAME_PUBLIC_POOL;
static const char* MINING_POOL_NAME_GOBRRR_POOL;
static const char* LOGOS_DIR;
};

View file

@ -1,10 +0,0 @@
#pragma once
#include <string>
#include <optional>
struct PoolStats {
std::string hashrate;
std::optional<int64_t> dailyEarnings;
};

View file

@ -1,21 +0,0 @@
// src/noderunners/noderunners_pool.cpp
#include "public_pool.hpp"
std::string PublicPool::getApiUrl() const {
return "https://public-pool.io:40557/api/client/" + poolUser;
}
PoolStats PublicPool::parseResponse(const JsonDocument& doc) const {
uint64_t totalHashrate = 0;
for (JsonVariantConst worker : doc["workers"].as<JsonArrayConst>()) {
totalHashrate += static_cast<uint64_t>(std::llround(worker["hashRate"].as<double>()));
}
return PoolStats{
.hashrate = std::to_string(totalHashrate),
.dailyEarnings = std::nullopt // Public Pool doesn't support daily earnings
};
}

View file

@ -1,15 +0,0 @@
#pragma once
#include "lib/mining_pool/mining_pool_interface.hpp"
#include "lib/mining_pool/noderunners/noderunners_pool.hpp"
#include <icons/icons.h>
class PublicPool : public NoderunnersPool {
public:
std::string getApiUrl() const override;
bool hasLogo() const override { return false; }
std::string getDisplayLabel() const override { return "PUBLIC/POOL"; }
PoolStats parseResponse(const JsonDocument& doc) const override;
};

View file

@ -1,6 +0,0 @@
// src/noderunners/noderunners_pool.cpp
#include "satoshi_radio_pool.hpp"
std::string SatoshiRadioPool::getApiUrl() const {
return "https://pool.satoshiradio.nl/api/v1/users/" + poolUser;
}

View file

@ -1,14 +0,0 @@
#pragma once
#include "lib/mining_pool/mining_pool_interface.hpp"
#include "lib/mining_pool/noderunners/noderunners_pool.hpp"
#include <icons/icons.h>
class SatoshiRadioPool : public NoderunnersPool {
public:
std::string getApiUrl() const override;
bool hasLogo() const override { return false; }
std::string getDisplayLabel() const override { return "SATOSHI/RADIO"; } // Fallback if needed
};

View file

@ -1,123 +0,0 @@
#include "mining_pool_stats_fetch.hpp"
TaskHandle_t miningPoolStatsFetchTaskHandle;
std::string miningPoolName;
std::string miningPoolStatsHashrate;
int miningPoolStatsDailyEarnings;
std::string getMiningPoolStatsHashRate()
{
return miningPoolStatsHashrate;
}
int getMiningPoolStatsDailyEarnings()
{
return miningPoolStatsDailyEarnings;
}
void taskMiningPoolStatsFetch(void *pvParameters)
{
std::string poolName = preferences.getString("miningPoolName", DEFAULT_MINING_POOL_NAME).c_str();
auto poolInterface = PoolFactory::createPool(poolName);
std::string poolUser = preferences.getString("miningPoolUser", DEFAULT_MINING_POOL_USER).c_str();
// Main stats fetching loop
for (;;)
{
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
HTTPClient http;
http.setUserAgent(USER_AGENT);
poolInterface->setPoolUser(poolUser);
std::string apiUrl = poolInterface->getApiUrl();
http.begin(apiUrl.c_str());
poolInterface->prepareRequest(http);
int httpCode = http.GET();
if (httpCode == 200)
{
String payload = http.getString();
JsonDocument doc;
deserializeJson(doc, payload);
PoolStats stats = poolInterface->parseResponse(doc);
miningPoolStatsHashrate = stats.hashrate;
if (stats.dailyEarnings)
{
miningPoolStatsDailyEarnings = *stats.dailyEarnings;
}
else
{
miningPoolStatsDailyEarnings = 0; // or any other default value
}
if (workQueue != nullptr && (getCurrentScreen() == SCREEN_MINING_POOL_STATS_HASHRATE || getCurrentScreen() == SCREEN_MINING_POOL_STATS_EARNINGS))
{
WorkItem priceUpdate = {TASK_MINING_POOL_STATS_UPDATE, 0};
xQueueSend(workQueue, &priceUpdate, portMAX_DELAY);
}
}
else
{
Serial.print(
F("Error retrieving mining pool data. HTTP status code: "));
Serial.println(httpCode);
}
}
}
void downloadMiningPoolLogoTask(void *pvParameters) {
std::string poolName = preferences.getString("miningPoolName", DEFAULT_MINING_POOL_NAME).c_str();
auto poolInterface = PoolFactory::createPool(poolName);
PoolFactory::downloadPoolLogo(poolName, poolInterface.get());
// If we're on the mining pool stats screen, trigger a display update
if (getCurrentScreen() == SCREEN_MINING_POOL_STATS_HASHRATE) {
WorkItem priceUpdate = {TASK_MINING_POOL_STATS_UPDATE, 0};
xQueueSend(workQueue, &priceUpdate, portMAX_DELAY);
}
xTaskNotifyGive(miningPoolStatsFetchTaskHandle);
vTaskDelete(NULL);
}
void setupMiningPoolStatsFetchTask()
{
xTaskCreate(downloadMiningPoolLogoTask,
"logoDownload",
(6 * 1024),
NULL,
12,
NULL);
xTaskCreate(taskMiningPoolStatsFetch,
"miningPoolStatsFetch",
(6 * 1024),
NULL,
tskIDLE_PRIORITY,
&miningPoolStatsFetchTaskHandle);
}
std::unique_ptr<MiningPoolInterface>& getMiningPool()
{
static std::unique_ptr<MiningPoolInterface> currentMiningPool;
if (!currentMiningPool) {
std::string poolName = preferences.getString("miningPoolName", DEFAULT_MINING_POOL_NAME).c_str();
currentMiningPool = PoolFactory::createPool(poolName);
}
return currentMiningPool;
}
LogoData getMiningPoolLogo()
{
LogoData logo = getMiningPool()->getLogo();
return logo;
}

View file

@ -1,19 +0,0 @@
#pragma once
#include <Arduino.h>
#include <HTTPClient.h>
#include "mining_pool/pool_factory.hpp"
#include "lib/config.hpp"
#include "lib/shared.hpp"
extern TaskHandle_t miningPoolStatsFetchTaskHandle;
void setupMiningPoolStatsFetchTask();
void taskMiningPoolStatsFetch(void *pvParameters);
std::string getMiningPoolStatsHashRate();
int getMiningPoolStatsDailyEarnings();
std::unique_ptr<MiningPoolInterface>& getMiningPool();
LogoData getMiningPoolLogo();

View file

@ -252,10 +252,7 @@ void handleNostrZapCallback(const String &subId, nostr::SignedNostrEvent *event)
setEpdContent(textEpdContent);
vTaskDelay(pdMS_TO_TICKS(315 * NUM_SCREENS) + pdMS_TO_TICKS(250));
if (preferences.getBool("ledFlashOnZap", DEFAULT_LED_FLASH_ON_ZAP))
{
queueLedEffect(LED_EFFECT_NOSTR_ZAP);
}
queueLedEffect(LED_EFFECT_NOSTR_ZAP);
if (timerPeriod > 0)
{
esp_timer_start_periodic(screenRotateTimer,

View file

@ -171,13 +171,14 @@ int downloadUpdateHandler(char updateType)
break;
case UPDATE_WEBUI:
{
latestRelease = getLatestRelease(getWebUiFilename());
latestRelease = getLatestRelease("littlefs.bin");
// updateWebUi(latestRelease.fileUrl, U_SPIFFS);
// return 0;
}
break;
}
// First, download the expected SHA256
String expectedSHA256 = downloadSHA256(latestRelease.checksumUrl);
if (expectedSHA256.isEmpty())

View file

@ -8,7 +8,7 @@ const char *wsServerPrice = "wss://ws.coincap.io/prices?assets=bitcoin";
// WebsocketsClient client;
esp_websocket_client_handle_t clientPrice = NULL;
esp_websocket_client_config_t config;
uint currentPrice = 90000;
uint currentPrice = 50000;
unsigned long int lastPriceUpdate;
bool priceNotifyInit = false;
std::map<char, std::uint64_t> currencyMap;

View file

@ -33,28 +33,15 @@ void workerTask(void *pvParameters) {
parseBitaxeBestDiff(getBitaxeBestDiff());
}
setEpdContent(taskEpdContent);
break;
}
case TASK_MINING_POOL_STATS_UPDATE: {
if (getCurrentScreen() == SCREEN_MINING_POOL_STATS_HASHRATE) {
taskEpdContent =
parseMiningPoolStatsHashRate(getMiningPoolStatsHashRate(), *getMiningPool());
} else if (getCurrentScreen() == SCREEN_MINING_POOL_STATS_EARNINGS) {
taskEpdContent =
parseMiningPoolStatsDailyEarnings(getMiningPoolStatsDailyEarnings(), getMiningPool()->getDailyEarningsLabel(), *getMiningPool());
}
setEpdContent(taskEpdContent);
break;
}
break;
case TASK_PRICE_UPDATE: {
uint currency = getCurrentCurrency();
uint price = getPrice(currency);
if (getCurrentScreen() == SCREEN_BTC_TICKER) {
taskEpdContent = parsePriceData(price, currency, preferences.getBool("suffixPrice", DEFAULT_SUFFIX_PRICE),
preferences.getBool("mowMode", DEFAULT_MOW_MODE),
preferences.getBool("suffixShareDot", DEFAULT_SUFFIX_SHARE_DOT)
);
taskEpdContent = parsePriceData(price, currency, preferences.getBool("suffixPrice", DEFAULT_SUFFIX_PRICE));
} else if (getCurrentScreen() == SCREEN_SATS_PER_CURRENCY) {
taskEpdContent = parseSatsPerCurrency(price, currency, preferences.getBool("useSatsSymbol", DEFAULT_USE_SATS_SYMBOL));
} else {
@ -189,17 +176,6 @@ void setCurrentScreen(uint newScreen) {
return;
}
break;
}
case SCREEN_MINING_POOL_STATS_HASHRATE:
case SCREEN_MINING_POOL_STATS_EARNINGS: {
if (preferences.getBool("miningPoolStats", DEFAULT_MINING_POOL_STATS_ENABLED)) {
WorkItem miningPoolStatsUpdate = {TASK_MINING_POOL_STATS_UPDATE, 0};
xQueueSend(workQueue, &miningPoolStatsUpdate, portMAX_DELAY);
} else {
setCurrentScreen(SCREEN_BLOCK_HEIGHT);
return;
}
break;
}
}

View file

@ -6,7 +6,6 @@
#include <data_handler.hpp>
#include <bitaxe_handler.hpp>
#include "lib/mining_pool/mining_pool_stats_handler.hpp"
#include "lib/epd.hpp"
#include "lib/shared.hpp"
@ -24,8 +23,7 @@ typedef enum {
TASK_BLOCK_UPDATE,
TASK_FEE_UPDATE,
TASK_TIME_UPDATE,
TASK_BITAXE_UPDATE,
TASK_MINING_POOL_STATS_UPDATE
TASK_BITAXE_UPDATE
} TaskType;
typedef struct {

View file

@ -143,40 +143,4 @@ String calculateSHA256(WiFiClient *stream, size_t contentLength) {
}
return result;
}
// uint8_t* getOceanIcon() {
// zlib_turbo zt;
// int iUncompSize = zt.gzip_info((uint8_t *)ocean_logo_comp, ocean_logo_size);
// uint8_t *pUncompressed;
// pUncompressed = (uint8_t *)malloc(iUncompSize+4);
// zt.gunzip((uint8_t *)ocean_logo_comp, ocean_logo_size, pUncompressed);
// }
WiFiClientSecure HttpHelper::secureClient;
WiFiClient HttpHelper::insecureClient;
bool HttpHelper::certBundleSet = false;
HTTPClient* HttpHelper::begin(const String& url) {
HTTPClient* http = new HTTPClient();
if (url.startsWith("https://")) {
if (!certBundleSet) {
secureClient.setCACertBundle(rootca_crt_bundle_start);
certBundleSet = true;
}
http->begin(secureClient, url);
} else {
http->begin(insecureClient, url);
}
http->setUserAgent(USER_AGENT);
return http;
}
void HttpHelper::end(HTTPClient* http) {
if (http) {
http->end();
delete http;
}
}

View file

@ -1,7 +1,6 @@
#pragma once
#include "MCP23017.h"
// #include <zlib_turbo.h>
#include <Adafruit_MCP23X17.h>
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>
#include <Preferences.h>
@ -12,18 +11,15 @@
#include <mbedtls/md.h>
#include "esp_crt_bundle.h"
#include <Update.h>
#include <HTTPClient.h>
#include <mutex>
#include <utils.hpp>
#include "defaults.hpp"
#define USER_AGENT "BTClock/3.0"
extern MCP23017 mcp1;
extern Adafruit_MCP23X17 mcp1;
#ifdef IS_BTCLOCK_V8
extern MCP23017 mcp2;
extern Adafruit_MCP23X17 mcp2;
#endif
extern Preferences preferences;
extern std::mutex mcpMutex;
@ -45,16 +41,24 @@ const PROGMEM int SCREEN_BLOCK_FEE_RATE = 6;
const PROGMEM int SCREEN_SATS_PER_CURRENCY = 10;
const PROGMEM int SCREEN_BTC_TICKER = 20;
// const PROGMEM int SCREEN_BTC_TICKER_USD = 20;
// const PROGMEM int SCREEN_BTC_TICKER_EUR = 21;
// const PROGMEM int SCREEN_BTC_TICKER_GBP = 22;
// const PROGMEM int SCREEN_BTC_TICKER_JPY = 23;
// const PROGMEM int SCREEN_BTC_TICKER_AUD = 24;
// const PROGMEM int SCREEN_BTC_TICKER_CAD = 25;
const PROGMEM int SCREEN_MARKET_CAP = 30;
const PROGMEM int SCREEN_MINING_POOL_STATS_HASHRATE = 70;
const PROGMEM int SCREEN_MINING_POOL_STATS_EARNINGS = 71;
// const PROGMEM int SCREEN_MARKET_CAP_USD = 30;
// const PROGMEM int SCREEN_MARKET_CAP_EUR = 31;
// const PROGMEM int SCREEN_MARKET_CAP_GBP = 32;
// const PROGMEM int SCREEN_MARKET_CAP_JPY = 33;
// const PROGMEM int SCREEN_MARKET_CAP_AUD = 34;
// const PROGMEM int SCREEN_MARKET_CAP_CAD = 35;
const PROGMEM int SCREEN_BITAXE_HASHRATE = 80;
const PROGMEM int SCREEN_BITAXE_BESTDIFF = 81;
const PROGMEM int SCREEN_COUNTDOWN = 98;
const PROGMEM int SCREEN_CUSTOM = 99;
const int SCREEN_COUNT = 7;
@ -69,12 +73,7 @@ const int usPerMinute = 60 * usPerSecond;
extern const char *isrg_root_x1cert;
extern const uint8_t rootca_crt_bundle_start[] asm("_binary_x509_crt_bundle_start");
// extern const uint8_t ocean_logo_comp[] asm("_binary_ocean_gz_start");
// extern const uint8_t ocean_logo_comp_end[] asm("_binary_ocean_gz_end");
// uint8_t* getOceanIcon();
// const size_t ocean_logo_size = ocean_logo_comp_end - ocean_logo_comp;
const PROGMEM char UPDATE_FIRMWARE = U_FLASH;
const PROGMEM char UPDATE_WEBUI = U_SPIFFS;
@ -86,26 +85,4 @@ struct ScreenMapping {
};
String calculateSHA256(uint8_t* data, size_t len);
String calculateSHA256(WiFiClient *stream, size_t contentLength);
namespace ArduinoJson {
template <typename T>
struct Converter<std::vector<T>> {
static void toJson(const std::vector<T>& src, JsonVariant dst) {
JsonArray array = dst.to<JsonArray>();
for (T item : src)
array.add(item);
}
};
}
class HttpHelper {
public:
static HTTPClient* begin(const String& url);
static void end(HTTPClient* http);
private:
static WiFiClientSecure secureClient;
static bool certBundleSet;
static WiFiClient insecureClient;
};
String calculateSHA256(WiFiClient *stream, size_t contentLength);

View file

@ -72,10 +72,6 @@ void IRAM_ATTR minuteTimerISR(void *arg) {
vTaskNotifyGiveFromISR(bitaxeFetchTaskHandle, &xHigherPriorityTaskWoken);
}
if (miningPoolStatsFetchTaskHandle != NULL) {
vTaskNotifyGiveFromISR(miningPoolStatsFetchTaskHandle, &xHigherPriorityTaskWoken);
}
if (xHigherPriorityTaskWoken == pdTRUE) {
portYIELD_FROM_ISR();
}

View file

@ -1,37 +1,26 @@
#include "webserver.hpp"
static const char* JSON_CONTENT = "application/json";
static const char *const PROGMEM strSettings[] = {
"hostnamePrefix", "mempoolInstance", "nostrPubKey", "nostrRelay", "bitaxeHostname", "miningPoolName", "miningPoolUser", "nostrZapPubkey", "httpAuthUser", "httpAuthPass", "gitReleaseUrl", "poolLogosUrl"};
static const char *const PROGMEM uintSettings[] = {"minSecPriceUpd", "fullRefreshMin", "ledBrightness", "flMaxBrightness", "flEffectDelay", "luxLightToggle", "wpTimeout", "srcV2Currency"};
static const char *const PROGMEM boolSettings[] = {"fetchEurPrice", "ledTestOnPower", "ledFlashOnUpd",
"mdnsEnabled", "otaEnabled", "stealFocus",
"mcapBigChar", "useSatsSymbol", "useBlkCountdown",
"suffixPrice", "disableLeds", "ownDataSource",
"mowMode", "suffixShareDot", "flOffWhenDark",
"flAlwaysOn", "flDisable", "flFlashOnUpd",
"mempoolSecure", "useNostr", "bitaxeEnabled",
"miningPoolStats", "verticalDesc",
"nostrZapNotify", "stagingSource", "httpAuthEnabled"};
AsyncWebServer server(80);
AsyncEventSource events("/events");
TaskHandle_t eventSourceTaskHandle;
#define HTTP_OK 200
#define HTTP_BAD_REQUEST 400
void setupWebserver()
{
events.onConnect([](AsyncEventSourceClient *client)
{ client->send("welcome", NULL, millis(), 1000); });
server.addHandler(&events);
// server.ad.
// server.serveStatic("/css", LittleFS, "/css/");
// server.serveStatic("/fonts", LittleFS, "/fonts/");
// server.serveStatic("/build", LittleFS, "/build");
// server.serveStatic("/swagger.json", LittleFS, "/swagger.json");
// server.serveStatic("/api.html", LittleFS, "/api.html");
// server.serveStatic("/fs_hash.txt", LittleFS, "/fs_hash.txt");
AsyncStaticWebHandler &staticHandler = server.serveStatic("/", LittleFS, "/").setDefaultFile("index.html");
server.rewrite("/convert", "/");
server.rewrite("/api", "/");
@ -42,6 +31,7 @@ void setupWebserver()
preferences.getString("httpAuthPass", DEFAULT_HTTP_AUTH_PASSWORD));
}
// server.on("/", HTTP_GET, onIndex);
server.on("/api/status", HTTP_GET, onApiStatus);
server.on("/api/system_status", HTTP_GET, onApiSystemStatus);
server.on("/api/wifi_set_tx_power", HTTP_GET, onApiSetWifiTxPower);
@ -61,8 +51,8 @@ void setupWebserver()
server.on("/api/show/text", HTTP_GET, onApiShowText);
server.on("/api/screen/next", HTTP_GET, onApiScreenControl);
server.on("/api/screen/previous", HTTP_GET, onApiScreenControl);
server.on("/api/screen/next", HTTP_GET, onApiScreenNext);
server.on("/api/screen/previous", HTTP_GET, onApiScreenPrevious);
AsyncCallbackJsonWebHandler *settingsPatchHandler =
new AsyncCallbackJsonWebHandler("/api/json/settings", onApiSettingsPatch);
@ -222,6 +212,36 @@ void asyncFileUpdateHandler(AsyncWebServerRequest *request, String filename, siz
void asyncFirmwareUpdateHandler(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final)
{
asyncFileUpdateHandler(request, filename, index, data, len, final, U_FLASH);
// if (!index)
// {
// Serial.printf("Update Start: %s\n", filename.c_str());
// // Update.runAsync(true);
// if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000))
// {
// Update.printError(Serial);
// }
// }
// if (!Update.hasError())
// {
// if (Update.write(data, len) != len)
// {
// Update.printError(Serial);
// }
// }
// if (final)
// {
// if (Update.end(true))
// {
// Serial.printf("Update Success: %uB\n", index + len);
// onApiRestart(request);
// }
// else
// {
// Update.printError(Serial);
// }
// }
}
JsonDocument getStatusObject()
@ -240,7 +260,7 @@ JsonDocument getStatusObject()
// root["espPsramSize"] = ESP.getPsramSize();
JsonObject conStatus = root["connectionStatus"].to<JsonObject>();
conStatus["price"] = isPriceNotifyConnected();
conStatus["blocks"] = isBlockNotifyConnected();
conStatus["V2"] = V2Notify::isV2NotifyConnected();
@ -275,6 +295,7 @@ JsonDocument getLedStatusObject()
for (uint i = 0; i < pixels.numPixels(); i++)
{
uint32_t pixColor = pixels.getPixelColor(pixels.numPixels() - i - 1);
uint alpha = (pixColor >> 24) & 0xFF;
uint red = (pixColor >> 16) & 0xFF;
uint green = (pixColor >> 8) & 0xFF;
uint blue = pixColor & 0xFF;
@ -292,26 +313,25 @@ JsonDocument getLedStatusObject()
return root;
}
void eventSourceUpdate() {
if (!events.count()) return;
JsonDocument doc = getStatusObject();
doc["leds"] = getLedStatusObject()["data"];
void eventSourceUpdate()
{
if (!events.count())
return;
JsonDocument root = getStatusObject();
JsonArray data = root["data"].to<JsonArray>();
// Get current EPD content directly as array
std::array<String, NUM_SCREENS> epdContent = getCurrentEpdContent();
// Add EPD content arrays
JsonArray data = doc["data"].to<JsonArray>();
// Copy array elements directly
for(const auto& content : epdContent) {
data.add(content);
}
root["leds"] = getLedStatusObject()["data"];
String buffer;
serializeJson(doc, buffer);
events.send(buffer.c_str(), "status");
String epdContent[NUM_SCREENS];
std::array<String, NUM_SCREENS> retEpdContent = getCurrentEpdContent();
std::copy(std::begin(retEpdContent), std::end(retEpdContent), epdContent);
copyArray(epdContent, data);
String bufString;
serializeJson(root, bufString);
events.send(bufString.c_str(), "status");
}
/**
@ -321,22 +341,21 @@ void eventSourceUpdate() {
void onApiStatus(AsyncWebServerRequest *request)
{
AsyncResponseStream *response =
request->beginResponseStream(JSON_CONTENT);
request->beginResponseStream("application/json");
JsonDocument root = getStatusObject();
// Get current EPD content directly as array
std::array<String, NUM_SCREENS> epdContent = getCurrentEpdContent();
// Add EPD content arrays
JsonArray data = root["data"].to<JsonArray>();
// Copy array elements directly
for(const auto& content : epdContent) {
data.add(content);
}
JsonArray rendered = root["rendered"].to<JsonArray>();
String epdContent[NUM_SCREENS];
root["leds"] = getLedStatusObject()["data"];
std::array<String, NUM_SCREENS> retEpdContent = getCurrentEpdContent();
std::copy(std::begin(retEpdContent), std::end(retEpdContent), epdContent);
copyArray(epdContent, data);
copyArray(epdContent, rendered);
serializeJson(root, *response);
request->send(response);
@ -349,7 +368,7 @@ void onApiStatus(AsyncWebServerRequest *request)
void onApiActionPause(AsyncWebServerRequest *request)
{
setTimerActive(false);
request->send(HTTP_OK);
request->send(200);
};
/**
@ -359,7 +378,7 @@ void onApiActionPause(AsyncWebServerRequest *request)
void onApiActionTimerRestart(AsyncWebServerRequest *request)
{
setTimerActive(true);
request->send(HTTP_OK);
request->send(200);
}
/**
@ -373,7 +392,7 @@ void onApiFullRefresh(AsyncWebServerRequest *request)
setEpdContent(newEpdContent, true);
request->send(HTTP_OK);
request->send(200);
}
/**
@ -388,21 +407,28 @@ void onApiShowScreen(AsyncWebServerRequest *request)
uint currentScreen = p->value().toInt();
setCurrentScreen(currentScreen);
}
request->send(HTTP_OK);
request->send(200);
}
/**
* @Api
* @Path("/api/screen/next")
*/
void onApiScreenControl(AsyncWebServerRequest *request) {
const String& action = request->url();
if (action.endsWith("/next")) {
nextScreen();
} else if (action.endsWith("/previous")) {
previousScreen();
}
request->send(HTTP_OK);
void onApiScreenNext(AsyncWebServerRequest *request)
{
nextScreen();
request->send(200);
}
/**
* @Api
* @Path("/api/screen/previous")
*/
void onApiScreenPrevious(AsyncWebServerRequest *request)
{
previousScreen();
request->send(200);
}
void onApiShowText(AsyncWebServerRequest *request)
@ -422,7 +448,7 @@ void onApiShowText(AsyncWebServerRequest *request)
setEpdContent(textEpdContent);
}
setCurrentScreen(SCREEN_CUSTOM);
request->send(HTTP_OK);
request->send(200);
}
void onApiShowTextAdvanced(AsyncWebServerRequest *request, JsonVariant &json)
@ -440,7 +466,7 @@ void onApiShowTextAdvanced(AsyncWebServerRequest *request, JsonVariant &json)
setEpdContent(epdContent);
setCurrentScreen(SCREEN_CUSTOM);
request->send(HTTP_OK);
request->send(200);
}
void onApiSettingsPatch(AsyncWebServerRequest *request, JsonVariant &json)
@ -458,49 +484,49 @@ void onApiSettingsPatch(AsyncWebServerRequest *request, JsonVariant &json)
bool settingsChanged = true;
if (settings["fgColor"].is<String>())
if (settings.containsKey("fgColor"))
{
String fgColor = settings["fgColor"].as<String>();
uint32_t color = strtol(fgColor.c_str(), NULL, 16);
preferences.putUInt("fgColor", color);
setFgColor(color);
preferences.putUInt("fgColor", strtol(fgColor.c_str(), NULL, 16));
setFgColor(int(strtol(fgColor.c_str(), NULL, 16)));
Serial.print(F("Setting foreground color to "));
Serial.println(color);
Serial.println(strtol(fgColor.c_str(), NULL, 16));
settingsChanged = true;
}
if (settings["bgColor"].is<String>())
if (settings.containsKey("bgColor"))
{
String bgColor = settings["bgColor"].as<String>();
uint32_t color = strtol(bgColor.c_str(), NULL, 16);
preferences.putUInt("bgColor", color);
setBgColor(color);
preferences.putUInt("bgColor", strtol(bgColor.c_str(), NULL, 16));
setBgColor(int(strtol(bgColor.c_str(), NULL, 16)));
Serial.print(F("Setting background color to "));
Serial.println(bgColor.c_str());
settingsChanged = true;
}
if (settings["timePerScreen"].is<uint>())
if (settings.containsKey("timePerScreen"))
{
preferences.putUInt("timerSeconds",
settings["timePerScreen"].as<uint>() * 60);
}
String strSettings[] = {"hostnamePrefix", "mempoolInstance", "nostrPubKey", "nostrRelay", "bitaxeHostname", "nostrZapPubkey", "httpAuthUser", "httpAuthPass", "gitReleaseUrl"};
for (String setting : strSettings)
{
if (settings[setting].is<String>())
if (settings.containsKey(setting))
{
preferences.putString(setting.c_str(), settings[setting].as<String>());
Serial.printf("Setting %s to %s\r\n", setting.c_str(),
settings[setting].as<String>().c_str());
settings[setting].as<String>());
}
}
String uintSettings[] = {"minSecPriceUpd", "fullRefreshMin", "ledBrightness", "flMaxBrightness", "flEffectDelay", "luxLightToggle", "wpTimeout", "srcV2Currency"};
for (String setting : uintSettings)
{
if (settings[setting].is<uint>())
if (settings.containsKey(setting))
{
preferences.putUInt(setting.c_str(), settings[setting].as<uint>());
Serial.printf("Setting %s to %d\r\n", setting.c_str(),
@ -508,7 +534,7 @@ void onApiSettingsPatch(AsyncWebServerRequest *request, JsonVariant &json)
}
}
if (settings["tzOffset"].is<int>())
if (settings.containsKey("tzOffset"))
{
int gmtOffset = settings["tzOffset"].as<int>() * 60;
size_t written = preferences.putInt("gmtOffset", gmtOffset);
@ -516,17 +542,25 @@ void onApiSettingsPatch(AsyncWebServerRequest *request, JsonVariant &json)
gmtOffset, settings["tzOffset"].as<int>(), written);
}
String boolSettings[] = {"fetchEurPrice", "ledTestOnPower", "ledFlashOnUpd",
"mdnsEnabled", "otaEnabled", "stealFocus",
"mcapBigChar", "useSatsSymbol", "useBlkCountdown",
"suffixPrice", "disableLeds", "ownDataSource",
"flAlwaysOn", "flDisable", "flFlashOnUpd",
"mempoolSecure", "useNostr", "bitaxeEnabled",
"nostrZapNotify", "stagingSource", "httpAuthEnabled"};
for (String setting : boolSettings)
{
if (settings[setting].is<bool>())
if (settings.containsKey(setting))
{
preferences.putBool(setting.c_str(), settings[setting].as<bool>());
preferences.putBool(setting.c_str(), settings[setting].as<boolean>());
Serial.printf("Setting %s to %d\r\n", setting.c_str(),
settings[setting].as<bool>());
settings[setting].as<boolean>());
}
}
if (settings["screens"].is<JsonArray>())
if (settings.containsKey("screens"))
{
for (JsonVariant screen : settings["screens"].as<JsonArray>())
{
@ -534,12 +568,12 @@ void onApiSettingsPatch(AsyncWebServerRequest *request, JsonVariant &json)
uint id = s["id"].as<uint>();
String key = "screen[" + String(id) + "]";
String prefKey = "screen" + String(id) + "Visible";
bool visible = s["enabled"].as<bool>();
bool visible = s["enabled"].as<boolean>();
preferences.putBool(prefKey.c_str(), visible);
}
}
if (settings["actCurrencies"].is<JsonArray>())
if (settings.containsKey("actCurrencies"))
{
String actCurrencies;
@ -553,10 +587,10 @@ void onApiSettingsPatch(AsyncWebServerRequest *request, JsonVariant &json)
}
preferences.putString("actCurrencies", actCurrencies.c_str());
Serial.printf("Set actCurrencies: %s\n", actCurrencies.c_str());
Serial.printf("Set actCurrencies: %s\n", actCurrencies);
}
if (settings["txPower"].is<int>())
if (settings.containsKey("txPower"))
{
int txPower = settings["txPower"].as<int>();
@ -583,7 +617,7 @@ void onApiSettingsPatch(AsyncWebServerRequest *request, JsonVariant &json)
}
}
request->send(HTTP_OK);
request->send(200);
if (settingsChanged)
{
queueLedEffect(LED_FLASH_SUCCESS);
@ -592,7 +626,7 @@ void onApiSettingsPatch(AsyncWebServerRequest *request, JsonVariant &json)
void onApiRestart(AsyncWebServerRequest *request)
{
request->send(HTTP_OK);
request->send(200);
if (events.count())
events.send("closing");
@ -606,7 +640,7 @@ void onApiIdentify(AsyncWebServerRequest *request)
{
queueLedEffect(LED_FLASH_IDENTIFY);
request->send(HTTP_OK);
request->send(200);
}
/**
@ -653,10 +687,6 @@ void onApiSettingsGet(AsyncWebServerRequest *request)
root["useBlkCountdown"] = preferences.getBool("useBlkCountdown", DEFAULT_USE_BLOCK_COUNTDOWN);
root["suffixPrice"] = preferences.getBool("suffixPrice", DEFAULT_SUFFIX_PRICE);
root["disableLeds"] = preferences.getBool("disableLeds", DEFAULT_DISABLE_LEDS);
root["mowMode"] = preferences.getBool("mowMode", DEFAULT_MOW_MODE);
root["verticalDesc"] = preferences.getBool("verticalDesc", DEFAULT_VERTICAL_DESC);
root["suffixShareDot"] = preferences.getBool("suffixShareDot", DEFAULT_SUFFIX_SHARE_DOT);
root["hostnamePrefix"] = preferences.getString("hostnamePrefix", DEFAULT_HOSTNAME_PREFIX);
root["hostname"] = getMyHostname();
@ -671,20 +701,15 @@ void onApiSettingsGet(AsyncWebServerRequest *request)
root["nostrZapNotify"] = preferences.getBool("nostrZapNotify", DEFAULT_ZAP_NOTIFY_ENABLED);
root["nostrZapPubkey"] = preferences.getString("nostrZapPubkey", DEFAULT_ZAP_NOTIFY_PUBKEY);
root["ledFlashOnZap"] = preferences.getBool("ledFlashOnZap", DEFAULT_LED_FLASH_ON_ZAP);
root["gitReleaseUrl"] = preferences.getString("gitReleaseUrl", DEFAULT_GIT_RELEASE_URL);
root["bitaxeEnabled"] = preferences.getBool("bitaxeEnabled", DEFAULT_BITAXE_ENABLED);
root["bitaxeHostname"] = preferences.getString("bitaxeHostname", DEFAULT_BITAXE_HOSTNAME);
root["miningPoolStats"] = preferences.getBool("miningPoolStats", DEFAULT_MINING_POOL_STATS_ENABLED);
root["miningPoolName"] = preferences.getString("miningPoolName", DEFAULT_MINING_POOL_NAME);
root["miningPoolUser"] = preferences.getString("miningPoolUser", DEFAULT_MINING_POOL_USER);
root["availablePools"] = PoolFactory::getAvailablePools();
root["httpAuthEnabled"] = preferences.getBool("httpAuthEnabled", DEFAULT_HTTP_AUTH_ENABLED);
root["httpAuthUser"] = preferences.getString("httpAuthUser", DEFAULT_HTTP_AUTH_USERNAME);
root["httpAuthPass"] = preferences.getString("httpAuthPass", DEFAULT_HTTP_AUTH_PASSWORD);
#ifdef HAS_FRONTLIGHT
root["hasFrontlight"] = true;
root["flDisable"] = preferences.getBool("flDisable");
@ -692,12 +717,8 @@ void onApiSettingsGet(AsyncWebServerRequest *request)
root["flAlwaysOn"] = preferences.getBool("flAlwaysOn", DEFAULT_FL_ALWAYS_ON);
root["flEffectDelay"] = preferences.getUInt("flEffectDelay", DEFAULT_FL_EFFECT_DELAY);
root["flFlashOnUpd"] = preferences.getBool("flFlashOnUpd", DEFAULT_FL_FLASH_ON_UPDATE);
root["flFlashOnZap"] = preferences.getBool("flFlashOnZap", DEFAULT_FL_FLASH_ON_ZAP);
root["hasLightLevel"] = hasLightLevel();
root["luxLightToggle"] = preferences.getUInt("luxLightToggle", DEFAULT_LUX_LIGHT_TOGGLE);
root["flOffWhenDark"] = preferences.getBool("flOffWhenDark", DEFAULT_FL_OFF_WHEN_DARK);
#else
root["hasFrontlight"] = false;
root["hasLightLevel"] = false;
@ -718,8 +739,17 @@ void onApiSettingsGet(AsyncWebServerRequest *request)
#endif
JsonArray screens = root["screens"].to<JsonArray>();
root["actCurrencies"] = getActiveCurrencies();
root["availableCurrencies"] = getAvailableCurrencies();
JsonArray actCurrencies = root["actCurrencies"].to<JsonArray>();
for (const auto &str : getActiveCurrencies())
{
actCurrencies.add(str);
}
JsonArray availableCurrencies = root["availableCurrencies"].to<JsonArray>();
for (const auto &str : getAvailableCurrencies())
{
availableCurrencies.add(str);
}
std::vector<ScreenMapping> screenNameMap = getScreenNameMap();
@ -732,10 +762,8 @@ void onApiSettingsGet(AsyncWebServerRequest *request)
o["enabled"] = preferences.getBool(key.c_str(), true);
}
root["poolLogosUrl"] = preferences.getString("poolLogosUrl", DEFAULT_MINING_POOL_LOGOS_URL);
AsyncResponseStream *response =
request->beginResponseStream(JSON_CONTENT);
request->beginResponseStream("application/json");
serializeJson(root, *response);
request->send(response);
@ -747,9 +775,8 @@ bool processEpdColorSettings(AsyncWebServerRequest *request)
if (request->hasParam("fgColor", true))
{
const AsyncWebParameter *fgColor = request->getParam("fgColor", true);
uint32_t color = strtol(fgColor->value().c_str(), NULL, 16);
preferences.putUInt("fgColor", color);
setFgColor(color);
preferences.putUInt("fgColor", strtol(fgColor->value().c_str(), NULL, 16));
setFgColor(int(strtol(fgColor->value().c_str(), NULL, 16)));
// Serial.print(F("Setting foreground color to "));
// Serial.println(fgColor->value().c_str());
settingsChanged = true;
@ -758,9 +785,8 @@ bool processEpdColorSettings(AsyncWebServerRequest *request)
{
const AsyncWebParameter *bgColor = request->getParam("bgColor", true);
uint32_t color = strtol(bgColor->value().c_str(), NULL, 16);
preferences.putUInt("bgColor", color);
setBgColor(color);
preferences.putUInt("bgColor", strtol(bgColor->value().c_str(), NULL, 16));
setBgColor(int(strtol(bgColor->value().c_str(), NULL, 16)));
// Serial.print(F("Setting background color to "));
// Serial.println(bgColor->value().c_str());
settingsChanged = true;
@ -772,7 +798,7 @@ bool processEpdColorSettings(AsyncWebServerRequest *request)
void onApiSystemStatus(AsyncWebServerRequest *request)
{
AsyncResponseStream *response =
request->beginResponseStream(JSON_CONTENT);
request->beginResponseStream("application/json");
JsonDocument root;
@ -780,9 +806,6 @@ void onApiSystemStatus(AsyncWebServerRequest *request)
root["espHeapSize"] = ESP.getHeapSize();
root["espFreePsram"] = ESP.getFreePsram();
root["espPsramSize"] = ESP.getPsramSize();
root["fsUsedBytes"] = LittleFS.usedBytes();
root["fsTotalBytes"] = LittleFS.totalBytes();
root["rssi"] = WiFi.RSSI();
root["txPower"] = WiFi.getTxPower();
@ -814,19 +837,19 @@ void onApiSetWifiTxPower(AsyncWebServerRequest *request)
if (WiFi.setTxPower(static_cast<wifi_power_t>(txPower)))
{
preferences.putInt("txPower", txPower);
request->send(HTTP_OK, "application/json", "{\"setTxPower\": \"ok\"}");
request->send(200, "application/json", "{\"setTxPower\": \"ok\"}");
return;
}
}
}
return request->send(HTTP_BAD_REQUEST);
return request->send(400);
}
void onApiLightsStatus(AsyncWebServerRequest *request)
{
AsyncResponseStream *response =
request->beginResponseStream(JSON_CONTENT);
request->beginResponseStream("application/json");
serializeJson(getLedStatusObject()["data"], *response);
@ -836,7 +859,7 @@ void onApiLightsStatus(AsyncWebServerRequest *request)
void onApiStopDataSources(AsyncWebServerRequest *request)
{
AsyncResponseStream *response =
request->beginResponseStream(JSON_CONTENT);
request->beginResponseStream("application/json");
stopPriceNotify();
stopBlockNotify();
@ -847,7 +870,7 @@ void onApiStopDataSources(AsyncWebServerRequest *request)
void onApiRestartDataSources(AsyncWebServerRequest *request)
{
AsyncResponseStream *response =
request->beginResponseStream(JSON_CONTENT);
request->beginResponseStream("application/json");
restartPriceNotify();
restartBlockNotify();
@ -860,7 +883,7 @@ void onApiRestartDataSources(AsyncWebServerRequest *request)
void onApiLightsOff(AsyncWebServerRequest *request)
{
setLights(0, 0, 0);
request->send(HTTP_OK);
request->send(200);
}
void onApiLightsSetColor(AsyncWebServerRequest *request)
@ -868,7 +891,7 @@ void onApiLightsSetColor(AsyncWebServerRequest *request)
if (request->hasParam("c"))
{
AsyncResponseStream *response =
request->beginResponseStream(JSON_CONTENT);
request->beginResponseStream("application/json");
String rgbColor = request->getParam("c")->value();
@ -892,7 +915,7 @@ void onApiLightsSetColor(AsyncWebServerRequest *request)
}
else
{
request->send(HTTP_BAD_REQUEST);
request->send(400);
}
}
@ -909,7 +932,7 @@ void onApiLightsSetJson(AsyncWebServerRequest *request, JsonVariant &json)
}
Serial.printf("Invalid values for LED set %d\n", lights.size());
request->send(HTTP_BAD_REQUEST);
request->send(400);
return;
}
@ -917,27 +940,27 @@ void onApiLightsSetJson(AsyncWebServerRequest *request, JsonVariant &json)
{
unsigned int red, green, blue;
if (lights[i]["red"].is<uint>() && lights[i]["green"].is<uint>() &&
lights[i]["blue"].is<uint>())
if (lights[i].containsKey("red") && lights[i].containsKey("green") &&
lights[i].containsKey("blue"))
{
red = lights[i]["red"].as<uint>();
green = lights[i]["green"].as<uint>();
blue = lights[i]["blue"].as<uint>();
}
else if (lights[i]["hex"].is<const char*>())
else if (lights[i].containsKey("hex"))
{
if (!sscanf(lights[i]["hex"].as<String>().c_str(), "#%02X%02X%02X", &red,
&green, &blue) == 3)
{
Serial.printf("Invalid hex for LED %d\n", i);
request->send(HTTP_BAD_REQUEST);
request->send(400);
return;
}
}
else
{
Serial.printf("No valid color for LED %d\n", i);
request->send(HTTP_BAD_REQUEST);
request->send(400);
return;
}
@ -948,7 +971,7 @@ void onApiLightsSetJson(AsyncWebServerRequest *request, JsonVariant &json)
pixels.show();
saveLedState();
request->send(HTTP_OK);
request->send(200);
}
void onIndex(AsyncWebServerRequest *request)
@ -958,14 +981,48 @@ void onIndex(AsyncWebServerRequest *request)
void onNotFound(AsyncWebServerRequest *request)
{
// Access-Control-Request-Method == POST might be better
// Serial.printf("NotFound, URL[%s]\n", request->url());
// Serial.printf("NotFound, METHOD[%s]\n", request->methodToString());
// int headers = request->headers();
// int i;
// for (i = 0; i < headers; i++)
// {
// AsyncWebHeader *h = request->getHeader(i);
// Serial.printf("NotFound HEADER[%s]: %s\n", h->name().c_str(),
// h->value().c_str());
// }
// int params = request->params();
// for (int i = 0; i < params; i++)
// {
// const AsyncWebParameter *p = request->getParam(i);
// if (p->isFile())
// { // p->isPost() is also true
// Serial.printf("NotFound FILE[%s]: %s, size: %u\n",
// p->name().c_str(), p->value().c_str(), p->size());
// }
// else if (p->isPost())
// {
// Serial.printf("NotFound POST[%s]: %s\n", p->name().c_str(),
// p->value().c_str());
// }
// else
// {
// Serial.printf("NotFound GET[%s]: %s\n", p->name().c_str(),
// p->value().c_str());
// }
// }
// Access-Control-Request-Method == POST might be better
if (request->method() == HTTP_OPTIONS ||
request->hasHeader("Sec-Fetch-Mode"))
{
// Serial.printf("NotFound, Return[%d]\n", 200);
request->send(HTTP_OK);
request->send(200);
}
else
{
@ -1001,7 +1058,7 @@ void onApiShowCurrency(AsyncWebServerRequest *request)
setCurrentCurrency(curChar);
setCurrentScreen(getCurrentScreen());
request->send(HTTP_OK);
request->send(200);
return;
}
request->send(404);
@ -1012,13 +1069,13 @@ void onApiFrontlightOn(AsyncWebServerRequest *request)
{
frontlightFadeInAll();
request->send(HTTP_OK);
request->send(200);
}
void onApiFrontlightStatus(AsyncWebServerRequest *request)
{
AsyncResponseStream *response =
request->beginResponseStream(JSON_CONTENT);
request->beginResponseStream("application/json");
JsonDocument root;
@ -1037,7 +1094,7 @@ void onApiFrontlightFlash(AsyncWebServerRequest *request)
{
frontlightFlash(preferences.getUInt("flEffectDelay"));
request->send(HTTP_OK);
request->send(200);
}
void onApiFrontlightSetBrightness(AsyncWebServerRequest *request)
@ -1045,11 +1102,11 @@ void onApiFrontlightSetBrightness(AsyncWebServerRequest *request)
if (request->hasParam("b"))
{
frontlightSetBrightness(request->getParam("b")->value().toInt());
request->send(HTTP_OK);
request->send(200);
}
else
{
request->send(HTTP_BAD_REQUEST);
request->send(400);
}
}
@ -1057,6 +1114,6 @@ void onApiFrontlightOff(AsyncWebServerRequest *request)
{
frontlightFadeOutAll();
request->send(HTTP_OK);
request->send(200);
}
#endif

View file

@ -14,7 +14,6 @@
#include "lib/price_notify.hpp"
#include "lib/screen_handler.hpp"
#include "webserver/OneParamRewrite.hpp"
#include "lib/mining_pool/pool_factory.hpp"
extern TaskHandle_t eventSourceTaskHandle;
@ -28,7 +27,8 @@ void onApiStatus(AsyncWebServerRequest *request);
void onApiSystemStatus(AsyncWebServerRequest *request);
void onApiSetWifiTxPower(AsyncWebServerRequest *request);
void onApiScreenControl(AsyncWebServerRequest *request);
void onApiScreenNext(AsyncWebServerRequest *request);
void onApiScreenPrevious(AsyncWebServerRequest *request);
void onApiShowScreen(AsyncWebServerRequest *request);
void onApiShowCurrency(AsyncWebServerRequest *request);

View file

@ -51,7 +51,7 @@ extern "C" void app_main()
if (hasLightLevel()) {
if (preferences.getUInt("luxLightToggle", DEFAULT_LUX_LIGHT_TOGGLE) != 0)
{
if (hasLightLevel() && getLightLevel() <= 1 && preferences.getBool("flOffWhenDark", DEFAULT_FL_OFF_WHEN_DARK))
if (hasLightLevel() && getLightLevel() <= 2)
{
if (frontlightIsOn()) {
frontlightFadeOutAll();

View file

@ -33,17 +33,6 @@ void test_CorrectSatsPerDollarConversion(void)
TEST_ASSERT_EQUAL_STRING("4", output[NUM_SCREENS - 1].c_str());
}
void test_SatsPerDollarAfter1B(void)
{
std::array<std::string, NUM_SCREENS> output = parseSatsPerCurrency(120000000, CURRENCY_USD, false);
TEST_ASSERT_EQUAL_STRING("SATS/USD", output[0].c_str());
TEST_ASSERT_EQUAL_STRING("0", output[NUM_SCREENS - 5].c_str());
TEST_ASSERT_EQUAL_STRING(".", output[NUM_SCREENS - 4].c_str());
TEST_ASSERT_EQUAL_STRING("8", output[NUM_SCREENS - 3].c_str());
TEST_ASSERT_EQUAL_STRING("3", output[NUM_SCREENS - 2].c_str());
TEST_ASSERT_EQUAL_STRING("3", output[NUM_SCREENS - 1].c_str());
}
void test_CorrectSatsPerPoundConversion(void)
{
std::array<std::string, NUM_SCREENS> output = parseSatsPerCurrency(37253, CURRENCY_GBP, false);
@ -97,81 +86,6 @@ void test_PriceOf1MillionUsd(void)
TEST_ASSERT_EQUAL_STRING("M", output[NUM_SCREENS - 1].c_str());
}
void test_PriceSuffixMode(void)
{
std::array<std::string, NUM_SCREENS> output = parsePriceData(93000, '$', true, false);
TEST_ASSERT_EQUAL_STRING("BTC/USD", output[0].c_str());
TEST_ASSERT_EQUAL_STRING("9", output[NUM_SCREENS - 5].c_str());
TEST_ASSERT_EQUAL_STRING("3", output[NUM_SCREENS - 4].c_str());
TEST_ASSERT_EQUAL_STRING(".", output[NUM_SCREENS - 3].c_str());
TEST_ASSERT_EQUAL_STRING("0", output[NUM_SCREENS - 2].c_str());
TEST_ASSERT_EQUAL_STRING("K", output[NUM_SCREENS - 1].c_str());
}
void test_PriceSuffixModeCompact1(void)
{
std::array<std::string, NUM_SCREENS> output = parsePriceData(100000, '$', true, false, true);
std::string joined = joinArrayWithBrackets(output);
TEST_ASSERT_EQUAL_STRING_MESSAGE("BTC/USD", output[0].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("$", output[NUM_SCREENS - 6].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("1", output[NUM_SCREENS - 5].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("0", output[NUM_SCREENS - 4].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("0.", output[NUM_SCREENS - 3].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("0", output[NUM_SCREENS - 2].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("K", output[NUM_SCREENS - 1].c_str(), joined.c_str());
}
void test_PriceSuffixModeCompact2(void)
{
std::array<std::string, NUM_SCREENS> output = parsePriceData(1000000, '$', true, false, true);
std::string joined = joinArrayWithBrackets(output);
TEST_ASSERT_EQUAL_STRING_MESSAGE("BTC/USD", output[0].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("$", output[NUM_SCREENS - 6].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("1.", output[NUM_SCREENS - 5].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("0", output[NUM_SCREENS - 4].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("0", output[NUM_SCREENS - 3].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("0", output[NUM_SCREENS - 2].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("M", output[NUM_SCREENS - 1].c_str(), joined.c_str());
}
void test_PriceSuffixModeMow(void)
{
std::array<std::string, NUM_SCREENS> output = parsePriceData(93600, '$', true, true);
std::string joined = joinArrayWithBrackets(output);
TEST_ASSERT_EQUAL_STRING_MESSAGE("$", output[0].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE(".", output[NUM_SCREENS - 5].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("0", output[NUM_SCREENS - 4].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("9", output[NUM_SCREENS - 3].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("3", output[NUM_SCREENS - 2].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("M", output[NUM_SCREENS - 1].c_str(), joined.c_str());
}
void test_PriceSuffixModeMowCompact(void)
{
std::array<std::string, NUM_SCREENS> output = parsePriceData(93600, '$', true, true, true);
std::string joined = joinArrayWithBrackets(output);
TEST_ASSERT_EQUAL_STRING_MESSAGE("MOW/UNITS", output[0].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("$", output[NUM_SCREENS - 6].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("0.", output[NUM_SCREENS - 5].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("0", output[NUM_SCREENS - 4].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("9", output[NUM_SCREENS - 3].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("3", output[NUM_SCREENS - 2].c_str(), joined.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("M", output[NUM_SCREENS - 1].c_str(), joined.c_str());
}
void test_McapLowerUsd(void)
{
std::array<std::string, NUM_SCREENS> output = parseMarketCap(810000, 26000, '$', true);
@ -278,7 +192,6 @@ int runUnityTests(void)
UNITY_BEGIN();
RUN_TEST(test_CorrectSatsPerDollarConversion);
RUN_TEST(test_CorrectSatsPerPoundConversion);
RUN_TEST(test_SatsPerDollarAfter1B);
RUN_TEST(test_SixCharacterBlockHeight);
RUN_TEST(test_SevenCharacterBlockHeight);
RUN_TEST(test_FeeRateDisplay);
@ -290,11 +203,6 @@ int runUnityTests(void)
RUN_TEST(test_Mcap1TrillionEurSmallChars);
RUN_TEST(test_Mcap1TrillionJpy);
RUN_TEST(test_Mcap1TrillionJpySmallChars);
RUN_TEST(test_PriceSuffixMode);
RUN_TEST(test_PriceSuffixModeCompact1);
RUN_TEST(test_PriceSuffixModeCompact2);
RUN_TEST(test_PriceSuffixModeMow);
RUN_TEST(test_PriceSuffixModeMowCompact);
return UNITY_END();
}

View file

@ -1,75 +0,0 @@
#include <utils.hpp>
#include <unity.h>
void test_parseMiningPoolStatsHashRate1dot34TH(void)
{
std::string hashrate;
std::string label;
std::string output;
parseHashrateString("1340000000000", label, output, 4);
TEST_ASSERT_EQUAL_STRING_MESSAGE("TH/S", label.c_str(), label.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("1.34", output.c_str(), output.c_str());
}
void test_parseMiningPoolStatsHashRate645GH(void)
{
std::string hashrate = "645000000000";
std::string label;
std::string output;
parseHashrateString(hashrate, label, output, 4);
TEST_ASSERT_EQUAL_STRING_MESSAGE("GH/S", label.c_str(), label.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("645", output.c_str(), output.c_str());
}
void test_parseMiningPoolStatsHashRateEmpty(void)
{
std::string hashrate = "";
std::string label;
std::string output;
parseHashrateString(hashrate, label, output, 4);
TEST_ASSERT_EQUAL_STRING_MESSAGE("H/S", label.c_str(), label.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("0", output.c_str(), output.c_str());
}
void test_parseMiningPoolStatsHashRateZero(void)
{
std::string hashrate = "0";
std::string label;
std::string output;
parseHashrateString(hashrate, label, output, 4);
TEST_ASSERT_EQUAL_STRING_MESSAGE("H/S", label.c_str(), label.c_str());
TEST_ASSERT_EQUAL_STRING_MESSAGE("0", output.c_str(), output.c_str());
}
// not needed when using generate_test_runner.rb
int runUnityTests(void)
{
UNITY_BEGIN();
RUN_TEST(test_parseMiningPoolStatsHashRate1dot34TH);
RUN_TEST(test_parseMiningPoolStatsHashRate645GH);
RUN_TEST(test_parseMiningPoolStatsHashRateZero);
RUN_TEST(test_parseMiningPoolStatsHashRateEmpty);
return UNITY_END();
}
int main(void)
{
return runUnityTests();
}
extern "C" void app_main()
{
runUnityTests();
}