Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to develop and realize Ble Bluetooth by IOS

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to develop and implement Ble Bluetooth in IOS. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Main blue tooth file .h main blue tooth file. MUUID file Bluetooth list shows the file

First: introduce the framework of Ble Bluetooth

BuleHelp.h

# import / / Import Bluetooth framework # import # import "DeviceModel.h" # import "Constants.h" # import "CommonUserDefaults.h" # import "CommonUtil.h" # import "TempDB.h" # define COMMAND_PACKET_MIN_SIZE 7@interface BlueHelp: NSObject// Bluetooth device search is shown in the list @ property (nonatomic,strong) NSMutableArray * periperals;// connection peripheral@property (nonatomic,strong) CBPeripheral * peripheral;// connection peripheral@property (nonatomic,strong) CBPeripheral * selectperipheral / / Central Manager @ property (nonatomic,strong) CBCentralManager * centerManager;@property (nonatomic,strong) DeviceModel * deviceModel;// equipment list @ property (nonatomic,strong) NSMutableArray * deviceList;@property (nonatomic,strong) NSMutableArray * commandArray;// whether to upgrade ota @ property (nonatomic) BOOL isOta;@property (nonatomic) BOOL isWritePacketDataSuccess;@property (strong,nonatomic) NSString * checkSumpetBash! * @ property isApplicationValid * @ discussion flag used to check whether the application writing is success * * / @ property (nonatomic) BOOL isApplicationValid / *! * @ property checkSum * * @ discussion checkSum received from the device for writing a single row * * / @ property (assign) uint8_t checksumming int endRowNumber! * @ property startRowNumber * * @ discussion Device flash start row number * * / @ property (nonatomic) int startRowNumberwitter int endRowNumber! * @ property endRowNumber * * @ discussion Device flash end row number * * / @ property (RowNumber) / *! * @ property siliconIDString * * @ discussion siliconID from the device response * * / @ property (strong,nonatomic) NSString * roomonIDStringwitter account! * @ property siliconRevString * * @ discussion silicon rev from the device response * * / @ property (strong,nonatomic) NSString * siliconRevString;// whether to send data @ property (nonatomic) BOOL isSendData;@property (strong,nonatomic) CommonUtil * commonUtil;@property (strong,nonatomic) TempDB * tempDB;@property (strong,nonatomic) NSDate * currentDate / / time format @ property (strong,nonatomic) NSDateFormatter * dateformatter;@property (strong,nonatomic) NSString * deviceName;//@property (nonatomic,strong) NSUserDefaults * userDefaults;@property (nonatomic,strong) CommonUserDefaults * userDefaults;// send temperature data @ property (nonatomic,strong) CBCharacteristic * sendtempcharateristic;// send OTA data @ property (nonatomic,strong) CBCharacteristic * sendotacharateristic;// High / low temperature data / / @ property (nonatomic,strong) CBCharacteristic * sendhighalarmcharateristic;////@property (nonatomic,strong) CBCharacteristic * sendlowalarmcharateristic / / ota@property (nonatomic,strong) CBCharacteristic * senddfucharateristic;// send string 'maximum value on CR' cleaner (3 bytes) @ property (nonatomic,strong) CBCharacteristic * senddcrstrateristic;// send string' PD' machine sub-shutdown (3 bytes) @ property (nonatomic,strong) CBCharacteristic * senddoutstrateristic;// mute @ property (strong,nonatomic) CBCharacteristic * sendmutealarmcharateristic;//calset@property (strong,nonatomic) CBCharacteristic * sendcalsetcharateristic;//intervaltime@property (strong,nonatomic) CBCharacteristic * sendintervaltimecharateristic / alarmswitch@property (strong,nonatomic) CBCharacteristic * sendalarmswitchcharateristic;//tempunit@property (strong,nonatomic) CBCharacteristic * sendtempunitcharateristic;@property (strong,nonatomic) CBCharacteristic * sendlowalarmswitchcharateristic;///+ (id) sharedManager;- (NSMutableArray *) getDeviceList;- (NSMutableArray *) getPeriperalList;- (void) startScan;// connection Bluetooth-(void) contentBlue: (int) row;// disconnect Bluetooth-(void) disContentBle;// disconnect ota Bluetooth connection-(void) disContentOtaBle;// temperature symbol-(void) writeTempUnit: (NSString *) value / / write alarm switch-(void) writeAlarmSwitch: (NSString *) value;// write mute alarm- (void) writeMuteAlarm: (NSString *) value;// write CR CLERVULE- (void) writeClearCR: (NSString *) value;// write interval time- (void) writeIntervalTime: (NSString *) value;// write cal set- (void) writeCalSet: (NSString *) value;// write device switch button-(void) writeBluePD: (NSString *) value / / write low temperature alarm / /-(void) writeLowAlarm: (NSString*) value;/ write high temperature alarm / /-(void) writeHighAlarm: (NSString*) value;//OTA firmware upgrade also known as DFU- (void) writeUpdateOTA: (NSString*) value;- (void) writeBlueOTA: (NSString*) value;- (void) wirteBlueOTAData: (NSData *) value;- (void) writeLowAlarmSwitch: (NSString*) value;- (void) discoverCharacteristicsWithCompletionHandler: (void (^) (BOOL success, NSError * error)) handler -(void) updateValueForCharacteristicWithCompletionHandler: (void (^) (BOOL success,id command,NSError * error) handler;- (void) stopUpdate;- (void) setCheckSumType: (NSString *) type;- (NSData *) createCommandPacketWithCommand: (uint8_t) commandCode dataLength: (unsigned short) dataLength data: (NSDictionary *) packetDataDictionary;- (void) writeValueToCharacteristicWithData: (NSData *) data bootLoaderCommandCode: (unsigned short) commandCode;/* * stop scanning * /-(void) stopScan;// is the first time to connect the device @ property (assign,nonatomic) BOOL isconnected / / current time @ property (nonatomic,assign) long currentTime;@property (nonatomic,strong) NSString * macAddre;@property (nonatomic,strong) NSString * macName;- (void) disMainOtaBle;@end

BuleHelp.m

/ / the method that is automatically called to check and scan Bluetooth after the program runs-(void) centralManagerDidUpdateState: (CBCentralManager *) central {if ([central state] = = CBCentralManagerStatePoweredOff) {NSLog (@ "CoreBluetooth BLE hardware is powered off");} else if ([central state] = = CBCentralManagerStatePoweredOn) {NSLog (@ "CoreBluetooth BLE hardware is powered on and ready"); [self startScan];} else if ([central state] = = CBCentralManagerStateUnauthorized) {NSLog (@ "CoreBluetooth BLE state is unauthorized") } else if ([central state] = = CBCentralManagerStateUnknown) {NSLog (@ "CoreBluetooth BLE state is unknown");} else if ([central state] = = CBCentralManagerStateUnsupported) {NSLog (@ "CoreBluetooth BLE hardware is unsupported on this platform");}}

/ * * start scanning when the program is running * /-(void) startScan {_ periperals = [[NSMutableArray alloc] init]; _ deviceList = [[NSMutableArray alloc] init]; / / 2. Scan external devices with central equipment [_ centerManager scanForPeripheralsWithServices:nil options:nil];} / * * stop scanning * /-(void) stopScan {[_ centerManager stopScan];}

/ * * the device can contain the Device addre address and you can get * 1 by putting it in key:kCBAdvDataManufacturerData. The hardware development engineer writes the address into the manufacturer's information of the equipment. * /-(void) centralManager: (CBCentralManager *) central didDiscoverPeripheral: (CBPeripheral *) peripheral advertisementData: (NSDictionary *) advertisementData RSSI: (NSNumber *) RSS {/ / determine that if (! [_ periperals containsObject:peripheral]) {/ / search if ([peripheral.name containsString:@ "TMW012BT"] | [peripheral.name containsString:@ "OTA"]) {NSLog (@ "DATA:% @", advertisementData) if the array does not contain the external devices currently scanned. NSArray * keys = [advertisementData allKeys]; for (int I = 0; I

