Skip to main content

BleConnect Module

The BleConnect module provides comprehensive Bluetooth device connection management for TopStepComKit SDK, including device discovery, binding, authentication, and connection lifecycle management. All callbacks execute on the main thread for safe UI updates.

Prerequisites

  • iOS 12.0 or higher
  • CoreBluetooth framework imported
  • Bluetooth permission granted by user (NSBluetoothPeripheralUsageDescription)
  • Valid user ID for device binding and connection

Data Models

TSPeripheralConnectParam

Connection parameters for device binding and connection operations.

PropertyTypeDescription
userIdNSString *User ID for device connection (required)
userInfoTSUserInfoModel *User profile information for personalization
authCodeNSString *Authentication code from QR code scanning during binding
allowConnectWithBTBOOLFlag indicating Bluetooth connection is allowed
brandNSString *Phone manufacturer name (e.g., "Apple")
modelNSString *Phone model identifier (e.g., "iPhone 15 Pro")
systemVersionNSString *Phone OS version (e.g., "iOS 17.0")

TSPeripheralScanParam

Advanced scan parameters for device discovery with filtering.

PropertyTypeDescription
userIdNSString *User ID for filtering (required)
serviceUUIDsNSArray<CBUUID *> *Filter by advertised service UUIDs (nil = no filter)
solicitedServiceUUIDsNSArray<CBUUID *> *Filter by solicited service UUIDs (nil = no filter)
deviceNameNSString *Filter by device Bluetooth name (nil = no filter)
macAddressNSString *Filter by MAC address (nil = no filter)
onlyUnconnectedBOOLReturn only unconnected devices (default: NO)
allowDuplicatesBOOLAllow multiple discoveries of same device (default: NO)
scanTimeoutNSIntegerScan timeout in seconds (0 = infinite)

TSPeripheral

Complete device information model containing system, screen, project, capability, and limitation data.

PropertyTypeDescription
systemInfoTSPeripheralSystem *Bluetooth connection and addressing information
screenInfoTSPeripheralScreen *Screen size, shape, and preview configurations
projectInfoTSPeripheralProject *Project ID, firmware version, serial number
capabilityTSPeripheralCapability *Supported features and fine-grained capabilities
limitationTSPeripheralLimitations *Device feature constraints and limits

TSPeripheralSystem

System-level information for device communication.

PropertyTypeDescription
peripheralCBPeripheral *Core Bluetooth peripheral object
centralCBCentralManager *Bluetooth central manager for connections
uuidNSString *UUID string from CBPeripheral (readonly)
macNSString *MAC address in colon-separated format (e.g., "DE:82:47:15:28:B0")
bleNameNSString *Device Bluetooth name
RSSINSNumber *Signal strength indicator
advertisementDataNSDictionary *Raw advertisement data from device

TSPeripheralScreen

Screen and preview image configuration.

PropertyTypeDescription
shapeTSPeriphShapeDevice physical shape (circle, square, rectangle)
screenSizeCGSizeScreen dimensions in pixels
screenBorderRadiusCGFloatScreen corner radius in pixels
dialPreviewSizeCGSizeWatch face preview thumbnail size in pixels
dialPreviewBorderRadiusCGFloatWatch face preview corner radius in pixels
videoPreviewSizeCGSizeCamera video stream size in pixels
videoPreviewBorderRadiusCGFloatVideo preview corner radius in pixels

TSPeripheralProject

Project and version information.

PropertyTypeDescription
projectIdNSString *Unique project identifier
companyIdNSString *Manufacturer identifier
brandNSString *Brand name (max 16 characters)
modelNSString *Model identifier (max 16 characters)
firmVersionNSString *Firmware version string (semantic versioning)
virtualVersionNSString *Internal version tracking number
serialNumberNSString *Unique device serial number
mainProjNumNSString *Main project number (FitCloudKit)
subProjNumNSString *Sub project number (FitCloudKit)

TSPeripheralCapability

Device capability container composing feature, message, and activity modules.

PropertyTypeDescription
featureAbilityTSFeatureAbility *Coarse-grained feature support flags
messageAbilityTSMessageAbility *Fine-grained message type support (nullable)
dailyActivityAbilityTSDailyActivityAbility *Fine-grained activity type support (nullable)

TSFeatureAbility

Feature module capability flags indicating which major features are supported.

PropertyTypeDescription
originAbilityNSData *Raw ability data from device (max 16 bytes)
supportCapabilitiesTSPeripheralSupportAbilityParsed capability flags bitmask
isSupportStepCountingBOOLStep counting support
isSupportDistanceCountingBOOLDistance counting support
isSupportCalorieCountingBOOLCalorie counting support
isSupportHeartRateBOOLHeart rate monitoring support
isSupportBloodPressureBOOLBlood pressure monitoring support
isSupportBloodOxygenBOOLBlood oxygen monitoring support
isSupportStressBOOLStress monitoring support
isSupportSleepBOOLSleep monitoring support
isSupportTemperatureBOOLTemperature monitoring support
isSupportECGBOOLECG monitoring support
isSupportFemaleHealthBOOLFemale health features support
isSupportInitiateWorkoutBOOLInitiate workout support
isSupportWeightManagementBOOLWeight management support
isSupportRemindersBOOLReminders support
isSupportCallManagementBOOLCall management support
isSupportAppNotificationsBOOLApp notifications support
isSupportMusicControlBOOLMusic control support
isSupportWeatherDisplayBOOLWeather display support
isSupportFindMyPhoneBOOLFind my phone support
isSupportAlarmClockBOOLAlarm clock support
isSupportWorldClockBOOLWorld clock support
isSupportMapNavigationBOOLMap navigation support
isSupportShakeCameraBOOLShake to take photo support
isSupportCameraPreviewBOOLCamera video preview support
isSupportEWalletBOOLE-wallet support
isSupportBusinessCardBOOLBusiness card support
isSupportPhotoAlbumBOOLPhoto album support
isSupportEBookBOOLE-book support
isSupportVoiceRecordingBOOLVoice recording support
isSupportAppStoreBOOLApp store support
isSupportMotionGamesBOOLMotion sensing games support
isSupportSportUploadBOOLSport upload support
isSupportERNIEBotBOOLERNIE Bot support
isSupportChatGPTBOOLChatGPT support
isSupportLoversFeatureBOOLLovers feature support
isSupportContactsBOOLContacts support
isSupportEmergencyContactsBOOLEmergency contacts support
isSupportMuslimPrayerBOOLMuslim prayer reminders support
isSupportQiblaCompassBOOLQibla compass support
isSupportNFCPaymentBOOLNFC payment support
isSupportVoiceAssistantBOOLVoice assistant support
isSupportFacePushBOOLWatch face push support
isSupportCustomFaceBOOLCustom watch face support
isSupportSlideshowFaceBOOLSlideshow watch face support
isSupportDialComponentBOOLDial component support
isSupportTimeSettingsBOOLTime settings support
isSupportLanguageBOOLLanguage settings support
isSupportUserInfoSettingsBOOLUser information settings support
isSupportDailyActivityBOOLDaily activity support
isSupportFirmwareUpgradeBOOLFirmware upgrade support
isSupportUnitSettingsBOOLUnit settings support
isSupportEarbudsAPIsBOOLEarbuds APIs support
isSupportAIChatBOOLAI chat support
isSupportAIChatAudioUsingScoBOOLAI chat audio using SCO support
isSupportScreenLockBOOLScreen lock support
isSupportGameLockBOOLGame lock support

TSMessageAbility

Fine-grained message type support management.

PropertyTypeDescription
No direct properties-Access through methods

TSDailyActivityAbility

Fine-grained daily activity type support management.

PropertyTypeDescription
No direct properties-Access through methods

TSBluetoothSystem

Complete Bluetooth system information (BLE and Classic Bluetooth).

