iosswiftbluetooth-lowenergycbperipheralhm-10

BLE Characteristic not reading full string at once


I m sending data from slider and buttons to Arduino through Hm10, but the problem is my string is getting read in two parts, it is getting divided from second last characteristic to a new line string.

 func writeValue(data: String){
    let valueString = (data as NSString).data(using: String.Encoding.utf8.rawValue)
    print("data string is" , data)

    //change the "data" to valueString
    if let blePeripheral = blePeripheral{
        if let txCharacteristic = txCharacteristic {
            blePeripheral.writeValue(valueString!, for: txCharacteristic, type: CBCharacteristicWriteType.withResponse)
            print(valueString!)
        }
    }
}

@IBAction func switchAction(_ sender: Any) {
    if switchUI.isOn {
        print("On ")
       // writeCharacteristic(val: 1)
        writeValue(data:"tp1z  ")
    }

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    print("characterstic value is" , characteristic.value!)
    if characteristic == rxCharacteristic {
        if let ASCIIstring = NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue) {
            characteristicASCIIValue = ASCIIstring
            print("Value Recieved: \((characteristicASCIIValue as String))")

            NotificationCenter.default.post(name:NSNotification.Name(rawValue: "Notify"), object: nil)

        }
    }
}


 func updateIncomingData () {

    NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "Notify"), object: nil , queue: nil){
        notification in
        let appendString = "\n"
        let myFont = UIFont(name: "Helvetica Neue", size: 15.0)
        let myAttributes2 = [NSAttributedStringKey.font: myFont!, NSAttributedStringKey.foregroundColor: UIColor.red]
       let attribString = NSAttributedString(string: "[Incoming]: " + (characteristicASCIIValue as String) + appendString, attributes: myAttributes2)

        let newAsciiText = NSMutableAttributedString(attributedString: self.consoleAsciiText!)
        self.baseTextView.attributedText = NSAttributedString(string: characteristicASCIIValue as String , attributes: myAttributes2)

        newAsciiText.append(attribString)

        self.consoleAsciiText = newAsciiText
        self.baseTextView.attributedText = self.consoleAsciiText
        print("incoming")

    }
}

I am not able to understand why is it breaking my string from second last character.


Solution

  • So in the end, I used to empty characters as it was breaking my string from second last character like below:-

    writeValue(data:"tp1z  ")
    

    It worked for me.