{"size": 1831, "ext": "js", "max_stars_repo_path": "config/config.js", "max_stars_repo_name": "shaonianzhentan/node-red-contrib-mqtt-bridge", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "config/config.js", "max_issues_repo_name": "shaonianzhentan/node-red-contrib-mqtt-bridge", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "config/config.js", "max_forks_repo_name": "shaonianzhentan/node-red-contrib-mqtt-bridge", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.1458333333, "max_line_length": 107, "alphanum_fraction": 0.4593118514}
module.exports = function (RED) {
    RED.nodes.registerType('mqtt-config', function (cfg) {
        RED.nodes.createNode(this, cfg);
        const server = RED.nodes.getNode(cfg.server);
        if (server) {
            server.register(this)
            const { clientId } = cfg

            let subscribe_prefix = `nr-mqtt-bridge/${server.broker}/`
            let publish_prefix = `nr-mqtt-bridge/${clientId}`
            if (!clientId) {
                subscribe_prefix = publish_prefix = 'nodered-mqtt-bridge/'
            }

            // 发布
            this.publish = (topic, payload) => {
                // 云端MQTT协议
                const type = Object.prototype.toString.call(payload)
                switch (type) {
                    case '[object Uint8Array]':
                        return server.client.publish(topic, payload)
                    case '[object Object]':
                        payload = JSON.stringify(payload)
                        break;
                    case '[object Number]':
                        payload = String(payload)
                        break;
                }
                // MQTT云
                if (clientId) {
                    server.client.publish(`nr-mqtt-bridge/${clientId}`, JSON.stringify({ topic, payload }))
                } else {
                    server.client.publish(topic, payload)
                }
            }
            // 订阅
            this.subscribe = (topic, callback) => {
                server.subscribe(topic, { qos: 0 }, function (mtopic, mpayload, mpacket) {
                    callback(mpayload)
                })
            }
            // 订阅前缀
            this.subscribe_topic = (topic) => subscribe_prefix + topic
            // 发布前缀
            this.publish_topic = (topic) => publish_prefix + topic
        }
    })
}