3.0.17 • Published 9 months ago

ciot v3.0.17

Weekly downloads
-
License
MIT
Repository
-
Last release
9 months ago

使用方法

一、本地为硬件服务,产品端使用CIoT.js的核心步骤:

1、初始化函数(建立websocket连接)

iot.init(ENTERPRISE_ID, APP_CODE);

2、设置回调事件,如果不设置回调事件,则无法接收事件,需要通过invoke的返回需要的结果。

iot.onEvent((eventName, data) => {
        console.log(`收到事件: ${eventName} 数据: ${data}`);
        switch (eventName) {
            case "OnEventData_Scale":
                data = '{"netWeight":"0.258", "tareWeight":"0.00", "grossWeight":"0.00", "readStatus":"stable"}';
                break;
            case 'OnEventData_AISdk':
                data = '这个里面返回的是ai秤的识别数据';
                break;
            case 'websocketError':
                console.error("Websocket异常错误.");
                showMsg("硬件服务异常错误,请检查硬件服务是否正常运行。");
                break;
            case 'websocketDisconnected':
                console.error("Websocket异常断开.");
                openScale(iot);
                break;
            default:
                console.warn(`未知事件名称: ${eventName}`);
        }
    });

3、连接插件(注:在完整示例中,有验证是否已安装插件,如果没有安装,则安装)

iot.connect({ pluginName: "PriceComputingScale", miniVersion: "1.0.0.1" });

4、调用插件中的方法

await iot.invoke("Read", {});

5、断开插件的连接

await iot.disconnect();

6、释放IoT对象,相当于断开了内部的websocket

iot.unInit();

二、本地为打印插件,产品端使用CIoT.js的核心步骤:

1、初始化函数(建立websocket连接)

iot.init(ENTERPRISE_ID, APP_CODE);

2、设置回调事件,如果不设置回调事件,则无法接收事件,需要通过invoke的返回需要的结果。

iot.onEvent((eventName, data) => {
        console.log(`收到事件: ${eventName} 数据: ${data}`);
    });

3、调用打印插件中的方法

await iot.invoke("PrintView", {});

4、释放IoT对象,相当于断开了内部的websocket

iot.unInit();

三、返回值

iot调用接口返回的值中,采用了错误包装模式,正确的如:

{
    "action": "ActionDemo",
    "clientld": "1dsdfw2edfwef",
    "taskld": "5241235efwef",
    "value": {
        "productld": 156235893,
        "weight": "193.88",
        "tareWeight": "19.99",
        "grossWeight": "1.033"
    }
}

注意value中不一定是对象,也有可能是字符串(为了兼容老的协议返回值),如:

{
    "action": "ActionDemo",
    "clientld": "1dsdfw2edfwef",
    "taskld": "5241235efwef",
    "value": "{\"productld\":156235893,\"weight\":\"193.88\",\"tareWeight\": \"19.99\",\"grossWeight\":\"1.033\"}"
}

错误的如:

{
    "action": "ActionDemo",
    "clientld": "1dsdfw2edfwef",
    "error": {
        "code": 1001,
        "errorCode": "public.print.error.printerror",
        "msg": "内部打印错误。",
        "urlTip": "错误解决方案",
        "url": "https://printapi.chanjet.com/api/err/desc/get?code=1001&errorCode=public.print.error.printerror",
        "taskld": "5241235efef"
    }
}

urlTip为错误提示,如客户点击“错误解决方案”,即可打开url地址。

四、CIoT支持的方法

1. getVersion

获取CIoT的版本,如当前版本为3.0.10,则返回3.0

2. getPrintDownloadUrl

获取打印插件的下载地址。下载

3. getDeviceDownloadUrl

获取硬件服务的下载地址。下载

4. setAddress

设置连接服务端的地址和端口

打印插件:setAddress("localhost", 11588);

打印插件:setAddress("localhost", 4799);

默认的端口为4799

5. init

初始化,参数为企业id和产品的app code |appCode|描述| |:-------- |:-----| |HSY|好生意| |HKJ|好会计| |TPLUS|T+| |POS|新零售| |TC|T+Cloud|

6. onEvent

硬件服务或打印插件的回调事件

7. uninit

断开websocket连接

8. invoke

调用服务端接口的函数方法,可以调用任何开放的接口。

9. connect

连接插件的函数方法(硬件服务有效)

10. disconnect

连接插件的函数方法(硬件服务有效)

五、产品端通过CIoT.js调用硬件服务完整示例代码:

import CIoT from "./dist/CIoT.js";

const ENTERPRISE_ID = process.env.ENTERPRISE_ID || "123456789";
const APP_CODE = process.env.APP_CODE || "POS";

// 初始化IoT实例
async function initIot() {
    const iot = new CIoT();
    try {
        const initResult = await iot.init(ENTERPRISE_ID, APP_CODE);
        if ("error" in initResult) {
            throw new Error(`初始化失败: ${initResult.error.msg}`);
        }
        console.log("初始化结果:", initResult);
        setupEventHandlers(iot);
    } catch (error) {
        console.error("IoT初始化失败:", error);
    }
    return iot;
}

