修复音量配置bug和加入自助配WIFI

parent ad769603
...@@ -60,9 +60,11 @@ target_include_directories(main PRIVATE ...@@ -60,9 +60,11 @@ target_include_directories(main PRIVATE
${THIRD_PARTY_INCLUDE_DIRS} ${THIRD_PARTY_INCLUDE_DIRS}
) )
# 将项目根目录传入代码,消除硬编码路径 # 运行数据位于部署目录,不能绑定编译机(尤其是 /tmp)的源码目录。
set(CAR_RUNTIME_DIR "/home/orangepi/car/master" CACHE PATH
"Deployment directory containing Deviceld.txt, zlog.conf and runtime data")
target_compile_definitions(main PRIVATE target_compile_definitions(main PRIVATE
PROJECT_ROOT_DIR="${CMAKE_CURRENT_SOURCE_DIR}" PROJECT_ROOT_DIR="${CAR_RUNTIME_DIR}"
GST_USE_UNSTABLE_API GST_USE_UNSTABLE_API
) )
......
#include "wifi_hotspot.h"
#include "wifi_operation.h"
#include "device_identity.h" #include "device_identity.h"
#include "device_wifi_change.h" #include "device_wifi_change.h"
#include "modules_common.h" #include "modules_common.h"
int connect_wifi(const char *ssid, const char *password);
int connect_wifi_with_fallback(const char *ssid, const char *password, const char *fallback_ssid);
int change_wifi_connect(const char *wifi_ssid, const char *wifi_password);
void connect_wifi_jking(void);
char g_current_ssid[SSID_MAX_LEN] = {0};//用于存现在已连接WiFi char g_current_ssid[SSID_MAX_LEN] = {0};//用于存现在已连接WiFi
static char s_wifi_last_ssid[SSID_MAX_LEN]= {0} ; static char s_wifi_last_ssid[SSID_MAX_LEN]= {0} ;
static char s_wifi_last_password[SSID_MAX_LEN]= {0} ; static char s_wifi_last_password[SSID_MAX_LEN]= {0} ;
//获取当前连接wifi //获取当前连接wifi
void get_current_wifi() { static void get_current_wifi_unlocked() {
g_current_ssid[0] = '\0'; g_current_ssid[0] = '\0';
FILE *fp = popen("nmcli -t -f ACTIVE,SSID dev wifi", "r"); FILE *fp = popen("nmcli -t -f ACTIVE,SSID dev wifi", "r");
...@@ -45,7 +52,7 @@ int cmp_signal_desc(const void *a, const void *b) { ...@@ -45,7 +52,7 @@ int cmp_signal_desc(const void *a, const void *b) {
return wb->signal - wa->signal; return wb->signal - wa->signal;
} }
//显示以连接WiFi名称和周围已有的WiFi和过滤掉信号强度低于50的WiFi //显示以连接WiFi名称和周围已有的WiFi和过滤掉信号强度低于50的WiFi
void scan_wifi_json() { static void scan_wifi_json_unlocked() {
get_current_wifi(); get_current_wifi();
char line[100]; char line[100];
...@@ -116,7 +123,7 @@ void scan_wifi_json() { ...@@ -116,7 +123,7 @@ void scan_wifi_json() {
} }
//连接WiFi //连接WiFi
int connect_wifi(const char* ssid, const char* password) { static int connect_wifi_unlocked(const char* ssid, const char* password) {
char cmd[CMD_BUFFER_SIZE]; char cmd[CMD_BUFFER_SIZE];
snprintf(cmd, sizeof(cmd), "nmcli dev wifi connect '%s' password '%s' 2>&1", ssid, password); snprintf(cmd, sizeof(cmd), "nmcli dev wifi connect '%s' password '%s' 2>&1", ssid, password);
...@@ -150,7 +157,7 @@ int connect_wifi(const char* ssid, const char* password) { ...@@ -150,7 +157,7 @@ int connect_wifi(const char* ssid, const char* password) {
} }
} }
//如果连接失败则回退 //如果连接失败则回退
int connect_wifi_with_fallback(const char* ssid, const char* password, const char* fallback_ssid) { static int connect_wifi_with_fallback_unlocked(const char* ssid, const char* password, const char* fallback_ssid) {
int ret = connect_wifi(ssid, password); int ret = connect_wifi(ssid, password);
if (ret != 0 && fallback_ssid && fallback_ssid[0] != 0) { if (ret != 0 && fallback_ssid && fallback_ssid[0] != 0) {
my_zlog_warn("⚠️ 连接失败,尝试回退连接原Wi-Fi:%s", fallback_ssid); my_zlog_warn("⚠️ 连接失败,尝试回退连接原Wi-Fi:%s", fallback_ssid);
...@@ -180,7 +187,7 @@ int connect_wifi_with_fallback(const char* ssid, const char* password, const cha ...@@ -180,7 +187,7 @@ int connect_wifi_with_fallback(const char* ssid, const char* password, const cha
return ret; return ret;
} }
//改变WiFi连接 //改变WiFi连接
int change_wifi_connect(const char *wifi_ssid,const char *wifi_password) { static int change_wifi_connect_unlocked(const char *wifi_ssid,const char *wifi_password) {
get_current_wifi(); get_current_wifi();
int ret = connect_wifi_with_fallback(wifi_ssid, wifi_password, g_current_ssid); int ret = connect_wifi_with_fallback(wifi_ssid, wifi_password, g_current_ssid);
my_zlog_info("WiFi连接返回代码:%d", ret); my_zlog_info("WiFi连接返回代码:%d", ret);
...@@ -199,7 +206,7 @@ int can_access_internet() { ...@@ -199,7 +206,7 @@ int can_access_internet() {
} }
//删除对应wifi //删除对应wifi
int delete_wifi_by_ssid(const char* ssid) { static int delete_wifi_by_ssid_unlocked(const char* ssid) {
if (ssid == NULL || strlen(ssid) == 0) { if (ssid == NULL || strlen(ssid) == 0) {
fprintf(stderr, "SSID is empty.\n"); fprintf(stderr, "SSID is empty.\n");
return -1; return -1;
...@@ -405,7 +412,7 @@ void wifichange_sendmqtt(int wifi_status) { //改WiFi发送 ...@@ -405,7 +412,7 @@ void wifichange_sendmqtt(int wifi_status) { //改WiFi发送
} }
//默认连接jking //默认连接jking
void connect_wifi_jking() { static void connect_wifi_jking_unlocked() {
if(check_or_create_wifi_conf() == 0) my_zlog_debug("文件已创建"); if(check_or_create_wifi_conf() == 0) my_zlog_debug("文件已创建");
if(write_wifi_conf() == 0) my_zlog_debug("写入成功"); if(write_wifi_conf() == 0) my_zlog_debug("写入成功");
int ret=change_wifi_connect(default_SSID,default_password); int ret=change_wifi_connect(default_SSID,default_password);
...@@ -419,7 +426,7 @@ void connect_wifi_jking() { ...@@ -419,7 +426,7 @@ void connect_wifi_jking() {
} }
//wifi改变初始化,放在main开头,必须要等mqtt直播就绪才行 //wifi改变初始化,放在main开头,必须要等mqtt直播就绪才行
int wifi_change_sendmqtt_init(){ static int wifi_change_sendmqtt_init_unlocked(){
int wififile_fd = compare_ssid_with_file(); int wififile_fd = compare_ssid_with_file();
if(wififile_fd==-1){ if(wififile_fd==-1){
if(can_access_internet()!=0){ if(can_access_internet()!=0){
...@@ -483,7 +490,7 @@ int wifi_change_sendmqtt_init(){ ...@@ -483,7 +490,7 @@ int wifi_change_sendmqtt_init(){
} }
//接收mqtt消息 //接收mqtt消息
void wifi_change_recmqtt(cJSON *body){ static void wifi_change_recmqtt_unlocked(cJSON *body){
cJSON *wifi_ssid = cJSON_GetObjectItem(body, "wifi_ssid"); cJSON *wifi_ssid = cJSON_GetObjectItem(body, "wifi_ssid");
cJSON *wifi_password = cJSON_GetObjectItem(body, "wifi_password"); cJSON *wifi_password = cJSON_GetObjectItem(body, "wifi_password");
cJSON *wifi_status = cJSON_GetObjectItem(body, "wifi_status"); cJSON *wifi_status = cJSON_GetObjectItem(body, "wifi_status");
...@@ -534,4 +541,67 @@ void wifi_change_recmqtt(cJSON *body){ ...@@ -534,4 +541,67 @@ void wifi_change_recmqtt(cJSON *body){
} }
} }
} }
\ No newline at end of file void scan_wifi_json(void) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return;
if (!wifi_hotspot_is_active()) scan_wifi_json_unlocked();
wifi_operation_end();
}
int connect_wifi(const char *ssid, const char *password) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return -1;
int result = -1;
if (!wifi_hotspot_is_active()) result = connect_wifi_unlocked(ssid, password);
wifi_operation_end();
return result;
}
int connect_wifi_with_fallback(const char *ssid, const char *password, const char *fallback_ssid) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return -1;
int result = -1;
if (!wifi_hotspot_is_active()) result = connect_wifi_with_fallback_unlocked(ssid, password, fallback_ssid);
wifi_operation_end();
return result;
}
int change_wifi_connect(const char *wifi_ssid, const char *wifi_password) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return -1;
int result = -1;
if (!wifi_hotspot_is_active()) result = change_wifi_connect_unlocked(wifi_ssid, wifi_password);
wifi_operation_end();
return result;
}
void connect_wifi_jking(void) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return;
if (!wifi_hotspot_is_active()) connect_wifi_jking_unlocked();
wifi_operation_end();
}
int wifi_change_sendmqtt_init(void) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return -1;
int result = -1;
if (!wifi_hotspot_is_active()) result = wifi_change_sendmqtt_init_unlocked();
wifi_operation_end();
return result;
}
void wifi_change_recmqtt(cJSON *body) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return;
if (!wifi_hotspot_is_active()) wifi_change_recmqtt_unlocked(body);
wifi_operation_end();
}
void get_current_wifi(void) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return;
if (!wifi_hotspot_is_active()) get_current_wifi_unlocked();
wifi_operation_end();
}
int delete_wifi_by_ssid(const char *ssid) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return -1;
int result = -1;
if (!wifi_hotspot_is_active()) result = delete_wifi_by_ssid_unlocked(ssid);
wifi_operation_end();
return result;
}
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
#include "device_wifi_change.h" #include "device_wifi_change.h"
#include "device_wifi_manager.h" #include "device_wifi_manager.h"
#include "modules_common.h" #include "modules_common.h"
#include "wifi_hotspot.h"
#include "wifi_operation.h"
#include <sys/types.h> #include <sys/types.h>
#include <sys/wait.h> #include <sys/wait.h>
...@@ -540,6 +542,7 @@ static int scan_visible_wifi(visible_wifi_entry_t *entries, int max_count) { ...@@ -540,6 +542,7 @@ static int scan_visible_wifi(visible_wifi_entry_t *entries, int max_count) {
} }
static int activate_saved_wifi_profile(const char *profile_name) { static int activate_saved_wifi_profile(const char *profile_name) {
if (wifi_hotspot_is_active()) return -1;
pid_t pid; pid_t pid;
int status; int status;
...@@ -561,7 +564,8 @@ static int activate_saved_wifi_profile(const char *profile_name) { ...@@ -561,7 +564,8 @@ static int activate_saved_wifi_profile(const char *profile_name) {
return -1; return -1;
} }
int device_wifi_connect_best_saved_visible(void) { static int device_wifi_connect_best_saved_visible_unlocked(void) {
if (wifi_hotspot_is_active()) return 0;
saved_wifi_entry_t saved[MAX_WIFI_ENTRIES]; saved_wifi_entry_t saved[MAX_WIFI_ENTRIES];
visible_wifi_entry_t visible[MAX_WIFI_ENTRIES]; visible_wifi_entry_t visible[MAX_WIFI_ENTRIES];
int saved_count; int saved_count;
...@@ -1006,7 +1010,8 @@ int get_saved_wifi_list(char ssid_list[][SSID_MAX_LENGTH], int max_count) { ...@@ -1006,7 +1010,8 @@ int get_saved_wifi_list(char ssid_list[][SSID_MAX_LENGTH], int max_count) {
return count; return count;
} }
int orange_pi_save_wifi(const char *ssid, const char *password) { static int orange_pi_save_wifi_unlocked(const char *ssid, const char *password) {
if (wifi_hotspot_is_active()) return -1;
int already_saved; int already_saved;
int used_cached_password = 0; int used_cached_password = 0;
char cached_password[WIFI_PSK_MAX_LENGTH + 1] = {0}; char cached_password[WIFI_PSK_MAX_LENGTH + 1] = {0};
...@@ -1060,7 +1065,8 @@ int orange_pi_save_wifi(const char *ssid, const char *password) { ...@@ -1060,7 +1065,8 @@ int orange_pi_save_wifi(const char *ssid, const char *password) {
return 0; return 0;
} }
int orange_pi_connect_wifi(const char *ssid, const char *password) { static int orange_pi_connect_wifi_unlocked(const char *ssid, const char *password) {
if (wifi_hotspot_is_active()) return -1;
char command[512]; char command[512];
int ret; int ret;
...@@ -1352,7 +1358,8 @@ int app_wifi_check_saved(const char *ssid) ...@@ -1352,7 +1358,8 @@ int app_wifi_check_saved(const char *ssid)
return found ? 0 : -1; return found ? 0 : -1;
} }
int app_wifi_switch(const char *ssid) { static int app_wifi_switch_unlocked(const char *ssid) {
if (wifi_hotspot_is_active()) return -1;
saved_wifi_entry_t entries[MAX_WIFI_ENTRIES]; saved_wifi_entry_t entries[MAX_WIFI_ENTRIES];
int count; int count;
int found = 0; int found = 0;
...@@ -1388,7 +1395,8 @@ int app_wifi_switch(const char *ssid) { ...@@ -1388,7 +1395,8 @@ int app_wifi_switch(const char *ssid) {
} }
/* 删除已保存的指定 SSID(受保护的 jking 不可删) */ /* 删除已保存的指定 SSID(受保护的 jking 不可删) */
int app_wifi_delete(const char *ssid) { static int app_wifi_delete_unlocked(const char *ssid) {
if (wifi_hotspot_is_active()) return -1;
if (!ssid || !ssid[0]) if (!ssid || !ssid[0])
return -1; return -1;
...@@ -1403,3 +1411,43 @@ int app_wifi_delete(const char *ssid) { ...@@ -1403,3 +1411,43 @@ int app_wifi_delete(const char *ssid) {
return 0; return 0;
return -1; return -1;
} }
int device_wifi_connect_best_saved_visible(void) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return 0;
int result = 0;
if (!wifi_hotspot_is_active()) result = device_wifi_connect_best_saved_visible_unlocked();
wifi_operation_end();
return result;
}
int orange_pi_save_wifi(const char *ssid, const char *password) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return -1;
int result = -1;
if (!wifi_hotspot_is_active()) result = orange_pi_save_wifi_unlocked(ssid, password);
wifi_operation_end();
return result;
}
int orange_pi_connect_wifi(const char *ssid, const char *password) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return -1;
int result = -1;
if (!wifi_hotspot_is_active()) result = orange_pi_connect_wifi_unlocked(ssid, password);
wifi_operation_end();
return result;
}
int app_wifi_switch(const char *ssid) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return -1;
int result = -1;
if (!wifi_hotspot_is_active()) result = app_wifi_switch_unlocked(ssid);
wifi_operation_end();
return result;
}
int app_wifi_delete(const char *ssid) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return -1;
int result = -1;
if (!wifi_hotspot_is_active()) result = app_wifi_delete_unlocked(ssid);
wifi_operation_end();
return result;
}
#include "wifi_operation.h"
#include <sys/file.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#ifndef WIFI_OPERATION_LOCK_PATH
#define WIFI_OPERATION_LOCK_PATH "/run/car-controlserver-wifi.lock"
#endif
static _Thread_local int s_fd = -1;
static _Thread_local unsigned s_depth;
static _Thread_local pid_t s_owner;
int wifi_operation_begin_wait(unsigned seconds)
{
pid_t pid = getpid();
if (s_owner != pid) {
/* A forked child must not reuse or unlock its parent's open description. */
if (s_fd >= 0) close(s_fd);
s_fd = -1; s_depth = 0; s_owner = pid;
}
if (s_depth) { s_depth++; return 0; }
int fd = open(WIFI_OPERATION_LOCK_PATH, O_CREAT | O_RDWR | O_CLOEXEC, 0600);
if (fd < 0) return -1;
struct timespec start, now;
clock_gettime(CLOCK_MONOTONIC, &start);
for (;;) {
if (flock(fd, LOCK_EX | LOCK_NB) == 0) {
s_fd = fd; s_depth = 1; return 0;
}
int error = errno;
clock_gettime(CLOCK_MONOTONIC, &now);
if ((error != EAGAIN && error != EWOULDBLOCK && error != EINTR) ||
seconds == 0 || now.tv_sec - start.tv_sec >= seconds) {
close(fd); errno = error; return -1;
}
struct timespec pause = {0, 100000000}; nanosleep(&pause, NULL);
}
}
int wifi_operation_begin(void) { return wifi_operation_begin_wait(0); }
void wifi_operation_end(void)
{
if (s_owner != getpid() || !s_depth) return;
if (--s_depth == 0) { flock(s_fd, LOCK_UN); close(s_fd); s_fd = -1; }
}
#ifndef WIFI_OPERATION_H
#define WIFI_OPERATION_H
/* Cross-process, per-thread-recursive lock for operations that touch Wi-Fi.
* Normal operations never wait; hotspot startup can wait for an in-flight one.
*/
int wifi_operation_begin(void);
int wifi_operation_begin_wait(unsigned seconds);
void wifi_operation_end(void);
#endif
#include "main.h" #include "main.h"
#include "device_identity.h"
#include "volume_control.h"
#include "wifi_hotspot.h"
#include <unistd.h> #include <unistd.h>
typedef int (*AppInitFn)(void); typedef int (*AppInitFn)(void);
static volatile sig_atomic_t s_stopping;
static void request_shutdown(int sig) { (void)sig; s_stopping = 1; }
typedef enum { typedef enum {
APP_INIT_CORE = 0, APP_INIT_CORE = 0,
...@@ -67,6 +72,11 @@ static int init_go_deploy(void) ...@@ -67,6 +72,11 @@ static int init_go_deploy(void)
return go_deploy_check_and_update(); return go_deploy_check_and_update();
} }
static int init_local_audio_volume(void)
{
return volume_control_load(mqtt_topic_pure_number());
}
static int init_ipc_unix_server(void) static int init_ipc_unix_server(void)
{ {
return ipc_start_unix_server(NULL); return ipc_start_unix_server(NULL);
...@@ -95,6 +105,7 @@ static const AppInitStep s_init_steps[] = { ...@@ -95,6 +105,7 @@ static const AppInitStep s_init_steps[] = {
{APP_INIT_APP, "device_id", device_id_file_init, 1, -3, "设备id读取失败"}, {APP_INIT_APP, "device_id", device_id_file_init, 1, -3, "设备id读取失败"},
{APP_INIT_APP, "device_topic", device_mqtt_topic_init, 1, -4, "设备id判断失败"}, {APP_INIT_APP, "device_topic", device_mqtt_topic_init, 1, -4, "设备id判断失败"},
{APP_INIT_APP, "hotspot_recovery", wifi_hotspot_init, 0, 0, "上次热点会话恢复失败"},
{APP_INIT_APP, "wifi_autoconfig", init_wifi_autoconfig, 1, -5, "网络配网失败"}, {APP_INIT_APP, "wifi_autoconfig", init_wifi_autoconfig, 1, -5, "网络配网失败"},
{APP_INIT_DEVICE_DRIVER, "hardware_iic", hardware_iic_init, 1, -7, "硬件iic初始化失败"}, {APP_INIT_DEVICE_DRIVER, "hardware_iic", hardware_iic_init, 1, -7, "硬件iic初始化失败"},
...@@ -103,6 +114,7 @@ static const AppInitStep s_init_steps[] = { ...@@ -103,6 +114,7 @@ static const AppInitStep s_init_steps[] = {
{APP_INIT_MODULE_SERVICE, "runtime_deps", runtime_deps_ensure, 0, 0, "运行时依赖检查/安装失败"}, {APP_INIT_MODULE_SERVICE, "runtime_deps", runtime_deps_ensure, 0, 0, "运行时依赖检查/安装失败"},
{APP_INIT_MODULE_SERVICE, "request_data", request_date, 1, -5, "请求数据失败"}, {APP_INIT_MODULE_SERVICE, "request_data", request_date, 1, -5, "请求数据失败"},
{APP_INIT_MODULE_SERVICE, "mqtt_video", http_mqtt_video_init, 1, -6, "请求mqtt服务器和video数据失败"}, {APP_INIT_MODULE_SERVICE, "mqtt_video", http_mqtt_video_init, 1, -6, "请求mqtt服务器和video数据失败"},
{APP_INIT_MODULE_SERVICE, "local_audio_volume", init_local_audio_volume, 0, 0, "读取本地播报音量失败,使用默认30%音量"},
{APP_INIT_MODULE_SERVICE, "go_deploy", init_go_deploy, 0, 0, "Go 程序检查/部署失败"}, {APP_INIT_MODULE_SERVICE, "go_deploy", init_go_deploy, 0, 0, "Go 程序检查/部署失败"},
{APP_INIT_MODULE_SERVICE, "ipc_unix_server", init_ipc_unix_server, 1, -8, "IPC Unix Socket Server 启动失败"}, {APP_INIT_MODULE_SERVICE, "ipc_unix_server", init_ipc_unix_server, 1, -8, "IPC Unix Socket Server 启动失败"},
{APP_INIT_MODULE_SERVICE, "wifi_config_agent", init_wifi_config_agent, 0, 0, "WiFi配置助手UDP服务启动失败"}, {APP_INIT_MODULE_SERVICE, "wifi_config_agent", init_wifi_config_agent, 0, 0, "WiFi配置助手UDP服务启动失败"},
...@@ -165,8 +177,11 @@ int main() ...@@ -165,8 +177,11 @@ int main()
play_audio_file("connectionSuccessful.mp3"); play_audio_file("connectionSuccessful.mp3");
/* 工作线程在后台常驻;主线程不得 app_shutdown,否则 join 后进程退出被 systemd 拉起 */ /* 工作线程在后台常驻;主线程不得 app_shutdown,否则 join 后进程退出被 systemd 拉起 */
for (;;) signal(SIGTERM, request_shutdown);
sleep(3600); signal(SIGINT, request_shutdown);
while (!s_stopping)
sleep(1);
wifi_hotspot_shutdown();
return 0; return 0;
} }
...@@ -3,12 +3,17 @@ ...@@ -3,12 +3,17 @@
#include "http_config_mqtt.h" #include "http_config_mqtt.h"
#include "device_wifi_manager.h" #include "device_wifi_manager.h"
#include "audioplay.h" #include "audioplay.h"
#include "volume_control.h"
#include "wifi_hotspot.h"
#include "wifi_operation.h"
#include "device_command.h"
#include "cJSON.h" #include "cJSON.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <pthread.h>
#define WIFI_OFFLINE_RECOVERY_INTERVAL_SEC 40 #define WIFI_OFFLINE_RECOVERY_INTERVAL_SEC 40
#define WIFI_RECOVERY_SETTLE_SEC 5 #define WIFI_RECOVERY_SETTLE_SEC 5
...@@ -164,7 +169,7 @@ static int try_play_filepath(const char *filepath) { ...@@ -164,7 +169,7 @@ static int try_play_filepath(const char *filepath) {
if (access(filepath, F_OK) != 0) { if (access(filepath, F_OK) != 0) {
return 0; return 0;
} }
if (audioplay_file_with_browser_preempt(filepath, 1.0) == 0) { if (audioplay_file_with_browser_preempt(filepath, volume_control_get_local_volume()) == 0) {
my_zlog_debug("离线音频播放成功: %s", filepath); my_zlog_debug("离线音频播放成功: %s", filepath);
return 1; return 1;
} }
...@@ -172,9 +177,121 @@ static int try_play_filepath(const char *filepath) { ...@@ -172,9 +177,121 @@ static int try_play_filepath(const char *filepath) {
return 0; return 0;
} }
void audio_play_system_prompt(const char *event, const char *fallback_filename) {
char filepath[256];
if (event && strspn(event, "abcdefghijklmnopqrstuvwxyz0123456789-") == strlen(event)) {
static const char *formats[] = {
"/usr/share/sounds/freedesktop/stereo/%s.oga",
"/usr/share/sounds/ubuntu/stereo/%s.ogg",
"/usr/share/sounds/freedesktop/stereo/%s.ogg",
};
for (size_t i = 0; i < sizeof(formats) / sizeof(formats[0]); i++) {
snprintf(filepath, sizeof(filepath), formats[i], event);
if (try_play_filepath(filepath)) return;
}
}
if (fallback_filename) play_audio_file(fallback_filename);
}
typedef struct {
char filepath[256];
unsigned count;
unsigned gap_ms;
double volume;
} SystemBeeps;
static pthread_mutex_t s_beep_lock = PTHREAD_MUTEX_INITIALIZER;
static int s_beep_busy;
static char *prepare_system_beeps(const char *filepath, unsigned count, unsigned gap_ms) {
char *temporary = NULL;
int fd = g_file_open_tmp("car-system-beeps-XXXXXX", &temporary, NULL);
if (fd < 0) return NULL;
close(fd);
GPtrArray *args = g_ptr_array_new();
for (const char *const *p = (const char *const[]){"ffmpeg", "-nostdin", "-v", "error", "-y", NULL}; *p; p++)
g_ptr_array_add(args, (gpointer)*p);
for (unsigned i = 0; i < count; i++) {
g_ptr_array_add(args, "-i"); g_ptr_array_add(args, (gpointer)filepath);
}
GString *filter = g_string_new(NULL);
for (unsigned i = 0; i < count; i++)
g_string_append_printf(filter, "[%u:a]apad=pad_dur=%u.%03u[a%u];",
i, gap_ms / 1000, gap_ms % 1000, i);
for (unsigned i = 0; i < count; i++) g_string_append_printf(filter, "[a%u]", i);
g_string_append_printf(filter,
"concat=n=%u:v=0:a=1,adelay=500|500,apad=pad_dur=0.3[out]", count);
const char *tail[] = {"-filter_complex", filter->str, "-map", "[out]",
"-ac", "2", "-ar", "44100", "-c:a", "pcm_s16le", "-f", "wav", temporary, NULL};
for (const char *const *p = tail; *p; p++) g_ptr_array_add(args, (gpointer)*p);
g_ptr_array_add(args, NULL);
int rc = device_command_run((const char *const *)args->pdata, 8, NULL);
g_ptr_array_free(args, TRUE); g_string_free(filter, TRUE);
if (rc != 0) {
my_zlog_warn("system prompt: continuous tone preparation failed exit=%d", rc);
unlink(temporary); g_free(temporary); return NULL;
}
return temporary;
}
static void *play_system_beeps(void *arg) {
SystemBeeps *job = arg;
my_zlog_info("system prompt: file=%s repeats=%u gap_ms=%u volume=%.3f",
job->filepath, job->count, job->gap_ms, job->volume);
/* Keep ALSA open through all short tones; allow the USB output to wake first. */
char *continuous = prepare_system_beeps(job->filepath, job->count, job->gap_ms);
unsigned plays = continuous ? 1 : job->count;
for (unsigned i = 0; i < plays; i++) {
my_zlog_info("system prompt: playback %u/%u continuous=%d", i + 1, plays, continuous != NULL);
int rc = audioplay_file_with_browser_preempt(continuous ? continuous : job->filepath, job->volume);
if (rc != 0) {
my_zlog_warn("system prompt: playback failed exit=%d", rc);
break;
}
if (i + 1 < plays) usleep(job->gap_ms * 1000);
}
if (continuous) { unlink(continuous); g_free(continuous); }
my_zlog_info("system prompt: playback task finished");
free(job);
pthread_mutex_lock(&s_beep_lock); s_beep_busy = 0; pthread_mutex_unlock(&s_beep_lock);
return NULL;
}
void audio_play_system_beeps(unsigned count, unsigned gap_ms) {
if (!count || count > 3 || gap_ms > 1000) return;
static const char *formats[] = {
"/usr/share/sounds/freedesktop/stereo/%s.oga",
"/usr/share/sounds/freedesktop/stereo/%s.ogg",
"/usr/share/sounds/ubuntu/stereo/%s.ogg",
};
const char *names[] = {"bell", "device-added", "dialog-information"};
SystemBeeps *job = calloc(1, sizeof(*job));
if (!job) return;
int found = 0;
for (size_t i = 0; i < sizeof(names) / sizeof(names[0]) && !found; i++) {
for (size_t j = 0; j < sizeof(formats) / sizeof(formats[0]); j++) {
snprintf(job->filepath, sizeof(job->filepath), formats[j], names[i]);
if (access(job->filepath, R_OK) == 0) { found = 1; break; }
}
}
if (!found) { my_zlog_warn("system prompt: no readable system sound available"); free(job); return; }
/* Provisioning tones have their own fixed gain, independent of driving speech. */
job->count = count; job->gap_ms = gap_ms; job->volume = 0.5;
pthread_mutex_lock(&s_beep_lock);
if (s_beep_busy) {
pthread_mutex_unlock(&s_beep_lock); free(job);
my_zlog_warn("system prompt: previous short tone still playing"); return;
}
s_beep_busy = 1; pthread_mutex_unlock(&s_beep_lock);
pthread_t thread;
if (pthread_create(&thread, NULL, play_system_beeps, job) != 0) {
pthread_mutex_lock(&s_beep_lock); s_beep_busy = 0; pthread_mutex_unlock(&s_beep_lock);
free(job); my_zlog_warn("system prompt: cannot create playback thread"); return;
}
pthread_detach(thread);
}
// 播放离线本地音频(无网络场景;按 audio_get_language 选择中文或 EN) // 播放离线本地音频(无网络场景;按 audio_get_language 选择中文或 EN)
void play_audio_file(const char *filename) { void play_audio_file(const char *filename) {
char cmd[512];
char filepath[256]; char filepath[256];
my_zlog_debug("尝试播放音频: %s (语言: %s)", filename, s_current_lang); my_zlog_debug("尝试播放音频: %s (语言: %s)", filename, s_current_lang);
...@@ -204,28 +321,7 @@ void play_audio_file(const char *filename) { ...@@ -204,28 +321,7 @@ void play_audio_file(const char *filename) {
else if (strstr(filename, "Success")) sys_sound = "service-login"; else if (strstr(filename, "Success")) sys_sound = "service-login";
else if (strstr(filename, "toScan")) sys_sound = "dialog-question"; else if (strstr(filename, "toScan")) sys_sound = "dialog-question";
if (is_command_available("paplay")) { audio_play_system_prompt(sys_sound, NULL);
snprintf(cmd, sizeof(cmd), "paplay /usr/share/sounds/ubuntu/stereo/%s.ogg", sys_sound);
if (system(cmd) == 0) {
my_zlog_debug("系统音 (paplay-ubuntu) 播放成功: %s", sys_sound);
return;
}
snprintf(cmd, sizeof(cmd), "paplay /usr/share/sounds/freedesktop/stereo/%s.oga", sys_sound);
if (system(cmd) == 0) {
my_zlog_debug("系统音 (paplay-freedesktop) 播放成功: %s", sys_sound);
return;
}
}
if (is_command_available("ffplay")) {
snprintf(cmd, sizeof(cmd), "ffplay -nodisp -autoexit -loglevel quiet /usr/share/sounds/ubuntu/stereo/%s.ogg", sys_sound);
if (system(cmd) == 0) {
my_zlog_debug("系统音 (ffplay) 播放成功: %s", sys_sound);
return;
}
}
my_zlog_error("所有播放尝试均失败!");
} }
static void download_cn_audio(const char *filename, int optional) { static void download_cn_audio(const char *filename, int optional) {
...@@ -464,6 +560,7 @@ static int has_internet_connection() { ...@@ -464,6 +560,7 @@ static int has_internet_connection() {
/* 一次完整的断网恢复周期:播报与扫描主动连接必须在同一个周期执行。 */ /* 一次完整的断网恢复周期:播报与扫描主动连接必须在同一个周期执行。 */
static int run_offline_recovery_cycle(void) { static int run_offline_recovery_cycle(void) {
if (wifi_hotspot_is_active()) return 0;
my_zlog_warn("断网恢复: 开始 40 秒周期播报和已保存 WiFi 检测"); my_zlog_warn("断网恢复: 开始 40 秒周期播报和已保存 WiFi 检测");
play_audio_file("connectionFailed.mp3"); play_audio_file("connectionFailed.mp3");
...@@ -492,7 +589,7 @@ void *thread_wifi_offline_recovery(void *arg) { ...@@ -492,7 +589,7 @@ void *thread_wifi_offline_recovery(void *arg) {
while (1) { while (1) {
time_t cycle_started = time(NULL); time_t cycle_started = time(NULL);
if (!has_internet_connection()) if (!wifi_hotspot_is_active() && !has_internet_connection())
run_offline_recovery_cycle(); run_offline_recovery_cycle();
time_t cycle_finished = time(NULL); time_t cycle_finished = time(NULL);
...@@ -506,16 +603,21 @@ void *thread_wifi_offline_recovery(void *arg) { ...@@ -506,16 +603,21 @@ void *thread_wifi_offline_recovery(void *arg) {
// 尝试连接 WiFi // 尝试连接 WiFi
static int try_connect_wifi(const char *ssid, const char *password) { static int try_connect_wifi(const char *ssid, const char *password) {
if (wifi_hotspot_is_active() || wifi_operation_begin() != 0) return 0;
char cmd[512]; char cmd[512];
// 使用 nmcli 连接,成功会自动保存为默认 // 使用 nmcli 连接,成功会自动保存为默认
snprintf(cmd, sizeof(cmd), "nmcli dev wifi connect \"%s\" password \"%s\"", ssid, password); snprintf(cmd, sizeof(cmd), "nmcli dev wifi connect \"%s\" password \"%s\"", ssid, password);
my_zlog_info("正在尝试连接 WiFi: %s ...", ssid); my_zlog_info("正在尝试连接 WiFi: %s ...", ssid);
return system(cmd) == 0; int result = !wifi_hotspot_is_active() && system(cmd) == 0;
wifi_operation_end();
return result;
} }
// 自动配网主逻辑 // 自动配网主逻辑
void check_and_autoconfig_wifi() { void check_and_autoconfig_wifi() {
audio_init_offline_language(); audio_init_offline_language();
/* A standalone portal/probe may already own Wi-Fi when main restarts. */
while (wifi_hotspot_is_active()) sleep(1);
my_zlog_debug("开始检查网络连接状态..."); my_zlog_debug("开始检查网络连接状态...");
// 1. 检查并处理依赖 // 1. 检查并处理依赖
...@@ -536,6 +638,7 @@ void check_and_autoconfig_wifi() { ...@@ -536,6 +638,7 @@ void check_and_autoconfig_wifi() {
time_t last_camera_warning_time = 0; time_t last_camera_warning_time = 0;
while (1) { while (1) {
if (wifi_hotspot_is_active()) { sleep(1); continue; }
time_t now = time(NULL); time_t now = time(NULL);
if (last_recovery_time == 0 || if (last_recovery_time == 0 ||
difftime(now, last_recovery_time) >= WIFI_OFFLINE_RECOVERY_INTERVAL_SEC) { difftime(now, last_recovery_time) >= WIFI_OFFLINE_RECOVERY_INTERVAL_SEC) {
......
...@@ -37,4 +37,10 @@ const char *audio_toggle_cn_en(void); ...@@ -37,4 +37,10 @@ const char *audio_toggle_cn_en(void);
// 播放离线本地音频(按当前语言;中文 ~/audio/xxx.mp3,英语 ~/audio/EN/xxx.mp3) // 播放离线本地音频(按当前语言;中文 ~/audio/xxx.mp3,英语 ~/audio/EN/xxx.mp3)
void play_audio_file(const char *filename); void play_audio_file(const char *filename);
// 优先系统提示音,缺失时回退已有语音;均使用缓存的播报音量。
void audio_play_system_prompt(const char *event, const char *fallback_filename);
// 后台播放同一系统铃声,通过次数和间隔区分状态,固定50%音量。
void audio_play_system_beeps(unsigned count, unsigned gap_ms);
#endif #endif
File deleted
#include "common.h" #include "common.h"
#include "audioplay.h" #include "audioplay.h"
#include "audio_sink.h" /* USB声卡排队锁 */ #include "audio_sink.h" /* USB声卡排队锁 */
#include "volume_control.h"
#include "device_identity.h" #include "device_identity.h"
#include "mqtt_init.h" #include "mqtt_init.h"
#include "http_config_mqtt.h" #include "http_config_mqtt.h"
...@@ -217,13 +218,15 @@ int audioplay_file_with_browser_preempt(const char *filepath, double volume) { ...@@ -217,13 +218,15 @@ int audioplay_file_with_browser_preempt(const char *filepath, double volume) {
volume = audioplay_volume_clamp(volume); volume = audioplay_volume_clamp(volume);
/* 先和项目内 DataChannel/本地音频排队,再让浏览器临时释放 USB 声卡。 */ /* 先和项目内 DataChannel/本地音频排队,再让浏览器临时释放 USB 声卡。 */
my_zlog_info("local audio: waiting for speaker");
audio_sink_lock_alsa(); audio_sink_lock_alsa();
my_zlog_info("local audio: speaker acquired, suspending Pulse output");
pulse_suspended = (pulse_suspend_default_output(1) == 0); pulse_suspended = (pulse_suspend_default_output(1) == 0);
if (pulse_suspended) { if (pulse_suspended) {
snprintf(command, sizeof(command), snprintf(command, sizeof(command),
/* timeout 使用 KILL,保证卡死的播放进程到 20 秒时立即释放 ALSA。 */ /* timeout 使用 KILL,保证卡死的播放进程到 20 秒时立即释放 ALSA。 */
"timeout -s KILL %ds gst-launch-1.0 -q filesrc location=%s ! mpegaudioparse ! mpg123audiodec ! audioconvert ! volume volume=%.3f ! audioresample ! audio/x-raw,channels=2 ! alsasink device=%s sync=true >/dev/null 2>&1", "timeout -s KILL %ds gst-launch-1.0 -q filesrc location=%s ! decodebin ! audioconvert ! volume volume=%.3f ! audioresample ! audio/x-raw,channels=2 ! alsasink device=%s sync=true >/dev/null 2>&1",
AUDIO_ANNOUNCEMENT_TIMEOUT_SEC, quoted_path, volume, AUDIO_ANNOUNCEMENT_TIMEOUT_SEC, quoted_path, volume,
AUDIO_LOCAL_ALSA_DEVICE); AUDIO_LOCAL_ALSA_DEVICE);
} else { } else {
...@@ -233,8 +236,11 @@ int audioplay_file_with_browser_preempt(const char *filepath, double volume) { ...@@ -233,8 +236,11 @@ int audioplay_file_with_browser_preempt(const char *filepath, double volume) {
AUDIO_ANNOUNCEMENT_TIMEOUT_SEC, volume, quoted_path); AUDIO_ANNOUNCEMENT_TIMEOUT_SEC, volume, quoted_path);
} }
my_zlog_info("local audio: playback started volume=%.3f mode=%s",
volume, pulse_suspended ? "ALSA" : "default output");
ret = system(command); ret = system(command);
exit_code = audio_system_exit_code(ret); exit_code = audio_system_exit_code(ret);
my_zlog_info("local audio: playback exit=%d", exit_code);
/* 无论正常结束、播放失败还是 timeout,退出前都恢复浏览器音频。 */ /* 无论正常结束、播放失败还是 timeout,退出前都恢复浏览器音频。 */
if (pulse_suspended) { if (pulse_suspended) {
...@@ -397,7 +403,8 @@ void audioplay_cycle(){ ...@@ -397,7 +403,8 @@ void audioplay_cycle(){
if (local_play_pending) { if (local_play_pending) {
int exit_code; int exit_code;
my_zlog_info("播放本地音频: %s", local_filepath); my_zlog_info("播放本地音频: %s", local_filepath);
exit_code = audioplay_file_with_browser_preempt(local_filepath, 1.0); exit_code = audioplay_file_with_browser_preempt(
local_filepath, volume_control_get_local_volume());
if (exit_code == 0) { if (exit_code == 0) {
my_zlog_debug("本地音频播放完成: %s", local_filepath); my_zlog_debug("本地音频播放完成: %s", local_filepath);
} else { } else {
......
...@@ -202,9 +202,21 @@ master/ ...@@ -202,9 +202,21 @@ master/
- **取值范围**:代码侧钳位为 **`[0, 2]`**(小于 0 按 0,大于 2 按 2)。 - **取值范围**:代码侧钳位为 **`[0, 2]`**(小于 0 按 0,大于 2 按 2)。
- **命令行格式**:`ffplay` 参数中音量格式化为 **`%.3f`**(保留 3 位小数)。 - **命令行格式**:`ffplay` 参数中音量格式化为 **`%.3f`**(保留 3 位小数)。
### 有人驾驶本地播报(`message_type` 2017)
- 开机联网后请求一次 `/api/drive/use/status/{设备号}`,解析字符串 `businessJson` 内的 `volume`,兼容数值 `0.01` 和数字字符串 `"0.01"`,保存在运行内存中,不再每 3 秒轮询;后台修改后需重启程序重新读取。
- 音量直接使用线性倍率:`0.3` 表示 30%,小于 0 按 0,大于 1 按 1(100%);请求失败或字段无效时默认 `0.3`。
- 该缓存用于加速提示、驾驶等级等 2017 本地音频;每次启动重新读取。
运行数据目录由 CMake `CAR_RUNTIME_DIR` 指定,默认 `/home/orangepi/car/master`。在临时目录编译时也使用部署目录读取 `Deviceld.txt`、日志及配置,不能将源码临时路径作为运行数据目录。部署到其他位置时通过 `-DCAR_RUNTIME_DIR=/实际部署目录` 设置。
### 阅读顺序建议(给接手同事) ### 阅读顺序建议(给接手同事)
1. `app/device_identity/device_identity.c` → 搞清「设备号如何落到具体车型」。 1. `app/device_identity/device_identity.c` → 搞清「设备号如何落到具体车型」。
2. `drivers/gpio/device_init.c` → 搞清「该车型初始化哪些引脚、软 PWM」。 2. `drivers/gpio/device_init.c` → 搞清「该车型初始化哪些引脚、软 PWM」。
3. `drivers/devicecontrol/devcontrol_common.c` + 对应 `*_control.c` → 搞清「遥控数据如何变成电机动作」。 3. `drivers/devicecontrol/devcontrol_common.c` + 对应 `*_control.c` → 搞清「遥控数据如何变成电机动作」。
4. `modules/mqtt/` → 搞清「 topic 与 payload 如何进 `device_walk_control`」。 4. `modules/mqtt/` → 搞清「 topic 与 payload 如何进 `device_walk_control`」。
### MQTT 维护与热点配网
Tailscale 2028 及反馈 3028、热点 2029 及反馈 3029、网页配网事务与回退规则见 `交接文档/MQTT维护与热点配网.md`。联网成功提示语及系统提示音也使用启动时读取的播报音量。
#include "device_feedback.h"
#include <stdbool.h>
#include "mqtt_init.h"
#include "device_identity.h"
int device_feedback_send(int type, const cJSON *request, const char *action,
const char *state, int code, const char *message, int final,
const cJSON *details)
{
cJSON *root = cJSON_CreateObject(), *head = cJSON_CreateObject();
cJSON *body = cJSON_CreateObject();
if (!root || !head || !body) {
cJSON_Delete(root); cJSON_Delete(head); cJSON_Delete(body);
return 0;
}
cJSON_AddNumberToObject(head, "message_type", type);
cJSON_AddItemToObject(root, "head", head);
cJSON_AddItemToObject(root, "body", body);
cJSON_AddStringToObject(body, "action", action);
cJSON_AddStringToObject(body, "status", state);
cJSON_AddNumberToObject(body, "code", code);
cJSON_AddBoolToObject(body, "success", code == 0);
cJSON_AddBoolToObject(body, "final", final);
cJSON_AddStringToObject(body, "message", message);
const cJSON *key = cJSON_GetObjectItemCaseSensitive(request, "key");
if (cJSON_IsString(key) || cJSON_IsNumber(key))
cJSON_AddItemToObject(body, "key", cJSON_Duplicate(key, 1));
if (details)
cJSON_AddItemToObject(body, "data", cJSON_Duplicate(details, 1));
char *payload = cJSON_PrintUnformatted(root);
int sent = payload ? mqtt_publish_to_topics(mqtt_topic_dev2app_number(),
mqtt_topic_pure_number(), payload, 1) : 0;
cJSON_free(payload);
cJSON_Delete(root);
return sent;
}
#ifndef DEVICE_FEEDBACK_H
#define DEVICE_FEEDBACK_H
#include <cjson/cJSON.h>
/* details is borrowed; only the request correlation key is echoed. */
int device_feedback_send(int message_type, const cJSON *request,
const char *action, const char *state, int code, const char *message,
int final, const cJSON *details);
#endif
...@@ -5,6 +5,8 @@ ...@@ -5,6 +5,8 @@
#include "drivers_common.h" #include "drivers_common.h"
#include "modules_common.h" #include "modules_common.h"
#include "webrtcpush_run.h" #include "webrtcpush_run.h"
#include "wifi_hotspot.h"
#include "device_feedback.h"
int g_heartbeat_count = 0; // 心跳计数 int g_heartbeat_count = 0; // 心跳计数
...@@ -382,6 +384,13 @@ int device_message_receive(cJSON *json) ...@@ -382,6 +384,13 @@ int device_message_receive(cJSON *json)
return 1; return 1;
} }
if (wifi_hotspot_is_active() && (s_message_type == 2003 || s_message_type == 2004 ||
s_message_type == 2008 || s_message_type == 2009)) {
device_feedback_send(3029, body, "configure", "busy", -1,
"设备热点配网中,请使用热点配网页面修改 Wi-Fi", 1, NULL);
return 1;
}
switch (s_message_type) switch (s_message_type)
{ {
case 2: case 2:
...@@ -478,6 +487,9 @@ int device_message_receive(cJSON *json) ...@@ -478,6 +487,9 @@ int device_message_receive(cJSON *json)
tailscale_control(body); tailscale_control(body);
my_zlog_debug("tailscale control"); my_zlog_debug("tailscale control");
break; break;
case 2029:
wifi_hotspot_control(body);
break;
default: default:
break; break;
} }
......
#include "device_command.h"
#include <glib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int device_command_run(const char *const argv[], unsigned seconds, char **output)
{
char deadline[16];
g_snprintf(deadline, sizeof(deadline), "%u", seconds);
GPtrArray *args = g_ptr_array_new();
if (geteuid() != 0) {
g_ptr_array_add(args, "sudo"); g_ptr_array_add(args, "-n");
}
g_ptr_array_add(args, "timeout"); g_ptr_array_add(args, "-k");
g_ptr_array_add(args, "5"); g_ptr_array_add(args, deadline);
for (int i = 0; argv[i]; i++) g_ptr_array_add(args, (gpointer)argv[i]);
g_ptr_array_add(args, NULL);
gchar *out = NULL, *err = NULL;
GError *error = NULL;
gint status = 0;
gboolean started = g_spawn_sync(NULL, (gchar **)args->pdata, NULL,
G_SPAWN_SEARCH_PATH, NULL, NULL, &out, &err, &status, &error);
if (output) {
const char *text = error ? error->message : (err && err[0] ? err : out);
*output = g_strndup(text ? text : "", 65536);
}
g_clear_error(&error);
g_free(out); g_free(err); g_ptr_array_free(args, TRUE);
return started && WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}
#ifndef DEVICE_COMMAND_H
#define DEVICE_COMMAND_H
/* Executes argv directly with a deadline; output is bounded and g_free()-owned. */
int device_command_run(const char *const argv[], unsigned timeout_sec, char **output);
#endif
#include <stdio.h> #include "tailscale_deploy.h"
#include <stdlib.h> #include "device_feedback.h"
#include "device_command.h"
#include "mylog.h"
#include <glib.h>
#include <pthread.h>
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include <cJSON.h>
#include "tailscale_deploy.h"
#include "common.h"
int tailscale_control(cJSON *body) { static pthread_mutex_t s_mutex = PTHREAD_MUTEX_INITIALIZER;
if (body == NULL) { static int s_busy;
my_zlog_error("tailscale_control: body is NULL"); static char s_last_digest[65];
return -1; static gint64 s_last_request;
} typedef struct { cJSON *request; char *action; char *authkey; } TailscaleJob;
cJSON *authkey_json = cJSON_GetObjectItem(body, "authkey"); static void report(TailscaleJob *job, const char *state, int code,
if (!cJSON_IsString(authkey_json) || (authkey_json->valuestring == NULL)) { const char *message, int final)
my_zlog_error("tailscale_control: authkey is missing or invalid"); {
return -2; device_feedback_send(3028, job->request, job->action, state, code, message, final, NULL);
} }
char *authkey = authkey_json->valuestring;
if (strcmp(authkey, "stop") == 0) { static int command(TailscaleJob *job, const char *const args[], unsigned timeout)
my_zlog_info("tailscale_control: Stopping Tailscale..."); {
// 尝试停止 tailscale并捕获输出 char *output = NULL;
FILE *fp = popen("sudo tailscale down 2>&1", "r"); int rc = device_command_run(args, timeout, &output);
if (fp != NULL) { /* CLI/installer output can contain credentials: never publish it verbatim. */
char buf[256]; if (rc != 0) my_zlog_warn("tailscale: %s command failed, exit=%d", job->action, rc);
while (fgets(buf, sizeof(buf), fp) != NULL) { g_free(output);
// 去除换行符让日志更整洁 return rc;
size_t len = strlen(buf); }
if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
my_zlog_info("tailscale output: %s", buf);
}
int ret = pclose(fp);
if (WEXITSTATUS(ret) == 0) {
my_zlog_info("tailscale_control: Tailscale stopped successfully");
} else {
my_zlog_warn("tailscale_control: Failed to stop Tailscale, ret=%d", WEXITSTATUS(ret));
return -3;
}
} else {
my_zlog_error("tailscale_control: Failed to execute stop command");
return -3;
}
} else { static int installed(void)
// 检查 tailscale 是否安装 {
if (system("which tailscale > /dev/null 2>&1") != 0) { char *path = g_find_program_in_path("tailscale");
my_zlog_info("tailscale_control: Tailscale not found. Installing..."); int found = path != NULL; g_free(path); return found;
// 安装 tailscale }
int install_ret = system("curl -fsSL https://tailscale.com/install.sh | sh");
if (install_ret != 0) {
my_zlog_warn("tailscale_control: Failed to install Tailscale, ret=%d", install_ret);
return -4;
}
// 用户要求不开机自启,因此先 disable
int disable_ret = system("sudo systemctl disable tailscaled > /dev/null 2>&1");
if (disable_ret != 0) {
my_zlog_warn("tailscale_control: disable tailscaled failed, ret=%d", disable_ret);
}
my_zlog_info("tailscale_control: Tailscale installed successfully");
}
// 确保服务已启动 static void *worker(void *arg)
int start_service_ret = system("sudo systemctl start tailscaled > /dev/null 2>&1"); {
if (start_service_ret != 0) { TailscaleJob *job = arg;
my_zlog_warn("tailscale_control: start tailscaled service failed, ret=%d", start_service_ret); int rc = 0;
if (strcmp(job->action, "stop") == 0) {
report(job, "stopping", 0, "正在关闭 Tailscale", 0);
if (installed()) {
const char *args[] = {"tailscale", "down", NULL};
rc = command(job, args, 35);
} }
report(job, rc == 0 ? "disabled" : "failed", rc,
// 启动 tailscale rc == 0 ? "Tailscale 已关闭" : "Tailscale 关闭失败,请检查服务状态", 1);
char cmd[512]; goto done;
snprintf(cmd, sizeof(cmd), "sudo tailscale up --authkey %s --hostname orangepi-01 2>&1", authkey); }
if (!installed()) {
my_zlog_info("tailscale_control: Starting Tailscale..."); report(job, "installing", 0, "正在安装 Tailscale", 0);
char *path = NULL;
FILE *fp_up = popen(cmd, "r"); int fd = g_file_open_tmp("car-tailscale-XXXXXX", &path, NULL);
if (fp_up != NULL) { if (fd < 0) { rc = -1; goto install_failed; }
char buf[256]; close(fd);
while (fgets(buf, sizeof(buf), fp_up) != NULL) { const char *download[] = {"curl", "-fsSL", "--max-time", "45",
size_t len = strlen(buf); "https://tailscale.com/install.sh", "-o", path, NULL};
if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0'; rc = command(job, download, 50);
my_zlog_info("tailscale up output: %s", buf); if (rc == 0) {
} const char *install[] = {"sh", path, NULL};
int start_ret = pclose(fp_up); rc = command(job, install, 300);
if (WEXITSTATUS(start_ret) == 0) {
my_zlog_info("tailscale_control: Tailscale started successfully");
} else {
my_zlog_warn("tailscale_control: Failed to start Tailscale, ret=%d", WEXITSTATUS(start_ret));
return -5;
}
} else {
my_zlog_error("tailscale_control: Failed to execute start command");
return -5;
} }
unlink(path); g_free(path);
if (rc != 0 || !installed()) { rc = rc ? rc : -1; goto install_failed; }
const char *disable[] = {"systemctl", "disable", "tailscaled", NULL};
command(job, disable, 20);
report(job, "installed", 0, "Tailscale 安装成功", strcmp(job->action, "install") == 0);
} else if (strcmp(job->action, "install") == 0) {
report(job, "installed", 0, "Tailscale 已安装", 1);
} }
if (strcmp(job->action, "install") == 0) goto done;
report(job, "starting", 0, "正在开启 Tailscale", 0);
const char *service[] = {"systemctl", "start", "tailscaled", NULL};
rc = command(job, service, 30);
if (rc == 0) {
const char *up[] = {"tailscale", "up", "--timeout=45s", "--authkey",
job->authkey, "--hostname", g_get_host_name(), NULL};
rc = command(job, up, 50);
}
report(job, rc == 0 ? "enabled" : "failed", rc,
rc == 0 ? "Tailscale 已开启" : "Tailscale 开启失败,请检查授权密钥和网络", 1);
goto done;
install_failed:
report(job, "failed", rc, "Tailscale 安装失败,请检查网络和软件源", 1);
done:
cJSON_Delete(job->request); g_free(job->action);
if (job->authkey) memset(job->authkey, 0, strlen(job->authkey));
g_free(job->authkey); g_free(job);
pthread_mutex_lock(&s_mutex); s_busy = 0; pthread_mutex_unlock(&s_mutex);
return NULL;
}
int tailscale_control(cJSON *body)
{
const cJSON *a = cJSON_GetObjectItemCaseSensitive(body, "action");
const cJSON *key = cJSON_GetObjectItemCaseSensitive(body, "authkey");
const char *auth = cJSON_IsString(key) ? key->valuestring : NULL;
const char *action = cJSON_IsString(a) ? a->valuestring :
(auth && strcmp(auth, "stop") == 0 ? "stop" : "start");
if ((strcmp(action, "start") != 0 && strcmp(action, "stop") != 0 &&
strcmp(action, "install") != 0) ||
(strcmp(action, "start") == 0 && (!auth || !auth[0] || strlen(auth) > 512))) {
device_feedback_send(3028, body, action, "failed", -2,
"参数无效:开启需要 authkey,关闭可使用 action=stop", 1, NULL);
return -2;
}
char *json = cJSON_PrintUnformatted(body);
char *digest = g_compute_checksum_for_string(G_CHECKSUM_SHA256, json ? json : "", -1);
cJSON_free(json);
pthread_mutex_lock(&s_mutex);
gint64 now = g_get_monotonic_time();
if (strcmp(s_last_digest, digest) == 0 && (s_busy || now - s_last_request < 2000000)) {
pthread_mutex_unlock(&s_mutex); g_free(digest); return 0;
}
if (s_busy) {
pthread_mutex_unlock(&s_mutex); g_free(digest);
device_feedback_send(3028, body, action, "busy", -3,
"已有 Tailscale 操作正在执行", 1, NULL);
return -3;
}
s_busy = 1; g_strlcpy(s_last_digest, digest, sizeof(s_last_digest));
s_last_request = now;
pthread_mutex_unlock(&s_mutex); g_free(digest);
TailscaleJob *job = g_new0(TailscaleJob, 1);
job->request = cJSON_Duplicate(body, 1);
job->action = g_strdup(action); job->authkey = g_strdup(auth);
report(job, "accepted", 0, "已收到 Tailscale 操作", 0);
pthread_t thread;
if (pthread_create(&thread, NULL, worker, job) != 0) {
report(job, "failed", -1, "无法创建 Tailscale 工作线程", 1);
cJSON_Delete(job->request); g_free(job->action); g_free(job->authkey); g_free(job);
pthread_mutex_lock(&s_mutex); s_busy = 0; pthread_mutex_unlock(&s_mutex);
return -1;
}
pthread_detach(thread);
return 0; return 0;
} }
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
#include "mpp_h264_source.h" #include "mpp_h264_source.h"
#include "audio_source.h" #include "audio_source.h"
#include "audio_sink.h" #include "audio_sink.h"
#include "volume_control.h"
#include "webrtcpush_config.h" #include "webrtcpush_config.h"
#include "webrtcpush_log.h" #include "webrtcpush_log.h"
#include "ws_signaling.h" #include "ws_signaling.h"
...@@ -103,7 +102,6 @@ typedef struct { ...@@ -103,7 +102,6 @@ typedef struct {
/* 音频 Opus track */ /* 音频 Opus track */
AudioSource *audio_source; AudioSource *audio_source;
AudioSink *audio_sink; AudioSink *audio_sink;
VolumeControl *volume_ctrl;
int audio_track; int audio_track;
int audio_payload_type; int audio_payload_type;
gboolean audio_track_open; gboolean audio_track_open;
...@@ -2087,10 +2085,6 @@ int rtc_client_start(AppState *app) ...@@ -2087,10 +2085,6 @@ int rtc_client_start(AppState *app)
client->audio_sink = audio_sink_start(WEBRTCPUSH_AUDIO_PLAYBACK_DEVICE, &play_err); client->audio_sink = audio_sink_start(WEBRTCPUSH_AUDIO_PLAYBACK_DEVICE, &play_err);
if (client->audio_sink) { if (client->audio_sink) {
my_zlog_info("libdatachannel: audio sink started device=%s", WEBRTCPUSH_AUDIO_PLAYBACK_DEVICE); my_zlog_info("libdatachannel: audio sink started device=%s", WEBRTCPUSH_AUDIO_PLAYBACK_DEVICE);
if (app->dev_room && app->dev_room[0]) {
client->volume_ctrl = volume_control_start(app->dev_room, client->audio_sink);
my_zlog_info("libdatachannel: volume control started vehicle=%s", app->dev_room);
}
} else { } else {
my_zlog_warn("libdatachannel: audio sink start failed: %s", play_err ? play_err : "?"); my_zlog_warn("libdatachannel: audio sink start failed: %s", play_err ? play_err : "?");
g_free(play_err); g_free(play_err);
...@@ -2133,8 +2127,6 @@ void rtc_client_stop(AppState *app) ...@@ -2133,8 +2127,6 @@ void rtc_client_stop(AppState *app)
g_thread_join(client->send_thread); g_thread_join(client->send_thread);
if (client->audio_send_thread) if (client->audio_send_thread)
g_thread_join(client->audio_send_thread); g_thread_join(client->audio_send_thread);
if (client->volume_ctrl)
volume_control_stop(client->volume_ctrl);
if (client->audio_sink) if (client->audio_sink)
audio_sink_stop(client->audio_sink); audio_sink_stop(client->audio_sink);
if (client->audio_source) if (client->audio_source)
......
#include "volume_control.h" #include "volume_control.h"
#include "webrtcpush_log.h" #include "mylog.h"
#include <libsoup/soup.h> #include <libsoup/soup.h>
#include <json-glib/json-glib.h> #include <json-glib/json-glib.h>
#include <math.h> #include <math.h>
#include <errno.h>
/* /*
* 定时拉取后端音量接口并设置到 AudioSink。 * 开机联网后拉取一次后端音量,缓存给 MQTT 2017 本地播报使用。
* *
* 接口:GET https://fcrs-api.yd-ss.com/api/drive/use/status/{vehicleId} * 接口:GET https://fcrs-api.yd-ss.com/api/drive/use/status/{vehicleId}
* 响应 JSON 中 businessJson 是字符串(需二次解析),取 volume 字段(0~1)。 * businessJson 是字符串(需二次解析),volume 支持数值和数字字符串:"0.01" = 1%。
* 有效数值钳位到 0~1;请求失败、缺字段或无效值保留默认 0.3。
* businessJson 可能出现在 data.businessJson / data.data.businessJson / data.result.businessJson。 * businessJson 可能出现在 data.businessJson / data.data.businessJson / data.result.businessJson。
* 每 3 秒拉一次,与手机端逻辑对齐。 * 缓存仅在工作线程启动前写入,运行期间只读,不再定时拉取。
*/ */
#define VC_INTERVAL_SEC 3 #define VC_DEFAULT_VOLUME 0.3
#define VC_DEFAULT_VOLUME 0.5
#define VC_VOLUME_EPSILON 0.001 /* 音量变化阈值,避免重复设置 */
#define VC_HTTP_TIMEOUT_SEC 5 #define VC_HTTP_TIMEOUT_SEC 5
#define VC_API_BASE "https://fcrs-api.yd-ss.com/api/drive/use/status/" #define VC_API_BASE "https://fcrs-api.yd-ss.com/api/drive/use/status/"
struct VolumeControl { static double s_local_volume = VC_DEFAULT_VOLUME;
gchar *vehicle_id;
AudioSink *sink; double volume_control_get_local_volume(void)
SoupSession *session; {
GThread *thread; return s_local_volume;
gint stop; /* 原子停止标志 */ }
gdouble current_volume;
}; static const gchar *business_json_string(JsonObject *obj)
{
JsonNode *node = json_object_get_member(obj, "businessJson");
if (node && JSON_NODE_HOLDS_VALUE(node) &&
json_node_get_value_type(node) == G_TYPE_STRING)
return json_node_get_string(node);
return NULL;
}
/* /*
* 在 JsonObject 中查找 businessJson 字符串。 * 在 JsonObject 中查找 businessJson 字符串。
...@@ -43,7 +50,7 @@ static const gchar *find_business_json(JsonObject *obj) ...@@ -43,7 +50,7 @@ static const gchar *find_business_json(JsonObject *obj)
/* 顶层 businessJson */ /* 顶层 businessJson */
if (json_object_has_member(obj, "businessJson")) if (json_object_has_member(obj, "businessJson"))
return json_object_get_string_member(obj, "businessJson"); return business_json_string(obj);
/* data.* */ /* data.* */
if (json_object_has_member(obj, "data")) { if (json_object_has_member(obj, "data")) {
...@@ -51,14 +58,14 @@ static const gchar *find_business_json(JsonObject *obj) ...@@ -51,14 +58,14 @@ static const gchar *find_business_json(JsonObject *obj)
if (JSON_NODE_HOLDS_OBJECT(node)) { if (JSON_NODE_HOLDS_OBJECT(node)) {
child = json_node_get_object(node); child = json_node_get_object(node);
if (json_object_has_member(child, "businessJson")) if (json_object_has_member(child, "businessJson"))
return json_object_get_string_member(child, "businessJson"); return business_json_string(child);
/* data.data.businessJson */ /* data.data.businessJson */
if (json_object_has_member(child, "data")) { if (json_object_has_member(child, "data")) {
JsonNode *n2 = json_object_get_member(child, "data"); JsonNode *n2 = json_object_get_member(child, "data");
if (JSON_NODE_HOLDS_OBJECT(n2)) { if (JSON_NODE_HOLDS_OBJECT(n2)) {
JsonObject *c2 = json_node_get_object(n2); JsonObject *c2 = json_node_get_object(n2);
if (json_object_has_member(c2, "businessJson")) if (json_object_has_member(c2, "businessJson"))
return json_object_get_string_member(c2, "businessJson"); return business_json_string(c2);
} }
} }
/* data.result.businessJson */ /* data.result.businessJson */
...@@ -67,7 +74,7 @@ static const gchar *find_business_json(JsonObject *obj) ...@@ -67,7 +74,7 @@ static const gchar *find_business_json(JsonObject *obj)
if (JSON_NODE_HOLDS_OBJECT(n2)) { if (JSON_NODE_HOLDS_OBJECT(n2)) {
JsonObject *c2 = json_node_get_object(n2); JsonObject *c2 = json_node_get_object(n2);
if (json_object_has_member(c2, "businessJson")) if (json_object_has_member(c2, "businessJson"))
return json_object_get_string_member(c2, "businessJson"); return business_json_string(c2);
} }
} }
} }
...@@ -79,13 +86,49 @@ static const gchar *find_business_json(JsonObject *obj) ...@@ -79,13 +86,49 @@ static const gchar *find_business_json(JsonObject *obj)
if (JSON_NODE_HOLDS_OBJECT(node)) { if (JSON_NODE_HOLDS_OBJECT(node)) {
child = json_node_get_object(node); child = json_node_get_object(node);
if (json_object_has_member(child, "businessJson")) if (json_object_has_member(child, "businessJson"))
return json_object_get_string_member(child, "businessJson"); return business_json_string(child);
} }
} }
return NULL; return NULL;
} }
static gdouble volume_from_node(JsonNode *node)
{
gdouble volume;
GType type;
if (!node || !JSON_NODE_HOLDS_VALUE(node))
return -1.0;
type = json_node_get_value_type(node);
if (type == G_TYPE_DOUBLE || type == G_TYPE_INT64) {
volume = json_node_get_double(node);
} else if (type == G_TYPE_STRING) {
const gchar *value = json_node_get_string(node);
gchar *end;
if (!value)
return -1.0;
errno = 0;
volume = g_ascii_strtod(value, &end);
if (end == value || errno == ERANGE)
return -1.0;
while (g_ascii_isspace(*end))
end++;
if (*end != '\0')
return -1.0;
} else {
return -1.0;
}
if (!isfinite(volume))
return -1.0;
if (volume < 0.0)
return 0.0;
if (volume > 1.0)
return 1.0;
return volume;
}
/* 从 HTTP 响应体解析音量,范围 0~1。失败返回 -1.0 */ /* 从 HTTP 响应体解析音量,范围 0~1。失败返回 -1.0 */
static gdouble parse_volume_from_response(const gchar *body, gsize len) static gdouble parse_volume_from_response(const gchar *body, gsize len)
{ {
...@@ -136,9 +179,7 @@ static gdouble parse_volume_from_response(const gchar *body, gsize len) ...@@ -136,9 +179,7 @@ static gdouble parse_volume_from_response(const gchar *body, gsize len)
if (root2 && JSON_NODE_HOLDS_OBJECT(root2)) { if (root2 && JSON_NODE_HOLDS_OBJECT(root2)) {
JsonObject *bobj = json_node_get_object(root2); JsonObject *bobj = json_node_get_object(root2);
if (json_object_has_member(bobj, "volume")) { if (json_object_has_member(bobj, "volume")) {
JsonNode *vn = json_object_get_member(bobj, "volume"); volume = volume_from_node(json_object_get_member(bobj, "volume"));
if (!json_node_is_null(vn))
volume = json_node_get_double(vn);
} }
} }
g_object_unref(p2); g_object_unref(p2);
...@@ -148,117 +189,66 @@ static gdouble parse_volume_from_response(const gchar *body, gsize len) ...@@ -148,117 +189,66 @@ static gdouble parse_volume_from_response(const gchar *body, gsize len)
return volume; return volume;
} }
static void fetch_and_apply_volume(VolumeControl *vc) int volume_control_load(const char *vehicle_id)
{ {
SoupSession *session;
SoupMessage *msg; SoupMessage *msg;
gchar *url; gchar *url;
guint status; guint status;
const gchar *body; const gchar *body;
gsize body_len; gsize body_len;
gdouble vol; gdouble vol;
int result = -1;
s_local_volume = VC_DEFAULT_VOLUME;
if (!vehicle_id || !vehicle_id[0]) {
my_zlog_warn("volume_control: empty vehicle_id, using default 30%%");
return -1;
}
session = soup_session_new_with_options(
SOUP_SESSION_TIMEOUT, (guint)VC_HTTP_TIMEOUT_SEC, NULL);
if (!session) {
my_zlog_warn("volume_control: failed to create HTTP session, using default 30%%");
return -1;
}
url = g_strdup_printf("%s%s", VC_API_BASE, vc->vehicle_id); url = g_strdup_printf("%s%s", VC_API_BASE, vehicle_id);
msg = soup_message_new("GET", url); msg = soup_message_new("GET", url);
if (!msg) { if (!msg) {
my_zlog_warn("volume_control: failed to create request for %s", url); my_zlog_warn("volume_control: failed to create request for %s", url);
g_free(url); g_free(url);
return; g_object_unref(session);
return -1;
} }
status = soup_session_send_message(vc->session, msg); status = soup_session_send_message(session, msg);
if (status != 200) { if (status != 200) {
my_zlog_warn("volume_control: HTTP %u for %s", status, url); my_zlog_warn("volume_control: HTTP %u for %s", status, url);
g_object_unref(msg); goto cleanup;
g_free(url);
return;
} }
body = msg->response_body->data; body = msg->response_body->data;
body_len = msg->response_body->length; body_len = msg->response_body->length;
if (!body || body_len == 0) { if (!body || body_len == 0) {
my_zlog_warn("volume_control: empty response body for %s", url); my_zlog_warn("volume_control: empty response body for %s", url);
g_object_unref(msg); goto cleanup;
g_free(url);
return;
} }
vol = parse_volume_from_response(body, body_len); vol = parse_volume_from_response(body, body_len);
if (vol < 0.0) { if (vol < 0.0) {
my_zlog_warn("volume_control: volume not found in response"); my_zlog_warn("volume_control: missing or invalid volume, using default 30%%");
} else if (fabs(vol - vc->current_volume) > VC_VOLUME_EPSILON) { } else {
/* 音量有变化才设置并记日志,避免噪音 */ s_local_volume = vol;
audio_sink_set_volume(vc->sink, vol); result = 0;
vc->current_volume = vol; my_zlog_info("volume_control: local announcement volume=%.3f (%.0f%%)",
my_zlog_info("volume_control: volume set to %.3f", vol); vol, vol * 100.0);
} }
cleanup:
g_object_unref(msg); g_object_unref(msg);
g_free(url); g_free(url);
} g_object_unref(session);
return result;
static gpointer volume_control_thread(gpointer data)
{
VolumeControl *vc = data;
while (g_atomic_int_get(&vc->stop) == 0) {
fetch_and_apply_volume(vc);
/* 分段睡眠(3s = 30 * 100ms),便于快速响应停止 */
for (gint i = 0; i < VC_INTERVAL_SEC * 10; i++) {
if (g_atomic_int_get(&vc->stop) != 0)
break;
g_usleep(100 * 1000); /* 100ms */
}
}
return NULL;
}
VolumeControl *volume_control_start(const char *vehicle_id, AudioSink *sink)
{
VolumeControl *vc;
if (!vehicle_id || !vehicle_id[0] || !sink) {
my_zlog_error("volume_control: invalid args");
return NULL;
}
vc = g_new0(VolumeControl, 1);
vc->vehicle_id = g_strdup(vehicle_id);
vc->sink = sink;
vc->current_volume = VC_DEFAULT_VOLUME;
vc->stop = 0;
/* 启动时先设默认音量 0.5 */
audio_sink_set_volume(sink, VC_DEFAULT_VOLUME);
/* libsoup 同步 session + HTTP 超时(部分版本不支持 async 属性,用 soup_session_new 兜底) */
vc->session = soup_session_new();
if (vc->session) {
GParamSpec *pspec;
pspec = g_object_class_find_property(G_OBJECT_GET_CLASS(vc->session), "timeout");
if (pspec)
g_object_set(vc->session, "timeout", (guint)VC_HTTP_TIMEOUT_SEC, NULL);
pspec = g_object_class_find_property(G_OBJECT_GET_CLASS(vc->session), "idle-timeout");
if (pspec)
g_object_set(vc->session, "idle-timeout", (guint)VC_HTTP_TIMEOUT_SEC, NULL);
}
vc->thread = g_thread_new("volume-control", volume_control_thread, vc);
my_zlog_info("volume_control: started vehicle_id=%s interval=%ds",
vehicle_id, VC_INTERVAL_SEC);
return vc;
}
void volume_control_stop(VolumeControl *vc)
{
if (!vc)
return;
g_atomic_int_set(&vc->stop, 1);
if (vc->thread)
g_thread_join(vc->thread);
if (vc->session)
g_object_unref(vc->session);
g_free(vc->vehicle_id);
g_free(vc);
} }
#ifndef VOLUME_CONTROL_H #ifndef VOLUME_CONTROL_H
#define VOLUME_CONTROL_H #define VOLUME_CONTROL_H
#include "audio_sink.h" /* 开机联网后、音频工作线程启动前调用一次。失败保留默认音量 0.3。 */
int volume_control_load(const char *vehicle_id);
typedef struct VolumeControl VolumeControl; /* MQTT 2017 本地播报音量,保存在运行内存中,范围 0~1。 */
double volume_control_get_local_volume(void);
/* vehicle_id: 设备号如 CN010200000132;audio_sink: 播放 sink 用于设置音量 */
VolumeControl *volume_control_start(const char *vehicle_id, AudioSink *sink);
void volume_control_stop(VolumeControl *vc);
#endif #endif
...@@ -126,11 +126,6 @@ ...@@ -126,11 +126,6 @@
/* 手机喊话结束后短暂保温,避免每个短包都冷启动声卡;到时仍会释放喇叭。 */ /* 手机喊话结束后短暂保温,避免每个短包都冷启动声卡;到时仍会释放喇叭。 */
#define WEBRTCPUSH_AUDIO_SINK_IDLE_TIMEOUT_MS 3000U #define WEBRTCPUSH_AUDIO_SINK_IDLE_TIMEOUT_MS 3000U
/* 后端音量控制接口 */
#define WEBRTCPUSH_VOLUME_API_BASE "https://fcrs-api.yd-ss.com/api/drive/use/status/"
#define WEBRTCPUSH_VOLUME_INTERVAL_SEC 3
#define WEBRTCPUSH_VOLUME_DEFAULT 0.5
/* /*
* 设备侧 DataChannel(myDataChannel): * 设备侧 DataChannel(myDataChannel):
......
#include "wifi_config_agent.h" #include "wifi_config_agent.h"
#include "wifi_hotspot.h"
#include "wifi_config_config.h" #include "wifi_config_config.h"
#include "device_debug_agent.h" #include "device_debug_agent.h"
#include "device_diag.h" #include "device_diag.h"
...@@ -300,6 +301,19 @@ static void send_config_result(int sock, const struct sockaddr_in *addr, int suc ...@@ -300,6 +301,19 @@ static void send_config_result(int sock, const struct sockaddr_in *addr, int suc
} }
/* config_ack:设备收到 config 后立即回复,表示已收到即将执行 */ /* config_ack:设备收到 config 后立即回复,表示已收到即将执行 */
static int reject_hotspot_operation(int sock, const struct sockaddr_in *addr, const char *cmd)
{
if (!wifi_hotspot_is_active()) return 0;
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "cmd", cmd);
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "message", "设备热点配网中,请通过热点网页修改 Wi-Fi");
char *payload = cJSON_PrintUnformatted(root);
if (payload) send_json(sock, addr, payload);
free(payload); cJSON_Delete(root);
return 1;
}
static void send_config_ack(int sock, const struct sockaddr_in *addr, int accepted, static void send_config_ack(int sock, const struct sockaddr_in *addr, int accepted,
const char *action, const char *message) const char *action, const char *message)
{ {
...@@ -350,6 +364,10 @@ static void handle_discover(int sock, const struct sockaddr_in *addr) ...@@ -350,6 +364,10 @@ static void handle_discover(int sock, const struct sockaddr_in *addr)
static void handle_config(int sock, const struct sockaddr_in *addr, cJSON *root) static void handle_config(int sock, const struct sockaddr_in *addr, cJSON *root)
{ {
if (wifi_hotspot_is_active()) {
send_config_result(sock, addr, 0, "设备热点配网中,请使用热点网页配置 Wi-Fi");
return;
}
cJSON *ssid_item = cJSON_GetObjectItemCaseSensitive(root, "ssid"); cJSON *ssid_item = cJSON_GetObjectItemCaseSensitive(root, "ssid");
cJSON *password_item = cJSON_GetObjectItemCaseSensitive(root, "password"); cJSON *password_item = cJSON_GetObjectItemCaseSensitive(root, "password");
cJSON *action_item = cJSON_GetObjectItemCaseSensitive(root, "action"); cJSON *action_item = cJSON_GetObjectItemCaseSensitive(root, "action");
...@@ -423,6 +441,7 @@ static void handle_wifi_list_query(int sock, const struct sockaddr_in *addr) ...@@ -423,6 +441,7 @@ static void handle_wifi_list_query(int sock, const struct sockaddr_in *addr)
static void handle_wifi_switch(int sock, const struct sockaddr_in *addr, cJSON *root) static void handle_wifi_switch(int sock, const struct sockaddr_in *addr, cJSON *root)
{ {
if (reject_hotspot_operation(sock, addr, "wifi_switch_result")) return;
cJSON *ssid_item = cJSON_GetObjectItemCaseSensitive(root, "ssid"); cJSON *ssid_item = cJSON_GetObjectItemCaseSensitive(root, "ssid");
cJSON *resp; cJSON *resp;
const char *ssid = NULL; const char *ssid = NULL;
...@@ -481,6 +500,7 @@ static void handle_wifi_switch(int sock, const struct sockaddr_in *addr, cJSON * ...@@ -481,6 +500,7 @@ static void handle_wifi_switch(int sock, const struct sockaddr_in *addr, cJSON *
static void handle_wifi_delete(int sock, const struct sockaddr_in *addr, cJSON *root) static void handle_wifi_delete(int sock, const struct sockaddr_in *addr, cJSON *root)
{ {
if (reject_hotspot_operation(sock, addr, "wifi_delete_result")) return;
cJSON *ssid_item = cJSON_GetObjectItemCaseSensitive(root, "ssid"); cJSON *ssid_item = cJSON_GetObjectItemCaseSensitive(root, "ssid");
cJSON *resp; cJSON *resp;
const char *ssid = NULL; const char *ssid = NULL;
......
#include "wifi_hotspot.h"
#include "wifi_provision.h"
#include "wifi_portal_page.h"
#include "device_command.h"
#include "device_feedback.h"
#include "device_identity.h"
#include "wifi_autoconfig.h"
#include "mylog.h"
#include "wifi_operation.h"
#include <libsoup/soup.h>
#include <curl/curl.h>
#include <glib.h>
#include <pthread.h>
#include <net/if.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define AP_IFACE "car-ap"
#define STA_IFACE "wlan0"
#define AP_IP "10.42.0.1"
#define PORTAL_URL "http://" AP_IP "/"
#define MARKER "/run/car-controlserver-hotspot.json"
#define SESSION_SECONDS 900
#define SWITCH_DELAY_SECONDS 8
static pthread_mutex_t s_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_t s_thread;
static int s_thread_started, s_starting, s_active, s_configuring, s_stopping, s_stop;
static char s_status[32] = "stopped", s_message[256] = "设备热点未开启";
static char s_ssid[64], s_token[37], s_ap_uuid[37], s_original[64], s_trial[37];
static char s_ap_name[80], s_trial_name[80];
static cJSON *s_request, *s_stop_request;
static GMainContext *s_context;
static GMainLoop *s_loop;
static GPid s_dns;
static gint64 s_started;
static int s_interface_created;
static int s_exclusive;
static char s_ap_iface[IFNAMSIZ] = AP_IFACE;
static char *s_scan_cache;
static gint64 s_scanned;
typedef struct {
char ssid[33], password[65], uuid[37], previous[64];
char name[80];
char session[37];
int exclusive;
} ConnectJob;
static int start_dns(void);
static guint64 process_start(pid_t pid)
{
char path[64], *text = NULL;
g_snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid);
if (!g_file_get_contents(path, &text, NULL, NULL)) return 0;
char *end = strrchr(text, ')');
gchar **fields = end && end[1] ? g_strsplit(end + 2, " ", -1) : NULL;
guint64 start = fields && g_strv_length(fields) > 19 && strcmp(fields[0], "Z") && strcmp(fields[0], "X") ?
g_ascii_strtoull(fields[19], NULL, 10) : 0;
g_strfreev(fields); g_free(text);
return start;
}
static int marker_owner_live(const cJSON *obj)
{
const cJSON *pid = cJSON_GetObjectItemCaseSensitive(obj, "owner_pid");
const cJSON *start = cJSON_GetObjectItemCaseSensitive(obj, "owner_start");
if (!cJSON_IsNumber(pid) || pid->valueint <= 1 || pid->valueint == getpid() ||
!cJSON_IsString(start) || !cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(obj, "owner_active"))) return 0;
guint64 expected = g_ascii_strtoull(start->valuestring, NULL, 10);
return expected && process_start(pid->valueint) == expected;
}
static int external_hotspot_active(void)
{
char *text = NULL;
if (!g_file_get_contents(MARKER, &text, NULL, NULL)) return 0;
cJSON *obj = cJSON_Parse(text); g_free(text);
int live = marker_owner_live(obj); cJSON_Delete(obj);
return live;
}
static int command(const char *const args[], unsigned timeout, char **output)
{
return device_command_run(args, timeout, output);
}
static int current_uuid(char *out, size_t size)
{
const char *args[] = {"nmcli", "-g", "GENERAL.CON-UUID", "device", "show", STA_IFACE, NULL};
char *text = NULL;
int rc = command(args, 8, &text);
if (text) g_strstrip(text);
g_strlcpy(out, rc == 0 && text && g_uuid_string_is_valid(text) ? text : "", size);
g_free(text);
return rc;
}
static int uuid_command(const char *verb, const char *uuid, unsigned timeout)
{
if (!uuid || !g_uuid_string_is_valid(uuid)) return -1;
const char *args[] = {"nmcli", "-w", "25", "connection", verb, "uuid", uuid, NULL};
return command(args, timeout, NULL);
}
static int reset_dhd_wifi(void)
{
if (!g_file_test("/sys/module/bcmdhd", G_FILE_TEST_IS_DIR)) return 0;
const char *off[] = {"nmcli", "radio", "wifi", "off", NULL};
const char *on[] = {"nmcli", "radio", "wifi", "on", NULL};
my_zlog_info("hotspot: resetting DHD WiFi after AP mode");
int down = command(off, 8, NULL);
g_usleep(700000);
/* Always re-enable WiFi, even if the disable command reported an error. */
int up = command(on, 8, NULL);
my_zlog_info("hotspot: DHD WiFi reset off=%d on=%d", down, up);
if (up != 0) return up;
const char *state_args[] = {"nmcli", "-g", "GENERAL.STATE", "device", "show", STA_IFACE, NULL};
for (int attempt = 0; attempt < 10; attempt++) {
g_usleep(500000);
char *state = NULL;
int rc = command(state_args, 3, &state);
int available = rc == 0 && state && atoi(state) >= 30 && atoi(state) <= 100;
g_free(state);
if (available) return 0;
}
my_zlog_warn("hotspot: DHD WiFi did not become available after reset");
return -1;
}
static int ensure_connection(const char *uuid)
{
if (!uuid || !uuid[0]) return 0;
char current[64], *state = NULL;
const char *args[] = {"nmcli", "-g", "GENERAL.STATE", "device", "show", STA_IFACE, NULL};
if (current_uuid(current, sizeof(current)) == 0 && !strcmp(current, uuid) &&
command(args, 8, &state) == 0 && state && atoi(state) == 100) {
g_free(state); return 0;
}
g_free(state);
int rc = uuid_command("up", uuid, 35);
if (rc != 0 && g_file_test("/sys/module/bcmdhd", G_FILE_TEST_IS_DIR) && reset_dhd_wifi() == 0)
rc = uuid_command("up", uuid, 35);
return rc;
}
static int named_uuid(const char *name, char *out, size_t size)
{
const char *args[] = {"nmcli", "-g", "connection.uuid", "connection", "show", "id", name, NULL};
char *text = NULL;
int rc = command(args, 8, &text);
if (text) g_strstrip(text);
int valid = rc == 0 && text && g_uuid_string_is_valid(text);
if (valid) g_strlcpy(out, text, size);
g_free(text);
return valid ? 0 : -1;
}
static int delete_named(const char *name)
{
if (!name || !name[0]) return 0;
const char *args[] = {"nmcli", "connection", "delete", "id", name, NULL};
return command(args, 10, NULL);
}
static void set_state(const char *status, const char *message)
{
pthread_mutex_lock(&s_lock);
g_strlcpy(s_status, status, sizeof(s_status));
g_strlcpy(s_message, message, sizeof(s_message));
pthread_mutex_unlock(&s_lock);
my_zlog_info("hotspot: status=%s", status);
}
int wifi_hotspot_is_active(void)
{
pthread_mutex_lock(&s_lock);
int active = s_starting || s_active || s_configuring || s_stopping;
pthread_mutex_unlock(&s_lock);
return active || external_hotspot_active();
}
static int stopping(void)
{
pthread_mutex_lock(&s_lock); int stop = s_stop; pthread_mutex_unlock(&s_lock);
return stop;
}
static cJSON *status_json(void)
{
cJSON *obj = cJSON_CreateObject();
pthread_mutex_lock(&s_lock);
cJSON_AddStringToObject(obj, "status", s_status);
cJSON_AddStringToObject(obj, "message", s_message);
cJSON_AddStringToObject(obj, "ssid", s_ssid);
cJSON_AddStringToObject(obj, "url", PORTAL_URL);
cJSON_AddBoolToObject(obj, "active", s_active);
cJSON_AddBoolToObject(obj, "configuring", s_configuring);
cJSON_AddBoolToObject(obj, "exclusive", s_exclusive);
pthread_mutex_unlock(&s_lock);
return obj;
}
static void feedback(const char *action, const char *state, int code,
const char *message, int final)
{
pthread_mutex_lock(&s_lock);
cJSON *request = cJSON_Duplicate(s_request, 1);
pthread_mutex_unlock(&s_lock);
cJSON *details = status_json();
device_feedback_send(3029, request, action, state, code, message, final, details);
cJSON_Delete(details); cJSON_Delete(request);
}
static int save_marker(void)
{
cJSON *obj = cJSON_CreateObject();
pthread_mutex_lock(&s_lock);
cJSON_AddStringToObject(obj, "ap_uuid", s_ap_uuid);
cJSON_AddStringToObject(obj, "original_uuid", s_original);
cJSON_AddStringToObject(obj, "trial_uuid", s_trial);
cJSON_AddStringToObject(obj, "ap_name", s_ap_name);
cJSON_AddStringToObject(obj, "trial_name", s_trial_name);
cJSON_AddStringToObject(obj, "interface", s_ap_iface);
cJSON_AddNumberToObject(obj, "dns_pid", s_dns);
cJSON_AddNumberToObject(obj, "owner_pid", getpid());
char start[32]; g_snprintf(start, sizeof(start), "%" G_GUINT64_FORMAT, process_start(getpid()));
cJSON_AddStringToObject(obj, "owner_start", start);
cJSON_AddBoolToObject(obj, "owner_active", s_starting || s_active || s_configuring || s_stopping);
pthread_mutex_unlock(&s_lock);
char *text = cJSON_PrintUnformatted(obj);
int saved = text && g_file_set_contents(MARKER, text, -1, NULL);
if (saved) chmod(MARKER, 0600);
cJSON_free(text); cJSON_Delete(obj);
return saved ? 0 : -1;
}
static int firewall_rules(int add)
{
char *path = g_find_program_in_path("iptables");
if (!path) return 0;
g_free(path);
const char *protocols[] = {"tcp", "tcp", "udp", "udp"};
const char *ports[] = {"80", "53", "53", "67"};
for (int i = 0; i < 4; i++) {
const char *check[] = {"iptables", "-w", "2", "-C", "INPUT", "-i", s_ap_iface,
"-p", protocols[i], "--dport", ports[i], "-m", "comment", "--comment",
"car-controlserver-hotspot", "-j", "ACCEPT", NULL};
int exists = command(check, 5, NULL) == 0;
if (exists == !!add) continue;
const char *change[] = {"iptables", "-w", "2", add ? "-I" : "-D", "INPUT", "-i", s_ap_iface,
"-p", protocols[i], "--dport", ports[i], "-m", "comment", "--comment",
"car-controlserver-hotspot", "-j", "ACCEPT", NULL};
if (command(change, 5, NULL) != 0 && add) return -1;
}
return 0;
}
static void stop_dns(GPid pid)
{
if (pid <= 1) return;
kill(pid, SIGTERM);
for (int i = 0; i < 30; i++) {
pid_t result = waitpid(pid, NULL, WNOHANG);
if (result == pid || result < 0) break;
g_usleep(100000);
}
if (waitpid(pid, NULL, WNOHANG) == 0) { kill(pid, SIGKILL); waitpid(pid, NULL, 0); }
g_spawn_close_pid(pid);
}
/* Recover only resources recorded in this root-owned marker after a service crash. */
int wifi_hotspot_init(void)
{
char *text = NULL;
if (!g_file_get_contents(MARKER, &text, NULL, NULL)) return 0;
cJSON *obj = cJSON_Parse(text); g_free(text);
if (!cJSON_IsObject(obj)) { cJSON_Delete(obj); return -1; }
if (marker_owner_live(obj)) { cJSON_Delete(obj); return 0; }
cJSON_Delete(obj);
if (wifi_operation_begin_wait(10) != 0) return -1;
text = NULL;
if (!g_file_get_contents(MARKER, &text, NULL, NULL)) { wifi_operation_end(); return 0; }
obj = cJSON_Parse(text); g_free(text);
if (!cJSON_IsObject(obj) || marker_owner_live(obj)) {
cJSON_Delete(obj); wifi_operation_end(); return 0;
}
cJSON *ap = cJSON_GetObjectItem(obj, "ap_uuid");
cJSON *old = cJSON_GetObjectItem(obj, "original_uuid");
cJSON *trial = cJSON_GetObjectItem(obj, "trial_uuid");
cJSON *dns = cJSON_GetObjectItem(obj, "dns_pid");
cJSON *ap_name = cJSON_GetObjectItem(obj, "ap_name");
cJSON *trial_name = cJSON_GetObjectItem(obj, "trial_name");
cJSON *iface = cJSON_GetObjectItem(obj, "interface");
if (cJSON_IsString(iface) && (!strcmp(iface->valuestring, AP_IFACE) || !strcmp(iface->valuestring, STA_IFACE)))
g_strlcpy(s_ap_iface, iface->valuestring, sizeof(s_ap_iface));
if (cJSON_IsNumber(dns) && dns->valueint > 1) {
char path[64], *cmdline = NULL; gsize len = 0;
g_snprintf(path, sizeof(path), "/proc/%d/cmdline", dns->valueint);
if (g_file_get_contents(path, &cmdline, &len, NULL)) {
for (gsize i = 0; i < len; i++) if (!cmdline[i]) cmdline[i] = ' ';
char expected[64]; g_snprintf(expected, sizeof(expected), "--interface=%s", s_ap_iface);
if (strstr(cmdline, "dnsmasq") && strstr(cmdline, expected) && strstr(cmdline, "car-hotspot.leases")) kill(dns->valueint, SIGTERM);
g_free(cmdline);
}
}
if (cJSON_IsString(trial) && g_uuid_string_is_valid(trial->valuestring)) {
uuid_command("down", trial->valuestring, 10);
uuid_command("delete", trial->valuestring, 10);
if (cJSON_IsString(trial_name) && g_str_has_prefix(trial_name->valuestring, "car-wifi-trial-"))
delete_named(trial_name->valuestring);
if (cJSON_IsString(old) && g_uuid_string_is_valid(old->valuestring)) ensure_connection(old->valuestring);
}
if (cJSON_IsString(ap) && g_uuid_string_is_valid(ap->valuestring)) {
firewall_rules(0);
uuid_command("down", ap->valuestring, 10);
uuid_command("delete", ap->valuestring, 10);
if (cJSON_IsString(ap_name) && g_str_has_prefix(ap_name->valuestring, "car-hotspot-"))
delete_named(ap_name->valuestring);
const char *del[] = {"iw", "dev", AP_IFACE, "del", NULL}; command(del, 10, NULL);
}
char current[64]; current_uuid(current, sizeof(current));
if (!current[0] && cJSON_IsString(old) && g_uuid_string_is_valid(old->valuestring))
ensure_connection(old->valuestring);
unlink(MARKER); cJSON_Delete(obj); wifi_operation_end();
return 0;
}
static gboolean quit_loop(gpointer unused)
{
(void)unused;
pthread_mutex_lock(&s_lock);
if (s_loop) g_main_loop_quit(s_loop);
pthread_mutex_unlock(&s_lock);
return G_SOURCE_REMOVE;
}
static void request_stop_session(const char *session)
{
pthread_mutex_lock(&s_lock);
if (session && strcmp(session, s_token)) { pthread_mutex_unlock(&s_lock); return; }
s_stop = 1; s_stopping = 1;
if (s_context) {
GSource *idle = g_idle_source_new();
g_source_set_callback(idle, quit_loop, NULL, NULL);
g_source_attach(idle, s_context);
g_source_unref(idle);
}
pthread_mutex_unlock(&s_lock);
}
static void request_stop(void) { request_stop_session(NULL); }
static int create_trial(void *ctx)
{
ConnectJob *job = ctx;
if (stopping()) return -1;
const char *open[] = {"nmcli", "connection", "add", "save", "no", "type", "wifi",
"ifname", STA_IFACE, "con-name", job->name, "ssid", job->ssid,
"connection.autoconnect", "no", NULL};
const char *secured[] = {"nmcli", "connection", "add", "save", "no", "type", "wifi",
"ifname", STA_IFACE, "con-name", job->name, "ssid", job->ssid,
"connection.autoconnect", "no",
"wifi-sec.key-mgmt", "wpa-psk", "wifi-sec.psk", job->password, NULL};
int rc = command(job->password[0] ? secured : open, 15, NULL);
if (rc == 0) {
rc = named_uuid(job->name, job->uuid, sizeof(job->uuid));
if (rc == 0) {
pthread_mutex_lock(&s_lock); g_strlcpy(s_trial, job->uuid, sizeof(s_trial)); pthread_mutex_unlock(&s_lock);
save_marker();
}
}
return rc;
}
static int activate_trial(void *ctx)
{
if (stopping()) return -1;
if (s_exclusive) {
/* Never leave the AP DHCP server listening on the user's real Wi-Fi LAN. */
pthread_mutex_lock(&s_lock); GPid dns = s_dns; s_dns = 0; pthread_mutex_unlock(&s_lock);
my_zlog_info("hotspot: stopping DHCP/DNS for WiFi trial");
stop_dns(dns);
my_zlog_info("hotspot: removing hotspot firewall rules");
firewall_rules(0); save_marker();
my_zlog_info("hotspot: deactivating AP before WiFi trial");
int rc = uuid_command("down", s_ap_uuid, 15);
my_zlog_info("hotspot: AP deactivation result=%d", rc);
if (rc != 0) return -1;
g_usleep(1000000);
if (reset_dhd_wifi() != 0) return -1;
}
int rc = uuid_command("up", ((ConnectJob *)ctx)->uuid, 35);
my_zlog_info("hotspot: WiFi trial activation result=%d", rc);
return rc;
}
typedef struct { GString *body; int overflow; } HttpProbe;
static size_t receive_probe(char *ptr, size_t size, size_t count, void *arg)
{
HttpProbe *probe = arg;
size_t n = size * count;
if (n > 65536 || probe->body->len + n > 65536) { probe->overflow = 1; return 0; }
g_string_append_len(probe->body, ptr, n); return n;
}
static int verify_trial(void *ctx)
{
ConnectJob *job = ctx;
char active[64];
if (stopping() || current_uuid(active, sizeof(active)) != 0 || strcmp(active, job->uuid)) return -1;
for (int attempt = 0; attempt < 2 && !stopping(); attempt++) {
CURL *curl = curl_easy_init();
if (!curl) return -1;
HttpProbe probe = {g_string_new(NULL), 0};
char url[256];
g_snprintf(url, sizeof(url), "https://fcrs-api.yd-ss.com/device/getConfig?deviceNo=%s", mqtt_topic_pure_number());
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_INTERFACE, STA_IFACE);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 8L);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 4L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, receive_probe);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &probe);
CURLcode rc = curl_easy_perform(curl);
long status = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status);
cJSON *json = rc == CURLE_OK && status == 200 ? cJSON_Parse(probe.body->str) : NULL;
cJSON *code = cJSON_GetObjectItem(json, "code");
int ok = cJSON_IsNumber(code) && code->valueint == 200 && cJSON_IsObject(cJSON_GetObjectItem(json, "data"));
cJSON_Delete(json); g_string_free(probe.body, TRUE); curl_easy_cleanup(curl);
if (ok) return 0;
if (attempt == 0) g_usleep(1000000);
}
return -1;
}
static int commit_trial(void *ctx)
{
ConnectJob *job = ctx;
if (stopping()) return -1;
/* Without --temporary, NM writes this formerly in-memory profile to disk. */
const char *args[] = {"nmcli", "connection", "modify", "uuid", job->uuid,
"connection.id", job->ssid, "connection.autoconnect", "yes", NULL};
int rc = command(args, 15, NULL);
if (rc == 0) {
pthread_mutex_lock(&s_lock);
s_trial[0] = 0;
s_trial_name[0] = 0;
g_strlcpy(s_original, job->uuid, sizeof(s_original));
pthread_mutex_unlock(&s_lock);
save_marker();
}
return rc;
}
static int discard_trial(void *ctx)
{
ConnectJob *job = ctx;
uuid_command("down", job->uuid, 10);
int rc = uuid_command("delete", job->uuid, 10);
if (job->name[0]) {
delete_named(job->name);
char remaining[64];
if (named_uuid(job->name, remaining, sizeof(remaining)) == 0) return -1;
}
/* A failed create can leave no profile at all; absence also means no saved credentials. */
if (rc != 0) {
const char *args[] = {"nmcli", "-g", "connection.uuid", "connection", "show", "uuid", job->uuid, NULL};
if (command(args, 8, NULL) != 0) rc = 0;
}
return rc;
}
static int restore_previous(void *ctx)
{
ConnectJob *job = ctx;
int rc = ensure_connection(job->previous);
my_zlog_info("hotspot: original WiFi restore result=%d", rc);
return rc;
}
static void progress(void *ctx, const char *stage)
{
(void)ctx;
const char *message = "正在准备临时 Wi-Fi 配置";
if (!strcmp(stage, "connecting")) message = "正在连接新 Wi-Fi,请保持手机连接设备热点";
else if (!strcmp(stage, "validating")) message = "正在验证新 Wi-Fi 是否可以联网";
else if (!strcmp(stage, "saving")) message = "联网验证成功,正在保存配置";
else if (!strcmp(stage, "rolling_back")) message = "新 Wi-Fi 不可用,正在恢复原 Wi-Fi";
set_state(stage, message);
feedback("configure", stage, 0, message, 0);
}
static void *connect_worker(void *arg)
{
ConnectJob *job = arg;
/* Keep the page reachable long enough to show the acknowledgement/countdown. */
if (job->exclusive) {
set_state("waiting", "配置已收到,即将切换 Wi-Fi;请在 App 查看验证结果");
for (int i = 0; i < SWITCH_DELAY_SECONDS * 10 && !stopping(); i++)
g_usleep(100000);
}
const WifiProvisionOps ops = {create_trial, activate_trial, verify_trial,
commit_trial, discard_trial, restore_previous, progress};
const char *failed = NULL;
int result = wifi_provision_run(&ops, job, &failed);
char message[256];
if (result == 0) {
g_strlcpy(message, "Wi-Fi 配置成功,已验证联网并保存配置", sizeof(message));
set_state("success", message);
feedback("configure", "success", 0, message, 1);
audio_play_system_beeps(2, 450);
} else {
int reopen = s_exclusive && (result == -2 || !job->previous[0]);
if (reopen && (uuid_command("up", s_ap_uuid, 30) != 0 || firewall_rules(1) != 0 || start_dns() != 0)) result = -2;
g_strlcpy(message, result == -2 ?
"Wi-Fi 配置失败,未保留新配置,但原 Wi-Fi 恢复或清理失败;热点保留,请重试" :
(job->previous[0] ? "Wi-Fi 配置失败,未保存新配置,已恢复原 Wi-Fi;请检查密码后重试" :
"Wi-Fi 配置失败,未保存新配置;热点保持开启,请检查后重试"), sizeof(message));
if (s_exclusive && result == -1 && job->previous[0])
g_strlcpy(message, "Wi-Fi 配置失败,未保存新配置,已恢复原 Wi-Fi;请在 App 重新开启热点后重试", sizeof(message));
set_state(result == -2 ? "rollback_failed" : "failed", message);
feedback("configure", result == -2 ? "rollback_failed" : "failed", result, message, 1);
my_zlog_warn("hotspot: WiFi trial failed at %s, rollback result=%d", failed, result);
audio_play_system_beeps(1, 180);
}
pthread_mutex_lock(&s_lock);
if (result != -2) { s_trial[0] = 0; s_trial_name[0] = 0; }
if (result == 0) g_strlcpy(s_original, job->uuid, sizeof(s_original));
s_configuring = 0;
pthread_mutex_unlock(&s_lock);
save_marker();
char session[37]; g_strlcpy(session, job->session, sizeof(session));
int close_failed = job->exclusive && result == -1 && job->previous[0];
memset(job->password, 0, sizeof(job->password)); g_free(job);
if (result == 0) { g_usleep(5000000); request_stop_session(session); }
else if (close_failed) request_stop_session(session);
return NULL;
}
static void json_response(SoupMessage *msg, guint status, cJSON *json)
{
char *text = cJSON_PrintUnformatted(json);
soup_message_set_status(msg, status);
soup_message_headers_replace(msg->response_headers, "Cache-Control", "no-store");
soup_message_set_response(msg, "application/json; charset=utf-8", SOUP_MEMORY_COPY,
text ? text : "{}", text ? strlen(text) : 2);
cJSON_free(text); cJSON_Delete(json);
}
static void error_response(SoupMessage *msg, guint status, const char *message)
{
cJSON *obj = cJSON_CreateObject(); cJSON_AddStringToObject(obj, "message", message);
json_response(msg, status, obj);
}
/* nmcli escapes ':' and '\\' in terse fields. Do not split escaped SSIDs. */
static int split_fields(const char *line, char fields[][256], int count)
{
int col = 0; size_t pos = 0;
memset(fields, 0, count * 256);
for (const char *p = line; *p && *p != '\n' && *p != '\r'; p++) {
char ch = *p;
if (ch == '\\' && p[1]) ch = *++p;
else if (ch == ':' && col + 1 < count) { fields[col++][pos] = 0; pos = 0; continue; }
if (pos + 1 < 256) fields[col][pos++] = ch;
}
return col + 1;
}
static void cache_networks(void)
{
const char *args[] = {"nmcli", "-t", "--escape", "yes", "-f", "SSID,SIGNAL,SECURITY",
"device", "wifi", "list", "ifname", STA_IFACE, "--rescan", "yes", NULL};
char *text = NULL;
int rc = command(args, 15, &text);
pthread_mutex_lock(&s_lock);
g_free(s_scan_cache);
s_scan_cache = rc == 0 ? g_strdup(text ? text : "") : NULL;
s_scanned = g_get_monotonic_time();
pthread_mutex_unlock(&s_lock);
g_free(text);
}
static void network_list(SoupMessage *msg)
{
/* This firmware can hang its radio when scanning in AP mode. Never rescan here. */
pthread_mutex_lock(&s_lock);
char *text = g_strdup(s_scan_cache);
gint64 age = (g_get_monotonic_time() - s_scanned) / G_USEC_PER_SEC;
pthread_mutex_unlock(&s_lock);
if (!text) { error_response(msg, 503, "开启热点前未能获取网络列表,请重新开启设备热点后重试"); return; }
cJSON *obj = cJSON_CreateObject(), *list = cJSON_CreateArray();
GHashTable *seen = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
gchar **lines = g_strsplit(text ? text : "", "\n", -1);
for (int i = 0; lines[i]; i++) {
char fields[3][256];
if (split_fields(lines[i], fields, 3) != 3 || !fields[0][0] || g_hash_table_contains(seen, fields[0])) continue;
g_hash_table_add(seen, g_strdup(fields[0]));
cJSON *entry = cJSON_CreateObject();
cJSON_AddStringToObject(entry, "ssid", fields[0]);
cJSON_AddNumberToObject(entry, "signal", atoi(fields[1]));
cJSON_AddStringToObject(entry, "security", fields[2]); cJSON_AddItemToArray(list, entry);
}
g_hash_table_destroy(seen); g_strfreev(lines); g_free(text);
cJSON_AddItemToObject(obj, "networks", list);
cJSON_AddBoolToObject(obj, "cached", 1);
cJSON_AddNumberToObject(obj, "age_seconds", age);
json_response(msg, 200, obj);
}
static void handle_connect(SoupMessage *msg)
{
const char *csrf = soup_message_headers_get_one(msg->request_headers, "X-CSRF-Token");
pthread_mutex_lock(&s_lock);
int authorized = csrf && strcmp(csrf, s_token) == 0;
int busy = s_configuring || s_stopping || !strcmp(s_status, "success");
char pending[37]; g_strlcpy(pending, s_trial, sizeof(pending));
char pending_name[80]; g_strlcpy(pending_name, s_trial_name, sizeof(pending_name));
pthread_mutex_unlock(&s_lock);
if (!authorized) { error_response(msg, 403, "页面已过期,请重新打开配网页面"); return; }
if (busy) { error_response(msg, 409, "已有配网操作正在执行,请稍候"); return; }
if (pending[0]) {
ConnectJob previous = {0}; g_strlcpy(previous.uuid, pending, sizeof(previous.uuid));
g_strlcpy(previous.name, pending_name, sizeof(previous.name));
if (discard_trial(&previous) != 0) {
error_response(msg, 409, "上次临时配置尚未清理,请恢复网络服务后重试"); return;
}
pthread_mutex_lock(&s_lock); s_trial[0] = 0; s_trial_name[0] = 0; pthread_mutex_unlock(&s_lock);
}
if (msg->request_body->length > 4096) { error_response(msg, 413, "请求过大"); return; }
cJSON *obj = cJSON_Parse(msg->request_body->data ? msg->request_body->data : "");
cJSON *ssid = cJSON_GetObjectItem(obj, "ssid"), *password = cJSON_GetObjectItem(obj, "password");
if (!cJSON_IsString(ssid) || !cJSON_IsString(password) ||
!wifi_provision_credentials_valid(ssid->valuestring, password->valuestring)) {
cJSON_Delete(obj); error_response(msg, 400, "网络名称需为 1–32 字节,密码需为 8–63 字符或 64 位十六进制密钥;开放网络可留空"); return;
}
ConnectJob *job = g_new0(ConnectJob, 1);
g_strlcpy(job->ssid, ssid->valuestring, sizeof(job->ssid));
g_strlcpy(job->password, password->valuestring, sizeof(job->password)); cJSON_Delete(obj);
char *uuid = g_uuid_string_random(); g_strlcpy(job->uuid, uuid, sizeof(job->uuid)); g_free(uuid);
g_snprintf(job->name, sizeof(job->name), "car-wifi-trial-%s", job->uuid);
current_uuid(job->previous, sizeof(job->previous));
pthread_mutex_lock(&s_lock);
g_strlcpy(job->session, s_token, sizeof(job->session));
job->exclusive = s_exclusive;
/* In single-radio mode wlan0 currently names our AP, never the rollback target. */
if (job->exclusive || !job->previous[0])
g_strlcpy(job->previous, s_original, sizeof(job->previous));
s_configuring = 1;
g_strlcpy(s_trial, job->uuid, sizeof(s_trial));
g_strlcpy(s_trial_name, job->name, sizeof(s_trial_name));
g_strlcpy(s_original, job->previous, sizeof(s_original));
pthread_mutex_unlock(&s_lock);
if (save_marker() != 0) {
pthread_mutex_lock(&s_lock); s_configuring = 0; s_trial[0] = 0; pthread_mutex_unlock(&s_lock);
memset(job->password, 0, sizeof(job->password)); g_free(job);
error_response(msg, 500, "无法保存临时恢复状态,未切换网络"); return;
}
int exclusive = job->exclusive;
pthread_t thread;
if (pthread_create(&thread, NULL, connect_worker, job) != 0) {
memset(job->password, 0, sizeof(job->password)); g_free(job);
pthread_mutex_lock(&s_lock); s_configuring = 0; s_trial[0] = 0; pthread_mutex_unlock(&s_lock);
error_response(msg, 500, "无法启动配网任务,请重试"); return;
}
pthread_detach(thread);
cJSON *ack = cJSON_CreateObject(); cJSON_AddStringToObject(ack, "message", "已收到配置,正在验证联网");
cJSON_AddBoolToObject(ack, "exclusive", exclusive);
cJSON_AddNumberToObject(ack, "switch_delay_seconds", exclusive ? SWITCH_DELAY_SECONDS : 0);
json_response(msg, 202, ack);
}
static void portal_handler(SoupServer *server, SoupMessage *msg, const char *path,
GHashTable *query, SoupClientContext *client, gpointer unused)
{
(void)server; (void)query; (void)client; (void)unused;
soup_message_headers_replace(msg->response_headers, "X-Content-Type-Options", "nosniff");
soup_message_headers_replace(msg->response_headers, "X-Frame-Options", "DENY");
const char *host = soup_message_headers_get_one(msg->request_headers, "Host");
if (!host || (strcmp(host, AP_IP) && strcmp(host, AP_IP ":80"))) {
soup_message_set_redirect(msg, SOUP_STATUS_FOUND, PORTAL_URL);
return;
}
if (!strcmp(path, "/api/connect")) {
if (strcmp(msg->method, "POST")) { error_response(msg, 405, "仅允许 POST 请求"); return; }
handle_connect(msg); return;
}
if (strcmp(msg->method, "GET")) { error_response(msg, 405, "仅允许 GET 请求"); return; }
if (!strcmp(path, "/api/status")) { json_response(msg, 200, status_json()); return; }
if (!strcmp(path, "/api/networks")) { network_list(msg); return; }
if (!strcmp(path, "/")) {
pthread_mutex_lock(&s_lock); char *token = g_strdup(s_token); pthread_mutex_unlock(&s_lock);
gchar **parts = g_strsplit(WIFI_PORTAL_PAGE, "__PORTAL_TOKEN__", -1);
char *html = g_strjoinv(token, parts); g_strfreev(parts); g_free(token);
soup_message_set_status(msg, 200);
soup_message_headers_replace(msg->response_headers, "Cache-Control", "no-store");
soup_message_set_response(msg, "text/html; charset=utf-8", SOUP_MEMORY_COPY, html, strlen(html)); g_free(html);
return;
}
soup_message_set_redirect(msg, SOUP_STATUS_FOUND, PORTAL_URL);
}
static gboolean monitor(gpointer unused)
{
(void)unused;
pthread_mutex_lock(&s_lock);
int busy = s_configuring;
GPid pid = s_dns;
int died = pid && waitpid(pid, NULL, WNOHANG) == pid;
if (died) s_dns = 0;
pthread_mutex_unlock(&s_lock);
if (died) {
set_state("failed", "热点 DHCP/DNS 服务意外退出");
feedback("start", "failed", -1, "热点 DHCP/DNS 服务意外退出", 1);
request_stop(); return G_SOURCE_REMOVE;
}
if (!busy && g_get_monotonic_time() - s_started > SESSION_SECONDS * G_USEC_PER_SEC) {
set_state("stopping", "设备热点已超时,正在关闭");
feedback("stop", "timeout", -1, "热点 15 分钟未完成配置,自动关闭", 1);
request_stop(); return G_SOURCE_REMOVE;
}
return G_SOURCE_CONTINUE;
}
static int start_dns(void)
{
char interface_arg[64]; g_snprintf(interface_arg, sizeof(interface_arg), "--interface=%s", s_ap_iface);
const char *dns[] = {"dnsmasq", "--keep-in-foreground", "--conf-file=/dev/null", "--user=root",
interface_arg, "--bind-interfaces", "--listen-address=" AP_IP, "--no-resolv", "--no-hosts",
"--address=/#/" AP_IP, "--dhcp-range=10.42.0.10,10.42.0.200,255.255.255.0,1h",
"--dhcp-option=3," AP_IP, "--dhcp-option=6," AP_IP,
"--dhcp-option-force=114," PORTAL_URL, "--dhcp-leasefile=/run/car-hotspot.leases",
"--pid-file=/run/car-hotspot.pid", NULL};
GPid pid = 0;
if (!g_spawn_async(NULL, (gchar **)dns, NULL, G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
NULL, NULL, &pid, NULL)) return -1;
g_usleep(400000);
if (waitpid(pid, NULL, WNOHANG) == pid) { g_spawn_close_pid(pid); return -1; }
pthread_mutex_lock(&s_lock); s_dns = pid; pthread_mutex_unlock(&s_lock);
save_marker();
return 0;
}
static int setup_exclusive_ap(void)
{
pthread_mutex_lock(&s_lock);
s_exclusive = 1; g_strlcpy(s_ap_iface, STA_IFACE, sizeof(s_ap_iface));
pthread_mutex_unlock(&s_lock);
feedback("start", "switching", 0, "正在切换热点配网模式,设备将暂时离开原 Wi-Fi", 0);
const char *single[] = {"nmcli", "connection", "add", "save", "no", "type", "wifi", "ifname", STA_IFACE,
"con-name", s_ap_name, "ssid", s_ssid, "mode", "ap", "connection.autoconnect", "no",
"802-11-wireless.band", "bg", "802-11-wireless.channel", "6",
"wifi-sec.key-mgmt", "wpa-psk", "wifi-sec.proto", "rsn",
"wifi-sec.pairwise", "ccmp", "wifi-sec.group", "ccmp", "wifi-sec.pmf", "disable",
"wifi-sec.psk", "12345678",
"ipv4.method", "manual", "ipv4.addresses", AP_IP "/24", "ipv4.never-default", "yes",
"ipv6.method", "disabled", NULL};
if (command(single, 15, NULL) != 0 || named_uuid(s_ap_name, s_ap_uuid, sizeof(s_ap_uuid)) != 0) return -1;
save_marker();
return uuid_command("up", s_ap_uuid, 30);
}
static int setup_ap(void)
{
if (geteuid() != 0 || if_nametoindex(AP_IFACE)) return -1;
for (const char *const *p = (const char *const[]){"iw", "nmcli", "dnsmasq", NULL}; *p; p++) {
char *found = g_find_program_in_path(*p); if (!found) return -1; g_free(found);
}
current_uuid(s_original, sizeof(s_original));
cache_networks();
char *uuid = g_uuid_string_random(); g_strlcpy(s_ap_uuid, uuid, sizeof(s_ap_uuid)); g_free(uuid);
g_snprintf(s_ap_name, sizeof(s_ap_name), "car-hotspot-%s", s_ap_uuid);
if (save_marker() != 0) return -1;
/* DHD virtual AP creation failed in the board logs and left BAD_IF state.
* Do not repeatedly enter that broken path before primary-interface setup. */
if (g_file_test("/sys/module/bcmdhd", G_FILE_TEST_IS_DIR)) {
my_zlog_info("hotspot: Broadcom DHD detected, using primary-interface WPA2 AP");
if (setup_exclusive_ap() != 0 || firewall_rules(1) != 0) return -1;
return start_dns();
}
char mac[18]; g_snprintf(mac, sizeof(mac), "02:ca:%.2s:%.2s:%.2s:%.2s", s_ap_uuid, s_ap_uuid+2, s_ap_uuid+4, s_ap_uuid+6);
const char *add_iface[] = {"iw", "dev", STA_IFACE, "interface", "add", AP_IFACE, "type", "__ap", "addr", mac, NULL};
if (command(add_iface, 10, NULL) != 0) return -1;
s_interface_created = 1;
const char *managed[] = {"nmcli", "device", "set", AP_IFACE, "managed", "yes", NULL};
for (int i = 0; command(managed, 5, NULL) != 0; i++) {
if (i >= 4) return -1;
g_usleep(300000);
}
/* Broadcom AP+STA shares its radio channel even when two channels are advertised. */
const char *link[] = {"iw", "dev", STA_IFACE, "link", NULL};
char *link_text = NULL;
int frequency = 2412;
if (command(link, 8, &link_text) == 0 && link_text) {
char *freq = strstr(link_text, "freq:");
if (freq) sscanf(freq, "freq: %d", &frequency);
}
g_free(link_text);
const char *band = frequency >= 5000 ? "a" : "bg";
int channel_number = frequency >= 5000 ? (frequency - 5000) / 5 :
(frequency == 2484 ? 14 : (frequency - 2407) / 5);
char channel[12]; g_snprintf(channel, sizeof(channel), "%d", channel_number > 0 ? channel_number : 1);
const char *add[] = {"nmcli", "connection", "add", "save", "no", "type", "wifi", "ifname", AP_IFACE,
"con-name", s_ap_name, "ssid", s_ssid, "mode", "ap",
"connection.autoconnect", "no", "802-11-wireless.band", band, "802-11-wireless.channel", channel,
"wifi-sec.key-mgmt", "wpa-psk", "wifi-sec.psk", "12345678",
"ipv4.method", "manual", "ipv4.addresses", AP_IP "/24", "ipv4.never-default", "yes",
"ipv6.method", "disabled", NULL};
if (command(add, 15, NULL) != 0) { my_zlog_warn("hotspot: AP profile creation failed"); return -1; }
if (named_uuid(s_ap_name, s_ap_uuid, sizeof(s_ap_uuid)) != 0) return -1;
save_marker();
if (uuid_command("up", s_ap_uuid, 30) != 0) {
my_zlog_warn("hotspot: concurrent AP unavailable, switching to single-radio setup mode");
uuid_command("down", s_ap_uuid, 10); uuid_command("delete", s_ap_uuid, 10);
delete_named(s_ap_name);
const char *del[] = {"iw", "dev", AP_IFACE, "del", NULL}; command(del, 10, NULL);
s_interface_created = 0;
if (setup_exclusive_ap() != 0) return -1;
}
char active[64]; current_uuid(active, sizeof(active));
if (!s_exclusive && s_original[0] && strcmp(active, s_original)) return -1;
if (firewall_rules(1) != 0) return -1;
return start_dns();
}
static void *server_worker(void *unused)
{
(void)unused;
SoupServer *server = NULL; GSource *watch = NULL;
GMainContext *context = g_main_context_new();
g_main_context_push_thread_default(context);
GMainLoop *loop = g_main_loop_new(context, FALSE);
pthread_mutex_lock(&s_lock); s_context = context; s_loop = loop; pthread_mutex_unlock(&s_lock);
int locked = wifi_operation_begin_wait(15) == 0;
if (!locked) goto failed;
if (setup_ap() != 0 || stopping()) goto failed;
server = soup_server_new(SOUP_SERVER_SERVER_HEADER, "Car WiFi Setup", NULL);
soup_server_add_handler(server, NULL, portal_handler, NULL, NULL);
GInetAddress *address = g_inet_address_new_from_string(AP_IP);
GSocketAddress *socket = g_inet_socket_address_new(address, 80);
GError *error = NULL;
int listening = soup_server_listen(server, socket, 0, &error);
g_object_unref(socket); g_object_unref(address);
if (!listening) { if (error) { my_zlog_warn("hotspot: HTTP listen failed: %s", error->message); g_error_free(error); } goto failed; }
pthread_mutex_lock(&s_lock); s_starting = 0; s_active = 1; s_started = g_get_monotonic_time(); pthread_mutex_unlock(&s_lock);
set_state("ready", "设备热点已开启,请用手机连接热点后配置 Wi-Fi");
feedback("start", "enabled", 0, "热点已开启,请连接热点后打开 http://10.42.0.1/ 配网", 1);
audio_play_system_beeps(3, 180);
watch = g_timeout_source_new_seconds(2); g_source_set_callback(watch, monitor, NULL, NULL); g_source_attach(watch, context);
if (!stopping()) g_main_loop_run(loop);
goto cleanup;
failed:
set_state("failed", "热点开启失败,请检查网卡并发模式、权限或 DHCP/DNS 服务");
feedback("start", "failed", -1, "热点开启失败,请检查网卡并发模式、权限或 DHCP/DNS 服务", 1);
audio_play_system_beeps(1, 180);
cleanup:
if (watch) { g_source_destroy(watch); g_source_unref(watch); }
if (server) { soup_server_disconnect(server); g_object_unref(server); }
int cleanup_failed = 0;
if (locked) {
pthread_mutex_lock(&s_lock); GPid dns = s_dns; s_dns = 0; pthread_mutex_unlock(&s_lock);
stop_dns(dns);
firewall_rules(0);
if (s_ap_uuid[0]) { uuid_command("down", s_ap_uuid, 10); uuid_command("delete", s_ap_uuid, 10); }
delete_named(s_ap_name);
if (s_interface_created) { const char *del[] = {"iw", "dev", AP_IFACE, "del", NULL}; command(del, 10, NULL); }
/* ensure_connection skips a healthy target, including a newly committed
* trial; a different or still-activating UUID must not skip recovery. */
if (s_original[0]) cleanup_failed = ensure_connection(s_original) != 0;
}
pthread_mutex_lock(&s_lock);
s_context = NULL; s_loop = NULL; s_active = 0; s_starting = 0; s_stopping = 0;
int pending = s_configuring || s_trial[0] || cleanup_failed;
cJSON *stop_request = s_stop_request; s_stop_request = NULL;
pthread_mutex_unlock(&s_lock);
if (locked) {
if (!pending) unlink(MARKER); else save_marker();
unlink("/run/car-hotspot.leases"); unlink("/run/car-hotspot.pid");
}
if (stop_request) {
device_feedback_send(3029, stop_request, "stop", cleanup_failed ? "failed" : "disabled",
cleanup_failed ? -1 : 0, cleanup_failed ? "热点已关闭,但原 Wi-Fi 恢复失败" : "设备热点已关闭", 1, NULL);
cJSON_Delete(stop_request);
}
pthread_mutex_lock(&s_lock);
if (cleanup_failed) {
g_strlcpy(s_status, "rollback_failed", sizeof(s_status));
g_strlcpy(s_message, "热点关闭后恢复原 Wi-Fi 失败", sizeof(s_message));
} else if (!strcmp(s_status, "ready") || !strcmp(s_status, "stopping")) {
g_strlcpy(s_status, "stopped", sizeof(s_status));
g_strlcpy(s_message, "设备热点已关闭", sizeof(s_message));
}
cJSON_Delete(s_request); s_request = NULL;
pthread_mutex_unlock(&s_lock);
g_main_loop_unref(loop); g_main_context_pop_thread_default(context); g_main_context_unref(context);
if (locked) wifi_operation_end();
return NULL;
}
int wifi_hotspot_control(cJSON *body)
{
cJSON *item = cJSON_GetObjectItemCaseSensitive(body, "action");
const char *action = cJSON_IsString(item) ? item->valuestring : "start";
if (external_hotspot_active()) {
device_feedback_send(3029, body, action, "busy", -1,
"另一个配网进程正在使用网卡,请等待其结束", 1, NULL);
return -1;
}
if (!strcmp(action, "status")) {
cJSON *details = status_json();
device_feedback_send(3029, body, action, "status", 0, "设备热点状态", 1, details); cJSON_Delete(details); return 0;
}
if (!strcmp(action, "stop")) {
pthread_mutex_lock(&s_lock);
if (s_configuring) {
pthread_mutex_unlock(&s_lock);
device_feedback_send(3029, body, action, "busy", -1, "正在验证 Wi-Fi,请等待完成后关闭热点", 1, NULL); return -1;
}
int active = s_active || s_starting;
if (active) { cJSON_Delete(s_stop_request); s_stop_request = cJSON_Duplicate(body, 1); }
pthread_mutex_unlock(&s_lock);
if (active) request_stop();
else device_feedback_send(3029, body, action, "disabled", 0, "设备热点已关闭", 1, NULL);
return 0;
}
if (strcmp(action, "start")) {
device_feedback_send(3029, body, action, "failed", -2, "action 仅支持 start、stop、status", 1, NULL); return -2;
}
pthread_mutex_lock(&s_lock);
if (s_starting || s_active || s_stopping || s_configuring) {
int active = s_active; pthread_mutex_unlock(&s_lock);
cJSON *details = status_json();
device_feedback_send(3029, body, action, active ? "enabled" : "starting", 0,
active ? "设备热点已开启" : "热点操作正在执行", active, details); cJSON_Delete(details); return 0;
}
int join = s_thread_started; s_thread_started = 0;
s_starting = 1; s_stop = 0;
pthread_mutex_unlock(&s_lock);
if (join) pthread_join(s_thread, NULL);
pthread_mutex_lock(&s_lock);
s_interface_created = 0; s_exclusive = 0; g_strlcpy(s_ap_iface, AP_IFACE, sizeof(s_ap_iface));
s_ap_uuid[0] = s_trial[0] = s_original[0] = 0;
s_ap_name[0] = s_trial_name[0] = 0;
cJSON_Delete(s_request); s_request = cJSON_Duplicate(body, 1);
g_strlcpy(s_ssid, g_get_host_name(), sizeof(s_ssid));
if (strlen(s_ssid) > 32) s_ssid[32] = 0;
char *token = g_uuid_string_random(); g_strlcpy(s_token, token, sizeof(s_token)); g_free(token);
g_strlcpy(s_status, "starting", sizeof(s_status)); g_strlcpy(s_message, "正在开启设备热点", sizeof(s_message));
pthread_mutex_unlock(&s_lock);
feedback("start", "accepted", 0, "正在开启设备热点", 0);
pthread_mutex_lock(&s_lock);
if (pthread_create(&s_thread, NULL, server_worker, NULL) != 0) {
s_starting = 0; pthread_mutex_unlock(&s_lock);
feedback("start", "failed", -1, "无法启动热点工作线程", 1); return -1;
}
s_thread_started = 1; pthread_mutex_unlock(&s_lock);
return 0;
}
void wifi_hotspot_shutdown(void)
{
pthread_mutex_lock(&s_lock); s_stop = 1; pthread_mutex_unlock(&s_lock);
for (int i = 0; i < 700; i++) {
pthread_mutex_lock(&s_lock); int busy = s_configuring; pthread_mutex_unlock(&s_lock);
if (!busy) break;
g_usleep(100000);
}
request_stop();
pthread_mutex_lock(&s_lock); int join = s_thread_started; s_thread_started = 0; pthread_mutex_unlock(&s_lock);
if (join) pthread_join(s_thread, NULL);
}
#ifndef WIFI_HOTSPOT_H
#define WIFI_HOTSPOT_H
#include <cjson/cJSON.h>
int wifi_hotspot_control(cJSON *body);
int wifi_hotspot_init(void);
int wifi_hotspot_is_active(void);
void wifi_hotspot_shutdown(void);
#endif
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>小车 Wi-Fi 配网</title>
<style>*{box-sizing:border-box}body{margin:0;background:#eef3f7;color:#172b3a;font:16px system-ui,sans-serif;min-height:100vh;display:grid;place-items:center;padding:22px}main{background:#fff;width:min(100%,460px);border-radius:24px;padding:30px;box-shadow:0 12px 40px #17374b12}.icon{font-size:32px}h1{font-size:25px;margin:14px 0 10px}p{color:#617383;line-height:1.65}label{display:block;font-weight:600;margin:22px 0 9px}select,input,button{font:inherit;width:100%;border-radius:12px;padding:13px}input,select{border:1px solid #cfdae2;background:#fbfcfd;color:#172b3a}button{border:0;background:#146d86;color:white;font-weight:650;margin-top:24px;cursor:pointer}button:disabled{opacity:.55;cursor:wait}.small{font-size:13px}.inline{font-weight:400;font-size:14px;display:flex;gap:8px;align-items:center}.inline input{width:auto}.link{border:0;background:none;color:#146d86;padding:0;text-align:left;margin-top:12px;font-size:14px}#status{padding:14px;border-radius:12px;background:#f1f6fa;margin-top:20px;line-height:1.6;overflow-wrap:anywhere}#status.good{background:#e6f6ee;color:#17633e}#status.bad{background:#fff0ed;color:#9e3c2c}footer{margin-top:22px;font-size:12px;color:#71818e}input:focus,select:focus,button:focus-visible{outline:3px solid #92cbd8;outline-offset:2px}</style></head>
<body><main><div class="icon" aria-hidden="true">📶</div><h1>为小车连接 Wi-Fi</h1><p>选择网络并输入密码。验证联网成功后,小车会保存配置并自动关闭设备热点。</p>
<form id="form"><label for="network">附近的 Wi-Fi</label><select id="network" required><option value="">正在扫描…</option></select><button class="link" id="rescan" type="button">刷新网络列表</button><label for="ssid">网络名称</label><input id="ssid" name="ssid" readonly aria-readonly="true" autocomplete="off" placeholder="请从上方选择 Wi-Fi"><label for="password">Wi-Fi 密码</label><input id="password" name="password" type="text" maxlength="64" autocomplete="off" autocapitalize="none" spellcheck="false" placeholder="开放网络可留空"><button id="submit" type="submit">验证并连接</button></form>
<div id="status" role="status" aria-live="polite">请保持手机连接设备热点,等待验证结果。</div><footer id="help">新网络不可用时不会保存密码,小车会尝试恢复原 Wi-Fi。请以验证结果为准。</footer></main>
<script>
const csrf='__PORTAL_TOKEN__', $=id=>document.getElementById(id);let busy=false,polling=false,completed=false,exclusive=false;
function message(text,kind=''){ $('status').textContent=text; $('status').className=kind; }
function lock(on){busy=on;for(const id of ['network','ssid','password','submit','rescan'])$(id).disabled=on;$('submit').textContent=on?'正在验证,请稍候…':'验证并连接';}
async function api(path,options={}){const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),4000);try{const r=await fetch(path,{cache:'no-store',...options,signal:controller.signal});const data=await r.json();if(!r.ok)throw Error(data.message||'请求失败,请重试');return data;}finally{clearTimeout(timer);}}
async function scan(){if(busy)return;$('rescan').disabled=true;try{const data=await api('/api/networks'),selected=$('network').value;$('network').replaceChildren(new Option('请选择 Wi-Fi',''));for(const n of data.networks){const op=new Option(n.ssid+' · '+n.signal+'%'+(n.security?' · '+n.security:''),n.ssid);$('network').appendChild(op);}if(data.networks.some(n=>n.ssid===selected))$('network').value=selected;$('ssid').value=$('network').value;if(!data.networks.length)message('没有获取到可选网络,请重新开启设备热点后重试。','bad');else if(data.cached)message('请选择列表中的 Wi-Fi,网络名称选择后不可编辑。');}catch(e){message(e.message,'bad');}finally{$('rescan').disabled=busy;}}
$('network').onchange=()=>{$('ssid').value=$('network').value;};$('rescan').onclick=scan;
async function poll(){if(polling)return;polling=true;let failures=0;while(!completed){try{const s=await api('/api/status');failures=0;if(s.status==='success'){message(s.message+' 热点即将关闭,请让手机连接同一 Wi-Fi。','good');completed=true;lock(true);break;}if(s.status==='failed'||s.status==='rollback_failed'){message(s.message,'bad');lock(false);break;}if(s.status==='stopping'||s.status==='stopped'){message('设备热点已关闭,请在 App 查看设备状态。');lock(true);break;}if(s.configuring){lock(true);message(s.message);}else if(!busy)break;}catch(e){if(exclusive){message('配置已提交,设备正在切换网络,暂时无法读取结果。手机可能自动关闭此页,请回到 App 确认设备上线和配网结果。');break;}if(++failures>15){message('暂时无法连接设备,请检查手机的 Wi-Fi 连接后重新打开此页面。','bad');break;}}await new Promise(r=>setTimeout(r,1000));}polling=false;}
$('form').onsubmit=async e=>{e.preventDefault();if(busy)return;const ssid=$('network').value;if(!ssid){message('请先选择 Wi-Fi。','bad');return;}lock(true);message('正在提交配置,请保持连接…');try{const ack=await api('/api/connect',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':csrf},body:JSON.stringify({ssid,password:$('password').value})});exclusive=!!ack.exclusive;if(exclusive){for(let remaining=ack.switch_delay_seconds||0;remaining>0;remaining--){message('配置已收到,约 '+remaining+' 秒后断开热点并验证 Wi-Fi。手机可能关闭此页,请在 App 查看结果。');await new Promise(r=>setTimeout(r,1000));}message('正在切换 Wi-Fi,请回到 App 等待设备上线并查看验证结果。');}poll();}catch(e){message(e.name==='AbortError'?'提交未能确认,请检查设备状态后重试。':e.message,'bad');lock(false);}};
(async()=>{try{const s=await api('/api/status');exclusive=!!s.exclusive;if(exclusive){$('help').textContent='提交后会先显示切换倒计时,再暂时断开设备热点以验证新 Wi-Fi。手机可能自动关闭此页,请在 App 查看结果;失败时设备会尝试恢复原 Wi-Fi。';}if(s.configuring){lock(true);poll();return;}if(s.status==='success'){message(s.message,'good');lock(true);return;}if(s.status==='failed'||s.status==='rollback_failed')message(s.message,'bad');}catch(e){}scan();})();
</script></body></html>
/* Embedded portal: regenerate from wifi_portal.html with JSON-escaped C strings. */
static const char WIFI_PORTAL_PAGE[] =
"<!doctype html>\n"
"<html lang=\"zh-CN\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>小车 Wi-Fi 配网</title>\n"
"<style>*{box-sizing:border-box}body{margin:0;background:#eef3f7;color:#172b3a;font:16px system-ui,sans-serif;min-height:100vh;display:grid;place-items:center;padding:22px}main{background:#fff;width:min(100%,460px);border-radius:24px;padding:30px;box-shadow:0 12px 40px #17374b12}.icon{font-size:32px}h1{font-size:25px;margin:14px 0 10px}p{color:#617383;line-height:1.65}label{display:block;font-weight:600;margin:22px 0 9px}select,input,button{font:inherit;width:100%;border-radius:12px;padding:13px}input,select{border:1px solid #cfdae2;background:#fbfcfd;color:#172b3a}button{border:0;background:#146d86;color:white;font-weight:650;margin-top:24px;cursor:pointer}button:disabled{opacity:.55;cursor:wait}.small{font-size:13px}.inline{font-weight:400;font-size:14px;display:flex;gap:8px;align-items:center}.inline input{width:auto}.link{border:0;background:none;color:#146d86;padding:0;text-align:left;margin-top:12px;font-size:14px}#status{padding:14px;border-radius:12px;background:#f1f6fa;margin-top:20px;line-height:1.6;overflow-wrap:anywhere}#status.good{background:#e6f6ee;color:#17633e}#status.bad{background:#fff0ed;color:#9e3c2c}footer{margin-top:22px;font-size:12px;color:#71818e}input:focus,select:focus,button:focus-visible{outline:3px solid #92cbd8;outline-offset:2px}</style></head>\n"
"<body><main><div class=\"icon\" aria-hidden=\"true\">📶</div><h1>为小车连接 Wi-Fi</h1><p>选择网络并输入密码。验证联网成功后,小车会保存配置并自动关闭设备热点。</p>\n"
"<form id=\"form\"><label for=\"network\">附近的 Wi-Fi</label><select id=\"network\" required><option value=\"\">正在扫描…</option></select><button class=\"link\" id=\"rescan\" type=\"button\">刷新网络列表</button><label for=\"ssid\">网络名称</label><input id=\"ssid\" name=\"ssid\" readonly aria-readonly=\"true\" autocomplete=\"off\" placeholder=\"请从上方选择 Wi-Fi\"><label for=\"password\">Wi-Fi 密码</label><input id=\"password\" name=\"password\" type=\"text\" maxlength=\"64\" autocomplete=\"off\" autocapitalize=\"none\" spellcheck=\"false\" placeholder=\"开放网络可留空\"><button id=\"submit\" type=\"submit\">验证并连接</button></form>\n"
"<div id=\"status\" role=\"status\" aria-live=\"polite\">请保持手机连接设备热点,等待验证结果。</div><footer id=\"help\">新网络不可用时不会保存密码,小车会尝试恢复原 Wi-Fi。请以验证结果为准。</footer></main>\n"
"<script>\n"
"const csrf='__PORTAL_TOKEN__', $=id=>document.getElementById(id);let busy=false,polling=false,completed=false,exclusive=false;\n"
"function message(text,kind=''){ $('status').textContent=text; $('status').className=kind; }\n"
"function lock(on){busy=on;for(const id of ['network','ssid','password','submit','rescan'])$(id).disabled=on;$('submit').textContent=on?'正在验证,请稍候…':'验证并连接';}\n"
"async function api(path,options={}){const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),4000);try{const r=await fetch(path,{cache:'no-store',...options,signal:controller.signal});const data=await r.json();if(!r.ok)throw Error(data.message||'请求失败,请重试');return data;}finally{clearTimeout(timer);}}\n"
"async function scan(){if(busy)return;$('rescan').disabled=true;try{const data=await api('/api/networks'),selected=$('network').value;$('network').replaceChildren(new Option('请选择 Wi-Fi',''));for(const n of data.networks){const op=new Option(n.ssid+' · '+n.signal+'%'+(n.security?' · '+n.security:''),n.ssid);$('network').appendChild(op);}if(data.networks.some(n=>n.ssid===selected))$('network').value=selected;$('ssid').value=$('network').value;if(!data.networks.length)message('没有获取到可选网络,请重新开启设备热点后重试。','bad');else if(data.cached)message('请选择列表中的 Wi-Fi,网络名称选择后不可编辑。');}catch(e){message(e.message,'bad');}finally{$('rescan').disabled=busy;}}\n"
"$('network').onchange=()=>{$('ssid').value=$('network').value;};$('rescan').onclick=scan;\n"
"async function poll(){if(polling)return;polling=true;let failures=0;while(!completed){try{const s=await api('/api/status');failures=0;if(s.status==='success'){message(s.message+' 热点即将关闭,请让手机连接同一 Wi-Fi。','good');completed=true;lock(true);break;}if(s.status==='failed'||s.status==='rollback_failed'){message(s.message,'bad');lock(false);break;}if(s.status==='stopping'||s.status==='stopped'){message('设备热点已关闭,请在 App 查看设备状态。');lock(true);break;}if(s.configuring){lock(true);message(s.message);}else if(!busy)break;}catch(e){if(exclusive){message('配置已提交,设备正在切换网络,暂时无法读取结果。手机可能自动关闭此页,请回到 App 确认设备上线和配网结果。');break;}if(++failures>15){message('暂时无法连接设备,请检查手机的 Wi-Fi 连接后重新打开此页面。','bad');break;}}await new Promise(r=>setTimeout(r,1000));}polling=false;}\n"
"$('form').onsubmit=async e=>{e.preventDefault();if(busy)return;const ssid=$('network').value;if(!ssid){message('请先选择 Wi-Fi。','bad');return;}lock(true);message('正在提交配置,请保持连接…');try{const ack=await api('/api/connect',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':csrf},body:JSON.stringify({ssid,password:$('password').value})});exclusive=!!ack.exclusive;if(exclusive){for(let remaining=ack.switch_delay_seconds||0;remaining>0;remaining--){message('配置已收到,约 '+remaining+' 秒后断开热点并验证 Wi-Fi。手机可能关闭此页,请在 App 查看结果。');await new Promise(r=>setTimeout(r,1000));}message('正在切换 Wi-Fi,请回到 App 等待设备上线并查看验证结果。');}poll();}catch(e){message(e.name==='AbortError'?'提交未能确认,请检查设备状态后重试。':e.message,'bad');lock(false);}};\n"
"(async()=>{try{const s=await api('/api/status');exclusive=!!s.exclusive;if(exclusive){$('help').textContent='提交后会先显示切换倒计时,再暂时断开设备热点以验证新 Wi-Fi。手机可能自动关闭此页,请在 App 查看结果;失败时设备会尝试恢复原 Wi-Fi。';}if(s.configuring){lock(true);poll();return;}if(s.status==='success'){message(s.message,'good');lock(true);return;}if(s.status==='failed'||s.status==='rollback_failed')message(s.message,'bad');}catch(e){}scan();})();\n"
"</script></body></html>\n";
#include "wifi_provision.h"
#include <string.h>
#include <ctype.h>
int wifi_provision_credentials_valid(const char *ssid, const char *password)
{
if (!ssid || !password || !ssid[0] || strlen(ssid) > 32)
return 0;
for (const unsigned char *p = (const unsigned char *)ssid; *p; p++)
if (*p < 32 || *p == 127) return 0;
size_t n = strlen(password);
if (n == 0 || (n >= 8 && n <= 63)) return 1;
if (n != 64) return 0;
for (size_t i = 0; i < n; i++)
if (!isxdigit((unsigned char)password[i])) return 0;
return 1;
}
int wifi_provision_run(const WifiProvisionOps *ops, void *ctx,
const char **failed_stage)
{
const char *stage = "creating";
if (ops->progress) ops->progress(ctx, stage);
int result = ops->create(ctx);
if (result == 0) {
stage = "connecting";
if (ops->progress) ops->progress(ctx, stage);
result = ops->activate(ctx);
}
if (result == 0) {
stage = "validating";
if (ops->progress) ops->progress(ctx, stage);
result = ops->verify(ctx);
}
if (result == 0) {
stage = "saving";
if (ops->progress) ops->progress(ctx, stage);
result = ops->commit(ctx);
}
if (result == 0) {
*failed_stage = "";
return 0;
}
*failed_stage = stage;
if (ops->progress) ops->progress(ctx, "rolling_back");
int discarded = ops->discard(ctx);
int restored = ops->restore(ctx);
if (discarded != 0 || restored != 0) return -2;
return -1;
}
#ifndef WIFI_PROVISION_H
#define WIFI_PROVISION_H
typedef struct {
int (*create)(void *);
int (*activate)(void *);
int (*verify)(void *);
int (*commit)(void *);
int (*discard)(void *);
int (*restore)(void *);
void (*progress)(void *, const char *);
} WifiProvisionOps;
/* Only commit may persist credentials. Every failure discards the trial first. */
int wifi_provision_run(const WifiProvisionOps *ops, void *ctx,
const char **failed_stage);
int wifi_provision_credentials_valid(const char *ssid, const char *password);
#endif
"""Check deployment paths in the compiled ELF without starting vehicle hardware."""
import argparse
from pathlib import Path
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("binary", type=Path)
parser.add_argument("--runtime-dir", default="/home/orangepi/car/master")
args = parser.parse_args()
if not args.binary.is_file():
parser.error(f"binary does not exist: {args.binary}")
data = args.binary.read_bytes()
if data[:4] != b"\x7fELF":
parser.error("expected an ELF executable")
for name in ("Deviceld.txt", "version.conf", "zlog.conf", "audio.mp3", "device_wifi.conf"):
expected = (args.runtime_dir.rstrip("/") + "/" + name).encode() + b"\0"
if expected not in data:
parser.exit(1, f"FAIL: deployment path missing: {expected[:-1].decode()}\n")
print("PASS: compiled runtime paths point to", args.runtime_dir)
#include "device_feedback.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
static int calls;
char *mqtt_topic_dev2app_number(void) { return "dev2app/test-device"; }
char *mqtt_topic_pure_number(void) { return "test-device"; }
int mqtt_publish_to_topics(const char *a, const char *b, const char *payload, int qos) {
assert(!strcmp(a, "dev2app/test-device") && !strcmp(b, "test-device"));
assert(qos == 1);
cJSON *json = cJSON_Parse(payload);
assert(cJSON_GetObjectItem(cJSON_GetObjectItem(json, "head"), "message_type")->valueint == 3028);
cJSON *body = cJSON_GetObjectItem(json, "body");
assert(!strcmp(cJSON_GetObjectItem(body, "key")->valuestring, "request-123"));
assert(cJSON_IsTrue(cJSON_GetObjectItem(body, "final")));
assert(cJSON_IsFalse(cJSON_GetObjectItem(body, "success")));
assert(!strstr(payload, "secret-key") && !cJSON_GetObjectItem(body, "authkey"));
cJSON_Delete(json); calls++; return 2;
}
int main(void) {
cJSON *request = cJSON_Parse("{\"key\":\"request-123\",\"authkey\":\"secret-key\"}");
assert(device_feedback_send(3028, request, "start", "failed", -1, "operation failed", 1, NULL) == 2);
assert(calls == 1);
assert(cJSON_GetObjectItem(request, "authkey"));
cJSON_Delete(request);
puts("PASS: MQTT feedback topics, correlation, result fields and credential omission");
return 0;
}
/* Hardware integration probe. Run only on a test board as root. */
#include "wifi_hotspot.h"
#include <glib.h>
#include <signal.h>
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
static volatile sig_atomic_t stop;
static void finish(int sig) { (void)sig; stop = 1; }
char *mqtt_topic_pure_number(void) { return "CN010200000020"; }
int device_feedback_send(int type, const cJSON *request, const char *action,
const char *state, int code, const char *message, int final, const cJSON *details) {
(void)request; (void)details;
printf("feedback %d %s %s code=%d final=%d %s\n", type, action, state, code, final, message);
fflush(stdout); return 1;
}
void my_zlog_warn(const char *fmt, ...) {
va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); fputc('\n', stderr);
}
void my_zlog_info(const char *fmt, ...) {
va_list args; va_start(args, fmt); vfprintf(stdout, fmt, args); va_end(args); fputc('\n', stdout);
}
void audio_play_system_beeps(unsigned count, unsigned gap_ms) {
printf("prompt bell repeats=%u gap_ms=%u\n", count, gap_ms); fflush(stdout);
}
int main(void) {
signal(SIGTERM, finish); signal(SIGINT, finish);
if (wifi_hotspot_init() != 0) return 1;
cJSON *request = cJSON_Parse("{\"action\":\"start\",\"key\":\"integration-probe\"}");
if (wifi_hotspot_control(request) != 0) return 1;
cJSON_Delete(request);
while (!stop) sleep(1);
wifi_hotspot_shutdown();
return 0;
}
#include "tailscale_deploy.h"
#include <glib.h>
#include <pthread.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t ready = PTHREAD_COND_INITIALIZER;
static int completed, commands, installed_events, enabled, disabled, fail_command;
static char *directory;
static char executable[256];
int device_command_run(const char *const args[], unsigned timeout, char **output) {
assert(timeout > 0); commands++;
if (output) *output = g_strdup("test-secret should never be published");
g_usleep(100000);
if (!strcmp(args[0], "sh")) {
assert(g_file_set_contents(executable, "#!/bin/sh\nexit 0\n", -1, NULL));
assert(chmod(executable, 0700) == 0);
}
if (!strcmp(args[0], "tailscale") && !strcmp(args[1], "up")) {
assert(!strcmp(args[3], "--authkey"));
assert(!strcmp(args[4], "test-secret;$(not-a-shell-command)"));
}
return fail_command && !strcmp(args[0], "systemctl") && !strcmp(args[1], "start") ? 1 : 0;
}
void my_zlog_warn(const char *fmt, ...) { (void)fmt; }
int device_feedback_send(int type, const cJSON *req, const char *action,
const char *state, int code, const char *message, int final, const cJSON *details) {
(void)action; (void)details;
assert(type == 3028 && !strstr(message, "test-secret"));
assert(!strcmp(cJSON_GetObjectItem(req, "key")->valuestring, "correlate-me"));
pthread_mutex_lock(&lock);
if (!strcmp(state, "installed")) installed_events++;
if (!strcmp(state, "enabled")) enabled++;
if (!strcmp(state, "disabled")) disabled++;
if (final) { assert(fail_command ? code != 0 && !strcmp(state, "failed") : code == 0); completed = 1; pthread_cond_signal(&ready); }
pthread_mutex_unlock(&lock); return 1;
}
int main(int argc, char **argv) {
assert(argc == 2);
fail_command = !strcmp(argv[1], "fail");
directory = g_dir_make_tmp("car-tailscale-test-XXXXXX", NULL); assert(directory);
g_snprintf(executable, sizeof(executable), "%s/tailscale", directory);
assert(g_setenv("PATH", directory, TRUE));
cJSON *request;
if (!strcmp(argv[1], "stop"))
request = cJSON_Parse("{\"authkey\":\"stop\",\"key\":\"correlate-me\"}");
else if (!strcmp(argv[1], "install"))
request = cJSON_Parse("{\"action\":\"install\",\"key\":\"correlate-me\"}");
else
request = cJSON_Parse("{\"authkey\":\"test-secret;$(not-a-shell-command)\",\"key\":\"correlate-me\"}");
assert(tailscale_control(request) == 0);
assert(tailscale_control(request) == 0); /* multi-broker duplicate must not launch again */
struct timespec until; clock_gettime(CLOCK_REALTIME, &until); until.tv_sec += 10;
pthread_mutex_lock(&lock);
while (!completed) assert(pthread_cond_timedwait(&ready, &lock, &until) == 0);
if (!strcmp(argv[1], "stop")) assert(disabled == 1 && commands == 0);
else if (!strcmp(argv[1], "install")) assert(installed_events == 1 && enabled == 0 && commands == 3);
else if (fail_command) assert(installed_events == 1 && enabled == 0 && commands == 4);
else assert(installed_events == 1 && enabled == 1 && commands == 5);
pthread_mutex_unlock(&lock);
cJSON_Delete(request);
unlink(executable); rmdir(directory); g_free(directory);
puts("PASS: asynchronous Tailscale feedback, duplicate suppression and safe argv");
return 0;
}
/*
* gcc tests/volume_control_test.c modules/webrtcpush/volume_control.c \
* -Imodules/webrtcpush -Imodules/logger \
* $(pkg-config --cflags --libs libsoup-2.4 json-glib-1.0) \
* -Wl,--wrap=soup_session_send_message -o volume_control_test
*/
#include "volume_control.h"
#include <libsoup/soup.h>
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
static const char *mock_body;
static guint mock_status = 200;
static unsigned request_count;
/* Replace only HTTP transport: exercise the real JSON parser and cached value. */
guint __wrap_soup_session_send_message(SoupSession *session, SoupMessage *msg)
{
(void)session;
assert(strcmp(soup_message_get_uri(msg)->path,
"/api/drive/use/status/CN010200000132") == 0);
request_count++;
soup_message_set_response(msg, "application/json", SOUP_MEMORY_COPY,
mock_body, strlen(mock_body));
SoupBuffer *body = soup_message_body_flatten(msg->response_body);
soup_buffer_free(body);
return mock_status;
}
void my_zlog_info(const char *format, ...) { (void)format; }
void my_zlog_warn(const char *format, ...) { (void)format; }
int main(void)
{
static const struct {
const char *body;
double expected;
int result;
} cases[] = {
{"{\"message\":\"success\",\"code\":200,\"data\":{\"id\":null,\"name\":null,\"value\":null,\"code\":null,\"parent\":null,\"child\":null,\"amount\":null,\"icon\":null,\"model\":0,\"businessJson\":\"{\\\"volume\\\":\\\"0.01\\\"}\",\"payChannel\":null}}", 0.01, 0},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":0.01}\"}}", 0.01, 0},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":\\\"0.9\\\"}\"}}", 0.9, 0},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":\\\"0\\\"}\"}}", 0, 0},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":\\\"3\\\"}\"}}", 1, 0},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":\\\"-0.1\\\"}\"}}", 0, 0},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":\\\" 0.01 \\\"}\"}}", 0.01, 0},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":\\\"1e-2\\\"}\"}}", 0.01, 0},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":\\\"\\\"}\"}}", 0.3, -1},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":\\\" \\\"}\"}}", 0.3, -1},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":\\\"0.01abc\\\"}\"}}", 0.3, -1},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":\\\"NaN\\\"}\"}}", 0.3, -1},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":\\\"Infinity\\\"}\"}}", 0.3, -1},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":\\\"1e999\\\"}\"}}", 0.3, -1},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":\\\"1e-999\\\"}\"}}", 0.3, -1},
{"{\"data\":{\"businessJson\":\"{\\\"volume\\\":0.3}\"}}", 0.3, 0},
{"{\"businessJson\":\"{\\\"volume\\\":0}\"}", 0.0, 0},
{"{\"businessJson\":\"{\\\"volume\\\":1}\"}", 1.0, 0},
{"{\"businessJson\":\"{\\\"volume\\\":3}\"}", 1.0, 0},
{"{\"businessJson\":\"{\\\"volume\\\":-0.5}\"}", 0.0, 0},
{"{\"data\":{\"data\":{\"businessJson\":\"{\\\"volume\\\":0.6}\"}}}", 0.6, 0},
{"{\"data\":{\"result\":{\"businessJson\":\"{\\\"volume\\\":0.7}\"}}}", 0.7, 0},
{"{\"result\":{\"businessJson\":\"{\\\"volume\\\":0.8}\"}}", 0.8, 0},
{"{}", 0.3, -1},
{"{\"businessJson\":\"{}\"}", 0.3, -1},
{"{\"businessJson\":\"{\\\"volume\\\":null}\"}", 0.3, -1},
{"{\"businessJson\":\"{\\\"volume\\\":true}\"}", 0.3, -1},
{"{\"businessJson\":null}", 0.3, -1},
{"{\"businessJson\":42}", 0.3, -1},
{"{\"businessJson\":\"invalid\"}", 0.3, -1},
{"invalid", 0.3, -1},
{"[]", 0.3, -1},
{"", 0.3, -1},
};
assert(fabs(volume_control_get_local_volume() - 0.3) < 1e-9);
assert(volume_control_load(NULL) == -1);
assert(volume_control_load("") == -1);
assert(request_count == 0);
for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
mock_body = cases[i].body;
unsigned before = request_count;
int result = volume_control_load("CN010200000132");
if (result != cases[i].result) {
fprintf(stderr, "case %zu: expected result %d, got %d; body=%s\n",
i, cases[i].result, result, mock_body);
return 1;
}
assert(request_count == before + 1);
assert(fabs(volume_control_get_local_volume() - cases[i].expected) < 1e-9);
}
mock_status = 503;
mock_body = "{\"businessJson\":\"{\\\"volume\\\":0.9}\"}";
assert(volume_control_load("CN010200000132") == -1);
assert(fabs(volume_control_get_local_volume() - 0.3) < 1e-9);
puts("PASS: startup volume parsing, clamping, fallback and one request per load");
return 0;
}
/* Compile with WIFI_OPERATION_LOCK_PATH pointing to an isolated test file. */
#include "wifi_operation.h"
#include <assert.h>
#include <pthread.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
static void child_try(int expected_busy)
{
pid_t pid = fork(); assert(pid >= 0);
if (pid == 0) {
int result = wifi_operation_begin();
if (result == 0) wifi_operation_end();
_exit((result != 0) == expected_busy ? 0 : 1);
}
int status; assert(waitpid(pid, &status, 0) == pid);
assert(WIFEXITED(status) && WEXITSTATUS(status) == 0);
}
static void *other_thread(void *unused)
{
(void)unused;
assert(wifi_operation_begin() != 0);
return NULL;
}
int main(void)
{
assert(wifi_operation_begin() == 0);
assert(wifi_operation_begin() == 0);
child_try(1);
pthread_t thread; assert(pthread_create(&thread, NULL, other_thread, NULL) == 0);
pthread_join(thread, NULL);
wifi_operation_end();
child_try(1); /* nested release must retain the outer operation */
wifi_operation_end();
child_try(0);
pid_t child = fork(); assert(child >= 0);
if (child == 0) { assert(wifi_operation_begin() == 0); _exit(0); }
int status; assert(waitpid(child, &status, 0) == child);
assert(wifi_operation_begin() == 0); /* exit/crash releases the kernel lock */
wifi_operation_end();
puts("PASS: recursive WiFi ownership, thread/process exclusion and exit recovery");
return 0;
}
#include "wifi_provision.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
typedef struct { char calls[32]; int n; char fail; int restore_fail; int discard_fail; } Test;
static int step(void *ctx, char op) {
Test *test = ctx; test->calls[test->n++] = op;
return op == test->fail ? -1 : 0;
}
static int create(void *p) { return step(p, 'C'); }
static int activate(void *p) { return step(p, 'A'); }
static int verify(void *p) { return step(p, 'V'); }
static int commit(void *p) { return step(p, 'S'); }
static int discard(void *p) { Test *t = p; int rc = step(p, 'D'); return t->discard_fail ? -1 : rc; }
static int restore(void *p) { Test *t = p; step(p, 'R'); return t->restore_fail ? -1 : 0; }
static const WifiProvisionOps ops = {create, activate, verify, commit, discard, restore, NULL};
int main(void) {
const char *stage;
Test ok = {0};
assert(wifi_provision_run(&ops, &ok, &stage) == 0);
assert(!strcmp(ok.calls, "CAVS"));
const char failures[] = "CAVS";
const char *sequences[] = {"CDR", "CADR", "CAVDR", "CAVSDR"};
const char *stages[] = {"creating", "connecting", "validating", "saving"};
for (int i = 0; i < 4; i++) {
Test test = {.fail = failures[i]};
assert(wifi_provision_run(&ops, &test, &stage) == -1);
assert(!strcmp(test.calls, sequences[i]));
assert(!strcmp(stage, stages[i]));
}
Test rollback = {.fail = 'V', .restore_fail = 1};
assert(wifi_provision_run(&ops, &rollback, &stage) == -2);
Test cleanup = {.fail = 'V', .discard_fail = 1};
/* A verifier failure plus a cleanup failure must never report clean rollback. */
assert(wifi_provision_run(&ops, &cleanup, &stage) == -2);
assert(wifi_provision_credentials_valid("test", "12345678"));
assert(wifi_provision_credentials_valid("open", ""));
assert(wifi_provision_credentials_valid("quotes' ; $(x)", "abc'12345"));
assert(!wifi_provision_credentials_valid("", "12345678"));
assert(!wifi_provision_credentials_valid("test\nname", "12345678"));
assert(!wifi_provision_credentials_valid("test", "123"));
assert(!wifi_provision_credentials_valid("123456789012345678901234567890123", "12345678"));
puts("PASS: WiFi validates before save; failures discard and restore; input validation");
return 0;
}
# MQTT 维护反馈与热点配网
# MQTT 维护反馈与热点配网
## 播报音量
开机从 `/api/drive/use/status/{设备号}` 读取 `businessJson.volume`,兼容数值和数字字符串,范围限制为 0–1,默认 0.3。2017 本地播报、联网成功/失败语音使用这个缓存倍率。后台修改后需重启程序重新读取。配网系统短音单独固定为 0.5(50%),不受 `businessJson.volume` 影响。
热点开启成功、配网成功、失败均使用同一个系统 `bell.oga` 音色,通过节奏区分:开启热点成功为三声、间隔 180 毫秒;配网成功为两声、间隔 450 毫秒;失败为一声。系统铃声缺失时各状态统一尝试相同的系统音效回退,不回退到语音。短音在后台播放,不阻塞热点 HTTP 服务或连接清理,固定 50% 音量。
系统短音先合成为带 500 毫秒静音前导、间隔和尾部静音的连续 WAV,再交给原有播放入口;整组声音只打开一次声卡,避免短音被声卡启动过程截掉。合成失败时记录错误并尝试原始系统音效。
配网短音复用现有 `audioplay_file_with_browser_preempt()` 播放入口与声卡排队逻辑,单独传入 0.5 音量,不另改声卡路由或混音器设置。
## Topic 与通用反馈
请求发往现有订阅 topic:`app2dev/{设备号}` 或 `ser2dev/{设备号}`。
反馈同时发往 `dev2app/{设备号}` 与 `{设备号}`,QoS 1。body 只回传请求的 `key`,不会回传授权密钥或 Wi-Fi 密码。
```json
{
"head": {"message_type": 3028},
"body": {
"key": "request-001",
"action": "start",
"status": "enabled",
"code": 0,
"success": true,
"final": true,
"message": "Tailscale 已开启"
}
}
```
`final:false` 是进度事件;`final:true` 是当前操作结果。`code:0` 表示成功,其他值表示失败。多 MQTT 节点可能重复传递同一反馈,上层应按请求 key 和操作状态显示结果。执行中的重复请求不会重复启动同一任务。
## Tailscale:2028 请求,3028 反馈
保留原格式:
```json
{"head":{"message_type":2028},"body":{"key":"ts-start-001","authkey":"tskey-auth-REPLACE"}}
```
关闭兼容原格式 `"authkey":"stop"`,也支持:
```json
{"head":{"message_type":2028},"body":{"key":"ts-stop-001","action":"stop"}}
```
仅安装:
```json
{"head":{"message_type":2028},"body":{"key":"ts-install-001","action":"install"}}
```
开启可显式指定 `action:start` 并提供 `authkey`。未安装时先安装,再开启。状态包括 `accepted`、`installing`、`installed`、`starting`、`enabled`、`stopping`、`disabled`、`failed`、`busy`。工作在后台线程执行,有超时限制,不阻塞 MQTT 接收线程;错误反馈不包含命令原始输出中的密钥。
## 热点:2029 请求,3029 反馈
开启:
```json
{"head":{"message_type":2029},"body":{"key":"wifi-ap-001","action":"start"}}
```
关闭/查询:将 `action` 改为 `stop` 或 `status`。验证 Wi-Fi 期间不接受手动关闭,也暂停旧的自动 Wi-Fi 恢复和其他保存/切换接口,防止多个流程相互抢占网卡。
- 热点名称:板子主机名,例如 `orangepi3b`。
- 密码:`12345678`。
- 配网页面:`http://10.42.0.1/`。
- DHCP/DNS 及 HTTP 探测重定向用于触发手机配网页面;手机未自动弹出时可手动打开上述地址。
- 页面显示开启热点前扫描到的附近 Wi-Fi;网络名称只能从列表选择,选择后只读;密码默认明文显示,不提供隐藏开关。热点期间不触发网卡扫描。支持开放网络及 WPA/WPA2 个人密码网络。
- `data.exclusive:true` 表示单网卡配网模式。此模式会暂时离开原 Wi-Fi,提交新网络后手机会断开设备热点;通过提示音和 MQTT 确认结果。
- 单网卡提交返回 202 后保留热点约 8 秒,页面显示切换倒计时。之后手机系统可能自动关闭配网页面,最终结果以设备验证反馈为准;页面关闭不表示验证成功。
### 配网事务
1. 记录原连接 UUID,保留原已保存配置。
2. 创建不落盘、不自动连接的临时试连配置。
3. 尝试连接;通过 `wlan0` 请求业务 HTTPS 配置接口,校验 HTTP 200、业务 code 200 和 data 对象,确认新 Wi-Fi 真正可用。
4. 验证通过才保存新配置并开启自动连接,然后关闭热点。
5. 任一步失败,删除试连配置并恢复原连接。单网卡模式恢复原 Wi-Fi 后结束热点会话,可由 App 重新发送 2029 开启重试;并发模式保留热点供重试。
6. 清理或回退失败明确反馈 `rollback_failed`,不冒充成功;无法恢复旧连接时尝试恢复热点供重新配置。
Broadcom DHD 驱动的板子直接使用主网卡热点模式,避免已在日志中确认失败的虚拟接口初始化;热点明确使用 WPA2/RSN/CCMP,并关闭 PMF,兼容该驱动。其他驱动优先尝试独立虚拟接口,失败时回退主网卡模式。单网卡切换到用户 Wi-Fi 前先停止热点 DHCP/DNS,避免在用户的真实局域网提供 DHCP。15 分钟未完成配网会结束会话并恢复原网络。
本板 DHD 驱动退出 AP 后曾拒绝正确密码网络和原连接的关联请求。切换到 STA 试连前会执行 Wi-Fi radio off/on,并等待 NetworkManager 报告接口可用;恢复原连接首次失败时,也会重新初始化后再试一次。已正常连接目标 UUID 时直接返回,不重复断开。
维护状态保存在 `/run/car-controlserver-hotspot.json`,服务重启时用于清理本进程创建的热点/临时配置并回退原连接;此文件不存 Wi-Fi 密码。服务正常退出会清理热点和 DHCP/DNS 子进程。
### 网页接口
仅监听热点地址 `10.42.0.1:80`:
- `GET /`:内嵌离线网页,无外部资源依赖。
- `GET /api/networks`:开启热点前的网络扫描缓存,包含缓存标记和年龄。
- `GET /api/status`:配网状态,不返回密码。
- `POST /api/connect`:JSON `{ssid,password}`,需页面内生成的 `X-CSRF-Token`;先返回 202(含 `exclusive`、`switch_delay_seconds`),再后台试连。
HTTP 主机名重定向和会话令牌用于保护配置提交。页面不会将网络名称拼入 HTML;后台执行 NetworkManager 命令使用独立 argv,不拼接用户提供的网络名称或密码到 shell。
### 回归测试
- `tests/volume_control_test.c`:接口数值/字符串倍率与边界。
- `tests/wifi_provision_test.c`:先验证后保存、失败清理与回退、输入边界。
- `tests/device_feedback_test.c`:topic、请求 key、结果字段、敏感信息遗漏。
- `tests/tailscale_feedback_test.c`:后台进度、安装/开启/关闭/失败、重复抑制、安全参数传递。
- `tests/check_runtime_paths.py`:检查最终 ELF 的运行数据目录。
- `tests/hotspot_probe.c`:板端手工集成测试探针,启动真实热点;仅在测试板上运行。
2026-11-06 在 `192.168.0.131`、DHD 驱动板端验证:正确密码通过业务 HTTPS 校验后保存、关闭热点;错误密码不落盘并恢复原连接;两次测试期间 main 未重启。该次错误密码从判定失败到原连接恢复约 1.3 秒,耗时取决于网络状态。网页验证通过:选择后的 SSID 只读、密码明文、无隐藏开关。带前导静音的三声系统铃声以 50% 倍率通过原播放入口播放,现场确认可听。
## main 内的自动联网冲突隔离
`main.c` 启动的 `thread_wifi_offline_recovery` 每约 40 秒检查互联网,失败时调用 `device_wifi_connect_best_saved_visible`,再通过 `nmcli connection up` 激活已保存 Wi-Fi。启动阶段 `check_and_autoconfig_wifi` 的循环也会调用恢复逻辑和扫码连接。单网卡热点期间没有互联网是正常状态,不能因此抢占 wlan0。
热点会话在 `/run/car-controlserver-hotspot.json` 写入所有者 PID、进程启动时间和活动状态;同进程和独立配网测试进程都能被新版 main 识别。过期 PID 或僵尸进程不视为活动配网。启动时遇到其他仍在运行的配网进程会等待,不清理它的热点。
`/run/car-controlserver-wifi.lock` 提供跨线程、跨进程的网卡操作排他锁。热点持有锁直至清理结束;普通自动重连、扫码连接和旧的扫描/切换入口不能抢占。热点开始时最多等待正在执行的网卡操作 15 秒,避免扫描后、切换前的竞态。正常关闭后恢复原定的自动联网机制。
单网卡模式提交配置时,回退目标使用开启热点前保存的 Wi-Fi UUID,不能使用此时 wlan0 上的热点 UUID。恢复连接前检查目标 UUID 与设备 connected 状态,避免对已经正常联网的连接重复执行激活。日志 `hotspot: status=...` 记录各阶段,不包含 Wi-Fi 密码。
旧版 main 不认识这些状态和锁。独立探针测试前必须停止旧 main,且停用可能重新启动或替换 main 的 OTA。当前已识别 OTA 为 `gostart.service`;测试期间应保持 inactive、disabled,未获授权不要重新启用。
# 香橙派车控项目交接文档 # 香橙派车控项目交接文档
...@@ -665,6 +665,7 @@ curl -i http://192.168.0.104:8080/ ...@@ -665,6 +665,7 @@ curl -i http://192.168.0.104:8080/
- 当前 USB 声卡位于 card 2,但枚举序号可能重启后变化,建议使用稳定的 ALSA by-id 或 udev 规则; - 当前 USB 声卡位于 card 2,但枚举序号可能重启后变化,建议使用稳定的 ALSA by-id 或 udev 规则;
- 日志显示系统会将 Yundea USB 声卡的输入/输出设为默认; - 日志显示系统会将 Yundea USB 声卡的输入/输出设为默认;
- MQTT 音频 `volume` 是线性增益,代码钳位到 `[0, 2]`。 - MQTT 音频 `volume` 是线性增益,代码钳位到 `[0, 2]`。
- MQTT 2017 有人驾驶本地播报:开机联网后读取一次 `/api/drive/use/status/{设备号}` 的 `businessJson.volume` 并缓存在运行内存中,范围 `[0, 1]`,`0.3` 表示 30%,默认 `0.3`;不再定时轮询。
## 13. 日志、监控与健康检查 ## 13. 日志、监控与健康检查
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment