Ios 从swift读取的值中发出
我正在做一个ble应用程序,当我试图从ble设备读取值时,它第一次返回零,当我返回并再次执行时,它返回值。在下面的代码中,我试图获取固件版本和电池的值。这是我第一次运行代码,它始终返回firmwire版本的nil和电池返回值。请帮助我找出为什么我在第一次执行时没有收到firmwire版本的值 这是我的密码Ios 从swift读取的值中发出,ios,swift,xcode,return,bluetooth-lowenergy,Ios,Swift,Xcode,Return,Bluetooth Lowenergy,我正在做一个ble应用程序,当我试图从ble设备读取值时,它第一次返回零,当我返回并再次执行时,它返回值。在下面的代码中,我试图获取固件版本和电池的值。这是我第一次运行代码,它始终返回firmwire版本的nil和电池返回值。请帮助我找出为什么我在第一次执行时没有收到firmwire版本的值 这是我的密码 extension SearchDeviceViewController: CBCentralManagerDelegate, CBPeripheralDelegate { func
extension SearchDeviceViewController: CBCentralManagerDelegate, CBPeripheralDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .unknown:
print("central.state is .unknown")
case .resetting:
print("central.state is .resetting")
case .unsupported:
print("central.state is .unsupported")
case .unauthorized:
print("central.state is .unauthorized")
case .poweredOff:
print("central.state is .poweredOff")
case .poweredOn:
print("central.state is .poweredOn")
centralManager.scanForPeripherals(withServices: nil)
@unknown default:
print("\(central.state)")
}
}
//establish a connection with detected BLE device
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
var dataFound = 0
for peripheralsFound in peripherals {
if peripheral.identifier == peripheralsFound.identifier {
dataFound = 1
}
}
if dataFound == 0 && peripheral.name != nil {
if !deviceIds.contains(peripheral.identifier.uuidString) {
peripherals.append(peripheral)
tblViewDeviceList.reloadData()
}
}
}
//On successful connection, request for all the services available in the BLE device
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("connected")
selectedPeripheral.discoverServices(nil)
}
//Request all the characteristics available in each services
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
print(4)
var count = 1
if let servicePeripheral = selectedPeripheral.services as [CBService]? { //get the services of the perifereal
for service in servicePeripheral {
//Then look for the characteristics of the services
if service.uuid.uuidString == "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" || service.uuid.uuidString == "180F" {
peripheral.discoverCharacteristics(nil, for: service)
} else {
if count == 1 {
Alert.showAlertView(withTitle: "", withMessage: "Invalid device")
count = count + 1
}
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
print("5")
if let characterArray = service.characteristics as [CBCharacteristic]? {
for cc in characterArray {
myCharacteristic = cc //saved it to send data in another function.
if cc.uuid.uuidString == "6E400002-B5A3-F393-E0A9-E50E24DCCA9E" {
writeValue()
} else {
peripheral.readValue(for: cc) //to read the value of the characteristic
peripheral.setNotifyValue(true, for: myCharacteristic)
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
print("7")
print(characteristic)
if characteristic.uuid.uuidString == "6E400003-B5A3-F393-E0A9-E50E24DCCA9E" {
if let readValue = characteristic.value {
if let datastring = NSString(data: readValue, encoding: String.Encoding.utf8.rawValue) {
self.firmware = datastring as String
}
}
}
if characteristic.uuid.uuidString == "2A19" {
if let readValue = characteristic.value {
let battery = readValue.compactMap({ String(format: "%02x", $0) }).joined()
if battery < "60" {
self.batteryStatus = "CHANGE"
} else if battery == "" {
self.batteryStatus = ""
} else {
self.batteryStatus = "OK"
}
if self.firmware != "" && battery != "" {
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let popupVC = storyboard.instantiateViewController(withIdentifier: "DeviceDetailsViewController") as! DeviceDetailsViewController
popupVC.deviceCount = defaults.integer(forKey: "devicesAdded")
popupVC.isNewDevice = true
popupVC.peripheralName = self.selectedPeripheral.name!
popupVC.deviceUUID = self.selectedPeripheral.identifier.uuidString
popupVC.fromSearch = true
popupVC.firmWare = self.firmware
popupVC.batteryStatus = self.batteryStatus
popupVC.modalPresentationStyle = .fullScreen
popupVC.modalTransitionStyle = .coverVertical
self.present(popupVC, animated: true, completion: nil)
}
}
}
}
func writeValue() {
print("8")
//Do something
let setCmnd = "GET_FW_VERSION"
let dataToSend: Data = setCmnd.data(using: String.Encoding.utf8)!
selectedPeripheral.writeValue(dataToSend, for: myCharacteristic, type: CBCharacteristicWriteType.withResponse)
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
}
}
扩展搜索设备视图控制器:CBCentralManagerDelegate、CBPeripheralDelegate{
func CentralManager数据状态(uCentral:CBCentralManager){
切换中央状态{
案件.未知:
打印(“central.state.is.unknown”)
案例.重置:
打印(“中心状态为重置”)
案例。不支持:
打印(“central.state.is.unsupported”)
案件.未经授权:
打印(“central.state.is.unauthorized”)
案例.断电:
打印(“central.state is.poweredOff”)
案例.poweredOn:
打印(“central.state is.poweredOn”)
centralManager.ScanFor外围设备(带服务:无)
@未知默认值:
打印(“\(central.state)”)
}
}
//与检测到的设备建立连接
func centralManager(ucentral:CBCentralManager,didDiscover peripal:cbperipal,advertisementData:[String:Any],rssi-rssi:NSNumber){
var dataFound=0
用于外围设备在外围设备中查找{
如果peripheral.identifier==peripheralsFound.identifier{
dataFound=1
}
}
如果dataFound==0&&peripheral.name!=nil{
if!deviceId.contains(peripheral.identifier.UUIString){
外围设备。附加(外围设备)
tblViewDeviceList.reloadData()
}
}
}
//成功连接后,请求BLE设备中的所有可用服务
func centralManager(uCentral:CBCentralManager,didConnect外围设备:CBPeripheral){
打印(“连接”)
所选外围设备。发现服务(无)
}
//请求每个服务中可用的所有特征
func外围设备(外围设备:cb外围设备,didDiscoverServices错误:错误?){
印刷品(4)
变量计数=1
如果let servicepipheral=selectedPeripheral.services as[CBService]?{//获取该peripheral的服务
用于servicePeripheral中的服务{
//然后查找服务的特征
如果service.uuid.uuidString==“6E400001-B5A3-F393-E0A9-E50E24DCA9E”| | service.uuid.uuidString==“180F”{
外围设备。发现特性(无,用于:服务)
}否则{
如果计数=1{
Alert.showAlertView(标题为“”,消息为“无效设备”)
计数=计数+1
}
}
}
}
}
func外围设备(外围设备:CBPeripal,DIDdiscoverCharacteristics服务:CBService,错误:error?){
打印(“5”)
如果让characterArray=service.characters作为[CBCharacteristic]{
用于characterArray中的cc{
myCharacteristic=cc//保存它以在另一个函数中发送数据。
如果cc.uuid.uuistring==“6E400002-B5A3-F393-E0A9-E50E24DCA9E”{
writeValue()
}否则{
peripheral.readValue(for:cc)//读取特征值
peripheral.setNotifyValue(true,用于:myCharacteristic)
}
}
}
}
func外围设备(uPeripal:CbPeripal,didUpdateValueFor characteristic:CBCharacteristic,error:error?){
打印(“7”)
打印(特征)
如果characteristic.uuid.uuistring==“6E400003-B5A3-F393-E0A9-E50E24DCA9E”{
如果让readValue=characteristic.value{
如果let datastring=NSString(数据:readValue,编码:String.encoding.utf8.rawValue){
self.firmware=datastring作为字符串
}
}
}
如果characteristic.uuid.uuistring==“2A19”{
如果让readValue=characteristic.value{
让battery=readValue.compactMap({String(格式:'%02x',$0)}).joined()
如果蓄电池<“60”{
self.batteryStatus=“更改”
}否则,如果电池==“”{
self.batteryStatus=“”
}否则{
self.batteryStatus=“确定”
}
如果self.firmware!=“”&电池!=“”{
让故事板:UIStoryboard=UIStoryboard(名称:“Main”,bundle:nil)
让popupVC=storyboard.instantialeviewcontroller(标识符为:“DeviceDetailsViewController”)作为!DeviceDetailsViewController
popupVC.deviceCount=defaults.integer(forKey:“devicesAdded”)
popupVC.isNewDevice=true
popupVC.peripheraldname=self.selectedperipherald.name!
popupVC.deviceUUID=self.selectedPeripheral.identifier.UUIString
popupVC.fromSearch=true
popupVC.firmWare=self.firmWare
popupVC.batteryStatus=自我batteryStatus
popupVC.modalPresentationStyle=.fullScreen
popupVC.ModAltTransitionStyle=.coverVertical
self.present(popupVC,动画:true,完成:nil)