Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

Mihini/mqtt

< Mihini
Revision as of 08:18, 11 March 2015 by Niranjan.babu.in.bosch.com (Talk | contribs) (Created page with "== MQTT == This example demonstrates the ON/OFF of LED lights via GPIO's pin 17 '''Variables''' local sched = require 'sched' local mqtt = require 'mqtt_library' //impor...")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

MQTT

This example demonstrates the ON/OFF of LED lights via GPIO's pin 17

Variables

local sched = require 'sched'
local mqtt   = require 'mqtt_library' //import MQTT Lib
local gpio = require 'gpio'
local log = require 'log'


local MQTT_BROKER       = 'iot.eclipse.org'  //sandbox broker hosted @Eclipse
local MQTT_PORT         = 1883               //Port number
local MQTT_LOG_NAME     = 'MQTT_LED'        

-- ---------------------------

local MQTT_LED_RECEIVE = "/MQTT/LED/"         //Topic that we subscribe for, to receive an event
local MQTT_LED_PUBLISH="/MQTT/PUBDATA/"       // topic that we publish in this example
local mqtt_client

Call back that will be called on a publish to a subscribed topic /MQTT/LED

 local function callback(topic, val)
   sched.wait(2)  //wait
    if( topic == '/MQTT/LED') then
        local val2 = gpio.configure(17,{direction="out", edge="both", activelow="0"})
        if(val=='on')then
          gpio.write(17,0)  
          mqtt_client:publish(MQTT_LED_PUBLISH, "Light's ON")
        elseif(val=='off') then
          gpio.write(17,1)
          mqtt_client:publish(MQTT_LED_PUBLISH, "Light's OFF")        -- publish data to a topic
   end
  end
end

Main Function

local function main()
   log(LOG_NAME, "INFO", "Application started")
  -- Connect to mqtt
    mqtt_client = mqtt.client.create(MQTT_BROKER, MQTT_PORT, callback)    --Create MQTT client
    log(LOG_NAME, "INFO", "MQTT Client is created")
     mqtt_client:connect(MQTT_LOG_NAME)                          --Connect to the server
     log(LOG_NAME, "INFO", "Connected to:" .. MQTT_LOG_NAME)
 sched.wait(2)
   mqtt_client:subscribe({MQTT_LED_RECEIVE})          --MQTT Subscribe to a topic
  while(true) do 
   -- print('INside main')
     mqtt_client:handler()           --MQTT handler continously calls sub and pub
 
    end--
  end
  sched.run(main)
  sched.loop()

Back to the top