@iot9x.com/ipc-utils
Version:
九星云、九星小程序、九星配置工具所共用的库方法
115 lines (114 loc) • 3.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PackageType = void 0;
const iconv_lite_1 = require("iconv-lite");
var PackageType;
(function (PackageType) {
/** 纯文本 */
PackageType[PackageType["PlainText"] = 1] = "PlainText";
/** 16进制 */
PackageType[PackageType["Hex"] = 2] = "Hex";
/** json */
PackageType[PackageType["JSON"] = 3] = "JSON";
/** base64 */
PackageType[PackageType["Base64"] = 4] = "Base64";
})(PackageType || (exports.PackageType = PackageType = {}));
/**
* 进制转换
* @param encoding 字符集: utf8, gb2312, cesu8...
* @returns { bufferToHex, hexToStr, strToHex, onHexSendChange, decodePackage, encodePackage }
*/
function useConversionUtil(encoding) {
/**
* 规范化编码名称:剥离所有非字母数字字符和附加年份。
* @returns { string }
*/
// const _canonicalizeEncoding = () =>
const _encoding = encoding.toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, '');
/**
* Buffer转HEX字符串
* @param buffer Buffer数据
* @returns { string }
*/
const bufferToHex = (buffer) => {
const array = [];
buffer.forEach((item) => {
array.push(item.toString(16).padStart(2, '0'));
});
return array.join(' ');
};
/**
* hex字符串转dec字符串
* @param str Hex字符串
* @returns { string }
*/
const hexToStr = (hexStr) => {
return (0, iconv_lite_1.decode)(Buffer.from(hexStr
.replaceAll(' ', '')
.match(/\w{2}/g)
.map((item) => parseInt(item, 16))), _encoding);
};
/**
* dec字符串转hex字符串
* @param hex hex字符串
* @param options 配置项
* @returns { string }
*/
const strToHex = (hex, options = {}) => {
const { needSpace } = options;
const buffer = (0, iconv_lite_1.encode)(hex, _encoding);
const array = [];
buffer.forEach((item) => {
array.push(item.toString(16).padStart(2, '0'));
});
return needSpace ? array.join(' ') : array.join('');
};
/**
* 输入框改变
* @param value 输入值
* @param isHex 是否是HEX
* @returns { string }
*/
const onHexSendChange = (value, isHex) => {
if (!value)
return '';
if (isHex)
return strToHex(value);
return hexToStr(value);
};
/**
* 解析带有类型前缀的字符串
* @param str 字符串
* @returns { [packageType, string] }
*/
const decodePackage = (str) => {
if (!str)
return [PackageType.PlainText, ''];
const packageType = parseInt(str.slice(0, 1), 10);
return [packageType, packageType === PackageType.Hex ? str.slice(1) : hexToStr(str.slice(1))];
};
/**
* 组合带有类型前缀的字符串
* @param value 字符串或者对象
* @param type 类型
* @returns { string }
*/
const encodePackage = (value, type = PackageType.PlainText) => {
if (!value)
return '';
if (type === PackageType.Hex)
return type + value.replaceAll(' ', '');
if (type === PackageType.JSON)
return type + strToHex(JSON.stringify(JSON.parse(value)));
return type + strToHex(value);
};
return {
bufferToHex,
hexToStr,
strToHex,
onHexSendChange,
decodePackage,
encodePackage,
};
}
exports.default = useConversionUtil;