extalk.lua 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. --[[
  2. @module extalk
  3. @summary extalk扩展库
  4. @version 1.1.1
  5. @date 2025.09.18
  6. @author 梁健
  7. @usage
  8. local extalk = require "extalk"
  9. -- 配置并初始化
  10. extalk.setup({
  11. key = "your_product_key",
  12. heart_break_time = 30,
  13. contact_list_cbfnc = function(dev_list) end,
  14. state_cbfnc = function(state) end
  15. })
  16. -- 发起对讲
  17. extalk.start("remote_device_id")
  18. -- 结束对讲
  19. extalk.stop()
  20. ]]
  21. local extalk = {}
  22. -- 模块常量(保留原始数据结构)
  23. extalk.START = 1 -- 通话开始
  24. extalk.STOP = 2 -- 通话结束
  25. extalk.UNRESPONSIVE = 3 -- 未响应
  26. extalk.ONE_ON_ONE = 5 -- 一对一来电
  27. extalk.BROADCAST = 6 -- 广播
  28. local AIRTALK_TASK_NAME = "airtalk_task"
  29. -- 消息类型常量(保留原始数据结构)
  30. local MSG_CONNECT_ON_IND = 0
  31. local MSG_CONNECT_OFF_IND = 1
  32. local MSG_AUTH_IND = 2
  33. local MSG_SPEECH_ON_IND = 3
  34. local MSG_SPEECH_OFF_IND = 4
  35. local MSG_SPEECH_CONNECT_TO = 5
  36. local MSG_SPEECH_STOP_TEST_END = 22
  37. -- 设备状态常量(保留原始数据结构)
  38. local SP_T_NO_READY = 0 -- 离线状态无法对讲
  39. local SP_T_IDLE = 1 -- 对讲空闲状态
  40. local SP_T_CONNECTING = 2 -- 主动发起对讲
  41. local SP_T_CONNECTED = 3 -- 对讲中
  42. local SUCC = "success"
  43. -- 全局状态变量(保留原始数据结构)
  44. local g_state = SP_T_NO_READY -- 设备状态
  45. local g_mqttc = nil -- mqtt客户端
  46. local g_local_id -- 本机ID
  47. local g_remote_id -- 对端ID
  48. local g_s_type -- 对讲的模式,字符串形式
  49. local g_s_topic -- 对讲用的topic
  50. local g_s_mode -- 对讲的模式
  51. local g_dev_list -- 对讲列表
  52. local g_dl_topic -- 下行消息topic模板
  53. -- 配置参数
  54. local extalk_configs_local = {
  55. key = 0, -- 项目key,一般需要和main的PRODUCT_KEY保持一致
  56. heart_break_time = 0, -- 心跳间隔(单位秒)
  57. contact_list_cbfnc = nil, -- 联系人回调函数,含设备号和昵称
  58. state_cbfnc = nil, -- 状态回调,分为对讲开始,对讲结束,未响应
  59. }
  60. -- 工具函数:参数检查
  61. local function check_param(param, expected_type, name)
  62. if type(param) ~= expected_type then
  63. log.error(string.format("参数错误: %s 应为 %s 类型,实际为 %s",
  64. name, expected_type, type(param)))
  65. return false
  66. end
  67. return true
  68. end
  69. -- 发送鉴权消息
  70. local function auth()
  71. if g_state == SP_T_NO_READY and g_mqttc then
  72. local topic = string.format("ctrl/uplink/%s/0001", g_local_id)
  73. local payload = json.encode({
  74. ["key"] = extalk_configs_local.key,
  75. ["device_type"] = 1
  76. })
  77. g_mqttc:publish(topic, payload)
  78. end
  79. end
  80. -- 发送心跳消息
  81. local function heart()
  82. if g_state == SP_T_CONNECTED and g_mqttc then
  83. local topic = string.format("ctrl/uplink/%s/0005", g_local_id)
  84. local payload = json.encode({
  85. ["from"] = g_local_id,
  86. ["to"] = g_remote_id
  87. })
  88. g_mqttc:publish(topic, payload)
  89. end
  90. end
  91. -- 开始对讲
  92. local function speech_on(ssrc, sample)
  93. g_state = SP_T_CONNECTED
  94. g_mqttc:subscribe(g_s_topic)
  95. airtalk.set_topic(g_s_topic)
  96. airtalk.set_ssrc(ssrc)
  97. log.info("对讲模式", g_s_mode)
  98. airtalk.speech(true, g_s_mode, sample)
  99. sys.sendMsg(AIRTALK_TASK_NAME, MSG_SPEECH_ON_IND, true)
  100. sys.timerLoopStart(heart, extalk_configs_local.heart_break_time * 1000)
  101. sys.timerStopAll(wait_speech_to)
  102. end
  103. -- 结束对讲
  104. local function speech_off(need_upload, need_ind)
  105. if g_state == SP_T_CONNECTED then
  106. g_mqttc:unsubscribe(g_s_topic)
  107. airtalk.speech(false)
  108. g_s_topic = nil
  109. end
  110. g_state = SP_T_IDLE
  111. sys.timerStopAll(auth)
  112. sys.timerStopAll(heart)
  113. sys.timerStopAll(wait_speech_to)
  114. if need_upload and g_mqttc then
  115. local topic = string.format("ctrl/uplink/%s/0004", g_local_id)
  116. g_mqttc:publish(topic, json.encode({["to"] = g_remote_id}))
  117. end
  118. if need_ind then
  119. sys.sendMsg(AIRTALK_TASK_NAME, MSG_SPEECH_OFF_IND, true)
  120. end
  121. end
  122. -- 对讲超时处理
  123. local function wait_speech_to()
  124. log.info("主动请求对讲超时无应答")
  125. speech_off(true, false)
  126. end
  127. -- 命令处理:请求对讲应答
  128. local function handle_speech_response(obj)
  129. if g_state ~= SP_T_CONNECTING then
  130. log.error("state", g_state, "need", SP_T_CONNECTING)
  131. return
  132. end
  133. if obj and obj["result"] == SUCC and g_s_topic == obj["topic"] then
  134. -- 开始对讲
  135. local sample_rate = obj["audio_code"] == "amr-nb" and 8000 or 16000
  136. speech_on(obj["ssrc"], sample_rate)
  137. return
  138. else
  139. log.info(obj["result"], obj["topic"], g_s_topic)
  140. sys.sendMsg(AIRTALK_TASK_NAME, MSG_SPEECH_ON_IND, false)
  141. end
  142. g_s_topic = nil
  143. g_state = SP_T_IDLE
  144. end
  145. -- 命令处理:对端来电
  146. local function handle_incoming_call(obj)
  147. if not obj or not obj["topic"] or not obj["ssrc"] or not obj["audio_code"] or not obj["type"] then
  148. local response = {
  149. ["result"] = "failed",
  150. ["topic"] = obj and obj["topic"] or "",
  151. ["info"] = "无效的请求参数"
  152. }
  153. g_mqttc:publish(string.format("ctrl/uplink/%s/8102", g_local_id), json.encode(response))
  154. return
  155. end
  156. -- 非空闲状态无法接收来电
  157. if g_state ~= SP_T_IDLE then
  158. log.error("state", g_state, "need", SP_T_IDLE)
  159. local response = {
  160. ["result"] = "failed",
  161. ["topic"] = obj["topic"],
  162. ["info"] = "device is busy"
  163. }
  164. g_mqttc:publish(string.format("ctrl/uplink/%s/8102", g_local_id), json.encode(response))
  165. return
  166. end
  167. local response, from = {}, nil
  168. -- 提取对端ID
  169. from = string.match(obj["topic"], "audio/(.*)/.*/.*")
  170. if not from then
  171. response = {
  172. ["result"] = "failed",
  173. ["topic"] = obj["topic"],
  174. ["info"] = "topic error"
  175. }
  176. g_mqttc:publish(string.format("ctrl/uplink/%s/8102", g_local_id), json.encode(response))
  177. return
  178. end
  179. -- 处理一对一通话
  180. if obj["type"] == "one-on-one" then
  181. g_s_topic = obj["topic"]
  182. g_remote_id = from
  183. g_s_type = "one-on-one"
  184. g_s_mode = airtalk.MODE_PERSON
  185. -- 触发回调
  186. if extalk_configs_local.state_cbfnc then
  187. extalk_configs_local.state_cbfnc({
  188. state = extalk.ONE_ON_ONE,
  189. id = from
  190. })
  191. end
  192. response = {["result"] = SUCC, ["topic"] = obj["topic"], ["info"] = ""}
  193. local sample_rate = obj["audio_code"] == "amr-nb" and 8000 or 16000
  194. speech_on(obj["ssrc"], sample_rate)
  195. end
  196. -- 处理广播
  197. if obj["type"] == "broadcast" then
  198. g_s_topic = obj["topic"]
  199. g_remote_id = from
  200. g_s_mode = airtalk.MODE_GROUP_LISTENER
  201. g_s_type = "broadcast"
  202. -- 触发回调
  203. if extalk_configs_local.state_cbfnc then
  204. extalk_configs_local.state_cbfnc({
  205. state = extalk.BROADCAST,
  206. id = from
  207. })
  208. end
  209. response = {["result"] = SUCC, ["topic"] = obj["topic"], ["info"] = ""}
  210. local sample_rate = obj["audio_code"] == "amr-nb" and 8000 or 16000
  211. speech_on(obj["ssrc"], sample_rate)
  212. end
  213. -- 发送响应
  214. g_mqttc:publish(string.format("ctrl/uplink/%s/8102", g_local_id), json.encode(response))
  215. end
  216. -- 命令处理:对端挂断
  217. local function handle_remote_hangup(obj)
  218. local response = {}
  219. if g_state == SP_T_IDLE then
  220. response = {["result"] = "failed", ["info"] = "no speech"}
  221. else
  222. log.info("0103", obj, obj["type"], g_s_type)
  223. if obj and obj["type"] == g_s_type then
  224. response = {["result"] = SUCC, ["info"] = ""}
  225. speech_off(false, true)
  226. else
  227. response = {["result"] = "failed", ["info"] = "type mismatch"}
  228. end
  229. end
  230. g_mqttc:publish(string.format("ctrl/uplink/%s/8103", g_local_id), json.encode(response))
  231. end
  232. -- 命令处理:更新设备列表
  233. local function handle_device_list_update(obj)
  234. local response = {}
  235. if obj then
  236. g_dev_list = obj["dev_list"]
  237. response = {["result"] = SUCC, ["info"] = ""}
  238. else
  239. response = {["result"] = "failed", ["info"] = "json info error"}
  240. end
  241. g_mqttc:publish(string.format("ctrl/uplink/%s/8101", g_local_id), json.encode(response))
  242. end
  243. -- 命令处理:鉴权结果
  244. local function handle_auth_result(obj)
  245. if obj and obj["result"] == SUCC then
  246. g_mqttc:publish(string.format("ctrl/uplink/%s/0002", g_local_id), "") -- 更新列表
  247. else
  248. sys.sendMsg(AIRTALK_TASK_NAME, MSG_AUTH_IND, false,
  249. "鉴权失败" .. (obj and obj["info"] or ""))
  250. end
  251. end
  252. -- 命令处理:设备列表更新应答
  253. local function handle_device_list_response(obj)
  254. if obj and obj["result"] == SUCC then
  255. g_dev_list = obj["dev_list"]
  256. if extalk_configs_local.contact_list_cbfnc then
  257. extalk_configs_local.contact_list_cbfnc(g_dev_list)
  258. end
  259. g_state = SP_T_IDLE
  260. sys.sendMsg(AIRTALK_TASK_NAME, MSG_AUTH_IND, true) -- 完整登录流程结束
  261. else
  262. sys.sendMsg(AIRTALK_TASK_NAME, MSG_AUTH_IND, false, "更新设备列表失败")
  263. end
  264. end
  265. -- 命令解析路由表
  266. local cmd_handlers = {
  267. ["8003"] = handle_speech_response, -- 请求对讲应答
  268. ["0102"] = handle_incoming_call, -- 平台通知对端对讲开始
  269. ["0103"] = handle_remote_hangup, -- 平台通知终端对讲结束
  270. ["0101"] = handle_device_list_update,-- 平台通知终端更新对讲设备列表
  271. ["8001"] = handle_auth_result, -- 平台对鉴权应答
  272. ["8002"] = handle_device_list_response -- 平台对终端获取终端列表应答
  273. }
  274. -- 解析接收到的消息
  275. local function analyze_v1(cmd, topic, obj)
  276. -- 忽略心跳和结束对讲的应答
  277. if cmd == "8005" or cmd == "8004" then
  278. return
  279. end
  280. -- 查找并执行对应的命令处理器
  281. local handler = cmd_handlers[cmd]
  282. if handler then
  283. handler(obj)
  284. else
  285. log.warn("未处理的命令", cmd)
  286. end
  287. end
  288. -- MQTT回调处理
  289. local function mqtt_cb(mqttc, event, topic, payload)
  290. log.info(event, topic or "")
  291. if event == "conack" then
  292. -- MQTT连接成功,开始自定义鉴权流程
  293. sys.sendMsg(AIRTALK_TASK_NAME, MSG_CONNECT_ON_IND)
  294. g_mqttc:subscribe("ctrl/downlink/" .. g_local_id .. "/#")
  295. elseif event == "suback" then
  296. if g_state == SP_T_NO_READY then
  297. if topic then
  298. auth()
  299. else
  300. sys.sendMsg(AIRTALK_TASK_NAME, MSG_AUTH_IND, false,
  301. "订阅失败" .. "ctrl/downlink/" .. g_local_id .. "/#")
  302. end
  303. elseif g_state == SP_T_CONNECTED and not topic then
  304. speech_off(false, true)
  305. end
  306. elseif event == "recv" then
  307. local result = string.match(topic, g_dl_topic)
  308. if result then
  309. local obj = json.decode(payload)
  310. analyze_v1(result, topic, obj)
  311. end
  312. elseif event == "disconnect" then
  313. speech_off(false, true)
  314. g_state = SP_T_NO_READY
  315. elseif event == "error" then
  316. log.error("MQTT错误发生")
  317. end
  318. end
  319. -- 任务消息处理
  320. local function task_cb(msg)
  321. if msg[1] == MSG_SPEECH_CONNECT_TO then
  322. speech_off(true, false)
  323. else
  324. log.info("未处理消息", msg[1], msg[2], msg[3], msg[4])
  325. end
  326. end
  327. -- 对讲事件回调
  328. local function airtalk_event_cb(event, param)
  329. log.info("airtalk event", event, param)
  330. if event == airtalk.EVENT_ERROR then
  331. if param == airtalk.ERROR_NO_DATA then
  332. log.error("长时间没有收到音频数据")
  333. speech_off(true, true)
  334. end
  335. end
  336. end
  337. -- MQTT任务主循环
  338. local function airtalk_mqtt_task()
  339. local msg, online = nil, false
  340. -- 初始化本地ID
  341. g_local_id = mobile.imei()
  342. g_dl_topic = "ctrl/downlink/" .. g_local_id .. "/(%w%w%w%w)"
  343. -- 创建MQTT客户端
  344. g_mqttc = mqtt.create(nil, "mqtt.airtalk.luatos.com", 1883, false, {rxSize = 32768})
  345. -- 配置对讲参数
  346. airtalk.config(airtalk.PROTOCOL_MQTT, g_mqttc, 200) -- 缓冲至少200ms播放
  347. airtalk.on(airtalk_event_cb)
  348. airtalk.start()
  349. -- 配置MQTT客户端
  350. g_mqttc:auth(g_local_id, g_local_id, mobile.muid())
  351. g_mqttc:keepalive(240) -- 默认值240s
  352. g_mqttc:autoreconn(true, 15000) -- 自动重连机制
  353. g_mqttc:debug(false)
  354. g_mqttc:on(mqtt_cb)
  355. log.info("设备信息", g_local_id, mobile.muid())
  356. -- 开始连接
  357. g_mqttc:connect()
  358. online = false
  359. while true do
  360. -- 等待MQTT连接成功
  361. msg = sys.waitMsg(AIRTALK_TASK_NAME, MSG_CONNECT_ON_IND)
  362. log.info("connected")
  363. -- 处理登录流程
  364. while not online do
  365. msg = sys.waitMsg(AIRTALK_TASK_NAME, MSG_AUTH_IND, 30000) -- 30秒超时
  366. if type(msg) == 'table' then
  367. online = msg[2]
  368. if online then
  369. -- 鉴权通过,60分钟后重新鉴权
  370. sys.timerLoopStart(auth, 3600000)
  371. else
  372. log.info(msg[3])
  373. -- 鉴权失败,5分钟后重试
  374. sys.timerLoopStart(auth, 300000)
  375. end
  376. else
  377. -- 超时未收到鉴权结果,重新发送
  378. auth()
  379. end
  380. end
  381. log.info("对讲管理平台已连接")
  382. -- 处理在线状态下的消息
  383. while online do
  384. msg = sys.waitMsg(AIRTALK_TASK_NAME)
  385. if type(msg) == 'table' and type(msg[1]) == "number" then
  386. if msg[1] == MSG_SPEECH_STOP_TEST_END then
  387. if g_state ~= SP_T_CONNECTING and g_state ~= SP_T_CONNECTED then
  388. log.info("没有对讲", g_state)
  389. else
  390. speech_off(true, false)
  391. end
  392. elseif msg[1] == MSG_SPEECH_ON_IND then
  393. if extalk_configs_local.state_cbfnc then
  394. local state = msg[2] and extalk.START or extalk.UNRESPONSIVE
  395. extalk_configs_local.state_cbfnc({state = state})
  396. end
  397. elseif msg[1] == MSG_SPEECH_OFF_IND then
  398. if extalk_configs_local.state_cbfnc then
  399. extalk_configs_local.state_cbfnc({state = extalk.STOP})
  400. end
  401. elseif msg[1] == MSG_CONNECT_OFF_IND then
  402. log.info("connect", msg[2])
  403. online = msg[2]
  404. end
  405. else
  406. log.info(type(msg), type(msg and msg[1]))
  407. end
  408. msg = nil -- 清理引用
  409. end
  410. online = false -- 重置在线状态
  411. end
  412. end
  413. -- 模块初始化
  414. function extalk.setup(extalk_configs)
  415. if not extalk_configs or type(extalk_configs) ~= "table" then
  416. log.error("AirTalk配置必须为table类型")
  417. return false
  418. end
  419. -- 检查配置参数
  420. if not check_param(extalk_configs.key, "string", "key") then
  421. return false
  422. end
  423. extalk_configs_local.key = extalk_configs.key
  424. if not check_param(extalk_configs.heart_break_time, "number", "heart_break_time") then
  425. return false
  426. end
  427. extalk_configs_local.heart_break_time = extalk_configs.heart_break_time
  428. if not check_param(extalk_configs.contact_list_cbfnc, "function", "contact_list_cbfnc") then
  429. return false
  430. end
  431. extalk_configs_local.contact_list_cbfnc = extalk_configs.contact_list_cbfnc
  432. if not check_param(extalk_configs.state_cbfnc, "function", "state_cbfnc") then
  433. return false
  434. end
  435. extalk_configs_local.state_cbfnc = extalk_configs.state_cbfnc
  436. -- 启动任务
  437. sys.taskInitEx(airtalk_mqtt_task, AIRTALK_TASK_NAME, task_cb)
  438. return true
  439. end
  440. -- 开始对讲
  441. function extalk.start(id)
  442. if g_state ~= SP_T_IDLE then
  443. log.warn("正在对讲无法开始,当前状态:", g_state)
  444. return false
  445. end
  446. if id == nil then
  447. -- 广播模式
  448. g_remote_id = "all"
  449. g_state = SP_T_CONNECTING
  450. g_s_mode = airtalk.MODE_GROUP_SPEAKER
  451. g_s_type = "broadcast"
  452. g_s_topic = string.format("audio/%s/all/%s",
  453. g_local_id, string.sub(tostring(mcu.ticks()), -4, -1))
  454. g_mqttc:publish(string.format("ctrl/uplink/%s/0003", g_local_id),
  455. json.encode({["topic"] = g_s_topic, ["type"] = g_s_type}))
  456. sys.timerStart(wait_speech_to, 15000)
  457. else
  458. -- 一对一模式
  459. log.info("向", id, "主动发起对讲")
  460. if id == g_local_id then
  461. log.error("不允许本机给本机拨打电话")
  462. return false
  463. end
  464. g_state = SP_T_CONNECTING
  465. g_remote_id = id
  466. g_s_mode = airtalk.MODE_PERSON
  467. g_s_type = "one-on-one"
  468. g_s_topic = string.format("audio/%s/%s/%s",
  469. g_local_id, id, string.sub(tostring(mcu.ticks()), -4, -1))
  470. g_mqttc:publish(string.format("ctrl/uplink/%s/0003", g_local_id),
  471. json.encode({["topic"] = g_s_topic, ["type"] = g_s_type}))
  472. sys.timerStart(wait_speech_to, 15000)
  473. end
  474. return true
  475. end
  476. -- 结束对讲
  477. function extalk.stop()
  478. if g_state ~= SP_T_CONNECTING and g_state ~= SP_T_CONNECTED then
  479. log.info("没有对讲,当前状态:", g_state)
  480. return false
  481. end
  482. log.info("主动断开对讲")
  483. speech_off(true, false)
  484. return true
  485. end
  486. return extalk