ESP8266-MQTT

FirewingUser.ESP8266-MQTT History

Hide minor edits - Show changes to output

Added line 67:
Added lines 1-2:
'+Updated with unlink, disconnect recovery and async queue event on 29 April, 2015+'
Changed line 62 from:
// If MQTT_ASYNC = True MQTT module use OnMQTTQueueChanges event
to:
// If MQTT_ASYNC = True caller program use OnMQTTQueueChanges event
Added line 66:
Added lines 71-74:
// Main program use his KeepAlive management
// so declare a variable and a constant
// then set only one timer and import Timers module
 
Deleted line 92:
   TopicNum        As Byte    = 2,
Added lines 105-106:
// Main program use his KeepAlive management
// So this sub handle Timers.OnTimeout event
Added lines 127-128:
// Main program want use an async mode to read queues..
// So this sub handle MQTT_ESP8266.OnMQTTQueueChanges event
Added line 141:
// This sub handle the broker connection event
Added lines 151-152:
   // Main program use his KeepAlive management
  // so add a single Timer at 1000 ms   
Added lines 197-198:
           // Main program use his KeepAlive management
            // so start all defined Timers (only one)
Added lines 211-212:
                 // Main program not use Async read method
                  // so read every queue changed flag
Deleted lines 5-6:
Attach:file.ext | link text
Added lines 56-65:
// If MQTT_TICKS = True MQTT module use his MQTT-Tick module
//              = False caller program must implement a timer to call the
//                sub MQTTSetKeepAlive every KeepAlive seconds

#option MQTT_TICKS        = False 

// If MQTT_ASYNC = True MQTT module use OnMQTTQueueChanges event
//              = False caller program must test MQTTIsQueueChanged(nQueue)
//                for changes
#option MQTT_ASYNC        = True
Changed lines 69-79 from:
to:
#if MQTT_TICKS = False
Private Dim
  KeepAlive        as UInteger    = 0

Const cKeepAliveSecs = 20
 
  #option TIMER_AVAILABLE = 1 
  Imports Timers
#endif

Changed lines 100-110 from:
private sub Main()   
  DelayMS(2000)

   console.write("First try a WiFi join..",13,10)
 
  if JoinToWiFi(WiFiNetName, WiFiNetPassword) then
      console.write("WiFi join successfully",13,10)
      console.write("Now set broker parms..",13,10)       
      If Not MQTTSetBroker(addressof(BrokerAddr)) Then
        console.write("Errors into configuration parms!",13,10)
        CloseSocket()
to:
#if MQTT_TICKS = False
Sub OnTimeout(ByRef timer As TimerItem) Handles Timers.OnTimeout
 
  Dim Item As TimerItem = timer                      
  Select Item
.ID                                   
   Case 0
      Item.Interval = 10
      If KeepAlive >
(99 * cKeepAliveSecs) Then
        console.write("MQTTSetKeepAlive",13,10)
        MQTT_ESP8266.MQTTSetKeepAlive()
        KeepAlive = 0
Added lines 111-153:
         KeepAlive = KeepAlive + 1
      End If
  End Select

  Item.Enabled = True
  timer = Item 
End Sub
#endif

#if MQTT_ASYNC = True
private sub QueueChanges(n as byte) handles MQTT_ESP8266.OnMQTTQueueChanges
  select n
  case 0   
      console.write("OK, message on 'MessQueue1'",13,10)
      console.write("->", MessQueue1,"<-",13,10)
  case 1                                       
      console.write("OK, message on 'MessQueue2'",13,10)
      console.write("->", MessQueue2,"<-",13,10)
  end select 
end sub
#endif

private sub HelloMessage() handles MQTT_ESP8266.OnMQTTBrokerConnected
  console.write("Broker is connected!!",13,10)   
end sub


private sub Main()   
  DelayMS(2000)

  #if MQTT_TICKS = False
  Timers.Add(1000)  ' 1000 ms timer
  #endif

  console.write("First try a WiFi join..",13,10)
 
  if JoinToWiFi(WiFiNetName, WiFiNetPassword) then
      console.write("WiFi join successfully",13,10)
      console.write("Now set broker parms..",13,10)       
      If Not MQTTSetBroker(addressof(BrokerAddr)) Then
        console.write("Errors into configuration parms!",13,10)
        CloseSocket()
      Else
