Bluetooth-Progammierung unter MacOS

MAC OSX spezifisches Forum
Beiträge, die plattformübergreifend sind, gehören ins 'Allgemein'-Forum.
ccode_new
Beiträge: 1214
Registriert: 27.11.2016 18:13
Wohnort: Erzgebirge

Bluetooth-Progammierung unter MacOS

Beitrag von ccode_new »

Hallo Leute,

hat sich jemand schon mal mit der Core Bluetooth - API befasst.

Ich suche native MacOS-API-Lösungen.

Danke!
Betriebssysteme: div. Windows, Linux, Unix - Systeme

no Keyboard, press any key
no mouse, you need a cat
ccode_new
Beiträge: 1214
Registriert: 27.11.2016 18:13
Wohnort: Erzgebirge

Re: Bluetooth-Progammierung unter MacOS

Beitrag von ccode_new »

Wenn sich mal jemand schlau machen möchte:

https://developer.apple.com/documentation/iobluetooth

Ist mal etwas Anderes als Linux/Windows - API.

Aber mal schauen was so geht.
Betriebssysteme: div. Windows, Linux, Unix - Systeme

no Keyboard, press any key
no mouse, you need a cat
ccode_new
Beiträge: 1214
Registriert: 27.11.2016 18:13
Wohnort: Erzgebirge

Re: Bluetooth-Progammierung unter MacOS

Beitrag von ccode_new »

Ich stehe hier noch stark am Anfang.

Erstmal muss ich das Ganze PureBasic - Interface - Gedöns richtig verstehen.

Dann muss ich die Sache mit der OOP mit Mac richtig verstehen.

Und außerdem:

Kann man CocoaMessage() außerhalb des Cocoa-Frameworks nutzen ?

ImportC "/System/Library/Frameworks/IOBluetooth.framework/Versions/A/IOBluetooth"
Dieses/ bzw. CoreBluetooth würde ich gerne nutzen.

Ich bin bei Mac - Api noch ganz am Anfang meines Wissens.
Betriebssysteme: div. Windows, Linux, Unix - Systeme

no Keyboard, press any key
no mouse, you need a cat
ccode_new
Beiträge: 1214
Registriert: 27.11.2016 18:13
Wohnort: Erzgebirge

Re: Bluetooth-Progammierung unter MacOS

Beitrag von ccode_new »

Ich führe meinen Monolog weiter.

Wie bekomme ich so etwas zum laufen:

CocoaMessage(0, IOBluetoothDevice, "pairedDevices:")

???

Swift-Code

Code: Alles auswählen

import IOBluetooth

class BluetoothDevices {
  func pairedDevices() {
    print("Bluetooth devices:")
    guard let devices = IOBluetoothDevice.pairedDevices() else {
      print("No devices")
      return
    }
    for item in devices {
      if let device = item as? IOBluetoothDevice {
        print("Name: \(device.name)")
        print("Paired?: \(device.isPaired())")
        print("Connected?: \(device.isConnected())")
      }
    }
  }
}

var bt = BluetoothDevices()
bt.pairedDevices()
Betriebssysteme: div. Windows, Linux, Unix - Systeme

no Keyboard, press any key
no mouse, you need a cat
ccode_new
Beiträge: 1214
Registriert: 27.11.2016 18:13
Wohnort: Erzgebirge

Re: Bluetooth-Progammierung unter MacOS

Beitrag von ccode_new »

Ich könnte Hilfe gebrauchen.

Das hier:

Code: Alles auswählen

ImportC "/System/Library/Frameworks/IOBluetooth.framework/Versions/A/IOBluetooth"
  IOBluetoothLocalDeviceAvailable()
EndImport

If IOBluetoothLocalDeviceAvailable()
  
  CocoaMessage(@inquiry, 0, "IOBluetoothDeviceInquiry inquiryWithDelegate:")
  
  Debug inquiry
  
  status = CocoaMessage(0, inquiry,	"start")
  
  Debug status
  
  If status > 0
    CocoaMessage(0, inquiry, "retain")
    busy = #True
  Else
    Debug "Keine Suche möglich!"
  EndIf
  
EndIf
ist mein Start, doch das Ende ist noch nicht in Sicht.

Hier mal zum fleißigen Übersetzen:

Code: Alles auswählen

#import <unistd.h>

#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#import <CoreFoundation/CoreFoundation.h>
#import <CoreServices/CoreServices.h>

#import <IOBluetooth/objc/IOBluetoothDeviceInquiry.h>
#import <IOBluetooth/IOBluetoothUserLib.h>
#import <IOBluetoothUI/IOBluetoothUIUserLib.h>

#import "BluetoothExplorerWindow.h"

//===========================================================================================================================
// Globals
//===========================================================================================================================

NSSize	gCellSize;
NSSize	gCellImageSize;

//===========================================================================================================================
//	BluetoothExplorerWindow
//===========================================================================================================================

@implementation BluetoothExplorerWindow

#if 0
#pragma mark -
#pragma mark === NSApp Delegate methods and routines ===
#endif

//===========================================================================================================================
//	- (void)awakeFromNib
//===========================================================================================================================

- (void)awakeFromNib
{
	gCellSize 		= NSMakeSize( 329, 70 );
	gCellImageSize	= NSMakeSize( 48, 48 );

    [NSApp	setDelegate:self];
    
    // Setup the button matrix to have zero buttons since we cannot do this in IB.
    [_buttonMatrix removeColumn:0];
    [_buttonMatrix renewRows:0 columns:1];
    [_buttonMatrix sizeToCells];
	[_buttonMatrix setCellSize:gCellSize];
	[_buttonMatrix setDoubleAction:@selector( deviceListDoubleAction )];
	
    [_matrixView setNeedsDisplay:TRUE];

	if( IOBluetoothValidateHardware( nil ) != kIOReturnSuccess )
	{
		[NSApp terminate:self];
	}
}


#if 0
#pragma mark -
#pragma mark === IBAction Actions ===
#endif

//===========================================================================================================================
// clearFoundDevices
//===========================================================================================================================

-(IBAction)clearFoundDevices:(id)sender
{
	int numberOfRows = [_buttonMatrix numberOfRows];

	while( numberOfRows > 0 )
	{
		[_buttonMatrix removeRow:0];
	
		--numberOfRows;
	}

	[_foundDevices removeAllObjects];
	[_foundDevices release];
	_foundDevices = NULL;
}

//===========================================================================================================================
//	- (IBAction)handleSearchButton:(id)sender
//===========================================================================================================================

- (IBAction) handleSearchButton:(id)sender
{
  
	IOReturn ret;
	
	if( !_busy )
	{
		if( IOBluetoothLocalDeviceAvailable() == FALSE )
		{
			return;
		}
		
		[_searchButton 	setEnabled:TRUE];
		ret = [self startInquiry];
	}
	else
	{
		[_searchButton 	setEnabled:FALSE];
		ret = [self stopInquiry];
	}	
}

#if 0
#pragma mark -
#pragma mark === Start and Stop Inquiry ===
#endif

//===========================================================================================================================
// startInquiry
//===========================================================================================================================

-(IOReturn)startInquiry
{
	IOReturn	status;

	[self	stopInquiry];

	_inquiry = [IOBluetoothDeviceInquiry	inquiryWithDelegate:self];
	
	status = [_inquiry	start];
	if( status == kIOReturnSuccess )
	{
		[_inquiry	retain];
		[_progressBar startAnimation:self];
		[_searchButton 	setTitle:@"Stop"];

		_busy = TRUE;
	}
	else
	{
		[_messageText setObjectValue:@"Idle (Search Failed)."];
	}
	
	return( status );
}

//===========================================================================================================================
// stopInquiry
//===========================================================================================================================
- (IOReturn) stopInquiry
{
	IOReturn ret = kIOReturnNotOpen;
	
	if( _inquiry )
	{
		ret = [_inquiry stop];
		[_inquiry release];
		_inquiry = nil;
	}
	
	return ret;
}

#if 0
#pragma mark -
#pragma mark === IOBluetoothDeviceInquiry Delegate Messages ===
#endif

//===========================================================================================================================
// deviceInquiryStarted
//===========================================================================================================================

- (void)	deviceInquiryStarted:(IOBluetoothDeviceInquiry*)sender
{
	[_messageText 	setObjectValue:@"Searching for Devices..."];
	[_progressBar 	startAnimation:self];
}

//===========================================================================================================================
// deviceInquiryDeviceFound
//===========================================================================================================================

