1 前言
在這個系列之前的部落格中,我研究覺得在iOS未越獄的情況下,無法使用藍牙來控制EV3,編寫類似Commander的程式。但,最近和網友的研究發現,通過External Accessory 來實作藍牙的傳輸比想象的簡單。MFI協定的問題比想象的容易很多,關鍵在于我們可以擷取EV3的MFI協定字元串。接下來讓我們看看是怎麼實作的。
開源代碼:點選打開連結
2 具體代碼實作
首先Apple官方有個關于External Accessory的demo 叫EAdemo,大家可以下下來,然後在plist檔案中改一下協定字元串,如下:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIyVGduV2QvwVe0lmdhJ3ZvwFM38CXlZHbvN3cpR2Lc1TPB10QGtWUCpEMJ9CXsxWam9CXwADNvwVZ6l2c052bm9CXUJDT1wkNhVzLcRnbvZ2LcJnVHRmdKNjW1ljMjZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39zN3ETMxkjMzEDMzETM0EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
然後運作一下,我們就可以直接連上EV3了。
有了這個基礎,我們研究一下實作原理。
Step 1:添加ExternalAccessory.Framework 這一步顯而易見。
Step 2:連接配接到EV3
- (void)connectEV3
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accessoryDidConnect:) name:EAAccessoryDidConnectNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accessoryDidDisconnect:) name:EAAccessoryDidDisconnectNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionDataReceived:) name:EADSessionDataReceivedNotification object:nil];
[[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];
self.sessionController = [EADSessionController sharedController];
accessoryList = [[NSMutableArray alloc] initWithArray:[[EAAccessoryManager sharedAccessoryManager] connectedAccessories]];
NSLog(@"accessory list:%@",accessoryList);
if(accessoryList != nil){
[self.sessionController setupControllerForAccessory:[accessoryList firstObject]
withProtocolString:@"COM.LEGO.MINDSTORMS.EV3"];
isConnected = [self.sessionController openSession];
}
}
- (void)accessoryDidConnect:(NSNotification *)notification {
NSLog(@"EV3 did connect!");
EAAccessory *connectedAccessory = [[notification userInfo] objectForKey:EAAccessoryKey];
[self.sessionController setupControllerForAccessory:connectedAccessory
withProtocolString:@"COM.LEGO.MINDSTORMS.EV3"];
isConnected = [self.sessionController openSession];
}
在這裡我也直接使用了EADemo上的代碼來分析。 由于官方例子的EADSessionController把資料傳輸這部分内容做得很好,我們直接拿來用就好了。 基本過程就是建立執行個體,建立controller,然後openSession。
Step 3:控制EV3 直接使用之前已經編寫好的EV3DirectCommander來實作 簡單的例子如下:
- (IBAction)go:(id)sender {
if (isConnected) {
NSData *data = [EV3DirectCommander turnMotorAtPort:EV3OutputPortB power:50];
[[EADSessionController sharedController] writeData:data];
isGo = YES;
}
}
3 為什麼用藍牙?
顯然之前用Wifi得買額外裝置,還得連wifi太麻煩,直接用藍牙省事很多,可以做得更好的效果!嘿嘿,大家可以自己搞個Commander了!更強大的Commander!