缺省
2025-07-09
支持字符串、换行符字符串、十六进制格式发送
在ws客户端 和 串口助手 上使用, 步骤(协议->下拉->配置->上传->选中目标JS文件)
/**
* @param {string} str 编辑的字符串
* @return {Uint8Array} 序列化后的数组
*/
function serialize(str) {
// 检查是否为十六进制格式 [xx xx xx]
if (str.match(/^\[([\da-fA-F]{2}\s*)+\]$/)) {
// 移除[]并分割成数组
const hexValues = str.slice(1, -1).trim().split(/\s+/);
// 转换为Uint8Array
return new Uint8Array(hexValues.map(hex => parseInt(hex, 16)));
}
// 普通字符串处理
str = str.replace(/\\r/g, '\r')
.replace(/\\n/g, '\n')
.replace(/\\t/g, '\t')
.replace(/\\f/g, '\f')
.replace(/\\b/g, '\b')
.replace(/\\v/g, '\v');
// 使用TextEncoder编码字符串
const data = new TextEncoder('gbk').encode(str);
return data;
}
/**
* @param {Uint8Array} array 接收缓冲区数组
* @return {number} 缓冲区数组中,能正确解析完整一包的长度
*/
function deserialize(array) {
//检索协议\n的结束标识
let len = array.findIndex(item => item == 10);
len += len >= 0 ? 1 : 0;
return len > 0 ? len : array.length;
}
/**
* @param {Uint8Array} array 通过接收序列化的长度提取的完整一包数据
* @return {string} 解析后的字符串
*/
function log(array, str) {
let log = '';
console.log(array);
// 创建一个新的Uint8Array来存储数据
const data = new Uint8Array(array.slice(0, array.length + 1));
try {
// 使用TextDecoder解码Uint8Array
log = new TextDecoder().decode(data);
} catch (error) {
console.error('解码错误:', error);
log = '';
}
if(str === '')
return log;
try {
let regex = new RegExp(str);
return regex.test(log)? log: '';
} catch (error) {
return log
}
}
async function custom1(transfer) {
transfer("hello1");
await new Promise(resolve => setTimeout(resolve, 1000));
transfer("hi1\r\n");
}
async function custom2(transfer) {
transfer("hello2");
await new Promise(resolve => setTimeout(resolve, 1000));
transfer("hi2\r\n");
}
async function custom3() {
alert('一个简短的介绍')
}
/**
* @return {Array} 预设按键数组
*/
function customJson() {
//json格式示例
// {
// "name": "按键名称",
// "title": "悬停时的提示信息",
// "str": "待序列化的发送字符串"
// "fun": "自定义函数"
// }
return [
{ name: "发送hello", str:"hello\\r\\n", title:"字符串示例" },
{ name: "发送hi", str:"hi\\r\\n", title:"换行符字符串示例" },
{ name: "发送hex", str:"[30 31 32]", title:"十六进制示例" },
{ name: "自定义发送1", fun:"custom1" },
{ name: "自定义发送2", fun:"custom2" },
{ name: "自定义介绍", fun: "custom3" },
];
}