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artthings-mqtt-bridge@3.0.0/server.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.37.0.\n * Original file: /npm/smartthings-mqtt-bridge@3.0.0/server.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","/*jslint node: true */\n'use strict';\n\nvar winston = require('winston'),\n    express = require('express'),\n    expressJoi = require('express-joi-validator'),\n    expressWinston = require('express-winston'),\n    bodyparser = require('body-parser'),\n    mqtt = require('mqtt'),\n    async = require('async'),\n    path = require('path'),\n    url = require('url'),\n    joi = require('joi'),\n    yaml = require('js-yaml'),\n    jsonfile = require('jsonfile'),\n    fs = require('fs'),\n    semver = require('semver'),\n    request = require('request');\n\nvar CONFIG_DIR = process.env.CONFIG_DIR || process.cwd(),\n    CONFIG_FILE = path.join(CONFIG_DIR, 'config.yml'),\n    SAMPLE_FILE = path.join(__dirname, '_config.yml'),\n    STATE_FILE = path.join(CONFIG_DIR, 'state.json'),\n    EVENTS_LOG = path.join(CONFIG_DIR, 'events.log'),\n    ACCESS_LOG = path.join(CONFIG_DIR, 'access.log'),\n    ERROR_LOG = path.join(CONFIG_DIR, 'error.log'),\n    CURRENT_VERSION = require('./package').version,\n    // The topic type to get state changes from smartthings\n    TOPIC_READ_STATE = 'state',\n    SUFFIX_READ_STATE = 'state_read_suffix',\n    // The topic type to send commands to smartthings\n    TOPIC_COMMAND = 'command',\n    SUFFIX_COMMAND = 'command_suffix',\n    // The topic type to send state changes to smartthings\n    TOPIC_WRITE_STATE = 'set_state',\n    SUFFIX_WRITE_STATE = 'state_write_suffix',\n    RETAIN = 'retain';\n\nvar app = express(),\n    client,\n    subscriptions = [],\n    callback = '',\n    config = {},\n    history = {};\n\n// Write all events to disk as well\nwinston.add(winston.transports.File, {\n    filename: EVENTS_LOG,\n    json: false\n});\n\n/**\n * Load user configuration (or create it)\n * @method loadConfiguration\n * @return {Object} Configuration\n */\nfunction loadConfiguration () {\n    if (!fs.existsSync(CONFIG_FILE)) {\n        winston.info('No previous configuration found, creating one');\n        fs.writeFileSync(CONFIG_FILE, fs.readFileSync(SAMPLE_FILE));\n    }\n\n    return yaml.safeLoad(fs.readFileSync(CONFIG_FILE));\n}\n\n/**\n * Load the saved previous state from disk\n * @method loadSavedState\n * @return {Object} Configuration\n */\nfunction loadSavedState () {\n    var output;\n    try {\n        output = jsonfile.readFileSync(STATE_FILE);\n    } catch (ex) {\n        winston.info('No previous state found, continuing');\n        output = {\n            subscriptions: [],\n            callback: '',\n            history: {},\n            version: '0.0.0'\n        };\n    }\n    return output;\n}\n\n/**\n * Resubscribe on a periodic basis\n * @method saveState\n */\nfunction saveState () {\n    winston.info('Saving current state');\n    jsonfile.writeFileSync(STATE_FILE, {\n        subscriptions: subscriptions,\n        callback: callback,\n        history: history,\n        version: CURRENT_VERSION\n    }, {\n        spaces: 4\n    });\n}\n\n/**\n * Migrate the configuration from the current version to the latest version\n * @method migrateState\n * @param  {String}     version Version the state was written in before\n */\nfunction migrateState (version) {\n    // Make sure the object exists\n    if (!config.mqtt) {\n        config.mqtt = {};\n    }\n\n    // This is the previous default, but it's totally wrong\n    if (!config.mqtt.preface) {\n        config.mqtt.preface = '/smartthings';\n    }\n\n    // Default Suffixes\n    if (!config.mqtt[SUFFIX_READ_STATE]) {\n        config.mqtt[SUFFIX_READ_STATE] = '';\n    }\n    if (!config.mqtt[SUFFIX_COMMAND]) {\n        config.mqtt[SUFFIX_COMMAND] = '';\n    }\n    if (!config.mqtt[SUFFIX_WRITE_STATE]) {\n        config.mqtt[SUFFIX_WRITE_STATE] = '';\n    }\n\n    // Default retain\n    if (config.mqtt[RETAIN] !== false) {\n        config.mqtt[RETAIN] = true;\n    }\n\n    // Default port\n    if (!config.port) {\n        config.port = 8080;\n    }\n\n    // Default protocol\n    if (!url.parse(config.mqtt.host).protocol) {\n        config.mqtt.host = 'mqtt://' + config.mqtt.host;\n    }\n\n    // Stuff was previously in subscription.json, load that and migrate it\n    var SUBSCRIPTION_FILE = path.join(CONFIG_DIR, 'subscription.json');\n    if (semver.lt(version, '1.1.0') && fs.existsSync(SUBSCRIPTION_FILE)) {\n        var oldState = jsonfile.readFileSync(SUBSCRIPTION_FILE);\n        callback = oldState.callback;\n        subscriptions = oldState.topics;\n    }\n\n    saveState();\n}\n\n/**\n * Handle Device Change/Push event from SmartThings\n *\n * @method handlePushEvent\n * @param  {Request} req\n * @param  {Object}  req.body\n * @param  {String}  req.body.name  Device Name (e.g. \"Bedroom Light\")\n * @param  {String}  req.body.type  Device Property (e.g. \"state\")\n * @param  {String}  req.body.value Value of device (e.g. \"on\")\n * @param  {Result}  res            Result Object\n */\nfunction handlePushEvent (req, res) {\n    var topic = getTopicFor(req.body.name, req.body.type, TOPIC_READ_STATE),\n        value = req.body.value;\n\n    winston.info('Incoming message from SmartThings: %s = %s', topic, value);\n    history[topic] = value;\n\n    client.publish(topic, value, {\n        retain: config.mqtt[RETAIN]\n    }, function () {\n        res.send({\n            status: 'OK'\n        });\n    });\n}\n\n/**\n * Handle Subscribe event from SmartThings\n *\n * @method handleSubscribeEvent\n * @param  {Request} req\n * @param  {Object}  req.body\n * @param  {Object}  req.body.devices  List of properties => device names\n * @param  {String}  req.body.callback Host and port for SmartThings Hub\n * @param  {Result}  res               Result Object\n */\nfunction handleSubscribeEvent (req, res) {\n    // Subscribe to all events\n    subscriptions = [];\n    Object.keys(req.body.devices).forEach(function (property) {\n        req.body.devices[property].forEach(function (device) {\n            subscriptions.push(getTopicFor(device, property, TOPIC_COMMAND));\n            subscriptions.push(getTopicFor(device, property, TOPIC_WRITE_STATE));\n        });\n    });\n\n    // Store callback\n    callback = req.body.callback;\n\n    // Store current state on disk\n    saveState();\n\n    // Subscribe to events\n    winston.info('Subscribing to ' + subscriptions.join(', '));\n    client.subscribe(subscriptions, function () {\n        res.send({\n            status: 'OK'\n        });\n    });\n}\n\n\n/**\n * Get the topic name for a given item\n * @method getTopicFor\n * @param  {String}    device   Device Name\n * @param  {String}    property Property\n * @param  {String}    type     Type of topic (command or state)\n * @return {String}             MQTT Topic name\n */\nfunction getTopicFor (device, property, type) {\n    var tree = [config.mqtt.preface, device, property],\n        suffix;\n\n    if (type === TOPIC_COMMAND) {\n        suffix = config.mqtt[SUFFIX_COMMAND];\n    } else if (type === TOPIC_READ_STATE) {\n        suffix = config.mqtt[SUFFIX_READ_STATE];\n    } else if (type === TOPIC_WRITE_STATE) {\n        suffix = config.mqtt[SUFFIX_WRITE_STATE];\n    }\n\n    if (suffix) {\n        tree.push(suffix);\n    }\n\n    return tree.join('/');\n}\n\n/**\n * Parse incoming message from MQTT\n * @method parseMQTTMessage\n * @param  {String} topic   Topic channel the event came from\n * @param  {String} message Contents of the event\n */\nfunction parseMQTTMessage (topic, message) {\n    var contents = message.toString();\n    winston.info('Incoming message from MQTT: %s = %s', topic, contents);\n\n    // Remove the preface from the topic before splitting it\n    var pieces = topic.substr(config.mqtt.preface.length + 1).split('/'),\n        device = pieces[0],\n        property = pieces[1],\n        topicReadState = getTopicFor(device, property, TOPIC_READ_STATE),\n        topicWriteState = getTopicFor(device, property, TOPIC_WRITE_STATE),\n        topicSwitchState = getTopicFor(device, 'switch', TOPIC_READ_STATE),\n        topicLevelCommand = getTopicFor(device, 'level', TOPIC_COMMAND);\n\n    // Deduplicate only if the incoming message topic is the same as the read state topic\n    if (topic === topicReadState) {\n        if (history[topic] === contents) {\n            winston.info('Skipping duplicate message from: %s = %s', topic, contents);\n            return;\n        }\n    }\n    history[topic] = contents;\n\n    // If sending level data and the switch is off, don't send anything\n    // SmartThings will turn the device on (which is confusing)\n    if (property === 'level' && history[topicSwitchState] === 'off') {\n        winston.info('Skipping level set due to device being off');\n        return;\n    }\n\n    // If sending switch data and there is already a nonzero level value, send level instead\n    // SmartThings will turn the device on\n    if (property === 'switch' && contents === 'on' &&\n        history[topicLevelCommand] > 0) {\n        winston.info('Passing level instead of switch on');\n        property = 'level';\n        contents = history[topicLevelCommand];\n    }\n\n    request.post({\n        url: 'http://' + callback,\n        json: {\n            name: device,\n            type: property,\n            value: contents,\n            command: (!pieces[2] || pieces[2] && pieces[2] === config.mqtt[SUFFIX_COMMAND])\n        }\n    }, function (error, resp) {\n        if (error) {\n            // @TODO handle the response from SmartThings\n            winston.error('Error from SmartThings Hub: %s', error.toString());\n            winston.error(JSON.stringify(error, null, 4));\n            winston.error(JSON.stringify(resp, null, 4));\n        }\n    });\n}\n\n// Main flow\nasync.series([\n    function loadFromDisk (next) {\n        var state;\n\n        winston.info('Starting SmartThings MQTT Bridge - v%s', CURRENT_VERSION);\n        winston.info('Loading configuration');\n        config = loadConfiguration();\n\n        winston.info('Loading previous state');\n        state = loadSavedState();\n        callback = state.callback;\n        subscriptions = state.subscriptions;\n        history = state.history;\n\n        winston.info('Perfoming configuration migration');\n        migrateState(state.version);\n\n        process.nextTick(next);\n    },\n    function connectToMQTT (next) {\n        winston.info('Connecting to MQTT at %s', config.mqtt.host);\n\n        client = mqtt.connect(config.mqtt.host, config.mqtt);\n        client.on('message', parseMQTTMessage);\n        client.on('connect', function () {\n            if (subscriptions.length > 0) {\n                client.subscribe(subscriptions);\n            }\n            next();\n            // @TODO Not call this twice if we get disconnected\n            next = function () {};\n        });\n    },\n    function configureCron (next) {\n        winston.info('Configuring autosave');\n\n        // Save current state every 15 minutes\n        setInterval(saveState, 15 * 60 * 1000);\n\n        process.nextTick(next);\n    },\n    function setupApp (next) {\n        winston.info('Configuring API');\n\n        // Accept JSON\n        app.use(bodyparser.json());\n\n        // Log all requests to disk\n        app.use(expressWinston.logger({\n            transports: [\n                new winston.transports.File({\n                    filename: ACCESS_LOG,\n                    json: false\n                })\n            ]\n        }));\n\n        // Push event from SmartThings\n        app.post('/push',\n            expressJoi({\n                body: {\n                    //   \"name\": \"Energy Meter\",\n                    name: joi.string().required(),\n                    //   \"value\": \"873\",\n                    value: joi.string().required(),\n                    //   \"type\": \"power\",\n                    type: joi.string().required()\n                }\n            }), handlePushEvent);\n\n        // Subscribe event from SmartThings\n        app.post('/subscribe',\n            expressJoi({\n                body: {\n                    devices: joi.object().required(),\n                    callback: joi.string().required()\n                }\n            }), handleSubscribeEvent);\n\n        // Log all errors to disk\n        app.use(expressWinston.errorLogger({\n            transports: [\n                new winston.transports.File({\n                    filename: ERROR_LOG,\n                    json: false\n                })\n            ]\n        }));\n\n        // Proper error messages with Joi\n        app.use(function (err, req, res, next) {\n            if (err.isBoom) {\n                return res.status(err.output.statusCode).json(err.output.payload);\n            }\n        });\n\n        app.listen(config.port, next);\n    }\n], function (error) {\n    if (error) {\n        return winston.error(error);\n    }\n    winston.info('Listening at http://localhost:%s', config.port);\n});\n"]}