Changed lines 183-189 from:
           console.write("Now send subscriptions to broker",13,10)           
to:
           console.write("Now send subscriptions to broker",13,10)

            #if MQTT_TICKS = False
            console.write("And start KeepAlive timer",13,10)
            Timers.Start         
            #endif 

         
Added line 197:
                 #if MQTT_ASYNC = False
Added line 206:
                 #endif
Added lines 5-6:

Attach:file.ext | link text
Changed line 22 from:
Attach:file.ext | link text
to:
Attach:FW-8266.jpg
Added lines 21-22:

Attach:file.ext | link text
Changed line 22 from:
This library has been tested with Firewing R2 PIC24 version and is for this reason that in the source I put a locking check for different conditions. If you want to try their hand at some willing to test different hardware I remind you that the PIC18 version could not support even 2048 bytes needed for the MQTT receive buffer then remains only version PIC32 for which perhaps you need to change some interrupt registers.
to:
This library has been tested with Firewing R2 PIC24 version and is for this reason that in the source I put a locking check for different conditions. If you want to try their hand at some willing to test different hardware I remind you that the PIC18 version could not support even 2048 bytes needed for the MQTT receive buffer then remains only PIC32 version for which perhaps you need to change some interrupt registers.
Added lines 21-22:

This library has been tested with Firewing R2 PIC24 version and is for this reason that in the source I put a locking check for different conditions. If you want to try their hand at some willing to test different hardware I remind you that the PIC18 version could not support even 2048 bytes needed for the MQTT receive buffer then remains only version PIC32 for which perhaps you need to change some interrupt registers.
Changed line 26 from:
So only 4 of 8 wires are connected to the Firewing board, GPIO lines can be used as general purpose I/O or can be used to update the firmware.. you can find several examples of how to do it in web.
to:
So only 5 of 8 wires are connected to the Firewing board, GPIO lines can be used as general purpose I/O or can be used to update the firmware.. you can find several examples of how to do it in web.
Added lines 25-26:

So only 4 of 8 wires are connected to the Firewing board, GPIO lines can be used as general purpose I/O or can be used to update the firmware.. you can find several examples of how to do it in web.
Deleted lines 21-22:
You can download Firewing library modules here: [[Attach:WiKi-MQTT-for-ESP8266-FW-Library.zip| ESP8266 WiFi Module MQTT Library ]]
Added lines 26-29:
You can download Firewing library modules here: [[Attach:WiKi-MQTT-for-ESP8266-FW-Library.zip| ESP8266 WiFi Module MQTT Library ]]

As usual to update the UserLibrary drag and drop the compressed file directly into the Firewing IDE editor window and two folders will be created, ESP8266 and MQTT, in your UserLibrary folder.

Deleted lines 222-264:
'''Updated 0n April 3, 2015'''

