Skip to content

Commit

Permalink
Merge pull request #34 from semvis123/master
Browse files Browse the repository at this point in the history
[macOS] Improved exceptions
  • Loading branch information
Plutoberth authored Feb 16, 2021
2 parents 3c623a8 + 4af9946 commit e121514
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 47 deletions.
5 changes: 3 additions & 2 deletions Client/macos/MacOSBluetoothConnector.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@
#include <mutex>
#include <condition_variable>
#include <deque>
#include <future>

class MacOSBluetoothConnector final : public IBluetoothConnector
{
public:
MacOSBluetoothConnector();
~MacOSBluetoothConnector();
static void connectToMac(MacOSBluetoothConnector* MacOSBluetoothConnector) noexcept(false);
static void connectToMac(MacOSBluetoothConnector* MacOSBluetoothConnector, std::promise<void> connectPromise) noexcept(false);
virtual void connect(const std::string& addrStr) noexcept(false);
virtual int send(char* buf, size_t length) noexcept(false);
virtual int recv(char* buf, size_t length) noexcept(false);
Expand All @@ -31,5 +32,5 @@ class MacOSBluetoothConnector final : public IBluetoothConnector
private:
void *rfcommDevice;
void *rfcommchannel;
std::thread* uthread = NULL;
std::thread uthread;
};
27 changes: 20 additions & 7 deletions Client/macos/MacOSBluetoothConnector.mm
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ -(void)rfcommChannelData:(IOBluetoothRFCOMMChannel *)rfcommChannel data:(void *)
}


void MacOSBluetoothConnector::connectToMac(MacOSBluetoothConnector* macOSBluetoothConnector)
void MacOSBluetoothConnector::connectToMac(MacOSBluetoothConnector* macOSBluetoothConnector, std::promise<void> connectPromise)
{
// get device
IOBluetoothDevice *device = (__bridge IOBluetoothDevice *)macOSBluetoothConnector->rfcommDevice;
Expand All @@ -63,29 +63,42 @@ -(void)rfcommChannelData:(IOBluetoothRFCOMMChannel *)rfcommChannel data:(void *)
asyncCommDelegate->delegateCPP = macOSBluetoothConnector;
// try to open channel
if ( [device openRFCOMMChannelAsync:&channel withChannelID:rfcommChannelID delegate:asyncCommDelegate] != kIOReturnSuccess ) {
throw RecoverableException("Error - could not open the rfcomm.\n", true);
RecoverableException exc = RecoverableException("Could not open the rfcomm.", false);
std::exception_ptr excPtr = std::make_exception_ptr(exc);
connectPromise.set_exception(excPtr);
return;
}
// store the channel
macOSBluetoothConnector->rfcommchannel = (__bridge void*) channel;

macOSBluetoothConnector->running = true;

// tell the other tread that we are done connecting
connectPromise.set_value();

// keep thread running
while (macOSBluetoothConnector->running) {
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.1]];
}
}
void MacOSBluetoothConnector::connect(const std::string& addrStr){
// convert mac adress to nsstring
// convert mac address to nsstring
NSString *addressNSString = [NSString stringWithCString:addrStr.c_str() encoding:[NSString defaultCStringEncoding]];
// get device based on mac adress
// get device based on mac address
IOBluetoothDevice *device = [IOBluetoothDevice deviceWithAddressString:addressNSString];
// if device is not connected
if (![device isConnected]) {
[device openConnection];
}
// store the device in an variable
std::promise<void> connectPromise;
std::future<void> connectFuture = connectPromise.get_future();

// store the device in a variable
rfcommDevice = (__bridge void*) device;
uthread = new std::thread(MacOSBluetoothConnector::connectToMac, this);
uthread = std::thread(MacOSBluetoothConnector::connectToMac, this, std::move(connectPromise));

// wait till the device is connected
connectFuture.get();
}

