Unable to connect to MQTT Server - arduino

I am using knolleary library to connect the Arduino UNO board to MQTT server. For broker I am using test.mosquitto.org (85.119.83.194) but I am not able to connect.
Here is my code:
/*
Basic MQTT example
- connects to an MQTT server
- publishes "hello world" to the topic "outTopic"
- subscribes to the topic "inTopic"
*/
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
byte server[] = { 10, 2, 63, 123};
byte ip[] = { 85, 119, 83, 194 };
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
Serial.println("Message received");
}
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
Serial.println("Ethernet Begin");
if (client.connect("arduinoClient")) {
Serial.println("Client connected");
client.subscribe("/notification/turnlighton");
}
else{
Serial.println("Client not connected");
}
}
void loop()
{
client.loop();
}
client.connect("arduinoClient") return false and "Client not connected" message is printed Serial Monitor.
I am not sure what should be the value of
byte server[] = { 10, 2, 63, 123};
As an alternate I also tried to connect to the Really Simple Message Broker (RSMB) in intranet. Still I get same message.
Can any one help in here?
Thanks in advance
SRS

You have it around the wrong way;
byte server[] is your mqtt server's ip address, in your case test.mosquitto.org (85.119.83.194)
byte ip[] is the static ip address you want the arduino to have on your network.
The other thing to check is that you can connect using a cli client to test.mosquitto.org as it is sometimes down I find.
Have a look at my temperature publishing code, https://github.com/matbor/arduinoTemps2mqtt it might give you a few hints as it was modified from that original example that comes with PubSubClient. In my one I just have the arduino running off DHCP.

Related

Simple Arduino Client Server communication via Ethernet, IP

Simple Ethernet communication between two Arduino boards. I used two Arduino UNO boards, Two Arduino Ethernet Shields.
Here is my Server Code
//Server
#include <SPI.h>
#include <Ethernet.h>
// network configuration. gateway and subnet are optional.
// the media access control (ethernet hardware) address for the shield:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
//the IP address for the shield:
byte ip[] = { 192,168,1,180 };
// the router's gateway address:
byte gateway[] = { 192, 168, 1, 1 };
// the subnet:
byte subnet[] = { 255, 255, 255, 0 };
EthernetServer server = EthernetServer(10001);
void setup()
{
// initialize the ethernet device
Ethernet.begin(mac, ip, gateway, subnet);
// start listening for clients
server.begin();
}
void loop()
{
// if an incoming client connects, there will be bytes available to read:
EthernetClient client = server.available();
if (client == true) {
// read bytes from the incoming client and write them back
// to any clients connected to the server:
server.write(client.read());
}
}
Here is my Client Code
//Client
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = {0xDE,0xAD,0xBE,0xEF,0xFE,0xEC};
IPAddress ip(192,168,1,177);
IPAddress server(192,168,1,180);
EthernetClient client(10001);
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
if (client.connect(server, 10001)) {
Serial.println("connected");
client.println("GET /search?q=arduino HTTP/1.0");
client.println();
} else {
Serial.println("connection failed");
}
}
void loop()
{
if (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}
}
I input those two codes to two Arduino boards. Wiring and other connection are correct and reliable.
But I got this output from client serial monitor
connecting...
connection failed
disconnecting.
According to my view, error may happen in client code. Can you help me to find the error?

Blink Led using MQTT in arduino

