Last active
July 15, 2018 04:03
-
-
Save syuchan1005/09773bcf92b777d21991b936175ed011 to your computer and use it in GitHub Desktop.
ESP8266を使用してHTTPリクエストでirsendする
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
ESP8266のIPのserverPortにリクエストを送信して下さい。 | |
(IPはSerialで出力しています) | |
リクエスト: | |
method: POST | |
URL: <ESP8266'sIP>:<serverPort> | |
Header: { | |
Content-Type: application/json | |
} | |
Body: "{ | |
"rawData": [irsendで送るデータ] | |
"frequency": 38000 // Optional, 38000がデフォルト | |
}" | |
下のssid, passwordを書き換えて使用してください. | |
*/ | |
#include <ESP8266WiFi.h> | |
#include <ESP8266mDNS.h> | |
#include <ArduinoOTA.h> | |
#include <ESP8266WebServer.h> | |
#include <aJSON.h> | |
#include <IRremoteESP8266.h> | |
#include <IRsend.h> | |
const char* ssid = "Your Wifi SSID Here!"; | |
const char* password = "Your Wifi Pass Here!"; | |
const int serverPort = 80; | |
const int lircSendPin = 5; | |
ESP8266WebServer server(serverPort); | |
IRsend irsend(lircSendPin); | |
struct IRSendData { | |
uint16_t *rawData; | |
int length; | |
int frequency; | |
}; | |
bool deserialize(IRSendData& data, char* json) { | |
aJsonObject* root = aJson.parse(json); | |
if (root == NULL) { | |
return false; | |
} else { | |
aJsonObject* rawData = aJson.getObjectItem(root, "rawData"); | |
data.length = aJson.getArraySize(rawData); | |
aJsonObject* freq = aJson.getObjectItem(root, "frequency"); | |
data.frequency = (freq != NULL) ? freq->valueint : 38000; | |
data.rawData = new uint16_t[data.length]; | |
for (int i = 0; i < data.length; i++) { | |
data.rawData[i] = uint16_t(aJson.getArrayItem(rawData, i)->valueint); | |
} | |
} | |
return true; | |
} | |
void setup() { | |
Serial.begin(115200); | |
WiFi.mode(WIFI_STA); | |
WiFi.begin(ssid, password); | |
if(WiFi.waitForConnectResult() != WL_CONNECTED) { | |
Serial.println("WiFi Connect Failed! Rebooting..."); | |
delay(1000); | |
ESP.restart(); | |
} | |
ArduinoOTA.begin(); | |
irsend.begin(); | |
server.on("/", HTTP_GET, [](){ | |
server.send(200, "text/plain", "Please Post Method"); | |
}); | |
server.on("/", HTTP_POST, [](){ | |
IRSendData data; | |
String body = server.arg("plain"); | |
int len = body.length() + 1; | |
char *str = new char[len]; | |
body.toCharArray(str, len); | |
if (!deserialize(data, str)) { | |
server.send(400, "text/plain", "Failed"); | |
} else { | |
irsend.sendRaw(data.rawData, data.length, data.frequency); | |
server.send(200, "text/plain", "OK"); | |
delete[] data.rawData; | |
} | |
delete[] str; | |
}); | |
server.begin(); | |
Serial.print("Browse: http://"); | |
Serial.println(WiFi.localIP()); | |
} | |
void loop() { | |
ArduinoOTA.handle(); | |
server.handleClient(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment