summaryrefslogtreecommitdiff
path: root/main/main.c
blob: aa6773b72ac972966f3a22df19d7b74182bb2823 (plain)
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
/*
 * This example code is in the Public Domain (or CC0 licensed, at your option.)
 * Unless required by applicable law or agreed to in writing, this
 * software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied.
 */

// This file contains a simple Hello World app which you can base you own
// native Badge apps on.

#include "main.h"

static const char *TAG = "TALER";

// #include "wifi.c"
#include "http-client.c"

static pax_buf_t buf;
xQueueHandle buttonQueue;

#include <esp_log.h>
#include <cJSON.h>
#include "qrcode.h"
#include <pax_codecs.h>

extern const char icon_png_start[] asm("_binary_icon_png_start");
extern const char icon_png_end[] asm("_binary_icon_png_end");

// Updates the screen with the latest buffer.
void disp_flush()
{
    ili9341_write(get_ili9341(), buf.buf);
}

// Exits the app, returning to the launcher.
void exit_to_launcher()
{
    REG_WRITE(RTC_CNTL_STORE0_REG, 0);
    esp_restart();
}

void initialize_things(void)
{
    // Initialize the screen, the I2C and the SPI busses.
    bsp_init();

    // Initialize the RP2040 (responsible for buttons, etc).
    bsp_rp2040_init();

    // This queue is used to receive button presses.
    buttonQueue = get_rp2040()->queue;

    // Initialize graphics for the screen.
    pax_buf_init(&buf, NULL, 320, 240, PAX_BUF_16_565RGB);

    // Initialize NVS.
    nvs_flash_init();

    // Initialize WiFi. This doesn't connect to Wifi yet.
    // wifi_init();

    // Set the background to an initial color
    int hue = esp_random() & 255;
    pax_col_t col = pax_col_hsv(hue, 255 /*saturation*/, 255 /*brighness*/);
    pax_background(&buf, col);
}

const pax_font_t *font = pax_font_saira_regular;

void show_message(const char *message)
{

    int hue = esp_random() & 255;
    pax_col_t col = pax_col_hsv(hue, 255 /*saturation*/, 255 /*brighness*/);
    pax_background(&buf, col);

    // Determine how the text dimensions so we can display it centered on
    // screen.
    pax_vec1_t dims = pax_text_size(font, font->default_size, message);

    // Draw the centered text.
    pax_draw_text(
        &buf,                     // Buffer to draw to.
        0xff000000,               // color
        font, font->default_size, // Font and size to use.
        // Position (top left corner) of the app.
        (buf.width - dims.x) / 2.0,
        (buf.height - dims.y) / 2.0,
        // The text to be rendered.
        message);

    // Draws the entire graphics buffer to the screen.
    disp_flush();
}

int read_key()
{
    rp2040_input_message_t buttonMessage = {0};
    if (xQueueReceive(buttonQueue, &buttonMessage, 0) == pdTRUE)
    {
        if (buttonMessage.state)
        {
            if (buttonMessage.input == RP2040_INPUT_BUTTON_HOME)
            {
                exit_to_launcher();
            }

            return buttonMessage.input;
        }
    }
    return 0;
}

int wait_any_key_or_exit()
{
    while (1)
    {
        rp2040_input_message_t buttonMessage = {0};
        if (xQueueReceive(buttonQueue, &buttonMessage, portMAX_DELAY) == pdTRUE)
        {
            if (buttonMessage.state)
            {
                if (buttonMessage.input == RP2040_INPUT_BUTTON_HOME)
                {
                    exit_to_launcher();
                }

                return buttonMessage.input;
            }
        }
    }
}

#define TALER_MERCHANT_HOST "merchant-backend.taler.ar"
#define TALER_MERCHANT_NAME "mch2022"
#define TALER_CREATE_ORDER_URL "/instances/" TALER_MERCHANT_NAME "/private/orders"
#define TALER_PAYMENT_URI "taler://pay/" TALER_MERCHANT_HOST "/instances/" TALER_MERCHANT_NAME "/"
#define TALER_PAYMENT_TEMPLATE TALER_PAYMENT_URI "%s/"

