Refactor to use new protocol module and sipo.
[bertos.git] / boards / sam3x-ek / examples / sam3x-ek_http_server / main.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2011 Develer S.r.l. (http://www.develer.com/)
30  *
31  * -->
32  *
33  * \author Andrea Righi <arighi@develer.com>
34  * \author Daniele Basile <asterix@develer.com>
35  *
36  * \brief Simple Http server.
37  *
38  * This simple web server read the site's pages from SD card, and manage
39  * the cases where SD is not present or page not found, using embedded pages.
40  * Quering from browser some cgi page, the server return a json dictionary.
41  */
42
43
44 #include "bitmaps.h"
45
46 #include "hw/hw_http.h"
47 #include "hw/hw_sd.h"
48 #include "hw/hw_adc.h"
49 #include "hw/hw_sdram.h"
50 #include "hw/hw_led.h"
51 #include "hw/hw_lcd.h"
52
53 // Define logging setting (for cfg/log.h module).
54 #define LOG_LEVEL         3
55 #define LOG_VERBOSITY     0
56 #include <cfg/log.h>
57 #include <cfg/debug.h>
58
59 #include <cpu/irq.h>
60 #include <cpu/power.h>
61
62 #include <drv/timer.h>
63 #include <drv/ser.h>
64 #include <drv/sd.h>
65 #include <drv/dmac_sam3.h>
66 #include <drv/adc.h>
67 #include <drv/lcd_hx8347.h>
68
69 #include <kern/proc.h>
70 #include <kern/monitor.h>
71 #include <struct/heap.h>
72
73 #include <net/http.h>
74
75 #include <netif/ethernetif.h>
76
77 #include <lwip/ip.h>
78 #include <lwip/ip_addr.h>
79 #include <lwip/netif.h>
80 #include <lwip/tcpip.h>
81 #include <lwip/dhcp.h>
82
83 #include <gfx/gfx.h>
84 #include <gfx/font.h>
85 #include <gfx/text.h>
86
87 #include <fs/fat.h>
88
89 #include <icons/bertos.h>
90
91 #include <stdlib.h>
92 #include <stdio.h>
93 #include <string.h>
94
95 /* Network interface global variables */
96 static struct ip_addr ipaddr, netmask, gw;
97 static struct netif netif;
98
99
100 #define GET_LED_STATUS(status, led_id)     (((status) & BV((led_id))) >> (led_id))
101 #define CLEAR_LED_STATUS(status, led_id)   ((status) &= ~BV((led_id)))
102 #define SET_LED_STATUS(status, led_id)     ((status) |= BV((led_id)))
103
104 typedef struct BoardStatus
105 {
106         char local_ip[sizeof("123.123.123.123")];
107         char last_connected_ip[sizeof("123.123.123.123")];
108         uint8_t led_status;
109         uint16_t internal_temp;
110         uint32_t up_time;
111         size_t tot_req;
112 } BoardStatus;
113
114 static BoardStatus status;
115 static uint8_t raster[RAST_SIZE(LCD_WIDTH, LCD_HEIGHT)];
116 static Bitmap *lcd_bitmap;
117 extern Font font_gohu;
118 static int lcd_brightness = LCD_BACKLIGHT_MAX;
119 static struct Heap heap;
120 static uint8_t tx_buf[2048];
121
122
123 static void init(void)
124 {
125         /* Enable all the interrupts */
126         IRQ_ENABLE;
127
128         /* Initialize debugging module (allow kprintf(), etc.) */
129         kdbg_init();
130         /* Initialize system timer */
131         timer_init();
132
133         /*
134          * Kernel initialization: processes (allow to create and dispatch
135          * processes using proc_new()).
136          */
137         proc_init();
138         sdram_init();
139         dmac_init();
140         adc_init();
141
142         /* Enable the adc to read internal temperature sensor */
143         hw_enableTempRead();
144         LED_INIT();
145
146         heap_init(&heap, (void *)SDRAM_BASE, SDRAM_SIZE);
147         lcd_bitmap = heap_allocmem(&heap, RAST_SIZE(LCD_WIDTH, LCD_HEIGHT));
148         if (lcd_bitmap)
149                 kprintf("Allocated memory for display raster, addr 0x%x\n", (unsigned)lcd_bitmap);
150         else
151         {
152                 kprintf("Error allocating memory for LCD raster!\n");
153         }
154
155         lcd_hx8347_init();
156         lcd_setBacklight(lcd_brightness);
157
158         gfx_bitmapInit(lcd_bitmap, raster, LCD_WIDTH, LCD_HEIGHT);
159         gfx_setFont(lcd_bitmap, &font_luBS14);
160         lcd_hx8347_blitBitmap(lcd_bitmap);
161
162         /* Initialize TCP/IP stack */
163         tcpip_init(NULL, NULL);
164
165         /* Bring up the network interface */
166         netif_add(&netif, &ipaddr, &netmask, &gw, NULL, ethernetif_init, tcpip_input);
167         netif_set_default(&netif);
168         netif_set_up(&netif);
169 }
170
171 static int sec_to_strDhms(uint32_t sec_time, char *str, size_t len)
172 {
173     uint32_t h = (sec_time / 3600);
174     uint32_t d = h / 24;
175     uint32_t m = ((sec_time - (h * 3600)) / 60);
176     uint32_t s = (sec_time - (m * 60) - (h * 3600));
177
178     if (len < sizeof("xxxxd xxh xxm xxs"))
179         return -1;
180
181     sprintf(str, "%ldd %ldh %ldm %lds", d, (h >= 24) ? h - 24 : h, m, s);
182
183     return 0;
184 }
185
186
187 static NORETURN void proc_displayRefresh(void)
188 {
189         while (1)
190         {
191                 //LOG_INFO("Refresh display\n");
192
193                 status.internal_temp = hw_convertToDegree(adc_read(ADC_TEMPERATURE_CH));
194                 status.up_time += 1;
195                 sec_to_strDhms(status.up_time, (char *)tx_buf, sizeof(tx_buf));
196
197                 gfx_bitmapClear(lcd_bitmap);
198                 text_style(lcd_bitmap, STYLEF_BOLD | STYLEF_UNDERLINE, STYLEF_BOLD | STYLEF_UNDERLINE);
199                 text_xprintf(lcd_bitmap, 0, 0, TEXT_CENTER | TEXT_FILL, "BeRTOS Simple Http Server");
200                 text_style(lcd_bitmap, 0, STYLEF_MASK);
201                 text_xprintf(lcd_bitmap, 2, 0, 0, "Board ip: %s", status.local_ip);
202                 text_xprintf(lcd_bitmap, 3, 0, 0, "Last connected ip: %s", status.last_connected_ip);
203                 text_xprintf(lcd_bitmap, 4, 0, 0, "Temperature: %d.%dC",        status.internal_temp / 10, status.internal_temp % 10);
204                 text_xprintf(lcd_bitmap, 5, 0, 0, "Up time: %s", tx_buf);
205
206                 lcd_hx8347_blitBitmap(lcd_bitmap);
207
208                 timer_delay(1000);
209         }
210 }
211
212 /*
213  * Return a JSON string of board status.
214  */
215 static int cgi_status(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
216 {
217         (void)recv_buf;
218         (void)recv_len;
219         (void)name;
220
221         status.tot_req++;
222         uint16_t volt = adc_read(1);
223
224         //Update board status.
225         sprintf(status.last_connected_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(client->pcb.ip->remote_ip.addr));
226         sprintf(status.local_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(client->pcb.ip->local_ip.addr));
227
228         sprintf((char *)tx_buf, "{ \"local_ip\":\"%s\",\"last_connected_ip\":\"%s\", \"temp\":%d.%d,\"volt\":%d,\"up_time\":%ld,\"tot_req\":%d, \
229 \"leds\":{ \"0\":\"%d\", \"1\":\"%d\", \"2\":\"%d\"}}",
230                                                                 status.local_ip, status.last_connected_ip,
231                                                                 status.internal_temp / 10, status.internal_temp % 10,
232                                                                 volt, status.up_time, status.tot_req,
233                                                                 GET_LED_STATUS(status.led_status, 0),
234                                                                 GET_LED_STATUS(status.led_status, 1),
235                                                                 GET_LED_STATUS(status.led_status, 2));
236
237
238
239
240         http_sendOk(client, HTTP_CONTENT_JSON);
241         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
242         return 0;
243 }
244
245 static int cgi_logo(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
246 {
247         (void)recv_buf;
248         (void)recv_len;
249         (void)name;
250
251         http_sendOk(client, HTTP_CONTENT_JPEG);
252         netconn_write(client, bertos_logo_jpg, bertos_logo_jpg_len, NETCONN_NOCOPY);
253         return 0;
254 }
255
256 /*
257  * Return the internal micro temperature string.
258  */
259 static int cgi_temp(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
260 {
261         (void)recv_buf;
262         (void)recv_len;
263         (void)name;
264
265         sprintf((char *)tx_buf, "[%d.%d]", status.internal_temp / 10, status.internal_temp % 10);
266
267         http_sendOk(client, HTTP_CONTENT_JSON);
268         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
269         return 0;
270 }
271
272
273 /*
274  * Return the board uptime.
275  */
276 static int cgi_uptime(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
277 {
278         (void)recv_buf;
279         (void)recv_len;
280         (void)name;
281
282         sec_to_strDhms(status.up_time, (char *)tx_buf, sizeof(tx_buf));
283
284         http_sendOk(client, HTTP_CONTENT_JSON);
285         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
286         return 0;
287 }
288
289 /*
290  * Return the VR1 potentiometer voltage.
291  */
292 static int cgi_resistor(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
293 {
294         (void)recv_buf;
295         (void)recv_len;
296         (void)name;
297
298         uint16_t volt = ADC_RANGECONV(adc_read(1), 0, 3300);
299         kprintf("volt %d\n", volt);
300         sprintf((char *)tx_buf, "[ \"%d.%dV\" ]",  volt / 1000, volt % 1000);
301
302         http_sendOk(client, HTTP_CONTENT_JSON);
303         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
304         return 0;
305 }
306
307
308 #define CGI_LED_ID_KEY    "n"
309 #define CGI_LED_CMD_KEY   "set"
310
311 static char key_value[80];
312
313 /*
314  * Reply to client the request string.
315  */
316 static int cgi_led(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
317 {
318         (void)recv_buf;
319         (void)recv_len;
320         (void)name;
321
322         char *query_str = strstr(name, "?") + 1;
323         size_t query_str_len = strlen(query_str);
324         int led_id;
325         int led_cmd;
326
327         int len = http_tokenizeGetRequest(query_str, query_str_len);
328
329         LOG_INFO("Found %d key/value pair\n", len);
330
331         if (http_getValue(query_str, query_str_len, CGI_LED_ID_KEY, key_value, sizeof(key_value)) < 0)
332         {
333                 LOG_ERR("key %s, not found\n", CGI_LED_ID_KEY);
334                 goto error;
335         }
336
337         LOG_INFO("Found key %s = %s\n", CGI_LED_ID_KEY, key_value);
338         led_id = atoi(key_value);
339
340
341         if (http_getValue(query_str, query_str_len, CGI_LED_CMD_KEY, key_value, sizeof(key_value)) < 0)
342         {
343                 LOG_ERR("key %s, not found\n", CGI_LED_CMD_KEY);
344                 goto error;
345         }
346
347         LOG_INFO("Found key %s = %s\n", CGI_LED_CMD_KEY, key_value);
348         led_cmd = atoi(key_value);
349
350         if (led_cmd)
351         {
352                 LED_ON(led_id);
353                 SET_LED_STATUS(status.led_status, led_id);
354         }
355         else
356         {
357                 LED_OFF(led_id);
358                 CLEAR_LED_STATUS(status.led_status, led_id);
359         }
360
361         sprintf((char *)tx_buf, "{\"n\":%d, \"set\":,%d}", led_id, led_cmd);
362
363         http_sendOk(client, HTTP_CONTENT_JSON);
364         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
365         return 0;
366
367 error:
368         http_sendInternalErr(client, HTTP_CONTENT_JSON);
369         return 0;
370 }
371
372 static int cgi_ledStatus(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
373 {
374         (void)recv_buf;
375         (void)recv_len;
376         (void)name;
377
378         sprintf((char *)tx_buf, "{ \"0\":\"%d\", \"1\":\"%d\", \"2\":\"%d\"}",
379                                                                 GET_LED_STATUS(status.led_status, 0),
380                                                                 GET_LED_STATUS(status.led_status, 1),
381                                                                 GET_LED_STATUS(status.led_status, 2));
382
383         http_sendOk(client, HTTP_CONTENT_JSON);
384         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
385         return 0;
386 }
387
388
389 #define CGI_MSG_CMD_KEY   "msg"
390
391 static int cgi_displayMsg(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
392 {
393         (void)recv_buf;
394         (void)recv_len;
395         (void)name;
396
397         char *query_str = strstr(name, "?") + 1;
398         size_t query_str_len = strlen(query_str);
399
400         int len = http_tokenizeGetRequest(query_str, query_str_len);
401
402         LOG_INFO("Found %d key/value pair\n", len);
403
404         if (http_getValue(query_str, query_str_len, CGI_MSG_CMD_KEY, key_value, sizeof(key_value)) > 0)
405         {
406
407                 LOG_INFO("Found key %s = %s\n", CGI_MSG_CMD_KEY, key_value);
408
409                 gfx_bitmapClear(lcd_bitmap);
410                 text_style(lcd_bitmap, STYLEF_BOLD | STYLEF_UNDERLINE, STYLEF_BOLD | STYLEF_UNDERLINE);
411                 text_xprintf(lcd_bitmap, 0, 0, TEXT_CENTER | TEXT_FILL, "BeRTOS Simple Http Server");
412                 text_style(lcd_bitmap, 0, STYLEF_MASK);
413                 text_xprintf(lcd_bitmap, 2, 0, TEXT_CENTER | TEXT_FILL, "Your message:");
414                 text_xprintf(lcd_bitmap, 10, 0, TEXT_CENTER, "%s", key_value);
415
416                 lcd_hx8347_blitBitmap(lcd_bitmap);
417
418                 http_sendOk(client, HTTP_CONTENT_JSON);
419                 return 0;
420         }
421
422         http_sendInternalErr(client, HTTP_CONTENT_JSON);
423         return 0;
424 }
425
426 /*
427  * Reply to client the request string.
428  */
429 static int cgi_echo(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
430 {
431         (void)name;
432
433         http_sendOk(client, HTTP_CONTENT_PLAIN);
434         netconn_write(client, recv_buf, recv_len, NETCONN_COPY);
435         return 0;
436 }
437
438 /*
439  * Return to client a string that display the CHIP ID information.
440  * See datasheet for more detail.
441  */
442 static int cgi_chipInfo(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
443 {
444         (void)recv_buf;
445         (void)recv_len;
446         (void)name;
447
448         sprintf((char *)tx_buf, "{ \"core_name\":\"%s\", \"arch_name\":\"%s\", \"sram_size\":\"%s\",\"flash_size\":\"%s\", \"mem_boot_type\":\"%s\" }",
449                                                 chipid_eproc_name(CHIPID_EPRCOC()),
450                                                 chipid_archnames(CHIPID_ARCH()),
451                                                 chipid_sramsize(CHIPID_SRAMSIZ()),
452                                                 chipid_nvpsize(CHIPID_NVPSIZ()),
453                                                 chipid_nvptype(CHIPID_NVTYP()));
454
455         http_sendOk(client, HTTP_CONTENT_JSON);
456         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
457
458         return 0;
459 }
460
461
462 static int cgi_error(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
463 {
464         (void)client;
465         (void)name;
466         (void)recv_buf;
467         (void)recv_len;
468
469         return -1;
470 }
471
472
473 /*
474  * Default function that http server call every client request, if it doesn't match a cgi table.
475  * In this implementation all client request are associate to real file stored on FAT file
476  * sistem on SD card. If the file there is not on SD card the server reply to client the
477  * error File not found, and send an harcoded page. In the same way, the server reply
478  * error page if the SD card is not present.
479  *
480  */
481 static int http_htmPageLoad(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
482 {
483         (void)recv_buf;
484         (void)recv_len;
485
486         if (SD_CARD_PRESENT())
487         {
488
489                 // SD fat filesystem context
490                 Sd sd;
491                 FATFS fs;
492                 FatFile in_file;
493                 FRESULT result;
494
495                 bool sd_ok = sd_init(&sd, NULL, 0);
496                 if (sd_ok)
497                 {
498                         LOG_INFO("Mount FAT filesystem.\n");
499                         result = f_mount(0, &fs);
500                         if (result != FR_OK)
501                         {
502                                 LOG_ERR("Mounting FAT volumes error[%d]\n", result);
503                                 sd_ok = false;
504                                 f_mount(0, NULL);
505                         }
506
507                         if (sd_ok)
508                         {
509                                 result = fatfile_open(&in_file, name,  FA_OPEN_EXISTING | FA_READ);
510
511                                 size_t count = 0;
512                                 if (result == FR_OK)
513                                 {
514                                         LOG_INFO("Opened file '%s' size %ld\n", name, in_file.fat_file.fsize);
515
516                                         int type = http_searchContentType(name);
517                                         http_sendOk(client, type);
518
519                                         while (count < in_file.fat_file.fsize)
520                                         {
521                                                 int len = kfile_read(&in_file.fd, tx_buf, sizeof(tx_buf));
522                                                 netconn_write(client, tx_buf, len, NETCONN_COPY);
523                                                 count += len;
524                                         }
525
526                                         kfile_flush(&in_file.fd);
527                                         kfile_close(&in_file.fd);
528
529                                         LOG_INFO("Sent: %d\n", count);
530                                 }
531                                 else
532                                 {
533                                         LOG_ERR("Unable to open file: '%s' error[%d]\n",  name, result);
534                                         http_sendFileNotFound(client, HTTP_CONTENT_HTML);
535                                         netconn_write(client, http_file_not_found, http_file_not_found_len - 1, NETCONN_NOCOPY);
536                                 }
537                         }
538                 }
539                 f_mount(0, NULL);
540                 LOG_INFO("Umount FAT filesystem.\n");
541         }
542         else
543         {
544                 http_sendFileNotFound(client, HTTP_CONTENT_HTML);
545                 netconn_write(client, http_sd_not_present, http_sd_not_present_len, NETCONN_NOCOPY);
546         }
547
548         return 0;
549 }
550
551
552 /*
553  * Static cgi table where we associate callback to page.
554  */
555 static HttpCGI cgi_table[] =
556 {
557         { CGI_MATCH_NAME, "echo",                cgi_echo          },
558         { CGI_MATCH_NAME, "get_temperature",     cgi_temp          },
559         { CGI_MATCH_NAME, "get_uptime",          cgi_uptime        },
560         { CGI_MATCH_NAME, "get_resistor",        cgi_resistor      },
561         { CGI_MATCH_NAME, "set_led",             cgi_led           },
562         { CGI_MATCH_NAME, "get_ledStatus",       cgi_ledStatus     },
563         { CGI_MATCH_NAME, "error",               cgi_error         },
564         { CGI_MATCH_NAME, "status",              cgi_status        },
565         { CGI_MATCH_NAME, "get_chipinfo",        cgi_chipInfo      },
566         { CGI_MATCH_NAME, "display",             cgi_displayMsg    },
567         { CGI_MATCH_NAME, "bertos_logo_jpg",     cgi_logo          },
568         { CGI_MATCH_NONE,  NULL,                 NULL              }
569 };
570
571
572 int main(void)
573 {
574         struct netconn *server;
575
576         /* Hardware initialization */
577         init();
578         http_init(http_htmPageLoad, cgi_table);
579
580         lcd_hx8347_blitBitmap24(12, 52, BMP_LOGO_WIDTH, BMP_LOGO_HEIGHT, bmp_logo);
581
582         dhcp_start(&netif);
583         while (!netif.ip_addr.addr)
584                 timer_delay(DHCP_FINE_TIMER_MSECS);
585
586         sprintf(status.local_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(netif.ip_addr.addr));
587         sprintf(status.last_connected_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(0));
588         LOG_INFO("dhcp ok: ip = %s\n", status.local_ip);
589
590         text_xprintf(lcd_bitmap, 14, 0, 0, "Board ip: %s", status.local_ip);
591         lcd_hx8347_blitBitmap(lcd_bitmap);
592
593
594         proc_new(proc_displayRefresh, NULL, KERN_MINSTACKSIZE * 2, NULL);
595
596         server = netconn_new(NETCONN_TCP);
597         netconn_bind(server, IP_ADDR_ANY, 80);
598         netconn_listen(server);
599
600         while (1)
601         {
602                 http_poll(server);
603         }
604 }