// 设置事件处理器
function setupEventHandlers(iot) {
    iot.onEvent((eventName, data) => {
        console.log(`收到事件: ${eventName} 数据: ${data}`);
        switch (eventName) {
            case "OnEventData_Scale":
                data = '{"netWeight":"0.258", "tareWeight":"0.00", "grossWeight":"0.00", "readStatus":"stable"}';
                break;
            case 'OnEventData_AISdk':
                data = '这个里面返回的是ai秤的识别数据';
                break;
            case 'websocketError':
                console.error("Websocket异常错误.");
                showMsg("硬件服务异常错误,请检查硬件服务是否正常运行。");
                break;
            case 'websocketDisconnected':
                console.error("Websocket异常断开.");
                openScale(iot);
                break;
            default:
                console.warn(`未知事件名称: ${eventName}`);
        }
    });
}

// 确保插件已安装
async function ensurePluginInstalled(iot) {
    try {
        const plugins = await iot.invoke('GetPluginList', {});
        if ("error" in plugins) {
            return plugins; // 直接返回错误结果
        }
        const pluginList = JSON.parse(plugins.value);
        const isPluginInstalled = pluginList.some(plugin => plugin.name === "PriceComputingScale");

        if (!isPluginInstalled) {
            const installResult = await iot.invoke('InstallPlugin', { pluginName: "PriceComputingScale", upgradeType: "zip" });
            if ("error" in installResult) {
                return installResult; // 直接返回错误结果
            }
        }
        return plugins; // 返回插件列表的结果
    } catch (error) {
        console.error("管理插件失败:", error);
        return { error: { msg: error.message } };
    }
}

// 连接插件
async function connectPlugin(iot) {
    try {
        const connectResult = await iot.connect({ pluginName: "PriceComputingScale", miniVersion: "1.0.0.1" });
        if ("error" in connectResult) {
            return connectResult; // 直接返回错误结果
        }
        console.log("连接结果:", connectResult);
        return connectResult; // 返回连接结果
    } catch (error) {
        console.error("连接插件失败:", error);
        return { error: { msg: error.message } };
    }
}

// 打开秤
async function openScale(iot) {
    try {
        const result = await iot.invoke("open", { scaleModel: "aclas.os2", port: "COM4" });
        if ("error" in result) {
            return result; // 直接返回错误结果
        }
        console.log("秤打开成功。");
        return result; // 返回打开秤的结果
    } catch (error) {
        console.error("打开秤失败:", error);
        return { error: { msg: error.message } };
    }
}

// 关闭秤
async function closeScale(iot) {
    try {
        const result = await iot.invoke("close", {});
        if ("error" in result) {
            return result; // 直接返回错误结果
        }
        console.log("秤关闭成功。");
        return result; // 返回关闭秤的结果
    } catch (error) {
        console.error("关闭秤失败:", error);
        return { error: { msg: error.message } };
    }
}

// 主函数
async function main() {
    const iot = await initIot();
    if (!iot) {
        return;
    }

    try {
        const ensurePluginResult = await ensurePluginInstalled(iot);
        if ("error" in ensurePluginResult) {
            console.error("确保插件安装失败:", ensurePluginResult.error.msg);
            return;
        }

        const connectPluginResult = await connectPlugin(iot);
        if ("error" in connectPluginResult) {
            console.error("连接插件失败:", connectPluginResult.error.msg);
            return;
        }

        const openResult = await openScale(iot);
        if ("error" in openResult) {
            console.error("打开秤失败:", openResult.error.msg);
            return;
        }

        const getComsResult = await iot.invoke("GetComs", {});
        if ("error" in getComsResult) {
            console.error(`获取端口失败: ${getComsResult.error.msg}`);
        } else {
            console.log(getComsResult);
        }

        for (let i = 0; i < 1000; i++) {
            const readResult = await iot.invoke("Read", {});
            if ("error" in readResult) {
                console.error(`读取失败: ${readResult.error.msg}`);
            } else {
                console.log(readResult);
            }
        }

        const closeResult = await closeScale(iot);
        if ("error" in closeResult) {
            console.error("关闭秤失败:", closeResult.error.msg);
            return;
        }
    } finally {
        try {
            await iot.disconnect();
        } catch (disconnectError) {
            console.error("断开连接失败:", disconnectError);
        }
        try {
            iot.unInit();
        } catch (unInitError) {
            console.error("反初始化失败:", unInitError);
        }
    }
}

main().catch(console.error);
3.0.13

9 months ago

3.0.16

9 months ago

3.0.17

9 months ago

3.0.15

9 months ago

3.0.9

10 months ago

3.0.12

10 months ago

3.0.3

10 months ago

3.0.10

10 months ago

3.0.2

10 months ago

3.0.11

10 months ago

3.0.8

10 months ago

3.0.7

10 months ago

3.0.6

10 months ago

3.0.5

10 months ago

2.0.26

1 year ago

2.0.24

1 year ago

2.0.25

1 year ago

2.0.22

1 year ago

2.0.21

1 year ago

2.0.19

1 year ago

2.0.20

1 year ago

2.0.18

1 year ago

2.0.17

2 years ago

2.0.15

2 years ago

2.0.3

2 years ago

2.0.16

2 years ago

2.0.13

2 years ago

2.0.5

2 years ago

2.0.11

2 years ago

2.0.7

2 years ago

2.0.12

2 years ago

2.0.9

2 years ago

2.0.10

2 years ago

2.0.8

2 years ago

2.0.2

2 years ago

2.0.1

2 years ago

1.0.2

3 years ago

1.0.3

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago