55 lines
1.5 KiB
JavaScript
55 lines
1.5 KiB
JavaScript
const pSettle = require('p-settle')
|
|
import logger from '@uci-utils/logger'
|
|
let log = logger({package:'@uci/gpio', file:'/src/commands.js'})
|
|
|
|
export default {
|
|
on: async function(packet) {
|
|
packet.pinCmd = 'on'
|
|
this.commands.set(packet)
|
|
return packet
|
|
},
|
|
off: async function(packet) {
|
|
packet.pinCmd = 'off'
|
|
await this.commands.set(packet)
|
|
return packet
|
|
},
|
|
toggle: async function(packet) {
|
|
packet.pinCmd = 'toggle'
|
|
await this.commands.set(packet)
|
|
return packet
|
|
},
|
|
set: async function(packet) {
|
|
packet.pinCmd = packet.pinCmd || 'set'
|
|
let pins = parsePins.call(this, packet.pins || packet.pin)
|
|
packet.res = await pSettle(
|
|
pins.map(pin => {
|
|
return this.pins[pin][packet.pinCmd](packet.value)
|
|
})
|
|
)
|
|
packet = await this.commands.get(packet)
|
|
this.emit('gpios',packet) // emit locally
|
|
this.push(packet) // will push on any socket
|
|
return packet
|
|
},
|
|
|
|
get: async function(packet) {
|
|
let pins = parsePins.call(this,packet.pins || packet.pin)
|
|
packet.pins = {}
|
|
pins.forEach(pin => packet.pins[pin] = this.pins[pin].value)
|
|
packet.cmd = 'status'
|
|
return packet
|
|
}
|
|
}
|
|
|
|
const parsePins = function(pins) {
|
|
if (typeof pins==='number') pins = [pins]
|
|
if (typeof pins==='string') {
|
|
if (pins==='all') pins = Object.keys(this.pins)
|
|
else {
|
|
pins = pins.split(/[,:\s]+/).map(Number).filter( (x) => !Number.isNaN(x))
|
|
}
|
|
}
|
|
// TODO plain object is pin and value pairs
|
|
return pins
|
|
}
|