/*
 *  Phonk based BLE Oximeter
 */

ui.addTitle(app.name);
network.bluetoothLE.start();

var bleClient = network.bluetoothLE.createClient();

// -> Write here the BLE device MAC Address
var deviceMacAddress = "00:A0:50:1F:23:70";
var gattServiceUUID = "49535343-fe7d-4ae5-8fa9-9fafd205e455";
var gattCharacteristicUUID = "49535343-1e4d-4bd9-ba61-23c647249616";
var gattCharacteristicDescriptorUUID = "00002902-0000-1000-8000-00805f9b34fb";
var gattNotificationEnable = 0x0100;

network.bluetoothLE.start()

//Main text display area
var txt = ui.addTextList(0.1, 0.1, 0.8, 0.2).autoScroll(true)
txt.props.textSize = 15

var dt = ui.addTextList(0.1, 0.35, 0.8, 0.2).autoScroll(true)
dt.props.textSize = 15


//scan bluetooth low energy networks
//this should show devices -> services -> characteristics
ui.addToggle(['Scan bluetooth', 'Stop scan'], 0.25, 0.7, 0.5, 0.1).onChange(function (e) {
  if (e.checked) {
    network.bluetoothLE.scan(function (data) {
      txt.add(data.name + ' ' + data.rssi + ' ' + data.mac)
    })
  } else {
    network.bluetoothLE.stopScan()
  }
})

// connect to a device
ui.addToggle(['Connect', 'Disconnect'], 0.25, 0.85, 0.5, 0.1).onChange(function (e) {
  if (e.checked) {
    bleClient.connectDevice(deviceMacAddress)
  } else {
    bleClient.disconnectDevice(deviceMacAddress)
  }
})

// enable notification
// var send = ui.addButton('Enable the Notification', 0.7, 0.85, 0.2, 0.1).onClick(function () {
//   bleClient.write(gattNotificationEnable, deviceMacAddress, gattServiceUUID, gattCharacteristicDescriptorUUID)
// })

bleClient.onNewDeviceStatus(function (e) {
  // double check if is the device we want to connect
  if (e.deviceMac === deviceMacAddress && e.status === 'connected') {
    bleClient.readFromCharacteristic(deviceMacAddress, gattServiceUUID, gattCharacteristicUUID)
    txt.add('connected to ' + e.deviceName)
  }
})

//https://stackoverflow.com/a/34310051
function toHexString(byteArray) {
  return Array.from(byteArray, function(byte) {
    return ('0' + (byte & 0xFF).toString(16)).slice(-2);
  }).join('')
}

bleClient.onNewData(function (e) {
  //var value = util.parseBytes(e.value, "string")
  // console.log('(' + e.deviceName + ') ' + e.deviceMac + '/' + e.serviceUUID + '/' + e.characteristicUUID + ' --> ')
  dt.add(toHexString(e.value))
})