broker = "192.168.1.212" mqttport = 1883 userID = "" userPWD = "" clientID = "speakerSpot" GPIO2 = 4 GPIO15 = 8 --r GPIO14 = 5 --g GPIO12 = 6 --b pwm.setup(GPIO2, 1000, 0) pwm.setup(GPIO15, 1000, 0) --blue pwm.setup(GPIO14, 1000, 0) --green pwm.setup(GPIO12, 1000, 0) --red color = {} wifi.setmode(wifi.STATION) wifi.sta.config("Scrabble","#P4nc4k3!") pwm.setduty(GPIO2, 512) function wifi_connect() ip = wifi.sta.getip() if ip ~= nill then print('Connected, ip is:' .. ip) tmr.stop(1) pwm.setduty(GPIO2, 0) ready = 1 else ready = 0 end end function mqtt_do() if ready == 1 then m = mqtt.Client(clientID, 120, userID, userPWD) m:connect( broker , mqttport, 0, function(conn) print("Connected to MQTT:" .. broker .. ":" .. mqttport .." as " .. clientID ) tmr.stop(0) connected = 1; sub_mqtt() on_mqtt() end) end end function sub_mqtt() m:subscribe('/livingRoom/speakerSpot/#', 0, function(conn) print('Subscribed') end) end function on_mqtt() m:on('message', function(conn, topic, input) if topic == "/livingRoom/speakerSpot/rgb" then red,green,blue = input:match("([^,]+),([^,]+),([^,]+)") color['r'] = tonumber(red) color['g'] = tonumber(green) color['b'] = tonumber(blue) print('red: '..color['r']..'\ngreen: '..color['g']..'\nblue: '..color['b']) -- if (color['r']>1000) then -- pwm.setduty(GPIO13, (color['g']-1000) * 10) -- end if (color['r'] <= 100 and color['r'] >= 0) then pwm.setduty(GPIO12, color['r']* 10) end if(color['g'] <= 100 and color['g'] >= 0) then pwm.setduty(GPIO14, color['g']* 10) end if(color['b'] <= 100 and color['b'] >= 0) then pwm.setduty(GPIO15, color['b']* 10) end end end) end tmr.alarm(0, 1000, 1, function() mqtt_do() tmr.delay(1000) end) tmr.alarm(1, 1111, 1, function() wifi_connect() end)