How do I pair an ESP32 and a HC-05 module? - arduino-uno

I have tried a lot of times, but any solution doesn't work.
I'm using an ESP32 as a Control and HC-05 as an anthena for an Arduino UNO.
I make that the HC-05 could read every String it recieves, but I'm not able to link the ESP32 (DevKit v1) with it. This is my code. I tried using address or name, but none of them works, only return "Failed to connect". But I can find it.
#include "BluetoothSerial.h"
BluetoothSerial SerialBT;
String MACadd = "00:19:08:35:31:63"; // HC-05 Address: 19:8:353163 (Given by the HC-05)
uint8_t address[6] = {0x00, 0x19, 0x08, 0x35, 0x31, 0x63};
String name = "AUTO"; // The name I put, I can find this by my mobile phone
char *pin = "1234"; //<- standard pin would be provided by default
bool connected;
void setup()
{
Serial.begin(115200);
SerialBT.begin("ESP32_Control", true);
SerialBT.setPin(pin);
Serial.println("The device started in master mode, make sure remote BT device is on!");
connected = SerialBT.connect(name);
if(connected)
Serial.println("Connected Succesfully!");
else
while(!SerialBT.connected(10000))
Serial.println("Failed to connect. Make sure remote device is available and in range, then restart app.");
if (SerialBT.disconnect()) // disconnect() may take upto 10 secs max
Serial.println("Disconnected Succesfully!");
SerialBT.connect(); // this would reconnect to the name(will use address, if resolved) or address used with connect(name/address).
}
void loop()
{
if (Serial.available())
SerialBT.write(Serial.read());
if (SerialBT.available())
Serial.write(SerialBT.read());
delay(20);
}

Related

TTGO ESP32 + GSM 800l - Read SMS - TinyGSM

