<noscript id="mmkmi"><source id="mmkmi"></source></noscript>
  • <noscript id="mmkmi"><kbd id="mmkmi"></kbd></noscript>
  • <table id="mmkmi"><source id="mmkmi"></source></table>
  • NodeMCU斷線檢測

    作者:z494627 | 更新時間:2016-05-20 | 瀏覽量:3005

    代碼源自例子代碼中的遠程開關代碼,可以處理多個gpio,并且檢測兩次心跳無返回會重啟設備

    --定義變量
    DEVICEID = "ID"
    APIKEY = "Key"
    INPUTID = "255"
    host = host or "www.eqytg.org"
    port = port or 8181
    --存活標記
    bLive=0
    
    --初始化GPIO列表
    LED=4
    LEDList={1,2,3,4,5,6,7,8,9}
    for i,v in ipairs(LEDList) do
    	print("GPIO:"..v)
    	gpio.mode(tonumber(v),gpio.OUTPUT)
    	print("GPIO:"..v.."OUTPUT")	 
    end
    
    --連接服務器(TCP連接)
    cu = net.createConnection(net.TCP)
    cu:connect(port, host)
    --接收處理
    cu:on("receive", function(cu, c)
      print(c)  
      r = cjson.decode(c)
      --如果存貨標記為1,置為0
      if bLive==1 then
    	if r.M=="isOL" then
    		bLive=0	
    	end
      end
      --如果是say代表命令
      if r.M == "say" then
    	if (string.sub(r.C,1,3)=="LED") then
    		--找到需要打開的LED號碼
    		pos=string.sub(r.C,4,4)		 
    		--獲取對應的GPIO號(見nodemcu對照)
    		LED=(LEDList[tonumber(pos)])		 
    		--ON--發送高電平
    		if (string.sub(r.C,5,6)=="ON") then
    			gpio.write(LED, gpio.HIGH)
    			ok, played = pcall(cjson.encode, {M="say",ID=r.ID,C=string.sub(r.C,1,4).." turn on!"})
    		else
    			--OFF 發送低電平
    			gpio.write(LED, gpio.LOW)
    			ok, played = pcall(cjson.encode, {M="say",ID=r.ID,C=string.sub(r.C,1,4).." turn off!"})
    		end
    		--反饋
    		print(played);
    		cu:send( played.."\n")
    	end
     end
     --收到連接正常,發送checkin
     if r.M == "WELCOME TO BIGIOT" then
    	ok, s = pcall(cjson.encode, {M="checkin",ID=DEVICEID,K=APIKEY})
    	if ok then
    	  print(s)
    	else
    	  print("failed to encode!")
    	end
    	cu:send( s.."\n" )
    	bLive=0
    	--定時心跳,防止掉線
    	tmr.alarm(1, 40000, 1, function()
    		--如果標記為1,表示未收到上次的心跳返回,重啟
    		if bLive==1 then
    			node.restart()
    		end
    		ok, ticket = pcall(cjson.encode, {M="isOL",ID="D"..DEVICEID})
    		print(ticket)
    		cu:send(ticket.."\n" )
    		--發送后將標記置為1
    		bLive=1		 
    	end)
     end
    end)



    評論:共2條

    TR28 評論于:2019-12-01 13:24:50
    寫得很好!
    njzc0232 評論于:2021-07-06 14:47:58
    驅動不了繼電器
    返回頂部
    <noscript id="mmkmi"><source id="mmkmi"></source></noscript>
  • <noscript id="mmkmi"><kbd id="mmkmi"></kbd></noscript>
  • <table id="mmkmi"><source id="mmkmi"></source></table>
  • 三上悠亚在线观看