WiFi通訊是指手機經過WiFi與外部設備創建鏈接,並與外部設備進行交互、通訊。手機與外部設備的WiFi通訊一般是使用Socket來實現的,在這裏先介紹一個第三方Socket庫(CocoaAsyncSocket)來實現WiFi通訊。app
CocoaAsyncSocket支持TCP和UDP,其中:AsyncSocket類是支持TCP的;AsyncUdpSocket類是支持UDP的。本文是創建在硬件經過UDP廣播包廣播自身信息,手機與硬件之間經過TCP鏈接傳輸數據。socket
首先,經過手動鏈接手機WiFi至外部設備,此時能夠獲取到外部WiFi的一些信息:atom
#import <UIKit/UIKit.h> @interface ViewController : UIViewController typedef void (^udpSocketBlock)(NSDictionary* dic,NSError* err);// block用於硬件返回信息的回調 @property (nonatomic,copy) udpSocketBlock udpSocketBlock; - (void)sendUdpBoardcast:(udpSocketBlock)block; @end
#import "ViewController.h" #import <AsyncSocket.h> #import <AsyncUdpSocket.h> @interface ViewController ()<AsyncSocketDelegate,AsyncUdpSocketDelegate> @property (nonatomic,strong) AsyncUdpSocket *udpSocket; @property (nonatomic,strong) AsyncSocket *socket; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)sendUdpBoardcast:(udpSocketBlock)block{ self.udpSocketBlock = block; if(!_udpSocket)_udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self]; NSData *data = [NSData data];// 此處data是根據硬件要求傳參數 UInt16 port = 34343;// 此處具體指需詢問硬件工程師 [self.udpSocket enableBroadcast:YES error:NULL]; [_udpSocket sendData:data toHost:@"255.255.255.255" port:port withTimeout:-1 tag:0];// 由於不知道具體的ip地址,因此host採用受限廣播地址 } - (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{ // data 接收到的外部設備返回的數據 id result = [self unpackageMessage:data]; // 對數據進行處理,此處調用的 - (id)unpackageMessage:(NSData *)data ;是根據與硬件方面協商的數據格式進行的數據處理 if ([[result valueForJSONKey:@"typeid"] isEqualToString:@"xxxx"]) { self.udpSocketBlock([result valueForJSONKey:@"data"],nil); } // 判斷的到的數據是否爲咱們須要的數據 return YES; // 發現設備後,則關閉發現通道 return NO; // 不關閉發現通道,一直處於發現狀態 } #pragma mark - udpSocket -(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{ }
經過調用該方法,能夠獲得外部設備返還的WiFi信息:spa
[self sendUdpBoardcast:^(NSDictionary *dic, NSError *err) { // dic爲硬件返回的參數 }];
獲取硬件參數以後,須要確認手機是否已於硬件鏈接,直接調用方法code
- (BOOL)isConnected;
若未鏈接,則需創建手機和硬件之間的socket鏈接:orm
- (BOOL)connectToHost:(NSString*)hostname onPort:(UInt16)port error:(NSError **)errPtr; // hostname、port均爲硬件返回的
CocoaAsyncSocket提供了寫入數據和讀取數據的方法:ip
// 數據的寫入 - (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag; // 數據的讀取 - (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag;
數據寫入具體格式須要根據硬件要求來決定,這裏提供幾種經常使用的數據類型轉換方法以供參考:unicode
-(NSData *)converHexStrToData:(NSString *)hexString { NSMutableData *data = [[NSMutableData alloc] init]; unsigned char whole_byte; char byte_chars[3] = {'\0','\0','\0'}; if (hexString.length%2) { //防止丟失半個byte hexString = [@"0" stringByAppendingString:hexString]; } int i; for (i = 0; i < [hexString length]/2; i++) { byte_chars[0] = [hexString characterAtIndex:i * 2]; byte_chars[1] = [hexString characterAtIndex:i * 2 + 1]; whole_byte = strtol(byte_chars, NULL, 16); [data appendBytes:&whole_byte length:1]; } return data; }
-(NSString *) converDataToHexString:(NSData *)data { if (data == nil) { return nil; } NSMutableString* hexString = [NSMutableString string]; const unsigned char *p = [data bytes]; for (int i=0; i < [data length]; i++) { [hexString appendFormat:@"%02x", *p++]; } return hexString; }
-(NSString *)stringFromHexString:(NSString *)hexString { char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1); bzero(myBuffer, [hexString length] / 2 + 1); for (int i = 0; i < [hexString length] - 1; i += 2) { unsigned int anInt; NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)]; NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr]; [scanner scanHexInt:&anInt]; myBuffer[i / 2] = (char)anInt; } NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4]; return unicodeString; }