ble-server/ble/gdata-characteristic.js
2017-09-05 18:36:35 +08:00

72 lines
1.6 KiB
JavaScript

const bleno = require('bleno')
const config = require('./config.json')
const localEvent = require('./localEvent')
var tmp = []
var idx = 0
var failFlag = false
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
failFlag = false
} else if (data.length === 1 && data[0] === 0xff) {
console.log(Buffer.from(tmp).toString())
if (!failFlag) {
localEvent.emit('print', Buffer.from(tmp).toString())
}
} else if (!failFlag) {
let pidx = ((data[0] & 0xff) << 8) + (data[1] & 0xff)
if (idx !== pidx) {
// insert fail method
failFlag = true
this.sendNotidy('fail')
}
idx++
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