How to connect into Action Cable websocket from Arduino? - ruby-on-rails

I built an app in Python Flask which controls the LED light on an Arduino through broadcasting the color selected in a form to all members of the websocket channel. I am now rebuilding in Rails and trying to determine how my Arduino can specify which channel it would like to join. I've already begun a connection to the WebSocket and seem to be getting the following back from Rails: [WSc] Received text: {"type":"ping","message":1544679171}.
Now I just need to determine how I can send in a request to specifically stream from the ArduinoChannel, but I'm not sure how to go about it. I've tried adding parameters to my webSocket.begin, but that doesn't seem to have any affect.
Below is my Arduino code for reference:
#include <ESP8266WiFi.h>
#include <WebSocketsClient.h>
#include <ArduinoJson.h>
#include <EEPROM.h>
// Initialize pins
int redpin = D0;
int greenpin = D2;
int bluepin = D4;
//// Connecting to the internet
const char* ssid = "**************";
const char* password = "******";
// Setting up the websocket client
WebSocketsClient webSocket;
// Set up the WiFi client;
WiFiClient client;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(redpin, OUTPUT);
pinMode(bluepin, OUTPUT);
pinMode(greenpin, OUTPUT);
delay(10);
WiFi.begin(ssid, password);
while(WiFi.status()!= WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.print("IP Address: ");
Serial.print(WiFi.localIP() + "\n");
Serial.print(WiFi.macAddress() + "\n");
// Initializing the WS2812B communication
setRgb(255,80,90);
// Initializing the websocket connection
webSocket.begin("192.168.1.93",3000, "/cable" );
// webSocket.sendTXT('{"command":"subscribe","identifier":"{\"channel\":\"ArduinoChannel\"}"', 0);
webSocket.onEvent(webSocketEvent);
webSocket.setReconnectInterval(5);
}
void loop() {
// put your main code here, to run repeatedly:
webSocket.loop();
}
void webSocketEvent(WStype_t type, uint8_t *payload, size_t length) {
switch(type) {
Serial.write(type);
case WStype_DISCONNECTED:
Serial.printf("[WSc] Disconnected!\n");
break;
case WStype_CONNECTED:
Serial.printf("[WSc] Connected to url: %s\n", payload);
break;
case WStype_TEXT:
Serial.printf("[WSc] Received text: %s\n", payload);
DynamicJsonBuffer jBuffer;
JsonObject &root = jBuffer.parseObject(payload);
setRgb(root["r"],root["g"],root["b"]);
break;
}
}
void setRgb(uint8_t r, uint8_t g, uint8_t b) {
analogWrite(redpin, r);
analogWrite(bluepin, b);
analogWrite(greenpin, g);
delay(10);
}

TL;DR:
how I can send in a request to specifically stream from the ArduinoChannel
To receive streams from ArduinoChannel, you'll need to "subscribe" by sending through Websocket connection the following the String data from Arduino-client:
"{\"command\":\"subscribe\",\"identifier\":\"{\\\"channel\\\":\\\"ArduinoChannel\\\"}\"}"
... which is almost the same as your commented out sendTXT code, but that probably you were just incorrectly "escaping" the double quotes.
References:
I traced from the JS-client version of ActionCable here
App.cable.subscriptions.create('ArduinoChannel')
Subscriptions.prototype.create = function create(channelName, mixin) {
var channel = channelName;
var params = (typeof channel === "undefined" ? "undefined" : _typeof(channel)) === "object" ? channel : {
channel: channel
};
// params = { channel: "ArduinoChannel" }
var subscription = new Subscription(this.consumer, params, mixin);
return this.add(subscription);
};
function Subscription(consumer) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var mixin = arguments[2];
classCallCheck(this, Subscription);
this.consumer = consumer;
this.identifier = JSON.stringify(params);
extend(this, mixin);
}
Subscriptions.prototype.add = function add(subscription) {
this.subscriptions.push(subscription);
this.consumer.ensureActiveConnection();
this.notify(subscription, "initialized");
this.sendCommand(subscription, "subscribe");
return subscription;
};
Subscriptions.prototype.sendCommand = function sendCommand(subscription, command) {
var identifier = subscription.identifier;
// command = "subscribe"; identifier = JSON.stringify(params) = '{"channel":"ArduinoChannel"}';
return this.consumer.send({
command: command,
identifier: identifier
});
};
Consumer.prototype.send = function send(data) {
// data = { command: 'subscribe', identifier: '{"channel":"ArduinoChannel"}' }
return this.connection.send(data);
};
Connection.prototype.send = function send(data) {
if (this.isOpen()) {
// JSON.stringify(data) = '{"command":"subscribe","identifier":"{\"channel\":\"ArduinoChannel\"}"}'
this.webSocket.send(JSON.stringify(data));
return true;
} else {
return false;
}
};

