Message is not publishing to ESP8266 from IBM Bluemix - arduino

I have programmed to my ESP8266 and subscribed one topic to keep listening messages. This is my graphical view of injecting message to IBM Iot node.
This is my settings of inject view
This is my settings of IBM Iot node.
Here are my logs at Serial Monitor, it is connected and subscribed to cmd channel
So far so good, When I am trying to inject a message to my IBM Iot node then it is not publishing a message, as it is not reaching on serial monitor and no log on debug view. here you can see
Here is source code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/releases/tag/v2.3
const char* ssid = "shiv";
const char* password = "manmohan#12345";
#define ORG "2kafk4"
#define DEVICE_TYPE "ESP8266"
#define DEVICE_ID "5CCF7FEED6F0"
#define TOKEN "opKF7v3#8jRM*mGkb_"
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char topic[] = "iot-2/cmd/test/fmt/String";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int payloadLength) {
Serial.print("callback invoked for topic: "); Serial.println(topic);
for (int i = 0; i < payloadLength; i++) {
Serial.print((char)payload[i]);
}
}
PubSubClient client(server, 1883, callback, wifiClient);
void setup() {
Serial.begin(115200);
Serial.println();
wifiConnect();
mqttConnect();
}
void loop() {
if (!client.loop()) {
mqttConnect();
}
}
void wifiConnect() {
Serial.print("Connecting to "); Serial.print(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("nWiFi connected, IP address: "); Serial.println(WiFi.localIP());
}
void mqttConnect() {
if (!client.connected()) {
Serial.print("Reconnecting MQTT client to "); Serial.println(server);
while (!client.connect(clientId, authMethod, token)) {
Serial.print(".");
delay(500);
}
initManagedDevice();
Serial.println();
}
}
void initManagedDevice() {
if (client.subscribe(topic)) {
Serial.println("subscribe to cmd OK");
} else {
Serial.println("subscribe to cmd FAILED");
}
}
I tried to check cloud foundry logs using cf command, here it is https://pastebin.com/dfMaS1Gd
Can anyone hint me what I am doing wrong ? Thanks in advance.

Confirm the device type is correctly specified in your node configuration. Currently the screenshot show 0.16.2 which doesn't seem to match the device type you registered and what is specified in your code.

Related

Why ESP8266 module can connect to my iPhone Hotspot but cannot connection to my home wifi?

Here is the code for scanning WiFi network and connecting to the WiFi.
#include<ESP8266WiFi.h>
#include<Arduino.h>
#define USER_SERIAL Serial
const char* ssid = "*****";
const char* pass = "*****";
void setup() {
USER_SERIAL.begin(115200);
searchWifi();
WiFi.mode(WIFI_STA);
WiFi.hostname("ESP-host");
WiFi.setPhyMode(WIFI_PHY_MODE_11G);
WiFi.enableInsecureWEP(true);
WiFi.begin(ssid,pass);
while(WiFi.status() != WL_CONNECTED){
USER_SERIAL.print(".");
delay(1000);
}
USER_SERIAL.print("");
USER_SERIAL.println("WiFi connected");
USER_SERIAL.print("IP Address: ");
USER_SERIAL.println(WiFi.localIP());
WiFi.setAutoReconnect(true);
WiFi.persistent(true);
}
void loop() {
// put your main code here, to run repeatedly:
}
void searchWifi(){
int numberOfNetwork = WiFi.scanNetworks();
USER_SERIAL.println("-----");
for ( int i = 0; i< numberOfNetwork;i++){
USER_SERIAL.print("Network name: ");
USER_SERIAL.println(WiFi.SSID(i));
USER_SERIAL.print("Signal Strength: ");
USER_SERIAL.println(WiFi.RSSI(i));
USER_SERIAL.println("-------------");
}
}
My WiFi is in 11bgn mixed mode, so it means that my connection allow all device to be connected. Moreover, my WiFi router is also have 2,4gHz frequency which is the requirement for ESP8266 to allow connection.

Connect to a public server using pubsubclient

I am using PubSubClient library to subscribe to a server using a nodemcu. I tested the code using cloudMQTT and MQTTlens and it worked fine. In addition to that, I used MQTTlens to check mqtt connection with my pc. In there, I did not specify username and password (I kept blank) and it worked just fine. When I want to connect for a public server (ex: "tcp://11.111.111.111"), does not connect.
code for nodemcu
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "*****";
const char* password = "****";
const char* mqttServer = "****";
const int mqttPort = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP8266Client")) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.publish("topic1", "Hello from ESP8266_tester1");
client.subscribe("topic1");
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void loop() {
client.loop();
}
the result from the serial monitor
Any suggestion is welcome
If you genuinely don't require a username and password then don't use the connect function that expects them:
...
if (client.connect("ESP8266Client")) {
...
I see you are using a fairly generic client id - ESP8266Client. Remember that all clients connecting to a broker must have a unique client id. If you depoyed this sketch to two different devices they would not both be able to connect at the same time.
The problem was with the ip I have provided. IP does not require "tcp://" part. After removing that, the code worked well.

ESP8266 Using wifimanager with onSoftAPModeProbeRequestReceived

I would like to use https://github.com/tzapu/WiFiManager in conjunction with onSoftAPModeProbeRequestReceived. The end goal is to config the wifi with WifiMaager then "switch over" and send probe request information via the wifi.
I get this to work without wifi manager using the following
#include <ESP8266httpUpdate.h>
#include <ESP8266WiFi.h>
#include <esp8266httpclient.h>
#include <stdio.h>
const char* ssid = "someap"; // The SSID (name) of the Wi-Fi
network you want to connect to
const char* password = ""; // The password of the Wi-Fi network
int status = WL_IDLE_STATUS;
String macAddr = "";
WiFiEventHandler probeRequestPrintHandler;
WiFiEventHandler probeRequestBlinkHandler;
bool blinkFlag;
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
Serial.print("Starting");
WiFi.persistent(false);
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, password);
probeRequestPrintHandler =
WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestPrint);
probeRequestBlinkHandler =
WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestBlink);
while ( status != 3)
{
Serial.print("Attempting to connect to network, SSID: ");
Serial.println(ssid);
status = WiFi.status();
WiFi.begin(ssid, password);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(WiFi.localIP());
}
void onProbeRequestPrint(const WiFiEventSoftAPModeProbeRequestReceived& evt)
{
if (macAddr != macToString(evt.mac))
{
macAddr = macToString(evt.mac);
Serial.print("Probe request from: ");
Serial.print(macToString(evt.mac));
Serial.print(" RSSI: ");
Serial.println(evt.rssi);
}
}
void onProbeRequestBlink(const WiFiEventSoftAPModeProbeRequestReceived&) {
blinkFlag = true;
}
void loop() {
if (blinkFlag) {
HTTPClient http; //Declare an object of class HTTPClient
http.begin("http://requestbin.fullcontact.com/110f1ss6a1?test=true");
//Specify request destination
int httpCode = http.GET();
Serial.println(httpCode);
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println(payload); //Print the response payload
}
http.end(); //Close connection
macAddr="";
blinkFlag = false;
digitalWrite(LED_BUILTIN, LOW);
delay(100);
digitalWrite(LED_BUILTIN, HIGH);
status = 0;
}
delay(1000);
}
String macToString(const unsigned char* mac) {
char buf[20];
snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return String(buf);
}
When the connection is established we rely on WiFiEventHandler probeRequestPrintHandler; and WiFiEventHandler probeRequestBlinkHandler; This does work and does collect the mac address, how ever it can not connect to the AP. Do I need to close the current wifi mode open the connection then close it?
Seems all I needed to do is add WiFi.begin(); before void loop()

Feather Huzzah MQTT

I'm attempting to connect my Feather Huzzah to a local MQTT server but the program keeps blowing up and throwing a stack trace. When I attempt to decode the stack trace it's just empty, more frequently I only get part of the stack trace. Here's the code that I'm running, most of it is pretty similar to the pub/sub client example code for Arduino. I've tried erasing the flash on the device, that didn't seem to help.
Even stranger is that it worked once, but as soon as I tried it again adding the callback the code stopped working and blows up. If I try removing the callback nothing changes. I've tried stripping out a lot of the code just to see if I can get a consistent connection to MQTT, but that doesn't seem to be working either. The MQTT server is the latest Mosquitto from Ubuntu 18.04.
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>
const char* ssid = "xxxxxxxx";
const char* password = "xxxxxxxxx";
const int hallPin = 14;
const int ledPin = 0;
const char* mqtt_server = "mosquitto.localdomain";
long lastMsg = 0;
char msg[100];
int value = 0;
int hallState = 0;
WiFiClient espClient;
PubSubClient client(espClient);
WiFiUDP ntpUDP;
// By default 'time.nist.gov' is used with 60 seconds update interval and
// no offset
NTPClient timeClient(ntpUDP);
// Setup and connect to the wifi
void setup_wifi() {
delay(100);
Serial.print("Connecting to: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Wifi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Gateway: ");
Serial.println(WiFi.gatewayIP());
}
//Reconnect to the MQTT broker
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("/homeassistant/devices/doorbell", "hello world");
// ... and resubscribe
client.subscribe("/homeassistant/doorbell/receiver");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
//Process messages incoming from the broker
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]);
}
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(hallPin, INPUT);
Serial.begin(115200);
setup_wifi();
timeClient.begin();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
setup_wifi();
}
if (!client.connected()) {
reconnect();
}
hallState = digitalRead(hallPin);
if (hallState == LOW) {
digitalWrite(ledPin, HIGH);
generateAndSendMessage();
delay(1000); //Add in a delay so it doesn't send messages extremely rapidly
} else {
digitalWrite(ledPin, LOW);
}
}
void generateAndSendMessage() {
timeClient.update();
StaticJsonBuffer<100> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["sensor"] = "doorbell";
root["time"] = timeClient.getEpochTime();
root["value"] = 1;
root.printTo(msg);
Serial.println(msg);
client.publish("/homeassistant/devices/doorbell", msg);
}
Looking at the generateAndSendMessage function, I believe you are having an issue due to the size of the MQTT buffer.
The MQTT buffer is by default set to 128 bytes. This includes the length of the channel name along with the message.
The length of you channel is 32 bytes, and the json buffer you used to make the message is 100 bytes long. So you might just be exceeding the 128 byte mark.
Just declare this before including the PubSubClient.h
#define MQTT_MAX_PACKET_SIZE 200
This macro defines the buffer size of the PubSubClient to 200. You can change it to whatever you believe is required.
I hope this helps.

Connecting esp8266 to AWS IoT

I am trying to connect a WeMos D1 mini based on ESP8266 to the Amazon Web Service AWS IoT using https://github.com/heskew/aws-sdk-arduino.
However, when I flash the device, I get a 403 back, with the following message:
"Credential should be scoped to correct service: 'execute-api'. "
Changing
this->awsService = "iotdata";
to
this->awsService = "execute-api";
in AmazonIOTClient.cpp results in a 404:
"No method found matching route things/my-thing/shadow for http method POST."
and, according to this thread the service should be 'iotdata' for the request to succeed.
Has someone had the same problem and figured out a way to get it running? If so, help would be greatly appreciated. Thanks!
Here the full code for the example:
#include <AmazonIOTClient.h>
#include <Esp8266AWSImplementations.h>
#include <AWSFoundationalTypes.h>
#include "keys.h"
const int sleepTimeS = 30;
void printWiFiData();
void printCurrentNetwork();
void publish(const char *topic, String data);
void publishToAWS();
void setup() {
Serial.begin(9600);
Serial.println("Started!");
publishToAWS();
ESP.deepSleep(sleepTimeS * 1000000);
}
void loop() {
}
void printWiFiData() {
// IP address
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// MAC address
byte mac[6];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
Serial.print(mac[5], HEX);
Serial.print(":");
Serial.print(mac[4], HEX);
Serial.print(":");
Serial.print(mac[3], HEX);
Serial.print(":");
Serial.print(mac[2], HEX);
Serial.print(":");
Serial.print(mac[1], HEX);
Serial.print(":");
Serial.println(mac[0], HEX);
}
void printCurrentNetwork() {
// SSID
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// signal strength:
Serial.print("signal strength (RSSI): ");
Serial.println(WiFi.RSSI());
}
void publish(const char *topic, String data) {
AmazonIOTClient iotClient;
ActionError actionError;
Esp8266HttpClient httpClient;
Esp8266DateTimeProvider dateTimeProvider;
Serial.println();
Serial.print("Connecting to ");
Serial.print(wifiSsid);
Serial.println("...");
WiFi.begin(wifiSsid, wifiPwd);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(50);
}
Serial.println("");
Serial.println("WiFi connected");
printCurrentNetwork();
printWiFiData();
delay(50);
Serial.println("Initializing IoT client...");
iotClient.setAWSRegion(awsIotRegion);
iotClient.setAWSEndpoint(awsIotEndpoint);
iotClient.setAWSDomain(awsIotDomain);
iotClient.setAWSPath("/things/my-thing/shadow");
iotClient.setAWSKeyID(awsKeyID);
iotClient.setAWSSecretKey(awsSecKey);
iotClient.setHttpClient(&httpClient);
iotClient.setDateTimeProvider(&dateTimeProvider);
delay(50);
Serial.println("Updating thing shadow...");
MinimalString shadow = ("{\"state\":{\"reported\":{\"text\":" + data + "}}}").c_str();
char* result = iotClient.update_shadow(shadow, actionError);
Serial.print("result: ");
Serial.println(result);
}
void publishToAWS() {
Serial.println("Publishing to AWS IoT Broker");
publish("my-thing/text", "Hello World!");
}
keys.cpp file:
#include "keys.h"
// AWS User Credentials
const char* awsKeyID = "XXXXXXXXXXXXXXXXXXXX";
const char* awsSecKey = "X1xxx23xxxxXXXX34XXxxxxX56xXxxxxxxXx789x";
// AWS IoT
const char* awsIotRegion = "eu-central-1";
const char* awsIotEndpoint = "xxxxxxxxxxxxxx";
const char* awsIotDomain = "iot.eu-central-1.amazonaws.com";
// Init and connect WiFi to local WLAN
char* wifiSsid = "mySSID";
char* wifiPwd = "password";
I can finally contribute something :)
I got this very same example working a few days ago. However I used the same library just a different branch iot-get-shadow-and-cleanup. I don't recall having to make any changes as the one you mentioned:
this->awsService = "iotdata"; to this->awsService = "execute-api";
Here are the correct settings for your AWS endpoint that goes into keys.cpp
awsIotRegion = "us-east-1";
awsIotEndpoint = "amazonaws.com";
awsIotDomain = "axxxxs2pxxxrlx.iot.us-east-1.amazonaws.com";`
Also add delete[] result; to the end of the publish() to save some precious heap space.
I would recommend using the iot-get-shadow-and-cleanup branch since it has fixes for memory leaks.
I made one more change to resolve all issues with running out of heap space when updating the shadow continiously. In AWSClient4.cpp I changed // delete[] server; to delete[] data; - I am not 100% sure if this was necessary but combined with the addition of delete[] result; I was able to update the shadown every minute continuously for an hour without loosing any heap.
Hope this helps.

Resources