Right way to send HEX data over BLE, struct.pack?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
mflmartin
Posts: 43
Joined: Sat Jul 23, 2016 7:30 pm

Right way to send HEX data over BLE, struct.pack?

Post by mflmartin » Sun Mar 07, 2021 11:21 pm

Hi,

What would be the right way to send this string over ble, with gattc_write?

Code: Select all

data_sfs = '7e00822c0100a5aa342906c15706cf5710382ce02e25d386302155369a1cd64023576dc1105a878e0f7f12bd79ae3ce5e297cf8f68e1234fae5d1b6d9cec0aca33b226adbe3506232abbc44e7a9483f3d54d4fb16b0bd15a343ea8027b9b9c77e1b3b4cdcbdced2c72b60b5d72d00c2b7e0d14677a2a137936a7a9b5990dc8faa4710f37ccb2'

data_sfs = bytearray(binascii.unhexlify(data_sfs))

ble.gattc_write(self._conn_handle, self._write_handle, data, 1)
	
Likewise, in order to decode a long HEX string, that might arrive in binary format from the BLE server?

I've seen, only a couple of examples, of BLE here, and they used either bytes directly, or they used struct. But I can't get my head to understand how can I struct.pack this bytearray, and tell it the size (format) of the struct... or if it is even necessary.

Thanks for the help in advance,

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Right way to send HEX data over BLE, struct.pack?

Post by jimmo » Thu Mar 11, 2021 5:24 am

mflmartin wrote:
Sun Mar 07, 2021 11:21 pm
I've seen, only a couple of examples, of BLE here, and they used either bytes directly, or they used struct. But I can't get my head to understand how can I struct.pack this bytearray, and tell it the size (format) of the struct... or if it is even necessary.
In this case you already have your packed data in your hex string. The struct.pack examples are where you start with integers and need to make it into bytes.

You shouldn't need the bytearray conversion from unhexlify -- it will return a "bytes" object, which you can already pass directly to gattc_write.

But what you have looks right and should work. Although I suspect you'll need to increase the MTU (see gattc_exchange_mtu).

On the reverse side, gatts_read will return the same bytes. You can convert it to a hex string with hexlify, but more likely you're going to want to look at individual bytes, or unpack it with struct.unpack -- it depends on what this data is encoding and what it means?

Post Reply