PubSubClient: Arduino sketch to create webserver & publish topic payload as soon as link is clicked

364 views
Skip to first unread message

K Smith

unread,
Dec 31, 2016, 6:47:24 AM12/31/16
to MQTT

Hi,

I am struggling with this.

I have an Arduino mega with ethernet shield.

I need an Arduino sketch that will create a webserver with a few links on it and publish a specific MQTT topic and payload as soon as a link is clicked.
Each link will have a different topic and payload.
There will be about 10 links on the page.

I have done extensive googling and yesterday spent the day trying to adjust existing code; I would post it up but it is just a mess now.

I thought I'd ask to see of this could be done before posting code.

Thanks

K Smith

unread,
Dec 31, 2016, 6:55:43 AM12/31/16
to MQTT
The muddle comes when trying to use the Arduino as a server for the web page and as a client for the MQTT publishing. 
Within void loop() I call "EthernetClient client" but I then can't call client.publish() as this is not known to the Ethernet library.
So I call the reconnect() function, as listed in the PubSubClient libraries and put the client.publish() commands in there, but the reconnect loop takes 30 seconds or so to update the MQTT topic with the contents of the payload on the server.

I'm sure my mix of server (web) and client (MQTT) architecture is rubbish anyway; I am not a c programmer. Well I'm not a programmer at all actually.

Anyone who knows  PubSubClient & using ardunio as a web server will understand what I'm talking about. Well they might ! What do you think?

Paul Fremantle

unread,
Dec 31, 2016, 1:45:08 PM12/31/16
to mq...@googlegroups.com
I think you might be getting a number of things confused.

1)  EthernetClient client should be in the setup() not the loop()

2) PubSubClient is a separate client that uses the EthernetClient in its startup. You can't call publish on EthernetClient, only on PubSubClient.

3) I would suggest getting a standalone PubSubClient example working before integrating into the Web Server. That would help simplify and solve one problem at a time.

4) we can't help decide if its a good idea to put the web server and MQTT client together without a better idea of what you want to achieve.

Paul

--
To learn more about MQTT please visit http://mqtt.org
---
You received this message because you are subscribed to the Google Groups "MQTT" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mqtt+unsubscribe@googlegroups.com.
To post to this group, send email to mq...@googlegroups.com.
Visit this group at https://groups.google.com/group/mqtt.
For more options, visit https://groups.google.com/d/optout.



--
Paul Fremantle
Doctoral Researcher, University of Portsmouth, School of Computing
Visiting Scientist, Institute of the Architecture of Application Systems, Stuttgart
Visiting Lecturer, Software Engineering Programme, Oxford University
Co-Founder, WSO2
Apache Member and Committer
twitter: pzfreo / skype: paulfremantle / blog: http://pzf.fremantle.org

Kes Smith

unread,
Dec 31, 2016, 7:58:18 PM12/31/16
to mq...@googlegroups.com
HI Paul,

Thanks for the ideas. I have been through the PubSubClient Library examples and couldn't figure out how to add a web server to any of those, which is the problem. I just do not know how to do it.

The effect I need is really simple; click on any of the 4 links in the code and immediately publish the topic and topic payload as shown, while the webserver continues to run. 

This is the code I have. I am now going in going in circles.

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetClient.h>

#include <PubSubClient.h>


byte gateway[]         = { 192, 168, 1, 1   };                     // internet access via router
byte subnet[]          = { 255, 255, 255, 0 };                     // subnet mask
byte mac[]             = { 0xAE, 0xAE, 0xBE, 0xAE, 0xFE, 0xAE };   // physical mac address
byte ip_webserver[]    = { 192, 168, 1, 51  };                     // ip of webserver

byte ip_mqtt_server[]  = { 192, 168, 1, 120  };                    // MQTT webserver 

EthernetServer server(80);


void callback(char* topic, byte* payload, unsigned int length) { 
  // handle message arrived
}

IPAddress server2(ip_mqtt_server);

EthernetClient ethClient;
PubSubClient client(server2, 1883, callback, ethClient);


String readString;


void setup() { 

                Ethernet.begin(mac, ip_webserver, subnet, gateway);
                server.begin();
                                
                client.setServer(server2, 1883);               // MQTT
                client.setCallback(callback);                  // MQTT
  
               
              }



void reconnect() {
   
  while (!client.connected())    {
                                       if (client.connect("arduinoClient")) 
                                       
                                           {  
                                               if (readString.indexOf("?lrm-main-on")  >0)  { client.publish("groungfloor/livingroom/mainlight_on_off", "on ");  }
                                               if (readString.indexOf("?lrm-main-off") >0)  { client.publish("groungfloor/livingroom/mainlight_on_off", "off");  }
                                               if (readString.indexOf("?lrm-side-on")  >0)  { client.publish("groungfloor/livingroom/sidelights_on_off","on" );  }
                                               if (readString.indexOf("?lrm-side-off") >0)  { client.publish("groungfloor/livingroom/sidelights_on_off","off");  }
                                                     
                                               //client.subscribe("headlands/groundfloor/bedroom4/temperature_DS18B20");
                                                                                            
                                           } 
                                           
                                           else 
                                           
                                           {
       
                                              Serial.print("failed, rc=");        
                                              Serial.println(" try again in 1 seconds");
                                              // Wait 1 seconds before retrying
                                              delay(1000);                              
         
                                           }

  
                                 }
              }