PropertyTypeDescription
bleInfoTSBluetoothInfo *BLE adapter information
btInfoTSBluetoothInfo *Classic Bluetooth adapter information

TSBluetoothInfo

Bluetooth adapter information.

PropertyTypeDescription
macAddressNSString *MAC address (colon-separated, may be nil on iOS)
nameNSString *Adapter name
statusTSBleStatusAdapter connection status

TSPeripheralLimitations

Device feature capability constraints.

PropertyTypeDescription
maxAlarmCountUInt8Maximum alarm clocks (0 = not supported)
maxContactCountUInt8Maximum contacts (0 = not supported)
maxEmergencyContactCountUInt8Maximum emergency contacts (0 = not supported, 255 = unlimited)
maxPushDialCountUInt8Maximum custom watch face slots (0 = not supported)
maxInnerDialCountUInt8Pre-installed watch faces count
maxWorldClockCountUInt8Maximum world clocks (0 = not supported, 255 = unlimited)
maxSedentaryReminderCountUInt8Maximum sedentary reminders (0 = not supported, 255 = unlimited)
maxWaterDrinkingReminderCountUInt8Maximum water drinking reminders (0 = not supported, 255 = unlimited)
maxMedicationReminderCountUInt8Maximum medication reminders (0 = not supported, 255 = unlimited)
maxCustomReminderCountUInt8Maximum custom reminders (0 = not supported, 255 = unlimited)

Enumerations

TSBleConnectionState

Bluetooth connection state enumeration defining the complete lifecycle from discovery through full readiness.

ValueNameDescription
0eTSBleStateDisconnectedDevice not connected (initial state or after failure)
1eTSBleStateConnectingEstablishing BLE physical connection
2eTSBleStateAuthenticatingPerforming bind/login authentication
3eTSBleStatePreparingDataFetching device information after authentication
4eTSBleStateConnectedFully connected and ready for data operations

TSScanCompletionReason

Reasons for scan completion.

ValueNameDescription
1000eTSScanCompleteReasonTimeoutScan timeout occurred
1001eTSScanCompleteReasonBleNotReadyBluetooth not ready
1002eTSScanCompleteReasonPermissionDeniedBluetooth permission denied
1003eTSScanCompleteReasonUserStoppedUser manually stopped scan
1004eTSScanCompleteReasonSystemErrorSystem error occurred
1005eTSScanCompleteReasonNotSupportBluetooth not supported

TSBleStatus

Bluetooth adapter connection status.

ValueNameDescription
0TSBleDisconnectedNot connected
1TSBleConnectedConnected (physical connection established)
2TSBleReadyReady (connected and notify/SPP opened)

TSPeriphShape

Device physical shape enumeration.

ValueNameDescription
0eTSPeriphShapeUnknowUnknown shape
1eTSPeriphShapeCircleCircular device (round watch)
2eTSPeriphShapeSquareSquare device (square watch)
3eTSPeriphShapeVerticalRectangleVertical rectangle (portrait orientation)
4eTSPeriphShapeTransverseRectangleHorizontal rectangle (landscape orientation)

TSPeripheralSupportAbility

Feature support capability flags (64-bit bitmask).

Bit RangeFeatures
0-12Health: steps, distance, calories, heart rate, blood pressure, oxygen, stress, sleep, temperature, ECG, female health, workouts, daily activity, weight
16-33Smart: reminders, calls, notifications, music, weather, find phone, alarm, world clock, maps, shake camera, camera preview, e-wallet, business card, photos, e-book, recording, app store, motion games
34-36AI: sport upload, ERNIE Bot, ChatGPT
37-39Social: lovers, contacts, emergency contacts
40-41Religious: Muslim prayer, Qibla compass
42-46Hardware: NFC, voice assistant, watch face, custom face, slideshow face
47-51System: time, language, user info, firmware upgrade, units
52-57Reserved: earbuds, dial component, AI chat, AI chat SCO, screen lock, game lock

Callback Types

TSScanDiscoveryBlock