on my code i can send an sms to my target number but i don't know how to read or receive sms from target number
the tinyGSM library doesn't have the read member function and i don't know how to use AT commands
void setup() {
// Set console baud rate
SerialMon.begin(115200);
// Keep power when running from battery
Wire.begin(I2C_SDA, I2C_SCL);
bool isOk = setPowerBoostKeepOn(1);
SerialMon.println(String("IP5306 KeepOn ") + (isOk ? "OK" : "FAIL"));
// Set modem reset, enable, power pins
pinMode(MODEM_PWKEY, OUTPUT);
pinMode(MODEM_RST, OUTPUT);
pinMode(MODEM_POWER_ON, OUTPUT);
digitalWrite(MODEM_PWKEY, LOW);
digitalWrite(MODEM_RST, HIGH);
digitalWrite(MODEM_POWER_ON, HIGH);
// Set GSM module baud rate and UART pins
SerialAT.begin(115200, SERIAL_8N1, MODEM_RX, MODEM_TX);
delay(3000);
// Restart SIM800 module, it takes quite some time
// To skip it, call init() instead of restart()
SerialMon.println("Initializing modem...");
modem.restart();
// use modem.init() if you don't need the complete restart
// Unlock your SIM card with a PIN if needed
if (strlen(simPIN) && modem.getSimStatus() != 3 ) {
modem.simUnlock(simPIN);
}
// To send an SMS, call modem.sendSMS(SMS_TARGET, smsMessage)
String smsMessage = "Hello from ESP32!";
/*if(modem.sendSMS(SMS_TARGET, smsMessage))
{
SerialMon.println(smsMessage);
}
else{
SerialMon.println("SMS failed to send");
}*/
SerialAT.println("AT"); //Once the handshake test is successful, it will back to OK
SerialAT.println("AT+CMGF=1"); // Configuring TEXT mode
SerialAT.println("AT+CNMI=1,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
}
void loop()
{
//readSMS(1);
//delay(1);
}

Why is this POST request from ESP32 to control KASA smart plug not working?

I am trying to communicate to a KASA HS103 smart plug using an HTTPS POST request sent via ESP32 (LoRa V2). For the actual POST content, I'm quite new to HTTP and have been following the instructions here: https://itnerd.space/2017/01/22/how-to-control-your-tp-link-hs100-smartplug-from-internet/
This is the POST request I am trying to send (with token & IDs modified):
URL: https://use1-wap.tplinkcloud.com/?token=fb2f7209-ATebDhHDOxB2wWc6wslPewO&appName=Kasa_Android&termID=1263f577-4387-4d3e-be79-705445d33bb08&appVer=1.4.4.607&ospf=Android+6.0.1&netType=wifi&locale=en_US
{
"method":"passthrough",
"params":{
"deviceId":"80068FEB5A735A5BB187B4EC309EF1BE1D6D8997",
"requestData":"{\"system\":{\"set_relay_state\":{\"state\":1}}}"
}
}
This will turn on the smart plug. I have verified that the POST request itself works, with both an online API tester (https://reqbin.com/) and through cURL on my MacBook.
I retrieved the URL token and device ID by authenticating with TP-Link server using my credentials through the API tester (also in the instructions linked above).
However, I am unable to control the smart plug when sending with ESP32. I am writing and compiling through the Arduino IDE, using the Heltec framework / libraries. Here is my code (started with the code from Rui Santos here and modified for my application):
/*
Rui Santos
Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-post-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
const char* ssid = "XXXXX";
const char* password = "XXXXX";
//Your Domain name with URL path or IP address with path
const char* serverName = "https://use1-wap.tplinkcloud.com/?token=fb2f7209-ATebDhHDOxB2wWc6wslPewO&appName=Kasa_Android&termID=1263f577-4387-4d3e-be79-705445d33bb08&appVer=1.4.4.607&ospf=Android+6.0.1&netType=wifi&locale=en_US HTTP/1.1";
const int port = 443;
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}
void loop() {
//Send an HTTP POST request every 10 minutes
if ((millis() - lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClientSecure *client = new WiFiClientSecure;
if (client) {
Serial.println("Client Created!");
//client -> setCACert(rootCACertificate);
{
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(*client, serverName);
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
//int httpResponseCode = http.POST("{\"api_key\":\"tPmAT5Ab3j7F9\",\"sensor\":\"BME280\",\"value1\":\"24.25\",\"value2\":\"49.54\",\"value3\":\"1005.14\"}");
int httpResponseCode = http.POST("{\"method\":\"passthrough\", \"params\": {\"deviceId\": \"80068FEB5A735A5BB187B4EC309EF1BE1D6D8997\", \"requestData\": \"{\"system\":{\"set_relay_state\":{\"state\":0}}}\" }}");
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.print("HTTP String: ");
Serial.println(payload);
// Free resources
http.end();
}
delete client;
} else {
Serial.println("Unable to create client");
}
} else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}
Here is the output from the serial terminal:
Connected to WiFi network with IP Address: 192.168.X.XXX
Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.
Client Created!
HTTP Response code: 200
HTTP String: {"error_code":-10100,"msg":"JSON format error"}
The smart plug does not turn off when uploading and running on ESP32.
Doing a quick search online for POST response codes, receiving 200 seems to mean the request was processed and OK, yet the error code is negative and message is "JSON format error".
Any ideas why this POST request is not working? Or anything I should try to get more info?
Thanks in advance!
Digging into "JSON format error" - turns out I had an extra "" around the 'requestData' value which parsed fine in cURL but could not be understood when sending raw through ESP32.
Removing those quotes fixed the problem and now I'm able to send POST requests successfully.
Here is the working code now:
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <Arduino_JSON.h>
const char* ssid = "XXXXX";
const char* password = "XXXXX";
//Your Domain name with URL path or IP address with path
const char* serverName = "https://use1-wap.tplinkcloud.com/?token=fb2f7209-ATebDhHDOxB2wWc6wslPewO&appName=Kasa_Android&termID=1163f577-4288-4d3d-be69-705445d33ba08&appVer=1.4.4.607&ospf=Android+6.0.1&netType=wifi&locale=en_US HTTP/1.1";
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}
void loop() {
//Send an HTTP POST request every 10 minutes
if ((millis() - lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClientSecure *client = new WiFiClientSecure;
if (client) {
{
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(*client, serverName);
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST("{\"method\":\"passthrough\",\"params\":{\"deviceId\":\"80068FEB3A733B5BB287B4EC309FE1BE1D7D8997\",\"requestData\":{\"system\":{\"set_relay_state\":{\"state\":1}}}}}");
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.print("HTTP String: ");
Serial.println(payload);
// Free resources
http.end();
}
delete client;
} else {
Serial.println("Unable to create client");
}
} else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}

Arduino(ESP8266) to laravel websocket channel subscription problem

i'm working on an IoT project which needs to connect to a laravel based socket server.
on laravel side all things are working just as should be but the problem is in arduino side which is a ESP8266 module being program by Arduino IDE.
i want to use Links2004/arduinoWebSockets library to connect to server.
it connects but i can't determine on which channel it should be.
is there any way on this library to tell the channel device should be on?
I gratefully appreciate any help :)
Arduino Test Code:
/*
Esp8266 Websockets Client
This sketch:
1. Connects to a WiFi network
2. Connects to a Websockets server
3. Sends the websockets server a message ("Hello Server")
4. Prints all incoming messages while the connection is open
Hardware:
For this sketch you only need an ESP8266 board.
Created 15/02/2019
By Gil Maimon
https://github.com/gilmaimon/ArduinoWebsockets
*/
#include <ArduinoWebsockets.h>
#include <ESP8266WiFi.h>
const char* ssid = "****"; //Enter SSID
const char* password = "******"; //Enter Password
const char* websockets_server_host = "xxx.xxx.xxx.xxx"; //Enter server adress -- serverip_or_name
const uint16_t websockets_server_port = 6001; // Enter server port
bool connected;
using namespace websockets;
WebsocketsClient client;
void setup() {
Serial.begin(115200);
// Connect to wifi
WiFi.begin(ssid, password);
// Wait some time to connect to wifi
for(int i = 0; i < 10 && WiFi.status() != WL_CONNECTED; i++) {
Serial.print(".");
delay(1000);
}
// Check if connected to wifi
if(WiFi.status() != WL_CONNECTED) {
Serial.println("No Wifi!");
return;
}
Serial.println("Connected to Wifi, Connecting to server.");
// try to connect to Websockets server
connected = client.connect(websockets_server_host, websockets_server_port, "/app/ab_key");
if(connected) {
Serial.println("Connecetd!");
client.send("Hello Server");
} else {
Serial.println("Not Connected!");
}
// run callback when messages are received
client.onMessage([&](WebsocketsMessage message) {
Serial.print("Got Message: ");
Serial.println(message.data());
});
}
void loop() {
if(connected) {
Serial.println("Connecetd!");
client.send("Hello Server");
} else {
connected = client.connect(websockets_server_host, websockets_server_port, "/app/ab_key");
Serial.println("try!");
}
// let the websockets client check for incoming messages
if(client.available()) {
client.poll();
}
delay(500);
}
terminal view of laravel websocket: laravel websocket

How to Wake ES8266 from deep sleep on Dev board NodeMCU

Basically, my project uses a force-sensing resistor to detect occupancy on the chair. The ESP8266 WiFi would wake from the sleep mode and send an update to the server. If there is no occupancy, the ESP8266 goes back to sleep.
My project uses Wiolink, a dev board that uses a ESP8266 WiFi chip. Hence, it is quite impossible to connect GPIO 16 to RST to wake up ( or reset ) the device.
Deep sleep is predefined at a set amount of time using this function ESP.deepsleep(). Is it possible to wake up with an external interrupt such as the force sensing resistor?
String apiKey = ""; // const char* ssid = ""; // wifi username const
char* password = ""; // wifi password
void setup() // Defines the initial condition of the hardware board.
{
Serial.begin(115200); delay(10);
}
void loop() // Defines the loop condition of the hardware board. {
sensorReading = analogRead(A0);
if(sensorReading >= 150) // Condition when someone is sitting;
{
//Wake ESP8266
//perform server update
}
if(sensorReading <=149) // Condition for no one sitting;
{
Serial.println("Going into deep sleep");
ESP.deepSleep(); //
}

How do I build a string from individual characters over BLE HC-08?

I am testing a BLE module (HC-08), which looks like a UART to the Arduino Uno.
This should be simple, but I have spent hours trying to build a string or char array from the response from commands sent over the software serial port.
first, here's the code:
#include <SoftwareSerial.h>
int data = 0;
SoftwareSerial Blue(10, 11); // RX, TX
void setup() {
Serial.begin(115200);
Blue.begin(9600);
Serial.println("BLE_Test started");
}
void loop() {
Blue.write("AT+VERSION?");
if (Blue.available()) {
data = Blue.read();
Serial.write(data);
}
delay(50);
}
And here's the output:
BLE_Test started
OK:SH-V1.251
OK:SH-V1.251
OK:SH-V1.251
OK:SH-V1.251
Each line ends with a CR-LF (13,10), so it looks fine on the screen.
So, here's my problem.
How can I build a string or char array out of the bytes coming from the BLE module? My goal is to make a function that simply sends a command string to the BLE module and return a string from the function. (Similar to Serial.readstring(), but SoftwareSerial has no readstring() property).
Like I said, it should be straightforward, but I am getting nowhere. Any tips would be appreciated.
it is readString with capital S and it is implemented in Stream which is a common base class for Serial implementations and SoftwareSerial and many other classes like LCD, EthernetClient, WiFiClient, ...
Doh!
That works, here's my working code:
//Send the command to the BLE module, returns with response in global inData
void getBlue(char* blueCmd) {
inData = "";
Blue.write(blueCmd);
delay(15);
while (Blue.available() > 0)
{
inData = Blue.readString();
}
}

Resources