Related

ESP8266 WeMos D1 using deepsleep drains too much battery

I've developed a fingerprint sensor using NodeMCU D1 mini powered by a 1000mah battery.
Everything seems working correctly except for battery energy consumption.
I have read several topic where user says that using deepsleep fuction on NodeMCU 1000mah battery should last more than 3 month but mine doesn't reach 2 days.
This is my circuit schematic
I also report here my code snipped that I'm currently using. The circuit should wake up from deepsleep when the button is pressed and start reading the fingerprint sensor. If it detect a valid fingerprint, a message is sent to MQTT broker.
#include <Adafruit_Fingerprint.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* _ssid = "ZZZXXXYYY";
const char* _password = "pass";
const char* mqttServer = "IPADDRESS";
const int mqttPort = 1883;
const char* mqttUser = "USER";
const char* mqttPassword = "PASS";
long initialMillis = 0;
unsigned int raw=0;
// On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
// uncomment this line:
//#define mySerial Serial
// For UNO and others without hardware serial, we must use software serial...
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino (WHITE wire)
// comment these two lines if using hardware serial
SoftwareSerial mySerial(4, 5);
WiFiClient espClient;
PubSubClient client(espClient);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
void setup()
{
Serial.begin(9600);
pinMode(A0, INPUT);
// Connect to Fingerprint. Set the data rate for the sensor serial port
finger.begin(57600);
delay(5);
if (finger.verifyPassword()) {
Serial.println("Found fingerprint sensor!");
} else {
Serial.println("Did not find fingerprint sensor :(");
ESP.deepSleep(10 * 1000000);
}
finger.getTemplateCount();
// Connect to WIFI
WiFi.mode(WIFI_STA);
WiFi.begin(_ssid, _password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Connect to MQTT
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESPFingerprint", mqttUser, mqttPassword )) {
Serial.println("Connected to MQTT server");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// Calculate battery percentage
raw = analogRead(A0);
String bLevel = "{\"Battery\":" + String(raw) + "}";
Serial.print("Battery: ");
Serial.print(raw);
Serial.print(" -> ");
Serial.println(bLevel);
initialMillis = millis();
client.publish("tele/fingerprint/LWT", "Online");
client.publish("tele/fingerprint/STATE", (char*)bLevel.c_str(), true);
Serial.print("MQTT subscribed: ");
Serial.println(WiFi.localIP());
}
void loop()
{
unsigned long currentMillis = millis();
int fid = getFingerprintIDez();
if(fid != -1) {
String fpIdstr = String(fid);
client.publish("cmnd/fingerprint/RESULT", (char*)fpIdstr.c_str());
Serial.println("Fingerprint correct. Going to sleep.");
client.publish("tele/fingerprint/LWT", "Offline");
// trigger disconnection from MQTT broker to correctly send the message before going to sleep
client.disconnect();
espClient.flush();
// wait until connection is closed completely
while(client.state() != -1){
delay(10);
}
ESP.deepSleep(0);
}
else if(currentMillis - initialMillis >= 15000){
Serial.println("Timeout expired. Going to sleep.");
client.publish("tele/fingerprint/LWT", "Offline");
ESP.deepSleep(0);
}
delay(50); //don't ned to run this at full speed.
}
uint8_t getFingerprintID() {
uint8_t p = finger.getImage();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image taken");
break;
case FINGERPRINT_NOFINGER:
Serial.println("No finger detected");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_IMAGEFAIL:
Serial.println("Imaging error");
return p;
default:
Serial.println("Unknown error");
return p;
}
// OK success!
p = finger.image2Tz();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image converted");
break;
case FINGERPRINT_IMAGEMESS:
Serial.println("Image too messy");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_FEATUREFAIL:
Serial.println("Could not find fingerprint features");
return p;
case FINGERPRINT_INVALIDIMAGE:
Serial.println("Could not find fingerprint features");
return p;
default:
Serial.println("Unknown error");
return p;
}
// OK converted!
p = finger.fingerFastSearch();
if (p == FINGERPRINT_OK) {
Serial.println("Found a print match!");
} else if (p == FINGERPRINT_PACKETRECIEVEERR) {
Serial.println("Communication error");
return p;
} else if (p == FINGERPRINT_NOTFOUND) {
Serial.println("Did not find a match");
return p;
} else {
Serial.println("Unknown error");
return p;
}
// found a match!
Serial.print("Found ID #"); Serial.print(finger.fingerID);
Serial.print(" with confidence of "); Serial.println(finger.confidence);
return finger.fingerID;
}
// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
uint8_t p = finger.getImage();
if (p != FINGERPRINT_OK) return -1;
p = finger.image2Tz();
if (p != FINGERPRINT_OK) return -1;
p = finger.fingerFastSearch();
if (p != FINGERPRINT_OK) return -1;
// found a match!
Serial.print("Found ID #"); Serial.print(finger.fingerID);
Serial.print(" with confidence of "); Serial.println(finger.confidence);
return finger.fingerID;
}
Can somebody let me know if there is something wrong in my code or circuit?

How to turn on LED that's attached to an arduino via BLE from ios app?

Here is the scenario. I have an esp32, 2 led's and a ios example app I found online here. Currently If I press a button on my esp32 it notifies the ios app to display "1", if pressed again it displays "0". This works perfectly.
The tricky part is that this ios app allows me to send a write command to the esp32. I'd like to make it so if '1' is sent LED A turns ON and LED B turns OFF, then LED A OFF and LED B ON when 0 is sent. I am unable to do this though. Try as I might I can't figure out where in the chain of this project something is wrong. Maybe the code on the esp32 or maybe the app i'm unsure.
Here is my arduino code. (There is more to the code not mentioned, I actually have 4 led's but I only want to turn on 2 certain ones when a write command is sent).
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
boolean oldState = LOW;
uint32_t value = 0;
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
class MyCallbacks: public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
std::string rxValue = pCharacteristic->getValue();
if (rxValue.length() > 0) {
Serial.print("Received Value: ");
for (int i = 0; i < rxValue.length(); i++) {
Serial.print(rxValue[i]);
}
Serial.println();
if (rxValue.find("1") != -1) {
digitalWrite(13, HIGH);
digitalWrite(27, LOW);
}
else if (rxValue.find("0") != -1) {
digitalWrite(13, LOW);
digitalWrite(27, HIGH);
}
}
}
};
const int bt1 = 14;
boolean bt1g = true;
int bt1t = 0;
void setup() {
pinMode(13, OUTPUT);
pinMode(15, OUTPUT);
pinMode(33, OUTPUT);
pinMode(27, OUTPUT);
pinMode(bt1, INPUT_PULLUP);
Serial.begin(9600);
BLEDevice::init("ESP32");
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
BLEService *pService = pServer->createService(SERVICE_UUID);
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY
);
pCharacteristic->addDescriptor(new BLE2902());
pService->start();
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(false);
pAdvertising->setMinPreferred(0x0);
BLEDevice::startAdvertising();
Serial.println("Waiting a client connection to notify...");
}
void loop()
{
if (bt1g) {
if (digitalRead(bt1) == LOW ) {
bt1t = (bt1t + 1) % 2;
Serial.println(bt1t);
bt1g = false;
}
}
if (!bt1g) {
if (digitalRead(bt1) == HIGH) {
bt1g = true;
}
}
if (bt1t == 0) {
digitalWrite(15, LOW);
digitalWrite(33, HIGH);
}
}
boolean newState = digitalRead(15);
if (deviceConnected) {
if (newState != oldState) {
if (newState == LOW) {
pCharacteristic->setValue("1");
}
else {
pCharacteristic->setValue("0");
}
pCharacteristic->notify();
};
oldState = newState;
}
delay(50);
}
It looks like the entire code for the ios app is too long to submit to this post so here is the github
I'm really unsure and stuck in a rut. Any help is appreciated!
Could it be you are not discovering the correct characteristics? It looks like you only have one service and one characteristic.

Arduino's serial communication with gsm board

I am trying to write a program where arduino receives text from the gsm module.But my program is able to read the first text and perform a duty,but i want it to receive multiple texts and perform individual tasks for each respective texts?Any help will be great.Thank You.
#include <SoftwareSerial.h>
SoftwareSerial gsm(2, 3);
String inString[64]; // string to hold input coming from device
String read;
int count = 0;
boolean verifyingDone = false; // flags to determine the action completed and to perform next action
boolean regist = false;
boolean registercomplete = false;
boolean location = false;
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
gsm.begin(4800);
delay(100);
gsm.print("ate0\r"); // removes the echo from the device
delay(100);
gsm.print("at+cnmi=1,2,0,0,0\r"); // to receive a text
Serial.print("The Device has been Intiated");
}
void loop() {
if (gsm.available())
{
while (gsm.available())
{
read = gsm.readString();
verifyNum(); // verifying the number
/* verifyingDone=true;
if(verifyingDone){
delay(1000);
gsm.print("at+cgpsinfo\r");
delay(1000);
checkGps();
verifyingDone=false;
*/
reading1: inString[count++] = read;
Serial.print(String(read));
if (count == 64) {
break;
}
}
delay(200);
count = 0;
}
}
void clearBufferArray()
{
for (int i = 0; i < count; i++)
{
inString[i] = "";
}
}
void verifyNum() {
if (read.startsWith("\r\n+CMT: ")) { // checking the incoming text and verifying the pre-defined number
int index1 = read.indexOf('"');
int index2 = read.indexOf('"', index1 + 1);
String Number = read.substring(index1 + 2, index2);
char floatbuf[100]; // make this at least big enough for the whole string
Number.toCharArray(floatbuf, 100);
int number = atoi(floatbuf);
//Serial.println(number);
delay(1000);
if (strcmp(number, 24190) == 0)
{
Serial.println("The Sending number is " + Number);
Serial.println("This is the registered number");
regist = true;
if (regist) {
gsm.print("AT+CMGS=\"0434519166\"\r"); // Sending registeration confirmation via sms
delay(100);
gsm.print("Success this mobile number has been registered .\r");
gsm.print("\r");
delay(100);
gsm.println((char)26);
delay(10000);
registercomplete = true;
if (regist == true && registercomplete == true) { //after complete registeration ,checking the gps and sending the co-ordinates
checkGps();
delay(500);
}
}
else {
gsm.print("AT+CMGSO=\"0434519166\" \,\"Someone tried to access your device\"\r"); // When not a registered number
}
}
}
}
void checkGps()
{
Serial.print("Gps Search has started");
delay(10000);//big delay to complete previous process //Not able to do this process completely------>Coz not able to re-read the string obtained from the first read..have to find an alternate to read incoming signals efficiently and re-using it
clearBufferArray();
delay(1000);
gsm.write("at+cgpsinfo\r");
delay(10000);
Serial.println();
Serial.println();
Serial.print("Locating.....Wait for a moment");
/*int spacePosition = read.indexOf(':');
if (read.charAt(spacePosition + 1) == ',' && regist==true )*/
if (read.startsWith("\r\n+CGPINFO:,,,"))
{
Serial.println("GPS signal not found.Go outside"); //
gsm.print("AT+CMGS=\"0434519166\"\r"); // Sending location as sms
delay(100);
gsm.print("GPS signal not found.Go outside ");
gsm.print("\r");
delay(100);
gsm.println((char)26);
delay(1000);
regist = false;
}
else
{
Serial.println("Signal found");
gsm.print("AT+CMGS=\"0434519166\"\r"); //Confirming signal found and sending location----->location finding programs can be obtained from previouses sketches
delay(100);
gsm.print("GPS found.Location will be sent soon ");
gsm.print("\r");
delay(100);
gsm.println((char)26);
delay(1000);
}
}
Thank You,Above code is justa tryout ,any help is welcome!

The ESP8266 is not connecting to MQTT broker hivemq

I have a simple code in which I am trying to connect to HiveMQ open broker and subscribe to a topic to listen to incoming messages.
here is the code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char *ssid = "P9Inct"; // cannot be longer than 32 characters!
const char *pass = "P9inct123*"; //
const char *mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char *mqtt_user = "testUser";
const char *mqtt_pass = "abc123";
const char *mqtt_client_name = "12312312332212";
#define BUFFER_SIZE 100
String incoming="";
String did="";
String state="";
// Update these with values suitable for your network.
//IPAddress server(172, 16, 0, 2);
String DEVID="8581870006";//"6931108641";//old
WiFiClient wclient;
PubSubClient client(wclient, mqtt_server,mqtt_port);
void callback(const MQTT::Publish& pub) {
// handle message arrived
Serial.print(pub.topic());
Serial.print(" => ");
if (pub.has_stream()) {
uint8_t buf[BUFFER_SIZE];
int read;
while (read = pub.payload_stream()->read(buf, BUFFER_SIZE)) {
Serial.write(buf, read);
}
pub.payload_stream()->stop();
Serial.println("");
} else
Serial.println(pub.payload_string());
////////////////////////////////////////////
incoming=String(pub.payload_string());
Serial.println(pub.payload_string());
Serial.println(incoming);
}
void setup() {
// Setup console
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println();
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println("...");
WiFi.begin(ssid, pass);
if (WiFi.waitForConnectResult() != WL_CONNECTED)
return;
Serial.println("WiFi connected");
}
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
Serial.println("Connecting to MQTT server");
if (client.connect(MQTT::Connect(mqtt_client_name)
.set_auth(mqtt_user, mqtt_pass))) {
Serial.println("Connected to MQTT server");
client.set_callback(callback);
client.subscribe("diy/1"+DEVID);
} else {
Serial.println("Could not connect to MQTT server");
}
}
if (client.connected())
client.loop();
}
}
WiFi connection is working fine but, communication via broker is not working and it always gives the message "Could not connect to MQTT server". How to make esp8266 work with HiveMQ broker. The dashboard of borker is
http://www.mqtt-dashboard.com/
So, you are connected. You have unnecessary print line in your loop. Try to adapt on this :
/* Incoming data callback. */
void callback(char* topic, byte* payload, unsigned int length)
{
char payloadStr[length + 1];
memset(payloadStr, 0, length + 1);
strncpy(payloadStr, (char*)payload, length);
Serial.printf("Topic : [%s]\n", topic);
Serial.printf("Payload : %s\n", payloadStr);
}
void performConnect()
{
uint16_t connectionDelay = 5000;
while (!client.connected())
{
if (client.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_KEY))
{
Serial.printf("Connected to Broker.\n");
client.subscribe("diy/1"+DEVID);
}
else
{
Serial.printf("MQTT Connect failed, rc = %d\n", client.state());
Serial.printf("Trying again in %d msec.\n", connectionDelay);
delay(connectionDelay);
}
}
}
void loop()
{
if (!client.connected())
{
performConnect();
}
client.loop();
}

Android to Arduino Uno + Wi-Fi shield string communication