#define TALER_CREATE_ORDER_URL_TEMPLATE "/instances/" TALER_MERCHANT_NAME "/private/orders/%s"

bool get_order_status(const char *token, const char *orderId, char **order_status)
{
    char local_response_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
    int token_len = strlen(token);

    int order_status_url_size = sizeof(TALER_CREATE_ORDER_URL_TEMPLATE) + strlen(orderId) + 1;
    char *order_status_url = (char *)malloc(order_status_url_size);
    snprintf(order_status_url, order_status_url_size, TALER_CREATE_ORDER_URL_TEMPLATE, orderId);

    esp_http_client_config_t config = {
        .port = 443,
        .host = TALER_MERCHANT_HOST,
        .path = order_status_url,
        .keep_alive_enable = true,
        .method = HTTP_METHOD_GET,
        .transport_type = HTTP_TRANSPORT_OVER_SSL,
        .cert_pem = inet_sec_root_cert_pem_start,
        .user_data = local_response_buffer,
        .event_handler = _http_event_handler,
    };
    esp_http_client_handle_t client = esp_http_client_init(&config);

    {
        char *auth_buffer = (char *)malloc(sizeof("Bearer secret-token:") + token_len + 1);
        sprintf(auth_buffer, "Bearer secret-token:%s", token);
        esp_http_client_set_header(client, "Authorization", auth_buffer);
        free(auth_buffer);
    }

    ESP_LOGI(TAG, "querying order status...");
    esp_err_t err = esp_http_client_perform(client);

    if (err == ESP_OK)
    {
        ESP_LOGI(TAG, "query ok. buffer has %s bytes", local_response_buffer);
        cJSON *response_json = cJSON_Parse(local_response_buffer);
        cJSON *orderStatus = cJSON_GetObjectItemCaseSensitive(response_json, "order_status");

        int order_len = strlen(orderStatus->valuestring);
        *order_status = (char *)malloc(order_len + 1);
        strncpy(*order_status, orderStatus->valuestring, order_len);
        (*order_status)[order_len] = '\0';
        ESP_LOGI(TAG, "order status %s", *order_status);
        cJSON_Delete(response_json);
    }
    else
    {
        char buffer[200];
        snprintf(buffer, sizeof(buffer), "failed = %d, %s",
                 esp_http_client_get_status_code(client),
                 esp_err_to_name(err));
        show_message(buffer);
    }

    esp_http_client_cleanup(client);
    return err == ESP_OK;
}

