微信小程序蓝牙模块开发

微信小程序蓝牙模块开发,第1张

//index.js

//获取应用实例

const app = getApp()

const util = require('../../utils/util.js')

const bletool = require('../../utils/bletool.js')

Page({

data: {

// lists: [{ 'order_no': '1111', 'car_no': '321', 'car_type': '尚好捷', 'order_date': '2018-01-02 08:00', 'order_money': '16.00', 'order_time': '4' }],

car_no: '',

order_no: '',

lists: [],

bleList: [], //蓝牙设备数组

serviceId: '',//592B3370-3900-9A71-4535-35D4212D2837

serviceMac: '',//C9:9B:4C:E7:DE:10

service_psd: '',//855525B837253705595800000329

service_uuid: '',

deviceId:'',

characteristics:[] //特征值

},

onLoad: function (options) {

this.initBle()

},

onReady: function () {

// 页面渲染完成

},

onShow: function () {

if (app.globalData.car_no.length>0){

this.getDeviceInfo()

}

},

onHide: function () {

// 页面隐藏

},

onUnload: function () {

// 页面关闭

app.globalData.car_no=''

},

//蓝牙相关

//初始化蓝牙

initBle: function () {

var that = this

wx.onBluetoothAdapterStateChange(function (res) {

console.log('adapterState changed, now is', res)

app.globalData.ble_state = res.available

if (res.available) {

that.initBle()

} else {

util.showToast('手机蓝牙已关闭')

app.globalData.ble_isonnectting = false

}

})

//打开蓝牙适配器

wx.openBluetoothAdapter({

success: function (res) {

console.log('打开蓝牙适配器成功')

that.getBluetoothAdapterState()

app.globalData.ble_state = true

that.onBluetoothDeviceFound()

},

fail: function (res) {

// fail

console.log(res)

util.showToast('请打开手机蓝牙')

},

complete: function (res) {

// complete

}

})

},

onBluetoothDeviceFound:function(){

var that = this

//监听扫描

wx.onBluetoothDeviceFound(function (res) {

// res电脑模拟器返回的为数组;手机返回的为蓝牙设备对象

console.log('监听搜索新设备:', res)

that.updateBleList([res])

})

},

getBluetoothAdapterState: function () {

var that = this

wx.getBluetoothAdapterState({

success: function (res) {

var available = res.available

var discovering = res.discovering

if (!available) {

util.showToast('蓝牙不可用')

} else {

if (!discovering) {

// that.startBluetoothDevicesDiscovery()

}

}

}

})

},

startBluetoothDevicesDiscovery: function () {

var that = this

var services = []

services.push(this.data.serviceId)

wx.showLoading({

title: '设备搜索中'

})

setTimeout(function () {

wx.hideLoading()

if (app.globalData.deviceId.length==0){

util.showModal('设备搜索失败,请重试')

}

}, 10000)

if(bletool.isIOS()){

wx.startBluetoothDevicesDiscovery({

services: services,

allowDuplicatesKey: true,

success: function (res) {

console.log('ios搜索成功')

console.log(res)

},

fail: function (err) {

console.log(err)

}

})

}else{

wx.startBluetoothDevicesDiscovery({

// services: services,

allowDuplicatesKey: true,

success: function (res) {

console.log('Android搜索成功')

console.log(res)

},

fail: function (err) {

console.log(err)

wx.hideLoading()

that.startBluetoothDevicesDiscovery()

// that.getBluetoothAdapterState()

util.showToast('搜索失败')

}

})

}

},

startConnectDevices: function (ltype, array) {

var that = this

clearTimeout(that.getConnectedTimer)

that.getConnectedTimer = null

wx.stopBluetoothDevicesDiscovery({

success: function (res) {

// success

}

})

app.globalData.ble_isonnectting = true

console.log('连接前:'+that.deviceId)

wx.createBLEConnection({

deviceId: that.deviceId,

success: function (res) {

if (res.errCode == 0) {

console.log('连接成功:')

that.getService(that.deviceId)

}

},

fail: function (err) {

console.log('连接失败:', err)

wx.hideLoading()

util.showModal('设备连接失败,请重试')

// if (ltype == 'loop') {

// that.connectDeviceIndex += 1

// that.loopConnect(array)

// } else {

// that.startBluetoothDevicesDiscovery()

// that.getConnectedBluetoothDevices()

// }

app.globalData.ble_isonnectting = false

},

complete: function () {

}

})

},

getService: function (deviceId) {

var that = this

// 监听蓝牙连接

wx.onBLEConnectionStateChange(function (res) {

console.log(res)

app.globalData.ble_isonnectting = res.connected

if (!res.connected) {

util.showToast('连接断开')

}

})

// 获取蓝牙设备service值

wx.getBLEDeviceServices({

deviceId: deviceId,

success: function (res) {

console.log('获取蓝牙设备service值')

console.log(res)

that.getCharacter(deviceId, res.services)

}

})

},

getCharacter: function (deviceId, services) {

var that = this

services.forEach(function (value, index, array) {

if (value.isPrimary) {

that.setData({

service_uuid: value.uuid,

deviceId: deviceId

})

app.globalData.service_uuid= value.uuid

app.globalData.deviceId=deviceId

}

})

//监听通知

wx.onBLECharacteristicValueChange(function (res) {

// callback

console.log('value change', res)

const hex = bletool.buf2char(res.value)

console.log('返回的数据:', hex)

//配对密码

if (hex.indexOf('855800000106') != -1) {

wx.hideLoading()

var charact_write = that.data.characteristics[1]

bletool.writeDataToDevice(that.data.deviceId, that.data.service_uuid, charact_write, that.data.service_psd)

wx.showToast({

title: '设备已连接',

icon: 'success',

duration: 3000

})

setTimeout(function () {

bletool.writeDataToDevice(that.data.deviceId, that.data.service_uuid, charact_write, '235525B837253705590400000273')

}, 2000)

} else if (hex.indexOf('23040000') != -1) {

//启动成功

that.starRenting()

}

})

wx.getBLEDeviceCharacteristics({

deviceId: deviceId,

serviceId: that.getServiceUUID(),

success: function (res) {

wx.getBLEDeviceCharacteristics({

deviceId: deviceId,

serviceId: that.getServiceUUID(),

success: function (res) {

console.log('特征', res)

that.setData({

characteristics:res.characteristics

})

app.globalData.characteristics = res.characteristics

var charact_read = res.characteristics[0]

},

loopConnect: function (devicesId) {

var that = this

var listLen = devicesId.length

if (devicesId[this.connectDeviceIndex]) {

this.deviceId = devicesId[this.connectDeviceIndex]

this.startConnectDevices('loop', devicesId)

} else {

console.log('已配对的设备小程序蓝牙连接失败')

that.startBluetoothDevicesDiscovery()

that.getConnectedBluetoothDevices()

}

},

//更新数据 devices为数组类型

updateBleList: function (devices) {

console.log('设备数据:',devices)

var newData = this.data.bleList

var that = this

var tempDevice = null

for (var i = 0i <devices.lengthi++) {

//ios设备

if (devices[i].devices != null) {

if (devices[i].devices.length >0) {

tempDevice = devices[i].devices[0]

}

else {

continue

}

}

//安卓

else {

tempDevice = devices[i]

}

if (!this.isExist(tempDevice)) {

newData.push(tempDevice)

}

}

console.log('数据:')

console.log(newData)

this.setData({

bleList: newData

})

if (!app.globalData.ble_isonnectting) {

var that = this

this.data.bleList.forEach(function (value, index, array) {

//找到对应id的设备,ios判断服务id安卓判断mac地址

var deviceId = value['deviceId']

if(bletool.isIOS()){

let advertisServiceUUID = value['advertisServiceUUIDs'][0]

if (advertisServiceUUID == that.data.serviceId.toUpperCase()){

that.deviceId = deviceId

console.log(that.deviceId)

that.startConnectDevices()

}

}else{

if (deviceId == that.data.serviceMac) {

that.deviceId = deviceId

console.log(that.deviceId)

that.startConnectDevices()

}

}

})

}

},

//是否已存在 存在返回true 否则false

isExist: function (device) {

var tempData = this.data.bleList

for (var i = 0i <tempData.lengthi++) {

if (tempData[i].deviceId == device.deviceId) {

return true

}

}

return false

},

//服务uuid

getServiceUUID: function () {

return bletool.stringTransition(this.data.service_uuid)

},

getDeviceInfo: function () {

let car_no = app.globalData.car_no

var that = this

wx.request({

url: app.globalData.serverURL + '?c=car&a=getDeviceInfo&open_id=' + app.globalData.open_id + '&car_no=' + car_no,

method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT

header: { 'content-type': 'application/json' }, // 设置请求的 header

success: function (res) {

// success

var data = res.data

console.log(data)

if (data.result == 1) {

app.globalData.serviceId = data.data.service_id

app.globalData.serviceMac = data.data.service_mac,

app.globalData.service_psd = '85' + data.data.service_psd + '5800000329'

that.setData({

serviceId: data.data.service_id,

serviceMac: data.data.service_mac,

service_psd: '85' + data.data.service_psd+'5800000329',

})

app.startBluetoothDevicesDiscovery()

// that.onBLECharacteristicValueChange()

} else {

util.showModal(data.msg)

}

},

fail: function () {

},

complete: function () {

// complete

}

})

},

})

https://segmentfault.com/a/1190000013502494

不需要调接口,想要渲染几个月的数据,手动传入即可

根据思否 Peggy7   这篇文章改了一下。

  <view class="freepop_body counter-warp">

    <view class="tac bg_ffffff">

      <view class="border_bot padtb20 padlr30 tac" v-if="canlendar_data&&canlendar_data.length>0">

        <van-icon name="arrow-left" size="20" class="vam" @click="goPrevMonth"/>

        <view class="inblock fz28 vam" style="margin: 0 50rpx">{{canlendar_data[cur].year}}年{{canlendar_data[cur].month}}月

        <van-icon name="arrow" size="20" class="vam" @click="goNextMonth" />

      <view class="week fz28 padtb20 border_bot" id="week">

        <view :class="[idx===0||idx===6 ? 'relax':'','week-item']" v-for="(item,idx) inweek_list" :key="idx">{{item}}

      <view class="month-block fz28" v-for="(canlendar_item,index) incanlendar_data" :key="index">

        <block v-if="index===cur">

          <view class="month-content">

            <view :class="[item.fullDate>=nowDate&&item.fullDate<=maxDate&&item.available? '':'gray','month-day',checkDate===item.fullDate?'startActive':'']" @click="chooseDate" :data-available="item.fullDate>=nowDate&&item.fullDate<=maxDate&&item.available" :data-fulldate="item.fullDate" v-for="(item,dd) in canlendar_item.allDays" :key="item.fullDate">

              <view class="isfull">

                {{item.fullDate>=nowDate &&item.fullDate<=maxDate &&!item.available?'满':''}}

<block v-if="checkDate===item.fullDate">

                  {{checkDate===item.fullDate ? '已选' : ''}}

              {{item.day?item.day:''}}

    <view style="padding: 40rpx 32rpx 0 32rpx">

      <text class="fz26">{{rule}}

    <view class="fixedBar bg_f9f9f9" style="padding: 20rpx 50rpx">

      <button class="globButton" style="border-radius: 10rpx" :disabled="disable" @click="submitFree">提 交

  import {imgObj}from '@/utils/imgs'

  import httpsfrom '@/utils/common'

  const {get,throttle}=https

  let hotel_id='',timer=null,cur_year='',cur_month='',cur_day='',arr=[]

export default {

data () {

return {

imgObj:imgObj,

      rule:'',

      disable:true,//按钮是否可点击

      week_list: ['日','一','二','三','四','五','六'],

      checkDate:'',//选择的日期

      cur:0,//第几个月份

      nowDate:'',//今天

      maxDate:'',//最大日期

      canlendar_data:[]

}

},

  onLoad(options){

hotel_id=options.hotelId

    // let {spa_date}=this.$store.state

// this.checkDate=spa_date.date[0]+'-'+spa_date.date[1]+'-'+spa_date.date[2]

    this.getDate_()

    const date =new Date()

    cur_year = date.getFullYear()

    cur_month = date.getMonth() +1

    cur_day = date.getDate()

    let month = cur_month.toString().length ===1 ?`0${cur_month}` : cur_month

    let day = cur_day.toString().length ===1 ?`0${cur_day}` : cur_day

    let nowDate =`${cur_year}-${month}-${day}`

    this.nowDate=nowDate

  },

  onUnload(){

//this.reset()

    clearTimeout(timer)

  },

  methods: {

reset(){

this.rule=''

      this.checkDate=''

    },

    goPrevMonth(){

if(this.cur==0){

return false

      }else{

this.cur--

}

},

    goNextMonth(){

if(this.cur==(this.canlendar_data.length-1)){

return false

      }else{

this.cur++

}

},

    chooseDate(e) {

const available = e.currentTarget.dataset.available

      const fullDate = e.currentTarget.dataset.fulldate

      if(!available) {

return false

      }else{

this.checkDate=fullDate

      }

},

    // chooseTheDate(data,index){

//  this.theCheck=data

//  this.theCheckIndex=index

//  this.disable=false

// },

    async getDate_() {

const loginResult =await get('api_v2/free/reservation',{

hotel_id:hotel_id

})

if (loginResult.code==200) {

let data=loginResult.data

        let newBrr=[]

        data.options.map((n,index)=>{

let tomo =new Date()

          tomo.setTime(tomo.getTime() + index *24 *60 *60 *1000)//1天 以后

          let tomoYear=tomo.getFullYear(),tomoMonth=tomo.getMonth() +1,tomoDate=tomo.getDate()

          tomoMonth=tomoMonth<10?'0'+tomoMonth:tomoMonth

          tomoDate=tomoDate<10?'0'+tomoDate:tomoDate

          newBrr.push({

val:tomoYear+'-'+tomoMonth+'-'+tomoDate,

            flag:n

})

})

this.maxDate=newBrr[newBrr.length-1].val

        arr=newBrr

        this.fillCalendar(6)

        this.rule=data.rule.replace(/\\n/g,"\n")

        this.disable=false

      }

},

    submitFree:throttle(async function() {

wx.showLoading({

title:'',

        mask:true

      })

let {checkDate}=this

      let that=this

      if(checkDate==''){

wx.showToast({

title:'请选择预约日期',

          icon:'none',

          duration:2000

        })

return false

      }

const loginResult =await get('api_v2/free/submit',{

hotel_id:hotel_id,

        estimated_at:checkDate

})

if (loginResult.code==200) {

wx.hideLoading()

        let data=loginResult.data

        let orderid=data.order_id

        that.goOrderdetail(orderid)

        that.$fire.fire('alreadyFree')

      }

}),

    goBack(){

wx.navigateBack({

delta:1

      })

},

    goOrderdetail:throttle(function(id) {

wx.redirectTo({

url:'/pages/orderdetailspa/index?orderId='+id

})

}),

    // 获取每月总天数

    getAllDaysOfMonth(year,month) {

return new Date(year,month,0).getDate()

    },

    // 获取每月第一天是星期几

    getFirstDayOfMonth(year,month) {

return new Date(year, month -1, 1).getDay()

    },

    // 计算本月前空了几格

    getEmptyGrids(year,month) {

// FirstDayOfMonth代表本月的第一天是星期几

      const FirstDayOfMonth =this.getFirstDayOfMonth(year, month)

      let emptyGrids = []

      // 有空格的情况

      if (FirstDayOfMonth >0) {

for (let i =0i <FirstDayOfMonthi++) {

emptyGrids.push({

'num':'',

            'fullDate':'x'  //x是我自己定义的一个值,代表没有日期

          })

        }

// 将空格放入数组

        return emptyGrids

      }else{

// 否则返回一个新数组

        return []

      }

},

    // 计算本月日历

    getDaysOfThisMonth(year,month) {

let days = []

      const AllDaysOfMonth =this.getAllDaysOfMonth(year, month)

      let fullMonth = month.toString().length ===1 ?`0${month}`:month

      for (let i =0i <AllDaysOfMonthi++) {

let day = i+1, fullDay = day,fullDate=''

        fullDay = fullDay.toString().length ===1 ?`0${day}` : fullDay

        fullDate=`${year}-${fullMonth}-${fullDay}`

        let obj={

day,

          fullDay,

          fullDate,

          'available':true

        }

for(let j=0j

if(fullDate==arr[j].val){

obj.available=arr[j].flag

          }

}

days.push(obj)

      }

// 返回每个月的具体日期

      return days

    },

    // 循环渲染日历

// 从本月开始渲染,n代表包括本月开始连续渲染几个月

    fillCalendar(n) {

let year = cur_year, month = cur_month, fullMonth, canlendar_data = []

      // 计算年月以及具体日历

      for (let i = cur_monthi <cur_month + ni++) {

let EmptyGrids =this.getEmptyGrids(year, month)

        let DaysOfThisMonth =this.getDaysOfThisMonth(year, month)

        // 把空格和具体日历合为一个数组

        let allDays = [...EmptyGrids, ...DaysOfThisMonth]

        // 对年份和月份的计算做一些判断

        if (month >12) {

year++

          month =1

          fullMonth ='01'

          canlendar_data.push({

year,

            month,

            fullMonth,

            allDays })

          month++

        }else{

fullMonth = month.toString().length ===1 ?`0${month}` : month

          canlendar_data.push({

year,

            month,

            fullMonth,

            allDays })

          month++

        }

}

this.canlendar_data=canlendar_data

    },

  }

}

<style lang="less">

  @import "../../../styles/freecalendar.less"


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/11376903.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-15
下一篇 2023-05-15

发表评论

登录后才能评论

评论列表(0条)

保存