Initial commit

This commit is contained in:
zhangshun
2026-06-01 15:55:59 +08:00
commit 40f9bdb590
1799 changed files with 362227 additions and 0 deletions

943
src/smart_json_wrapper.cpp Normal file
View File

@@ -0,0 +1,943 @@
#include "smart_json_wrapper.h"
#include "KinematicsWebAPI.h"
#include <emscripten.h>
#include <cmath>
#include <chrono>
#include <sstream>
#include <iomanip>
#include <regex>
#include <algorithm>
#include <memory>
#include <iostream>
#include <cstring>
#include <cctype>
// ========== 内存管理辅助函数 ==========
namespace
{
// 创建 WASM 内存中的字符串(使用 malloc 分配,与 JavaScript 的 _free 兼容)
char *createWasmString(const std::string &str)
{
if (str.empty())
{
char *buffer = (char *)malloc(1);
if (buffer)
{
buffer[0] = '\0';
}
return buffer;
}
size_t len = str.length();
char *buffer = (char *)malloc(len + 1); // +1 for null terminator
if (buffer)
{
// 使用 std::copy 复制字符串内容
std::copy(str.begin(), str.end(), buffer);
buffer[len] = '\0'; // 添加 null 终止符
}
return buffer;
}
// 安全释放 WASM 字符串(使用 free 释放,与 JavaScript 的 _free 兼容)
void freeWasmString(const char *str)
{
if (str)
{
free(const_cast<char *>(str));
}
}
}
// ========== SmartResponse 实现 ==========
std::string SmartResponse::toJson() const
{
std::stringstream ss;
ss << "{";
ss << "\"success\":" << (success ? "true" : "false") << ",";
ss << "\"code\":" << code << ",";
ss << "\"msg\":\"" << msg << "\",";
ss << "\"req_code\":\"" << req_code << "\",";
ss << "\"req_cmd\":\"" << req_cmd << "\",";
ss << "\"execution_time\":" << std::fixed << std::setprecision(3) << execution_time << ",";
// 处理结果数据
ss << "\"res_data\":";
if (res_data.has_value())
{
try
{
if (res_data.type() == typeid(int))
{
ss << std::any_cast<int>(res_data);
}
else if (res_data.type() == typeid(float))
{
ss << std::fixed << std::setprecision(3) << std::any_cast<float>(res_data);
}
else if (res_data.type() == typeid(double))
{
ss << std::fixed << std::setprecision(3) << std::any_cast<double>(res_data);
}
else if (res_data.type() == typeid(bool))
{
ss << (std::any_cast<bool>(res_data) ? "true" : "false");
}
else if (res_data.type() == typeid(std::string))
{
ss << "\"" << std::any_cast<std::string>(res_data) << "\"";
}
else if (res_data.type() == typeid(std::vector<int>))
{
auto arr = std::any_cast<std::vector<int>>(res_data);
ss << "[";
for (size_t i = 0; i < arr.size(); ++i)
{
if (i > 0)
ss << ",";
ss << arr[i];
}
ss << "]";
}
else
{
// 默认处理为字符串
ss << "\"complex_data\"";
}
}
catch (const std::bad_any_cast &)
{
ss << "null";
}
}
else
{
ss << "null";
}
// 执行信息
if (!execution_info.empty())
{
ss << ",\"execution_info\":{";
bool first = true;
for (const auto &[key, value] : execution_info)
{
if (!first)
ss << ",";
ss << "\"" << key << "\":\"" << value << "\"";
first = false;
}
ss << "}";
}
ss << "}";
return ss.str();
}
SmartResponse SmartResponse::createSuccess(const std::string &req_code,
const std::string &req_cmd,
const std::any &data)
{
SmartResponse resp;
resp.success = true;
resp.code = 0;
resp.msg = "操作成功";
resp.req_code = req_code;
resp.req_cmd = req_cmd;
resp.res_data = data;
return resp;
}
SmartResponse SmartResponse::createError(const std::string &req_code,
const std::string &req_cmd,
int code,
const std::string &msg)
{
SmartResponse resp;
resp.success = false;
resp.code = code;
resp.msg = msg;
resp.req_code = req_code;
resp.req_cmd = req_cmd;
return resp;
}
// ========== 字符串工具函数 ==========
std::string SmartJsonProcessor::trim(const std::string &str)
{
size_t first = str.find_first_not_of(" \t\n\r");
if (first == std::string::npos)
return "";
size_t last = str.find_last_not_of(" \t\n\r");
return str.substr(first, (last - first + 1));
}
std::vector<std::string> SmartJsonProcessor::split(const std::string &str, char delimiter)
{
std::vector<std::string> tokens;
std::stringstream ss(str);
std::string token;
while (std::getline(ss, token, delimiter))
{
token = trim(token);
if (!token.empty())
{
tokens.push_back(token);
}
}
return tokens;
}
// ========== SmartJsonProcessor 实现 ==========
SmartJsonProcessor::SmartJsonProcessor()
{
registerMathFunctions();
}
SmartJsonProcessor::~SmartJsonProcessor()
{
// 清理资源
}
// ========== JSON 解析 ==========
std::map<std::string, std::any> SmartJsonProcessor::parseJsonParams(const std::string &json_str)
{
std::map<std::string, std::any> params;
// 简化JSON解析解析键值对
std::regex param_regex("\"([^\"]+)\"\\s*:\\s*([^,}\\s\"]+|\"[^\"]*\")");
std::sregex_iterator it(json_str.begin(), json_str.end(), param_regex);
std::sregex_iterator end;
while (it != end)
{
std::smatch match = *it;
std::string key = match[1].str();
std::string value = match[2].str();
// 移除引号
if (!value.empty() && value[0] == '"' && value.back() == '"')
{
value = value.substr(1, value.length() - 2);
}
params[key] = inferJsonValue(key, value);
++it;
}
// 特别处理数组参数
std::regex array_regex("\"([^\"]+)\"\\s*:\\s*\\[([^\\]]*)\\]");
it = std::sregex_iterator(json_str.begin(), json_str.end(), array_regex);
while (it != end)
{
std::smatch match = *it;
std::string key = match[1].str();
std::string array_str = match[2].str();
// 尝试解析为整数数组
auto int_array = parseIntArray(array_str);
if (!int_array.empty())
{
params[key] = int_array;
}
else
{
// 尝试解析为浮点数数组
auto float_array = parseFloatArray(array_str);
if (!float_array.empty())
{
params[key] = float_array;
}
}
++it;
}
return params;
}
std::any SmartJsonProcessor::inferJsonValue(const std::string &key, const std::string &value_str)
{
if (value_str.empty())
{
return std::string();
}
// 根据键名猜测类型
std::string lower_key = key;
// std::transform(lower_key.begin(), lower_key.end(), lower_key.begin(), ::towlower);
// std::transform(lower_key.begin(), lower_key.end(), lower_key.begin(), std::tolower);
// 布尔值
if (value_str == "true" || value_str == "false")
{
return value_str == "true";
}
// 尝试解析为数字
try
{
// 检查是否是整数
// if (value_str.find('.') == std::string::npos && value_str.find('e') == std::string::npos)
// {
// return std::stoi(value_str);
// }
// else
// {
// return std::stof(value_str);
// }
}
catch (...)
{
// 不是数字,保持字符串
}
return value_str;
}
std::vector<int> SmartJsonProcessor::parseIntArray(const std::string &array_str)
{
std::vector<int> result;
auto tokens = split(array_str, ',');
for (const auto &token : tokens)
{
try
{
result.push_back(std::stoi(trim(token)));
}
catch (...)
{
// 转换失败,清空数组并返回
result.clear();
break;
}
}
return result;
}
std::vector<float> SmartJsonProcessor::parseFloatArray(const std::string &array_str)
{
std::vector<float> result;
auto tokens = split(array_str, ',');
for (const auto &token : tokens)
{
try
{
result.push_back(std::stof(trim(token)));
}
catch (...)
{
// 转换失败,清空数组并返回
result.clear();
break;
}
}
return result;
}
// ========== 数学函数注册 ==========
void SmartJsonProcessor::registerMathFunctions()
{
auto &registry = FunctionRegistry::instance();
// 1. add 函数
auto add_func = std::make_shared<FunctionInfo>("add", "整数加法");
add_func->addParam("a", ParamType::INT, 0)
.addParam("b", ParamType::INT, 0)
.addAlias("a", {"num1", "first", "x", "operand1", "left"})
.addAlias("b", {"num2", "second", "y", "operand2", "right"})
.setHandler([](const std::vector<std::any> &args) -> std::any
{
if (args.size() >= 2) {
int a = 0, b = 0;
try {
a = std::any_cast<int>(args[0]);
b = std::any_cast<int>(args[1]);
} catch (...) {
// 尝试转换
if (args[0].type() == typeid(float)) a = static_cast<int>(std::any_cast<float>(args[0]));
if (args[1].type() == typeid(float)) b = static_cast<int>(std::any_cast<float>(args[1]));
}
return add(a, b);
}
return 0; });
registry.registerFunction(add_func);
// 2. subtract 函数
auto sub_func = std::make_shared<FunctionInfo>("subtract", "整数减法");
sub_func->addParam("a", ParamType::INT, 0)
.addParam("b", ParamType::INT, 0)
.addAlias("a", {"num1", "minuend", "x"})
.addAlias("b", {"num2", "subtrahend", "y"})
.setHandler([](const std::vector<std::any> &args) -> std::any
{
if (args.size() >= 2) {
int a = 0, b = 0;
try {
a = std::any_cast<int>(args[0]);
b = std::any_cast<int>(args[1]);
} catch (...) {
if (args[0].type() == typeid(float)) a = static_cast<int>(std::any_cast<float>(args[0]));
if (args[1].type() == typeid(float)) b = static_cast<int>(std::any_cast<float>(args[1]));
}
return subtract(a, b);
}
return 0; });
registry.registerFunction(sub_func);
// 3. multiply 函数
auto mul_func = std::make_shared<FunctionInfo>("multiply", "乘法运算");
mul_func->addParam("a", ParamType::FLOAT, 0.0f)
.addParam("b", ParamType::FLOAT, 0.0f)
.addAlias("a", {"num1", "factor1", "x", "multiplicand"})
.addAlias("b", {"num2", "factor2", "y", "multiplier"})
.setHandler([](const std::vector<std::any> &args) -> std::any
{
if (args.size() >= 2) {
float a = 0.0f, b = 0.0f;
try {
if (args[0].type() == typeid(float)) a = std::any_cast<float>(args[0]);
else if (args[0].type() == typeid(int)) a = static_cast<float>(std::any_cast<int>(args[0]));
if (args[1].type() == typeid(float)) b = std::any_cast<float>(args[1]);
else if (args[1].type() == typeid(int)) b = static_cast<float>(std::any_cast<int>(args[1]));
} catch (...) {
// 使用默认值
}
return multiply(a, b);
}
return 0.0f; });
registry.registerFunction(mul_func);
// 4. divide 函数
auto div_func = std::make_shared<FunctionInfo>("divide", "除法运算");
div_func->addParam("a", ParamType::FLOAT, 0.0f)
.addParam("b", ParamType::FLOAT, 1.0f)
.addAlias("a", {"numerator", "dividend", "x"})
.addAlias("b", {"denominator", "divisor", "y"})
.setHandler([](const std::vector<std::any> &args) -> std::any
{
if (args.size() >= 2) {
float a = 0.0f, b = 1.0f;
try {
if (args[0].type() == typeid(float)) a = std::any_cast<float>(args[0]);
else if (args[0].type() == typeid(int)) a = static_cast<float>(std::any_cast<int>(args[0]));
if (args[1].type() == typeid(float)) b = std::any_cast<float>(args[1]);
else if (args[1].type() == typeid(int)) b = static_cast<float>(std::any_cast<int>(args[1]));
} catch (...) {
// 使用默认值
}
if (b == 0.0f) {
throw std::runtime_error("除数不能为零");
}
return divide(a, b);
}
return 0.0f; });
registry.registerFunction(div_func);
// 5. fibonacci 函数
auto fib_func = std::make_shared<FunctionInfo>("fibonacci", "斐波那契数列");
fib_func->addParam("n", ParamType::INT, 0)
.addAlias("n", {"number", "index", "term", "position"})
.setHandler([](const std::vector<std::any> &args) -> std::any
{
if (!args.empty()) {
int n = 0;
try {
n = std::any_cast<int>(args[0]);
} catch (...) {
if (args[0].type() == typeid(float)) n = static_cast<int>(std::any_cast<float>(args[0]));
}
if (n < 0) n = 0;
if (n > 40) n = 40; // 限制大小避免性能问题
return fibonacci(n);
}
return 0; });
registry.registerFunction(fib_func);
// 6. create_buffer 函数
auto create_buf_func = std::make_shared<FunctionInfo>("create_buffer", "创建缓冲区");
create_buf_func->addParam("size", ParamType::INT, 1024)
.addAlias("size", {"length", "capacity", "bytes"})
.setHandler([](const std::vector<std::any> &args) -> std::any
{
if (!args.empty()) {
int size = 1024;
try {
size = std::any_cast<int>(args[0]);
} catch (...) {
if (args[0].type() == typeid(float)) size = static_cast<int>(std::any_cast<float>(args[0]));
}
if (size <= 0) size = 1024;
if (size > 1024 * 1024) size = 1024 * 1024; // 限制1MB
void* buffer = create_buffer(size);
std::stringstream ss;
ss << "0x" << std::hex << reinterpret_cast<uintptr_t>(buffer);
return ss.str();
}
return "null"; });
registry.registerFunction(create_buf_func);
// 7. compute_sum 函数
auto sum_func = std::make_shared<FunctionInfo>("compute_sum", "数组求和");
sum_func->addParam("array", ParamType::INT_ARRAY, std::vector<int>())
.addAlias("array", {"arr", "list", "values", "numbers"})
.setHandler([](const std::vector<std::any> &args) -> std::any
{
if (!args.empty()) {
try {
auto arr = std::any_cast<std::vector<int>>(args[0]);
if (arr.empty()) return 0;
return compute_sum(arr.data(), static_cast<int>(arr.size()));
} catch (...) {
return 0;
}
}
return 0; });
registry.registerFunction(sum_func);
// 8. get_greeting 函数
auto greet_func = std::make_shared<FunctionInfo>("get_greeting", "获取问候语");
greet_func->setHandler([](const std::vector<std::any> &args) -> std::any
{
const char* greeting = get_greeting();
return std::string(greeting); });
registry.registerFunction(greet_func);
}
// ========== 主处理函数 ==========
SmartResponse SmartJsonProcessor::processRequest(const std::string &json_request)
{
auto start_time = std::chrono::high_resolution_clock::now();
try
{
// 1. 解析基础信息
std::string req_code = "REQ_" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count());
std::string req_cmd = "unknown";
// 简化解析req_cmd
std::regex cmd_regex("\"req_cmd\"\\s*:\\s*\"([^\"]+)\"");
std::smatch match;
if (std::regex_search(json_request, match, cmd_regex))
{
req_cmd = match[1].str();
}
// 2. 获取函数信息
auto &registry = FunctionRegistry::instance();
auto func_info = registry.getFunction(req_cmd);
if (!func_info)
{
return SmartResponse::createError(req_code, req_cmd, 1001,
"未找到函数: " + req_cmd);
}
// 3. 解析参数
auto input_params = parseJsonParams(json_request);
// 4. 智能参数匹配
auto matched_params = registry.smartMatchParams(func_info, input_params);
// 5. 验证参数
std::string error_msg;
if (!func_info->validateParams(matched_params, error_msg))
{
return SmartResponse::createError(req_code, req_cmd, 1002, error_msg);
}
// 6. 准备调用参数
std::vector<std::any> call_args;
for (const auto &param : func_info->params)
{
auto it = matched_params.find(param.name);
if (it != matched_params.end())
{
call_args.push_back(it->second);
}
else if (param.default_value.has_value())
{
call_args.push_back(param.default_value);
}
else
{
call_args.push_back(std::any()); // 空值
}
}
// 7. 执行函数
std::any result;
try
{
result = func_info->handler(call_args);
}
catch (const std::exception &e)
{
return SmartResponse::createError(req_code, req_cmd, 3001,
std::string("执行错误: ") + e.what());
}
// 8. 构建响应
auto response = SmartResponse::createSuccess(req_code, req_cmd, result);
// 9. 添加执行信息
response.execution_info["matched_params"] = std::to_string(matched_params.size());
response.execution_info["function"] = func_info->name;
// 10. 计算执行时间
auto end_time = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
end_time - start_time);
response.execution_time = duration.count() / 1000.0;
return response;
}
catch (const std::exception &e)
{
return SmartResponse::createError("ERROR", "unknown", 5001,
std::string("处理异常: ") + e.what());
}
}
std::map<std::string, std::shared_ptr<FunctionInfo>>
SmartJsonProcessor::getAvailableFunctions() const
{
auto &registry = FunctionRegistry::instance();
return registry.getAllFunctions();
}
std::string SmartJsonProcessor::getFunctionInfo(const std::string &func_name) const
{
auto &registry = FunctionRegistry::instance();
auto func_info = registry.getFunction(func_name);
if (!func_info)
{
return "函数未找到: " + func_name;
}
std::stringstream ss;
ss << "函数: " << func_info->name << "\n";
ss << "描述: " << func_info->description << "\n";
ss << "参数:\n";
for (const auto &param : func_info->params)
{
ss << " - " << param.name << " (" << param.getTypeName() << ")";
if (param.is_optional)
ss << " [可选]";
if (param.default_value.has_value())
{
ss << " [默认: ";
try
{
if (param.type == ParamType::INT)
ss << param.convert<int>(param.default_value);
else if (param.type == ParamType::FLOAT)
ss << param.convert<float>(param.default_value);
else if (param.type == ParamType::STRING)
ss << param.convert<std::string>(param.default_value);
}
catch (...)
{
ss << "unknown";
}
ss << "]";
}
ss << "\n";
}
return ss.str();
}
// ========== WASM 导出函数 ==========
static SmartJsonProcessor *g_smart_processor = nullptr;
// 信号处理
static KinematicsWebAPI *global_server = nullptr;
EMSCRIPTEN_KEEPALIVE
const char *init_func()
{
try
{
if (!global_server)
{
global_server = new KinematicsWebAPI();
}
if (!global_server)
{
auto error = SmartResponse::createError("ERROR", "unknown", 1001, "init_func 请求数据为空");
return createWasmString(error.toJson());
}
auto response = SmartResponse::createSuccess("req_code", "init_func");
return createWasmString(response.toJson());
}
catch (const std::exception &e)
{
auto error = SmartResponse::createError("ERROR", "unknown", 5001,
std::string("处理异常: ") + e.what());
return createWasmString(error.toJson());
}
}
EMSCRIPTEN_KEEPALIVE
const char *func(const char *json_request)
{
if (!global_server)
{
// 注意:这里需要动态分配,否则作用域结束会被销毁
global_server = new KinematicsWebAPI();
}
try
{
if (!json_request)
{
auto error = SmartResponse::createError("ERROR", "unknown", 1001, "请求数据为空");
return createWasmString(error.toJson());
}
std::string request_str(json_request);
std::string response_str = global_server->func(request_str);
return createWasmString(response_str);
}
catch (const std::exception &e)
{
auto error = SmartResponse::createError("ERROR", "unknown", 5001,
std::string("处理异常: ") + e.what());
return createWasmString(error.toJson());
}
}
EMSCRIPTEN_KEEPALIVE
const char *smart_process_json(const char *json_request)
{
if (!g_smart_processor)
{
g_smart_processor = new SmartJsonProcessor();
}
try
{
if (!json_request)
{
auto error = SmartResponse::createError("ERROR", "unknown", 1001, "请求数据为空");
return createWasmString(error.toJson());
}
std::string request_str(json_request);
auto response = g_smart_processor->processRequest(request_str);
return createWasmString(response.toJson());
}
catch (const std::exception &e)
{
auto error = SmartResponse::createError("ERROR", "unknown", 5001,
std::string("处理异常: ") + e.what());
return createWasmString(error.toJson());
}
}
EMSCRIPTEN_KEEPALIVE
const char *smart_get_function_list()
{
if (!g_smart_processor)
{
g_smart_processor = new SmartJsonProcessor();
}
try
{
auto functions = g_smart_processor->getAvailableFunctions();
std::stringstream ss;
ss << "[";
bool first = true;
for (const auto &[name, func_info] : functions)
{
if (!first)
ss << ",";
ss << "{";
ss << "\"name\":\"" << name << "\",";
ss << "\"description\":\"" << func_info->description << "\",";
ss << "\"params\":[";
bool first_param = true;
for (const auto &param : func_info->params)
{
if (!first_param)
ss << ",";
ss << "{";
ss << "\"name\":\"" << param.name << "\",";
ss << "\"type\":\"" << param.getTypeName() << "\",";
ss << "\"optional\":" << (param.is_optional ? "true" : "false");
ss << "}";
first_param = false;
}
ss << "]";
ss << "}";
first = false;
}
ss << "]";
std::string result_str = ss.str();
return createWasmString(result_str);
}
catch (const std::exception &e)
{
std::string error = "{\"error\":\"" + std::string(e.what()) + "\"}";
return createWasmString(error);
}
}
EMSCRIPTEN_KEEPALIVE
const char *smart_get_function_info(const char *func_name)
{
if (!g_smart_processor)
{
g_smart_processor = new SmartJsonProcessor();
}
try
{
if (!func_name)
{
std::string error = "{\"error\":\"函数名不能为空\"}";
return createWasmString(error);
}
std::string info = g_smart_processor->getFunctionInfo(func_name);
return createWasmString(info);
}
catch (const std::exception &e)
{
std::string error = "{\"error\":\"" + std::string(e.what()) + "\"}";
return createWasmString(error);
}
}
EMSCRIPTEN_KEEPALIVE
const char *smart_test_match(const char *json_request)
{
if (!g_smart_processor)
{
g_smart_processor = new SmartJsonProcessor();
}
try
{
if (!json_request)
{
auto error = SmartResponse::createError("TEST", "test", 1001, "请求数据为空");
return createWasmString(error.toJson());
}
// 演示智能匹配过程
std::string request_str(json_request);
// 解析请求
std::regex cmd_regex("\"req_cmd\"\\s*:\\s*\"([^\"]+)\"");
std::smatch match;
std::string req_cmd = "unknown";
if (std::regex_search(request_str, match, cmd_regex))
{
req_cmd = match[1].str();
}
auto &registry = FunctionRegistry::instance();
auto func_info = registry.getFunction(req_cmd);
if (!func_info)
{
auto error = SmartResponse::createError("TEST", req_cmd, 1001,
"未找到函数: " + req_cmd);
error.execution_info["test_type"] = "function_not_found";
return createWasmString(error.toJson());
}
// 解析参数
SmartJsonProcessor processor;
auto input_params = processor.parseJsonParams(request_str);
// 智能匹配
auto matched_params = registry.smartMatchParams(func_info, input_params);
// 显示匹配结果
std::stringstream ss;
ss << "{\"test\":\"smart_match\",";
ss << "\"function\":\"" << func_info->name << "\",";
ss << "\"description\":\"" << func_info->description << "\",";
ss << "\"input_params\":[";
bool first = true;
for (const auto &[key, value] : input_params)
{
if (!first)
ss << ",";
ss << "{\"key\":\"" << key << "\",";
ss << "\"type\":\"" << static_cast<int>(registry.deduceParamType(value)) << "\"}";
first = false;
}
ss << "],";
ss << "\"matched_params\":[";
first = true;
for (const auto &[key, value] : matched_params)
{
if (!first)
ss << ",";
ss << "{\"key\":\"" << key << "\",";
ss << "\"type\":\"" << static_cast<int>(registry.deduceParamType(value)) << "\"}";
first = false;
}
ss << "]";
ss << "}";
std::string result_str = ss.str();
return createWasmString(result_str);
}
catch (const std::exception &e)
{
std::string error = "{\"error\":\"" + std::string(e.what()) + "\"}";
return createWasmString(error);
}
}
EMSCRIPTEN_KEEPALIVE
const char *smart_get_version()
{
std::string version = "{\"version\":\"1.0.0\",\"name\":\"Smart WASM JSON API\"}";
return createWasmString(version);
}
EMSCRIPTEN_KEEPALIVE
void smart_free_string(const char *str)
{
freeWasmString(str);
}
// 导出额外的辅助函数
EMSCRIPTEN_KEEPALIVE
void *wasm_malloc(size_t size)
{
return malloc(size);
}
EMSCRIPTEN_KEEPALIVE
void wasm_free(void *ptr)
{
if (ptr)
{
free(ptr);
}
}