? ? ? ?其實(shí)整個(gè)項(xiàng)目最不好理解的就是app端和硬件的交互怖竭,因?yàn)榭蛻舳撕苌倩厝ソ佑|底層的東西毙替,所以開始會(huì)覺得不知所措可岂,接下跟大家分享一下具體流程错敢。
? ? ? ?首先,我們接入了一個(gè)第三方缕粹,叫ESPTouch,把客戶端所連接的WIFI信息發(fā)送給硬件稚茅,需要把WIFI的SSID和SECURT發(fā)送給硬件,用到的朋友可以去官網(wǎng)下個(gè)demo平斩。
// 獲取WIFI信息
#import <SystemConfiguration/CaptiveNetwork.h>
- (NSDictionary *)WIFIDic{
NSArray *ifs = (id)CFBridgingRelease(CNCopySupportedInterfaces());
NSLog(@"%s: Supported interfaces: %@", __func__, ifs);
for (NSString *ifnam in ifs) {
_WIFIDic = (id)CFBridgingRelease(CNCopyCurrentNetworkInfo((CFStringRef)ifnam));
//? ? ? ? NSLog(@"%s: %@ => %@", __func__, ifnam, _WIFIDic);
if (_WIFIDic && [_WIFIDic count]) {
break;
} ??}
NSLog(@"wifi信息? %@? ",_WIFIDic);
return _WIFIDic ; ? }
然后峰锁,在鏈接成功的方法中發(fā)送UDP廣播,給大家推薦一個(gè)很好用的第三方pod "CocoaAsyncSocket";
.h文件中:
<GCDAsyncUdpSocketDelegate>
self.updSuccess = NO;
self.udpSocket = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError * error = nil;
//? ? [_udpSocket bindToPort:46000 error:&error];? //? 綁定端口 若客戶端只向服務(wù)端發(fā)送消息而不用接收到其他的udp消息就可以不用綁定端口
[self.udpSocket enableBroadcast:YES error:&error]; //? 啟用廣播
if (error) {//監(jiān)聽錯(cuò)誤打印錯(cuò)誤信息
NSLog(@"error:%@",error);
}else {//監(jiān)聽成功則開始接收信息
[_udpSocket receiveOnce:&error];
}
NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
if (!self.updTimers) {
self.updTimers = [NSTimer scheduledTimerWithTimeInterval:2 repeats:YES block:^(NSTimer * _Nonnull timer) {
if (self.updSuccess == YES) {
[self.updTimers invalidate];
self.updTimers = nil;
}else{
//data 需要發(fā)送的信息 ?host IP地址 ?port 端口號(hào)
[_udpSocket sendData:data toHost:host port:port withTimeout:10 tag:0];
} ? ?}]; ? ?}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag{
NSLog(@"發(fā)送信息成功");
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{
NSLog(@"發(fā)送信息失敗 %@",error);
}
#pragma mark? --------------------UDP廣播的回調(diào)----------------------------
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{
self.updSuccess = YES;
NSString * ip = [GCDAsyncUdpSocket hostFromAddress:address];
uint16_t port = [GCDAsyncUdpSocket portFromAddress:address];
//? ? NSString * message = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if (!data || [data length] == 0) {
return;
}
// 十六進(jìn)制轉(zhuǎn)字符串
NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
[data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
unsigned char *dataBytes = (unsigned char*)bytes;
for (NSInteger i = 0; i < byteRange.length; i++) {
NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
if ([hexStr length] == 2) {
[string appendString:hexStr];
} else {
[string appendFormat:@"0%@", hexStr]; } ?}
}];
NSLog(@"接收到服務(wù)端的消息:ip:%@? port:%d? message:%@",ip,port,string);
if ([self.delegate respondsToSelector:@selector(clientSocketDidReceiveMessage:andPort:withHost:)]) {
[self.delegate clientSocketDidReceiveMessage:string andPort:port withHost:ip];
}
[self.udpSocket receiveOnce:nil];
}
這就好了双戳,UPD完成虹蒋,,然后在回調(diào)方法中發(fā)送TC:
.h文件中:<GCDAsyncSocketDelegate>
//將GCDAsynSocket設(shè)置為全局變量
self.tcpSocket = [[GCDAsyncSocket alloc] initWithDelegate:self? delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
[self.tcpSocket connectToHost:servesIP onPort:port error:&error];
[self.tcpSocket writeData:[message dataUsingEncoding:NSUTF8StringEncoding] withTimeout:5 tag:101];
[self.tcpSocket readDataWithTimeout:5 tag:0];
//withTimeout: 超時(shí)時(shí)間 -1? 表示不超時(shí)
//tag: 一個(gè)標(biāo)識(shí)
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
NSLog(@"鏈接成功");
}
// 服務(wù)器返回?cái)?shù)據(jù)
- (void)socket:(GCDAsyncSocket*)sock didReadData:(NSData *)data withTag:(long)tag {
self.tcpIsSuccess = YES;
// 十六進(jìn)制轉(zhuǎn)字符串
NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
[data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
unsigned char *dataBytes = (unsigned char*)bytes;
for (NSInteger i = 0; i < byteRange.length; i++) {
NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
if ([hexStr length] == 2) {
[string appendString:hexStr];
} else {
[string appendFormat:@"0%@", hexStr]; ? } ? } ? ?}];
[self.delegate tcpSocketDicReceiveMessage:string];
[self.tcpSocket readDataWithTimeout:5 tag:0];
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
NSLog(@"已經(jīng)斷開連接!");
if (self.tcpIsSuccess == NO) {
[self.delegate tcpConnectError]; ? }
[self.tcpSocket readDataWithTimeout:5 tag:0]; ? }
如果飒货,回調(diào)成功魄衅,恭喜你,app與硬件交互完成了塘辅。