--ģ,
local base = _G
local string = require"string"
local sys  = require"sys"
local mqtt = require"mqtt"
require"aliyuniotauth"
module(...,package.seeall)

--mqttͻ˶,ݷַ,ݷ˿ڱ
local mqttclient,gaddr,gports,gclientid,gusername
--Ŀǰʹõgportеindex
local gportidx = 1
local gconnectedcb,gconnecterrcb

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

--[[
sckerrcb
  SOCKETʧܻص
  
		rstringͣʧԭֵ
			CONNECTmqttڲsocketһֱʧܣٳԶ
ֵ
]]
local function sckerrcb(r)
	print("sckerrcb",r,gportidx,#gports)
	if r=="CONNECT" then
		if gportidx<#gports then
			gportidx = gportidx+1
			connect(true)
		else
			sys.restart("aliyuniot sck connect err")
		end
	end
end

function connect(change)
	if change then
		mqttclient:change("TCP",gaddr,gports[gportidx])
	else
		--һmqtt client
		mqttclient = mqtt.create("TCP",gaddr,gports[gportidx])
	end
	--,Ҫһд룬ҸԼwill
	--mqttclient:configwill(1,0,0,"/willtopic","will payload")
	--mqtt
	mqttclient:connect(gclientid,240,gusername,"",gconnectedcb,gconnecterrcb,sckerrcb)
end

--[[
databgn
  Ȩ֤ɹ豸ݷ
  		
ֵ
]]
local function databgn(host,ports,clientid,username)
	gaddr,gports,gclientid,gusername = host or gaddr,ports or gports,clientid,username
	gportidx = 1
	connect()
end

local procer =
{
	ALIYUN_DATA_BGN = databgn,
}

sys.regapp(procer)


--[[
config
  ðƷϢ豸Ϣ
  
		productkeystringͣƷʶѡ
		productsecretstringͣƷԿѡ
ֵ
]]
function config(productkey,productsecret)
	sys.dispatch("ALIYUN_AUTH_BGN",productkey,productsecret)
end

function regcb(connectedcb,connecterrcb)
	gconnectedcb,gconnecterrcb = connectedcb,connecterrcb
end

function subscribe(topics,ackcb,usertag)
	mqttclient:subscribe(topics,ackcb,usertag)
end

function regevtcb(evtcbs)
	mqttclient:regevtcb(evtcbs)
end

function publish(topic,payload,qos,ackcb,usertag)
	mqttclient:publish(topic,payload,qos,ackcb,usertag)
end
