4 * This file is part of BeRTOS.
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.
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.
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
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.
29 * Copyright 2011 Develer S.r.l. (http://www.develer.com/)
33 * \author Andrea Righi <arighi@develer.com>
34 * \author Daniele Basile <asterix@develer.com>
36 * \brief Simple Http server.
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.
46 #include "hw/hw_http.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"
53 // Define logging setting (for cfg/log.h module).
55 #define LOG_VERBOSITY 0
57 #include <cfg/debug.h>
60 #include <cpu/power.h>
62 #include <drv/timer.h>
65 #include <drv/dmac_sam3.h>
67 #include <drv/lcd_hx8347.h>
69 #include <kern/proc.h>
70 #include <kern/monitor.h>
71 #include <struct/heap.h>
75 #include <netif/ethernetif.h>
78 #include <lwip/ip_addr.h>
79 #include <lwip/netif.h>
80 #include <lwip/tcpip.h>
81 #include <lwip/dhcp.h>
89 #include <icons/bertos.h>
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)
102 /* Network interface global variables */
103 static struct ip_addr ipaddr, netmask, gw;
104 static struct netif netif;
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)))
111 typedef struct BoardStatus
113 char local_ip[sizeof("123.123.123.123")];
114 char last_connected_ip[sizeof("123.123.123.123")];
116 uint16_t internal_temp;
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];
130 static void init(void)
132 /* Enable all the interrupts */
135 /* Initialize debugging module (allow kprintf(), etc.) */
137 /* Initialize system timer */
141 * Kernel initialization: processes (allow to create and dispatch
142 * processes using proc_new()).
149 /* Enable the adc to read internal temperature sensor */
153 heap_init(&heap, (void *)SDRAM_BASE, SDRAM_SIZE);
154 lcd_bitmap = heap_allocmem(&heap, RAST_SIZE(LCD_WIDTH, LCD_HEIGHT));
156 kprintf("Allocated memory for display raster, addr 0x%x\n", (unsigned)lcd_bitmap);
159 kprintf("Error allocating memory for LCD raster!\n");
163 lcd_setBacklight(lcd_brightness);
165 gfx_bitmapInit(lcd_bitmap, raster, LCD_WIDTH, LCD_HEIGHT);
166 gfx_setFont(lcd_bitmap, &font_luBS14);
167 lcd_hx8347_blitBitmap(lcd_bitmap);
169 /* Initialize TCP/IP stack */
170 tcpip_init(NULL, NULL);
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);
178 static int sec_to_strDhms(uint32_t sec_time, char *str, size_t len)
180 uint32_t h = (sec_time / 3600);
182 uint32_t m = ((sec_time - (h * 3600)) / 60);
183 uint32_t s = (sec_time - (m * 60) - (h * 3600));
185 if (len < sizeof("xxxxd xxh xxm xxs"))
188 sprintf(str, "%ldd %ldh %ldm %lds", d, (h >= 24) ? h - 24 : h, m, s);
194 static NORETURN void proc_displayRefresh(void)
198 //LOG_INFO("Refresh display\n");
200 status.internal_temp = hw_convertToDegree(adc_read(ADC_TEMPERATURE_CH));
202 sec_to_strDhms(status.up_time, (char *)tx_buf, sizeof(tx_buf));
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);
213 lcd_hx8347_blitBitmap(lcd_bitmap);
220 * Return a JSON string of board status.
222 static int cgi_status(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
229 uint16_t volt = adc_read(1);
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));
235 sprintf((char *)tx_buf, "{ \"local_ip\":\"%s\",\"last_connected_ip\":\"%s\", \"temp\":%d.%d,\"volt\":%d,\"up_time\":%d,\"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));
244 http_sendOk(client, HTTP_CONTENT_JSON);
245 netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
249 static int cgi_logo(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
255 http_sendOk(client, HTTP_CONTENT_JPEG);
256 netconn_write(client, bertos_logo_jpg, bertos_logo_jpg_len, NETCONN_NOCOPY);
261 * Return the internal micro temperature string.
263 static int cgi_temp(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
269 sprintf((char *)tx_buf, "[%d.%d]", status.internal_temp / 10, status.internal_temp % 10);
271 http_sendOk(client, HTTP_CONTENT_JSON);
272 netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
278 * Return the board uptime.
280 static int cgi_uptime(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
286 sec_to_strDhms(status.up_time, (char *)tx_buf, sizeof(tx_buf));
288 http_sendOk(client, HTTP_CONTENT_JSON);
289 netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
294 * Return the VR1 potentiometer voltage.
296 static int cgi_resistor(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
302 uint16_t volt = ADC_RANGECONV(adc_read(1), 0, 3300);
303 kprintf("volt %d\n", volt);
304 sprintf((char *)tx_buf, "[ \"%d.%dV\" ]", volt / 1000, volt % 1000);
306 http_sendOk(client, HTTP_CONTENT_JSON);
307 netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
312 #define CGI_LED_ID_KEY "n"
313 #define CGI_LED_CMD_KEY "set"
315 static char key_value[80];
318 * Reply to client the request string.
320 static int cgi_led(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
326 char *query_str = strstr(name, "?") + 1;
327 size_t query_str_len = strlen(query_str);
331 int len = http_tokenizeGetRequest(query_str, query_str_len);
333 LOG_INFO("Found %d key/value pair\n", len);
335 if (http_getValue(query_str, query_str_len, CGI_LED_ID_KEY, key_value, sizeof(key_value)) < 0)
337 LOG_ERR("key %s, not found\n", CGI_LED_ID_KEY);
341 LOG_INFO("Found key %s = %s\n", CGI_LED_ID_KEY, key_value);
342 led_id = atoi(key_value);
345 if (http_getValue(query_str, query_str_len, CGI_LED_CMD_KEY, key_value, sizeof(key_value)) < 0)
347 LOG_ERR("key %s, not found\n", CGI_LED_CMD_KEY);
351 LOG_INFO("Found key %s = %s\n", CGI_LED_CMD_KEY, key_value);
352 led_cmd = atoi(key_value);
357 SET_LED_STATUS(status.led_status, led_id);
362 CLEAR_LED_STATUS(status.led_status, led_id);
365 sprintf((char *)tx_buf, "{\"n\":%d, \"set\":,%d}", led_id, led_cmd);
367 http_sendOk(client, HTTP_CONTENT_JSON);
368 netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
372 http_sendInternalErr(client, HTTP_CONTENT_JSON);
376 static int cgi_ledStatus(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
382 sprintf((char *)tx_buf, "{ \"0\":\"%d\", \"1\":\"%d\", \"2\":\"%d\"}",
383 GET_LED_STATUS(status.led_status, 0),
384 GET_LED_STATUS(status.led_status, 1),
385 GET_LED_STATUS(status.led_status, 2));
387 http_sendOk(client, HTTP_CONTENT_JSON);
388 netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
393 #define CGI_MSG_CMD_KEY "msg"
395 static int cgi_displayMsg(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
401 char *query_str = strstr(name, "?") + 1;
402 size_t query_str_len = strlen(query_str);
404 int len = http_tokenizeGetRequest(query_str, query_str_len);
406 LOG_INFO("Found %d key/value pair\n", len);
408 if (http_getValue(query_str, query_str_len, CGI_MSG_CMD_KEY, key_value, sizeof(key_value)) > 0)
411 LOG_INFO("Found key %s = %s\n", CGI_MSG_CMD_KEY, key_value);
413 gfx_bitmapClear(lcd_bitmap);
414 text_style(lcd_bitmap, STYLEF_BOLD | STYLEF_UNDERLINE, STYLEF_BOLD | STYLEF_UNDERLINE);
415 text_xprintf(lcd_bitmap, 0, 0, TEXT_CENTER | TEXT_FILL, "BeRTOS Simple Http Server");
416 text_style(lcd_bitmap, 0, STYLEF_MASK);
417 text_xprintf(lcd_bitmap, 2, 0, TEXT_CENTER | TEXT_FILL, "Your message:");
418 text_xprintf(lcd_bitmap, 10, 0, TEXT_CENTER, "%s", key_value);
420 lcd_hx8347_blitBitmap(lcd_bitmap);
422 http_sendOk(client, HTTP_CONTENT_JSON);
426 http_sendInternalErr(client, HTTP_CONTENT_JSON);
431 * Reply to client the request string.
433 static int cgi_echo(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
437 http_sendOk(client, HTTP_CONTENT_PLAIN);
438 netconn_write(client, recv_buf, recv_len, NETCONN_COPY);
443 * Return to client a string that display the CHIP ID information.
444 * See datasheet for more detail.
446 static int cgi_chipInfo(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
452 sprintf((char *)tx_buf, "{ \"core_name\":\"%s\", \"arch_name\":\"%s\", \"sram_size\":\"%s\",\"flash_size\":\"%s\", \"mem_boot_type\":\"%s\" }",
453 chipid_eproc_name(CHIPID_EPRCOC()),
454 chipid_archnames(CHIPID_ARCH()),
455 chipid_sramsize(CHIPID_SRAMSIZ()),
456 chipid_nvpsize(CHIPID_NVPSIZ()),
457 chipid_nvptype(CHIPID_NVTYP()));
459 http_sendOk(client, HTTP_CONTENT_JSON);
460 netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
466 static int cgi_error(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
478 * Default function that http server call every client request, if it doesn't match a cgi table.
479 * In this implementation all client request are associate to real file stored on FAT file
480 * sistem on SD card. If the file there is not on SD card the server reply to client the
481 * error File not found, and send an harcoded page. In the same way, the server reply
482 * error page if the SD card is not present.
485 static int http_htmPageLoad(struct netconn *client, const char *name, char *recv_buf, size_t recv_len)
490 if (SD_CARD_PRESENT())
493 // SD fat filesystem context
499 bool sd_ok = sd_init(&sd, NULL, 0);
502 LOG_INFO("Mount FAT filesystem.\n");
503 result = f_mount(0, &fs);
506 LOG_ERR("Mounting FAT volumes error[%d]\n", result);
513 result = fatfile_open(&in_file, name, FA_OPEN_EXISTING | FA_READ);
518 LOG_INFO("Opened file '%s' size %ld\n", name, in_file.fat_file.fsize);
520 int type = http_searchContentType(name);
521 http_sendOk(client, type);
523 while (count < in_file.fat_file.fsize)
525 int len = kfile_read(&in_file.fd, tx_buf, sizeof(tx_buf));
526 netconn_write(client, tx_buf, len, NETCONN_COPY);
530 kfile_flush(&in_file.fd);
531 kfile_close(&in_file.fd);
533 LOG_INFO("Sent: %d\n", count);
537 LOG_ERR("Unable to open file: '%s' error[%d]\n", name, result);
538 http_sendFileNotFound(client, HTTP_CONTENT_HTML);
539 netconn_write(client, http_file_not_found, http_file_not_found_len - 1, NETCONN_NOCOPY);
544 LOG_INFO("Umount FAT filesystem.\n");
548 http_sendFileNotFound(client, HTTP_CONTENT_HTML);
549 netconn_write(client, http_sd_not_present, http_sd_not_present_len, NETCONN_NOCOPY);
557 * Static cgi table where we associate callback to page.
559 static HttpCGI cgi_table[] =
561 { CGI_MATCH_NAME, "echo", cgi_echo },
562 { CGI_MATCH_NAME, "get_temperature", cgi_temp },
563 { CGI_MATCH_NAME, "get_uptime", cgi_uptime },
564 { CGI_MATCH_NAME, "get_resistor", cgi_resistor },
565 { CGI_MATCH_NAME, "set_led", cgi_led },
566 { CGI_MATCH_NAME, "get_ledStatus", cgi_ledStatus },
567 { CGI_MATCH_NAME, "error", cgi_error },
568 { CGI_MATCH_NAME, "status", cgi_status },
569 { CGI_MATCH_NAME, "get_chipinfo", cgi_chipInfo },
570 { CGI_MATCH_NAME, "display", cgi_displayMsg },
571 { CGI_MATCH_NAME, "bertos_logo_jpg", cgi_logo },
572 { CGI_MATCH_NONE, NULL, NULL }
578 struct netconn *server;
580 /* Hardware initialization */
582 http_init(http_htmPageLoad, cgi_table);
584 lcd_hx8347_blitBitmap24(12, 52, BMP_LOGO_WIDTH, BMP_LOGO_HEIGHT, bmp_logo);
587 while (!netif.ip_addr.addr)
588 timer_delay(DHCP_FINE_TIMER_MSECS);
590 sprintf(status.local_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(netif.ip_addr.addr));
591 sprintf(status.last_connected_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(0));
592 kprintf("dhcp ok: ip = %s", status.local_ip);
594 text_xprintf(lcd_bitmap, 14, 0, 0, "Board ip: %s", status.local_ip);
595 lcd_hx8347_blitBitmap(lcd_bitmap);
598 proc_new(proc_displayRefresh, NULL, KERN_MINSTACKSIZE * 2, NULL);
600 server = netconn_new(NETCONN_TCP);
601 netconn_bind(server, IP_ADDR_ANY, 80);
602 netconn_listen(server);