module(...,package.seeall)

require"aliyuniotssl"

--ϴkeysecretûԼڰϴĿԼĿϢ޸ֵ
local PRODUCT_KEY,PRODUCT_SECRET = "1000163201","4K8nYcT4Wiannoev"
--Ϣ⣬ҪDEVICE_NAMEDEVICE_SECRET
--libлʹ豸IMEISNDEVICE_NAMEDEVICE_SECRETڰ豸ʱDEVICE_NAMEIMEIȻɵDEVICE_SECRETSNд豸

local qos1cnt = 1

--[[
print
  ӡӿڣļедӡaliyuniotǰ׺
  
ֵ
]]
local function print(...)
	_G.print("test",...)
end

--[[
pubqos1testackcb
  1qosΪ1ϢյPUBACKĻص
  
		usertagmqttclient:publishʱusertag
		resulttrueʾɹfalsenilʾʧ
ֵ
]]
local function pubqos1testackcb(usertag,result)
	print("pubqos1testackcb",usertag,result)
	sys.timer_start(pubqos1test,20000)
	qos1cnt = qos1cnt+1
end

--[[
pubqos1test
  1qosΪ1Ϣ
  
ֵ
]]
function pubqos1test()
	--ע⣺ڴ˴Լȥpayloadݱ룬aliyuniotвpayloadκαת
	aliyuniotssl.publish("/"..PRODUCT_KEY.."/"..misc.getimei().."/update","qos1data",1,pubqos1testackcb,"publish1test_"..qos1cnt)
end

--[[
subackcb
  MQTT SUBSCRIBE֮յSUBACKĻص
  
		usertagmqttclient:subscribeʱusertag
		resulttrueʾĳɹfalsenilʾʧ
ֵ
]]
local function subackcb(usertag,result)
	print("subackcb",usertag,result)
end

--[[
rcvmessage
  յPUBLISHϢʱĻص
  
		topicϢ⣨gb2312룩
		payloadϢأԭʼ룬յpayloadʲôݣʲôݣûκαת
		qosϢȼ
ֵ
]]
local function rcvmessagecb(topic,payload,qos)
	print("rcvmessagecb",topic,payload,qos)
	aliyuniotssl.publish("/"..PRODUCT_KEY.."/"..misc.getimei().."/update","device receive:"..payload,qos)
end

--[[
connectedcb
  MQTT CONNECTɹص
  		
ֵ
]]
local function connectedcb()
	print("connectedcb")
	--
	aliyuniotssl.subscribe({{topic="/"..PRODUCT_KEY.."/"..misc.getimei().."/get",qos=0}, {topic="/"..PRODUCT_KEY.."/"..misc.getimei().."/get",qos=1}}, subackcb, "subscribegetopic")
	--ע¼ĻصMESSAGE¼ʾյPUBLISHϢ
	aliyuniotssl.regevtcb({MESSAGE=rcvmessagecb})
	--һqosΪ1Ϣ
	pubqos1test()
end

--[[
connecterrcb
  MQTT CONNECTʧܻص
  
		rʧԭֵ
			1Connection Refused: unacceptable protocol version
			2Connection Refused: identifier rejected
			3Connection Refused: server unavailable
			4Connection Refused: bad user name or password
			5Connection Refused: not authorized
ֵ
]]
local function connecterrcb(r)
	print("connecterrcb",r)
end

aliyuniotssl.config(PRODUCT_KEY,PRODUCT_SECRET)
aliyuniotssl.regcb(connectedcb,connecterrcb)