Device discovery callback during scan.

typedef void(^TSScanDiscoveryBlock)(TSPeripheral *_Nonnull peripheral);
ParameterTypeDescription
peripheralTSPeripheral *Discovered device with name, ID, and signal information

TSScanCompletionBlock

Scan completion callback.

typedef void(^TSScanCompletionBlock)(TSScanCompletionReason reason, NSError * _Nullable error);
ParameterTypeDescription
reasonTSScanCompletionReasonReason for scan completion
errorNSError *Error details if applicable (nullable)

TSBleConnectionStateCallback

Connection state change callback during connection process.

typedef void (^TSBleConnectionStateCallback)(TSBleConnectionState connectionState);
ParameterTypeDescription
connectionStateTSBleConnectionStateCurrent connection state

TSBleConnectionCompletionBlock

Connection result callback with state and optional error.

typedef void (^TSBleConnectionCompletionBlock)(TSBleConnectionState connectionState, NSError *_Nullable error);
ParameterTypeDescription
connectionStateTSBleConnectionStateFinal or current connection state
errorNSError *Error details if failure occurred (nullable)

API Reference

Get current connection state

Retrieve the current Bluetooth connection state asynchronously.

- (void)getConnectState:(TSBleConnectionStateCallback)completion;
ParameterTypeDescription
completionTSBleConnectionStateCallbackCallback returning current connection state

Code Example:

id<TSBleConnectInterface> bleConnect = /* ... get interface ... */;

[bleConnect getConnectState:^(TSBleConnectionState connectionState) {
switch (connectionState) {
case eTSBleStateDisconnected:
TSLog(@"Device disconnected");
break;
case eTSBleStateConnecting:
TSLog(@"Device connecting...");
break;
case eTSBleStateAuthenticating:
TSLog(@"Device authenticating...");
break;
case eTSBleStatePreparingData:
TSLog(@"Device preparing data...");
break;
case eTSBleStateConnected:
TSLog(@"Device connected and ready");
break;
}
}];

Start scanning for devices

Begin searching for Bluetooth devices with simple timeout configuration.

- (void)startSearchPeripheral:(NSTimeInterval)timeout
discoverPeripheral:(TSScanDiscoveryBlock)discoverPeripheral
completion:(TSScanCompletionBlock)completion;
ParameterTypeDescription
timeoutNSTimeIntervalScan timeout in seconds (0 = default 30 seconds)
discoverPeripheralTSScanDiscoveryBlockCallback triggered when device discovered
completionTSScanCompletionBlockCallback when scan completes or times out

Code Example:

id<TSBleConnectInterface> bleConnect = /* ... get interface ... */;

[bleConnect startSearchPeripheral:30.0 // 30 second timeout
discoverPeripheral:^(TSPeripheral *peripheral) {
TSLog(@"Device found: %@, RSSI: %@", peripheral.systemInfo.bleName, peripheral.systemInfo.RSSI);

// Update UI with discovered device
[self updateDeviceListWithPeripheral:peripheral];
} completion:^(TSScanCompletionReason reason, NSError *error) {
if (error) {
TSLog(@"Scan error: %@", error.localizedDescription);
} else {
TSLog(@"Scan completed with reason: %ld", (long)reason);
}
}];

Start scanning with advanced parameters

Begin searching with detailed filter and configuration options.

- (void)startSearchPeripheralWithParam:(TSPeripheralScanParam *)param
discoverPeripheral:(TSScanDiscoveryBlock)discoverPeripheral
completion:(TSScanCompletionBlock)completion;
ParameterTypeDescription
paramTSPeripheralScanParam *Scan parameters with filters and timeout
discoverPeripheralTSScanDiscoveryBlockCallback for device discovery
completionTSScanCompletionBlockCallback when scan completes

Code Example:

id<TSBleConnectInterface> bleConnect = /* ... get interface ... */;