bool post_new_order(float amount, const char *token, char **orderId_out)
{
    char newOrderBuffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
    esp_http_client_config_t config = {
        .port = 443,
        .host = TALER_MERCHANT_HOST,
        .path = TALER_CREATE_ORDER_URL,
        .keep_alive_enable = true,
        .method = HTTP_METHOD_POST,
        .transport_type = HTTP_TRANSPORT_OVER_SSL,
        .cert_pem = inet_sec_root_cert_pem_start,
        .user_data = newOrderBuffer,
        .event_handler = _http_event_handler,
    };
    esp_http_client_handle_t newOrderClient = esp_http_client_init(&config);

    int token_len = strlen(token);

    char post_data[128];

    esp_http_client_set_header(newOrderClient, "Content-Type", "application/json");
    {
        char *auth_buffer = (char *)malloc(sizeof("Bearer secret-token:") + token_len + 1);
        sprintf(auth_buffer, "Bearer secret-token:%s", token);
        esp_http_client_set_header(newOrderClient, "Authorization", auth_buffer);
        free(auth_buffer);
    }

    snprintf(post_data, sizeof(post_data), "{\"order\":{\"summary\":\"sold in mch2022\",\"amount\":\"ARS:%3.2f\"},\"create_token\":false}", amount);
    esp_http_client_set_post_field(newOrderClient, post_data, strlen(post_data));

    ESP_LOGI(TAG, "creating order...");
    esp_err_t err = esp_http_client_perform(newOrderClient);

    if (err == ESP_OK)
    {
        ESP_LOGI(TAG, "query ok. buffer has %s", newOrderBuffer);
        cJSON *response_json = cJSON_Parse(newOrderBuffer);
        cJSON *orderId = cJSON_GetObjectItemCaseSensitive(response_json, "order_id");
        int order_len = strlen(orderId->valuestring);
        *orderId_out = (char *)malloc(order_len + 1);
        strncpy(*orderId_out, orderId->valuestring, order_len);
        (*orderId_out)[order_len] = '\0';
        ESP_LOGI(TAG, "order id '%s' len %d", *orderId_out, order_len);
        cJSON_Delete(response_json);
    }
    else
    {
        char buffer[200];
        snprintf(buffer, sizeof(buffer), "failed = %d, %s",
                 esp_http_client_get_status_code(newOrderClient),
                 esp_err_to_name(err));
        show_message(buffer);
    }

    esp_http_client_cleanup(newOrderClient);
    return err == ESP_OK;
}

#define SQUARE_SIZE 5

void esp_qrcode_print_screen(esp_qrcode_handle_t qrcode)
{
    int size = esp_qrcode_get_size(qrcode);
    int border = 2;

    float ypos = 40;

    pax_background(&buf, 0xb0FFFFFF); // black background

    const char *message = "Use the GNU Taler Wallet to pay\n          or any key to cancel.";
    pax_vec1_t dims = pax_text_size(font, font->default_size, message);

    // 240y * 320x

    // Draw the centered text.
    pax_draw_text(
        &buf,                     // Buffer to draw to.
        0xff000000,               // color
        font, font->default_size, // Font and size to use.
        // Position (top left corner) of the app.
        (buf.width - dims.x) / 2.0,
        5,
        // The text to be rendered.
        message);

    for (int y = -border; y < size + border; y += 2)
    {

        float xpos = 60;
        for (int x = -border; x < size + border; x += 2)
        {
            if (esp_qrcode_get_module(qrcode, x, y))
            {
                pax_draw_rect(&buf, 0xb0000000, xpos, ypos, SQUARE_SIZE, SQUARE_SIZE);
            }
            if ((x < size + border) && esp_qrcode_get_module(qrcode, x + 1, y))
            {
                pax_draw_rect(&buf, 0xb0000000, xpos + SQUARE_SIZE, ypos, SQUARE_SIZE, SQUARE_SIZE);
            }
            if ((y < size + border) && esp_qrcode_get_module(qrcode, x, y + 1))
            {
                pax_draw_rect(&buf, 0xb0000000, xpos, ypos + SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE);
            }
            if ((x < size + border) && (y < size + border) && esp_qrcode_get_module(qrcode, x + 1, y + 1))
            {
                pax_draw_rect(&buf, 0xb0000000, xpos + SQUARE_SIZE, ypos + SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE);
            }

            xpos += SQUARE_SIZE + SQUARE_SIZE;
        }
        ypos += SQUARE_SIZE + SQUARE_SIZE;
    }

    disp_flush();
}

char LAST_ORDER[200] = "";

char LAST_STATUS[200] = "";
char WIFI_STATUS[200] = "connected";
float NEXT_ORDER_PRICE = 3.2;
#define MENU_TEMPLATE "Merchant name: %s\nWifi status: %s\nLast order: %s\nNext order price: %3.2f\n"

#define SECOND_OPTION_EXIT 0
#define SECOND_OPTION_RETRY 1
#define SECOND_OPTION_REFUND 2