- (void)	deviceInquiryDeviceFound:(IOBluetoothDeviceInquiry*)sender	device:(IOBluetoothDevice*)device
{
	[self addDeviceToList:device];
	[_messageText setObjectValue:[NSString stringWithFormat:@"Found %d devices...", [[sender foundDevices] count]]];
}

//===========================================================================================================================
// deviceInquiryUpdatingDeviceNamesStarted
//===========================================================================================================================

- (void)	deviceInquiryUpdatingDeviceNamesStarted:(IOBluetoothDeviceInquiry*)sender	devicesRemaining:(int)devicesRemaining
{
	[_messageText setObjectValue:[NSString stringWithFormat:@"Refreshing %d device names...", devicesRemaining]];
}

//===========================================================================================================================
// deviceInquiryDeviceNameUpdated
//===========================================================================================================================

- (void)	deviceInquiryDeviceNameUpdated:(IOBluetoothDeviceInquiry*)sender	device:(IOBluetoothDevice*)device devicesRemaining:(int)devicesRemaining
{
	[_messageText setObjectValue:[NSString stringWithFormat:@"Refreshing %d device names...", devicesRemaining]];
	
	[self	updateDeviceInfoInList:device];
}

//===========================================================================================================================
// deviceInquiryComplete
//===========================================================================================================================

- (void)	deviceInquiryComplete:(IOBluetoothDeviceInquiry*)sender	error:(IOReturn)error	aborted:(BOOL)aborted
{
	if( aborted )
	{
		[_messageText	setObjectValue:@"Idle (inquiry stopped)."];
	}
	else
	{
		[_messageText	setObjectValue:@"Idle (inquiry complete)."];
	}

	[_progressBar 	stopAnimation:self];
	[_searchButton 	setTitle:@"Search"];
	[_searchButton 	setEnabled:TRUE];

	_busy = FALSE;
}

#if 0
#pragma mark -
#pragma mark === UI Stuff ===
#endif

//===========================================================================================================================
//	deviceListDoubleAction
//===========================================================================================================================

- (void)deviceListDoubleAction
{
	NSBeep();
}

//===========================================================================================================================
//	addDeviceToList
//===========================================================================================================================

-(void)addDeviceToList:(IOBluetoothDevice*)inDevice
{
    id								newButton;
	const BluetoothDeviceAddress*	addressPtr			= [inDevice getAddress];
    id 								buttonIcon			= NULL;
    NSString*						deviceCODString		= nil;
    NSString*						deviceAddressString	= nil;
	NSString*						deviceNameString	= [inDevice getName];
	NSString*						connectionInfo		= nil;

	// Get the device address and deal with the name.

	if( addressPtr )
	{
		deviceAddressString = [NSString stringWithFormat:@"%02x-%02x-%02x-%02x-%02x-%02x",	addressPtr->data[0],
																							addressPtr->data[1],
																							addressPtr->data[2],
																							addressPtr->data[3],
																							addressPtr->data[4],
																							addressPtr->data[5]];
	}
	
	if( !deviceNameString )
	{
		deviceNameString = @"<Name not yet known>";
	}
	
	// Make sure we don't already have this device in the list.
	
	if( ![self saveNewDeviceIfAcceptable:inDevice] )
	{
		// Already have seen it. Bail.
	
		return;
	}
	
	// Create COD info string.

	deviceCODString = [NSString stringWithFormat:@"Major Class: %@ (0x%02x)\nMinor Class: %@ (0x%02x)",
													GetStringForMajorCOD( [inDevice getDeviceClassMajor] ),
													[inDevice getDeviceClassMajor],
													GetStringForMinorCOD( [inDevice getDeviceClassMajor], [inDevice getDeviceClassMinor] ),
													[inDevice getDeviceClassMinor]];
	
	// If there is a connection in place shows the connection handle:
	if ( [inDevice isConnected] )
	{
		connectionInfo =  [NSString stringWithFormat:@"Connected, Connection Handle 0x%04x", [inDevice getConnectionHandle]];
	}
	else
	{
		connectionInfo =  [NSString stringWithFormat:@"Not Connected"];
	}

	
	// load up an image for the class of device which we have found.
	
	buttonIcon = [NSImage imageNamed:@"BluetoothLogo.tiff"];
	[buttonIcon setScalesWhenResized:TRUE];
	[buttonIcon setSize:gCellImageSize];

	// Make space for and get a button for the new device.
	
	[_buttonMatrix addRow];	
	newButton = [_buttonMatrix cellAtRow:[_buttonMatrix numberOfRows]-1 column:0];
	if( !newButton ) return;

	// Set the button's attributes.

	[newButton setImage:buttonIcon];
	[newButton setTitle:[NSString stringWithFormat:@"%@ / %@\n%@\n%@", [deviceAddressString uppercaseString], deviceNameString, deviceCODString, connectionInfo]];
	[newButton setTag:(int)inDevice];

	// make it the right type of button and update the display.
	
	[_buttonMatrix sizeToCells];
	[_matrixView setNeedsDisplay:TRUE];
}

