tplink-bulb-web/index.js

60 lines
2.0 KiB
JavaScript
Raw Permalink Normal View History

2018-07-01 11:57:22 +00:00
'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',
2018-07-03 17:09:18 +00:00
transition = 0,
2018-07-01 11:57:22 +00:00
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) => {
2018-07-03 17:09:18 +00:00
bulb.power(true, transition, { brightness: parseInt(req.params.brightness) })
2018-07-01 11:57:22 +00:00
.then(r => res.json(r))
2018-07-03 17:09:18 +00:00
.catch(next)
2018-07-01 11:57:22 +00:00
})
.use('/on', (req, res, next) => {
2018-07-03 17:09:18 +00:00
bulb.power(true, transition, { brightness: 100 })
2018-07-01 11:57:22 +00:00
.then(r => res.json(r))
2018-07-03 17:09:18 +00:00
.catch(next)
2018-07-01 11:57:22 +00:00
})
.use('/off', (req, res, next) => {
bulb.power(false, 0)
.then(r => res.json(r))
2018-07-03 17:09:18 +00:00
.catch(next)
2018-07-01 11:57:22 +00:00
})
.use('/color/hex/:color', (req, res, next) => {
let color = colorsys.hexToHsl(req.params.color)
2018-07-03 17:09:18 +00:00
bulb.power(true, transition, {
2018-07-01 11:57:22 +00:00
hue: color.h,
saturation: color.s,
brightness: color.l,
color_temp: 0
})
.then(r => res.json(r))
2018-07-03 17:09:18 +00:00
.catch(next)
2018-07-01 11:57:22 +00:00
})
.use('/color/chsb/:colortemp/:hue/:saturation/:brightness', (req, res, next) => {
2018-07-03 17:09:18 +00:00
bulb.power(true, transition, {
2018-07-01 11:57:22 +00:00
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))
2018-07-03 17:09:18 +00:00
.catch(next)
2018-07-01 11:57:22 +00:00
})
.use('/info', (req, res, next) => {
bulb.info()
.then(r => res.json(r.light_state))
2018-07-03 17:09:18 +00:00
.catch(next)
2018-07-01 11:57:22 +00:00
})