【IOT】小项目2贝壳物联

1.获取www.bigiot.net的ip 121.42.180.30

【IOT】小项目2贝壳物联_第1张图片

2.创建一个智能设备

记住 ID:11374
APIKEY :65ab1c85b
通过贝壳物联平台通讯协议 https://www.bigiot.net/help/1.html
设备登录 (加密)
别忘了\n
{“M”:“checkin”,“ID”:“xx1”,“K”:“xx2”}\n
{“M”:“checkin”,“ID”:“11374”,“K”:“65ab1c85b”}\n
【IOT】小项目2贝壳物联_第2张图片
{“M”:“checkin”,“ID”:“11374”,“K”:“65ab1c85b”}\n
{“M”:“say”,“ID”:“U8030”,“C”:“hello”,“SIGN”:“xx4”}\n
【IOT】小项目2贝壳物联_第3张图片

3.快速开始

https://www.bigiot.net/help/20.html

init.lua

print("set up wifi mode")
wifi.setmode(wifi.STATION)
station_cfg={}
--here SSID and PassWord should be modified according your wireless router
station_cfg.ssid="ZNCZ-WIFI"
station_cfg.pwd="ZFW123456"
station_cfg.save=true
wifi.sta.config(station_cfg)

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

--use sjson
_G.cjson = sjson
--modify DEVICEID INPUTID APIKEY
DEVICEID = "11374"
APIKEY = "65ab1c85b"
INPUTID = "36"
host = host or "www.bigiot.net"
port = port or 8181
LED = 4
isConnect = false
gpio.mode(LED,gpio.OUTPUT)
local function run()
  local cu = net.createConnection(net.TCP)
  cu:on("receive", function(cu, c) 
    print(c)
    isConnect = true
    r = cjson.decode(c)
    if r.M == "say" then
      if r.C == "play" then   
        gpio.write(LED, gpio.LOW)  
        ok, played = pcall(cjson.encode, {M="say",ID=r.ID,C="LED turn on!"})
        cu:send( played.."\n" )
      end
      if r.C == "stop" then   
        gpio.write(LED, gpio.HIGH)
        ok, stoped = pcall(cjson.encode, {M="say",ID=r.ID,C="LED turn off!"})
        cu:send( stoped.."\n" ) 
      end
    end
  end)
  cu:on('disconnection',function(scu)
    cu = nil
    isConnect = false

    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
  if isConnect then
    cu:send(s.."\n")
  end
  tmr.alarm(1, 60000, 1, function()
    if isConnect then
      cu:send(s.."\n")
    end
  end)
end
run()

测试:

如果 返回了 checkok才是连接成功
【IOT】小项目2贝壳物联_第4张图片
通过设备对话:
【IOT】小项目2贝壳物联_第5张图片
PLAY 灯开

STOP灯关

点击 遥控设备

【IOT】小项目2贝壳物联_第6张图片
三角为PLAY

方块为STOP

你可能感兴趣的:(NodeMCU)