//===========================================================================================================================
// updateDeviceInfoInList
//===========================================================================================================================

-(void)updateDeviceInfoInList:(IOBluetoothDevice *)inDevice
{
	id button = [_buttonMatrix cellWithTag:(int)inDevice];
	if( button )
	{
		NSString* deviceCODString 					= nil;
		const BluetoothDeviceAddress*	addressPtr	= [inDevice getAddress];
		NSString* deviceAddressString				= nil;
		NSString* name								= [inDevice getName];
		NSString* connectionInfo = nil;

		deviceCODString = [NSString stringWithFormat:@"Major Class: %@ (0x%02x)\nMinor Class: %@ (0x%02x)",
													GetStringForMajorCOD( [inDevice getDeviceClassMajor] ),
													[inDevice getDeviceClassMajor],
													GetStringForMinorCOD( [inDevice getDeviceClassMajor], [inDevice getDeviceClassMinor] ),
													[inDevice getDeviceClassMinor]];
                                                                                                        
		// If there is a connection in place shows the connection handle:
		if ( [inDevice isConnected] )
		{
			connectionInfo =  [NSString stringWithFormat:@"Connected, Connection Handle 0x%04x", [inDevice getConnectionHandle]];
		}
		else
		{
			connectionInfo =  [NSString stringWithFormat:@"Not Connected"];
		}

		// Get the device address and deal with the name.

		if( addressPtr )
		{
			deviceAddressString = [NSString stringWithFormat:@"%02x-%02x-%02x-%02x-%02x-%02x",	addressPtr->data[0],
																								addressPtr->data[1],
																								addressPtr->data[2],
																								addressPtr->data[3],
																								addressPtr->data[4],
																								addressPtr->data[5]];
		}
			
		if( !deviceAddressString )
		{
			deviceAddressString = @"Could not be retrieved.";
		}
		
		[button setTitle:[NSString stringWithFormat:@"%@ / %@\n%@\n%@", [deviceAddressString uppercaseString], name, deviceCODString, connectionInfo]];
		[_buttonMatrix setNeedsDisplay:TRUE];
	}
	else
	{
		NSLog( @"Nope, tag could not be found in matrix" );
	}
}

//===========================================================================================================================
//	saveNewDeviceIfAcceptable
//===========================================================================================================================

-(BOOL)saveNewDeviceIfAcceptable:(IOBluetoothDevice*)inNewDevice
{
	NSEnumerator*					enumerator;
	IOBluetoothDevice*				tmpDevice;
	const BluetoothDeviceAddress* 	newDeviceAddress = [inNewDevice getAddress];

	if( !_foundDevices )
	{
		_foundDevices = [[NSMutableArray alloc] initWithCapacity:1];
		if( !_foundDevices ) return( FALSE );
		[_foundDevices retain];
	}
	
	// walk the devices in the array.
	
	enumerator = [_foundDevices objectEnumerator];
	if( enumerator )
	{
		const BluetoothDeviceAddress* tempAddress = NULL;
			
		while( (tmpDevice = [enumerator nextObject]) )
		{
			tempAddress = [tmpDevice getAddress];
			
			if( memcmp( newDeviceAddress, tempAddress, sizeof( BluetoothDeviceAddress ) ) == 0 )
			{
				// Already have it.
				return( FALSE );
			}
		}
	}
	
	[_foundDevices addObject:inNewDevice];
	
	// Return that we haven't seen it.
	
	return( TRUE );
}

@end

#if 0
#pragma mark -
#pragma mark === C Stuff ===
#endif

//===========================================================================================================================
//	GetStringForMajorCOD
//===========================================================================================================================

NSString* GetStringForMajorCOD( BluetoothDeviceClassMajor inDeviceClassMajor )
{	
    switch( inDeviceClassMajor )
    {
        case( kBluetoothDeviceClassMajorMiscellaneous ):
		{
            return( @"Miscellaneous" );
            break;
		}           
        case( kBluetoothDeviceClassMajorComputer ):
		{
            return( @"Computer" );
			break;
		}
        case( kBluetoothDeviceClassMajorPhone ):
		{
            return( @"Phone" );
			break;
		}
        case( kBluetoothDeviceClassMajorLANAccessPoint ):
		{
            return( @"LAN Access Point" );
			break;
		}
		case( kBluetoothDeviceClassMajorAudio ):
		{
            return( @"Audio" );
			break;
		}
		case( kBluetoothDeviceClassMajorPeripheral ):
		{
            return( @"Peripheral" );
            break;
		}
		case( kBluetoothDeviceClassMajorImaging ):
		{
            return( @"Imaging" );
            break;
		}
    }
	
	return( @"Unclassified" );
}

//===========================================================================================================================
//	GetStringForMinorCOD
//===========================================================================================================================

NSString* GetStringForMinorCOD( BluetoothDeviceClassMajor inDeviceClassMajor, BluetoothDeviceClassMajor inDeviceClassMinor )
{	
    switch( inDeviceClassMajor )
    {
        case( kBluetoothDeviceClassMajorMiscellaneous ):
		{
            return( [NSString stringWithFormat:@"Unclassified",inDeviceClassMinor] );
            break;
		}           
        case( kBluetoothDeviceClassMajorComputer ):
		{
            if( inDeviceClassMinor == 0 ) return(  @"Unclassified" );
            if( inDeviceClassMinor == 1 ) return(  @"Desktop Workstation" );
            if( inDeviceClassMinor == 2 ) return(  @"Server" );
            if( inDeviceClassMinor == 3 ) return(  @"Laptop" );
            if( inDeviceClassMinor == 4 ) return(  @"Handheld" );
            if( inDeviceClassMinor == 5 ) return(  @"Palmsized" );
            if( inDeviceClassMinor == 6 ) return(  @"Wearable" );
			break;
		}
        case( kBluetoothDeviceClassMajorPhone ):
		{
			if( inDeviceClassMinor == 0 ) return(  @"Unclassified" );
            if( inDeviceClassMinor == 1 ) return(  @"Cellular" );
            if( inDeviceClassMinor == 2 ) return(  @"Cordless" );
            if( inDeviceClassMinor == 3 ) return(  @"SmartPhone" );
            if( inDeviceClassMinor == 4 ) return(  @"Wired Modem or Voice Gateway" );
            if( inDeviceClassMinor == 5 ) return(  @"Common ISDN Access" );
			break;
		}
        case( kBluetoothDeviceClassMajorLANAccessPoint ):
		{
			if( inDeviceClassMinor == 0 ) return(  @"0 used" );
            if( inDeviceClassMinor == 1 ) return(  @"1-17 used" );
            if( inDeviceClassMinor == 2 ) return(  @"18-33 used" );
            if( inDeviceClassMinor == 3 ) return(  @"34-50 used" );
            if( inDeviceClassMinor == 4 ) return(  @"51-67 used" );
            if( inDeviceClassMinor == 5 ) return(  @"68-83 used" );
            if( inDeviceClassMinor == 6 ) return(  @"84-99 used" );
            if( inDeviceClassMinor == 7 ) return(  @"No Service" );
			break;
		}
		case( kBluetoothDeviceClassMajorAudio ):
		{
			if( inDeviceClassMinor == 0 ) return(  @"Unclassified" );
			if( inDeviceClassMinor == 1 ) return(  @"Headset" );
			if( inDeviceClassMinor == 2 ) return(  @"Hands Free" );
			if( inDeviceClassMinor == 3 ) return(  @"Reserved 1" );
			if( inDeviceClassMinor == 4 ) return(  @"Microphone" );
			if( inDeviceClassMinor == 5 ) return(  @"Loudspeaker" );
			if( inDeviceClassMinor == 6 ) return(  @"Headphones" );
			if( inDeviceClassMinor == 7 ) return(  @"Portable" );
			if( inDeviceClassMinor == 8 ) return(  @"Car" );
			if( inDeviceClassMinor == 9 ) return(  @"Set-top Box" );
			if( inDeviceClassMinor == 10 ) return(  @"HiFi" );
			if( inDeviceClassMinor == 11 ) return(  @"VCR" );
			if( inDeviceClassMinor == 12 ) return(  @"Video Camera" );
			if( inDeviceClassMinor == 13 ) return(  @"CamCorder" );
			if( inDeviceClassMinor == 14 ) return(  @"Video Monitor" );
			if( inDeviceClassMinor == 15 ) return(  @"Video Display and Loudspeaker" );
			if( inDeviceClassMinor == 16 ) return(  @"Conferencing" );
			if( inDeviceClassMinor == 17 ) return(  @"Reserved2" );
			if( inDeviceClassMinor == 18 ) return(  @"Gaming Toy" );
			break;
		}
		case( kBluetoothDeviceClassMajorPeripheral ):
		{
			if( inDeviceClassMinor == 0 ) return(  @"Unclassified" );
            break;
		}
		case( kBluetoothDeviceClassMajorImaging ):
		{
			if( inDeviceClassMinor == 0 ) return(  @"Unclassified" );
            break;
		}
    }
	
	return(  @"Unclassified" );
}
Betriebssysteme: div. Windows, Linux, Unix - Systeme

