ESP8266连接贝壳物联网

ESP8266应该已经烧录了nodemcu固件

首先,我们创建一个init.lua文件,8266在上电就会执行init.lua里面的程序,以下为init.lua文件

在第三行需要输入要连接的WiFi名称和密码

print("set up wifi mode")
wifi.setmode(wifi.STATION)
wifi.sta.config("wifi","password")
wifi.sta.connect()
tmr.alarm(1, 1000, 1, function()
if wifi.sta.getip()== nil then
print("IP unavaiable, Waiting...")
else
tmr.stop(1)
print("Config done, IP is "..wifi.sta.getip())
dofile("kaiguan.lua")
end
end)

以下是kaiguan.lua

在DEVICEID 输入自己在贝壳物联申请的ID
在APIKEY输入设备的KEY
在INPUTID输入数据传入的接口(如果不使用可以忽略)

DEVICEID = "-------"
APIKEY = "-----------"
INPUTID = "------"
host = host or "www.bigiot.net"
port = port or 8181
pin = 4
pwm.setup(pin,50,70)  --128   PWM
pwm.start(pin)



local function run()
  local cu = net.createConnection(net.TCP)
   cu:on("receive", function(cu, c) 
        r = cjson.decode(c)
    if r.M == "say" then
      if r.C == "play" then  
        gpio.write(led, gpio.LOW) 
        print('0') 
        ok, played = pcall(cjson.encode, {M="say",ID=r.ID,C="LED1"})
        cu:send( played.."\n" )
      end
      if r.C == "stop" then 
        gpio.write(led, gpio.HIGH)  
        print('1') 
        ok, stoped = pcall(cjson.encode, {M="say",ID=r.ID,C="LED2"})
        cu:send( stoped.."\n" ) 
      end
      
      
      
    end
  end)
  cu:on('disconnection',function(scu)
    cu = nil
   print("disconnection~~~~~~~~~~~~")
    tmr.stop(1)
    tmr.alarm(6,5000,0,run)
  end)
  cu:connect(port, host)
  ok, s = pcall(cjson.encode, {M="checkin",ID=DEVICEID,K=APIKEY})
  if ok then
    print(s)
  else
   print("failed to encode!")
  end 
  ----------------------
  cu:on('connection',function(scu) 
     
    ok, stoped = pcall(cjson.encode, {M="checkout",ID=DEVICEID,K=APIKEY})
    cu:send( stoped.."\n" ) 

     cu:send(s.."\n")
       
        
        
        
        data1=1

      
        
        
        uart.on("data",function(data)
                data1=data
        end,0)
     
    tmr.alarm(3, 4500, 1, function()
           
           
      
           
    end)
  end)
  ------------------------------
  tmr.alarm(1, 60000, 1, function()
    cu:send(s.."\n")
  end)


  tmr.alarm(2, 5400000, 1, function()


   ok, stoped = pcall(cjson.encode, {M="checkout",ID=DEVICEID,K=APIKEY})
   cu:send( stoped.."\n" ) 
   tmr.delay(2000000)
   dofile("init.lua")

   -- cu:connect(port, host)
  --ok, s = pcall(cjson.encode, {M="checkin",ID=DEVICEID,K=APIKEY})
  --if ok then
    --print(s)
 -- else
  -- print("failed to encode!")
  --end 
  end)


  
end
run()



你可能感兴趣的:(ESP8266连接贝壳物联网)