JoywayBeacon iOS SDK Integration Guide

This guide explains how to use JoywayLib.iOS static library to implement iBeacon device configuration

1. Project Integration

1.1 Directory Structure

Place the JoywayLib directory in the project root:

JoywayBeacon.iOS/
├── JoywayLib/
│   ├── libJoywayLib.a          # Static library file
│   ├── DeviceConfig/
│   │   ├── DeviceConfig.h      # Device configuration manager interface
│   │   └── iBeaconConfigParam.h # iBeacon parameter encapsulation class
│   ├── BT/                     # Bluetooth related headers
│   └── ...other dependencies
└── JoywayBeacon/
    └── ...project source code

1.2 Xcode Configuration

  • Link Binary With Libraries Add libJoywayLib.a
  • Header Search Paths Add $(SRCROOT)/JoywayLib
  • Framework Search Paths Ensure Bluetooth frameworks are included
  • 2. Core Class Reference

    2.1 DeviceConfig (Device Configuration Manager)

    Manages the complete flow of Bluetooth connection, login, parameter reading and saving

    Method/PropertyDescription configStateCurrent configuration state (Idle/Connecting/LoggingIn/ReadingParams/WritingParams/Done) workingParamsFromDeviceWorking parameters array read from device initWithDeviceMac:devicePassword:paramLen:eventHandler:Initialization method with device MAC, password, parameter length and event handler startStart configuration flow (connect → login → query params) stopStop configuration flow and disconnect Bluetooth saveParamsToDevice:Send save parameters command to device

    2.2 DeviceConfigEventHandler (Event Callback Protocol)

    Callback MethodDescriptionRequired onConnectStatusChanged:status:isConnected:Connection status changedYes onParamsRead:params:Successfully read device parametersYes onParamsSaved:success:errorMsg:Parameter save resultYes onFirmwareVersionReceived:fwpId:Received firmware versionYes onLoginFailed:Login failed (wrong password)No onFirmwareVersionQueryFailed:Firmware version query failedNo onDeviceFound:Target device found during scanningNo onParamsQueryStarted:Started querying device parametersNo onLoginStarted:Started logging in to deviceNo

    2.3 iBeaconConfigParam (iBeacon Parameter Encapsulation)

    Encapsulates iBeacon configuration parameters with serialization capabilities

    PropertyTypeDescription uuidNSString*iBeacon UUID majorlong longMajor value minorlong longMinor value txPowerintTransmit power intervalintAdvertising interval useBuzzerBOOLWhether to use buzzer useLedBOOLWhether to use LED beaconNameNSString*Device name rssiAtOneMeterintRSSI value at 1 meter adv1IntervalintAdvertising channel 1 interval adv1TimeLenintAdvertising channel 1 duration adv2IntervalintAdvertising channel 2 interval adv2TimeLenintAdvertising channel 2 duration adv1NeverStopBOOLChannel 1 never stop adv2NeverStopBOOLChannel 2 never stop devicePasswordNSString*Device password
    MethodDescription getWorkingParamsDataGenerate 72-byte working parameters data (for saving) getBytes_UUID1/UUID2/MajorMinor/TxPower/...Get byte data for each parameter (flag transfer method) getBytesDataListToSendGet list of byte arrays for all parameters

    3. Complete Usage Flow

    3.1 Initialize and Start Configuration

    // 1. Import headers
    #import "DeviceConfig.h"
    #import "iBeaconConfigParam.h"
    
    // 2. Declare protocol conformance
    @interface iBeaconConfigViewController : UIViewController <DeviceConfigEventHandler>
    
    // 3. Initialize DeviceConfig
    self.deviceConfig = [[DeviceConfig alloc] initWithDeviceMac:self.mac
                                                  devicePassword:self.password
                                                       paramLen:72
                                                   eventHandler:self];
    
    // 4. Start configuration flow (connect → login → query params)
    [self.deviceConfig start];

    3.2 Handle Connection Status Changes

    - (void)onConnectStatusChanged:(NSString*)mac status:(NSString*)status isConnected:(BOOL)isConnected {
        if (isConnected) {
            NSLog(@"Device connected");
        } else {
            NSLog(@"Connection status: %@", status);
            if ([status isEqualToString:@"连接失败"]) {
                // Connection failed, show error to user
            }
        }
    }

    3.3 Handle Login Failure

    - (void)onLoginFailed:(NSString*)mac {
        NSLog(@"Login failed, wrong password");
        // Show password error to user, close page
    }

    3.4 Handle Parameter Read Result

    - (void)onParamsRead:(NSString*)mac params:(NSMutableArray<NSNumber*>*)params {
        NSLog(@"Successfully read device parameters, %ld bytes", params.count);
        
        // Parse parameters and display to UI
        // params is an array of 72 NSNumber*, each representing a byte (0-255)
        
        // Example: Parse password (first 8 bytes)
        NSMutableString *password = [NSMutableString string];
        for (int i = 0; i < 8 && i < params.count; i++) {
            uint8_t byte = [params[i] unsignedCharValue];
            if (byte != 0) [password appendFormat:@"%c", byte];
        }
        
        // Parse other parameters...
    }

    3.5 Save Parameters to Device

    // 1. Create parameter object
    iBeaconConfigParam *param = [[iBeaconConfigParam alloc] init];
    param.uuid = @"00000000-0000-0000-0000-000000000000";
    param.major = 1;
    param.minor = 1;
    param.txPower = -60;
    param.interval = 100;
    param.useBuzzer = YES;
    param.useLed = YES;
    param.beaconName = @"MyBeacon";
    param.devicePassword = @"000000";
    // ...set other parameters
    
    // 2. Generate 72-byte working parameters data
    NSData *paramsData = [param getWorkingParamsData];
    
    // 3. Send save command
    [self.deviceConfig saveParamsToDevice:paramsData];

    3.6 Handle Save Result

    - (void)onParamsSaved:(NSString*)mac success:(BOOL)success errorMsg:(NSString*)errorMsg {
        if (success) {
            NSLog(@"Configuration saved successfully");
            // Disconnect and close page
            [self.deviceConfig stop];
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            NSLog(@"Configuration save failed: %@", errorMsg);
            // Show error to user, close page
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }

    4. Configuration Flow Sequence

    User clicks Connect button
            │
            ▼
    ┌─────────────────────────────────────────────────────────────┐
    │  1. Show login dialog, enter device password                 │
    └─────────────────────────────────────────────────────────────┘
            │
            ▼
    ┌─────────────────────────────────────────────────────────────┐
    │  2. Check if device is already connected                     │
    │     ├─ Connected → Send login command directly               │
    │     └─ Not connected → Start Bluetooth scanning (600s timeout)│
    └─────────────────────────────────────────────────────────────┘
            │
            ▼
    ┌─────────────────────────────────────────────────────────────┐
    │  3. Device found → Stop scanning → Connect device (30s timeout)│
    └─────────────────────────────────────────────────────────────┘
            │
            ▼
    ┌─────────────────────────────────────────────────────────────┐
    │  4. Connected → Wait 2 seconds (GATT ready) → Send login    │
    │     command (30s timeout)                                    │
    └─────────────────────────────────────────────────────────────┘
            │
            ▼
    ┌─────────────────────────────────────────────────────────────┐
    │  5. Login success → Query firmware version → Query working  │
    │     parameters (30s timeout)                                 │
    │     ├─ Login failed → Show password error → Close page      │
    │     └─ Firmware version query failed → Show error → Continue│
    └─────────────────────────────────────────────────────────────┘
            │
            ▼
    ┌─────────────────────────────────────────────────────────────┐
    │  6. Parameters received → Parse and display → User modifies │
    └─────────────────────────────────────────────────────────────┘
            │
            ▼
    ┌─────────────────────────────────────────────────────────────┐
    │  7. User clicks Save → Validate parameters → Send save      │
    │     command (30s timeout)                                    │
    │     ├─ Save success → Disconnect → Close page               │
    │     └─ Save failed → Show error → Close page                │
    └─────────────────────────────────────────────────────────────┘

    5. Timeout Handling

    Timeout PhaseTimeout DurationTrigger ConditionHandling Scanning Timeout600 secondsDevice not found after scanning startedShow "Device not found", close page Connection Timeout30 secondsConnection failed after device foundShow "Connection timeout", close page Login Timeout30 secondsNo response after login command sentShow "Login timeout", close page Parameter Query Timeout30 secondsNo response after query command sentShow "Parameter query failed", close page Save Timeout30 secondsNo response after save command sentShow "Save timeout", keep page for retry

    6. Notes

    Bluetooth Permissions: Ensure Bluetooth permission descriptions are added in Info.plist (NSBluetoothAlwaysUsageDescription, NSBluetoothPeripheralUsageDescription)
    Protocol Protection: Communication protocol definitions are compiled into the static library and not exposed as header files
    Thread Safety: All callbacks are executed on the main thread, UI can be updated directly
    Resource Release: Always call [deviceConfig stop] when closing the page to release Bluetooth connection resources