ble-server/gdata-characteristic.js

60 lines
1.3 KiB
JavaScript

const bleno = require('bleno')
const config = require('./config.json')
const localEvent = require('./localEvent')
var tmp = []
var idx = 0
const notifyDesciptor = new bleno.Descriptor({
uuid: '8888',
value: 0
})
class DataCharacteristic extends bleno.Characteristic {
constructor() {
super({
uuid: config.uuid.service.func.data,
properties: ['write', 'writeWithoutResponse', 'notify'],
descriptors: [
notifyDesciptor
]
})
this._notifyFunc = null
}
onWriteRequest(data, offset, withoutResponse, callback) {
console.log(`offset :: ${offset} , withoutRes :: ${withoutResponse}`)
console.log(`get data`, data)
if (data.length == 1 && data[0] == 0x00) {
tmp = []
idx = 0
} else if (data.length == 1 && data[0] == 0xff) {
console.log(Buffer.from(tmp).toString())
localEvent.emit('print', Buffer.from(tmp).toString())
} else {
tmp = [...tmp, ...data.slice(2, data.length)]
}
if (!withoutResponse) {
console.log('send response')
callback(this.RESULT_SUCCESS)
}
}
sendNotidy(str) {
if (!this._notifyFunc) return
this._notifyFunc(Buffer.from(str))
}
onSubscribe(maxValueSize, cb) {
console.log(maxValueSize)
this._notifyFunc = cb
}
onUnsubscribe() {
this._notifyFunc = null
}
}
module.exports = DataCharacteristic