tplink-bulb-web/index.js
manalejandro 9b08f458aa refactor
2018-07-03 19:09:18 +02:00

60 lines
2.0 KiB
JavaScript

'use strict'
const TPLSmartDevice = require('tplink-lightbulb'),
express = require('express'),
app = express(),
morgan = require('morgan'),
rfs = require('rotating-file-stream'),
colorsys = require('colorsys'),
accessLogStream = rfs('access.log', { interval: '1d', path: __dirname + '/logs' }),
router = express.Router(),
ip = process.argv[3] || '10.0.0.130',
transition = 0,
bulb = new TPLSmartDevice(ip)
app.use(morgan('combined', { stream: accessLogStream }))
.use('/api', router)
.use(express.static(__dirname + '/public'))
.listen(process.argv[2] || 3000)
router.use('/on/:brightness', (req, res, next) => {
bulb.power(true, transition, { brightness: parseInt(req.params.brightness) })
.then(r => res.json(r))
.catch(next)
})
.use('/on', (req, res, next) => {
bulb.power(true, transition, { brightness: 100 })
.then(r => res.json(r))
.catch(next)
})
.use('/off', (req, res, next) => {
bulb.power(false, 0)
.then(r => res.json(r))
.catch(next)
})
.use('/color/hex/:color', (req, res, next) => {
let color = colorsys.hexToHsl(req.params.color)
bulb.power(true, transition, {
hue: color.h,
saturation: color.s,
brightness: color.l,
color_temp: 0
})
.then(r => res.json(r))
.catch(next)
})
.use('/color/chsb/:colortemp/:hue/:saturation/:brightness', (req, res, next) => {
bulb.power(true, transition, {
color_temp: parseInt(req.params.colortemp),
hue: parseInt(req.params.hue),
saturation: parseInt(req.params.saturation),
brightness: parseInt(req.params.brightness)
})
.then(r => res.json(r))
.catch(next)
})
.use('/info', (req, res, next) => {
bulb.info()
.then(r => res.json(r.light_state))
.catch(next)
})