Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Config Variables --
- DEVICE_NAME = "front-door"
- WIFI_NAME = "xxxxxxxx"
- WIFI_KEY = "xxxxxxxx"
- MQTT_IP = "192.168.1.xxx"
- MQTT_PORT = 1883
- MQTT_TOPIC = "sensors"
- -- Internal Variables --
- WIFI_STATUS = 255
- SENSOR_STATUS = 1
- BROKER_STATUS = 0
- BROKER = mqtt.Client(DEVICE_NAME .. "-sensor", 120)
- -- Translation Tables --
- WIFI_STATUS_TABLE = {}
- WIFI_STATUS_TABLE[wifi.STA_IDLE] = "Idle"
- WIFI_STATUS_TABLE[wifi.STA_CONNECTING] = "Connecting..."
- WIFI_STATUS_TABLE[wifi.STA_WRONGPWD] = "Auth Error"
- WIFI_STATUS_TABLE[wifi.STA_APNOTFOUND] = "AP Not Found"
- WIFI_STATUS_TABLE[wifi.STA_FAIL] = "Failure"
- WIFI_STATUS_TABLE[wifi.STA_GOTIP] = "Connected"
- WIFI_STATUS_TABLE[255] = "Disabled"
- SENSOR_STATUS_TABLE = {}
- SENSOR_STATUS_TABLE[0] = "OFF"
- SENSOR_STATUS_TABLE[1] = "ON"
- BROKER_STATUS_TABLE = {}
- BROKER_STATUS_TABLE[0] = "Disconnected"
- BROKER_STATUS_TABLE[1] = "Connected"
- -- MQTT Management --
- function broker_published()
- print("MQTT: Published Update")
- end
- function broker_connect()
- BROKER_STATUS = 1
- print("MQTT Status: " .. BROKER_STATUS_TABLE[BROKER_STATUS])
- BROKER:publish(MQTT_TOPIC .. "/" .. DEVICE_NAME, SENSOR_STATUS_TABLE[SENSOR_STATUS], 0, 0, broker_published)
- end
- function broker_offline()
- BROKER_STATUS = 0
- print("MQTT Status: " .. BROKER_STATUS_TABLE[BROKER_STATUS])
- BROKER:connect(MQTT_IP, MQTT_PORT, 0, nil)
- end
- -- Main Loop --
- function main()
- if wifi.sta.status() ~= WIFI_STATUS then
- WIFI_STATUS = wifi.sta.status()
- if WIFI_STATUS == wifi.STA_GOTIP then
- print("MQTT Status: Connecting...")
- BROKER:connect(MQTT_IP, MQTT_PORT, 0, nil)
- end
- print("WiFi Status: " .. WIFI_STATUS_TABLE[WIFI_STATUS])
- end
- if WIFI_STATUS == wifi.STA_GOTIP then
- if SENSOR_STATUS ~= gpio.read(1) then
- SENSOR_STATUS = gpio.read(1)
- print("Sensor Status: " .. SENSOR_STATUS_TABLE[SENSOR_STATUS])
- if BROKER_STATUS ~= 0 then
- BROKER:publish(MQTT_TOPIC .. "/" .. DEVICE_NAME, SENSOR_STATUS_TABLE[SENSOR_STATUS],0, 0, broker_published)
- end
- end
- end
- tmr.alarm(1,500,0,main)
- end
- -- Init Code --
- -- Wifi Config
- config = {}
- config.ssid = WIFI_NAME
- config.pwd = WIFI_KEY
- config.connected_cb = connected
- wifi.setmode(wifi.STATION)
- wifi.sta.sethostname(DEVICE_NAME .. "-sensor")
- wifi.sta.config(config)
- -- GPIO Config
- gpio.mode(1, gpio.INPUT, gpio.PULLUP)
- -- Broker Config
- BROKER:on("connect", broker_connect)
- BROKER:on("offline", broker_offline)
- -- Loop Entry
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement