Skip to content

Instantly share code, notes, and snippets.

@harimototatsu
Created June 11, 2021 04:42
Show Gist options
  • Save harimototatsu/c681bd48fdab28e1bdc4533745f14648 to your computer and use it in GitHub Desktop.
Save harimototatsu/c681bd48fdab28e1bdc4533745f14648 to your computer and use it in GitHub Desktop.
ble
//
// BLEManager.swift
// BlueBackground
//
// Created by Anas Imtiaz on 11/04/2020.
// Copyright © 2020 NovelBits. All rights reserved.
//
import Foundation
import CoreBluetooth
import CoreLocation
struct Peripheral: Identifiable {
let id: Int
let name: String
let rssi: Int
}
class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeripheralManagerDelegate {
var myCentral: CBCentralManager!
var myPeripheralManager: CBPeripheralManager!
var myService: CBMutableService!
var myp:CBPeripheral?
@Published var isSwitchedOn = false
@Published var peripherals = [Peripheral]()
let serviceUUID = CBUUID(string: "229BFF00-03FB-40DA-98A7-B0DEF65C2D4B")
let peripheralServiceUUID = CBUUID(string: "229BFF00-03FB-40DA-98A7-B0DEF65C2D4B")
let peripheralCharacteristicUUID = CBUUID(string: "229BFF00-03FB-40DA-98A7-B0DEF65C2D4B")
override init() {
super.init()
myCentral = CBCentralManager(delegate: self, queue: nil)
myCentral.delegate = self
myPeripheralManager = CBPeripheralManager(delegate: self, queue: nil)
myPeripheralManager.delegate = self
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
isSwitchedOn = true
}
else {
isSwitchedOn = false
}
}
func centralManager(_ myCentral: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
var peripheralName: String!
if let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String {
peripheralName = name
}
else {
peripheralName = "Unknown"
}
let PERIPHERAL = Peripheral(id: peripherals.count, name: peripheralName, rssi: RSSI.intValue)
print(PERIPHERAL)
peripherals.append(PERIPHERAL)
if PERIPHERAL.name == "konashi3-f03f16"{
myCentral.connect(peripheral)
myCentral.stopScan()
centralManager(myCentral, didConnect: peripheral)
myCentral.cancelPeripheralConnection(peripheral)
}
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
<#code#>
}
func centralManager(_ myCentral: CBCentralManager, didConnect peripheral: CBPeripheral) {
// myPeripheralManager.delegate = self
// print("接続成功")
// 指定のサービスを探す
// let services: [CBUUID] = [CBUUID(string: "180A")]
// peripheral.discoverServices([peripheralServiceUUID])
// すべてのサービスを探す
PERIPHERAL = peripheral
peripheral.discoverServices(nil)
}
func centralManagr(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
print("connection failed.")
}
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
if let error = error {
print("エラー: \(error)")
return
}
guard let services = peripheral.services, services.count > 0 else {
print("no services")
return
}
print("\(services.count) 個のサービスを発見! \(services)")
// for service in services {
// // キャラクタリスティック探索開始
// peripheral.discoverCharacteristics(nil, for: service)
// }
}
// 接続が失敗すると呼ばれるデリゲートメソッド
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
print("connection failed.")
}
func startScanning() {
print("startScanning")
myCentral.scanForPeripherals(withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey: false])
}
var PERIPHERAL: CBPeripheral!
func connect() {
for periphera in peripherals {
if periphera.name != nil && periphera.name == "konashi3-f03f16" {
myCentral?.stopScan()
break;
}
}
if PERIPHERAL != nil {
myCentral.connect(PERIPHERAL!, options: nil)
}
}
func stopScanning() {
print("stopScanning")
myCentral.stopScan()
}
// CBPeripheralManagerDelegate
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment