Arduino's serial communication with gsm board - geolocation

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!

Related

Blue ESP8266-12e tx light staying on

I have some code I have been putting on an ESP8266-12e board. Until recently it always worked fine. Now though when I finish uploading the code the blue light on the ESP8266-12e is staying on. I have tried it on two different board and the blue light stay on on both. I can't figure out what I changed in the code.
I have decided to put it up and have everyone look at it and let me know what I may be missing.
I hope someone can find something.
My code:
//NodeMCU 1.0 (ESP-12E Module constant connect)
#include <ESP8266WiFi.h>
#include <FS.h> //https://github.com/esp8266/Arduino
#include <EEPROM.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
//MQTT stuff
#define AIO_SERVER "go,here"
#define AIO_SERVERPORT SSSS // 8883 for MQTTS
#define AIO_USERNAME "FFFFFF"
#define AIO_KEY "XXXXXXXXXXXXXXXXXXXXXXX"
int tripper = 1;
#define MQTT_CONN_KEEPALIVE 18000000
#define LED3 16
//NEW AUTOCONNECT
const byte numChars = 32;
char receivedChars[numChars];
char Password[36]="";
char apiKey[16]="";
char apiKey2[32]="";
char channelKey[16];
char channelKey2[16];
String channelKey21= "&";
byte pinState = LOW;
char ssid[] = "";
char pass[] = "";
String Label = "";
String TOTAL = "";
uint32_t m=0;
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe trip2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/trip");
Adafruit_MQTT_Publish move1 = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/motion");
/*************************** Error Reporting *********************************/
Adafruit_MQTT_Subscribe errors = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/errors");
Adafruit_MQTT_Subscribe throttle = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/throttle");
//NEW AUTOCONNECT
int LED2 = 13;
int MOVEMENT = 5;
//send ssid/pass
String f;
//mqtt
char temperature[]="000";
String level;
String battery;
String trip;
String date;
int addr = 0;
//END NEW AUTOCONNECT
void MQTT_connect();
void setup() {
Serial.begin(115200);
pinMode(MOVEMENT,OUTPUT);
digitalWrite(MOVEMENT,LOW);
pinMode(D5,OUTPUT);
digitalWrite(D5,LOW);
pinMode(LED3,OUTPUT);
digitalWrite(LED3,LOW);
pinMode(LED2,INPUT);
Serial.println(F("Adafruit MQTT demo"));
//NEW AUTOCONNECT
WiFiManager wifiManager;
// put your setup code here, to run once:
WiFiManagerParameter customAPIKey("apiKey", "Time Zone #", apiKey, 16);
wifiManager.addParameter(&customAPIKey);
wifiManager.autoConnect("FloWT2");
Serial.println("Connected");
strcpy(apiKey,customAPIKey.getValue());
EEPROM.begin(512); //Initialize EEPROM
EEPROM.write(addr, 'A'); //Write character A
addr++; //Increment address
EEPROM.write(addr, 'B'); //Write character A
String www = apiKey;
Serial.print("www");
Serial.print (www);
for(int i=0;i<www.length();i++) //loop upto string lenght www.length() returns length of string
{
EEPROM.write(0x0F+i,www[i]); //Write one by one with starting address of 0x0F
}
EEPROM.commit();
delay (2000);
if (WiFi.status() == WL_DISCONNECTED) {
wifiManager.autoConnect("FloWT2");
delay(60000);}
if (WiFi.status() == WL_CONNECTED) { Serial.println("Connected");
delay(1000);
//get time zone
EEPROM.begin(512);
Serial.println(""); //Goto next line, as ESP sends some garbage when you reset it
Serial.print(char(EEPROM.read(addr))); //Read from address 0x00
addr++; //Increment address
Serial.print(char(EEPROM.read(addr))); //Read from address 0x01
addr++; //Increment address
Serial.println(char(EEPROM.read(addr))); //Read from address 0x02
//Read string from eeprom
String www;
//Here we dont know how many bytes to read it is better practice to use some terminating character
//Lets do it manually www.circuits4you.com total length is 20 characters
for(int i=0;i<16;i++)
{
www = www + char(EEPROM.read(0x0F+i)); //Read one by one with starting address of 0x0F
}
Serial.println("this");
Serial.print(www);
Serial.println("IP address: "); Serial.println(WiFi.localIP());
// Setup MQTT subscription for onoff feed
mqtt.subscribe(&trip2);
// Setup MQTT subscriptions for throttle & error messages
mqtt.subscribe(&throttle);
mqtt.subscribe(&errors);
WiFiClient client;
delay(2000);
Serial.printf("SSID: %s\n", WiFi.SSID().c_str());
Serial.printf("SSID: %s\n", WiFi.psk().c_str());
String ssidString = WiFi.SSID().c_str();
String pskString = WiFi.psk().c_str();
f = String('<')+String("Hi")+String(',')+String(ssidString)+String(',')+String(pskString)+String(',')+String(www)+String('>');
delay (1000);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
}
client.stop();
}
void loop() {
MQTT_connect();
uint32_t m=0;
Serial.print(F("\nSending motion val "));
Serial.print(m);
Serial.print("...");
if (! move1.publish(m)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
long state = digitalRead(LED2);
if(state == HIGH) {
m = 1;
Serial.print(F("\nSending motion val "));
Serial.print(m);
Serial.print("...");
digitalWrite(MOVEMENT,HIGH);
delay(1000);
digitalWrite(MOVEMENT,LOW);
if (! move1.publish(m)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
}
else{
}
// this is our 'wait for incoming subscription packets' busy subloop
// try to spend your time here
//12e
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(5000))) {
if (subscription == &trip2) {
Serial.print(F("Got onoff: "));
Serial.println((char *)trip2.lastread);
uint16_t sliderval = atoi((char *)trip2.lastread);
//THIS IS FOR LATCHING RELAY TURN ON D5 HIGH THEN OFF AFTER 1 SECOND
//NEXt TURN D6 HIGH THEN OFF AFTER A SECONDS
if((sliderval ==0)&&(tripper == 1)){
digitalWrite(D5,HIGH);
delay(1000);
digitalWrite(D5,LOW);
tripper = 2;
Serial.print(tripper);
Serial.print("tripped");
}
else if(sliderval == 50){
}
else if((sliderval == 100)&&(tripper == 2)){
digitalWrite(LED3,HIGH);
delay(1000);
digitalWrite(LED3,LOW);
tripper = 1;
Serial.print(tripper);
Serial.print("tripped2");
}
} else if(subscription == &errors) {
Serial.print(F("ERROR: "));
Serial.println((char *)errors.lastread);
} else if(subscription == &throttle) {
Serial.println((char *)throttle.lastread);
}
}
}
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}
I hope it is not toooo long.
Anyway I hope someone can find my problem. Everything works ok with the blue light on it is just know supposed to be that I can tell.
When I upload another code it doesn't stay on so it has to be in the code.
I will keep looking.
THANKS
So I got the blue light to go off. Instead of pinMode(D4,INPUT); and digitalWrite(D4,LOW); D4 is pin 16 which is the wake pin. So I had to define it thus #define LED3 16 and then pinMode(LED3,INPUT); and digitalWrite(LED3,LOW); I will change my original code to reflect these changes.

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?

MQTT subscription

Can someone help me with this code?
The goal is to trigger a Led when the value of the payload is > 1000.
It is a MQTT subscribtion code based on the esp8266mqtt PubSub client example. I will use it for a subscribyion of a topic from a CO2sensor
I've tried to modify a part of it but I think it has yo do something with the kind of datatype or a wrong condition?
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char *ssid = "xxx";
const char *password = "xxx";
const char *mqtt_server = "xxxx";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
int led = D4;
void setup_wifi()
{
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if value of C02 is above 1000
i = atoi (payload); //convert string to integer
if ( i > 1000) // comparison
{
digitalWrite(led, HIGH); // Turn the LED on
}
else
{
digitalWrite(led, LOW); // Turn the LED off
}
}
void reconnect()
{
// Loop until we're reconnected
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str()))
{
Serial.println("connected");
// Once connected, publish an announcement...
//client.publish("outTopic", "Test");
// ... and resubscribe
client.subscribe("my/sensors/co2");
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
pinMode(led, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop()
{
if (!client.connected())
{
reconnect();
}
client.loop();
}
Kind regards
Hi, This is what I publish:
void pubMessage() {
char message[16];
snprintf(message, sizeof(message), "%d", co2);
client.publish("my/sensors/co2", message);
delay(30000);
First you are casting the first byte of payload to a char.
Since it's just the first byte, it has a max value of 256.
Second you are comparing that 1 bytes value to the string '1000'
Without knowing exactly what you are publishing it is very hard to tell you how to fix it.
If you are publishing a string representing the number then you will need to parse it first with atoi() then do the comparison to the integer 1000 not the string.
If it is a byte value then you will need to read the correct value from the incoming byte array before doing the comparison.

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.

Getting Error code -1 (HTTP_CONNECTION_REFUSED) after first connection

I have a setup with two ESP8266 chips.
One is AP and listening for alarms from other ESP8266 in WiFi mode.
AP is an access point accepting get requests from "alarm" chips.
My problem is that when the first GET request has been handled (succesfully) by the AP, it is no longer possible to make more requests unless the AP chip is reset.
Connection to the AP WiFI goes fine apparently but the actual get request only works on the first attempt after reset, the next ones all return error code -1 to the client.
Code from the AP chip:
void setupAP()
{
WiFi.mode(WIFI_AP);
String AP_NameString = "KEEP SAFE " + deviceID;
char AP_NameChar[AP_NameString.length() + 1];
memset(AP_NameChar, 0, AP_NameString.length() + 1);
for (int i = 0; i < AP_NameString.length(); i++)
AP_NameChar[i] = AP_NameString.charAt(i);
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); // subnet FF FF FF 00
WiFi.softAP(AP_NameChar, WiFiAPPSK);
yield();
activeMenu = mainMenu;
server.on("/setup", handleWebRequest_Setup); //Associate the handler function to the path
server.on("/confirm", handleWebRequest_Confirm); //Associate the handler function to the path
server.on("/alarm", HTTP_GET, handleWebRequest_Alarm);
server.begin(); //Start the server
Serial.println("Server listening");
}
void handleWebRequest_Alarm(){
Serial.println("Client connected");
sensorAlarmPostback(server);
String s = "";
s += "<!DOCTYPE HTML>\r\n<html>\r\n";
s += "OK";
s += "</html>\n";
// Send the response to the client
Serial.println("Send OK to client");
server.send(200, "text/html", s);
Serial.println("OK Has been sent to the client");
}
void sensorAlarmPostback(ESP8266WebServer serv) {
Serial.println(String("Alaram recieved from : " + serv.arg("id")));
for (int i = 0; i < maxSensors; i++)
{
if (sensors[i].ID == serv.arg("id"))
sensors[i].alarm = true;
yield();
}
Serial.println("Sensor alarm flag has been set");
}
Code from the "sender" (alarm) chip:
void loop() {
initWifi();
publishAlarm();
WiFi.disconnect();
delay(30 * 1000); // Wait 30 seconds before next alarm
}
void initWifi() {
WiFi.disconnect();
WiFi.mode(WIFI_STA); // added in V 3.1a to disable AP_SSID publication in Client mode - default was WIFI_AP_STA
WiFi.begin(ssid.c_str(), password.c_str());
int retryCount = 0;
while (WiFi.status() != WL_CONNECTED && retryCount < 10) {
delay(2000);
retryCount++;
}
if (WiFi.status() != WL_CONNECTED)
Serial.println("WiFi ERROR");
else
Serial.println("WiFi Connected");
delay(500);
}
void publishAlarm(){
HTTPClient http;
String postStr = "?id=" + AlarmID;
postStr.replace("\r", "");
postStr.replace("\n", "");
Serial.println("String is");
Serial.println(postStr);
Serial.println("Connecting to Controller...");
String PostURL = "http://10.10.10.1/alarm" + postStr;
Serial.println("URL is: " + PostURL);
http.begin(PostURL);
int httpCode = http.GET();
if (httpCode > 0)
{
Serial.println("httpCode > 0");
yield();
delay(100);
http.end();
}
else
{
Serial.println("Error in upload " + String(httpCode));
yield();
delay(100);
http.end();
}
}
I realize that there is a lot of unneeded stuff in the code, but I have been trying almost everything. I just don't get it, and I have the same problem in other projects as well. The chips I use are Wemos D1 Minis and various NodeMCU dev. boards. Does not seem to be related to a specific board.
Update - SOLVED
I decided to wipe my entire development environment and re-install.
It wasn't that big of a deal.
And after a recompile and deployment to the chip (The AP Chip) it works as it alwas should have.
Oh well ....
Hope this helps someone if they end up in the same situation.
Now to cleaning up the code

Resources