echo '' ;

Archives

ESP32 Mongoose OS Interface -MQTT

 

Mongoose OS Credentials configure

Two way to configure the MQTT Credentials  in Mongoose OS file. This Example tested with mongoose os , demo-js app, windows 10, 64bit, mos tool, ESP32 DevKitC from ESPressif.

  • First one is using mos tool  UI
    • GO to 127.0.0.1:1992/  –> Device Config  –> Change the MQTT Credential in MQTT Setting  and Save with Reboot
    • Afterwards its generate the new file name is conf9.json
  • Second methods is change the mqtt Credential in conf0.json  file

 

Required

  • ESP32 Any kind of boards
  • Mongoose OS firmware
  • Mos Tool
  • MQTT Server Credentials
  • WiFi Crendentials

Note : This ESP32 Mongoose OS interface – MQTT is tested with Windows 10 64bit machine, mos tool(Web Browser based IDE for Mongoose OS), ESp32 DevkitC board from ESPressif.

 

Follow

  • Make sure already set your WiFi Credentials (otherwise MQTT is not work, also check the MQTT Connected status in Terminal windows)

 

Code : init.js  file

load('api_config.js');
load('api_events.js');
load('api_gpio.js');
load('api_mqtt.js');
load('api_sys.js');

let button = Cfg.get('pins.button');
let topic = '/devices/' + Cfg.get('device.id') + '/events';

print('button GPIO:', button);

let getInfo = function() {
  return JSON.stringify({
    total_ram: Sys.total_ram(),
    free_ram: Sys.free_ram()
  });
};

// Publish to MQTT topic on a button press. Button is wired to GPIO pin 0
GPIO.set_button_handler(button, GPIO.PULL_UP, GPIO.INT_EDGE_NEG, 20, function() {
  let message = getInfo();
  let ok = MQTT.pub(topic, message, 1);
  print('Published:', ok, topic, '->', message);
}, null);

// Monitor network connectivity.
Event.addGroupHandler(Net.EVENT_GRP, function(ev, evdata, arg) {
  let evs = '???';
  if (ev === Net.STATUS_DISCONNECTED) {
    evs = 'DISCONNECTED';
  } else if (ev === Net.STATUS_CONNECTING) {
    evs = 'CONNECTING';
  } else if (ev === Net.STATUS_CONNECTED) {
    evs = 'CONNECTED';
  } else if (ev === Net.STATUS_GOT_IP) {
    evs = 'GOT_IP';
  }
  print('== Net event:', ev, evs);
}, null);

 

Output

  • Results : {“free_ram”:148676,”total_ram”:229296}
  • Topic : /device/esp32_0255EC/events

 


 

 

ESP8266 MQTT broker BONDAR

The ESP8266 can indeed be programmed to act as an MQTT broker, allowing it to handle messaging between different devices in a network using the MQTT protocol. Will Discuss “ESP8266 MQTT broker BONDAR”.

Get Start of ESP8266 MQTT broker BONDAR

Create an account

  • Create an account in here
  • Activate your iotcentral account

Download Bin FIle

Flash the Bondar Firmware

  • your ESP8266 starting from address 0x0. (Use esptool.py or ESP Flash Download Tool)
  • For Linus
    • sudo esptool.py -p /dev/ttyUSB0 –baud 9600 write_flash -fs 32m-c1 -fm dio -ff 40m 0x00000 bondar.bin

ESP8266 Configuration

  • ESP8266 will start as Access Point mode. and named as Bondar_XXXXXXXXX  . (Ex refer Below image : Bondar_2e3ae80cb19a ) and should use default password 12345678
  • Now connect that AP Network (Bondar_2e3ae80cb19a ) with your laptop or mobile.
  • Go to 192.168.4.1 in your browser and you will get a configuration page. Then enter your wifi Credential and your he user and password used on IoTCentral.eu
  • Reset the ESP8266 by Click button and also unplug and re-plug the power cable (I recommend you to unplug and then plug the power cable).
  • After Rest you can see when did soft web browser reset button

IoTCentral.eu Account Details

  • Login to your home page on IoTCentral.eu
  • You will see your allocated topic
  • Use allocated_topic/your_topics to connect to iotcentral.eu:1883 and /allocated_topic/your_topic to connect from your Wi-Fi network.

Note :   Always use your email address and the password used on IoTCentral.eu to publish and subscribe. In this way your data is protected and no one will get access to your data since the topic is secret and you are using your username and password to publish and subscribe to the cloud.


ESP8266 NodeMCU Module – MQTT

Functions

  • mqtt.Client()  – Creates a MQTT client.
  • mqtt.client:close()  – Closes connection to the broker.
  • mqtt.client:connect() – Connects to the broker specified by the given host, port, and secure options.
  • mqtt.client:lwt( ) – Setup Last Will and Testament (optional).
  • mqtt.client:on()  – Registers a callback function for an event.
  • mqtt.client:publish()  – Publishes a message.
  • mqtt.client:subscribe()  – Subscribes to one or several topics.
  • mqtt.client:unsubscribe()  – Unsubscribes from one or several topics.

 

MQTT Example

  • MQTT subscribe and publish the data to
-- Required Modules :Mqtt,Wifi
-- https://www.aruneworld.com/
-- Tested By    : Arun(20170527)
-- Example Name : AEW_Mqtt.lua
---------------------------------------------------------------------------------
station_cfg={}
station_cfg.ssid= "ArunEworld" station_cfg.pwd= "ArunEworld.com"    --please change your SSID and Passworld

print("wifi init")
wifi.setmode(wifi.STATIONAP)
wifi.sta.config(station_cfg)
wifi.sta.connect()


--Initializing Mqtt
DEVICE_NAME     =   "ArunEworld-"..node.chipid()
PUBLISH_TOPIC   =   "ArunEworld/"..DEVICE_NAME.."-Result"
SUBSCRIBE_TOPIC =   "ArunEworld/"..DEVICE_NAME
CLIENT_ID       =   DEVICE_NAME
USERNAME        =   "username"              --  please change your username
PASSWORD        =   "Password"              --  please change your Password
HOSTNAME        =   "mqtt.aruneworld.com"   --  Please change your port
PORT            =   "Port_Number"                       --  Please change your port number

-- Mqtt Setup
m = mqtt.Client(CLIENT_ID, 120, USERNAME, PASSWORD, 0)
    m:connect(HOSTNAME, PORT, 0, function(conn) 
    m:publish(PUBLISH_TOPIC,DEVICE_NAME.." is Online", 1, 0, function(conn) end)
    m:subscribe(SUBSCRIBE_TOPIC, 1, function(conn)  end)
end)

--Mqtt Receive function
m:on("message", function(client, topic, payload)        
        if payload ~= nil then
            print(payload)
        else
            print("Mqtt Reccived nill payload message")
        end
    collectgarbage("collect")
end)

--Mqtt Send function
local function Send_MQTT(strings)
    m:publish(PUBLISH_TOPIC,strings, 1, 0, function(conn)   end)
end

--Wifi Event Monitoring
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
    print("\n\tSTA - CONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: "..T.BSSID.."\n\tChannel: "..T.channel)
end)

wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
    print("\n\tSTA - DISCONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: "..T.BSSID.."\n\treason: "..T.reason)
end)

wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
    print("\n\tSTA - GOT IP".."\n\tStation IP: "..T.IP.."\n\tSubnet mask: "..T.netmask.."\n\tGateway IP: "..T.gateway)
end)

 


 Read and Write files using MQTT

  • transfer files over mqtt
-- For More info :- https://www.aruneworld.com/ 
-- Tested By : Arun(20170527)
-- Required Modules : CJSON, FILE, MQTT, WiFi,

station_cfg={}
DEVICE_NAME = node.chipid()
station_cfg.ssid= "ArunEworld" station_cfg.pwd= "Arun"
PUBLISH_TOPIC = "MQTT_File_Ex_PUB"
SUBSCRIBE_TOPIC = "MQTT_File_Ex_SUB"
CLIENT_ID = DEVICE_NAME
USERNAME = ""
PASSWORD = ""
HOSTNAME = "iot.eclipse.org"
PORT = 1883

print("wifi init")
wifi.setmode(wifi.STATIONAP)
wifi.sta.config(station_cfg)
wifi.sta.connect()

-- test transfer files over mqtt.
m_dis={}            --Created the table and name is m_dis
function dispatch(m,t,pl)
    if pl~=nil and m_dis[t] then
        m_dis[t](m,pl)
    end
end

function pubfile(m,filename)
    file.close()
    file.open(filename)
    repeat
    local pl=file.read(1024)
    if pl then m:publish("/topic2",pl,0,0) end
    until not pl
    file.close()
end
-- payload(json): {"cmd":xxx,"content":xxx}
function topic1func(m,pl)
    print("get1: "..pl)
    local pack = cjson.decode(pl)
    if pack.content then
        if pack.cmd == "open" then file.open(pack.content,"w+")
        elseif pack.cmd == "write" then file.write(pack.content)
        elseif pack.cmd == "close" then file.close()
        elseif pack.cmd == "remove" then file.remove(pack.content)
        elseif pack.cmd == "run" then dofile(pack.content)
        elseif pack.cmd == "read" then pubfile(m, pack.content)
        end
    end