no Keyboard, press any key
no mouse, you need a cat
ccode_new
Beiträge: 1214
Registriert: 27.11.2016 18:13
Wohnort: Erzgebirge

Re: Bluetooth-Progammierung unter MacOS

Beitrag von ccode_new »

Ich habe schon mal die "Sparvariante" hinbekommen: :mrgreen:

Code: Alles auswählen

ImportC "/System/Library/Frameworks/IOBluetooth.framework/Versions/A/IOBluetooth"
  IOBluetoothLocalDeviceAvailable()
EndImport

ImportC "/System/Library/Frameworks/IOBluetoothUI.framework/Versions/A/IOBluetoothUI"
  IOBluetoothGetDeviceSelectorController()
EndImport


Structure BluetoothDeviceAddress
    blupp.b[6]
EndStructure
  
btaddr.BluetoothDeviceAddress


If IOBluetoothLocalDeviceAvailable()
  
  title.s = "Meine Bluetooth-Auswahl"
  header.s = "Bitte verbinden sie Bluetooth-Geräte."
  description.s = "Hier sind ganz viele tolle verbundene Bluetoothgeräte."
  prompt.s = "Auswahl"
  cancel_txt.s = "Beenden"
  
  ref = IOBluetoothGetDeviceSelectorController()
  CocoaMessage(0, ref, "setTitle:$", @title)
  CocoaMessage(0, ref, "setHeader:$", @header)
  CocoaMessage(0, ref, "setDescriptionText:$", @description)
  CocoaMessage(0, ref, "setPrompt:$", @prompt)
  CocoaMessage(0, ref, "setCancel:$", @cancel_txt)
  CocoaMessage(0, ref, "runModal")
  
EndIf
Mein Ziel ist:
Ich möchte ein Modul für PureBasic erstellen.
Dieses soll unter allen 3 Betriebssysteme (Windows/Linux/MacOS) funktionieren.
Grundlegende gewünschte Funktionen:
-Bluetooth-Adaper:
->Adresse bekommen
->Name bekommen
->Name setzen
->Sichtbarkeit setzen
->Geräte suchen

-Verbindung zu Clienten
->Name von Clienten erhalten
->Adresse von Clienten erhalten

-Senden mit OBEX

-etc.
Betriebssysteme: div. Windows, Linux, Unix - Systeme

no Keyboard, press any key
no mouse, you need a cat
ccode_new
Beiträge: 1214
Registriert: 27.11.2016 18:13
Wohnort: Erzgebirge

Re: Bluetooth-Progammierung unter MacOS

Beitrag von ccode_new »

Code: Alles auswählen

ImportC ""
  class_addMethod(Class.i, Selector.i, *Callback, *Types)
  class_createInstance(Class.i, ExtraBytes.i)
  class_addProtocol(Class.i, Protocol.i)
  objc_allocateClassPair(ModelClass.i, NewClassName.P-ASCII, ExtraBytes.i)
  objc_lookUpClass(ClassName.P-ASCII)
  object_setClass(ObjectToModify.i, NewClass.i)
  objc_registerClassPair(NewClass.i)
  objc_getProtocol(ProtocolName.P-ASCII)
  sel_registerName(MethodName.P-ASCII)
  
  RunApplicationEventLoop()