int MacOSBluetoothConnector::recv(char* buf, size_t length)
Expand Down Expand Up @@ -136,7 +149,7 @@ -(void)rfcommChannelData:(IOBluetoothRFCOMMChannel *)rfcommChannel data:(void *)
{
running = false;
// wait for the thread to finish
uthread->join();
uthread.join();
// close connection
closeConnection();
}
Expand Down
72 changes: 36 additions & 36 deletions Client/macos/Main.storyboard
Original file line number Diff line number Diff line change
Expand Up @@ -131,55 +131,29 @@
<windowController id="B8D-0N-5wS" sceneMemberID="viewController">
<window key="window" title="SonyHeadphonesClient" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" visibleAtLaunch="NO" animationBehavior="default" id="IQv-IB-iLA">
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
<rect key="contentRect" x="0.0" y="995" width="432" height="205"/>
<rect key="contentRect" x="0.0" y="995" width="432" height="188"/>
<rect key="screenRect" x="0.0" y="0.0" width="1920" height="1200"/>
<value key="minSize" type="size" width="432" height="205"/>
<value key="maxSize" type="size" width="432" height="205"/>
<value key="minSize" type="size" width="432" height="188"/>
<value key="maxSize" type="size" width="432" height="188"/>
</window>
<connections>
<segue destination="XfG-lQ-9wD" kind="relationship" relationship="window.shadowedContentViewController" id="lIw-zv-7Km"/>
</connections>
</windowController>
<customObject id="Oky-zY-oP4" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="75.5" y="250"/>
<point key="canvasLocation" x="75" y="241"/>
</scene>
<!--View Controller-->
<scene sceneID="hIz-AP-VOD">
<objects>
<viewController id="XfG-lQ-9wD" customClass="ViewController" sceneMemberID="viewController">
<view key="view" id="m2S-Jp-Qdl">
<rect key="frame" x="0.0" y="0.0" width="423" height="205"/>
<rect key="frame" x="0.0" y="0.0" width="423" height="187"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="HVf-Ir-otU">
<rect key="frame" x="252" y="52" width="144" height="16"/>
<autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" lineBreakMode="clipping" title="Ambient Sound Level:" id="e00-m9-yK3">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="aux-7E-1O2">
<rect key="frame" x="392" y="52" width="33" height="16"/>
<autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" lineBreakMode="clipping" title="0" id="cRP-Qr-45A">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<slider verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="O6v-na-xL2">
<rect key="frame" x="18" y="44" width="230" height="28"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" flexibleMinY="YES"/>
<sliderCell key="cell" enabled="NO" state="on" alignment="left" maxValue="19" tickMarkPosition="below" numberOfTickMarks="20" allowsTickMarkValuesOnly="YES" sliderType="linear" id="q5G-me-sXi"/>
<connections>
<action selector="sendData:" target="XfG-lQ-9wD" id="5p1-OX-wuC"/>
</connections>
</slider>
<button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="aqv-Ws-wbl">
<rect key="frame" x="13" y="112" width="397" height="32"/>
<rect key="frame" x="13" y="94" width="397" height="32"/>
<autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMaxX="YES" flexibleMinY="YES"/>
<buttonCell key="cell" type="push" title="Connect to Bluetooth device" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="FJH-jh-019">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
Expand All @@ -190,7 +164,7 @@
</connections>
</button>
<textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" fixedFrame="YES" setsMaxLayoutWidthAtFirstLayout="YES" translatesAutoresizingMaskIntoConstraints="NO" id="T72-Gf-fe7">
<rect key="frame" x="18" y="147" width="387" height="38"/>
<rect key="frame" x="18" y="129" width="387" height="38"/>
<autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" selectable="YES" id="402-em-glw">
<font key="font" metaFont="system"/>
Expand All @@ -201,9 +175,9 @@ Source: https://github.com/Plutoberth/SonyHeadphonesClient</string>
</textFieldCell>
</textField>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="V6f-ZQ-bKY">
<rect key="frame" x="18" y="76" width="387" height="36"/>
<rect key="frame" x="18" y="78" width="387" height="16"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" lineBreakMode="clipping" title="Not connected" id="YBf-lp-MdN">
<textFieldCell key="cell" lineBreakMode="truncatingTail" truncatesLastVisibleLine="YES" title="Not connected" id="YBf-lp-MdN">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
Expand All @@ -220,6 +194,32 @@ Source: https://github.com/Plutoberth/SonyHeadphonesClient</string>
<action selector="sendData:" target="XfG-lQ-9wD" id="VS7-xg-wZb"/>
</connections>
</button>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="HVf-Ir-otU">
<rect key="frame" x="252" y="46" width="144" height="16"/>
<autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" lineBreakMode="clipping" title="Ambient Sound Level:" id="e00-m9-yK3">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="aux-7E-1O2">
<rect key="frame" x="392" y="46" width="33" height="16"/>
<autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" lineBreakMode="clipping" title="0" id="cRP-Qr-45A">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<slider verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="O6v-na-xL2">
<rect key="frame" x="18" y="38" width="230" height="28"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" flexibleMinY="YES"/>
<sliderCell key="cell" enabled="NO" state="on" alignment="left" maxValue="19" tickMarkPosition="below" numberOfTickMarks="20" allowsTickMarkValuesOnly="YES" sliderType="linear" id="q5G-me-sXi"/>
<connections>
<action selector="sendData:" target="XfG-lQ-9wD" id="5p1-OX-wuC"/>
</connections>
</slider>
</subviews>
</view>
<connections>
Expand All @@ -232,7 +232,7 @@ Source: https://github.com/Plutoberth/SonyHeadphonesClient</string>
</viewController>
<customObject id="rPt-NT-nkU" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="75.5" y="715.5"/>
<point key="canvasLocation" x="75.5" y="706.5"/>
</scene>
</scenes>
</document>
13 changes: 11 additions & 2 deletions Client/macos/ViewController.mm
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,24 @@ - (void)viewDidLoad {
}

- (void)displayError:(RecoverableException)exc {
NSString *errorText;
if (exc.shouldDisconnect){
bt.disconnect();
[ANCSlider setEnabled:FALSE];
[focusOnVoice setEnabled:FALSE];
[connectButton setTitle:@"Connect to Bluetooth device"];
statusItem.button.image = [NSImage imageNamed:@"NSRefreshTemplate"];
[connectedLabel setStringValue:[@"Unexpected error occurred and disconnected: \n" stringByAppendingString:@(exc.what())]];
errorText = @"Unexpected error occurred and disconnected.";
} else {
[connectedLabel setStringValue:[@"Unexpected error occurred: \n" stringByAppendingString:@(exc.what())]];
errorText = @"Unexpected error occurred.";
}
[connectedLabel setStringValue: errorText];
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:errorText];
[alert setInformativeText:@(exc.what())];
[alert addButtonWithTitle:@"Ok"];
[alert runModal];

}

- (void)statusItemClick:(id)sender {
Expand Down Expand Up @@ -78,6 +86,7 @@ - (IBAction)connectToDevice:(id)sender {
bt.connect([[device addressString] UTF8String]);
} catch (RecoverableException& exc) {
[self displayError:exc];
return;
}
// give it some time to connect
int timeout = 5;
Expand Down

0 comments on commit e121514

Please sign in to comment.