<commit_before>import Foundation
import CoreBluetooth

public class MeshManager : NSObject {

    var nodes: [String: CBPeripheral]
    var centralManager: CBCentralManager?
    var peripheralManager: CBPeripheralManager?
    var characteristic: CBMutableCharacteristic?

    internal var pastConnections: [UUID]

    override public init() {
        nodes = [:]
        pastConnections = []
    }

    public func start() {
        if centralManager == nil {
             centralManager = CBCentralManager(delegate: self, queue: nil)
        }
        if peripheralManager == nil {
            peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
        }
    }

    public func listConnectedNodes() -> [String] {
        return nodes.keys.map { $0 }
    }

    public func send(message: MeshMessages, toNodeNamed name: String) {
        guard let peripheral = nodes[name],
            let characteristic = peripheral.services?.first?.characteristics?.first else { return }

        peripheral.writeValue(message.messageType, for: characteristic, type: .withoutResponse)
    }

    public func send(message: MeshMessages, toNodeNamed name: String, forCharacteristic characteristic: CBMutableCharacteristic) {
        guard let peripheral = nodes[name] else { return }
        
        peripheral.writeValue(message.messageType, for: characteristic, type: .withoutResponse)
    }
    
    public func sendToAllNodes(message: MeshMessages) {
        for node in listConnectedNodes() {
            send(message: message, toNodeNamed: node)
        }
    }

    public func disconnect(fromNode node: String) {
        guard let peripheral = nodes[node] else { return }
        centralManager?.cancelPeripheralConnection(peripheral)
    }
}

extension MeshManager : CBPeripheralManagerDelegate {
    public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        if peripheral.state == .poweredOn {
            print("peripheral is powered on")
            characteristic = CBMutableCharacteristic(type: CBUUID(string: "12EC1524-CEC6-11E5-B3AE-0002A5D5C51B"),
                                                         properties: [CBCharacteristicProperties.read, CBCharacteristicProperties.write, CBCharacteristicProperties.writeWithoutResponse],
                                                         value: nil,
                                                         permissions: [CBAttributePermissions.readable, CBAttributePermissions.writeable])
            let service = CBMutableService(type: CBUUID(string: "12ec7140-cec6-11e5-b3ae-0002a5d5c51b"), primary: true)
            service.characteristics = [(characteristic)!]

            peripheralManager?.add(service)
            
            //peripheralManager?.startAdvertising([CBAdvertisementDataServiceUUIDsKey : [service.uuid], CBAdvertisementDataLocalNameKey: "foo"])
 
        } else {
            print("Peripheral Manager for Bluetooth is not on")
        }
        
    }
    
    public func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {
        if ((error) != nil) {
            print("error starting advertising: \(error.debugDescription)")
        }
    }
    
    public func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {
        print("Service added")
        let uuid = service.characteristics?.first?.uuid
        print("UUID of added service characteristic is \(uuid)")
        if ((error) != nil) {
            print("error adding service")
        }
    }
    
    public func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
        print("Received write request!")
    }


}

extension MeshManager : CBCentralManagerDelegate {
    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            self.centralManager?.scanForPeripherals(withServices: nil, options: nil)
        } else {
            print("Central Manager for Bluetooth is not on")<commit_msg>Holly|Cannon - Check first byte of write request for message type.<commit_after>import Foundation
import CoreBluetooth

public class MeshManager : NSObject {

    var nodes: [String: CBPeripheral]
    var centralManager: CBCentralManager?
    var peripheralManager: CBPeripheralManager?
    var characteristic: CBMutableCharacteristic?

    internal var pastConnections: [UUID]

    override public init() {
        nodes = [:]
        pastConnections = []
    }

    public func start() {
        if centralManager == nil {
             centralManager = CBCentralManager(delegate: self, queue: nil)
        }
        if peripheralManager == nil {
            peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
        }
    }

    public func listConnectedNodes() -> [String] {
        return nodes.keys.map { $0 }
    }

    public func send(message: MeshMessages, toNodeNamed name: String) {
        guard let peripheral = nodes[name],
            let characteristic = peripheral.services?.first?.characteristics?.first else { return }

        peripheral.writeValue(message.messageType, for: characteristic, type: .withoutResponse)
    }

    public func send(message: MeshMessages, toNodeNamed name: String, forCharacteristic characteristic: CBMutableCharacteristic) {
        guard let peripheral = nodes[name] else { return }
        
        peripheral.writeValue(message.messageType, for: characteristic, type: .withoutResponse)
    }
    
    public func sendToAllNodes(message: MeshMessages) {
        for node in listConnectedNodes() {
            send(message: message, toNodeNamed: node)
        }
    }

    public func disconnect(fromNode node: String) {
        guard let peripheral = nodes[node] else { return }
        centralManager?.cancelPeripheralConnection(peripheral)
    }
}

extension MeshManager : CBPeripheralManagerDelegate {
    public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        if peripheral.state == .poweredOn {
            print("peripheral is powered on")
            characteristic = CBMutableCharacteristic(type: CBUUID(string: "12EC1524-CEC6-11E5-B3AE-0002A5D5C51B"),
                                                         properties: [CBCharacteristicProperties.read, CBCharacteristicProperties.write, CBCharacteristicProperties.writeWithoutResponse],
                                                         value: nil,
                                                         permissions: [CBAttributePermissions.readable, CBAttributePermissions.writeable])
            let service = CBMutableService(type: CBUUID(string: "12ec7140-cec6-11e5-b3ae-0002a5d5c51b"), primary: true)
            service.characteristics = [(characteristic)!]

            peripheralManager?.add(service)
            
            //peripheralManager?.startAdvertising([CBAdvertisementDataServiceUUIDsKey : [service.uuid], CBAdvertisementDataLocalNameKey: "foo"])
 
        } else {
            print("Peripheral Manager for Bluetooth is not on")
        }
        
    }
    
    public func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {
        if ((error) != nil) {
            print("error starting advertising: \(error.debugDescription)")
        }
    }
    
    public func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {
        print("Service added")
        let uuid = service.characteristics?.first?.uuid
        print("UUID of added service characteristic is \(uuid)")
        if ((error) != nil) {
            print("error adding service")
        }
    }
    
    public func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
        if (requests.first?.value?.first == 3) {
            print("Received HEARTBEAT!")
        } else if (requests.first?.value?.first == 6) {
            print("Received VOTING HB!")
        } else {
            print("Received some other kind of write request! Message type is \(requests.first?.value?.first)")
        }
    }


}

extension MeshManager : CBCentralManagerDelegate {
    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            self.centralManager?.scanForPeripherals(withServices: nil, options: nil)
        } else {
            print("Central Manager for Bluetooth is not on")
{'fraction_non_alphanumeric': 0.08713546566321731, 'fraction_numerical': 0.00940733772342427, 'mean_word_length': 2.5977157360406093, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3075779', 'n_tokens_mistral': 2232, 'n_tokens_neox': 2092, 'n_words': 525}