EndImport

ImportC "/System/Library/Frameworks/IOBluetooth.framework/Versions/A/IOBluetooth"
  IOBluetoothLocalDeviceAvailable()
  IOBluetoothNumberOfAvailableHIDDevices()
EndImport


Global appDelegate = CocoaMessage(0, CocoaMessage(0, 0, "NSApplication sharedApplication"), "delegate")
Global delegateClass = object_getClass_(appDelegate)

;Global inquiry
Global device
Global ende.b = #False

Structure BluetoothDeviceAddress
    blupp.b[6]
EndStructure
  
Global btaddr.BluetoothDeviceAddress

Procedure Exit()
  If ende = #True
    End
  EndIf
EndProcedure

ProcedureC deviceInquiryComplete(obj.i, sel.i, sender.i, error.i, aborted.i)
;   CocoaMessage(@device, sender, "foundDevices")
;   If CocoaMessage(0, device, "count") > 0
;     For i = 0 To CocoaMessage(0, device, "count") - 1
;       CocoaMessage(@sname, CocoaMessage(0, device, "objectAtIndex:", i), "name")
;       Debug PeekS(CocoaMessage(0, sname, "UTF8String"), -1, #PB_UTF8)
;     Next i
;   EndIf
  ende = #True
  Exit()
EndProcedure

ProcedureC deviceInquiryDeviceFound(obj.i, sel.i, sender.i, devices.i)
  Debug PeekS(CocoaMessage(0, CocoaMessage(0, devices, "addressString"), "UTF8String"), -1, #PB_UTF8)
  Debug PeekS(CocoaMessage(0, CocoaMessage(0, devices, "name"), "UTF8String"), -1, #PB_UTF8)
EndProcedure

ProcedureC deviceInquiryDeviceNameUpdated(obj.i, sel.i, sender.i, device.i, devicesRemaining.l)
  ;Debug device
EndProcedure

ProcedureC deviceInquiryStarted(obj.i, sel.i, sender.i)
  Debug "Searching for Devices..."
EndProcedure

ProcedureC deviceInquiryUpdatingDeviceNamesStarted(obj.i, sel.i, sender.i, devicesRemaining.l)
  
EndProcedure

adapter = CocoaMessage(0, 0, "IOBluetoothDevice new")

CocoaMessage(@devices, 0, "IOBluetoothDevice pairedDevices")

CocoaMessage(@addr, CocoaMessage(0, devices, "objectAtIndex:", 0), "getAddress")

CocoaMessage(@str_addr, CocoaMessage(0, devices, "objectAtIndex:", 0), "addressString")

Debug PeekS(CocoaMessage(0, str_addr, "UTF8String"), -1, #PB_UTF8)

CocoaMessage(@name, CocoaMessage(0, devices, "objectAtIndex:", 0), "name")

Debug PeekS(CocoaMessage(0, name, "UTF8String"), -1, #PB_UTF8)

CocoaMessage(@name, CocoaMessage(0, devices, "objectAtIndex:", 0), "openConnection")

Debug CocoaMessage(0, CocoaMessage(0, devices, "objectAtIndex:", 0), "isPaired")
Debug CocoaMessage(0, CocoaMessage(0, devices, "objectAtIndex:", 0), "isConnected")


hci = CocoaMessage(0, 0, "IOBluetoothHostController new")

hci_name = CocoaMessage(0, hci, "nameAsString")
Debug PeekS(CocoaMessage(0, hci_name, "UTF8String"), -1, #PB_UTF8)

;-Suche

CocoaMessage(@inquiry, 0, "IOBluetoothDeviceInquiry alloc") ;new

class_addMethod(delegateClass, sel_registerName("deviceInquiryComplete:error:aborted:"), @deviceInquiryComplete(), "v@:@@@")
class_addMethod(delegateClass, sel_registerName("deviceInquiryDeviceFound:device:"), @deviceInquiryDeviceFound(), "v@:@@")
class_addMethod(delegateClass, sel_registerName("deviceInquiryDeviceNameUpdated:device:devicesRemaining:"), @deviceInquiryDeviceNameUpdated(), "v@:@@@")
class_addMethod(delegateClass, sel_registerName("deviceInquiryStarted:"), @deviceInquiryStarted(), "v@:@")
class_addMethod(delegateClass, sel_registerName("deviceInquiryUpdatingDeviceNamesStarted:devicesRemaining:"), @deviceInquiryUpdatingDeviceNamesStarted(), "v@:@@")

CocoaMessage(0, inquiry, "initWithDelegate:", class_createInstance(delegateClass, 0))
;CocoaMessage(0, inquiry, "setDelegate:", class_createInstance(delegateClass, 0)) 

CocoaMessage(@status, inquiry, "start")

;CocoaMessage(@status, inquiry, "stop")
RunApplicationEventLoop()
So kann ich den Namen des lokalen BT-Adapters auslesen:

Code: Alles auswählen

hci = CocoaMessage(0, 0, "IOBluetoothHostController new")

hci_name = CocoaMessage(0, hci, "nameAsString")
Debug PeekS(CocoaMessage(0, hci_name, "UTF8String"), -1, #PB_UTF8)
Wie kann ich diesen setzen ?

Danke!
Zuletzt geändert von ccode_new am 04.12.2019 23:10, insgesamt 2-mal geändert.
Betriebssysteme: div. Windows, Linux, Unix - Systeme

no Keyboard, press any key
no mouse, you need a cat
ccode_new
Beiträge: 1214
Registriert: 27.11.2016 18:13
Wohnort: Erzgebirge

Re: Bluetooth-Progammierung unter MacOS

Beitrag von ccode_new »

...
Zuletzt geändert von ccode_new am 04.12.2019 23:09, insgesamt 1-mal geändert.
Betriebssysteme: div. Windows, Linux, Unix - Systeme

no Keyboard, press any key
no mouse, you need a cat
Benutzeravatar
mk-soft
Beiträge: 3695
Registriert: 24.11.2004 13:12
Wohnort: Germany

Re: Bluetooth-Progammierung unter MacOS

Beitrag von mk-soft »

Die glaube das du besser im englischen Forum die Frage für maOS stellen solltest...

Da sind mehr mit Erfahrung dabei...
Mach ich auch so.

Links:
https://www.purebasic.fr/english/viewto ... 19&t=72642
https://www.purebasic.fr/english/viewto ... 19&t=50795
Alles ist möglich, fragt sich nur wie...
Projekte ThreadToGUI / EventDesigner V3 / OOP-BaseClass-Modul
Downloads auf MyWebspace / OneDrive
ccode_new
Beiträge: 1214
Registriert: 27.11.2016 18:13
Wohnort: Erzgebirge

Re: Bluetooth-Progammierung unter MacOS

Beitrag von ccode_new »

...

Code: Alles auswählen

;x64

ImportC ""
  CFStringCreateWithCString(alloc, *cStr.p-utf8, encoding)
EndImport

ImportC "/System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration"
  SCPreferencesCreate(allocator.i, name.i, prefs.i)
  SCPreferencesSetComputerName.b(prefs.i, name.i, nameEncoding.i)
  SCPreferencesSetLocalHostName(prefs.i, name.i)
  SCPreferencesLock(prefs.i, check.b)
  SCPreferencesUnlock(prefs.i)
  SCPreferencesCommitChanges.b(prefs.i)
  SCPreferencesApplyChanges.b(prefs.i)
EndImport

#kCFStringEncodingUTF8 = $08000100

XIncludeFile "Admin.pbi"

Global prefs.i, success.b, cfs, compName.i, commit.b

RunAsAdmin::Login()

cfs = CFStringCreateWithCString(#Null, UTF8("scutil"), #kCFStringEncodingUTF8)
compName = CFStringCreateWithCString(#Null, UTF8("DerComputer"), #kCFStringEncodingUTF8)

prefs = SCPreferencesCreate(#Null, cfs, #Null)

success = SCPreferencesLock(prefs, #True)

If success = #True
  SCPreferencesSetComputerName(prefs, compName, #kCFStringEncodingUTF8)
  SCPreferencesSetLocalHostName(prefs, compName)
  ;RunProgram("scutil", ~"--set ComputerName \"DerComputer\"", GetCurrentDirectory())
  
  commit = SCPreferencesCommitChanges(prefs)
  If commit = #True
    SCPreferencesApplyChanges(prefs)
  EndIf
EndIf

SCPreferencesUnlock(prefs)
Jetzt gehts an OBEX, etc.
Betriebssysteme: div. Windows, Linux, Unix - Systeme

no Keyboard, press any key
no mouse, you need a cat
Antworten