end

m_dis["/topic1"]=topic1func
-- Lua: mqtt.Client(clientid, keepalive, user, pass)
--m=mqtt.Client()
m = mqtt.Client(CLIENT_ID, 20, USERNAME, PASSWORD, 0)
m:on("connect",function(m) 
    print("connection "..node.heap()) 
    m:subscribe("/topic1",0,function(m) print("sub done") end)
    m:publish(PUBLISH_TOPIC,DEVICE_NAME.." is Live", 1, 0, function(m) print("[LOG]:- Mqtt "..DEVICE_NAME.." is Live in Online Mode") end)
    
    end )
m:on("offline", function(conn)
    print("disconnect to broker...")
    print(node.heap())
end)
m:on("message",dispatch )
-- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
--m:connect(192.168.18.88,1883,0,1)
--host = "iot.eclipse.org"
m:connect(HOSTNAME,1883,0,1)

-- usage:
-- another client(pc) subscribe to /topic2, will receive the test.lua content.
-- and publish below message to /topic1
-- {"cmd":"open","content":"test.lua"}
-- {"cmd":"write","content":"print([[hello world]])\n"}
-- {"cmd":"write","content":"print(\"hello2 world2\")\n"}
-- {"cmd":"write","content":"test.lua"}
-- {"cmd":"run","content":"test.lua"}
-- {"cmd":"read","content":"test.lua"}

 


 

MQTT to cloud

-- test with cloudmqtt.com
m_dis={}
function dispatch(m,t,pl)
    if pl~=nil and m_dis[t] then
        m_dis[t](m,pl)
    end
end
function topic1func(m,pl)
    print("get1: "..pl)
end
function topic2func(m,pl)
    print("get2: "..pl)
end
m_dis["/topic1"]=topic1func
m_dis["/topic2"]=topic2func
-- Lua: mqtt.Client(clientid, keepalive, user, pass)
m=mqtt.Client("nodemcu1",60,"test","test123")
m:on("connect",function(m) 
    print("connection "..node.heap()) 
    m:subscribe("/topic1",0,function(m) print("sub done") end)
    m:subscribe("/topic2",0,function(m) print("sub done") end)
    m:publish("/topic1","hello",0,0) m:publish("/topic2","world",0,0)
    end )
m:on("offline", function(conn)
    print("disconnect to broker...")
    print(node.heap())
end)
m:on("message",dispatch )
-- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
m:connect("m11.cloudmqtt.com",11214,0,1)
tmr.alarm(0,10000,1,function() local pl = "time: "..tmr.time() 
    m:publish("/topic1",pl,0,0)
    end)

 

 

 


Next :

Previous :


 

Embedded Protocol – MQTT

Message Queue Telemetry Transport (ISO/IEC PRF 20922), or MQTT, is a lightweight protocol designed for machine-to-machine (M2M) device communication using a Publish/Subscribe pattern. It was developed by Message Queue Telemetry Transport (ISO/IEC PRF 20922) and Lightweight protocol for (M2M) device communication using  Publish/Subscribe. It was Developed By  Andy Stanford-Clark (IBM) and Arlen Nipper (Eurotech; now Cirrus Link) in 1999. Unlike HTTP, which follows a request/response paradigm, It utilizes a publish/subscribe architecture. The central communication point in It is the Broker. It is available for implementation in C, C++, JavaScript, Lua, Python, and soon in C#.


Client functions

FieldDescription
HostAddress of the MQTT broker.
PortDefault: 1883.
ClientIDUnique client identifier.
UsernameUTF-8 encoded string for authentication.
PasswordClient’s password if flag set.
Keep AliveDuration client stays connected (seconds).
SSLIndicates SSL/TLS encryption usage.
Clean SessionIf set, session clears subscriptions and messages.
Last-will TopicTopic for “Last Will” message on disconnect.
Last-will QoSQuality of Service for “Last Will”.
Last-will RetainRetain status for “Last Will” message.
Last-will MessageContent of “Last Will” in case of disconnection.
TopicMessage destination hierarchy.
+ Plush signSingle-level wildcard in subscriptions.
# Hash SignMultilevel wildcard in subscriptions.
Publish QoSQuality of Service levels:
QoS(0) – At most once
QoS(1) – At least once
QoS(2) – Exactly once
RetainMessage retention by broker.
SubscriptionsList of subscribed topics.
MessagePayload data transmitted.
BrokerServer distributing messages.
ClientDevice or app connected to broker.
Quality of ServiceMessage delivery guarantee.
Retained MessagesBroker-stored messages for new subscribers.
Persistent SessionBroker-maintained session after client disconnects.
Last will and Testament and SYS topicClient’s “Last Will” message and system topics interaction.

PHP MQTT


Web Apps


WordPress Plugin

DIOT SCADA with MQTT By Ecava

Image Source

DIOT which stands for Decoupled IOT, has its SCADA functionalities decoupled into Host and Node for flexibility and scalability that catered for IoT era. This plugin functions as the SCADA Host to work with your device or system, which will be treated as SCADA Node. You just need to enter the broker/server into the configuration. You may then subscribe to the desired topic with a shortcode to display in any desired web page or post. [diot topic="building/floor/device/sensor"] Or, if you have a JSON content, you may add dollar sign as JSON root: [diot topic="building/floor/device/sensor$json.data"]. The content will be updated dynamically when the device publish any data. You may also choose to display your realtime data in trending chart. Check out Ecava DIOT online demo to see how easy things can be done now! For more see here : https://wordpress.org/plugins/ecava-diot-scada/

Image Source

WP-MQTT By Roy Tanck

Setting up Tthis is easy. Simply supply your MQTT broker’s details and configure which WordPress events should trigger messages. “MQTT is a machine-to-machine (M2M)/”Internet of Things” connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport.” (from mqtt.org) A number of events are predefined. Simply check the right checkbox and fill in the message’s subject and text.

  • Pageview
  • User login
  • Failed user login
  • Post published
  • Page published
  • New comment

Other events can be added using the “custom events” section. This allows you to use any WordPress hook (actions and filters) to trigger messages.

Image Source


Android App

Check this below name in Play-store

  • Dashboard
  • IOT Manager
  • IOT

Broker Service Supporter

The following list of brokers may be used online or locally also giving free and paid service

Adafruit IO (Online – Free)

  • Website : Adafruit IO
  • Adafruit supporting online free service.
  • You can use adafruit client libraries to Python, Node JS, Rubby and Arduino. see the client libraries section).
  • The following details are to connect a client to Adafruit IO.
    • Host : io.adafruit.com
    • Port : 1883 or 8883
    • Username : Your adafruit account username
    • Password : Your adafruit IO Key

CloudMQTT (Online -Free and Paid)

  • Website :
  • CloudMQTT
  • Online – Free Plans : Cute Cat and
  • Paid Plans : Keen Kola, Loud Leopard, Power Pug)
  • Using Amazon Web Service
  • Type : mosquitto

HiveMQ (Online -Free and Paid)

Connect to Public Broker

  • Dashboard
    • Broker: broker.hivemq.com
    • TCP Port: 1883
    • Websocket Port: 8000
  • Web socket Client : http://www.hivemq.com/demos/websocket-client/
    • Broker: broker.mqttdashboard.com
    • TCP Port: 1883
    • Websocket Port: 8000

Setup local instance

m2m

Free public broker service

  • q.m2m.io
    • Broker: q.m2m.io
    • Port: 1883.
    • Application : Facebook messenger

Mosquitto  (Local and Online free)

Eclipse Mosquitto™ is an open source v3.1/v3.1.1 Broker.

Free public Service

  • iot.eclipse.org
    • Broker: iot.eclipse.org
    • Port: 1883, 80(WebScoket), 443 (WebSockets+SSl)
  • mosquitto
    • Broker : test.mosquitto.org
    • Port:
      • 1883 : MQTT, unencrypted
      • 8883 : MQTT, encrypted
      • 8884 : MQTT, encrypted, client certificate required
      • 8080 : MQTT over WebSockets, unencrypted
      • 8081 : MQTT over WebSockets, encrypted
      • 80(WebScoket), 443 (WebSockets+SSl)

rabbitMQ

  • https://www.rabbitmq.com/
  • Install on windows

Free public broker service

  • dev.rabbitmq.com
    • Broker: dev.rabbitmq.com
    • Port: 1883,

SimpleML

  • Free MQTT service to evaluate Machine Learning models, documentation

Free public broker service

  • simpleml
    • Broker: mqtt.simpleml.com
    • Port : 1883 (MQTT), 8883 (MQTT +SSl), 80(REST), 80(WebSockets), 5683 (CoAP)

Other free public broker service

  • dioty.co
    • Broker : dioty
    • Port : 1883 (MQTT), 8883 (MQTT +SSl), 80(REST), 8080(WebSockets), 8880 (WebSocket +SSL)
  • swifitch.cz
    • Broker :mqtt.swifitch.cz
    • Port : 1883 (MQTT)

Interview Questions


Reference