57 行
1.4 KiB
JavaScript
57 行
1.4 KiB
JavaScript
var http = require('../../utils/request')
|
|
|
|
Page({
|
|
data: {
|
|
scanning: false,
|
|
deviceId: '',
|
|
error: ''
|
|
},
|
|
|
|
onScan: function () {
|
|
var self = this
|
|
self.setData({ scanning: true, error: '' })
|
|
|
|
wx.scanCode({
|
|
onlyFromCamera: true,
|
|
scanType: ['qrCode'],
|
|
success: function (res) {
|
|
var deviceId = self.parseDeviceId(res.result)
|
|
if (!deviceId) {
|
|
self.setData({ scanning: false, error: '无效的设备二维码' })
|
|
return
|
|
}
|
|
self.bindDevice(deviceId)
|
|
},
|
|
fail: function () {
|
|
self.setData({ scanning: false })
|
|
}
|
|
})
|
|
},
|
|
|
|
parseDeviceId: function (content) {
|
|
if (/^[0-9A-Fa-f]{16}$/.test(content)) return content
|
|
try {
|
|
var url = new URL(content)
|
|
var id = url.searchParams.get('device_id') || url.searchParams.get('id')
|
|
return id || null
|
|
} catch (e) {
|
|
return null
|
|
}
|
|
},
|
|
|
|
bindDevice: function (deviceId) {
|
|
var self = this
|
|
http.post('/api/v1/device/bind', { device_id: deviceId }).then(function (data) {
|
|
self.setData({ scanning: false })
|
|
wx.navigateTo({
|
|
url: '/pages/ble-connect/ble-connect?device_id=' + deviceId + '&bind_token=' + data.bind_token
|
|
})
|
|
}).catch(function (err) {
|
|
self.setData({
|
|
scanning: false,
|
|
error: err.message || '绑定失败'
|
|
})
|
|
})
|
|
}
|
|
})
|