< [keys count]; ++i) { id key = [keys objectAtIndex: i]; NSString *keyName = (NSString *) key; NSData *value = [advertisementData objectForKey: key]; if([keyName isEqualToString:@"kCBAdvDataManufacturerData"]){ NSLog(@"value is %@",value); NSString *result = [self convertDataToHexStr:value]; NSLog(@"reslut is %@",result); if(result!=nil&&result.length>

4) {NSString* d = [result substringFromIndex:4]; NSLog (@ "D IS% @", d); / / lowercase / / NSString* lower = [test lowercaseString]; / / uppercase NSString* upper = [d uppercaseString]; _ macAddre = [NSString stringWithFormat:@ "Splash NRV% @", upper];} if ([keyName isEqualToString:@ "kCBAdvDataLocalName"]) {NSString* aStr= (NSString*) value; NSLog (@ "astr is% @", aStr); _ macName = aStr }} _ deviceModel = [DeviceModel new]; _ deviceModel.deviceName = _ macName; / / Bluetooth address _ deviceModel.deviceAddre = _ macAddre; int rssi = [RSS intValue]; NSString * range = [NSString stringWithFormat:@ "% d", rssi]; NSString * rs = [NSString stringWithFormat:@ "RSSI% @ dBm", range]; / / add to it [self.periperals addObject:peripheral]; _ deviceModel.deviceRssi = rs; [_ deviceList addObject:_deviceModel];}

