Help sending ble_client.ble_write value

I have a BLE device that I’m trying to send a value to one of the characteristics. I’m not familiar with C++ but have experience in other languages (JS, Python) but nothing with extreme typing like C++ it seems like.

I have a global variable that comes from an number (template) (1-100)

globals:
  - id: current_head_tilt
    type: int
    initial_value: "0"
    restore_value: no

- ble_client.ble_write:
    id: CJBed
    service_uuid: AA000000-A000-00A0-00A0-00A0A0A0000000
    characteristic_uuid: BB000000-A000-00A0-00A0-00A0A0A0000000
    value: !lambda |-
      return id(current_head_tilt);

and I keep getting an error on compile:

error: could not convert 'current_head_tilt->esphome::globals::GlobalsComponent<int>::value()' from 'int' to 'std::vector<unsigned char>'

I eventually need to convert the number into a hex value and then pass it along in the value for the ble_write but am having difficulties getting passed this step.

Could someone provide any help? This is really the first time I’ve used the ble_client

Hi @siege36,

the ble_write method needs a “byte array” (or vector in C++ lingo).

As you have an int but only numbers between 0-100, you need to get at least the first byte from the integer.

Unfortunately, I can’t set up a test environment right now, but you could try something like this:

value: !lambda |-
      uint8_t first_byte = id(current_head_tilt) & 0x000000ff;
      return first_byte;

The & is a “binary and” operator, the 0x000000ff acts as a “mask” to which bits you want to have, with ff beeing the last 8 bits. As the cpu cores used by ESP are little endian, these should be the value between 0-100.

If the compiler can not convert a single byte to an array/vector of bytes, you might need to do this by hand as well.

value: !lambda |-
      uint8_t first_byte = id(current_head_tilt) & 0x000000ff;
      vector<unsigned char> result { first_byte };
      return result;

But as I said, unfortunately I have no compiler at hand to test this out, but it might give you the right direction.

Best regards
mrzottel

@mrzottel

Thanks so much for your help. I had to declare the vector’s standard class but that got me to where I need to go.

For anyone else looking for how to send an global int number to a ble_write command:

- ble_client.ble_write:
    id: Bed
    service_uuid: DB801000-F324-29C3-38D1-85C0C2E86885
    characteristic_uuid: DB801041-F324-29C3-38d1-85C0C2E86885
    value: !lambda |-
      uint8_t first_byte = id(current_head_tilt) & 0x000000ff;
      std::vector<unsigned char> result { first_byte };
      return result;
1 Like