iOS中的WiFi与硬件通信
WiFi通信是指手机通过WiFi与外部设备建立连接,并与外部设备进行交互、通信。手机与外部设备的WiFi通信通常是使用Socket来实现的,在这里先介绍一个第三方Socket库(CocoaAsyncSocket)来实现WiFi通信。
CocoaAsyncSocket支持TCP和UDP,其中:
AsyncSocket类是支持TCP的;
AsyncUdpSocket类是支持UDP的。
本文是建立在硬件通过UDP广播包广播自身信息,手机与硬件之间通过TCP连接传输数据。
WiFi连接的建立
首先,通过手动连接手机WiFi至外部设备,此时可以获取到外部WiFi的一些信息:
#import <UIKit/UIKit.h>@interface ViewController : UIViewControllertypedef 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信息:
[self sendUdpBoardcast:^(NSDictionary *dic, NSError *err) {// dic为硬件返回的参数
}];
获取硬件参数之后,需要确认手机是否已于硬件连接,直接调用方法
- (BOOL)isConnected;
若未连接,则需建立手机和硬件之间的socket连接:
- (BOOL)connectToHost:(NSString*)hostname onPort:(UInt16)port error:(NSError **)errPtr;
// hostname、port均为硬件返回的
数据的写入和读取
CocoaAsyncSocket提供了写入数据和读取数据的方法:
// 数据的写入
- (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
// 数据的读取
- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag;
数据写入具体格式需要根据硬件要求来决定,这里提供几种常用的数据类型转换方法以供参考:
- 十六进制字符串转NSData
-(NSData *)converHexStrToData:(NSString *)hexString {NSMutableData *data = [[NSMutableData alloc] init];unsigned char whole_byte;char byte_chars[3] = {'\0','\0','\0'};if (hexString.length%2) {//防止丢失半个bytehexString = [@"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; }
- NSData转十六进制字符串
-(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; }
iOS中的WiFi与硬件通信相关推荐
- iOS中获取WiFi的SSID(CNCopySupportedInterfaces())
获取当前设备连接WiFi: ios5之前可以通过读取配置文件获取,ios5以后苹果修改wifi列表文件位置,只有root权限才可以读取. ios4:/System/Library/SystemConf ...
- java中实现与USB硬件通信
目前在网络上查询java与usb的设备通信资源都非常的少大多都来自一个05年的文章,本人也摘取了网上的例子,例子中直接运行也出现了一些问题,经过debug还是可以直接在windows上直接使用java ...
- iOS音频编程之实时语音通信
http://blog.csdn.net/it_yangjing/article/details/51909991 在CSDN上显示的代码格式不全,在github blog地址显示正确 iOS音频编程 ...
- ios中常用的第三方库
下拉刷新 EGOTableViewPullRefresh – 最早的下拉刷新控件. SVPullToRefresh – 下拉刷新控件. MJRefresh – 仅需一行代码就可以为UITableVie ...
- Audio Unit: iOS中最底层最强大的音频控制API
阅读的前提: Audio Session基础(Audio Session) Core Audio基本数据结构(Core Audio) 音视频基础知识 C/C++ 简单数据结构,函数使用 以下概念是文中 ...
- Audio Unit: iOS中最底层最强大音频控制API
阅读前提: Audio Session基础(Audio Session) Core Audio基本数据结构(Core Audio) 音视频基础知识 C/C++ 简单数据结构,函数使用 以下概念是文中常 ...
- iphone smtp服务器没有响应,电子邮件卡在iPhone或iPad上的发件箱?如何修复iOS中的未发送邮件 | MOS86...
您曾经在iOS中发送电子邮件,只能将信息卡在iPhone,iPad或iPod touch的邮件应用发件箱中?你知道这是什么时候发生的,因为在iOS的Mail应用程序的底部,状态栏在iOS中显示1个未发 ...
- iOS 中KVC、KVO、NSNotification、delegate 总结及区别
iOS 中KVC.KVO.NSNotification.delegate 总结及区别 1.KVC,即是指 NSKeyValueCoding,一个非正式的Protocol,提供一种机制来间接访问对象的属 ...
- linux中关于wifi函数,wifi详解(五)
user interface Android WiFiService WPA_Supplicant DHD Driver Dongle Binary BCM43xxHardware 蓝色:需要修改 黑 ...
最新文章
- Meta旨在打造世界上最快的人工智能超级计算机
- C++中创建二维数组的几种方法
- 【聊透SpringMVC】自学java和三大框架要多久
- WCF 第五章 并发和实例(服务行为)
- Aloy:风格化角色的设计和建模
- python假设检验平均_Python|Excel|SPSS|R|Stata|Eviews统计数据假设检验T|F|卡方检验
- 解放你的双手-Sql Server 2000智能提示工具[破解版]
- Linux保护文件实现,Linux完整性保护机制模块实现分析(1)
- Linux系统安装与使用基础实验报告
- 固态硬盘系统经常假死_使用固态硬盘装Win10经常假死怎么解决
- CSP 202009-4 星际旅行
- MapProxy的部署与TMS地图服务代理
- 应各位朋友的要求,贴出当年写的考研经历文章,希望能再给准备考研的朋友一些启发吧
- 申请苹果开发者账号(2016最新版)
- c++调用opencv实现图片叠加以及添加水印效果
- RabbitMQ None of the specified endpoints were reachable 错误 解决方案
- 详解ShellShock 漏洞复现原理,内附ShellShock的修复方法
- 可恶的as3.0,下载一个所谓的绿色flash cs5,竟然提示JAVA运行时环境初始化错误,请重新安flash
- 苹果打字怎么换行_iPhone实用小技巧,安卓转苹果的同学看完收获尤其大
- 迷宫算法总结(最短路径)BFS宽度优先