ble-server/gdata-characteristic.js

64 lines
1.5 KiB
JavaScript

const bleno = require('bleno')
const config = require('./config.json')
const localEvent = require('./localEvent')
var tmp = []
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 = []
console.log(data[0])
} else if (data.length == 1 && data[0] == 0xff) {
//console.log(tmp)
console.log(Buffer.from(tmp).toString())
localEvent.emit('print', Buffer.from(tmp).toString())
// printString(Buffer.from(tmp).toString())
// if(this._notifyFunc) {
// this._notifyFunc(Buffer.from([0x00,0x01]))
// }
} 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