void show_menu(int second_option)
{
    pax_background(&buf, 0xb0FFFFFF); // black background
    // pax_draw_image(&buf, &icon_png_start, 10, 10);
    pax_insert_png_buf(&buf, icon_png_start, icon_png_end - icon_png_start, 10, 10, PAX_BUF_32_8888ARGB);

    pax_draw_text(&buf, 0xFF000000, font, 18, 50, 20, "GNU Taler Merchant client\n#MCH2022");

    char *status_buffer = NULL;
    int status_buffer_size = sizeof(MENU_TEMPLATE) + strlen(TALER_MERCHANT_NAME) + strlen(LAST_STATUS) + strlen(WIFI_STATUS);
    status_buffer = (char *)malloc(status_buffer_size);
    snprintf(status_buffer, status_buffer_size, MENU_TEMPLATE, TALER_MERCHANT_NAME, WIFI_STATUS, LAST_STATUS, NEXT_ORDER_PRICE);
    pax_draw_text(&buf, 0xFF000000, font, 18, 20, 80, status_buffer);

    if (second_option == SECOND_OPTION_EXIT)
    {
        pax_draw_text(&buf, 0xFF000000, font, 18, 20, 240 - 18, "🅰 create order 🅱 exit");
    }
    if (second_option == SECOND_OPTION_RETRY)
    {
        pax_draw_text(&buf, 0xFF000000, font, 18, 20, 240 - 18, "🅰 create order 🅱 retry");
    }
    if (second_option == SECOND_OPTION_REFUND)
    {
        pax_draw_text(&buf, 0xFF000000, font, 18, 20, 240 - 18, "🅰 create order 🅱 refund");
    }
    disp_flush();
}

void setup_wifi()
{
    show_message("Connecting to MCH2022 wifi");
    ESP_LOGI(TAG, "Initializing wifi...");

    wifi_init();
    bool connected = false;
    while (!connected)
    {
        connected = wifi_connect_ent("MCH2022", "badge", "badge", "badge", ESP_EAP_TTLS_PHASE2_PAP, 30);
        if (!connected)
        {
            ESP_LOGI(TAG, "could not connect, trying again...");
            show_message("go near an MCH2022 access point");
        }
    }
    ESP_LOGI(TAG, "Connected.");
}

bool create_new_order()
{
    char *orderId = NULL;

    char creating_order_message[200];
    snprintf(creating_order_message, 200, "Creating order for ARS:%3.2f ...", NEXT_ORDER_PRICE);
    show_message(creating_order_message);

    bool order_created = post_new_order(NEXT_ORDER_PRICE, "305a16ce7cc2e2793060e39b9210a700", &orderId);

    if (order_created)
    {
        char *paymentURI = NULL;
        int order_len = strlen(orderId);
        paymentURI = (char *)malloc(sizeof(TALER_PAYMENT_URI) + order_len + /*last slash*/ 1 + /*0*/ 1);
        sprintf(paymentURI, TALER_PAYMENT_TEMPLATE, orderId);

        strcpy(LAST_ORDER, orderId);
        LAST_ORDER[order_len] = '\0';

        esp_qrcode_config_t cfg = {
            .max_qrcode_version = 10,
            .display_func = esp_qrcode_print_screen,
            .qrcode_ecc_level = ESP_QRCODE_ECC_LOW,
        };

        esp_qrcode_generate(&cfg, paymentURI);
        free(paymentURI);
        free(orderId);
        return true;
    }
    else
    {
        strcpy(LAST_STATUS, "error creating the order");
        return false;
    }
}
bool query_order_until_paid()
{
    bool order_is_pay_or_cancel = false;
    bool qr_scanned = false;
    bool paid = false;

    int tick = 0;
    while (!order_is_pay_or_cancel)
    {
        char *order_status = NULL;

        ESP_LOGI(TAG, "====== TESTING ORDER %s", LAST_ORDER);

        bool query_ok = get_order_status("305a16ce7cc2e2793060e39b9210a700", LAST_ORDER, &order_status);

        if (!query_ok)
        {
            ESP_LOGI(TAG, "query went wrong");
            strcpy(LAST_STATUS, "error getting status");
            return false;
        }
        ESP_LOGI(TAG, "query status: %s", order_status);

        char *tick_str[] = {
            ".",
            "..",
            "...",
            "....",
        };
        snprintf(LAST_STATUS, 200, "%s %s", order_status, tick_str[tick]);
        tick++;
        if (tick > 3)
        {
            tick = 0;
        }

        if (!qr_scanned && strcmp(order_status, "claimed") == 0)
        {
            show_message("payment claimed!\nwaiting to be paid...");
            qr_scanned = true;
        }

        if (strcmp(order_status, "paid") == 0)
        {
            order_is_pay_or_cancel = true;
            paid = true;
        }
        int last_key = read_key();
        ESP_LOGI(TAG, "read key: %d", last_key);
        if (last_key == RP2040_INPUT_BUTTON_BACK)
        {
            order_is_pay_or_cancel = true;
        }

        free(order_status);
    }
    return paid;
}

void app_main()
{

    ESP_LOGI(TAG, "Starting...");
    initialize_things();

    setup_wifi();
    int second_option = SECOND_OPTION_EXIT;
    while (1)
    {
        show_menu(second_option);

        const int key = wait_any_key_or_exit();

        ///////////////////////////
        // start of main switch
        ///////////////////////////
        if (key == RP2040_INPUT_BUTTON_ACCEPT)
        {
            bool ok = create_new_order();
            if (!ok)
            {
                second_option = SECOND_OPTION_EXIT;
                continue;
            }
            ESP_LOGI(TAG, "user is seeing qr code now");
            ok = query_order_until_paid();
            if (!ok)
            {
                second_option = SECOND_OPTION_RETRY;
            }
            else
            {
                second_option = SECOND_OPTION_REFUND;
            }
        }
        else if (key == RP2040_INPUT_BUTTON_BACK && second_option == SECOND_OPTION_EXIT)
        {
            exit_to_launcher();
        }
        else if (key == RP2040_INPUT_BUTTON_BACK && second_option == SECOND_OPTION_RETRY)
        {
            ESP_LOGI(TAG, "retrying order %s", LAST_ORDER);
            bool ok = query_order_until_paid();
            if (!ok)
            {
                second_option = SECOND_OPTION_RETRY;
            }
            else
            {
                second_option = SECOND_OPTION_REFUND;
            }
        }
        else if (key == RP2040_INPUT_BUTTON_BACK && second_option == SECOND_OPTION_REFUND)
        {
            show_message("not yet implemented!");
            wait_any_key_or_exit();
        }
        else if (key == RP2040_INPUT_JOYSTICK_UP)
        {
            ESP_LOGI(TAG, "inc price 0.1");
            NEXT_ORDER_PRICE += 0.1;
        }
        else if (key == RP2040_INPUT_JOYSTICK_DOWN)
        {
            ESP_LOGI(TAG, "dec price 0.1");
            NEXT_ORDER_PRICE -= 0.1;
        }
        else if (key == RP2040_INPUT_JOYSTICK_LEFT)
        {
            ESP_LOGI(TAG, "inc price 1");
            NEXT_ORDER_PRICE += 1;
        }
        else if (key == RP2040_INPUT_JOYSTICK_RIGHT)
        {
            ESP_LOGI(TAG, "dec price 1");
            NEXT_ORDER_PRICE -= 1;
        }
        ///////////////////////////
        // end of main switch
        ///////////////////////////
        if (NEXT_ORDER_PRICE > 30)
        {
            NEXT_ORDER_PRICE = 30;
        }
        if (NEXT_ORDER_PRICE < 0.1)
        {
            NEXT_ORDER_PRICE = 0.1;
        }
    }
}