-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservo.ino.tpl
108 lines (88 loc) · 2.67 KB
/
servo.ino.tpl
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
#include <stdio.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>
#include <Servo.h>
Servo servo;
#define HTTP_REST_PORT 80
#define WIFI_RETRY_DELAY 500
#define MAX_WIFI_INIT_RETRY 50
#define LED 16
#define DATA_PIN 2 // D4
#define NEUTRAL 0
#define PUSHED 60
#define PUSH_DELAY 500
const char* wifi_ssid = "YOUR SSID";
const char* wifi_passwd = "YOUR WIFI PASSWORD";
ESP8266WebServer http_rest_server(HTTP_REST_PORT);
int init_wifi() {
int retries = 0;
Serial.println("Connecting to WiFi AP..........");
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_passwd);
// check the status of WiFi connection to be WL_CONNECTED
while ((WiFi.status() != WL_CONNECTED) && (retries < MAX_WIFI_INIT_RETRY)) {
retries++;
delay(WIFI_RETRY_DELAY);
Serial.print("#");
}
return WiFi.status(); // return the WiFi connection status
}
void get_servo() {
StaticJsonBuffer<200> jsonBuffer;
JsonObject& jsonObj = jsonBuffer.createObject();
char JSONmessageBuffer[200];
//http_rest_server.send(204);
jsonObj["angle"] = servo.read();
jsonObj["attached"] = servo.attached();
jsonObj.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
http_rest_server.send(200, "application/json", JSONmessageBuffer);
}
void post_servo() {
StaticJsonBuffer<500> jsonBuffer;
String post_body = http_rest_server.arg("plain");
Serial.println(post_body);
JsonObject& jsonBody = jsonBuffer.parseObject(http_rest_server.arg("plain"));
Serial.print("HTTP Method: ");
Serial.println(http_rest_server.method());
if (!jsonBody.success()) {
Serial.println("error in parsin json body");
http_rest_server.send(400);
}
else {
http_rest_server.sendHeader("Location", "/servo/" + String(1));
http_rest_server.send(201);
servo.write(jsonBody["angle"]);
delay(jsonBody["duration"]);
servo.write(NEUTRAL);
}
}
void config_rest_server_routing() {
http_rest_server.on("/", HTTP_GET, []() {
http_rest_server.send(200, "text/html",
"Welcome to the ESP8266 REST Web Server");
});
http_rest_server.on("/servo", HTTP_GET, get_servo);
http_rest_server.on("/servo", HTTP_POST, post_servo);
}
void setup(void) {
servo.write(NEUTRAL);
servo.attach(DATA_PIN);
delay(2000);
Serial.begin(115200);
if (init_wifi() == WL_CONNECTED) {
Serial.print("Connected to ");
Serial.print(wifi_ssid);
Serial.print("--- IP: ");
Serial.println(WiFi.localIP());
}
else {
Serial.print("Error connecting to: ");
Serial.println(wifi_ssid);
}
config_rest_server_routing();
http_rest_server.begin();
Serial.println("HTTP REST Server Started");
}
void loop(void) {
http_rest_server.handleClient();
}