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