-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOrangePill.ino
385 lines (332 loc) · 10.8 KB
/
OrangePill.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <R4HttpClient.h>
#include <ArduinoJson.h>
#include "ArduinoGraphics.h"
#include "Arduino_LED_Matrix.h"
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32
#define OLED_RESET -1
WiFiSSLClient client;
R4HttpClient http;
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
ArduinoLEDMatrix matrix;
const long blocksPerHalving = 210000;
const float initialReward = 50.0;
const float maxSupply = 21000000.0;
const long SATOSHIS_IN_ONE_BTC = 100000000;
//TODO parse from json settings file
const char* ssid = "FederalReserve"; // Replace with your WiFi network name
const char* password = "MoneyPrinterGoBrrr"; // Replace with your WiFi password
const int delayMillis = 5000;
float percentMined = 0;
void setup() {
Serial.begin(9600);
while (!Serial);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(delayMillis);
Serial.print(".");
}
Serial.println("\nConnected to WiFi!");
displayCenteredText("Connected to WiFi", 1, 0, 0);
delay(500);
display.clearDisplay();
displayCenteredText("Buy Bitcoin", 1, 0, 0);
matrix.begin();
drawBitcoin();
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
connectToWiFi();
}
Serial.println("Getting block height...");
display.clearDisplay();
String blockHeightStr = getBitcoinBlockHeight();
if (blockHeightStr == "-1") {
display.setTextSize(1);
display.setCursor(0, 0);
display.print("Error fetching block height");
} else {
String blockLabel = "-Block Height-";
displayCenteredText(blockLabel, 1, 0, -12);
displayCenteredText(formatWithCommas(blockHeightStr), 2, 0, 3);
display.display();
delay(delayMillis); // Wait before fetching prices
display.clearDisplay();
displayCenteredText("-Percent Mined-", 1, 0, -12);
percentMined = calculatePercentageMined(blockHeightStr.toInt());
displayCenteredText(String(percentMined) + "%", 2, 0, 3);
}
Serial.println("Getting Bitcoin price...");
String priceUSD = getBitcoinPrice("USD");
display.clearDisplay();
if (priceUSD == "-1") {
display.print("Error fetching price");
} else {
displayCenteredText("-USD per BTC-", 1, 0, -12);
displayCenteredText("$"+formatWithCommas(priceUSD), 2, 0, 3);
delay(delayMillis);
int satsPerDollar = SATOSHIS_IN_ONE_BTC / priceUSD.toInt();
display.clearDisplay();
display.setTextSize(1);
display.setCursor(15, 9);
display.print("MSK");
display.setCursor(10, 15);
display.print("-----");
display.setCursor(12, 15);
display.print("----");
display.setCursor(10, 21);
display.print("UTC+3");
display.setTextSize(2); // Large text for the value
displayCenteredText(moscowTime(satsPerDollar), 2, 12, 3);
display.display();
delay(delayMillis); // Wait 5 seconds before updating again
}
if(blockHeightStr != "-1" && priceUSD != "-1"){
String marketCap = calculateMarketCap(priceUSD.toFloat(), percentMined);
display.clearDisplay();
displayCenteredText("-Market Cap-", 1, 0, -12);
displayCenteredText(String(marketCap), 2, 0, 3);
} else {
display.clearDisplay();
display.print("Error fetching market cap");
}
Serial.println("Getting Fees");
String fastestFee = getFastestFee();
if(fastestFee != "-1"){
display.clearDisplay();
display.setTextSize(1);
display.setCursor(15, 12);
display.print("sats");
display.setCursor(10, 17);
display.print("-----");
display.setCursor(12, 17);
display.print("----");
display.setCursor(10, 23);
display.print("vByte");
displayCenteredText("-Fastest Fee-", 1, 0, -12);
displayCenteredText(fastestFee, 2, 12, 2);
} else {
display.clearDisplay();
display.print("Error fetching fastest fee");
}
}
String moscowTime(int satsPerDollar) {
int hours = satsPerDollar / 100;
int minutes = satsPerDollar % 100;
// Format the hours and minutes with leading zeros if needed
String formattedTime = "";
if (hours < 10) formattedTime += "0"; // Add leading zero for hours
formattedTime += String(hours) + ":";
if (minutes < 10) formattedTime += "0"; // Add leading zero for minutes
formattedTime += String(minutes);
return formattedTime;
}
String getBitcoinBlockHeight() {
if (WiFi.status() == WL_CONNECTED) {
http.begin(client, "https://mempool.space/api/blocks", 443);
http.setTimeout(3000);
int httpResponseCode = http.GET();
if (httpResponseCode == HTTP_CODE_OK) {
String response = http.getBody();
http.close();
Serial.println("Block data retrieved");
DynamicJsonDocument doc(4096);
DeserializationError error = deserializeJson(doc, response);
//TODO there is an issue with the length need to fix.
if (!error || error) {
int highestHeight = 0;
for (JsonObject block : doc.as<JsonArray>()) {
int height = block["height"];
if (height > highestHeight) {
highestHeight = height;
}
}
return String(highestHeight);
} else {
Serial.print("JSON deserialization failed: ");
Serial.println(error.f_str());
}
} else {
Serial.print("HTTP request failed, error code: ");
Serial.println(httpResponseCode);
}
http.close();
} else {
Serial.println("WiFi not connected");
}
return "-1";
}
String getFastestFee(void){
if (WiFi.status() == WL_CONNECTED) {
http.begin(client, "https://mempool.space/api/v1/fees/recommended", 443);
http.setTimeout(3000);
int httpResponseCode = http.GET();
if (httpResponseCode == HTTP_CODE_OK) {
String response = http.getBody();
http.close();
Serial.println("Fee data retrieved");
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, response);
if (!error) {
if (doc.containsKey("fastestFee")) {
int fee = doc["fastestFee"];
return String(fee);
} else {
Serial.print("Fee not found");
}
} else {
Serial.print("JSON deserialization failed: ");
Serial.println(error.f_str());
}
} else {
Serial.print("HTTP request failed, error code: ");
Serial.println(httpResponseCode);
}
http.close();
} else {
Serial.println("WiFi not connected");
}
return "-1";
}
float calculatePercentageMined(long currentBlockHeight) {
// Constants
float totalMined = 0;
// Calculate total mined based on halving events
int halvingCount = currentBlockHeight / blocksPerHalving;
for (int i = 0; i < halvingCount; i++) {
totalMined += blocksPerHalving * (initialReward / pow(2, i));
}
// Add remaining blocks in the current cycle if any
int remainingBlocks = currentBlockHeight % blocksPerHalving;
if (remainingBlocks > 0) {
totalMined += remainingBlocks * (initialReward / pow(2, halvingCount));
}
// Calculate percentage mined
float percentageMined = (totalMined / maxSupply) * 100.0;
return round(percentageMined * 100) / 100; // Round to nearest hundredth
}
String getBitcoinPrice(const char* currency) {
if (WiFi.status() == WL_CONNECTED) {
http.begin(client, "https://mempool.space/api/v1/prices", 443);
http.setTimeout(3000);
int httpResponseCode = http.GET();
if (httpResponseCode == HTTP_CODE_OK) {
String response = http.getBody();
http.close();
Serial.println("Price data retrieved");
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, response);
if (!error) {
if (doc.containsKey(currency)) {
int price = doc[currency];
return String(price);
} else {
Serial.print("Currency not found: ");
Serial.println(currency);
}
} else {
Serial.print("JSON deserialization failed: ");
Serial.println(error.f_str());
}
} else {
Serial.print("HTTP request failed, error code: ");
Serial.println(httpResponseCode);
}
http.close();
} else {
Serial.println("WiFi not connected");
}
return "-1";
}
void connectToWiFi() {
Serial.print("Connecting to WiFi...");
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("Connecting to WiFi...");
display.display();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected!");
display.clearDisplay();
display.setCursor(0, 0);
display.print("Connected to WiFi!");
display.display();
delay(2000); // Display the message for 2 seconds
}
void displayCenteredText(const String &text, int textSize, int16_t xOffset, int16_t yOffset) {
display.setTextSize(textSize);
// Calculate X position to center text
int16_t xCenter = (SCREEN_WIDTH - text.length() * 6 * textSize) / 2;
int16_t yCenter = ((SCREEN_HEIGHT - 4 * textSize) / 2) + yOffset;
display.setCursor(xCenter + xOffset, yCenter);
display.print(text);
display.display();
}
String formatWithCommas(String numberStr) {
int len = numberStr.length();
// Start from the end of the string and insert commas every 3 digits
for (int i = len - 3; i > 0; i -= 3) {
numberStr = numberStr.substring(0, i) + "," + numberStr.substring(i);
}
return numberStr;
}
void drawBitcoin() {
matrix.clear();
const uint32_t bitcoin[][4] = {
{
0x1203f011,
0x1e01101,
0x103f0120,
66
},
{
0x3184a444,
0x44042081, //heart
0x100a0040
}
};
matrix.stroke(0xFFFFFFFF);
matrix.textScrollSpeed(35);
const char text[] = " Buy Bitcoin ";
matrix.textFont(Font_5x7);
matrix.beginText(0, 1, 0xFFFFFF);
matrix.println(text);
matrix.endText(SCROLL_LEFT);
matrix.endDraw();
delay(1000);
matrix.loadFrame(bitcoin[0]);
delay(1000);
matrix.loadFrame(bitcoin[1]);
delay(1000);
matrix.loadFrame(bitcoin[0]);
}
String calculateMarketCap(float priceUSD, float percentMined) {
float marketCap = (priceUSD * maxSupply) * (percentMined/100);
// Format the market cap
String marketCapStr;
if (marketCap >= 1e12) {
marketCap = round(marketCap / 1e10) / 100.0; // Round to nearest hundredth
marketCapStr = String(marketCap, 2) + "T"; // Trillions
} else if (marketCap >= 1e9) {
marketCap = round(marketCap / 1e7) / 100.0; // Round to nearest hundredth
marketCapStr = String(marketCap, 2) + "B"; // Billions
} else {
marketCapStr = String(marketCap, 0); // Exact value if less than billion
}
return "$" + marketCapStr;
}