Comply to new betos module. Add comments.
[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 the /status page, the server return a json dictionary where are store
41  * some board status info, like board temperature, up-time, etc.
42  */
43
44
45 #include "hw/hw_sd.h"
46 #include "hw/hw_adc.h"
47 #include "hw/hw_sdram.h"
48
49 #include <cfg/debug.h>
50
51 #include <cpu/irq.h>
52 #include <cpu/power.h>
53
54 #include <drv/timer.h>
55 #include <drv/ser.h>
56 #include <drv/sd.h>
57 #include <drv/dmac_sam3.h>
58 #include <drv/adc.h>
59
60 #include <kern/proc.h>
61 #include <kern/monitor.h>
62
63 #include <netif/ethernetif.h>
64
65 #include <lwip/ip.h>
66 #include <lwip/ip_addr.h>
67 #include <lwip/netif.h>
68 #include <lwip/tcpip.h>
69 #include <lwip/dhcp.h>
70
71 #include <fs/fat.h>
72
73 #include <icons/bertos.h>
74
75 #include <stdio.h>
76 #include <string.h>
77
78 /* Network interface global variables */
79 static struct ip_addr ipaddr, netmask, gw;
80 static struct netif netif;
81
82 // SD fat filesystem context
83 static Sd sd;
84 static FATFS fs;
85 static FatFile in_file;
86
87 typedef struct BoardStatus
88 {
89         char local_ip[sizeof("123.123.123.123")];
90         char last_connected_ip[sizeof("123.123.123.123")];
91         uint16_t internal_temp;
92         ticks_t up_time;
93         size_t tot_req;
94 } BoardStatus;
95
96 static BoardStatus status;
97
98 static void init(void)
99 {
100         /* Enable all the interrupts */
101         IRQ_ENABLE;
102
103         /* Initialize debugging module (allow kprintf(), etc.) */
104         kdbg_init();
105         /* Initialize system timer */
106         timer_init();
107
108         /*
109          * Kernel initialization: processes (allow to create and dispatch
110          * processes using proc_new()).
111          */
112         proc_init();
113         sdram_init();
114
115         /* Initialize TCP/IP stack */
116         tcpip_init(NULL, NULL);
117
118         /* Bring up the network interface */
119         netif_add(&netif, &ipaddr, &netmask, &gw, NULL, ethernetif_init, tcpip_input);
120         netif_set_default(&netif);
121         netif_set_up(&netif);
122
123         dmac_init();
124
125         adc_init();
126         /* Enable the adc to read internal temperature sensor */
127         hw_enableTempRead();
128 }
129
130 static NORETURN void status_process(void)
131 {
132         while (1)
133         {
134                 status.internal_temp = hw_convertToDegree(adc_read(ADC_TEMPERATURE_CH));
135                 status.up_time++;
136                 timer_delay(1000);
137         }
138 }
139
140 static void get_fileName(char *revc_buf, char *name, size_t len)
141 {
142         char *p = strstr(revc_buf, "GET");
143         if (p)
144         {
145                 //skip the "/" in get string request
146                 p += sizeof("GET") + 1;
147                 for (size_t i = 0; *p != ' '; i++,p++)
148                 {
149                         if (i > len)
150                                 break;
151                         name[i] = *p;
152                 }
153         }
154 }
155
156 static const char http_html_hdr_200[] = "HTTP/1.1 200 OK\r\nContent-type: text/html\r\n\r\n";
157 static const char http_html_hdr_404[] = "HTTP/1.1 404 Not Found\r\nContent-type: text/html\r\n\r\n";
158
159 static const char http_file_not_found[] = "\
160 <!DOCTYPE html PUBLIC \"-//IETF//DTD HTML 2.0//EN\"> \
161 <html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"> \
162 <title>404 Not Found</title></head><body><img src=\"bertos_logo_jpg.jpg\"><h1>404 Not Found</h1>\
163 <p>The requested URL was not found on this server.</p><hr>\
164 <address>BeRTOS simple HTTP server</address></body></html>";
165
166
167 static const char http_sd_not_present[] = " \
168 <!DOCTYPE html PUBLIC \"-//IETF//DTD HTML 2.0//EN\">  \
169 <html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">  \
170 <title>BeRTOS simple HTTP Server</title></head><body><img src=\"bertos_logo_jpg.jpg\"> \
171 <h1>BeRTOS simple HTTP Server</h1><p>Simple Http server, the site's pages are stored on SD card, check it if is present.</p><hr>\
172 <a href=\"http://www.bertos.org\">www.BeRTOS.org</a></body></html> \
173 ";
174
175 static uint8_t tx_buf[2048];
176
177 #define IP_ADDR_TO_INT_TUPLE(addr) \
178                 (int)((addr) >>  0 & 0xff), \
179                 (int)((addr) >>  8 & 0xff), \
180                 (int)((addr) >> 16 & 0xff), \
181                 (int)((addr) >> 24 & 0xff)
182
183
184 static char file_name[80];
185 int main(void)
186 {
187         struct netconn *server;
188         FRESULT result;
189
190         /* Hardware initialization */
191         init();
192
193         proc_new(status_process, NULL, KERN_MINSTACKSIZE * 2, NULL);
194
195         dhcp_start(&netif);
196         while (!netif.ip_addr.addr)
197                 timer_delay(DHCP_FINE_TIMER_MSECS);
198         kprintf("dhcp ok: ip = %d.%d.%d.%d\n", IP_ADDR_TO_INT_TUPLE(netif.ip_addr.addr));
199
200         server = netconn_new(NETCONN_TCP);
201         netconn_bind(server, IP_ADDR_ANY, 80);
202         netconn_listen(server);
203
204         while (1)
205         {
206                 struct netconn *client;
207                 struct netbuf *rx_buf_conn;
208                 char *rx_buf;
209                 u16_t len;
210
211                 client = netconn_accept(server);
212                 if (!client)
213                         continue;
214
215                 //Update board status.
216                 sprintf(status.last_connected_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(client->pcb.ip->remote_ip.addr));
217                 sprintf(status.local_ip, "%d.%d.%d.%d", IP_ADDR_TO_INT_TUPLE(client->pcb.ip->local_ip.addr));
218                 status.tot_req++;
219
220                 rx_buf_conn = netconn_recv(client);
221                 if (rx_buf_conn)
222                 {
223                         netbuf_data(rx_buf_conn, (void **)&rx_buf, &len);
224                         if (rx_buf)
225                         {
226                                 memset(file_name, 0, sizeof(file_name));
227                                 memset(tx_buf, 0, sizeof(tx_buf));
228
229                                 get_fileName(rx_buf, file_name, sizeof(file_name));
230
231                                 kprintf("%s\n", file_name);
232                                 if (strlen(file_name) == 0)
233                                         strcpy(file_name, "index.htm");
234
235                                 if (!strcmp("bertos_logo_jpg.jpg", file_name))
236                                 {
237                                         netconn_write(client, bertos_logo_jpg, bertos_logo_jpg_len, NETCONN_NOCOPY);
238                                 }
239                                 else if (!strcmp("status", file_name))
240                                 {
241                                         sprintf((char *)tx_buf, "[ %s, %s, %d.%d, %ld, %d ]", status.local_ip, status.last_connected_ip,
242                                                                                                                                 status.internal_temp / 10, status.internal_temp % 10,
243                                                                                                                                 status.up_time, status.tot_req);
244
245                                         netconn_write(client, tx_buf, strlen((char *)tx_buf), NETCONN_COPY);
246                                 }
247                                 else if (SD_CARD_PRESENT())
248                                 {
249                                         bool sd_ok = sd_init(&sd, NULL, 0);
250                                         if (sd_ok)
251                                         {
252                                                 kprintf("Mount FAT filesystem.\n");
253                                                 result = f_mount(0, &fs);
254                                                 if (result != FR_OK)
255                                                 {
256                                                         kprintf("Mounting FAT volumes error[%d]\n", result);
257                                                         sd_ok = false;
258                                                         f_mount(0, NULL);
259                                                 }
260
261                                                 if (sd_ok)
262                                                 {
263                                                         result = fatfile_open(&in_file, file_name,  FA_OPEN_EXISTING | FA_READ);
264
265                                                         size_t count = 0;
266                                                         if (result == FR_OK)
267                                                         {
268                                                                 kprintf("Opened file '%s' size %ld\n", file_name, in_file.fat_file.fsize);
269
270                                                                 netconn_write(client, http_html_hdr_200, sizeof(http_html_hdr_200) - 1, NETCONN_NOCOPY);
271
272                                                                 while (count < in_file.fat_file.fsize)
273                                                                 {
274                                                                         int len = kfile_read(&in_file.fd, tx_buf, sizeof(tx_buf));
275                                                                         netconn_write(client, tx_buf, len, NETCONN_COPY);
276                                                                         count += len;
277                                                                 }
278
279                                                                 kfile_flush(&in_file.fd);
280                                                                 kfile_close(&in_file.fd);
281
282                                                                 kprintf("Sent: %d\n", count);
283                                                         }
284                                                         else
285                                                         {
286                                                                 kprintf("Unable to open file: '%s' error[%d]\n",  file_name, result);
287                                                                 netconn_write(client, http_html_hdr_404, sizeof(http_html_hdr_404) - 1, NETCONN_NOCOPY);
288                                                                 netconn_write(client, http_file_not_found, sizeof(http_file_not_found) - 1, NETCONN_NOCOPY);
289                                                         }
290                                                 }
291                                         }
292                                         f_mount(0, NULL);
293                                         kprintf("Umount FAT filesystem.\n");
294                                 }
295                                 else
296                                 {
297                                         netconn_write(client, http_html_hdr_404, sizeof(http_html_hdr_404) - 1, NETCONN_NOCOPY);
298                                         netconn_write(client, http_sd_not_present, sizeof(http_sd_not_present), NETCONN_NOCOPY);
299                                 }
300                         }
301                         netconn_close(client);
302                         netbuf_delete(rx_buf_conn);
303                 }
304                 netconn_delete(client);
305         }
306 }