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