TSPeripheralScanParam *param = [[TSPeripheralScanParam alloc] init];
param.userId = @"user123";
param.scanTimeout = 30; // 30 second timeout
param.allowDuplicates = YES; // Get RSSI updates
param.deviceName = @"MyDevice"; // Filter by name (optional)
param.onlyUnconnected = YES;

[bleConnect startSearchPeripheralWithParam:param
discoverPeripheral:^(TSPeripheral *peripheral) {
TSLog(@"Found device: %@", peripheral.systemInfo.bleName);
} completion:^(TSScanCompletionReason reason, NSError *error) {
TSLog(@"Scan completed");
}];

Stop scanning

Halt the current device search operation.

- (void)stopSearchPeripheral;

Code Example:

id<TSBleConnectInterface> bleConnect = /* ... get interface ... */;

// Stop scanning
[bleConnect stopSearchPeripheral];
TSLog(@"Scan stopped");

Connect to device

Establish initial connection and binding to a new device.

- (void)connectWithPeripheral:(TSPeripheral *)peripheral
param:(TSPeripheralConnectParam *)param
completion:(TSBleConnectionCompletionBlock)completion;
ParameterTypeDescription
peripheralTSPeripheral *Device to connect to
paramTSPeripheralConnectParam *Connection parameters including user ID
completionTSBleConnectionCompletionBlockCallback for connection progress and result

Code Example:

id<TSBleConnectInterface> bleConnect = /* ... get interface ... */;
TSPeripheral *device = /* ... selected device ... */;

TSPeripheralConnectParam *param = [[TSPeripheralConnectParam alloc] initWithUserId:@"user123"];
param.authCode = @"123456"; // From QR code
param.brand = @"Apple";
param.model = @"iPhone 15";
param.systemVersion = @"17.0";

[bleConnect connectWithPeripheral:device param:param completion:^(TSBleConnectionState connectionState, NSError *error) {
if (error) {
TSLog(@"Connection failed: %@", error.localizedDescription);
return;
}

switch (connectionState) {
case eTSBleStateConnecting:
TSLog(@"Connecting...");
[self updateProgressText:@"Connecting to device..."];
break;
case eTSBleStateAuthenticating:
TSLog(@"Authenticating...");
[self updateProgressText:@"Authenticating..."];
break;
case eTSBleStatePreparingData:
TSLog(@"Preparing data...");
[self updateProgressText:@"Preparing data..."];
break;
case eTSBleStateConnected:
TSLog(@"Connected!");
[self showConnectionSuccessUI];
break;
case eTSBleStateDisconnected:
TSLog(@"Disconnected");
break;
}
}];

Reconnect to device

Re-establish connection to a previously bound device.

- (void)reconnectWithPeripheral:(TSPeripheral *)peripheral
param:(TSPeripheralConnectParam *)param
completion:(TSBleConnectionCompletionBlock)completion;
ParameterTypeDescription
peripheralTSPeripheral *Previously bound device to reconnect
paramTSPeripheralConnectParam *Connection parameters with same user ID
completionTSBleConnectionCompletionBlockCallback for reconnection progress and result

Code Example:

id<TSBleConnectInterface> bleConnect = /* ... get interface ... */;
TSPeripheral *device = /* ... stored device ... */;

TSPeripheralConnectParam *param = [[TSPeripheralConnectParam alloc] initWithUserId:@"user123"];
param.brand = @"Apple";
param.model = @"iPhone 15";
param.systemVersion = @"17.0";

[bleConnect reconnectWithPeripheral:device param:param completion:^(TSBleConnectionState connectionState, NSError *error) {
if (error) {
TSLog(@"Reconnection failed: %@", error.localizedDescription);
} else if (connectionState == eTSBleStateConnected) {
TSLog(@"Reconnected successfully!");
}
}];

Disconnect device

Safely disconnect from current device while preserving binding information.

- (void)disconnectCompletion:(TSCompletionBlock)completion;
ParameterTypeDescription
completionTSCompletionBlockCallback when disconnection completes

Code Example:

