fdf90de5092a44f42e44b871ce25a1f176ca2c96
[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 "hw/hw_http.h"
45 #include "hw/hw_sd.h"
46 #include "hw/hw_adc.h"
47 #include "hw/hw_sdram.h"
48
49 // Define logging setting (for cfg/log.h module).
50 #define LOG_LEVEL         3
51 #define LOG_VERBOSITY     0
52 #include <cfg/log.h>
53 #include <cfg/debug.h>
54
55 #include <cpu/irq.h>
56 #include <cpu/power.h>
57
58 #include <drv/timer.h>
59 #include <drv/ser.h>
60 #include <drv/sd.h>
61 #include <drv/dmac_sam3.h>
62 #include <drv/adc.h>
63
64 #include <kern/proc.h>
65 #include <kern/monitor.h>
66
67 #include <net/http.h>
68
69 #include <netif/ethernetif.h>
70
71 #include <lwip/ip.h>
72 #include <lwip/ip_addr.h>
73 #include <lwip/netif.h>
74 #include <lwip/tcpip.h>
75 #include <lwip/dhcp.h>
76
77 #include <fs/fat.h>
78
79 #include <icons/bertos.h>
80
81 #include <stdio.h>
82 #include <string.h>
83
84 /* Network interface global variables */
85 static struct ip_addr ipaddr, netmask, gw;
86 static struct netif netif;
87
88 typedef struct BoardStatus
89 {
90         char local_ip[sizeof("123.123.123.123")];
91         char last_connected_ip[sizeof("123.123.123.123")];
92         uint16_t internal_temp;
93         uint32_t up_time;
94         size_t tot_req;
95 } BoardStatus;
96
97 static BoardStatus status;
98
99
100 static void init(void)
101 {
102         /* Enable all the interrupts */
103         IRQ_ENABLE;
104
105         /* Initialize debugging module (allow kprintf(), etc.) */
106         kdbg_init();
107         /* Initialize system timer */
108         timer_init();
109
110         /*
111          * Kernel initialization: processes (allow to create and dispatch
112          * processes using proc_new()).
113          */
114         proc_init();
115         sdram_init();
116
117         /* Initialize TCP/IP stack */
118         tcpip_init(NULL, NULL);
119
120         /* Bring up the network interface */
121         netif_add(&netif, &ipaddr, &netmask, &gw, NULL, ethernetif_init, tcpip_input);
122         netif_set_default(&netif);
123         netif_set_up(&netif);
124
125         dmac_init();
126
127         adc_init();
128         /* Enable the adc to read internal temperature sensor */
129         hw_enableTempRead();
130 }
131
132 static NORETURN void status_process(void)
133 {
134         while (1)
135         {
136                 status.internal_temp = hw_convertToDegree(adc_read(ADC_TEMPERATURE_CH));
137                 status.up_time++;
138                 timer_delay(1000);
139         }
140 }
141
142 /* Macro to unpack the ip addres from lwip format */
143 #define IP_ADDR_TO_INT_TUPLE(addr) \
144                 (int)((addr) >>  0 & 0xff), \
145                 (int)((addr) >>  8 & 0xff), \
146                 (int)((addr) >> 16 & 0xff), \
147                 (int)((addr) >> 24 & 0xff)
148
149
150 static uint8_t tx_buf[2048];
151
152 /*
153  * Return a JSON string of board status.
154  */
155 static int cgi_status(struct netconn *client, const char *name, char *revc_buf, size_t revc_len)
156 {
157         (void)revc_buf;
158         (void)revc_len;
159         (void)name;
160
161         //Update board status.
162         sprintf(status.last_connected_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(client->pcb.ip->remote_ip.addr));
163         sprintf(status.local_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(client->pcb.ip->local_ip.addr));
164         sprintf((char *)tx_buf, "[ \"%s\", \"%s\", %d.%d, %ld, %d ]", status.local_ip, status.last_connected_ip,
165                                                                                                                         status.internal_temp / 10, status.internal_temp % 10,
166                                                                                                                         status.up_time, status.tot_req);
167
168         status.tot_req++;
169
170         http_sendOk(client);
171         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
172         return 0;
173 }
174
175 static int cgi_logo(struct netconn *client, const char *name, char *revc_buf, size_t revc_len)
176 {
177         (void)revc_buf;
178         (void)revc_len;
179         (void)name;
180
181         http_sendOk(client);
182         netconn_write(client, bertos_logo_jpg, bertos_logo_jpg_len, NETCONN_NOCOPY);
183         return 0;
184 }
185
186 /*
187  * Return the internal micro temperature string.
188  */
189 static int cgi_temp(struct netconn *client, const char *name, char *revc_buf, size_t revc_len)
190 {
191         (void)revc_buf;
192         (void)revc_len;
193         (void)name;
194
195         sprintf((char *)tx_buf, "[%d.%d]", status.internal_temp / 10, status.internal_temp % 10);
196
197         http_sendOk(client);
198         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
199         return 0;
200 }
201
202
203 /*
204  * Return the board uptime.
205  */
206 static int cgi_uptime(struct netconn *client, const char *name, char *revc_buf, size_t revc_len)
207 {
208         (void)revc_buf;
209         (void)revc_len;
210         (void)name;
211
212
213
214         uint32_t m = status.up_time / 60;
215         uint32_t h = m / 60;
216         uint32_t s = status.up_time  - (m * 60) - (h * 3600);
217
218         sprintf((char *)tx_buf, "[\"%ldh %ldm %lds\"]", h, m, s);
219
220         http_sendOk(client);
221         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
222         return 0;
223 }
224
225 /*
226  * Return the VR1 potentiometer voltage.
227  */
228 static int cgi_resistor(struct netconn *client, const char *name, char *revc_buf, size_t revc_len)
229 {
230         (void)revc_buf;
231         (void)revc_len;
232         (void)name;
233
234         uint16_t volt = ADC_RANGECONV(adc_read(1), 0, 3300);
235         sprintf((char *)tx_buf, "[ \"%d.%dV\" ]",  volt / 1000, volt % 1000);
236
237         http_sendOk(client);
238         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
239         return 0;
240 }
241
242 /*
243  * Reply to client the request string.
244  */
245 static int cgi_led(struct netconn *client, const char *name, char *revc_buf, size_t revc_len)
246 {
247         (void)name;
248
249         http_sendOk(client);
250         netconn_write(client, revc_buf, revc_len, NETCONN_COPY);
251         return 0;
252 }
253
254 /*
255  * Reply to client the request string.
256  */
257 static int cgi_echo(struct netconn *client, const char *name, char *revc_buf, size_t revc_len)
258 {
259         (void)name;
260
261         http_sendOk(client);
262         netconn_write(client, revc_buf, revc_len, NETCONN_COPY);
263         return 0;
264 }
265
266
267
268 /*
269  * Default function that http server call every client request, if it doesn't match a cgi table.
270  * In this implementation all client request are associate to real file stored on FAT file
271  * sistem on SD card. If the file there is not on SD card the server reply to client the
272  * error File not found, and send an harcoded page. In the same way, the server reply
273  * error page if the SD card is not present.
274  *
275  */
276 static int http_htmPageLoad(struct netconn *client, const char *name, char *revc_buf, size_t revc_len)
277 {
278         (void)revc_buf;
279         (void)revc_len;
280
281         if (SD_CARD_PRESENT())
282         {
283
284                 // SD fat filesystem context
285                 Sd sd;
286                 FATFS fs;
287                 FatFile in_file;
288                 FRESULT result;
289
290                 bool sd_ok = sd_init(&sd, NULL, 0);
291                 if (sd_ok)
292                 {
293                         LOG_INFO("Mount FAT filesystem.\n");
294                         result = f_mount(0, &fs);
295                         if (result != FR_OK)
296                         {
297                                 LOG_ERR("Mounting FAT volumes error[%d]\n", result);
298                                 sd_ok = false;
299                                 f_mount(0, NULL);
300                         }
301
302                         if (sd_ok)
303                         {
304                                 result = fatfile_open(&in_file, name,  FA_OPEN_EXISTING | FA_READ);
305
306                                 size_t count = 0;
307                                 if (result == FR_OK)
308                                 {
309                                         LOG_INFO("Opened file '%s' size %ld\n", name, in_file.fat_file.fsize);
310
311                                         http_sendOk(client);
312
313                                         while (count < in_file.fat_file.fsize)
314                                         {
315                                                 int len = kfile_read(&in_file.fd, tx_buf, sizeof(tx_buf));
316                                                 netconn_write(client, tx_buf, len, NETCONN_COPY);
317                                                 count += len;
318                                         }
319
320                                         kfile_flush(&in_file.fd);
321                                         kfile_close(&in_file.fd);
322
323                                         LOG_INFO("Sent: %d\n", count);
324                                 }
325                                 else
326                                 {
327                                         LOG_ERR("Unable to open file: '%s' error[%d]\n",  name, result);
328                                         http_sendFileNotFound(client);
329                                         netconn_write(client, http_file_not_found, http_file_not_found_len - 1, NETCONN_NOCOPY);
330                                 }
331                         }
332                 }
333                 f_mount(0, NULL);
334                 LOG_INFO("Umount FAT filesystem.\n");
335         }
336         else
337         {
338                 http_sendFileNotFound(client);
339                 netconn_write(client, http_sd_not_present, http_sd_not_present_len, NETCONN_NOCOPY);
340         }
341
342         return 0;
343 }
344
345 /*
346  * Return to client a string that display the CHIP ID information.
347  * See datasheet for more detail.
348  */
349 static int cgi_chipInfo(struct netconn *client, const char *name, char *revc_buf, size_t revc_len)
350 {
351         (void)revc_buf;
352         (void)revc_len;
353         (void)name;
354
355         sprintf((char *)tx_buf, "{ \"core_name\":\"%s\", \"arch_name\":\"%s\", \"sram_size\":\"%s\",\
356                                                                 \"flash_size\":\"%s\", \"mem_boot_type\":\"%s\" }",
357         chipid_eproc_name(CHIPID_EPRCOC()),
358         chipid_archnames(CHIPID_ARCH()),
359         chipid_sramsize(CHIPID_SRAMSIZ()),
360         chipid_nvpsize(CHIPID_NVPSIZ()),
361         chipid_nvptype(CHIPID_NVTYP()));
362
363         http_sendOk(client);
364         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
365
366         return 0;
367 }
368
369 /*
370  * Static cgi table where we associate callback to page.
371  */
372 static HttpCGI cgi_table[] =
373 {
374         { CGI_MATCH_WORD, "echo",                cgi_echo          },
375         { CGI_MATCH_NAME, "get_temperature",     cgi_temp          },
376         { CGI_MATCH_NAME, "get_uptime",          cgi_uptime        },
377         { CGI_MATCH_NAME, "get_resistor",        cgi_resistor      },
378         { CGI_MATCH_NAME, "set_led",             cgi_led           },
379         { CGI_MATCH_WORD, "status",              cgi_status        },
380         { CGI_MATCH_NAME, "get_chipinfo",        cgi_chipInfo      },
381         { CGI_MATCH_NAME, "bertos_logo_jpg",     cgi_logo          },
382         { CGI_MATCH_NONE,  NULL,                 NULL              }
383 };
384
385
386 int main(void)
387 {
388         struct netconn *server;
389
390         /* Hardware initialization */
391         init();
392         http_init(http_htmPageLoad, cgi_table);
393
394         proc_new(status_process, NULL, KERN_MINSTACKSIZE * 2, NULL);
395
396         dhcp_start(&netif);
397         while (!netif.ip_addr.addr)
398                 timer_delay(DHCP_FINE_TIMER_MSECS);
399         kprintf("dhcp ok: ip = %d.%d.%d.%d\n", IP_ADDR_TO_INT_TUPLE(netif.ip_addr.addr));
400
401         server = netconn_new(NETCONN_TCP);
402         netconn_bind(server, IP_ADDR_ANY, 80);
403         netconn_listen(server);
404
405         while (1)
406         {
407                 http_poll(server);
408         }
409 }