Why does BLE-program ble_simple_central.py respond with instead of data

Summary

The Micropython code example for Bluetooth Low Energy (BLE) communication between a central and peripheral device using ble_simple_central.py and ble_simple_peripheral.py is not working as expected. The peripheral device is able to print received data correctly, but the central device is only printing <memoryview> instead of the actual data.

Root Cause

The root cause of this issue is that the on_notify callback in ble_simple_central.py is not properly handling the received data. The memoryview object is being printed directly, instead of being decoded and printed as a string.

Why This Happens in Real Systems

This happens in real systems because Micropython uses memoryview objects to represent binary data, and if not handled properly, it can lead to unexpected behavior. In this case, the on_notify callback is not properly decoding the received data, resulting in the <memoryview> being printed.

Real-World Impact

The real-world impact of this issue is that the central device is not able to properly receive and process data from the peripheral device, which can lead to unexpected behavior and errors in the system.

Example or Code

def on_rx(v):
    # Decode the memoryview object as a string
    data = v.decode('utf-8')
    print("RX", data)
central.on_notify(on_rx)

How Senior Engineers Fix It

Senior engineers would fix this issue by properly decoding the memoryview object as a string in the on_notify callback. They would use the decode method to convert the binary data to a string, and then print the decoded data.

Why Juniors Miss It

Juniors may miss this issue because they are not familiar with the memoryview object and how to properly handle it in Micropython. They may not know that the memoryview object needs to be decoded as a string before it can be printed, and may instead try to print it directly, resulting in the <memoryview> being printed. Key takeaways include:

  • Properly handling binary data in Micropython is crucial to avoid unexpected behavior
  • Decoding memoryview objects is necessary to convert binary data to a string
  • Understanding the nuances of Micropython and its handling of binary data is essential for developing reliable BLE applications.