id<TSBleConnectInterface> bleConnect = /* ... get interface ... */;

[bleConnect disconnectCompletion:^(NSError *error) {
if (error) {
TSLog(@"Disconnect error: %@", error.localizedDescription);
} else {
TSLog(@"Device disconnected");
}
}];

Unbind device

Completely remove device binding and clear all pairing information.

- (void)unbindPeripheralCompletion:(TSCompletionBlock)completion;
ParameterTypeDescription
completionTSCompletionBlockCallback when unbinding completes

Code Example:

id<TSBleConnectInterface> bleConnect = /* ... get interface ... */;

[bleConnect unbindPeripheralCompletion:^(NSError *error) {
if (error) {
TSLog(@"Unbind error: %@", error.localizedDescription);
} else {
TSLog(@"Device unbound - must rebind to use again");
}
}];

Check connection status

Quickly verify if device is currently connected.

- (BOOL)isConnected;

Returns: BOOL — YES if device connected, NO otherwise

Code Example:

id<TSBleConnectInterface> bleConnect = /* ... get interface ... */;

if ([bleConnect isConnected]) {
TSLog(@"Device is connected");
// Enable features that require connection
} else {
TSLog(@"Device is not connected");
// Show connection UI
}

Get Bluetooth adapter information

Retrieve complete Bluetooth system information for BLE and Classic Bluetooth.

- (void)getBluetoothInfo:(void(^)(TSBluetoothSystem * _Nullable bluetoothInfo, NSError * _Nullable error))completion;
ParameterTypeDescription
completionBlock returning TSBluetoothSystem *Callback with Bluetooth system information and optional error

Code Example:

id<TSBleConnectInterface> bleConnect = /* ... get interface ... */;

[bleConnect getBluetoothInfo:^(TSBluetoothSystem *bluetoothInfo, NSError *error) {
if (error) {
TSLog(@"Error getting Bluetooth info: %@", error.localizedDescription);
return;
}

if (bluetoothInfo) {
TSLog(@"BLE Status: %ld", (long)bluetoothInfo.bleInfo.status);
TSLog(@"BLE Name: %@", bluetoothInfo.bleInfo.name);

if (bluetoothInfo.btInfo) {
TSLog(@"BT Status: %ld", (long)bluetoothInfo.btInfo.status);
TSLog(@"BT Name: %@", bluetoothInfo.btInfo.name);
}
}
}];

Important Notes

  1. All callbacks execute on the main thread — Safe for direct UI updates without dispatch_async

  2. Connection state flow on success:

    • eTSBleStateDisconnectedeTSBleStateConnectingeTSBleStateAuthenticatingeTSBleStatePreparingDataeTSBleStateConnected
  3. Connection state flow on failure at any stage:

    • Any state → eTSBleStateDisconnected with error details in completion callback
  4. Multiple callback invocations — The completion callback is triggered multiple times with different states during connection; use state parameter to track progress

  5. Scan resource management — Call stopSearchPeripheral when not needed to conserve battery and release resources

  6. User ID requirement — Always provide valid user ID in connection and scan parameters for proper binding

  7. MAC address availability — MAC addresses may be nil on iOS due to privacy restrictions

  8. Thread safety — Methods can be safely called from any thread; callbacks always return on main thread

  9. **Disconnection vs Unbinding** — Disconnection preserves binding (use reconnectWithPeripheral); unbinding removes all pairing info (use connectWithPeripheral to rebind)

  10. Capability modules — Check featureAbility first (coarse-grained); then check messageAbility and dailyActivityAbility for fine-grained details of supported types

  11. Limitation constraints — Value of 0 means feature not supported; value of 255 (TSUnLimitNum) means unlimited

  12. Default scan timeout — Pass 0 to startSearchPeripheral: to use default 30-second timeout; use TSPeripheralScanParam for custom timeout

  13. Error handling — Always check error parameter in callbacks; connection failures may occur at any stage

  14. State callback purpose — Use state callback for progress UI updates; use completion callback for business logic decisions