package ble import ( "ble_simulator/internal/device" "ble_simulator/internal/tui" "tinygo.org/x/bluetooth" ) // SetupService configures the GATT service with command and notify characteristics func SetupService(adapter *bluetooth.Adapter, state *device.DeviceState, logger *tui.LogBuffer) (*bluetooth.Characteristic, error) { var notifyChar bluetooth.Characteristic err := adapter.AddService(&bluetooth.Service{ UUID: ServiceUUID, Characteristics: []bluetooth.CharacteristicConfig{ { UUID: CommandCharUUID, Flags: bluetooth.CharacteristicWritePermission | bluetooth.CharacteristicWriteWithoutResponsePermission, WriteEvent: func(client bluetooth.Connection, offset int, value []byte) { cmd := string(value) logger.RX("Command: %s", cmd) response := state.ProcessCommand(cmd) logger.TX("Response: %s", response) // Non-blocking write in goroutine to avoid blocking the BLE stack go func() { _, err := notifyChar.Write([]byte(response + "\n")) if err != nil { logger.Err("Failed to send response: %v", err) } }() }, }, { UUID: NotifyCharUUID, Flags: bluetooth.CharacteristicReadPermission | bluetooth.CharacteristicNotifyPermission, Handle: ¬ifyChar, }, }, }) if err != nil { return nil, err } return ¬ifyChar, nil }