self._st_signal = "normal" # normal/weak
self._timer = osTimer()
- self._mode = "off" # off/red_on/green_on/blue_blink/red_blink/bg_alt
+ self._mode = "off" # off/red_on/green_on/green_blink/blue_blink/red_blink/bg_alt
self._blink_on = 0
self._bg_phase = 0
self._period_ms = 1000
EventMesh.subscribe("set_led_state", self.set_led_state)
EventMesh.subscribe("get_led_debug_state", self.get_led_debug_state)
- try:
- self._set_off()
- except Exception:
- pass
# LED 电平极性:有些板子是低电平点亮(active-low),也可能仅某一路反相
self._inv_r = 0
self._inv_g = 0
self._inv_b = all_inv
except Exception:
pass
+ try:
+ self._apply_by_table()
+ except Exception:
+ try:
+ self._set_off()
+ except Exception:
+ pass
def _timer_stop(self):
try:
self._timer_stop()
self._set_rgb(0, 1, 0)
+ def _set_green_blink(self, period_ms=1000):
+ """待机/空闲:绿灯慢闪(替代呼吸灯,数字 GPIO 整颗亮灭)。"""
+ period_ms = period_ms or 1000
+ try:
+ if self._mode == "green_blink" and int(self._period_ms) == int(period_ms):
+ return
+ except Exception:
+ pass
+ self._mode = "green_blink"
+ self._period_ms = period_ms
+ self._blink_on = 1
+ self._timer_stop()
+ self._set_rgb(0, 1, 0)
+ self._timer.start(self._period_ms, 1, self._timer_cb)
+
def _set_blue_blink(self, period_ms=1000):
self._mode = "blue_blink"
self._period_ms = period_ms or 1000
EventMesh.publish("publish_AI_btnInfo", {"func": self._timer_cb_})
def _timer_cb_(self):
+ if self._mode == "green_blink":
+ self._blink_on = 0 if self._blink_on else 1
+ self._set_rgb(0, 1 if self._blink_on else 0, 0)
+ return
if self._mode == "blue_blink":
self._blink_on = 0 if self._blink_on else 1
self._set_rgb(0, 0, 1 if self._blink_on else 0)
self._set_green_on()
return
if self._st_ai == "thinking":
- self._set_bg_alt(1000)
+ # 蓝绿「交替」:约 0.5 s 换一色(`period_ms` 为换色间隔)
+ self._set_bg_alt(500)
return
if self._st_ai == "listening":
+ # 「慢闪」:整颗亮灭整周期约 2×period_ms → period_ms=1000 约 2 s 一亮灭
self._set_blue_blink(1000)
return
except Exception:
pass
+ # AI 会话或流播放中:ai_state 短暂 idle 时仍不让充电红/充满绿抢占(低电/弱网仍走后面分支)
+ _skip_charge_led = 0
+ try:
+ if EventMesh.publish("get_VC_satrt_flag") == 1:
+ _skip_charge_led = 1
+ except Exception:
+ pass
+ if not _skip_charge_led:
+ try:
+ if EventMesh.publish("get_vc_stream_active") == 1:
+ _skip_charge_led = 1
+ except Exception:
+ pass
# 基础态:充电/电量/信号
try:
- if self._st_charging == "full":
- self._set_green_on()
- return
- if self._st_charging == "charging":
- self._set_red_on()
- return
+ if not _skip_charge_led:
+ if self._st_charging == "full":
+ self._set_green_on()
+ return
+ if self._st_charging == "charging":
+ self._set_red_on()
+ return
if self._st_battery in ("empty", "low"):
self._set_red_blink(1000)
return
if self._st_signal == "weak":
- self._set_bg_alt(2000)
+ # 弱网:蓝绿「慢交替」,与 thinking 同节拍定义(约 1 s 换一色)
+ self._set_bg_alt(1000)
return
except Exception:
pass
- self._set_off()
+ # 空闲待机:绿灯慢闪(整周期约 2×idle_ms,默认对齐「慢闪 ≈2 s 一亮灭」)
+ try:
+ idle_ms = 1000
+ if "vc_config" in globals() and vc_config:
+ idle_ms = int(vc_config.get_int("LED_IDLE_GREEN_BLINK_MS", 1000))
+ if idle_ms < 400:
+ idle_ms = 400
+ self._set_green_blink(idle_ms)
+ except Exception:
+ self._set_green_blink(1000)
def get_led_debug_state(self, event=None, msg=None):
# 供按键/状态机打印当前 LED 聚合状态与最终模式
self.KeyAI_long_press = 1
#EventMesh.publish("AI_key_long_press")
EventMesh.publish("publish_AI_btnInfo",{"func":self.AI_key_long_press})
- if self.KeyAI_timer_count >= 10*3 : #长按3s 上一次是短按则拨打sos紧急联系人
+ try:
+ _sos_on = vc_config.get_bool("SOS_ENABLED", True)
+ except Exception:
+ _sos_on = True
+ if _sos_on and self.KeyAI_timer_count >= 10*3 : #长按3s 上一次是短按则拨打sos紧急联系人
print("long sos phone:{}".format(self.KeySOS_timer_flag))
if self.KeySOS_timer_flag == 1:
print("KeySOS_timer_flag!!!!!!!!!!!!!!!") #短按两次需要清除标识
if self.KeyAI_long_press == 0:
- if self.KeySOS_timer_flag == 0:
+ try:
+ _sos_on = vc_config.get_bool("SOS_ENABLED", True)
+ except Exception:
+ _sos_on = True
+ if _sos_on and self.KeySOS_timer_flag == 0:
self.KeySOS_timer_flag = 1
self.KeySos_long_press = 0
self.KeySOS_timer.start(5000, 0, self.KeySos_timer_cb) #短按开启5s定时器 5s之内没有长按3s则清除标识 长按3s拨打sos紧急联系人
usys.print_exception(e)
if response != None:
response.close()
-#阿里VC状态枚举
-VC_State_None=0
-VC_State_Listening=1#听
-VC_State_SpeechStart=2#说开始
-VC_State_SpeechIng=3#正在说
-VC_State_SpeechEnd=4#说结束
-VC_State_RequestToRespond=5 #TTS请求或者chat请求
-VC_State_Thinking=6#想(chat)
-VC_State_Responding=7#音频播放
-VC_State_TTSStart=8
-VC_State_TTSData=9
-VC_State_TTSFinish=10
-VC_State_TTSEnd=11
-VC_State_TTSError=12
-VC_State_DialogError=13
-VC_State_End=14
+# 原 VC_State_* 整型已移除;会话/轮次见 VCTurnState / VCStateMachine(含 tts_rx_phase、speech_uplink_open)。
VC_record_TYPE_PCM = 0
VC_record_TYPE_AMR = 1
AwaitPlayedAck = 7
+class VC_TtsRxPhase:
+ Idle = 0
+ Started = 1
+ ServerCompleted = 2
+
+
class VCMode:
Realtime = 0 # VAD on(长对话,协议:无需 audio.create/completed)
PushToTalk = 1 # VAD off(单对话,协议:必须 audio.create/completed 包裹音频帧)
self.last_tts_pending_ms = 0
self.await_played = False
self.last_tts_completed_ms = 0
+ self.tts_rx_phase = VC_TtsRxPhase.Idle
+ self.speech_uplink_open = 0
+
+ def reset_rx_phases(self):
+ self.tts_rx_phase = VC_TtsRxPhase.Idle
+ self.speech_uplink_open = 0
+
+ def mark_tts_rx_idle(self):
+ self.tts_rx_phase = VC_TtsRxPhase.Idle
+
+ def on_server_asr_started(self):
+ if self.session == VCSessionState.Started:
+ self.speech_uplink_open = 1
+ self.log("server.asr.started")
def _turn_name(self, t):
try:
def log(self, reason=""):
# 只用于关键节点的单行状态日志,便于串口快速定位状态漂移
try:
- print("[FSM] {} session={} turn={} await_played={}".format(
+ print("[FSM] {} session={} turn={} await_played={} tts_rx={} speech_up={}".format(
reason,
self._session_name(self.session),
self._turn_name(self.turn),
1 if self.await_played else 0,
+ int(self.tts_rx_phase),
+ 1 if self.speech_uplink_open else 0,
))
except Exception:
pass
self.await_played = False
self.last_tts_completed_ms = 0
self.last_llm_ms = 0
+ self.reset_rx_phases()
def on_server_started(self):
+ self.reset_rx_phases()
self.session = VCSessionState.Started
# 新会话 started:确保进入 Listening,且清理上轮播放门控
self.await_played = False
def on_server_tts_started(self):
if self.session == VCSessionState.Started:
self.turn = VCTurnState.TtsReceiving
+ self.tts_rx_phase = VC_TtsRxPhase.Started
self.log("server.tts.started")
def on_server_tts_completed(self):
if self.session == VCSessionState.Started:
# tts.completed 只表示服务端音频下发结束,本地可能仍在播放;保持 Playing,由 await_played 门控播完上报
self.await_played = True
+ self.tts_rx_phase = VC_TtsRxPhase.ServerCompleted
try:
self.last_tts_completed_ms = utime.ticks_ms()
except Exception:
def on_server_canceled(self):
if self.session == VCSessionState.Started:
self.turn = VCTurnState.Listening
+ self.reset_rx_phases()
self.log("server.canceled")
def on_server_completed(self):
self.turn = VCTurnState.Listening
self.await_played = False
self.last_tts_completed_ms = 0
+ self.mark_tts_rx_idle()
self.log("local.audio_played")
def on_local_play_start(self):
return 1
except Exception:
pass
+ try:
+ if getattr(self.fsm, "tts_rx_phase", VC_TtsRxPhase.Idle) != VC_TtsRxPhase.Idle:
+ return 1
+ except Exception:
+ pass
try:
t = getattr(self.fsm, "turn", VCTurnState.Idle)
- if t in (VCTurnState.TtsReceiving, VCTurnState.Playing):
+ if t in (VCTurnState.TtsReceiving, VCTurnState.Playing, VCTurnState.AwaitPlayedAck):
return 1
except Exception:
pass
pass
return 0
+ def _vc_fsm_log_snip(self):
+ try:
+ f = self.fsm
+ return "sess={} turn={} tts_rx={} await={} sp_up={}".format(
+ int(getattr(f, "session", -1)),
+ int(getattr(f, "turn", -1)),
+ int(getattr(f, "tts_rx_phase", -1)),
+ 1 if getattr(f, "await_played", False) else 0,
+ 1 if getattr(f, "speech_uplink_open", 0) else 0,
+ )
+ except Exception:
+ return "fsm=?"
+
+ def _vc_tts_pipeline_busy(self):
+ try:
+ if getattr(self.fsm, "await_played", False):
+ return True
+ if getattr(self.fsm, "tts_rx_phase", VC_TtsRxPhase.Idle) != VC_TtsRxPhase.Idle:
+ return True
+ t = getattr(self.fsm, "turn", VCTurnState.Idle)
+ if t in (VCTurnState.TtsReceiving, VCTurnState.Playing, VCTurnState.AwaitPlayedAck):
+ return True
+ if getattr(self, "_tts_pending", 0) == 1:
+ return True
+ if getattr(self, "VC_Play_flag", 0) == 1:
+ return True
+ except Exception:
+ pass
+ return False
+
+ def _vc_vad_uplink_stop_eligible(self):
+ # 对应旧 VC_state >= SpeechStart
+ try:
+ if getattr(self.fsm, "speech_uplink_open", 0):
+ return True
+ t = getattr(self.fsm, "turn", VCTurnState.Idle)
+ return t not in (VCTurnState.Idle, VCTurnState.Listening)
+ except Exception:
+ return False
+
+ def _vc_long_idle_active_speech_or_later(self):
+ # 对应旧 VC_state >= SpeechIng
+ try:
+ t = getattr(self.fsm, "turn", VCTurnState.Idle)
+ return t not in (VCTurnState.Idle, VCTurnState.Listening)
+ except Exception:
+ return False
+
# ===== Push-To-Talk(单对话模式)=====
# 语义:
# - 长按:无论当前处于 TTS/Thinking/任何中间态,立即打断并进入新一轮录音上行
self._server_vad_silence = 1
if getattr(self, "VC_record_state_flag", 0) == 0:
+ try:
+ if getattr(self, "VC_mode", 0) != 1:
+ print("[VC][long_idle] _uplink_request_stop skip (record_state==0) reason={}".format(reason))
+ except Exception:
+ pass
return
+ try:
+ if getattr(self, "VC_mode", 0) != 1:
+ print("[VC][long_idle] step=uplink_stop_exec reason={} VC_record_state_flag={}".format(
+ reason, getattr(self, "VC_record_state_flag", -1)))
+ except Exception:
+ pass
print("[VC][uplink_ctrl] Request STOP by {}".format(reason))
self.VC_Speech_End()
self._uplink_active = 1
self._uplink_bytes = 0
self._uplink_start_ms = utime.ticks_ms()
- print("[VC][uplink] START len={} VC_state={} VC_record_state_flag={}".format(
- first_len, self.VC_state, self.VC_record_state_flag))
+ print("[VC][uplink] START len={} {} VC_record_state_flag={}".format(
+ first_len, self._vc_fsm_log_snip(), self.VC_record_state_flag))
except Exception:
pass
if self._uplink_active != 1:
return
dur = utime.ticks_diff(utime.ticks_ms(), self._uplink_start_ms) if self._uplink_start_ms else -1
- print("[VC][uplink] END reason={} bytes={} dur_ms={} VC_state={} VC_record_state_flag={}".format(
- reason, self._uplink_bytes, dur, self.VC_state, self.VC_record_state_flag))
+ print("[VC][uplink] END reason={} bytes={} dur_ms={} {} VC_record_state_flag={}".format(
+ reason, self._uplink_bytes, dur, self._vc_fsm_log_snip(), self.VC_record_state_flag))
except Exception:
pass
self._uplink_active = 0
# if self.AI_VC_send_data_queue_thread_id == 0:
# self.AI_VC_send_data_queue_thread_id = _thread.start_new_thread(self.AI_VC_send_data_queue_thread, ())
- self.VC_state = VC_State_None #阿里ai VC状态
self.VC_dialog_id = ""#
self.VC_message_id=None
self.VC_task_id =None
self.AI_client_VC_isconnect =0
self.AI_client_VC_debug =0
- self.asr_state = VC_State_None #阿里VC_ASR VC状态
+ self.asr_state = 0 # 预留:ASR 侧状态(当前未参与分支)
self.key_state = 0
self.AI_client_asr = None
self.play_flag = 0
self.VC_record_state_flag = 0
self.AI_key_long_press_flag = 0
+ self._asr_completed_tone_done = 0 # asr.completed 本地 think 提示每轮仅一次
self.websocket_error_count = 0
self.AI_new_voice_url = "" #未读语音地址/音乐播放地址/闹钟播放标志
self.music_play_flag = 0 #音乐播放标志
t = getattr(self.fsm, "turn", None)
except Exception:
t = None
- print("[KEY] AI_key_press VC_mode={} VC_state={} turn={} led={}".format(
- getattr(self, "VC_mode", -1), getattr(self, "VC_state", -1), t, led))
+ print("[KEY] AI_key_press VC_mode={} {} turn={} led={}".format(
+ getattr(self, "VC_mode", -1), self._vc_fsm_log_snip(), t, led))
except Exception:
pass
# 按键提示音(设备差异由 default_config.py 控制)
playing = (t in (VCTurnState.TtsReceiving, VCTurnState.Playing))
except Exception:
playing = False
- if playing or (self.VC_state >= VC_State_TTSStart and self.VC_state <= VC_State_TTSEnd) or getattr(self, "VC_Play_flag", 0) == 1:
+ if playing or self._vc_tts_pipeline_busy():
self._ptt_short_press_stop = 1
try:
cancel = {"event": "cancel", "payload": {}}
pass
# 长对话播放态:短按打断并续聊(复用 dialog_id)
- if self.VC_state >= VC_State_TTSStart and self.VC_state <= VC_State_TTSEnd:
+ if self._vc_tts_pipeline_busy():
print("【打断播放】设备正在说话,仅中断播放,不发起新对话")
self.is_ruppt_tts = 1
EventMesh.publish("publish_AI_btnInfo",{"func":self.AI_client_VC_RequestToSpeak})#打断
self.AI_TTS_str = ""#"你好,有什么吩咐"
self.AI_ASR_str = ""
self.AI_ASR_str_tmp = ""
- self.VC_state = VC_State_None
# if self.VC_state != VC_State_None:
# EventMesh.publish("publish_AI_btnInfo",{"func":self.Close})
# EventMesh.publish("publish_AI_btnInfo",{"func":utime.sleep_ms,'data':(10)})
self.AI_TTS_str = ""#"你好,有什么吩咐"
self.AI_ASR_str = ""
self.AI_ASR_str_tmp = ""
- self.VC_state = VC_State_None
# if self.VC_state != VC_State_None:
# EventMesh.publish("publish_AI_btnInfo",{"func":self.Close})
# EventMesh.publish("publish_AI_btnInfo",{"func":utime.sleep_ms,'data':(10)})
t = getattr(self.fsm, "turn", None)
except Exception:
t = None
- print("[KEY] AI_key_release VC_mode={} VC_state={} turn={} led={}".format(
- getattr(self, "VC_mode", -1), getattr(self, "VC_state", -1), t, led))
+ print("[KEY] AI_key_release VC_mode={} {} turn={} led={}".format(
+ getattr(self, "VC_mode", -1), self._vc_fsm_log_snip(), t, led))
except Exception:
pass
print("AI_key_release123")
self.voice_flag=0
EventMesh.publish("play_tts",[tts_play_str,1])
return
- if self.AI_key_long_press_flag == 1 :#有长按
- #self.AI_client_VC_end_speech()
- #EventMesh.publish("publish_AI_btnInfo",{"func":utime.sleep_ms,'data':(1000)})
- #EventMesh.publish("publish_AI_btnInfo",{"func":self.AI_client_asr_StopTranscription_requset})
- #self.AI_client_asr_StopTranscription_requset()#请求停止
+ if self.AI_key_long_press_flag == 1 :#有长按(或上一轮未清干净的残留)
if self.VC_mode == 1 :#长按单次问答模式
- # if self.AI_ASR_str_tmp != "":
- print("AI_key_release:asr_str:{}".format(self.AI_ASR_str))
- # EventMesh.publish("publish_AI_btnInfo",{"func":self.AI_VC_start})
- self.AI_client_VC_end_speech()
- pass
-
+ # 仅在本轮确实仍在录音上行时发 audio.completed;否则视为短按「提示音」路径
+ if getattr(self, "VC_record_state_flag", 0) != 0:
+ print("AI_key_release:asr_str:{}".format(self.AI_ASR_str))
+ self.AI_client_VC_end_speech()
+ else:
+ self.AI_key_long_press_flag = 0
+ try:
+ if getattr(self, "_ptt_short_press_stop", 0) == 1:
+ self._ptt_short_press_stop = 0
+ return
+ except Exception:
+ pass
+ try:
+ if "vc_config" in globals() and vc_config:
+ self.AI_TTS_str = vc_config.get_attr("PTT_HINT", None)
+ except Exception:
+ pass
+ if not self.AI_TTS_str:
+ self.AI_TTS_str = "请您按住圆形的按钮开始讲话,讲完松开即可 "
+ EventMesh.publish("publish_AI_btnInfo",{"func":self.AI_VC_start})
else :
if self.VC_mode == 1 :#长按单次问答模式
# 若刚刚短按用于“停止播报”,则不再触发提示音 TTS,直接回到 idle
t = getattr(self.fsm, "turn", None)
except Exception:
t = None
- print("[KEY] AI_key_long_press VC_mode={} VC_state={} turn={} led={}".format(
- getattr(self, "VC_mode", -1), getattr(self, "VC_state", -1), t, led))
+ print("[KEY] AI_key_long_press VC_mode={} {} turn={} led={}".format(
+ getattr(self, "VC_mode", -1), self._vc_fsm_log_snip(), t, led))
except Exception:
pass
print("AI_key_long_press")
self.AI_record_tmp_queue.clear()
self.VC_record_state_flag = 0
+ # PTT 一轮录音结束:清长按语义,避免后续短按松手误走 end_speech 而不播提示音
+ try:
+ if getattr(self, "VC_mode", -1) == 1:
+ self.AI_key_long_press_flag = 0
+ except Exception:
+ pass
# 录音停止:关闭聆听灯(恢复 base)
try:
EventMesh.publish("set_led_state", {"ai_state": "idle"})
if self.VAD_count != 0:
EventMesh.publish("publish_AI_btnInfo",{"func":self.VC_Play_Pause,"data":0})#恢复音频播放
self.VAD_count = 0
- if self.VC_state >= VC_State_TTSStart:
+ if self._vc_tts_pipeline_busy():
pass
if vad_state == 1:
self.AI_record_tmp_queue.put(read_buf)#入缓存队列
# 创建VC客户端
try:
signal = net.csqQueryPoll()
- if signal == -1 or sim.getStatus() != 1:#网络正常
- self.websocket_error()
+ if signal == -1 or sim.getStatus() != 1:#无蜂窝/无卡等:弱网提示
+ self.websocket_error(play_weak_signal_tone=True)
return
req_str = ""
ack = "ack=1"
lang = "lang=zh-cn"#普通话测试环境
try:
- if "loang" in self.VC_TTS_voice_type[self.VC_TTS_voice_key]:
+ if "lang" in self.VC_TTS_voice_type[self.VC_TTS_voice_key]:
lang = self.VC_TTS_voice_type[self.VC_TTS_voice_key]["lang"]
else:
print("not lang!!!!!!!!!!!!!!!!!!!!!!")
if VC_WS_IO_LOG:
print("[VC] ws url {}".format(url))
- self.AI_client_VC = uwebsocket.Client.connect(url, debug=True)
+ self.AI_client_VC = uwebsocket.Client.connect(url, debug=False)
#self.AI_WS_connect_Queue.put(self.AI_client_VC)
print("[VC] websocket_connect ok")
- except Exception as e: #网络连接异常
+ except Exception as e: #网络连接异常(已通过 CSQ/SIM,多为 URL/握手/服务端问题,勿播「信号弱」)
usys.print_exception(e)
print("websocket_connect_VC error!!!\r\n")
+ try:
+ print("[VC] ws connect exc: {}".format(e))
+ except Exception:
+ pass
str_error = str(e)
if str_error.find("[Errno 22] EINVAL")!= -1:
print("[VC] websocket EINVAL: {}".format(str_error))
- self.websocket_error()
+ self.websocket_error(play_weak_signal_tone=False)
EventMesh.publish("set_storage_config",["powerRestart",1])#调试临时关闭
utime.sleep_ms(1000)
self.aud.stopPlayStream()
self.aud.stopAll()
Power.powerRestart()
- self.websocket_error()
+ self.websocket_error(play_weak_signal_tone=False)
return
#print("AI_client_VC:{}".format(self.AI_client_VC))
if self.AI_client_VC == None:
EventMesh.publish("update_dev_token")#获取token
- self.websocket_error()
+ self.websocket_error(play_weak_signal_tone=False)
return
self.AI_client_VC_debug+=1
utime.sleep_ms(10)
self.AI_client_VC_isconnect = 1
print("websocket_connect_VC end")
- def websocket_error(self,TTS_str=None):
+ def websocket_error(self, TTS_str=None, play_weak_signal_tone=False):
+ """play_weak_signal_tone=True 时播 xinhaoruo1(弱网/无卡类);连接/协议失败请传 False,避免误报「信号弱」。"""
+ try:
+ if getattr(self, "VC_mode", 0) != 1:
+ print("[VC][long_idle] websocket_error enter VC_mode={} TTS_str={} weak_hint={} -> Close then uplink_stop(async)".format(
+ getattr(self, "VC_mode", -1), TTS_str, play_weak_signal_tone))
+ except Exception:
+ pass
print("websocket_error1!!!!")
utime.sleep_ms(800)
self.Close()
self.AI_ASR_str_tmp = ""
self.AI_ASR_flag = 0
# 可能由收包线程/其它线程触发:统一切回主线程执行 stop,避免“异常→重试→再异常”的循环
+ try:
+ if getattr(self, "VC_mode", 0) != 1:
+ print("[VC][long_idle] websocket_error schedule uplink_stop reason=websocket_error + set_led_idle")
+ except Exception:
+ pass
EventMesh.publish("publish_AI_btnInfo",{"func":self._uplink_request_stop, "data":"websocket_error"})
EventMesh.publish("set_led_state", {"ai_state": "idle"})
if TTS_str == None:
self.websocket_error_count+=1
# if self.websocket_error_count <=3:
# EventMesh.publish("audio_montage_play",["xinhaoruo1.mp3"])
- if self.websocket_error_count <10 :
-
- EventMesh.publish("audio_montage_play",["xinhaoruo1.mp3"])
+ if play_weak_signal_tone and self.websocket_error_count < 10:
+ EventMesh.publish("audio_montage_play", ["xinhaoruo1.mp3"])
elif self.websocket_error_count >=10:
EventMesh.publish("paly_iccid_imei")
self.fsm.await_played = False
self.fsm.last_tts_completed_ms = 0
self.fsm.last_llm_ms = 0
+ self.fsm.reset_rx_phases()
except Exception:
pass
self.AI_client_VC_recv_thread_close()#关闭读线程
self.AI_client_VC_recv_lock = 0
count+=1
- if self.VC_state >= VC_State_TTSStart and (self.tts_in_data_len - self.tts_out_data_len > 64*1024 or count>5):
+ if self._vc_tts_pipeline_busy() and (self.tts_in_data_len - self.tts_out_data_len > 64*1024 or count>5):
count = 0
utime.sleep_ms(1)
- if self.VC_state < VC_State_TTSStart:
+ if not self._vc_tts_pipeline_busy():
utime.sleep_ms(1)
recv_data = cli.recv()
if self.AI_client_VC_recv_lock == 2:
# if self.AI_new_voice_url != "":
# EventMesh.publish("publish_AI_btnInfo",{"func":self.AI_client_new_voice})
- self.VC_state = VC_State_None
elif jsload_data["event"] == "config.update" :#配置更新中,需要停止录音
- self.VC_state = VC_State_End
+ try:
+ self.fsm.reset_rx_phases()
+ except Exception:
+ pass
self.request_uplink_stop("config.update")
elif jsload_data["event"] == "asr.started" :#asr开始
- self.VC_state = VC_State_SpeechStart
+ try:
+ self.fsm.on_server_asr_started()
+ except Exception:
+ pass
self._server_vad_silence = 0
self._turn_has_asr_completed = 0
self._turn_has_vad_silence = 0
self._turn_has_tts_started = 0
self._llm_completed_ms = 0
+ try:
+ self._asr_completed_tone_done = 0
+ except Exception:
+ pass
try:
self._drop_tts_audio = 0
except Exception:
self.AI_TTS_str = "我没听清,请再说一遍"
elif jsload_data["event"] == "asr.completed" :#asr 终止的标识
self._turn_has_asr_completed = 1
- # æ\8a¢å\8d è§\84å\88\99ï¼\9aæ\9c¬å\9c°æ\8f\90示é\9f³ä¸\8då\8f¯æ\89\93æ\96æµ\81æ\92æ\94¾
+ # æ\9c¬å\9c° think æ\8f\90示ï¼\9aæ¯\8fè½® ASR æ\9c\80å¤\9aä¸\80次ï¼\8cä¸\94ä¸\8då¾\97ä¸\8eæµ\81å¼\8f TTS/PCM æ\92æ\94¾ç«\9eæ\80\81ï¼\88é\81¿å\85\8dé\95¿å¯¹è¯\9då\81¶å\8f\91è¿\9eæ\92ã\80\8cæ»´ã\80\8dï¼\89
try:
- if EventMesh.publish("get_vc_stream_active") != 1:
- self.aud.play(1, 1, 'U:/static/think.mp3') #播放按键音
+ if getattr(self, "_asr_completed_tone_done", 0) == 1:
+ pass
+ else:
+ stream_on = False
+ try:
+ stream_on = EventMesh.publish("get_vc_stream_active") == 1
+ except Exception:
+ stream_on = False
+ pcm_busy = getattr(self, "play_pcm", None) is not None
+ playing = getattr(self, "VC_Play_flag", 0) == 1
+ try:
+ thinking = getattr(self.fsm, "turn", VCTurnState.Idle) == VCTurnState.Thinking
+ except Exception:
+ thinking = False
+ if (not stream_on) and (not pcm_busy) and (not playing) and (not thinking):
+ self.aud.play(1, 1, 'U:/static/think.mp3')
+ self._asr_completed_tone_done = 1
except Exception:
pass
print("self.commands_mode:{}".format(self.commands_mode))
self._turn_has_vad_silence = 1
self._uplink_mark_end("vad.silence")
if self.record_data_save_flag == 0:
- if self.VC_record_state_flag != 0 and self.VC_state >= VC_State_SpeechStart:
+ if self.VC_record_state_flag != 0 and self._vc_vad_uplink_stop_eligible():
self.request_uplink_stop("vad.silence")
elif jsload_data["event"] == "llm.created" :#思考(LLM)
try:
EventMesh.publish("set_led_state", {"ai_state": "thinking"})
except Exception:
pass
- self.VC_state = VC_State_Thinking
self._llm_completed_ms = 0
# EventMesh.publish("publish_AI_btnInfo",{"func":self.VC_Play_Start})
pass
if self.VC_record_state_flag == 1:#llm返回数据还没停止,就先停止
self.request_uplink_stop("llm.delta")
elif jsload_data["event"] == "tts.started" :#tts开始
- self.VC_state = VC_State_TTSStart
self._server_vad_silence = 1
self._turn_has_tts_started = 1
self._tts_pending = 0
# 播放灯由阶段事件控制
elif jsload_data["event"] == "tts.completed" :#tts结束
# tts.completed 仅表示下发结束,本地可能仍在播放;绿灯关闭在本地播放结束时处理
- self.VC_state = VC_State_TTSEnd
try:
# server event 已在统一入口 on_server_event 触发 FSM,这里避免重复驱动
pass
print("AI_VC_start :AI_audio_queue_thread_id :{} ".format(self.AI_audio_queue_thread_id))
else:
print("AI_VC_start :AI_audio_queue_thread_id != 0 ")
- self.VC_state = VC_State_None
elif jsload_data["event"] == "completed" :#会话结束(可能无 TTS,如 ASR 空)
# 重要:服务端常在 tts.completed 后紧跟 completed。
# 若本轮存在 TTS/待发 audio.played,则不能在此清零 LocalRespondingEnded_timerout/_need_audio_played_ack,
# 否则会掐断「播完→audio.played→下一轮录音」链路,表现为最多 1~2 轮就停。
- if self._need_audio_played_ack == 1 or self.VC_state >= VC_State_TTSStart or self.VC_Play_flag == 1:
+ if self._need_audio_played_ack == 1 or self._vc_tts_pipeline_busy() or self.VC_Play_flag == 1:
pass
else:
# 无 TTS 的 completed:清状态并按需进入下一轮(见下方条件)
self.LocalRespondingEnded_timerout = 0
self._need_audio_played_ack = 0
- self.VC_state = VC_State_None
+ try:
+ self.fsm.reset_rx_phases()
+ except Exception:
+ pass
# 连续对话:若本轮没有 TTS(或服务端直接 completed),需要立刻回到聆听状态
# 否则会出现“有时 1 轮/2 轮后就停住”的现象(服务端 completed 但端侧未重新开录音上行)。
if self.VC_mode == 0 and self.Close_flag == 0:
self.recv_voice = 0
print("不开启定时器标志位置0")
self.LocalRespondingEnded_timerout = 8
- self.VC_state = VC_State_End
+ try:
+ self.fsm.reset_rx_phases()
+ except Exception:
+ pass
pass
elif jsload_data["event"] == "audio.convert.failed": #音频转换失败了
self._tts_pending = 0
self._tts_pending_ms = 0
if self.VC_mode == 0 and self.Close_flag == 0:
- self.VC_state = VC_State_None
+ try:
+ self.fsm.reset_rx_phases()
+ except Exception:
+ pass
EventMesh.publish("publish_AI_btnInfo", {"func": self.AI_VC_start})
except Exception:
pass
self._fb_last_thinking_restart_ms = now_ms
self._llm_completed_ms = 0
self._server_vad_silence = 0
- self.VC_state = VC_State_None
+ try:
+ self.fsm.reset_rx_phases()
+ except Exception:
+ pass
try:
print("[VC][thinking_timeout] AI_VC_start age_ms={} thr={}".format(
age_ms, restart_threshold_ms))
EventMesh.publish("system_sleep_rest")#防止黑屏
self.close_timerout += 1
if self.close_timerout > 20 and self.VC_mode != 1 :#:#20秒没数据就close 长按单次问答模式不关
-
- if self.VC_state >= VC_State_SpeechIng:
+ try:
+ print("[VC][long_idle] timeout_20s_gate close_timerout={} VC_mode={} {} (thr=SpeechIng)".format(
+ self.close_timerout, self.VC_mode, self._vc_fsm_log_snip()))
+ except Exception:
+ pass
+ if self._vc_long_idle_active_speech_or_later():
+ print("[VC][long_idle] branch=speech_no_rsp -> websocket_error + ud_error")
print("接口无响应,超时退出")
EventMesh.publish("publish_AI_btnInfo",{"func":self.websocket_error,"data":"接口超时了。请重试"})
self.ud_error(["VC",self.VC_taskid])
else:
+ print("[VC][long_idle] branch=idle_timeout -> Close")
EventMesh.publish("publish_AI_btnInfo",{"func":self.Close})
#EventMesh.publish("sleep_BT")#休眠蓝牙
if (is_pcm_empty and drained) or too_long:
EventMesh.publish("publish_AI_btnInfo", {"func": self.VC_Play_End})
self._fsm_apply_actions(self.fsm.on_local_play_end())
- self.VC_state = VC_State_None
+ try:
+ self.fsm.reset_rx_phases()
+ except Exception:
+ pass
except Exception:
pass
if self.online_kws == 1:
pass
# thinking/llm→tts 等兜底已在 _fsm_timeout_table_tick 内统一处理
- self.VC_pingping_timerout+=1
- if self.VC_pingping_timerout>3:
- self.VC_pingping_timerout=0
- self.AI_client_VC_ping()
+ # VC WebSocket 文本 ping:间隔由 default_config 的 VC_WS_PING_INTERVAL_SEC 控制(秒),<=0 表示关闭 ping
+ try:
+ _ping_iv = int(vc_config.get_int("VC_WS_PING_INTERVAL_SEC", 4))
+ except Exception:
+ _ping_iv = 4
+ if _ping_iv > 0:
+ self.VC_pingping_timerout += 1
+ if self.VC_pingping_timerout >= _ping_iv:
+ self.VC_pingping_timerout = 0
+ self.AI_client_VC_ping()
# self.asr_pingping_timerout += 1
# if self.asr_pingping_timerout>3:
# self.asr_pingping_timerout=0
#utime.sleep_ms(50)
else:
- print("self.VC_state :{}".format(self.VC_state ))
+ print("AI_VC_start2 (already connected) {}".format(self._vc_fsm_log_snip()))
EventMesh.publish(constants.EVENT.SYSTEM_UP)#唤醒休眠
if self.AI_client_VC_isconnect == 0:
#self.Close()
self.AI_client_VC_start_requset()
print("AI_VC_start3")
- self.VC_state = VC_State_None
if self.AI_TTS_str == "" and self.AI_new_voice_url == "":#没有tts要播放的时候才开始录音 并音频路径为空
#开始asr录音
self._uplink_request_start("AI_VC_start")#开启线程获取录音数据(统一入口)
token = EventMesh.publish("get_dev_token")
if token ==None:
token = ""
+ # bot_option:优先从 default_config(usr 可覆盖)读取 VC_BOT_ID / VC_WORKFLOW_ID,允许空字符串
+ _def_bot_id = "7462617881076351002"
+ _def_workflow_id = "7462621757327196187"
+ try:
+ if "vc_config" in globals() and vc_config:
+ _vc_bot_id = vc_config.get_attr("VC_BOT_ID", _def_bot_id)
+ _vc_workflow_id = vc_config.get_attr("VC_WORKFLOW_ID", _def_workflow_id)
+ if _vc_bot_id is None:
+ _vc_bot_id = ""
+ if _vc_workflow_id is None:
+ _vc_workflow_id = ""
+ else:
+ _vc_bot_id, _vc_workflow_id = _def_bot_id, _def_workflow_id
+ except Exception:
+ _vc_bot_id, _vc_workflow_id = _def_bot_id, _def_workflow_id
json_data = \
{
"header": {
"bot_option": {
"use_workflow": True,
#"input_format": "text",
- "bot_id":"7462617881076351002",#语言助手
- "workflow_id":"7462621757327196187",
+ "bot_id": _vc_bot_id,
+ "workflow_id": _vc_workflow_id,
}
}
if "vc_config" in globals() and vc_config:
opt = vc_config.get_attr("DIALOG_BOT_OPTION", None)
if isinstance(opt, dict):
- if "bot_id" in opt and opt["bot_id"]:
- json_data["payload"]["dialog_attributes"]["cfg"]["bot_option"]["bot_id"] = opt["bot_id"]
+ if "bot_id" in opt:
+ json_data["payload"]["dialog_attributes"]["cfg"]["bot_option"]["bot_id"] = opt.get("bot_id") or ""
if "workflow_id" in opt:
json_data["payload"]["dialog_attributes"]["cfg"]["bot_option"]["workflow_id"] = opt.get("workflow_id") or ""
if "use_workflow" in opt:
json_data["payload"]["dialog_attributes"]["cfg"]["bot_option"]["bot_id"] = cur.get("bot_id")
if "workflow_id" in cur:
json_data["payload"]["dialog_attributes"]["cfg"]["bot_option"]["workflow_id"] = cur.get("workflow_id") or ""
- if json_data["payload"]["dialog_attributes"]["cfg"]["bot_option"].get("workflow_id", "") == "":
- json_data["payload"]["dialog_attributes"]["cfg"]["bot_option"]["use_workflow"] = False
if cur.get("openai_option"):
json_data["payload"]["dialog_attributes"]["cfg"]["openai_option"] = cur.get("openai_option")
except Exception:
pass
+ try:
+ _bo = json_data["payload"]["dialog_attributes"]["cfg"]["bot_option"]
+ if not _bo.get("bot_id", "") or not _bo.get("workflow_id", ""):
+ _bo["use_workflow"] = False
+ except Exception:
+ pass
try:
if "vc_config" in globals() and vc_config:
p = vc_config.get_attr("DIALOG_PROVIDER_DEFAULT", None)
json_data["payload"]["commands"] = []
if self.VC_mode == 0 :#and dev_type != "7PIN_BK_coze":#长对话模式打开vad
json_data["payload"]["inbound_attributes"]["disable_vad"] = False
- self.VC_state = VC_State_None
# 新会话开始:在收到服务端 started 前,禁止发送音频帧(避免 session not initialized)
self._vc_session_started = 0
try:
- self.VC_state = VC_State_SpeechStart
+ try:
+ self.fsm.on_server_asr_started()
+ except Exception:
+ pass
#结束上传语音
def AI_client_VC_end_speech(self):
json_data = \
EventMesh.publish("publish_AI_btnInfo",{"func":self.VC_init})
EventMesh.publish("publish_AI_btnInfo",{"func":self.AI_client_VC_send,"data":ujson.dumps(json_data)})
utime.sleep_ms(1)
- self.VC_state = VC_State_None
+ try:
+ self.fsm.reset_rx_phases()
+ except Exception:
+ pass
# #self.Close()
# self.AI_VC_start()
#TTS播放
self.AI_TTS_str = ""#"你好,有什么吩咐"
self.AI_ASR_str = ""
self.AI_ASR_str_tmp = ""
- self.VC_state = VC_State_None
self._uplink_request_stop("kws_even_cb")
self._uplink_request_start("kws_even_cb")
self.AI_VC_start()
utime.sleep_ms(2)
else:
break
+ # 打断后 PCM 偶发未打开:加重试,避免「队列有数据、play_pcm=None、无声」
+ if self.VC_play_TYPE == VC_play_TYPE_PCM and self.play_pcm is None and self.VC_stop_play_audio_flag == 1:
+ for j in range(4):
+ if self.VC_Play_flag == 0:
+ self.VC_Play_Start()
+ utime.sleep_ms(30 + j * 35)
+ if self.play_pcm is not None:
+ break
try:
if self.VC_play_TYPE == VC_play_TYPE_PCM:
# if self.VC_play_samplerate == 8000:
def Close_VC(self,event,msg):
EventMesh.publish("publish_AI_btnInfo",{"func":self.Close})
def Close(self):
+ try:
+ if getattr(self, "VC_mode", 0) != 1:
+ print("[VC][long_idle] Close() enter VC_mode={} {} VC_satrt_flag={} VC_record_state_flag={}".format(
+ getattr(self, "VC_mode", -1), self._vc_fsm_log_snip(),
+ getattr(self, "VC_satrt_flag", -1), getattr(self, "VC_record_state_flag", -1)))
+ except Exception:
+ pass
self.VC_stop_play_audio_flag = 0
+ try:
+ self.AI_key_long_press_flag = 0
+ except Exception:
+ pass
self.VC_Thinking_timerout = 0
self.AI_ASR_timer.stop()
self._1S_timer.stop()
pass
self.is_ruppt_tts = 0#打断标志位清零
print("ai_VC Close1!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
+ try:
+ if getattr(self, "VC_mode", 0) != 1:
+ print("[VC][long_idle] step=set_led_state_idle (first)")
+ except Exception:
+ pass
EventMesh.publish("set_led_state", {"ai_state": "idle"})
self.tts_in_data_len = 0
self.tts_out_data_len = 0
usys.print_exception(e)
# Close 可能被不同线程触发:统一切回主线程执行 stop
+ try:
+ if getattr(self, "VC_mode", 0) != 1:
+ print("[VC][long_idle] step=schedule_uplink_stop reason=Close (async publish_AI_btnInfo)")
+ except Exception:
+ pass
EventMesh.publish("publish_AI_btnInfo",{"func":self._uplink_request_stop, "data":"Close"})
print("ai_VC Close1.1!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print("ai_VC Close1.2!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
+ try:
+ if getattr(self, "VC_mode", 0) != 1:
+ print("[VC][long_idle] step=websocket_deconnect_VC")
+ except Exception:
+ pass
try:
self.websocket_deconnect_VC()
except Exception as e:
if self.AI_VC_send_data_queue.empty()!=True:
self.AI_VC_send_data_queue.clear()
self.play_new_voice_flag = 0 #语音消息播放状态
- if self.voice_choose_flag == 0:#如果没有未读语音
- self.AI_new_voice_url ="" #语音播放地址
+ if self.voice_choose_flag == 0: # 如果没有未读语音
+ self.AI_new_voice_url = "" # 语音播放地址
print("关闭并重置语音标志位")
- print("关闭但是没有重置语音标志位")
+ else:
+ print("关闭但是没有重置语音标志位")
self.AI_ASR_send_buf_len = 0
#self.AI_WS_connect_Queue.put(self.AI_client_VC)
+ try:
+ if getattr(self, "VC_mode", 0) != 1:
+ print("[VC][long_idle] step=set_led_state_idle (second) -> VC_init VC_satrt_flag=0")
+ except Exception:
+ pass
EventMesh.publish("set_led_state", {"ai_state": "idle"})
self.VC_init()
self.VC_satrt_flag = 0
import usys\r
import sms\r
from Gsensor import SC7A20\r
+def _sos_feature_enabled():\r
+ try:\r
+ import vc_config\r
+ return vc_config.get_bool("SOS_ENABLED", True)\r
+ except Exception:\r
+ return True\r
+\r
+\r
+def _btn_cfg():\r
+ try:\r
+ import vc_config\r
+ return vc_config\r
+ except Exception:\r
+ return None\r
+\r
+\r
+def _btn_int(name, default):\r
+ c = _btn_cfg()\r
+ return c.get_int(name, default) if c else default\r
+\r
+\r
+def _btn_bool(name, default):\r
+ c = _btn_cfg()\r
+ return c.get_bool(name, default) if c else default\r
+\r
+\r
+def _btn_device_enabled():\r
+ return _btn_bool("BTN_DEVICE_ENABLED", True)\r
+\r
+\r
if EventMesh.model == "D10" :\r
audio_buf = ['audio_find_haixiu', 'R_ALARM_NEW', 'R_BLOOD_SUGAR', 'R_CALL_mp3', 'R_CHARGE_FULL', 'R_CHARGE_IN', 'R_CHARGE_OUT', 'R_CUR_BATTERY_LEVEL', 'R_DRINK_ALARM', 'R_FALL_ALARM', 'R_HOME_ALARM', 'R_HSENSOR_RESULT_FAILE', 'R_HSENSOR_RESULT_HR_TITLE', 'R_HSENSOR_RESULT_OK', 'R_HSENSOR_SPO2_TITLE', 'R_HSENSOR_TEMP_TITLE', 'R_MEDICINE_ALARM', 'R_NO_SET_SOS_DIAL', 'R_NO_SET_VIDOE', 'R_NO_SIM', 'R_POWER_OFF_1', 'R_READ_STEP_0', 'R_READ_STEP_1', 'R_READ_STEP_2', 'R_READ_STEP_3', 'R_READ_STEP_4', 'R_READ_TIME_0', 'R_READ_TIME_1', 'R_READ_TIME_2', 'R_READ_TIME_3', 'R_READ_TIME_4', 'R_READ_TIME_5', 'R_READ_TIME_6', 'R_READ_TIME_7', 'R_READ_TIME_8', 'R_READ_TIME_9', 'R_READ_TIME_MIN', 'R_READ_TIME_ZHENG', 'R_RESET_ALARM', 'R_RESET_END_ALARM', 'R_SIM_CONNECT', 'R_SIM_FAILE', 'R_SLEEP_ALARM', 'R_SOS_ALERT', 'R_TSENSOR_RESULT_VALUE_DOT', 'R_UNREAD_WECHAT', 'R_VIDEO_ANSWER', 'R_VIDEO_ANSWERING', 'R_VIDEO_CALL_CONNECT', 'R_VIDEO_CALL_ENDING', 'R_VIDEO_CALL_IN', 'R_VIDEO_VOICE_IN', 'R_VIDEO_WAITING', 'R_WAKEUP_ALARM', 'R_WECHAT_RECV']\r
\r
pass\r
\r
def dial_sos_phone(self, event, msg): #拨打紧急求助电话\r
+ if not _sos_feature_enabled():\r
+ return\r
flag = EventMesh.publish("get_call_state")\r
if flag == 0:\r
\r
self.pk = PowerKey()\r
self.__pwk_timer = osTimer()\r
self.aud = audio.Audio(0)\r
- self.aud.set_pa(Pin.GPIO29)\r
- self.aud.setVolume(11)\r
+ vc = _btn_cfg()\r
+ pa_gpio = vc.pin_gpio_attr("BTN_AUDIO_PA_GPIO", "GPIO29", Pin) if vc else Pin.GPIO29\r
+ if pa_gpio is not None:\r
+ self.aud.set_pa(pa_gpio)\r
+ else:\r
+ self.aud.set_pa(Pin.GPIO29)\r
+ self.aud.setVolume(_btn_int("BTN_AUDIO_VOLUME", 11))\r
# self.keypad = machine.KeyPad(1, 2)\r
- self.__PowerDownTimeOut = 3000\r
+ self.__PowerDownTimeOut = _btn_int("BTN_POWER_DOWN_TIMEOUT_MS", 3000)\r
+ self.__btn_poll_ms = _btn_int("BTN_POLL_MS", 100)\r
+ self.__btn_release_timeout_ms = _btn_int("BTN_RELEASE_TIMEOUT_MS", 500)\r
+ self.__pwk_led_on_ticks = _btn_int("BTN_PWK_LED_ON_TICKS", 5)\r
+ self.__pwk_power_off_ticks = _btn_int("BTN_PWK_POWER_OFF_TICKS", 100)\r
+ self.__pwk_power_off_no_sim_ticks = _btn_int("BTN_PWK_POWER_OFF_NO_SIM_TICKS", 30)\r
+ self.__pwk_release_debounce_ticks = _btn_int("BTN_PWK_RELEASE_DEBOUNCE_TICKS", 1)\r
+ self.__sos_long_press_ticks = _btn_int("BTN_SOS_LONG_PRESS_TICKS", 30)\r
+ self.__sos_release_debounce_ticks = _btn_int("BTN_SOS_RELEASE_DEBOUNCE_TICKS", 1)\r
+ self.__wechat_long_press_ticks = _btn_int("BTN_WECHAT_LONG_PRESS_TICKS", 15)\r
+ self.__wechat_release_debounce_ticks = _btn_int("BTN_WECHAT_RELEASE_DEBOUNCE_TICKS", 1)\r
self.__tp = tp\r
self.pwk_press = 0\r
self.pwk_count = 0\r
# self.keypad.set_callback(self.key_callback)\r
\r
self.pk.powerKeyEventRegister(self.powerKey_callback)\r
- \r
- self.extint = ExtInt(ExtInt.GPIO26, ExtInt.IRQ_RISING_FALLING, ExtInt.PULL_DISABLE, self.pwk_extint_cb)\r
- self.extint.enable()\r
-\r
- self.sosKey = ExtInt(ExtInt.GPIO22, ExtInt.IRQ_RISING_FALLING, ExtInt.PULL_PU, self.sosKey_extint_cb)\r
- self.sosKey.enable()\r
-\r
- self.wechatKey = ExtInt(ExtInt.GPIO20, ExtInt.IRQ_RISING_FALLING, ExtInt.PULL_PU, self.wechatKey_extint_cb)\r
- self.wechatKey.enable()\r
+ if not _btn_device_enabled():\r
+ return\r
\r
- key19 = Pin(Pin.GPIO19, Pin.OUT, Pin.PULL_PU, 0)\r
+ vc = _btn_cfg()\r
+ pwk_gpio = vc.extint_gpio_attr("BTN_PWK_GPIO", "GPIO26", ExtInt) if vc else ExtInt.GPIO26\r
+ if pwk_gpio is not None:\r
+ pwk_pull = vc.extint_pull_attr("BTN_PWK_PULL", "PULL_DISABLE", ExtInt) if vc else ExtInt.PULL_DISABLE\r
+ self.extint = ExtInt(pwk_gpio, ExtInt.IRQ_RISING_FALLING, pwk_pull, self.pwk_extint_cb)\r
+ self.extint.enable()\r
+\r
+ sos_gpio = vc.extint_gpio_attr("BTN_SOS_GPIO", "GPIO22", ExtInt) if vc else ExtInt.GPIO22\r
+ if sos_gpio is not None:\r
+ sos_pull = vc.extint_pull_attr("BTN_SOS_PULL", "PULL_PU", ExtInt) if vc else ExtInt.PULL_PU\r
+ self.sosKey = ExtInt(sos_gpio, ExtInt.IRQ_RISING_FALLING, sos_pull, self.sosKey_extint_cb)\r
+ self.sosKey.enable()\r
+\r
+ wechat_gpio = vc.extint_gpio_attr("BTN_WECHAT_GPIO", "GPIO20", ExtInt) if vc else ExtInt.GPIO20\r
+ if wechat_gpio is not None:\r
+ wechat_pull = vc.extint_pull_attr("BTN_WECHAT_PULL", "PULL_PU", ExtInt) if vc else ExtInt.PULL_PU\r
+ self.wechatKey = ExtInt(wechat_gpio, ExtInt.IRQ_RISING_FALLING, wechat_pull, self.wechatKey_extint_cb)\r
+ self.wechatKey.enable()\r
+\r
+ aux_gpio = vc.get_attr("BTN_AUX_OUT_GPIO", "GPIO19") if vc else "GPIO19"\r
+ if aux_gpio:\r
+ aux_init = _btn_int("BTN_AUX_OUT_INIT", 0)\r
+ aux_pull = vc.pin_pull_attr("BTN_AUX_OUT_PULL", "PULL_PU", Pin) if vc else Pin.PULL_PU\r
+ Pin(getattr(Pin, aux_gpio), Pin.OUT, aux_pull, aux_init)\r
\r
def pwk_extint_cb(self,args):#侧边按键\r
# self.GPIO26_status = self.extint.read_level()\r
self.pwkey_press = 1\r
self.pwkey_count = 0\r
self.led_state = 0\r
- self.pwkey_timer.start(100, 1, self.publish_pwkKey_btn_event_cb)\r
+ self.pwkey_timer.start(self.__btn_poll_ms, 1, self.publish_pwkKey_btn_event_cb)\r
# EventMesh.debug_log("key22_extint_cb:self.key22_timer.start!!!!\n")\r
\r
def pwKey_press_cb(self, data):\r
self.GPIO26_status = self.extint.read_level()\r
if self.pwkey_press == 1 :\r
self.pwkey_count += 1\r
- if self.pwkey_count > 5:\r
+ if self.pwkey_count > self.__pwk_led_on_ticks:\r
if self.led_state == 0:\r
self.led_state = 1\r
EventMesh.publish("set_led_time_arg",[1,1,330,led_mode.LONG_LIGHT_GREEN,2,1,led_mode.OTHER_MEASURE_MODE])#測量成功\r
- if self.pwkey_count >= 10*10:\r
+ if self.pwkey_count >= self.__pwk_power_off_ticks:\r
EventMesh.publish("stop_led_timer")#设置参数\r
self.pwkey_timer.stop()\r
self.pwkey_count = 0\r
EventMesh.publish("open_power_on", 3)#\r
return\r
\r
- if self.pwkey_count >= 3*10 :\r
+ if self.pwkey_count >= self.__pwk_power_off_no_sim_ticks:\r
if EventMesh.publish("get_sim_Status") != 1:\r
EventMesh.debug_log("长3秒关机")\r
EventMesh.publish("stop_led_timer")#设置参数\r
\r
\r
if self.GPIO26_status == 1:#松开\r
- if self.pwkey_count >= 1: #防抖100ms\r
+ if self.pwkey_count >= self.__pwk_release_debounce_ticks: #防抖\r
# EventMesh.debug_log("self.GPIO26_status == 1")\r
self.pwkey_timer.stop()\r
self.pwkey_count = 0\r
self.pwkey_press = 0\r
self.led_state = 0\r
self.pwKey_press_count+=1\r
- self.pwkey_timer.start(500, 0, self.publish_pwKey_timeout_cb_do)#松手超时1s判断\r
+ self.pwkey_timer.start(self.__btn_release_timeout_ms, 0, self.publish_pwKey_timeout_cb_do)#松手超时判断\r
\r
def hsensorTest_timer_cb(self,e):\r
EventMesh.publish("system_sleep_rest")#防止黑屏 \r
self.sosKey_long_press = 0\r
self.sosKey_count = 0\r
self.sosKey_press = 1\r
- self.sosKey_timer.start(100, 1, self.publish_soskey_btn_event_cb)\r
+ self.sosKey_timer.start(self.__btn_poll_ms, 1, self.publish_soskey_btn_event_cb)\r
# EventMesh.debug_log("key22_extint_cb:self.key22_timer.start!!!!\n")\r
\r
def sosKey_press_cb(self, data):\r
# else:\r
# EventMesh.publish("set_led_time_arg",[1000,200,1,led_mode.FLASH_LIGHT_RED,led_mode.DEFAULT_LONG_LIGHT_MODE,led_mode.OTHER_MEASURE_MODE])#设置参数\r
self.sosKey_count += 1\r
- if self.sosKey_count >= 10*3: #长按3s sos拨号\r
+ if self.sosKey_count >= self.__sos_long_press_ticks: #长按 sos拨号\r
if self.sosKey_long_press == 0:\r
self.sosKey_long_press = 1\r
flag = EventMesh.publish("get_call_state")#在通话或者电话拨进 或者拨出不允许寻找设备\r
\r
# EventMesh.debug_log("self.sosKey_count {}",self.sosKey_count)\r
if self.sosKey_status == 1:#松开\r
- if self.sosKey_count >= 1: #防抖100ms\r
+ if self.sosKey_count >= self.__sos_release_debounce_ticks: #防抖\r
self.sosKey_timer.stop()\r
self.sosKey_count = 0\r
self.sosKey_press = 0\r
self.sosKey_long_press = 0\r
self.sosKey_press_count+=1\r
- self.sosKey_timer.start(500, 0, self.publish_sosKey_timeout_cb_do)#松手超时1s判断\r
+ self.sosKey_timer.start(self.__btn_release_timeout_ms, 0, self.publish_sosKey_timeout_cb_do)#松手超时判断\r
def publish_sosKey_timeout_cb_do(self, *args, **kwargs):\r
EventMesh.publish("publish_message_event_btnInfo",{"func":self.sosKey_timeout_cb,"data":0}) \r
\r
self.led_state = 0\r
self.wechatKey_count = 0\r
self.wechat_state = 0\r
- self.wechatKey_timer.start(100, 1, self.publish_wechat_btn_event_cb)\r
+ self.wechatKey_timer.start(self.__btn_poll_ms, 1, self.publish_wechat_btn_event_cb)\r
else:\r
# EventMesh.debug_log('### wechatKey_extint_cb end')\r
EventMesh.publish("close_wechat_btn_timer")\r
if self.wechatKey_press == 1 :#是否按下\r
tmp = EventMesh.publish("get_wechat_time")#获取微聊时间戳\r
self.wechatKey_count += 1\r
- if self.wechatKey_count >= 15: #长按1s进入微聊录音\r
+ if self.wechatKey_count >= self.__wechat_long_press_ticks: #长按进入微聊录音\r
flag = EventMesh.publish("get_call_state") \r
fall_down = EventMesh.publish("get_fall_down_state")#跌倒报警标识\r
if flag != None:\r
self.wechatKey_press_count=0\r
return\r
if self.WeChatKey_status == 1:#松开\r
- if self.wechatKey_count >= 1: #防抖100ms\r
+ if self.wechatKey_count >= self.__wechat_release_debounce_ticks: #防抖\r
# EventMesh.debug_log("WeChat time!!!!!!!!!!!!!!")\r
self.wechatKey_timer.stop()\r
self.wechatKey_count = 0\r
self.wechatKey_press = 0\r
self.wechat_state = 0\r
self.wechatKey_press_count+=1\r
- self.wechatKey_timer.start(500, 0, self.publish_wechatKey_btn_event_cb)#松手超时1s判断\r
+ self.wechatKey_timer.start(self.__btn_release_timeout_ms, 0, self.publish_wechatKey_btn_event_cb)#松手超时判断\r
\r
def publish_wechatKey_btn_event_cb(self, *args, **kwargs):\r
EventMesh.publish("publish_message_event_btnInfo",{"func":self.wechatKey_timeout_cb,"data":0}) \r