--[[
ģƣsim
ģ鹦ܣѯsim״̬iccidimsimccmnc
ģ޸ʱ䣺2017.02.13
]]

--ģ,
local string = require"string"
local ril = require"ril"
local sys = require"sys"
local base = _G
local os = require"os"
module(...)

--سõȫֺ
local tonumber = base.tonumber
local tostring = base.tostring
local req = ril.request

--simimsisimiccid
local imsi,iccid,status

--[[
geticcid
  ȡsimiccid
  
ֵiccidûжȡ򷵻nil
ע⣺luaű֮󣬻ᷢatȥѯiccidҪһʱܻȡiccidô˽ӿڣϷnil
]]
function geticcid()
	return iccid
end

--[[
getimsi
  ȡsimimsi
  
ֵimsiûжȡ򷵻nil
ע⣺luaű֮󣬻ᷢatȥѯimsiҪһʱܻȡimsiô˽ӿڣϷnil
]]
function getimsi()
	return imsi
end

--[[
getmcc
  ȡsimmcc
  
ֵmccûжȡ򷵻""
ע⣺luaű֮󣬻ᷢatȥѯimsiҪһʱܻȡimsiô˽ӿڣϷ""
]]
function getmcc()
	return (imsi ~= nil and imsi ~= "") and string.sub(imsi,1,3) or ""
end

--[[
getmnc
  ȡsimgetmnc
  
ֵmncûжȡ򷵻""
ע⣺luaű֮󣬻ᷢatȥѯimsiҪһʱܻȡimsiô˽ӿڣϷ""
]]
function getmnc()
	return (imsi ~= nil and imsi ~= "") and string.sub(imsi,4,5) or ""
end

--[[
getstatus
  ȡsim״̬
  
ֵtrueʾsimfalsenilʾδ⵽߿쳣
ע⣺luaű֮󣬻ᷢatȥѯ״̬Ҫһʱܻȡ״̬ô˽ӿڣϷnil
]]
function getstatus()
	return status
end

--[[
rsp
  ģڡͨ⴮ڷ͵ײcoreATӦ
  
		cmdӦӦAT
		successATִнtruefalse
		responseATӦеִнַ
		intermediateATӦемϢ
ֵ
]]
local function rsp(cmd,success,response,intermediate)
	if cmd == "AT+CCID" then
		iccid = intermediate
	elseif cmd == "AT+CIMI" then
		imsi = intermediate
		--һڲϢIMSI_READY֪ͨѾȡimsi
		sys.dispatch("IMSI_READY")
	end
end

--[[
urc
  ģڡעĵײcoreͨ⴮ϱ֪ͨĴ
  
		dataַ֪ͨϢ
		prefix֪ͨǰ׺
ֵ
]]
local function urc(data,prefix)
	--sim״̬֪ͨ
	if prefix == "+CPIN" then
		status = false
		--sim
		if data == "+CPIN: READY" then
			status = true
			req("AT+CCID")
			req("AT+CIMI")
			sys.dispatch("SIM_IND","RDY")
		--δ⵽sim
		elseif data == "+CPIN: NOT INSERTED" then
			sys.dispatch("SIM_IND","NIST")
		else
			--simpin
			if data == "+CPIN: SIM PIN" then
				sys.dispatch("SIM_IND_SIM_PIN")	
			end
			sys.dispatch("SIM_IND","NORDY")
		end
	end
end

--עAT+CCIDӦ
ril.regrsp("+CCID",rsp)
--עAT+CIMIӦ
ril.regrsp("+CIMI",rsp)
--ע+CPIN֪ͨĴ
ril.regurc("+CPIN",urc)
