当前位置:网站首页>Wechat applet Bluetooth connects hardware devices and communicates. Applet Bluetooth automatically reconnects due to abnormal distance. JS realizes CRC check bit
Wechat applet Bluetooth connects hardware devices and communicates. Applet Bluetooth automatically reconnects due to abnormal distance. JS realizes CRC check bit
2022-07-07 05:43:00 【Bitter sea 123】
One 、 Small program to search Bluetooth :
Be careful :comtl It's the tool function I encapsulated , Be of no great importance , It may not be used in actual projects :
const comtl = require('../../utils/commontool')
const app = getApp() // Get the globally defined variables , Need to be in app.js in :App({globalData: { params: ''}}),params Is the global variable name
let timerid = 0 // Timer id
Page({
data: {
datas:[], // All Bluetooth data
deviceId:'', // Bluetooth devices id
bluename:'', // Bluetooth devices name
serviceuuid:'', // Select the service of Bluetooth device uuid Intercepting string
serviceId:'', // service id ,uuid
characteristicNotifyId:'', // Read the characteristic value of the data id
characteristicWriteId:'', // Write the characteristic value of data id
timerStat:true
},
searchDevice: function() {
// Bluetooth initialization
clearInterval(timerid)
wx.vibrateShort()
let _this = this
let arr = []
this.setData({
datas:arr
})
wx.openBluetoothAdapter({
success: function(res) {
_this.getBluetoothState()
},
fail: function(res) {
comtl.toast(' Bluetooth initialization failed ','error',2000)
}
})
},
getBluetoothState: function() {
// Get the status of the local Bluetooth adapter
let _this = this
wx.getBluetoothAdapterState({
success: function(res) {
_this.findBleDevices()
},
fail: function(e) {
comtl.toast(' Failed to get the status of the local Bluetooth adapter ','error',2000)
}
})
},
findBleDevices: function() {
// Search Bluetooth
comtl.openloading(' Search Bluetooth ...',false)
let _this = this
wx.startBluetoothDevicesDiscovery({
success: function(res) {
_this.onBluetoothDeviceFound()
},
fail: function(res) {
comtl.toast(' Bluetooth search failed ','error',2000)
}
})
},
onBluetoothDeviceFound: function() {
// Listen for events when a new device is found
let _this = this
wx.onBluetoothDeviceFound(function(res) {
_this.getBluetoothDevices()
})
},
getBluetoothDevices: function() {
let _this = this
wx.getBluetoothDevices({
// Get all Bluetooth devices searched during the Bluetooth module takes effect , Including devices already connected to the machine
success: function(res) {
_this.setData({
datas:res.devices
})
},
fail: function(res) {
comtl.toast(' Failed to get Bluetooth device ','error',2000)
}
})
},
clickBlueToolHandle: function(e) {
wx.vibrateShort()
let _this = this
wx.closeBLEConnection({
// Disconnect the Bluetooth low-power device
deviceId:_this.data.deviceId
})
wx.stopBluetoothDevicesDiscovery() // Stop searching for nearby Bluetooth peripherals
if(e){
let deviceId = e.currentTarget.dataset.deid;
let bluename = e.currentTarget.dataset.bluename;
let serviceuuid = e.currentTarget.dataset.serviceuuid;
this.setData({
deviceId:deviceId,
bluename:bluename,
serviceuuid:serviceuuid
})
}
// Bluetooth connectivity
wx.createBLEConnection({
// Connect to Bluetooth low-power devices
deviceId: _this.data.deviceId,
timeout:5000,
success: function(res) {
clearInterval(timerid)
_this.stopBluetooth() // stop searching
_this.monitorIsBreak();
_this.getBLEDeviceServices(); // Access to services
},
fail: function(res) {
wx.hideLoading()
comtl.toast(' Failed to connect low-power Bluetooth ','error',2000)
},
complete: function (){
comtl.toast(' I won't support it ','error',2000)
}
})
},
monitorIsBreak(){
// Abnormal disconnection of monitoring
let _this = this
wx.onBLEConnectionStateChange(function(res) {
if(!res.connected) {
// Judge whether it is disconnected
_this.timerConnect()// Turn on timer
wx.vibrateLong()
comtl.toast(' Bluetooth is disconnected ','error',5000)
_this.setData({
timerStat:false
})
}else{
_this.setData({
timerStat:true
})
}
})
},
stopBluetooth() {
// Stop Bluetooth search
wx.stopBluetoothDevicesDiscovery({
success: function(res) {
comtl.closeloading() // Turn off stop searching occlusion
comtl.toast(' Stop Bluetooth search ','success',2000)
},
fail: function(res) {
comtl.toast(' Failed to stop Bluetooth search ','error',2000)
}
})
},
getBLEDeviceServices: function() {
// Get all services of Bluetooth low-power devices uuid
let services = [];
let _this = this;
wx.getBLEDeviceServices({
deviceId: _this.data.deviceId,
success: function(res) {
services = res.services
if (services.length <= 0) {
comtl.toast(' No service ','error',2000)
return
}
// Cycle to get serviceId
for (let x in services) {
//x = index
if (services[x].uuid.indexOf(_this.data.serviceuuid) >= 0) {
// Find effective UUID
_this.setData({
serviceId:services[x].uuid
})
_this.getBLEDeviceCharacteristics()
break
}
}
},
fail: function(res) {
comtl.toast(' Failed to get device service ','error',2000)
}
})
},
getBLEDeviceCharacteristics: function() {
// Get all the features in a service of Bluetooth low-power device
let charactArray = [];
let _this = this;
wx.getBLEDeviceCharacteristics({
deviceId: this.data.deviceId,
serviceId: this.data.serviceId, // This is the one above UUID
success: function(res) {
charactArray = res.characteristics;
if (charactArray.length <= 0) {
comtl.toast(' Failed to get characteristic value ','error',2000)
return
}
//charactArray That is to say res.characteristics There is one that can read data Can write data Use them separately
for (var x in charactArray) {
// Writing data
if (charactArray[x].properties.write) {
_this.setData({
characteristicWriteId:charactArray[x].uuid
})
}
// Reading data
if (charactArray[x].properties.notify) {
_this.setData({
characteristicNotifyId:charactArray[x].uuid
})
}
}
app.params = _this.data
wx.switchTab({
url: '../home/home'
})
},
fail: function(res) {
comtl.toast(' Bluetooth does not support ','error',2000)
}
})
},
onShareAppMessage: function(res) {
return {
title: 'F3000X',
path: 'pages/searchbuletool/searchbuletool',
success: function(res) {
}
}
},
onShow(){
clearInterval(timerid)
},
timerConnect(){
// The timer automatically reconnects ( Disconnect and reconnect due to distance )
let _this = this
if (_this.data.timerStat) {
timerid = setInterval(()=>{
_this.clickBlueToolHandle()
},5000)
}
}
})
Two 、 Connect a Bluetooth device
take datas:[] Bluetooth data in traversal rendering to a wxml On the page , Click the data of a device to connect , It should be noted that , Your own applet needs to support a Bluetooth device , Otherwise, even if connected to Bluetooth, the device cannot be operated , Such as :
const comtl = require('../../utils/commontool')
const app = getApp()
let dataString = ''
Page({
data: {
datas:[], // All Bluetooth data
deviceId:'', // Bluetooth devices id
bluename:'', // Bluetooth devices name
serviceuuid:'', // Select the service of Bluetooth device uuid Intercepting string
serviceId:'', // service id ,uuid
characteristicNotifyId:'', // Read the characteristic value of the data id
characteristicWriteId:'', // Write the characteristic value of data id
domdatas:{
}, // Page numeric data
domunit:{
}, // Page unit data
transdat:'', // Converted value
transdat1:'', // Converted value
transdat2:'', // Converted value
timerId:0, // Timer id
isGoRest:false
},
onLoad() {
let isExist = wx.getStorageSync('history')
if(isExist === '' || isExist === undefined){
wx.setStorageSync('history',[])
}
},
redatat: function(dt) {
// Start reading data
if(dt.BtchFlowCount){
this.setData({
domdatas:dt,
transdat: this.filter(this.data.domdatas.ReadyConst,this.data.domunit.dotted),
transdat1: this.filter(this.data.domdatas.MinutFlowCount,this.data.domunit.dotted),
transdat2: this.filter(this.data.domdatas.BtchFlowCount,this.data.domunit.dotted)
})
}else if(dt.dotted){
this.setData({
domunit:dt
})
}
let _this = this
wx.notifyBLECharacteristicValueChange({
deviceId: this.data.deviceId,
serviceId: this.data.serviceId,
characteristicId: this.data.characteristicNotifyId,
state: true,
success: function(res) {
_this.onBLECharacteristicValueChange();
}
})
dataString = ''
},
onBLECharacteristicValueChange: function() {
// Monitor Bluetooth eigenvalue changes
wx.onBLECharacteristicValueChange(function(res) {
dataString += comtl.ab2hex(res.value)
})
},
writedata: function(hex) {
// Writing data
wx.writeBLECharacteristicValue({
deviceId: this.data.deviceId,
serviceId: this.data.serviceId,
characteristicId: this.data.characteristicWriteId,
value: comtl.str2ab(hex),
success: function(res) {
},
fail: function(res) {
}
})
},
startTimer(){
// Get data regularly :
let ids = setInterval(()=>{
this.readUnit()
},100)
setTimeout(()=>{
clearInterval(ids)
},800)
let timerid = setInterval(()=>{
this.readData()
},1000)
this.setData({
timerId:timerid
})
},
readData(){
// Read numerical data :
let domdat = comtl.transformData(dataString)
this.redatat(domdat)
this.writedata('01030001001E9402')
},
readUnit(){
// Reading units :
let domdat = comtl.transformUnit(dataString)
this.redatat(domdat)
this.writedata('01035003000624C8')
},
starttap(){
wx.vibrateShort()
this.writedata('011020070001020014862A')
setTimeout(()=>{
if(this.data.domdatas.OperatStat == ' Running '){
comtl.toast(' The successful running ','success',200)
}
},1000)
this.setData({
isGoRest:false
})
},
stoptap(){
wx.vibrateShort()
this.writedata('01102007000102001547EA')
setTimeout(()=>{
if(this.data.domdatas.OperatStat == ' Pause '){
comtl.toast(' Pause succeeded ','success',2000)
}
},1000)
this.setData({
isGoRest:false
})
},
resettap(){
wx.vibrateShort()
this.writedata('01102007000102001E062D')
setTimeout(()=>{
if(this.data.domdatas.OperatStat == ' end '){
comtl.toast(' End successfully ','success',2000)
}
},1000)
this.setData({
isGoRest:true
})
},
gosetvaluepage() {
// Jump to the modify quantitative value page
wx.vibrateShort()
if (this.data.isGoRest) {
wx.navigateTo({
url: '../setvalue/setvalue?showvalue='+this.data.transdat+'&dotte='+this.data.domunit.dotted
})
}else{
comtl.toast(' Please finish first ','error',2000)
}
},
filter(num,d){
// Handle decimal points
let nums = num + ''
let ds = Number(d)
let indexdot = nums.indexOf('.')
if(indexdot == -1){
nums += '.000000000'
indexdot = nums.indexOf('.')
}else{
nums += '000000000'
}
let lastnum = parseInt(nums.slice((indexdot + ds +1),(indexdot + ds + 2)))
let secondlast = parseInt(nums.slice((indexdot + ds),(indexdot + ds + 1)))
if (!secondlast && secondlast != 0){
return nums.slice(0,indexdot)
}else {
if (lastnum >= 5){
return nums.slice(0,(indexdot + ds)) + (secondlast + 1)
} else {
return nums.slice(0,indexdot + ds +1)
}
}
},
onShow(){
if (app.params) {
this.setData({
deviceId:app.params.deviceId,
bluename:app.params.bluename,
serviceuuid:app.params.serviceuuid,
serviceId:app.params.serviceId,
characteristicNotifyId:app.params.characteristicNotifyId,
characteristicWriteId:app.params.characteristicWriteId
})
}
this.startTimer()
},
onHide(){
clearInterval(this.data.timerId)
}
})
3、 ... and 、 Data reading and writing
Bluetooth reads and writes data and tcp And so on , You need to send something to the device first ( service ), The applet is called subscription , Every time you read and write data, you need to send instructions , The instruction may also include the calculation of check bits, etc , Don't understand can baidu , I don't explain it too much here , as follows :
const app = getApp()
const crc = require('../../utils/crc.js')
const comtl = require('../../utils/commontool')
Page({
data: {
keybordshow:true,
showvalue:'',
inputvale:'',
deviceId:'',
bluename:'',
serviceuuid:'',
serviceId:'',
characteristicNotifyId:'',
characteristicWriteId:'',
dotte:'',
historys:[]
},
onLoad(options) {
let history = wx.getStorageSync('history')
this.setData({
historys:history,
showvalue:options.showvalue,
dotte:options.dotte
})
if (app.params) {
this.setData({
deviceId:app.params.deviceId,
bluename:app.params.bluename,
serviceuuid:app.params.serviceuuid,
serviceId:app.params.serviceId,
characteristicNotifyId:app.params.characteristicNotifyId,
characteristicWriteId:app.params.characteristicWriteId
})
}
},
transforminputvalue(num,d){
let e = Number(num)
switch(d){
case '0':
e = e*1 + '';
break;
case '1':
e = e*10 + '';
break;
case '2':
e = e*100 + '';
break;
case '3':
e = e*1000 + '';
break;
default:
e = e + '';
break;
}
let nd = e.indexOf('.')
if (nd >=0){
let str = e.slice(0,e.indexOf('.'))
return parseInt(str)
} else {
return e
}
},
inputChangeHalder(e){
this.setData({
inputvale:e.detail.value
})
},
writein(){
wx.vibrateShort()
let _this = this
this.setData({
keybordshow:true,
})
wx.writeBLECharacteristicValue({
deviceId: this.data.deviceId,
serviceId: this.data.serviceId,
characteristicId: this.data.characteristicWriteId,
value: crc(_this.transforminputvalue(_this.data.inputvale,_this.data.dotte),'01102005000204'),
success: function(res) {
comtl.toast(' success ','success',2000)
let newhistarr = _this.data.historys.concat(_this.data.inputvale)
newhistarr = [...new Set(newhistarr.map(it => it))]
if(newhistarr.length >= 8){
newhistarr = newhistarr.splice(1, 9)
}
wx.setStorageSync('history',newhistarr)
_this.setData({
historys:newhistarr
})
console.log(_this.data.historys)
wx.switchTab({
url: '../home/home'
})
},
fail: function(res) {
console.log(" Sending instructions failed :")
}
})
},
gobackhome(){
wx.vibrateShort()
wx.switchTab({
url: '../home/home'
})
},
restInputvalue(el){
wx.vibrateShort()
var newvalue = el.currentTarget.dataset.newvalue;
this.setData({
inputvale:newvalue
})
}
})
Calculate check bits :
// crc Check output :
module.exports = (inputNumber,joinTempStr)=>{
// let inputNumber = 0103011215, The value to enter :( The values that need to be converted )
// let joinTempStr = 011001030002, The value that needs to be spliced
// Convert the user input characters to : Single-precision floating-point :
let flownum = parseFloat(inputNumber)
// Floating point rotation 16 Base number :
let hexstr = flownum.toString(16)
let count = 8 - hexstr.length
if (count > 0) {
let zeronum = ''
for(let i = 0;i < count;i++){
zeronum += '0'
}
hexstr = zeronum + hexstr
}
// Splicing :
let temphex = joinTempStr + hexstr
// count crc Check bit method :
function returnCRC(parapms){
var CRC = {
};
CRC._auchCRCHi = [
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
];
CRC._auchCRCLo = [
0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
0x43, 0x83, 0x41, 0x81, 0x80, 0x40
];
CRC.CRC16 = function (buffer) {
var hi = 0xff;
var lo = 0xff;
for (var i = 0; i < buffer.length; i++) {
var idx = hi ^ buffer[i];
hi = (lo ^ CRC._auchCRCHi[idx]);
lo = CRC._auchCRCLo[idx];
}
return CRC.padLeft((hi << 8 | lo ).toString(16).toUpperCase(), 4, '0');
};
CRC.isArray = function (arr) {
return Object.prototype.toString.call(arr) === '[object Array]';
};
CRC.ToCRC16 = function (str) {
return CRC.CRC16(CRC.isArray(str) ? str : CRC.strToByte(str));
};
CRC.ToModbusCRC16 = function (str) {
return CRC.CRC16(CRC.isArray(str) ? str : CRC.strToHex(str));
};
CRC.strToByte = function (str) {
var tmp = str.split(''), arr = [];
for (var i = 0, c = tmp.length; i < c; i++) {
var j = encodeURI(tmp[i]);
if (j.length == 1) {
arr.push(j.charCodeAt());
} else {
var b = j.split('%');
for (var m = 1; m < b.length; m++) {
arr.push(parseInt('0x' + b[m]));
}
}
}
return arr;
};
CRC.convertChinese = function (str) {
var tmp = str.split(''), arr = [];
for (var i = 0, c = tmp.length; i < c; i++) {
var s = tmp[i].charCodeAt();
if (s <= 0 || s >= 127) {
arr.push(s.toString(16));
}
else {
arr.push(tmp[i]);
}
}
return arr;
};
CRC.filterChinese = function (str) {
var tmp = str.split(''), arr = [];
for (var i = 0, c = tmp.length; i < c; i++) {
var s = tmp[i].charCodeAt();
if (s > 0 && s < 127) {
arr.push(tmp[i]);
}
}
return arr;
};
CRC.strToHex = function (hex, isFilterChinese) {
hex = isFilterChinese ? CRC.filterChinese(hex).join('') : CRC.convertChinese(hex).join('');
// Clear all spaces
hex = hex.replace(/\s/g, "");
// If the number of characters is odd , Fill in a space
hex += hex.length % 2 != 0 ? " " : "";
var c = hex.length / 2, arr = [];
for (var i = 0; i < c; i++) {
arr.push(parseInt(hex.substr(i * 2, 2), 16));
}
return arr;
};
CRC.padLeft = function (s, w, pc) {
if (pc == undefined) {
pc = '0';
}
for (var i = 0, c = w - s.length; i < c; i++) {
s = pc + s;
}
return s;
};
return CRC.ToModbusCRC16(parapms)
}
// call crc The verification method is used for verification calculation :
let crcResult = returnCRC(temphex)
// Second splicing :
let twoJoinStr = temphex + crcResult
// turn Buffer:
function strToBuffer(str) {
var buf = new ArrayBuffer(str.length / 2);
var bufView = new Uint8Array(buf);
for (var i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = parseInt(str.slice(i * 2, i * 2 + 2),16);
}
return buf;
}
return strToBuffer(twoJoinStr);
}
Packaged comtl Tools :
// A common method of storage :
module.exports = {
// Message box :
"toast": (title,icon,duration) => {
wx.showToast({
title,
icon,
duration
})
},
// Turn on loading:
"openloading": (title,mask) => {
wx.showLoading({
title,
mask
})
},
// close loading:
"closeloading": () => {
wx.hideLoading()
},
transformData(totalstr){
// Convert numeric type ( Resolve numeric types )
let datatobj = {
}
// console.log(" Temperature value :"+this.hexToSingle(totalstr.slice(30,38)))
// console.log(" Flow batch accumulation :"+this.hexToSingle(totalstr.slice(86,94)))
// console.log(" The flow is accumulated :"+this.hexToSingle(totalstr.slice(94,102)))
// console.log(" Advance quantitative value :"+this.hexToSingle(totalstr.slice(102,110)))
// console.log(" Running state :"+parseInt(totalstr.slice(118,122),16))
// console.log(" Component number :"+this.hex2dex(totalstr.slice(110,114)))
// console.log(" Batch number :"+this.hex2dex(totalstr.slice(114,118)))
datatobj.MinutFlowCount = this.hexToSingle(totalstr.slice(94,102))
datatobj.BtchFlowCount = this.hexToSingle(totalstr.slice(86,94))
datatobj.PiCount = this.hex2dex(totalstr.slice(114,118))
datatobj.MinutCount = this.hex2dex(totalstr.slice(110,114))
datatobj.ReadyConst = this.hexToSingle(totalstr.slice(102,110))
switch(parseInt(totalstr.slice(118,122),16)){
case 0:
datatobj.OperatStat=' end ';
break;
case 1:
datatobj.OperatStat=' Pause ';
break;
case 2:
datatobj.OperatStat=' This time has been completed ';
break;
case 3:
datatobj.OperatStat=' Running ';
break;
}
return datatobj
},
transformUnit(totalstr){
// Converting units ( Analytical unit )
let dtunit = {
}
dtunit.dotted = this.hex2dex(totalstr.slice(26,30))
switch(this.hex2dex(totalstr.slice(6,10))){
case '2':
dtunit.unit='m³';
break;
case '5':
dtunit.unit='kg';
break;
case '8':
dtunit.unit='L';
break;
case '11':
dtunit.unit='t';
break;
case '41':
dtunit.unit='mL';
break;
}
return dtunit
},
ab2hex(buffer){
// ArrayBuffer turn 16 Progress string
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
},
str2ab(str){
// String to ArrayBuffer object
let buf = new ArrayBuffer(str.length / 2);
let bufView = new Uint8Array(buf);
for (var i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = parseInt(str.slice(i * 2, i * 2 + 2),16);
}
return buf;
},
hexToSingle(t) {
// Hexadecimal to floating point
let start = t.slice(0,4)
let end = t.slice(4,8)
t = end + start
t = t.replace(/\s+/g, "");
if (t == "") {
return "";
}
if (t == "00000000") {
return "0";
}
if ((t.length > 8) || (isNaN(parseInt(t, 16)))) {
return "Error";
}
if (t.length < 8) {
t = this.FillString(t, "0", 8, true);
}
t = parseInt(t, 16).toString(2);
t = this.FillString(t, "0", 32, true);
var s = t.substring(0, 1);
var e = t.substring(1, 9);
var m = t.substring(9);
e = parseInt(e, 2) - 127;
m = "1" + m;
if (e >= 0) {
m = m.substr(0, e + 1) + "." + m.substring(e + 1)
} else {
m = "0." + this.FillString(m, "0", m.length - e - 1, true)
}
if (m.indexOf(".") == -1) {
m = m + ".0";
}
var a = m.split(".");
var mi = parseInt(a[0], 2);
var mf = 0;
for (var i = 0; i < a[1].length; i++) {
mf += parseFloat(a[1].charAt(i)) * Math.pow(2, -(i + 1));
}
m = parseInt(mi) + parseFloat(mf);
if (s == 1) {
m = 0 - m;
}
return m;
},
FillString(t, c, n, b) {
if ((t == "") || (c.length != 1) || (n <= t.length)) {
return t;
}
var l = t.length;
for (var i = 0; i < n - l; i++) {
if (b == true) {
t = c + t;
}
else {
t += c;
}
}
return t;
},
hex2dex (str) {
// call :16 Turn into the system 10 Base number
return parseInt(str, 16).toString(10)
}
}
Tips : This article, pictures and other materials come from the Internet , If there is infringement , Please send an email to :[email protected] Contact the author to delete .
The author : misery
边栏推荐
- SAP ABAP BDC(批量数据通信)-018
- Polynomial locus of order 5
- 拼多多商品详情接口、拼多多商品基本信息、拼多多商品属性接口
- Leakage relay jd1-100
- Unity让摄像机一直跟随在玩家后上方
- Taobao Commodity details page API interface, Taobao Commodity List API interface, Taobao Commodity sales API interface, Taobao app details API interface, Taobao details API interface
- 毕业之后才知道的——知网查重原理以及降重举例
- Getting started with DES encryption
- What are the common message queues?
- Hcip seventh operation
猜你喜欢

爬虫练习题(三)

How does mapbox switch markup languages?

CVE-2021-3156 漏洞复现笔记

How Alibaba cloud's DPCA architecture works | popular science diagram

Sidecar mode

1. AVL tree: left-right rotation -bite

ForkJoin最全详解(从原理设计到使用图解)
![[reading of the paper] a multi branch hybrid transformer network for channel terminal cell segmentation](/img/f6/cd307c03ea723e1fb6a0011b37d3ef.png)
[reading of the paper] a multi branch hybrid transformer network for channel terminal cell segmentation

Zero sequence aperture of leakage relay jolx-gs62 Φ one hundred

Jhok-zbl1 leakage relay
随机推荐
Design, configuration and points for attention of network unicast (one server, multiple clients) simulation using OPNET
导航栏根据路由变换颜色
Go 語言的 Context 詳解
集群、分布式、微服務的區別和介紹
[Oracle] simple date and time formatting and sorting problem
【Shell】清理nohup.out文件
AI人脸编辑让Lena微笑
Nodejs get client IP
纪念下,我从CSDN搬家到博客园啦!
基于NCF的多模块协同实例
Web Authentication API兼容版本信息
Dynamic memory management
When deleting a file, the prompt "the length of the source file name is greater than the length supported by the system" cannot be deleted. Solution
“多模态”概念
Life experience of an update statement
async / await
消息队列:重复消息如何处理?
How does mapbox switch markup languages?
zabbix_get测试数据库失败
Initial experience of annotation