I have to implement a prototyping scenario that blink LED in the arduino with MQTT protocol. I already tried with several MQTT libraries but non of them not work perfectly. Connection to the MQTT broker working successfully but when I publish the message with topic which I set in arduino not blink the LED. Arduno have to publish a message when it successfully connect but this publishing part also not working
this is my code
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Set the MAC address
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 100);
IPAddress server(192, 168, 1, 20);
// Set what PINs our Led's are connected to
int redPin = 13;
//int greenPin = 6;
//int bluePin = 7;
// Set a generic code that will trigger our Blue Led
// think of this as a set of codes for automation you might write
byte triggerRed[13] = "12345";
// handles messages that are returned from the broker on our subscribed channel
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("New message from broker on topic:");
Serial.println(topic);
Serial.print("Payload:");
Serial.write(payload, length);
// Check and see if our payload matches our simple trigger test
if ((length == 5) & (memcmp(payload, triggerRed, 5) == 0) )
{
//blink(redPin);
}
}
EthernetClient ethClient;
PubSubClient client(ethClient);
// Fire up our PubSub client
//PubSubClient client(server, 1883, callback);
void setup()
{
// Open serial communications
Serial.begin(9600);
client.setServer(server, 1883);
client.setCallback(callback);
// Setup our Leds
pinMode(redPin, OUTPUT);
// pinMode(greenPin, OUTPUT);
// pinMode(bluePin, OUTPUT);
// attempt a DHCP connection
Serial.println("Attempting to get an IP address using DHCP:");
if (!Ethernet.begin(mac))
{
// if DHCP fails, start with a hard-coded address:
Serial.println("failed to get an IP address using DHCP, trying manually");
Ethernet.begin(mac, ip);
}
Serial.print("My address:");
Serial.println(Ethernet.localIP());
// Connect to Broker, give it arduino as the name
if (client.connect("arduino")) {
// Good, we connected turn on the red led
digitalWrite(redPin, HIGH);
// Publish a message to the status topic
client.publish("status","Arduino is now online");
// Listen for messages on the control topic
client.subscribe("ultra");
}
}
void loop()
{
client.loop();
}
// Anything with flashing lights.
void blink(int targetLed)
{
digitalWrite(redPin, HIGH);
}
how can I fix this ?
Put connection routine in a loop and try with test.mosquitto.org first.
Here is code that works for me (Ethernet shield hardware):
definitions:
#define CLIENT_NAME "myclientname"
#define TOPIC "mytopic"
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 105);
IPAddress server(85, 119, 83, 194);// test.mosquitto.org
#define MQTT_PORT 1883
IPAddress myDns(8, 8, 8, 8);
EthernetClient ethClient;
PubSubClient client(ethClient);
setup:
client.setServer(server, MQTT_PORT);
client.setCallback(callback);
Ethernet.begin(mac);
loop:
if (!client.connected()) {
reconnect();
}
client.loop();
reconnect routine
void reconnect() {
if (millis() - reconnectionTimer >reconnection_period){// Loop until we're reconnected
reconnectionTimer = millis();
if (!client.connected()) {
// Attempt to connect
if (client.connect(CLIENT_NAME)) {
client.subscribe(TOPIC);
}
else {
Serial.print(client.state());
Serial3.print(client.state());
}
}
}
}
update for blink:
void blink(){
digitalWrite(led, LOW);
delay(500);
digitalWrite(led, HIGH);
}
I lost a lot of time because i had the problem with the mqtt server. ensure that your server is using mqtt protocol, because i was using ws protocol and any library that I tried doesn't works with this protocol

Arduino Knolleary PubSubClient will publish messages but can't receive them

I am using the Knolleary PubSubClient to make a connection to my MQTT server. I have been able to successfully authenticate and make a connection after not much work. I can even publish messages to topics. However, the issue I am having is that I can subscribe to topics and get no error, but when I publish to that topic (from mosquitto on my Mac) the callback does not get called and the message to the subscribe topic does not appear to be received. I have tried running a mosquitto subscription to the same topic at the same time, and that does receive the published message. Not sure if there is a problem in my callback code or what is going on here. Any help would be appreciated. Arduino code is below:
/*
Basic MQTT example
- connects to an MQTT server
- publishes "hello world" to the topic "outTopic"
- subscribes to the topic "inTopic"
*/
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte server[] = { 10, 2, 63, 123 };
byte ip[] = { 192, 168, 1, 10 };
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println(topic);
//convert byte to char
payload[length] = '\0';
String strPayload = String((char*)payload);
Serial.println(strPayload);
//int valoc = strPayload.lastIndexOf(',');
//String val = strPayload.substring(valoc+1);
//Serial.println(val);
}
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void setup()
{
Serial.begin(19200);
Serial.println("==STARTING==");
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
//delay(500);
boolean con = client.connect("1", "3snzzon5dyade:abc", "OBSCURED_FOR_SEC");
while(con != 1){
Serial.println("no con-while");
con = client.connect("1", "3snzzon5dyade:abc", "OBSCURED_FOR_SEC");
}
//Serial.println(con);
if(con){
Serial.println("got con");
client.publish("testq","hello world");
client.subscribe("testq");
}else Serial.println("no con");
}
void loop()
{
client.loop();
}
Like I said, I can see everything working properly with mosquitto. I have even tried matching up client_ids with no luck. Any help or ideas would be greatly appreciated.
your subscribe topic "testq" must be in an array like
char testq[] = {'t', 'e', 's', 't', 'q', '\0'};
be sure to finisht your array with an ,'\0'
Then you subscribe with:
client.subscribe(testq);

Arduino Ethernet Reading from PHP File

I am writing a simple Arduino Ethernet program. The program sends an HTTP GET Request to the server and then the server echos "Hello World" and I should be able to receive it through the Arduino Ethernet and print it on the Serial monitor of the Arduino 1.0.4 IDE. Here are some useful information. I am using a XAMPP Server on Windows Server 2003. I have placed my PHP file in /xampp/htdocs/xampp and the file name is rec.php. The contents of rec.php is
<?php
echo "Hello World";
?>
This is the file content of the Arduino program
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x7E, 0xAE}
IPAddress server { 192, 168, 1, 223 };
IPAddress ipAddress { xxx,xxx,xxx,xxx };
IPAddress myDNS {8,8,8,8};
IPAddress myGateway{192,168,1,1};
IPAddress mySubnet{255,255,255,0};
EthernetClient client;
void setup()
{
Serial.begin(9600);
Ethernet.begin(mac, ipAddress, myDNS, myGateway, mySubnet);
delay(1000);
Serial.println("connecting");
if(client.connect(server, 80))
{
Serial.println("Connected");
client.println("GET /rec.php HTTP/1.1");
}
else
Serial.println("Not Connected");
}
void loop()
{
if(client.available())
{
char c = client.read();
Serial.println(c);
delay(1000);
}
else
{
Serial.println("Not Available");
delay(1000);
}
}
After I load the program on the Arduino I get this message on the Serial Monitor "HTTP/1.1 400 Bad Request". Any suggestion on how to solve that problem? and please keep your answers simple.
You are not sending the necessary line ends. The protocol requires a CR-LF at the end of the request method and another CR-LF at the end of the full request that can include other header lines. See:
HTTP requests
This means in your case you need two CR-LF's to terminate the request. Don't rely on default println function. Take control of the line ends in your code with print:
client.print("GET /rec.php HTTP/1.1\r\n\r\n");

When I should use client.available() in Arduino?

I bought an Ethernet shield and I wrote a code, but I saw that there is .available() method. I don't know where to use it. So guys, do you know where and when I should use it? Here is my sample code:
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192, 168, 1, 107);
EthernetServer server = EthernetServer(80);
void setup() {
Serial.begin(9600);
Ethernet.begin(mac, ip);
server.begin();
}
void loop() {
EthernetClient client = server.available();
if(client) {
if(client.available()) {
char c = client.read();
Serial.print(c);
}
}
}
Thank you.
Client.available() returns the number of bytes that a client (remote client) may have written. If you're writing an HTTP server, the first client data would be: GET /URL HTTP/1.0.
You then write back to that client with Client.write(). For example:
c.write("HTTP/1.0 200 OK")

Resources