/ / analyze the data in the broadcast-(void) getAdvertisementData: (NSDictionary *) advertisementData {NSArray * keys = [advertisementData allKeys]; for (int I = 0; I < [keys count]; + + I) {id key = [keys objectAtIndex: I]; NSString * keyName = (NSString *) key; NSObject * value = [advertisementData objectForKey: key]; if ([keyName isEqualToString:@ "kCBAdvDataManufacturerData]) {printf (" key:% s\ n ", [keyName cStringUsingEncoding: NSUTF8StringEncoding]); NSString * values = (NSString *) value NSLog (@ "values is% @", values);}}

/ * * the method that connects the Bluetooth device to the external call * passes in the corresponding number of rows * /-(void) contentBlue: (int) row {[_ centerManager connectPeripheral:_ periperals] options:nil];}-(void) disContentBle {/ / critical disconnection Bluetooth notification should also stop if ((_ peripheralcharateristics disconnecting if) {[_ peripheral setNotifyValue:NO forCharacteristic:_sendtempcharateristic]; [self disconnectPeripheral:_peripheral]) }} / * * disconnect the ota * /-(void) disContentOtaBle {if (_ peripheralizable articnil & & _ sendotacharateristic disconnected nil) {[_ peripheral setNotifyValue:NO forCharacteristic:_sendotacharateristic]; [self disconnectPeripheral:_peripheral];}}-(void) disMainOtaBle {if (_ peripheralizable roomnil) {[self disconnectPeripheral:_peripheral];}}-(void) disconnectPeripheral: (CBPeripheral*) peripheral {[_ centerManager cancelPeripheralConnection:peripheral];}

/ / connected successfully-(void) centralManager: (CBCentralManager *) central didConnectPeripheral: (CBPeripheral *) peripheral {NSLog (@ "connected successfully"); if (peripheralsuccessfully connected nil) {/ / stop scanning this time for automatic connection [_ centerManager stopScan]; / / device name _ deviceName = peripheral.name; _ selectperipheral = peripheral; peripheral.delegate = self; / / re-scan service [peripheral discoverServices:nil];}}

/ / connection failure-(void) centralManager: (CBCentralManager *) central didFailToConnectPeripheral: (CBPeripheral *) peripheral error: (nullable NSError *) error {NSLog (@ "connection failure, failure reason:% @", error); NSString * disContentBlue = @ "discontentblue"; NSDictionary * blueDiscontent = [NSDictionary dictionaryWithObject:disContentBlue forKey:@ "disconnect"]; / / broadcast connection failure [[NSNotificationCenter defaultCenter] postNotificationName:@ "disNofiction" object:nil userInfo:blueDiscontent];}

/ / disconnect-(void) centralManager: (CBCentralManager *) central didDisconnectPeripheral: (CBPeripheral *) peripheral error: (NSError *) error {NSLog (@ "disconnect"); NSString * disContentBlue = @ "discontentblue"; / / _ blueiscon = @ "Disconnect"; NSDictionary * blueDiscontent = [NSDictionary dictionaryWithObject:disContentBlue forKey:@ "disconnect"]; / / failed to send broadcast connection [NSNotificationCenter defaultCenter] postNotificationName:@ "disNofiction" object:nil userInfo:blueDiscontent];}

/ / it will be called as soon as the service is scanned, and the peripheral is the peripheral of the service-(void) peripheral: (CBPeripheral *) peripheral didDiscoverServices: (NSError *) error {if (error) {NSLog (@ "scan service error reason:% @", error) } else {/ / get services scanned in peripherals for (CBService * service in peripheral.services) {/ / get services that need to be scanned, such as FFF0, such as printing temperature data / / printing all service / / finding required features from required services / / scanning features from peripheral services [peripheral discoverCharacteristics:nil forService:service];}

/ / it will be called as soon as the feature is scanned, and the peripherals and services are the peripherals and services where the feature is located-(void) peripheral: (CBPeripheral *) peripheral didDiscoverCharacteristicsForService: (nonnull CBService *) service error: (nullable NSError *) error {if (error) {NSLog (@ "scan feature error, error reason:% @", error) } else {/ / traverse the feature and get the desired feature for processing for (CBCharacteristic * characteristic in service.characteristics) {NSLog (@ "characteristic is% @", characteristic.UUID); / / if it is temperature data processing if ([characteristic.UUID isEqual:BOOT_TEMPVALUE_UUID]) {/ / print out all the feature information _ isconnected = true; _ peripheral = peripheral; _ sendtempcharateristic = characteristic; [peripheral setNotifyValue:YES forCharacteristic:characteristic] } / / if ota upgrades ota else if ([characteristic.UUID isEqual:BOOT_OTA_WIRTE_UUID]) {_ peripheral = peripheral; _ sendotacharateristic = characteristic; / / set notification [peripheral setNotifyValue:YES forCharacteristic:characteristic]; _ isOta = TRUE; [_ userDefaults saveOta:_isOta]; / / [_ setBool:_isOta forKey:@ "isOTA"]; NSString * s = @ "OTA"; NSDictionary * tempOta = [NSDictionary dictionaryWithObject:s forKey:@ "ota"] [[NSNotificationCenter defaultCenter] postNotificationName:@ "tempOTA" object:nil userInfo:tempOta];} / / CAL else if ([characteristic.UUID isEqual:BOOT_CAL_UUID]) {_ sendcalsetcharateristic = characteristic; [peripheral setNotifyValue:YES forCharacteristic:characteristic];} / / intervaltime else if ([characteristic.UUID isEqual:BOOT_INTERVALTIME_UUID]) {_ sendintervaltimecharateristic = characteristic; [peripheral setNotifyValue:YES forCharacteristic:characteristic];} / Tempunit else if ([characteristic.UUID isEqual:BOOT_TEMPUNIT_UUID]) {_ sendtempunitcharateristic = characteristic [peripheral setNotifyValue:YES forCharacteristic:characteristic];} / DFU else if ([characteristic.UUID isEqual:BOOT_DFU_UUID]) {_ senddfucharateristic = characteristic; [peripheral setNotifyValue:YES forCharacteristic:characteristic];} / / send string 'CR' maximum (3 bytes) else if ([characteristic.UUID isEqual:BOOT_CRSTRING_UUID]) {_ senddcrstrateristic = characteristic; [peripheral setNotifyValue:YES forCharacteristic:characteristic] } / / send string 'PD' sub-shutdown (3 bytes) else if ([characteristic.UUID isEqual:BOOT_OUTSTRING_UUID]) {_ senddoutstrateristic = characteristic; [peripheral setNotifyValue:YES forCharacteristic:characteristic];} else {}}

/ * set notification * /-(void) notifyCharacteristic: (CBPeripheral *) peripheral characteristic: (CBCharacteristic *) characteristic {[peripheral setNotifyValue:YES forCharacteristic:characteristic]; [_ centerManager stopScan];} / * cancel notification * /-(void) cancelNotifyCharacteristic: (CBPeripheral *) peripheral characteristic: (CBCharacteristic *) characteristic {[peripheral setNotifyValue:NO forCharacteristic:characteristic];}

/ * receive data parsing * /-(void) peripheral: (CBPeripheral *) peripheral didUpdateValueForCharacteristic: (CBCharacteristic *) characteristic error: (NSError *) error {/ / whether it is Ota if (! self.isSendOta) {if (self.readtempcharater = = characteristic) {NSString * tmpData = [self.cmUtil getTempTMWData:characteristic]; if (tmpDataroomnil) {/ / start processing data NSArray * data = [tmpData componentsSeparatedByString:@ ","]; TmpModel * tp = [TmpModel alloc] init]; tp.tmp = data [0] Tp.max = data [1]; tp.unit = data [2]; / / electricity tp.bat = data [3]; NSDictionary * tempDict = [NSDictionary dictionaryWithObject:tp forKey:@ "tempData"]; [[NSNotificationCenter defaultCenter] postNotificationName:@ "tempNofiction" object:nil userInfo:tempDict]; if ([tp.bat isEqual:@ "1"]) {/ / low power broadcast NSDictionary * LowDict = [NSDictionary dictionaryWithObject:tp forKey:@ "lowData"]; [NSNotificationCenter defaultCenter] postNotificationName:@ "lowNofiction" object:nil userInfo:LowDict] }

/ / = = write data block = / / * write send time * /-(void) writeIntervalTime: (NSString *) value periperalData: (CBPeripheral*) periperal {if }} / * write temperature unit * /-(void) writeTmpUnit: (NSString*) value periperalData: (CBPeripheral*) periperal {if }} / * write the Calvalue * /-(void) writeCalValue: (NSString *) value periperalData: (CBPeripheral*) periperal {if (valueworthiness. }} / * send Ota to cause the device to enter Ota * /-(void) writeDfuValue: (NSString *) value periperalData: (CBPeripheral*) periperal {if (valuefucharge.senddfucharaterportable equipment) {[self writeData:value forCharacteristic:self.senddfucharater periperalData:periperal] }} / * send Max Temp to achieve zeroing option * /-(void) writeClearValue: (NSString *) value periperalData: (CBPeripheral*) periperal {if (valueworthy, nilpotent, periperalizable, nilpotent self.sendclearcharaterial clearing nil) {[self writeData:value forCharacteristic:self.sendclearcharater periperalData:periperal] }} / * send shutdown option to achieve remote switch on and off * /-(void) writeCloseValue: (NSString *) value periperalData: (CBPeripheral*) periperal {if (valuewritten data processing * /-(void) writeData: (CBCharacteristic *) characteristic periperalData: (CBPeripheral*) periperal {NSData * data = [value dataUsingEncoding:NSUTF8StringEncoding]) If (characteristic.properties & CBCharacteristicPropertyWriteWithoutResponse) {[periperal writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];} else {[periperal writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];}}

This is the end of the article on "how to develop and implement Ble Bluetooth in IOS". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report