[swift] Swift Core Bluetooth와 의료 기기 연동

개요

의료 기기는 현대 의학에서 중요한 역할을 담당하고 있으며, 사용자의 건강 상태를 모니터링하고 진단에 도움을 줍니다. Swift Core Bluetooth 프레임워크는 Swift 언어로 Bluetooth Low Energy(BLE) 기기와 통신할 수 있는 강력한 기능을 제공합니다. 이 글에서는 Swift Core Bluetooth를 사용하여 의료 기기와의 연동을 어떻게 할 수 있는지 알아보겠습니다.

시작하기 전에

의료 기기와의 연동을 위해 몇 가지 사전 작업이 필요합니다. 먼저, iOS 디바이스에서 BLE 지원을 확인하고, 반드시 Bluetooth 권한을 요청해야 합니다. 또한 개발자 포털에서 당신의 앱을 등록하고 암호화된 통신에 대한 인증 키를 받아야 합니다.

Core Bluetooth 사용하기

Swift Core Bluetooth 프레임워크를 사용하려면 먼저 해당 프레임워크를 import해야 합니다. 다음 예제 코드는 기기 스캔을 시작하여 주변의 BLE 기기를 찾는 방법을 보여줍니다.

import CoreBluetooth

class MyDeviceManager: NSObject, CBCentralManagerDelegate {
    var centralManager: CBCentralManager!
    
    override init() {
        super.init()
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            centralManager.scanForPeripherals(withServices: nil, options: nil)
        } else {
            print("Bluetooth를 활성화해주세요.")
        }
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print("디바이스 이름: \(peripheral.name ?? "알 수 없음")")
        print("디바이스 신호 세기: \(RSSI)")
    }
}

위 코드에서는 CBCentralManagerDelegate 프로토콜을 채택하여 디바이스 스캔 결과를 받아오고, 발견된 디바이스의 이름과 신호 세기를 출력하고 있습니다. 이제 우리는 주변의 BLE 디바이스를 찾아볼 수 있습니다.

의료 기기와 연동하기

BLE 기기를 찾은 후에는 해당 기기와 연결하여 데이터를 주고받을 수 있습니다. 다음 예제 코드는 연결된 기기에서 지원하는 서비스와 해당 서비스의 특성을 찾아보는 방법을 보여줍니다.

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    peripheral.delegate = self
    peripheral.discoverServices(nil)
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    if let services = peripheral.services {
        for service in services {
            print("서비스 UUID: \(service.uuid)")
            peripheral.discoverCharacteristics(nil, for: service)
        }
    }
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    if let characteristics = service.characteristics {
        for characteristic in characteristics {
            print("특성 UUID: \(characteristic.uuid)")
        }
    }
}

위 코드에서는 디바이스와의 연결이 성공한 후에 CBPeripheralDelegate 프로토콜을 채택하여 서비스와 특성을 찾고 출력하고 있습니다. 이제 우리는 연결된 의료 기기가 제공하는 기능을 알아낼 수 있습니다.

데이터 주고받기

연결된 기기의 서비스와 특성을 찾은 후에는 해당 특성에서 데이터를 읽거나 쓸 수 있습니다. 다음 예제 코드는 의료 기기의 특정 특성에서 데이터를 읽어오고 개인 정보를 표시하는 방법을 보여줍니다.

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    guard let data = characteristic.value else { return }
    let valueString = String(data: data, encoding: .utf8)
    print("읽어온 데이터: \(valueString ?? "")")
    
    if let valueString = valueString {
        displayUserData(valueString)
    }
}

func displayUserData(_ userData: String) {
    // 사용자의 개인 정보를 표시하는 코드 작성
}

위 코드에서는 CBPeripheralDelegate 프로토콜을 사용하여 특성의 값을 읽어와서 출력하고 있습니다. 이제 읽어온 데이터를 이용하여 사용자의 개인 정보를 표시하는 코드를 작성하면 됩니다.

결론

Swift Core Bluetooth 프레임워크는 개발자들이 의료 기기와의 연동을 쉽게 구현할 수 있도록 도와주는 강력한 도구입니다. 이 글에서는 BLE 기기를 찾고, 서비스와 특성을 찾으며, 데이터를 주고받는 방법을 살펴보았습니다. 이를 바탕으로 의료 기기와의 연동을 구현할 수 있으며, 사용자의 건강 상태를 모니터링하거나 의료 정보를 수집할 수 있습니다.

참고 자료