void loop() 

 //1st open bracket
 { 

  EthernetClient client = server.available();

  // 2nd open bracket
  if (client) {

       // 3rd open bracket    
       while (client.connected()) {   

                //4th open bracket         
                if (client.available()) {
     
                         char c = client.read();
                         //read char by char HTTP request
     
                                     // open bracket with closed bracket
                                     if (readString.length() < 100)    {
                                         //store characters to string
                                         readString += c;
                                          Serial.print(c);             }

                       //5th open bracket
                       if (c == '\n') {       //if HTTP request has ended

          
           ////////////////////////////////////
           //        HTML STARTED            // 
           ////////////////////////////////////


           //////////////////  HTML header statements /////////////////////////          
      
           client.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>");
           client.println("<html xmlns='http://www.w3.org/1999/xhtml'>");

           client.println("<html><head><meta name='viewport' content='width=device-width'><title></title><style>a{color:blue}.content1{width: 20px; float:right;}.content2{width: 20px; float:left;}</style></head><body><center><br/>");



           //////////////////////////////////////////////////////
           //   LINKS to : Computer & Mobile,  LAN  &  WAN     // 
           //////////////////////////////////////////////////////
           
           client.println("<b><font size=+2 color='#CC33FF'>House</font></b><br/><br/>");


                      
           //////// Room Door Switches ////////////////////////////////////
           
           client.println("<b><font size=+1 color='#CC33FF'>Room Door Switches</font></b><br/>");

           client.println("<a href='/?lrm-main-on' target='x2'>LRm, Main Light On</a>&nbsp;&nbsp;&nbsp;<a href='/?lrm-main-off' target='x2'>LRm, Main Light Off</a><br/>");
           client.println("<a href='/?lrm-side-on' target='x2'>LRm, Side Light On</a>&nbsp;&nbsp;&nbsp;<a href='/?lrm-side-off' target='x2'>LRm, Side Light Off</a><br/>");
          
           
           ///////////////////////////////////////////////////////////////////////////////////
           //   CRITICAL ..  below iframe code stops page refresh on the button click       // 
           ///////////////////////////////////////////////////////////////////////////////////

           client.println("<iframe name=x2 style='display:none'></iframe>");
      
           ////////////////////////////////////
           
           client.println("<p></p></center></body></html>");

           ////////////////////////////////////
           //        HTML FINISHED           // 
           ////////////////////////////////////
 
  

           

           /////////////////////////////////////////////
           //        SWITCHING LOGIC BEGINS           // 
           /////////////////////////////////////////////
       

           // LRm Main Door Switch //
           
           // main on 
           if (readString.indexOf("?lrm-main-on")   >0){reconnect(); }
           
           // main off 
           if (readString.indexOf("?lrm-main-off") >0){reconnect(); }
                                                    

  
           // LRm Side Door Switch //
           // on button90, off button91
                      
           // side on 
           if (readString.indexOf("?lrm-side-on")   >0){reconnect();}

           // side off 
           if (readString.indexOf("?lrm-side-off") >0){reconnect();}
                                                    

           
           //clearing string for next read
           readString="";  
           
           delay(1);
           //stopping client
           client.stop();

                
            //5th bracket closed             
            }

         //4th bracket closed
         }
       
      //3rd bracket closed
      }

   //2nd bracket closed
   }

//1st bracket closed
}


You received this message because you are subscribed to a topic in the Google Groups "MQTT" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/mqtt/wNBSA9J-pPE/unsubscribe.
To unsubscribe from this group and all its topics, send an email to mqtt+unsubscribe@googlegroups.com.

Paul Fremantle

unread,
Jan 1, 2017, 5:57:11 AM1/1/17
to mq...@googlegroups.com
Kes

I can't exactly figure out what you are up to here, but one thing is clear - you have mixed up the logic for publishing with the reconnect logic. You are also using the variable client for multiple different clients. I also can't spot a mqtt client loop.

Paul

Kes Smith

unread,
Jan 1, 2017, 9:04:07 AM1/1/17
to mq...@googlegroups.com
That's because I don't know anything about C. 

If you know of a simple example anywhere that runs a webster and can client.publish () the moment a Web link on the server is clicked.

I'm not too bothered about how it is achieved.

Thanks

Paul Fremantle

unread,
Jan 1, 2017, 4:15:58 PM1/1/17
to mq...@googlegroups.com
Kes

I don't have any examples like that.

Sorry
Paul

Kes Smith

unread,
Jan 1, 2017, 4:50:56 PM1/1/17
to mq...@googlegroups.com
Thanks for ideas Paul. 

When I get something going, I will fork it and anyone can then copy or improve it.
Reply all
Reply to author
Forward
0 new messages