I am trying to make a wireless light control device (on/off/dimming) using an Arduino, an Android app, and a router.
I am setting the Arduino to a static IP 192.168.1.2 using the router. I am sending strings ("1"-off, "2"-decrease brightness, "3"-increase brightness, "4"-on) from the Android app to the IP address 192.168.1.2. I have connected the Arduino to the Internet using the Arduino Wi-Fi shield and set up the WifiServer using the following code:
char ssid[] = "NAME"; // Your network SSID (name)
char pass[] = "PASS"; // Your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // Your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(23);
boolean alreadyConnected = false; // Whether or not the client was connected previously.
void setup() {
// Start serial port:
Serial.begin(9600);
// Attempt to connect to Wi-Fi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
// Wait 10 seconds for connection:
delay(10000);
}
// Start the server:
server.begin();
// You're connected now, so print out the status:
printWifiStatus();
}
The main problem I am having is how to accept and print out the strings from the Android device. The current code I have to do this is:
// Listen for incoming clients
WiFiClient client = server.available();
if (client) {
// An HTTP request ends with a blank line
boolean newLine = true;
String line = "";
while (client.connected() && client.available()) {
char c = client.read();
Serial.print(c);
// If you've gotten to the end of the line (received a newline
// character) and the line is blank, the HTTP request has ended,
// so you can send a reply.
if (c == '\n' && newLine) {
// Send a standard HTTP response header
//client.println("HTTP/1.1 200 OK");
//client.println("Content-Type: text/html");
//client.println();
}
if (c == '\n') {
// You're starting a new line
newLine = true;
Serial.println(line);
line = "";
}
else if (c != '\r') {
// You've gotten a character on the current line
newLine = false;
line += c;
}
}
Serial.println(line);
// Give the web browser time to receive the data
delay(1);
// Close the connection:
//client.stop();
}
}
I am basing this code off of the blog post Android Arduino Switch with a TinyWebDB hack, but this code is for an Ethernet shield. The Android app was made using the MIT App Inventor, which is similar to the one found the blog post.
TLDR, how can I get the strings using the Arduino Wi-Fi shield?
You can read the characters into a full string instead of reading each individual character into the serial monitor as in your example above.
In your example, this bit of code would read each character from the client TCP session and print it to the serial monitor, thus displaying the HTTP requests in the serial console.
char c = client.read();
Serial.print(c);
Try something like this instead. Declare a string named "readString" before your setup() function in the Arduino sketch like this:
String readString;
void setup() {
//setup code
}
void loop() {
// Try this when you're reading inside the while client.connected loop instead of the above:
if (readString.length() < 100) {
readString += c;
Serial.print(c);
}
Here is a working example of the loop():
void loop() {
// Listen for incoming clients
WiFiClient client = server.available();
if (client) {
Serial.println("new client");
// An HTTP request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
//Serial.write(c);
// If you've gotten to the end of the line (received a newline
// character) and the line is blank, the HTTP request has ended,
// so you can send a reply.
if (readString.length() < 100) {
readString += c;
Serial.print(c);
}
if (c == '\n' && currentLineIsBlank) {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connnection: close");
client.println();
client.println("<!DOCTYPE HTML>");
//send the HTML stuff
client.println("<html><head><title>Admin Web</title><style type=\"text/css\">");
client.println("body { font-family: sans-serif }");
client.println("h1 { font-size: 14pt; }");
client.println("p { font-size: 10pt; }");
client.println("a { color: #2020FF; }");
client.println("</style>");
client.println("</head><body text=\"#A0A0A0\" bgcolor=\"#080808\">");
client.println("<h1>Arduino Control Panel</h1><br/>");
client.println("<form method=\"link\" action=\"/unlockdoor\"><input type=\"submit\" value=\"Unlock Door!\"></form>");
client.println("<br/>");
client.println("</body></html>");
break;
}
if (c == '\n') {
// You're starting a new line.
currentLineIsBlank = true;
}
else if (c != '\r') {
// You've gotten a character on the current line.
currentLineIsBlank = false;
}
}
}
// Give the web browser time to receive the data.
delay(1);
// Close the connection:
client.stop();
Serial.println("client disonnected");
if (readString.indexOf("/unlockdoor") > 0)
{
unlockdoor();
Serial.println("Unlocked the door!");
}
readString = "";
}

Resources