As rightly pointed out in [[http://www.firewing.info/forum/viewtopic.php?f=7&t=207#p1166 | this post ]] by Jerry Messina the MQTT-Tick.bas module should be change as follows to prevent invalid keep-alive time:

Module MQTT-Tick.BAS

=firewing [=

module Tick

private const _osc = _clock                            // alias for Code Explorer
private const _fosc as uinteger = _osc * 1000000 / 2    // instructions per second
private const _ms as ushort = _fosc / 1000              // instructions every 1 ms

private _ticks as uinteger = 0                            // increment every millisecond

// interrupt will increment tick every millisecond...
private Interrupt OnTimer(Pic.T2Interrupt) 
  _ticks += 1              ' increment tick     
  IFS0.7 = 0              ' clear interrupt flag
End Interrupt

public function Time() as uinteger
  disable(OnTimer)
  Time = _ticks
  enable(OnTimer)
end function

// alias for code compatibility with existing MQTT module
public dim ms as Time

// init module...
sub main()
  T2CON = 0                ' clear Timer 1 - no presccale
  PR2 = _ms                ' set timer period
  IFS0.7 = 0              ' clear timer interrupt flag   
  T2CON.15 = 1            ' start timer
  enable(OnTimer)
end sub

End module

=]
Added lines 24-25:
The ESP8266 module is certainly among the most nominated in the network for its low cost and ease of use. The library uses the main serial for debugging and uses the second serial to drive the ESP8266 through the i/o lines D2 and D3 as shown (remember also to connect the pin CH_PD to 3.3 volts):
Changed lines 33-34 from:
To use MQTT need a server named "Broker" and even in this case there are open source libraries for all operating systems and I used mosquitto for windows that provides two of his application to send new and receive messages from the command line. Mosquitto also provides a service broker on line for any test but after a couple of weeks has banned my IP address.
to:
To use MQTT need a server named "Broker" and even in this case there are open source libraries for all operating systems and I used mosquitto for windows that provides two of his application to send new and receive messages from the command line. Mosquitto also provides a service broker on line at 85.119.83.194 IP address.
Deleted lines 36-38:
You can download FW test programs here: [[Attach:MQTT-Programs.zip | FW test programs]]

Changed lines 40-41 from:
!!MQTT Reader program
to:
!!ESP8266 MQTT Reader program
Changed lines 43-77 from:
#option WIZ_DHCP_DEBUG    = false
#option WIZ_DNS_DEBUG      = false
#option MQTT_DEBUG        = false
#option MQTT_DUMP          = false

#option USE_DHCP          = true
#option USE_DNS            = false
#option WIZ_SCS_PIN        = _D10 
#option WIZ_RST_PIN        = _D9   
#option TCP_PORT_ROM_ADDR  = 0

imports "W5500-Consts"
imports "W5500-Utils"
imports "W5500"
imports "MQTT"

Private Sub ConfigDisplay()
    Console.Write(13,10)
    Console.Write("MAC Address ",SARtoString(),13,10)
    Console.Write("IP Address  ",SIPRtoString(),13,10)
    Console.Write("Subnet Mask ",SUBRtoString(),13,10)
    Console.Write("Gateway    ",GARtoString(),13,10)
    Console.Write(13,10)   
End Sub

#if USE_DHCP
  imports "W5500-DHCP"
  sub OnUpdate() Handles W5500_DHCP.OnUpdateEvent
      ConfigDisplay()
  End Sub

  sub OnConflict() Handles W5500_DHCP.OnConflictEvent
  End Sub
#endif

to:
clock = 80

#option MQTT_DEBUG        = False
#option MQTT_DUMP          = False

#option _gccOptimise = s
imports "MQTT-ESP8266"

Deleted lines 55-56:
Dim sockreg        As Byte
Changed line 57 from:
   BrokerAddr(4)  As Byte    = {192,168,1,50},
to:
   BrokerAddr(4)  As Byte    = {85,119,83,194},   // Mosquitto MQTT Broker Service
Changed lines 64-67 from:
   MessQueue1      As String(256),
    MessQueue2      As String(256),
    WillMessage    As String(256)
to:
   MessQueue1      As String(256) = "",
    MessQueue2      As String(256) = "",
    WillMessage    As String(256) = "Sorry, see you later"
   
private dim
    WiFiNetName    as string = "<WiFiNetName>",
    WiFiNetPassword as string = "<WiFiNetPassword>"   

Deleted lines 72-86:
   #if USE_DHCP = true     
      Console.Write("Now find the DHCP server.. ",13,10)   
      If DHCPTask(3) = false Then
          Console.Write("DHCP error, so must set static parms.. ",13,10)
          ConfigDisplay()
      End If   
  #else
      Console.Write("Using static config.. ",13,10)   
      ConfigDisplay()
  #endif

  DelayMS(1000)

  console.writeline("")
  console.writeline("My IP Address is " + SIPRtoString())
Changed lines 74-90 from:
   sockreg = 0

  MessQueue1=
""
  MessQueue2= ""
   WillMessage = "Sorry, see you later"

  If Not MQTTSetBroker(sockreg, addressof(BrokerAddr), 1883, &H00) Then
     console.writeline("MQTT: Errors into configuration parms")
      W5500.Close(sockreg)
  Else
      console.writeline("MQTT: Broker parms is ok..")
      console.writeline("MQTT: Now store 2 subscriptions in memory")
      If MQTTAddSubscription(addressof(Topic1),
                            QOS_LEVEL_EXACTLY_ONCE,
                            addressof(MessQueue1),
                            SizeOf(MessQueue1)) Then
        console.writeline("MQTT: Subscriptions added successfully on Topic1"
)
to:

  console.write("First try a WiFi join..",13,10)
 
  if JoinToWiFi(WiFiNetName, WiFiNetPassword) then
 
  console.write("WiFi join successfully",13,10)
 
    console.write("Now set broker parms..",13,10)       
      If Not MQTTSetBroker(addressof(BrokerAddr)) Then
 
      console.write("Errors into configuration parms!",13,10)
         CloseSocket()
Changed lines 84-116 from:
         console.writeline("MQTT: Unable to set subscription on Topic1")
      End If

      If MQTTAddSubscription(addressof(Topic2),
                            QOS_LEVEL_EXACTLY_ONCE,
                            addressof(MessQueue2),
                            SizeOf(MessQueue2)) Then
          console.writeline("MQTT: Subscriptions added successfully on Topic2")
      Else
          console.writeline("MQTT: Unable to set subscription on Topic1")
      End If

 
      console.writeline("MQTT: Now can try a connection to broker")
 
      If MQTTConnect("MyMQTTReader", false, false, 1, addressof(WillTopic), addressof(WillMessage)) Then
        console.writeline("MQTT: MyReader is now connected to broker")           
        console.writeline("MQTT: Now send subscriptions to broker")           
        If MQTTSubscribe() Then
            console.writeline("MQTT: Subscriptions are made")           
            console.writeline("All is done!")           

            While true
              MQTTService()
              if MQTTIsQueueChanged(0) Then
                  console.writeline("A new message on MessQueue1")
                  console.writeline(">", MessQueue1)
              End If
              If MQTTIsQueueChanged(1) Then
                  console.writeline("A new message on MessQueue2")
                  console.writeline(">", MessQueue2)
              End If
            End While               
to:
         console.write("Broker parms is ok..",13,10)
        console.write("Now store 2 subscriptions in memory",13,10)
        If MQTTAddSubscription(addressof(Topic1),
                                QOS_LEVEL_EXACTLY_ONCE,
                                True,
                                True,
                                addressof(MessQueue1),
                                SizeOf(MessQueue1)) Then
            console.write("Subscription added successfully on Topic1",13,10)
Changed line 94 from:
           console.writeline("MQTT: Unable to set subscriptions on broker")
to:
           console.write("Unable to set subscription on Topic1!",13,10)
Changed lines 96-97 from:
     Else
        console.writeline("MQTT: Unable to set connection")
to:

        If MQTTAddSubscription(addressof(Topic2),
                                QOS_LEVEL_EXACTLY_ONCE,
                                True,
                                True,
                                addressof(MessQueue2),
                                SizeOf(MessQueue2)) Then
            console.write("Subscription added successfully on Topic2",13,10)
        Else
            console.write("Unable to set subscription on Topic1!",13,10)
        End If

     
        console.write("Now can try a connection to broker...",13,10)
     
        If MQTTConnect("MyMQTTReader", false, false, 1, addressof(WillTopic), addressof(WillMessage)) Then
            console.write("'MyMQTTReader' is now connected to broker",13,10)           
            console.write("Now send subscriptions to broker",13,10)           
            If MQTTSubscribe() Then
              console.write("All subscriptions are made",13,10)           
              console.write("All is done.",13,10)
              console.write("Now you must send some messages with an MQTT Client please.",13,10)           

              while True
                  MQTTService()
                  if MQTTIsQueueChanged(0) Then
                    console.write("OK, message on 'MessQueue1'",13,10)
                    console.write("->", MessQueue1,"<-",13,10)
                  End If
                  If MQTTIsQueueChanged(1) Then
                    console.write("OK, message on 'MessQueue2'",13,10)
                    console.write("->", MessQueue2,"<-",13,10)
                  End If
              end while                                           
            Else
              console.write("Unable to set subscriptions on broker!",13,10)
            End If
        Else
            console.write("Unable to set connection!",13,10)
        End If
Changed lines 137-138 from:
   End If
to:
   else
      console.write("Unable to join to this WiFi network!",13,10)     
  end if
     
Changed lines 147-148 from:
!!MQTT Sender program
to:
!!ESP8266 MQTT Sender program
Changed lines 150-151 from:
#option WIZ_DHCP_DEBUG    = false
#option WIZ_DNS_DEBUG      = false
to:
clock = 80
Changed lines 153-184 from:
#option MQTT_DUMP          = false

#option USE_DHCP          = true
#option USE_DNS            = false
#option WIZ_SCS_PIN        = _D10 
#option WIZ_RST_PIN        = _D9   
#option TCP_PORT_ROM_ADDR  = 0

imports "W5500-Consts"
imports "W5500-Utils"
imports "W5500"
imports "MQTT"

Private Sub ConfigDisplay()
    Console.Write(13,10)
    Console.Write("MAC Address ",SARtoString(),13,10)
    Console.Write("IP Address  ",SIPRtoString(),13,10)
    Console.Write("Subnet Mask ",SUBRtoString(),13,10)
    Console.Write("Gateway    ",GARtoString(),13,10)
    Console.Write(13,10)   
End Sub

#if USE_DHCP
  imports "W5500-DHCP"
  sub OnUpdate() Handles W5500_DHCP.OnUpdateEvent
      ConfigDisplay()
  End Sub

  sub OnConflict() Handles W5500_DHCP.OnConflictEvent
  End Sub
#endif

to:
#option MQTT_DUMP          = False
#option _gccOptimise = s
imports "MQTT-ESP8266"

Changed lines 161-164 from:
Dim sockreg        As Byte

Private Const

    BrokerAddr(4)   As Byte    = {192,168,1,50},
to:
Private Const
    BrokerAddr(4)  As Byte    = {85,119,83,194},   // Mosquitto MQTT Broker Service
Changed lines 169-172 from:
   WillMessage    As String(256),
   MessQueue1      as string(256),
    MessQueue2     as string(256)
to:
   WillMessage    As String(256) = "Sorry, see you later",
    MessQueue1      as string(256) = "",
   MessQueue2      as string(256) = ""

private dim
    WiFiNetName    as string = "<WiFiNetName>",
    WiFiNetPassword as string = "<WiFiNetPassword>"   
     
 
Changed lines 179-193 from:
   #if USE_DHCP = true     
      Console.Write("Now find the DHCP server.. ",13,10)   
      If DHCPTask(3) = false Then
          Console.Write("DHCP error, so must set static parms.. ",13,10)
          ConfigDisplay()
      End If   
  #else
      Console.Write("Using static config.. ",13,10)   
      ConfigDisplay()
  #endif

  DelayMS(1000)

  console.writeline("")
  console.writeline("My IP Address is " + SIPRtoString())
to:
  
Changed lines 181-210 from:
   sockreg = 0

  MessQueue1= ""
  MessQueue2= ""
  WillMessage = "Sorry, see you later"

  If Not MQTTSetBroker(sockreg, addressof(BrokerAddr), 1883, &H00) Then
  console.writeline("MQTT: Errors into configuration parms")
      W5500.Close(sockreg)
  Else
  console.writeline("MQTT: Broker parms is ok..")
  console.writeline("MQTT: Now connect to it")

      If MQTTConnect("MyMQTTSender",
                    false,
                    false,
                    0,
                    addressof(WillTopic),
                    addressof(WillMessage) ) Then
       
        console.writeline("MQTT: MySender is now connected to broker")           
        If MQTTPublish(addressof(Topic1),"Hello world on Topic1") Then
            console.writeline("MQTT: Message published")
        Else
            console.writeline("MQTT: Unable to publish message")
        End If

        While true
            MQTTService()
        End While
to:

  console.write("First try a WiFi join..",13,10)
  if JoinToWiFi(WiFiNetName, WiFiNetPassword) then
      If Not MQTTSetBroker(addressof(BrokerAddr)) Then
        console.writeline("Errors into configuration parms!")
        CloseSocket()
Changed lines 188-193 from:
         console.writeline("MQTT: Unable to set connection")
      End If
  End If

  While true
  End While
to:
         console.writeline("Broker parms is ok..")
        console.writeline("Now connect to it")
 
        If MQTTConnect("MyMQTTSender",
                        false,
                        false,
                        0,
                        addressof(WillTopic),
                        addressof(WillMessage)) Then
           
            console.writeline("'MyMQTTSender' is now connected to broker")           
            If MQTTPublish(addressof(Topic1),"Hello world on my wonderfull Topic1") Then
              console.writeline("Message published")
            Else
              console.writeline("Unable to publish message!")
            End If

            While true
              MQTTService()
            End While
        Else
            console.writeline("Unable to set connection!")
        End If     
      end if
  else
      console.write("Unable to join to this WiFi network!",13,10)     
  end if 
  while True
  end while 
Added line 218:
Changed lines 21-24 from:
Attach:file.ext | link text
You can download Firewing library modules here:
[[Attach:MQTT-Library.zip | MQTT Library ]]

This library is [[http
://sfcompiler.co.uk/phpBB3/viewtopic.php?f=5&t=1944 | compatible ]] with this shields or eth module
to:

You can download Firewing library modules here:
[[Attach:WiKi-MQTT-for-ESP8266-FW-Library.zip| ESP8266 WiFi Module MQTT Library ]]

Attach
:esp8266-pins-FW.jpg
Added lines 1-334:
The best system to interchange data between different systems remains MQTT and there are about libraries for all operating systems and for all development systems.
MQ Telemetry Transport (MQTT) is a lightweight broker-based publish/subscribe messaging protocol designed to be open, simple, lightweight and easy to implement.

These characteristics make it ideal for use in constrained environments, for example, but not limited to where the network is expensive, has low bandwidth or is unreliable or when run on an embedded device with limited processor or memory resources.

I wanted to try my hand from here in the thing and I started with good examples on the net and converting the various sources to get a library working with the protocol 3.1
This protocol has only a few restrictions in the use of wildcard characters but lends itself to interchange messages string between systems without great waste of resources and every system support it.

Features of the protocol include the publish/subscribe message pattern to provide one-to-many message distribution and decoupling of applications, a messaging transport that is agnostic to the content of the payload and the use of pure TCP/IP to provide basic network connectivity.
Three qualities of service for message delivery ar supported:
* "At most once", where messages are delivered according to the best efforts of the underlying TCP/IP network. Message loss or duplication can occur. This level could be used, for example, with ambient sensor data where it does not matter if an individual reading is lost as the next one will be published soon after.
* "At least once", where messages are assured to arrive but duplicates may occur.
* "Exactly once", where message are assured to arrive exactly once. This level could be used, for example, with billing systems where duplicate or lost messages could lead to incorrect charges being applied.

So from here [[http://www.firewing.info/pmwiki.php?n=FirewingUser.MQTT | MQTT library for Wiz550io]] I wanted to try my hand in the conversion of it for a WiFi module and which if not ESP8266 already repeatedly named in Firewing forums.

I started from a library example that David John Barker gave me and I referred to it in the MQTT-ESP8266.BAS module.
The example gave me performed automatically the settings, join wifi network,
transfer data and then close the connection.
While in the case of the MQTT I needed a continuous connection I remodeled the library for this purpose.
Attach:file.ext | link text
You can download Firewing library modules here: [[Attach:MQTT-Library.zip | MQTT Library ]]

This library is [[http://sfcompiler.co.uk/phpBB3/viewtopic.php?f=5&t=1944 | compatible ]] with this shields or eth module

For the debugging I used two programs written in VB.NET that reference the open source library M2Mqtt (m2mqtt.codeplex.com) which among other things allows to get executables for Windows / Linux (Mono) and Windows Phone (7.8 and 8.1) a boon.
However, nothing prevents you from using other development systems since this protocol is well established and there are a lot of libraries/sources for Android and iOS.

You can download vb.net windows client examples here: [[Attach:MQTT-Windows-Client.zip | VB.NET test client]]

To use MQTT need a server named "Broker" and even in this case there are open source libraries for all operating systems and I used mosquitto for windows that provides two of his application to send new and receive messages from the command line. Mosquitto also provides a service broker on line for any test but after a couple of weeks has banned my IP address.

In this protocol is defined "Topic" a message queue and one of the most important features is the ability to define a Topic (named WillTopic ) to send a message (named WillMessage) to other connected clients that occurred a single client disconnection. If we add the fact that everyone can have a broker in your own home and can make visible the internet service by opening a single port of a router .. hello internet of things.

You can download FW test programs here: [[Attach:MQTT-Programs.zip | FW test programs]]


Clearly not going to go into too much detail of MQTT but would definitely recommend to take a ride on the Internet to gather information and in a week or so you'll be more than satisfied.


!!MQTT Reader program

=firewing [=
#option WIZ_DHCP_DEBUG    = false
#option WIZ_DNS_DEBUG      = false
#option MQTT_DEBUG        = false
#option MQTT_DUMP          = false

#option USE_DHCP          = true
#option USE_DNS            = false
#option WIZ_SCS_PIN        = _D10 
#option WIZ_RST_PIN        = _D9   
#option TCP_PORT_ROM_ADDR  = 0

imports "W5500-Consts"
imports "W5500-Utils"
imports "W5500"
imports "MQTT"

Private Sub ConfigDisplay()
    Console.Write(13,10)
    Console.Write("MAC Address ",SARtoString(),13,10)
    Console.Write("IP Address  ",SIPRtoString(),13,10)
    Console.Write("Subnet Mask ",SUBRtoString(),13,10)
    Console.Write("Gateway    ",GARtoString(),13,10)
    Console.Write(13,10)   
End Sub

#if USE_DHCP
  imports "W5500-DHCP"
  sub OnUpdate() Handles W5500_DHCP.OnUpdateEvent
      ConfigDisplay()
  End Sub

  sub OnConflict() Handles W5500_DHCP.OnConflictEvent
  End Sub
#endif

// ##################################################################################

// ##################################################################################

Dim sockreg        As Byte

Private Const
    BrokerAddr(4)  As Byte    = {192,168,1,50},
    Topic1                      = "/mqtt/topic1",
    Topic2                      = "/mqtt/topic2",
    TopicNum        As Byte    = 2,
    WillTopic                  = "/mqtt/willtopic" 

Private Dim
    MessQueue1      As String(256),
    MessQueue2      As String(256),
    WillMessage    As String(256)

private sub Main()   
  #if USE_DHCP = true     
      Console.Write("Now find the DHCP server.. ",13,10)   
      If DHCPTask(3) = false Then
          Console.Write("DHCP error, so must set static parms.. ",13,10)
          ConfigDisplay()
      End If   
  #else
      Console.Write("Using static config.. ",13,10)   
      ConfigDisplay()
  #endif

  DelayMS(1000)

  console.writeline("")
  console.writeline("My IP Address is " + SIPRtoString())
  DelayMS(2000)
  sockreg = 0

  MessQueue1= ""
  MessQueue2= ""
  WillMessage = "Sorry, see you later"

  If Not MQTTSetBroker(sockreg, addressof(BrokerAddr), 1883, &H00) Then
      console.writeline("MQTT: Errors into configuration parms")
      W5500.Close(sockreg)
  Else
      console.writeline("MQTT: Broker parms is ok..")
      console.writeline("MQTT: Now store 2 subscriptions in memory")
      If MQTTAddSubscription(addressof(Topic1),
                            QOS_LEVEL_EXACTLY_ONCE,
                            addressof(MessQueue1),
                            SizeOf(MessQueue1)) Then
        console.writeline("MQTT: Subscriptions added successfully on Topic1")
      Else
        console.writeline("MQTT: Unable to set subscription on Topic1")
      End If

      If MQTTAddSubscription(addressof(Topic2),
                            QOS_LEVEL_EXACTLY_ONCE,
                            addressof(MessQueue2),
                            SizeOf(MessQueue2)) Then
          console.writeline("MQTT: Subscriptions added successfully on Topic2")
      Else
          console.writeline("MQTT: Unable to set subscription on Topic1")
      End If

 
      console.writeline("MQTT: Now can try a connection to broker")
 
      If MQTTConnect("MyMQTTReader", false, false, 1, addressof(WillTopic), addressof(WillMessage)) Then
        console.writeline("MQTT: MyReader is now connected to broker")           
        console.writeline("MQTT: Now send subscriptions to broker")           
        If MQTTSubscribe() Then
            console.writeline("MQTT: Subscriptions are made")           
            console.writeline("All is done!")           

            While true
              MQTTService()
              if MQTTIsQueueChanged(0) Then
                  console.writeline("A new message on MessQueue1")
                  console.writeline(">", MessQueue1)
              End If
              If MQTTIsQueueChanged(1) Then
                  console.writeline("A new message on MessQueue2")
                  console.writeline(">", MessQueue2)
              End If
            End While               
        Else
            console.writeline("MQTT: Unable to set subscriptions on broker")
        End If
      Else
        console.writeline("MQTT: Unable to set connection")
      End If
  End If

  While true
  End While
end sub
=]


!!MQTT Sender program

=firewing [=
#option WIZ_DHCP_DEBUG    = false
#option WIZ_DNS_DEBUG      = false
#option MQTT_DEBUG        = false
#option MQTT_DUMP          = false

#option USE_DHCP          = true
#option USE_DNS            = false
#option WIZ_SCS_PIN        = _D10 
#option WIZ_RST_PIN        = _D9   
#option TCP_PORT_ROM_ADDR  = 0

imports "W5500-Consts"
imports "W5500-Utils"
imports "W5500"
imports "MQTT"

Private Sub ConfigDisplay()
    Console.Write(13,10)
    Console.Write("MAC Address ",SARtoString(),13,10)
    Console.Write("IP Address  ",SIPRtoString(),13,10)
    Console.Write("Subnet Mask ",SUBRtoString(),13,10)
    Console.Write("Gateway    ",GARtoString(),13,10)
    Console.Write(13,10)   
End Sub

#if USE_DHCP
  imports "W5500-DHCP"
  sub OnUpdate() Handles W5500_DHCP.OnUpdateEvent
      ConfigDisplay()
  End Sub

  sub OnConflict() Handles W5500_DHCP.OnConflictEvent
  End Sub
#endif

// ##################################################################################

// ##################################################################################

Dim sockreg        As Byte

Private Const
    BrokerAddr(4)  As Byte    = {192,168,1,50},
    Topic1                      = "/mqtt/topic1",
    Topic2                      = "/mqtt/topic2",
    TopicNum        As Byte    = 2,
    WillTopic                  = "/mqtt/willtopic"   

Private Dim
    WillMessage    As String(256),
    MessQueue1      as string(256),
    MessQueue2      as string(256)
 
private sub Main()
  #if USE_DHCP = true     
      Console.Write("Now find the DHCP server.. ",13,10)   
      If DHCPTask(3) = false Then
          Console.Write("DHCP error, so must set static parms.. ",13,10)
          ConfigDisplay()
      End If   
  #else
      Console.Write("Using static config.. ",13,10)   
      ConfigDisplay()
  #endif

  DelayMS(1000)

  console.writeline("")
  console.writeline("My IP Address is " + SIPRtoString())
  DelayMS(2000)
  sockreg = 0

  MessQueue1= ""
  MessQueue2= ""
  WillMessage = "Sorry, see you later"

  If Not MQTTSetBroker(sockreg, addressof(BrokerAddr), 1883, &H00) Then
  console.writeline("MQTT: Errors into configuration parms")
      W5500.Close(sockreg)
  Else
  console.writeline("MQTT: Broker parms is ok..")
  console.writeline("MQTT: Now connect to it")

      If MQTTConnect("MyMQTTSender",
                    false,
                    false,
                    0,
                    addressof(WillTopic),
                    addressof(WillMessage) ) Then
       
        console.writeline("MQTT: MySender is now connected to broker")           
        If MQTTPublish(addressof(Topic1),"Hello world on Topic1") Then
            console.writeline("MQTT: Message published")
        Else
            console.writeline("MQTT: Unable to publish message")
        End If

        While true
            MQTTService()
        End While
      Else
        console.writeline("MQTT: Unable to set connection")
      End If
  End If

  While true
  End While
end sub
=]

'''Updated 0n April 3, 2015'''

As rightly pointed out in [[http://www.firewing.info/forum/viewtopic.php?f=7&t=207#p1166 | this post ]] by Jerry Messina the MQTT-Tick.bas module should be change as follows to prevent invalid keep-alive time:

Module MQTT-Tick.BAS

=firewing [=

module Tick

private const _osc = _clock                            // alias for Code Explorer
private const _fosc as uinteger = _osc * 1000000 / 2    // instructions per second
private const _ms as ushort = _fosc / 1000              // instructions every 1 ms

private _ticks as uinteger = 0                            // increment every millisecond

// interrupt will increment tick every millisecond...
private Interrupt OnTimer(Pic.T2Interrupt) 
  _ticks += 1              ' increment tick     
  IFS0.7 = 0              ' clear interrupt flag
End Interrupt

public function Time() as uinteger
  disable(OnTimer)
  Time = _ticks
  enable(OnTimer)
end function

// alias for code compatibility with existing MQTT module
public dim ms as Time

// init module...
sub main()
  T2CON = 0                ' clear Timer 1 - no presccale
  PR2 = _ms                ' set timer period
  IFS0.7 = 0              ' clear timer interrupt flag   
  T2CON.15 = 1            ' start timer
  enable(OnTimer)
end sub

End module

=]