Draw some info to display, and refresh it every some time. Add cgi to write message...
[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 /* Macro to unpack the ip addres from lwip format in 4 int*/
96 #define IP_ADDR_TO_INT_TUPLE(addr) \
97                 (int)((addr) >>  0 & 0xff), \
98                 (int)((addr) >>  8 & 0xff), \
99                 (int)((addr) >> 16 & 0xff), \
100                 (int)((addr) >> 24 & 0xff)
101
102 /* Network interface global variables */
103 static struct ip_addr ipaddr, netmask, gw;
104 static struct netif netif;
105
106
107 #define GET_LED_STATUS(status, led_id)     (((status) & BV((led_id))) >> (led_id))
108 #define CLEAR_LED_STATUS(status, led_id)   ((status) &= ~BV((led_id)))
109 #define SET_LED_STATUS(status, led_id)     ((status) |= BV((led_id)))
110
111 typedef struct BoardStatus
112 {
113         char local_ip[sizeof("123.123.123.123")];
114         char last_connected_ip[sizeof("123.123.123.123")];
115         uint8_t led_status;
116         uint16_t internal_temp;
117         uint32_t up_time;
118         size_t tot_req;
119 } BoardStatus;
120
121 static BoardStatus status;
122 static uint8_t raster[RAST_SIZE(LCD_WIDTH, LCD_HEIGHT)];
123 static Bitmap *lcd_bitmap;
124 extern Font font_gohu;
125 static int lcd_brightness = LCD_BACKLIGHT_MAX;
126 static struct Heap heap;
127
128
129 static void init(void)
130 {
131         /* Enable all the interrupts */
132         IRQ_ENABLE;
133
134         /* Initialize debugging module (allow kprintf(), etc.) */
135         kdbg_init();
136         /* Initialize system timer */
137         timer_init();
138
139         /*
140          * Kernel initialization: processes (allow to create and dispatch
141          * processes using proc_new()).
142          */
143         proc_init();
144         sdram_init();
145         dmac_init();
146         adc_init();
147
148         /* Enable the adc to read internal temperature sensor */
149         hw_enableTempRead();
150         LED_INIT();
151
152         heap_init(&heap, (void *)SDRAM_BASE, SDRAM_SIZE);
153         lcd_bitmap = heap_allocmem(&heap, RAST_SIZE(LCD_WIDTH, LCD_HEIGHT));
154         if (lcd_bitmap)
155                 kprintf("Allocated memory for display raster, addr 0x%x\n", (unsigned)lcd_bitmap);
156         else
157         {
158                 kprintf("Error allocating memory for LCD raster!\n");
159         }
160
161         lcd_hx8347_init();
162         lcd_setBacklight(lcd_brightness);
163
164         gfx_bitmapInit(lcd_bitmap, raster, LCD_WIDTH, LCD_HEIGHT);
165         gfx_setFont(lcd_bitmap, &font_luBS14);
166         lcd_hx8347_blitBitmap(lcd_bitmap);
167
168         /* Initialize TCP/IP stack */
169         tcpip_init(NULL, NULL);
170
171         /* Bring up the network interface */
172         netif_add(&netif, &ipaddr, &netmask, &gw, NULL, ethernetif_init, tcpip_input);
173         netif_set_default(&netif);
174         netif_set_up(&netif);
175 }
176
177 static void sec_to_hms(uint32_t sec_time, uint32_t *h, uint32_t *m,  uint32_t *s)
178 {
179         *m = sec_time / 60;
180         *h = (*m) / 60;
181         *s = sec_time - ((*m) * 60) - ((*h) * 3600);
182 }
183
184 static NORETURN void proc_displayRefresh(void)
185 {
186         while (1)
187         {
188                 //LOG_INFO("Refresh display\n");
189                 uint32_t m;
190                 uint32_t h;
191                 uint32_t s;
192                 status.internal_temp = hw_convertToDegree(adc_read(ADC_TEMPERATURE_CH));
193                 status.up_time += 5;
194                 sec_to_hms(status.up_time, &h, &m, &s);
195
196                 text_xprintf(lcd_bitmap, 11, 0, TEXT_FILL, " ");
197                 text_xprintf(lcd_bitmap, 11, 0, 0, "Board ip: %s", status.local_ip);
198
199                 text_xprintf(lcd_bitmap, 12, 0, TEXT_FILL, " ");
200                 text_xprintf(lcd_bitmap, 12, 0, 0, "Last connected ip: %s", status.last_connected_ip);
201
202                 text_xprintf(lcd_bitmap, 13, 0, TEXT_FILL, " ");
203                 text_xprintf(lcd_bitmap, 13, 0, 0, "Temperature: %d.%dC",       status.internal_temp / 10, status.internal_temp % 10);
204
205                 text_xprintf(lcd_bitmap, 14, 0, TEXT_FILL, " ");
206                 text_xprintf(lcd_bitmap, 14, 0, 0, "Up time: %ldh %ldm %lds", h, m, s);
207
208                 lcd_hx8347_blitBitmap(lcd_bitmap);
209                 lcd_hx8347_blitBitmap24(10, 0, BMP_LOGO_WIDTH, BMP_LOGO_HEIGHT, bmp_logo);
210
211                 timer_delay(5000);
212         }
213 }
214
215
216 static uint8_t tx_buf[2048];
217
218 /*
219  * Return a JSON string of board status.
220  */
221 static int cgi_status(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
222 {
223         (void)recv_buf;
224         (void)recv_len;
225         (void)name;
226
227         status.tot_req++;
228         uint16_t volt = ADC_RANGECONV(adc_read(1), 0, 3300);
229         //Update board status.
230         sprintf(status.last_connected_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(client->pcb.ip->remote_ip.addr));
231         sprintf(status.local_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(client->pcb.ip->local_ip.addr));
232
233         sprintf((char *)tx_buf, "{ \"local_ip\":\"%s\",\"last_connected_ip\":\"%s\", \"temp\":%d.%d,\"volt\":%d.%d,\"up_time\":%ld,\"tot_req\":%d, \
234 \"leds\":{ \"0\":\"%d\", \"1\":\"%d\", \"2\":\"%d\"}}",
235                                                                 status.local_ip, status.last_connected_ip,
236                                                                 status.internal_temp / 10, status.internal_temp % 10,
237                                                                 volt / 1000, volt % 1000,
238                                                                 status.up_time, status.tot_req,
239                                                                 GET_LED_STATUS(status.led_status, 0),
240                                                                 GET_LED_STATUS(status.led_status, 1),
241                                                                 GET_LED_STATUS(status.led_status, 2));
242
243         http_sendOk(client, HTTP_CONTENT_JSON);
244         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
245         return 0;
246 }
247
248 static int cgi_logo(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
249 {
250         (void)recv_buf;
251         (void)recv_len;
252         (void)name;
253
254         http_sendOk(client, HTTP_CONTENT_JPEG);
255         netconn_write(client, bertos_logo_jpg, bertos_logo_jpg_len, NETCONN_NOCOPY);
256         return 0;
257 }
258
259 /*
260  * Return the internal micro temperature string.
261  */
262 static int cgi_temp(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
263 {
264         (void)recv_buf;
265         (void)recv_len;
266         (void)name;
267
268         sprintf((char *)tx_buf, "[%d.%d]", status.internal_temp / 10, status.internal_temp % 10);
269
270         http_sendOk(client, HTTP_CONTENT_JSON);
271         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
272         return 0;
273 }
274
275
276 /*
277  * Return the board uptime.
278  */
279 static int cgi_uptime(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
280 {
281         (void)recv_buf;
282         (void)recv_len;
283         (void)name;
284
285         uint32_t m;
286         uint32_t h;
287         uint32_t s;
288         sec_to_hms(status.up_time, &h, &m, &s);
289
290         sprintf((char *)tx_buf, "[\"%ldh %ldm %lds\"]", h, m, s);
291
292         http_sendOk(client, HTTP_CONTENT_JSON);
293         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
294         return 0;
295 }
296
297 /*
298  * Return the VR1 potentiometer voltage.
299  */
300 static int cgi_resistor(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
301 {
302         (void)recv_buf;
303         (void)recv_len;
304         (void)name;
305
306         uint16_t volt = ADC_RANGECONV(adc_read(1), 0, 3300);
307         kprintf("volt %d\n", volt);
308         sprintf((char *)tx_buf, "[ \"%d.%dV\" ]",  volt / 1000, volt % 1000);
309
310         http_sendOk(client, HTTP_CONTENT_JSON);
311         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
312         return 0;
313 }
314
315
316 #define CGI_LED_ID_KEY    "n"
317 #define CGI_LED_CMD_KEY   "set"
318
319 static char key_value[80];
320
321 /*
322  * Reply to client the request string.
323  */
324 static int cgi_led(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
325 {
326         (void)recv_buf;
327         (void)recv_len;
328         (void)name;
329
330         char *query_str = strstr(name, "?") + 1;
331         size_t query_str_len = strlen(query_str);
332         int led_id;
333         int led_cmd;
334
335         int len = http_tokenizeGetRequest(query_str, query_str_len);
336
337         LOG_INFO("Found %d key/value pair\n", len);
338
339         if (http_getValue(query_str, query_str_len, CGI_LED_ID_KEY, key_value, sizeof(key_value)) < 0)
340         {
341                 LOG_ERR("key %s, not found\n", CGI_LED_ID_KEY);
342                 goto error;
343         }
344
345         LOG_INFO("Found key %s = %s\n", CGI_LED_ID_KEY, key_value);
346         led_id = atoi(key_value);
347
348
349         if (http_getValue(query_str, query_str_len, CGI_LED_CMD_KEY, key_value, sizeof(key_value)) < 0)
350         {
351                 LOG_ERR("key %s, not found\n", CGI_LED_CMD_KEY);
352                 goto error;
353         }
354
355         LOG_INFO("Found key %s = %s\n", CGI_LED_CMD_KEY, key_value);
356         led_cmd = atoi(key_value);
357
358         if (led_cmd)
359         {
360                 LED_ON(led_id);
361                 SET_LED_STATUS(status.led_status, led_id);
362         }
363         else
364         {
365                 LED_OFF(led_id);
366                 CLEAR_LED_STATUS(status.led_status, led_id);
367         }
368
369         sprintf((char *)tx_buf, "{\"n\":%d, \"set\":,%d}", led_id, led_cmd);
370
371         http_sendOk(client, HTTP_CONTENT_JSON);
372         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
373         return 0;
374
375 error:
376         http_sendInternalErr(client, HTTP_CONTENT_JSON);
377         return 0;
378 }
379
380 static int cgi_ledStatus(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
381 {
382         (void)recv_buf;
383         (void)recv_len;
384         (void)name;
385
386         sprintf((char *)tx_buf, "{ \"0\":\"%d\", \"1\":\"%d\", \"2\":\"%d\"}",
387                                                                 GET_LED_STATUS(status.led_status, 0),
388                                                                 GET_LED_STATUS(status.led_status, 1),
389                                                                 GET_LED_STATUS(status.led_status, 2));
390
391         http_sendOk(client, HTTP_CONTENT_JSON);
392         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
393         return 0;
394 }
395
396
397 #define CGI_MSG_CMD_KEY   "msg"
398
399 static int cgi_displayMsg(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
400 {
401         (void)recv_buf;
402         (void)recv_len;
403         (void)name;
404
405         char *query_str = strstr(name, "?") + 1;
406         size_t query_str_len = strlen(query_str);
407
408         int len = http_tokenizeGetRequest(query_str, query_str_len);
409
410         LOG_INFO("Found %d key/value pair\n", len);
411
412         if (http_getValue(query_str, query_str_len, CGI_MSG_CMD_KEY, key_value, sizeof(key_value)) < 0)
413         {
414                 LOG_ERR("key %s, not found\n", CGI_MSG_CMD_KEY);
415                 goto error;
416         }
417
418         LOG_INFO("Found key %s = %s\n", CGI_MSG_CMD_KEY, key_value);
419
420         text_xprintf(lcd_bitmap, 10, 0, TEXT_FILL, " ");
421         text_xprintf(lcd_bitmap, 10, 0, TEXT_CENTER, "%s", key_value);
422
423         http_sendOk(client, HTTP_CONTENT_JSON);
424         return 0;
425
426 error:
427         http_sendInternalErr(client, HTTP_CONTENT_JSON);
428         return 0;
429 }
430
431 /*
432  * Reply to client the request string.
433  */
434 static int cgi_echo(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
435 {
436         (void)name;
437
438         http_sendOk(client, HTTP_CONTENT_PLAIN);
439         netconn_write(client, recv_buf, recv_len, NETCONN_COPY);
440         return 0;
441 }
442
443 /*
444  * Return to client a string that display the CHIP ID information.
445  * See datasheet for more detail.
446  */
447 static int cgi_chipInfo(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
448 {
449         (void)recv_buf;
450         (void)recv_len;
451         (void)name;
452
453         sprintf((char *)tx_buf, "{ \"core_name\":\"%s\", \"arch_name\":\"%s\", \"sram_size\":\"%s\",\"flash_size\":\"%s\", \"mem_boot_type\":\"%s\" }",
454                                                 chipid_eproc_name(CHIPID_EPRCOC()),
455                                                 chipid_archnames(CHIPID_ARCH()),
456                                                 chipid_sramsize(CHIPID_SRAMSIZ()),
457                                                 chipid_nvpsize(CHIPID_NVPSIZ()),
458                                                 chipid_nvptype(CHIPID_NVTYP()));
459
460         http_sendOk(client, HTTP_CONTENT_JSON);
461         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
462
463         return 0;
464 }
465
466
467 static int cgi_error(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
468 {
469         (void)client;
470         (void)name;
471         (void)recv_buf;
472         (void)recv_len;
473
474         return -1;
475 }
476
477
478 /*
479  * Default function that http server call every client request, if it doesn't match a cgi table.
480  * In this implementation all client request are associate to real file stored on FAT file
481  * sistem on SD card. If the file there is not on SD card the server reply to client the
482  * error File not found, and send an harcoded page. In the same way, the server reply
483  * error page if the SD card is not present.
484  *
485  */
486 static int http_htmPageLoad(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
487 {
488         (void)recv_buf;
489         (void)recv_len;
490
491         if (SD_CARD_PRESENT())
492         {
493
494                 // SD fat filesystem context
495                 Sd sd;
496                 FATFS fs;
497                 FatFile in_file;
498                 FRESULT result;
499
500                 bool sd_ok = sd_init(&sd, NULL, 0);
501                 if (sd_ok)
502                 {
503                         LOG_INFO("Mount FAT filesystem.\n");
504                         result = f_mount(0, &fs);
505                         if (result != FR_OK)
506                         {
507                                 LOG_ERR("Mounting FAT volumes error[%d]\n", result);
508                                 sd_ok = false;
509                                 f_mount(0, NULL);
510                         }
511
512                         if (sd_ok)
513                         {
514                                 result = fatfile_open(&in_file, name,  FA_OPEN_EXISTING | FA_READ);
515
516                                 size_t count = 0;
517                                 if (result == FR_OK)
518                                 {
519                                         LOG_INFO("Opened file '%s' size %ld\n", name, in_file.fat_file.fsize);
520
521                                         int type = http_searchContentType(name);
522                                         http_sendOk(client, type);
523
524                                         while (count < in_file.fat_file.fsize)
525                                         {
526                                                 int len = kfile_read(&in_file.fd, tx_buf, sizeof(tx_buf));
527                                                 netconn_write(client, tx_buf, len, NETCONN_COPY);
528                                                 count += len;
529                                         }
530
531                                         kfile_flush(&in_file.fd);
532                                         kfile_close(&in_file.fd);
533
534                                         LOG_INFO("Sent: %d\n", count);
535                                 }
536                                 else
537                                 {
538                                         LOG_ERR("Unable to open file: '%s' error[%d]\n",  name, result);
539                                         http_sendFileNotFound(client, HTTP_CONTENT_HTML);
540                                         netconn_write(client, http_file_not_found, http_file_not_found_len - 1, NETCONN_NOCOPY);
541                                 }
542                         }
543                 }
544                 f_mount(0, NULL);
545                 LOG_INFO("Umount FAT filesystem.\n");
546         }
547         else
548         {
549                 http_sendFileNotFound(client, HTTP_CONTENT_HTML);
550                 netconn_write(client, http_sd_not_present, http_sd_not_present_len, NETCONN_NOCOPY);
551         }
552
553         return 0;
554 }
555
556
557 /*
558  * Static cgi table where we associate callback to page.
559  */
560 static HttpCGI cgi_table[] =
561 {
562         { CGI_MATCH_NAME, "echo",                cgi_echo          },
563         { CGI_MATCH_NAME, "get_temperature",     cgi_temp          },
564         { CGI_MATCH_NAME, "get_uptime",          cgi_uptime        },
565         { CGI_MATCH_NAME, "get_resistor",        cgi_resistor      },
566         { CGI_MATCH_NAME, "set_led",             cgi_led           },
567         { CGI_MATCH_NAME, "get_ledStatus",       cgi_ledStatus     },
568         { CGI_MATCH_NAME, "error",               cgi_error         },
569         { CGI_MATCH_NAME, "status",              cgi_status        },
570         { CGI_MATCH_NAME, "get_chipinfo",        cgi_chipInfo      },
571         { CGI_MATCH_NAME, "display",             cgi_displayMsg    },
572         { CGI_MATCH_NAME, "bertos_logo_jpg",     cgi_logo          },
573         { CGI_MATCH_NONE,  NULL,                 NULL              }
574 };
575
576
577 int main(void)
578 {
579         struct netconn *server;
580
581         /* Hardware initialization */
582         init();
583         http_init(http_htmPageLoad, cgi_table);
584
585         proc_new(proc_displayRefresh, NULL, KERN_MINSTACKSIZE * 2, NULL);
586
587         dhcp_start(&netif);
588         while (!netif.ip_addr.addr)
589                 timer_delay(DHCP_FINE_TIMER_MSECS);
590
591         sprintf(status.local_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(netif.ip_addr.addr));
592         sprintf(status.last_connected_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(0));
593         kprintf("dhcp ok: ip = %s", status.local_ip);
594
595         text_xprintf(lcd_bitmap, 12, 0, 0, "Board ip: %s", status.local_ip);
596
597         lcd_hx8347_blitBitmap(lcd_bitmap);
598         lcd_hx8347_blitBitmap24(12, 0, BMP_LOGO_WIDTH, BMP_LOGO_HEIGHT, bmp_logo);
599
600         server = netconn_new(NETCONN_TCP);
601         netconn_bind(server, IP_ADDR_ANY, 80);
602         netconn_listen(server);
603
604         while (1)
605         {
606                 http_poll(server);
607         }
608 }