/
Elzar.ino
127 lines (102 loc) · 2.74 KB
/
Elzar.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <SPI.h>
#include <Ethernet.h>
#include "Common.h"
// pin 9 on ethernet board is LED. it's also TX
int LedPin = 9;
// hard-coded ethernet stuff
byte MacAddress[] = { 0x90,0xA2,0xDA,0x0D,0x74,0x6E };
// Initialize the Ethernet server library on a port
EthernetServer HttpServer(80);
void InitLed()
{
// initialize the digital pin as an output.
pinMode(LedPin, OUTPUT);
// turn it off by default. seems to be on at first...
EnableLed(false);
}
void EnableLed(boolean Enable)
{
digitalWrite( LedPin, Enable ? HIGH : LOW );
}
void InitDebugSerial()
{
// the debug serial
Serial.begin(9600);
// wait for serial port to connect ("Needed for leonardo only")
while ( !Serial )
{
;
}
}
void InitHttpServer()
{
HOST_NAME = "Elzar";
// init the Ethernet lib
Ethernet.begin( MacAddress );
// start the server
HttpServer.begin();
// debug
String Debug;
Debug += "Http server at ";
Debug += IPToString( Ethernet.localIP() );
DebugPrint( Debug );
}
boolean OnHttpClient(EthernetClient& Client)
{
HttpRequest Request;
if ( !ReadHttp( Client, Request ) )
{
DebugPrint("Failed to read HTTP from client");
return false;
}
// looking for a file? don't think so (favicon.ico probably...)
if ( IsFileUrl( Request.mUrl ) )
{
SendHttp( Client, Request, 404, Request.mUrl + " not found." );
return false;
}
// show content
DebugPrint( String(" ** Print this; ") + Request.mUrl );
DebugPrint( Request.mContent );
DebugPrint( " ** Done ** ");
// generate response
int ResultCode = 200;
String ResultContent = "Thaaayyynnnkks.";
// send response
if ( !SendHttp( Client, Request, ResultCode, ResultContent ) )
return false;
// close client regardless. we don't have a need for a lot of bandwidth re-use :P
// gr: let connection-close in our response close the connection and wait for client to do so?
Client.stop();
return true;
}
// the setup routine runs once when you press reset:
void setup()
{
InitDebugSerial();
InitLed();
InitHttpServer();
}
// the loop routine runs over and over again forever:
void loop()
{
Sleep();
// listen for incoming clients
EthernetClient Client = HttpServer.available();
if (Client)
{
EnableLed(true);
OnHttpClient( Client );
// kick em off again
if ( Client.connected() )
{
Client.stop();
DebugPrint("kicked off client");
}
else
{
DebugPrint("Client disconnected");
}
EnableLed(false);
}
}