iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📶️

Transmitting M5Stack CoreS3 Camera Images via Bluetooth LE

に公開

KeyVisual

Introduction

I've recently started tinkering with IoT, and among other things, I've been experimenting with the M5Stack CoreS3.

In this article, I'll summarize my implementation for transmitting camera images from the CoreS3 to an iPhone via Bluetooth LE (hereafter BLE), as a memo for myself.

Here's a video of it in action:
https://www.youtube.com/watch?v=CHJW-Q-wOJY

In this article, I'll briefly touch on what BLE is, and then explain step-by-step how to transfer images from the M5Stack CoreS3 to an iPhone, including code.

Note that the sample code for this project is available on GitHub, so if you want to try it out, please refer to it.

https://github.com/edom18/M5StackCamera-BLE-Sample

About Bluetooth LE

Quoting from Wikipedia, it is described as follows:

Bluetooth Low Energy (Bluetooth LE, BLE) is a low-power wireless communication mode that is part of the Bluetooth wireless PAN technology, added from version 4.0. Bluetooth consists of Bluetooth Basic Rate/Enhanced Data Rate (BR/EDR) and Bluetooth Low Energy (LE)[1].

It is designed with the intention of enabling communication and implementation at lower power and lower cost compared to traditional BR/EDR. It is independent of BR/EDR and has no compatibility, although BR/EDR and LE can coexist. The original specification was developed by Nokia in 2006 under the name Wibree[2], and was integrated into Bluetooth 4.0 as Bluetooth Low Energy in December 2009.

Personal computers (PC: Windows, macOS, Linux, etc.) and mobile devices (Android devices, iPhone/iPad/Apple Watch[note 1], Windows Phone, BlackBerry, etc.) support Bluetooth Low Energy as standard, and it is widely adopted. It is used in sports and fitness, medical, PC peripherals[3], beacons[4], and other applications.

BLE Terminology

Here are some key terms needed when working with BLE:

  • Central
  • Peripheral
  • Advertising

Peripheral

"Peripheral" is an English word meaning "surrounding." Therefore, it is used for devices that are "peripheral," such as IoT devices or sensors.

Central

On the other hand, the "central" refers to devices like smartphones; they discover and connect to peripheral devices. In this configuration, for example, a connected temperature sensor (peripheral) sends temperature data to the central, which then processes it.

Advertising

In BLE, peripheral devices perform "advertising." The term "advertising" means something like "promotional activity." Essentially, it refers to the peripheral device emitting signals so that central devices can discover it.

About BLE Communication

BLE is built upon the following protocol stack:

Protocol Stack

Among these, GATT is particularly important for this article.

Note that the packet format exchanged over BLE is described in detail in the following article, so if you're interested, take a look:

http://marchan.e5.valueserver.jp/cabin/comp/jbox/arc212/doc21201.html

ATT (Attribute)

In the BLE protocol, ATT (Attribute) is the smallest entity defined in GATT. Therefore, all data is represented by ATT.

Below is a diagram showing the structure, quoted from the BLE specification:

Data Structure

The hierarchical structure is as follows:

GATT (Generic Attribute) Hierarchical Data Structure
Profile
 ├── Service <UUID>
 │    ├── Characteristic <UUID>
 │    │    ├── Properties
 │    │    ├── Value
 │    │    ├── Descriptor <UUID>
 │    │    │    └── Value
 │    │    ├── Descriptor <UUID>
 │    │    │    └── Value
 │    │    ├── ..
 │    ├── Characteristic <UUID>
 │    │
 ├── Service <UUID>

In other words, one Profile contains multiple Services, each Service has multiple Characteristics, and each Characteristic can have multiple Descriptors.

In particular, a Characteristic can be thought of as a "function" from an implementation perspective, as the word "characteristic" suggests. In this implementation, we define one Characteristic for "receiving commands from the iPhone" and another for "sending JPEG data."

About the Client Characteristic Configuration Descriptor (CCCD)

A Characteristic represents a function and holds its data. A Characteristic also has at least two attributes: the Characteristic Declaration and the Characteristic Value. The Characteristic Declaration includes properties that indicate how other devices can access it, such as read, write, or whether notifications can be received when data changes.

Furthermore, if the property permits notifications, you must write to a descriptor called the CCCD to enable notifications. If you don't, the characteristic may have notification capability but will not actually send notifications to other devices.

Writing 0x0001 to the CCCD enables notify, and writing 0x0002 enables indicate. (Indicate and notify are explained later.)

BLE Connection Flow

Now that we've covered the general mechanisms, let's move on to the actual implementation. First, the connection flow using BLE.

As mentioned earlier, the peripheral device performs advertising, the central catches that signal, and when it finds a device that holds the service it's looking for, it establishes a connection.

Advertising

First, let's look at the advertising implementation on the M5Stack CoreS3 side.

Advertising
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include <BLE2902.h>

#define SERVICE_UUID                 "FE56"
#define CONTROL_CHARACTERISTIC_UUID  "beb5483e-36e1-4688-b7f5-ea07361b26a8"
#define JPEG_CHARACTERISTIC_UUID     "c9d1cba2-1f32-4fb0-b6bc-9b73c7d8b4e2"
#define SERVER_NAME                  "M5CoreS3"

/* ================ BLE State ================ */
BLEServer *pServer = nullptr;
BLECharacteristic *pControlCharacteristic = nullptr;
BLECharacteristic *pJpegCharacteristic = nullptr;
bool deviceConnected = false;

// --------------------------------------------

void setupBle() {
  log("Init BLE");

  BLEDevice::init(SERVER_NAME);

  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  BLEService *pService = pServer->createService(SERVICE_UUID);

  pControlCharacteristic = pService->createCharacteristic(
    CONTROL_CHARACTERISTIC_UUID,
    BLECharacteristic::PROPERTY_READ |
    BLECharacteristic::PROPERTY_WRITE |
    BLECharacteristic::PROPERTY_WRITE_NR |
    BLECharacteristic::PROPERTY_NOTIFY
  );
  pControlCharacteristic->setCallbacks(new ControlCallbacks());
  pControlCharacteristic->addDescriptor(new BLE2902());

  pJpegCharacteristic = pService->createCharacteristic(
    JPEG_CHARACTERISTIC_UUID,
    BLECharacteristic::PROPERTY_READ     |
    BLECharacteristic::PROPERTY_INDICATE
  );
  pJpegCharacteristic->addDescriptor(new BLE2902());

  pService->start();

  BLEAdvertising *pAdvertising = pServer->getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->setScanResponse(true);
  pAdvertising->start();

  log("BLE ready");
}

Using the BLE library makes the configuration simple. We generate the server, service, and characteristics using the BLEDevice class.

The generation of each element is based on the hierarchical structure described earlier. That is, instances are created in a parent-child relationship: server → service → characteristic.

Also, as mentioned, when creating a Characteristic, you must specify its properties. Another important point is that characteristics that receive notifications need to have a CCCD descriptor added.

Certain descriptors have fixed UUIDs; for CCCD, it is defined as 0x2902. Below is the code adding the CCCD:

Adding CCCD
pJpegCharacteristic->addDescriptor(new BLE2902());

Once preparation is complete, advertising begins. The relevant code snippet is shown below:

Starting Advertising
BLEAdvertising *pAdvertising = pServer->getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
pAdvertising->start();

Executing this starts BLE advertising. To verify this information on iOS, you can use an app like BLE Scanner to check if the target service is being advertised.

https://apps.apple.com/jp/app/ble-scanner-4-0/id1221763603

Setting Up Callbacks

Even after advertising starts and a central discovers and connects, no processing begins by default. (It simply becomes internally connected.) To perform useful processing, you need to set up callbacks and handle them appropriately.

In the library used here, callbacks are set by subclassing the appropriate classes.

Below is the server callback. It tracks onConnect and onDisconnect. It can also track changes in the MTU value used for communication.

Server Callback Implementation
class MyServerCallbacks : public BLEServerCallbacks {
  void onConnect(BLEServer *server) override {
    Serial.println("connect");
    log("Connected a client.");
    deviceConnected = true;
  }

  void onDisconnect(BLEServer *server) override {
    Serial.println("=== BLE DISCONNECTED ===");
    log("Disconnected a client.");
    deviceConnected = false;
    BLEAdvertising *advertising = server->getAdvertising();
    if (advertising != nullptr) {
      advertising->start();
    }
  }

  void onMtuChanged(BLEServer *pServer, esp_ble_gatts_cb_param_t *param) override {
    Serial.println("On MTU changed.");
    if (!param) {
      return;
    }
    uint16_t mtu = param->mtu.mtu;
    Serial.printf("MTU=%u\n", mtu);
  }
};

Next is the callback for the "ControlCharacteristic," which is used to receive commands from the central. Here, when the central sends data "SEND_JPEG", it captures a camera image and prepares to send it back.

Control Characteristic Callback
class ControlCallbacks : public BLECharacteristicCallbacks {
  void onRead(BLECharacteristic *characteristic) override {
    Serial.println("Control characteristic read.");
    String value = characteristic->getValue();
    log(value);
  }

  void onWrite(BLECharacteristic *characteristic) override {
    if (isSending) return;

    String value = characteristic->getValue();
    Serial.printf("Received control characteristic: %s\n", value.c_str());
    if (value == "SEND_JPEG") {
      Serial.println("Command received.");
      log("Command received.");
      prepareSendJpegToCentral();
    }
  }
};

The next callback is for the "JpegCharacteristic." It is used to detect when the central has acknowledged receipt of data. Details will be explained later.

Jpeg Characteristic Callback
class JpegCharacteristicCallbacks : public BLECharacteristicCallbacks {
  void onStatus(BLECharacteristic* characteristic, Status s, uint32_t code) override {
    Serial.printf("s=%d, code=%d\n", s, code);
    
    switch (s) {
      case Status::SUCCESS_INDICATE:
        needsWaitForConfirm = false;
        break;
    }
  }
};

Sending Process

Once a command is received on the ControlCharacteristic, the actual sending begins. The preparation of image data and the sending process are as follows:

Image Send Preparation
void prepareSendJpegToCentral() {
  if (!deviceConnected || pJpegCharacteristic == nullptr) {
    Serial.println("No central");
    log("No central");
    return;
  }

  if (!checkCCCD()) {
    return;
  }

  // Wait a bit to ensure BLE connection is stable after CCCD write
  Serial.println("Waiting for BLE connection to stabilize...");

  gJpegBuffer.clear();
  if (!captureFrameJPEG(gJpegBuffer, 80)) {
    Serial.println("Failed to capture camera image.");
    log("Failed to capture camera image.");
    return;
  }

  totalSize = static_cast<uint32_t>(gJpegBuffer.size());
  Serial.printf("JPEG size: %lu bytes\n", static_cast<unsigned long>(totalSize));

  if (pServer != nullptr) {
    const uint16_t connId = pServer->getConnId();
    const uint16_t peerMtu = pServer->getPeerMTU(connId);
    if (peerMtu > 0) {
      negotiatedMtu = peerMtu;
    }
  }

  payloadSize = negotiatedMtu > 3 ? negotiatedMtu - 3 : 20;
  if (payloadSize < 20) {
    payloadSize = 20;
  }
  Serial.printf("MTU negotiated: %u, payload chunk: %u bytes\n",
                static_cast<unsigned>(negotiatedMtu),
                static_cast<unsigned>(payloadSize));

  needsSendHeader = true;
}

This step converts the camera image to JPEG and determines the JPEG size and the payload size for transmission. Once preparation is complete, the send is triggered.

Image Sending Process
void sendJpegToCentral() {
  const size_t chunk = std::min(payloadSize, gJpegBuffer.size() - offset);
  if (!sendChunk(pJpegCharacteristic, &gJpegBuffer[offset], chunk)) {
    Serial.printf("Chunk send failed at %u/%u (disconnected=%d)\n",
                  static_cast<unsigned>(chunkIndex + 1),
                  static_cast<unsigned>(totalChunks),
                  !deviceConnected);
    // Reset everything on failure
    resetParams();
    return;
  }

  offset += chunk;
  chunkIndex += 1;
  if ((chunkIndex % 10) == 0 || chunkIndex == totalChunks || chunkIndex <= 3) {
    Serial.printf("Chunk %u/%u sent (%u bytes total)\n",
                  static_cast<unsigned>(chunkIndex),
                  static_cast<unsigned>(totalChunks),
                  static_cast<unsigned>(offset));
  }

  // If not all data sent yet, proceed to next sending
  if (offset < gJpegBuffer.size() && deviceConnected) {
    return;
  }

  const bool transferComplete = (chunkIndex == totalChunks) && (offset == gJpegBuffer.size());
  if (!transferComplete) {
    Serial.printf("JPEG transfer incomplete (%u/%u chunks)\n",
                  static_cast<unsigned>(chunkIndex),
                  static_cast<unsigned>(totalChunks));
    // Reset everything on failure
    resetParams();
    return;
  }

  Serial.println("Has been sent.");
  log("Has been sent");

  Serial.printf("JPEG %s %luB (%u/%u)\n",
              transferComplete ? "sent" : "partial",
              static_cast<unsigned long>(offset),
              static_cast<unsigned>(chunkIndex),
              static_cast<unsigned>(totalChunks));

  resetParams();
}

// Header Sending
void sendHeaderToCentral() {
  // First, send the header as preparation
  uint8_t header[8];
  header[0] = 'J';
  header[1] = 'P';
  header[2] = 'E';
  header[3] = 'G';
  // Pack the size
  header[4] = (totalSize >> 24) & 0xFF;
  header[5] = (totalSize >> 16) & 0xFF;
  header[6] = (totalSize >> 8) & 0xFF;
  header[7] = totalSize & 0xFF;

  if (!sendChunk(pJpegCharacteristic, header, sizeof(header))) {
    Serial.println("Failed to send JPEG header");
    resetParams();
    return;
  }

  // Initialize sending info
  offset = 0;
  chunkIndex = 0;
  totalChunks = (gJpegBuffer.size() + payloadSize - 1) / payloadSize;

  needsSendHeader = false;
  isSending = true;
}

// Chunk Sending
static bool sendChunk(BLECharacteristic *characteristic, const uint8_t *data, size_t length) {
  if (!deviceConnected) {
    Serial.println("sendChunk: device not connected");
    return false;
  }
  if (characteristic == nullptr) {
    Serial.println("sendChunk: characteristic is null");
    return false;
  }
  if (data == nullptr || length == 0) {
    Serial.println("sendChunk: invalid data");
    return false;
  }

  characteristic->setValue(const_cast<uint8_t*>(data), length);
  characteristic->indicate(); // indicate is explained later

  if (!deviceConnected) {
    Serial.println("sendChunk: connection lost during notify");
    return false;
  }

  return true;
}

Data transmission is performed by first setting the value to the characteristic and then "notifying" it. In this case, we use the indicate() function for sending.

Indicate vs Notify

BLE actually provides two communication methods: indicate() and notify(). You may have noticed the following property settings in the characteristic definition:

Property Settings
pJpegCharacteristic = pService->createCharacteristic(
  JPEG_CHARACTERISTIC_UUID,
  BLECharacteristic::PROPERTY_READ     |
  BLECharacteristic::PROPERTY_INDICATE
);

The BLECharacteristic::PROPERTY_INDICATE specified here is that setting. There is also BLECharacteristic::PROPERTY_NOTIFY, and you choose which communication method to use by setting the appropriate property.

Indicate is a notification that requests receipt confirmation from the central. It is useful when you need to reliably deliver data, as in our case. On the other hand, Notify is a one-way notification, suitable for cases where missing a notification is not a serious problem, such as periodic temperature sensor readings.

Indicate and Confirm

For reliable data transmission, we used indicate(), which allows for receipt confirmation. According to the BLE specification, you must not send subsequent data until a confirm signal (the receipt confirmation from the central) is received. Therefore, we track the onStatus() function in the JPEG characteristic callback and wait for the confirm before sending the next chunk.

Below is the re-posted callback for JpegCharacteristic:

Checking Status in Callback
class JpegCharacteristicCallbacks : public BLECharacteristicCallbacks {
  void onStatus(BLECharacteristic* characteristic, Status s, uint32_t code) override {
    Serial.printf("s=%d, code=%d\n", s, code);
    
    switch (s) {
      case Status::SUCCESS_INDICATE:
        needsWaitForConfirm = false;
        break;
    }
  }
}

Sending in the loop() Function

The loop() function runs continuously, and we send one chunk per loop iteration.

Sending in the loop() Function
void loop() {
  // ===== (previous code omitted) =====

  if (needsSendHeader) {
    sendHeaderToCentral();
    return;
  }

  if (isSending) {
    sendJpegToCentral();
  }
}

This turned out to be a tricky pitfall. In my initial implementation, I tried to send all chunks inside the callback. However, the iPhone side never received any data. Then, I moved the sending process to the loop() function, and it worked successfully.

iOS Side Implementation

The sending process is now complete. Next, let's look at the receiving process on the iOS side.

The overall implementation flow is as follows:

  1. Use the CoreBluetooth framework
  2. Establish a connection using CBCentralManager
  3. Implement a delegate for the central
  4. Implement a delegate for the peripheral

Scanning and Connecting to a Peripheral

As mentioned earlier, the peripheral is advertising. We find it by scanning.

Start Scanning
private let serviceUUID = CBUUID(string: "FE56")

// --------

private func beginScanning() {
  guard shouldScan else { return }
  central.scanForPeripherals(withServices: [serviceUUID],
                                  options: [CBCentralManagerScanOptionAllowDuplicatesKey: false])
}

All scan results are handled by implementing delegate methods. When creating a CBCentralManager, we set the delegate to self as follows:

Delegate Setup
private lazy var central: CBCentralManager = {
  CBCentralManager(delegate: self, queue: centralQueue)
}()

We won't go into the full detail of the delegate implementation here. We'll only show the handling when a peripheral is discovered. Please refer to the GitHub repository for the complete code. When a peripheral is found, we set a delegate and call central.connect() to attempt connection.

CBCentralManagerDelegate
extension BLEJpegSample: CBCentralManagerDelegate {
  public func centralManager(_ central: CBCentralManager,
                             didDiscover peripheral: CBPeripheral,
                             advertisementData: [String: Any],
                             rssi RSSI: NSNumber) {
    updateStatus("Found \(peripheral.name ?? "M5CoreS3")")
    shouldScan = false
    central.stopScan()
    updateState(.connecting)
    targetPeripheral = peripheral
    peripheral.delegate = self
    central.connect(peripheral, options: nil)
  }
}

Receiving Data from the Peripheral

Below is an excerpt of the delegate handling for the peripheral. The first part processes the characteristics on the peripheral.

An important point: as mentioned earlier, for jpegCharacteristic, you need to call peripheral.setNotifyValue(true, for: jpegPeripheral) to write to the CCCD. This writes either 0x0001 or 0x0002 to the CCCD.

CBPeripheralDelegate
extension BLEJpegSample: CBPeripheralDelegate {
  public func peripheral(_ peripheral: CBPeripheral,
                        didDiscoverCharacteristicsFor service: CBService,
                        error: Error?) {
  if let error = error {
    updateState(.error)
    updateStatus("Characteristic discovery failed: \(error.localizedDescription)")
    return
  }
  guard let chars = service.characteristics else { return }
  for characteristic in chars {
    switch characteristic.uuid {
    case controlCharacteristicUUID:
      controlCharacteristic = characteristic
    case jpegCharacteristicUUID:
      jpegCharacteristic = characteristic
      peripheral.setNotifyValue(true, for: characteristic)
      updateStatus("Subscribing to JPEG")
    default:
      continue
    }
  }

  public func peripheral(_ peripheral: CBPeripheral,
                         didUpdateValueFor characteristic: CBCharacteristic,
                         error: Error?) {
    if let error = error {
      updateStatus("Update error: \(error.localizedDescription)")
      return
    }
      
    guard let data = characteristic.value else { return }
    if characteristic.uuid == jpegCharacteristicUUID {
      handleJpegNotification(data)
    }
  }
}

By setting setNotifyValue to true, notifications from the peripheral can be received. Then, via the delegate method didUpdateValueFor:error, data from the peripheral is received. In this implementation, we accumulate chunk data and, upon receiving the last piece, convert it into an image.

Handling Received Data

We'll now explain the data reception process. The received Data initially contains a header. The header is 8 bytes: the first 4 bytes contain the string JPEG, and the next 4 bytes contain the image size.

Header Reception and Parsing
private func handleJpegNotification(_ data: Data) {
  print("[BLEJpegSample] Received notification with \(data.count) bytes")
    
  // If the expected image length is already known, we have already received the header
  if expectedImageLength == nil {
    headerBuffer.append(data)
      
    // In this sample, the header is assumed to be 8 bytes
    let requiredHeaderBytes = 8
    if headerBuffer.count < requiredHeaderBytes {
      updateStatus("Receiving header (\(headerBuffer.count)/\(requiredHeaderBytes))")
      return
    }

    // In this sample, the header starts with "JPEG", so we verify that
    let header = headerBuffer.prefix(requiredHeaderBytes)
    let signature = Data(header.prefix(4))
    guard signature == Data("JPEG".utf8) else {
      updateStatus("Unexpected JPEG header")
      resetTransferState()
      return
    }

    // The last 4 bytes of the header are the image data size
    let lengthBytes = header.suffix(4)
    var length: UInt32 = 0
    for byte in lengthBytes {
      length = (length << 8) | UInt32(byte)
    }
    let expectedCount = Int(length)
    expectedImageLength = expectedCount
    let signatureString = String(data: signature, encoding: .ascii) ?? "JPEG"
    print("[BLEJpegSample] Header signature=\(signatureString) expected=\(expectedCount) bytes")
    updateStatus("Header received: \(expectedCount) bytes")

    let remainder = headerBuffer.dropFirst(requiredHeaderBytes)
    headerBuffer.removeAll(keepingCapacity: false)
    if !remainder.isEmpty {
      transferBuffer.append(contentsOf: remainder)
      print("[BLEJpegSample] Appended remainder \(remainder.count) bytes")
    }

    if let expected = expectedImageLength {
      // If the buffer already has the expected size, finalize the transfer
      if transferBuffer.count >= expected {
        finalizeTransfer()
      }
      else {
        let received = transferBuffer.count
        print("[BLEJpegSample] After header remainder -> \(received)/\(expected) bytes")
        updateStatus("Receiving JPEG (\(received)/\(expected))")
        scheduleTransferCompletion()
      }
    }
    count = 0
    return
  }
  // ===== later part omitted =====
}

After parsing the header and determining the expected image size, we set it and prepare for subsequent data reception. Below is the part that accumulates data into the buffer when further data is received.

Accumulating Received Data
private func handleJpegNotification(_ data: Data) {
  // ===== previous part omitted =====

  // ---------------------------
  // Data reception after header

  transferBuffer.append(data)
  guard let expected = expectedImageLength else {
    scheduleTransferCompletion()
    return
  }

  count += 1
    
  let received = transferBuffer.count
  print("[BLEJpegSample] Chunk(\(count)) received, total \(received)/\(expected)")
  if received >= expected {
    finalizeTransfer()
  }
  else {
    updateStatus("Receiving JPEG (\(received)/\(expected))")
    scheduleTransferCompletion()
  }
}

Converting to an Image

After receiving all data, we convert it to an image and display it on the screen.

Image Conversion
private func finalizeTransfer() {
  guard let expected = expectedImageLength,
        transferBuffer.count >= expected else {
    print("[BLEJpegSample] finalizeTransfer skipped; buffer=\(transferBuffer.count) expected=\(expectedImageLength ?? -1)")
    return
  }
    
  let jpegSlice = transferBuffer.prefix(expected)
  let jpegData = Data(jpegSlice)
  let hasValidHeader = jpegData.starts(with: [0xFF, 0xD8])
  let hasValidFooter = jpegData.suffix(2) == Data([0xFF, 0xD9])

  chunkTimeoutWorkItem?.cancel()
  chunkTimeoutWorkItem = nil
  headerBuffer.removeAll(keepingCapacity: false)
  transferBuffer.removeAll(keepingCapacity: false)
  expectedImageLength = nil

  guard hasValidHeader, hasValidFooter else {
    print("[BLEJpegSample] JPEG markers invalid header=\(hasValidHeader) footer=\(hasValidFooter)")
    updateStatus("JPEG invalid (missing markers)")
    DispatchQueue.main.async {
      self.lastJpegData = nil
#if canImport(UIKit)
      self.lastImage = nil
#endif
    }
    return
  }

  DispatchQueue.main.async {
    self.lastJpegData = jpegData
#if canImport(UIKit)
    self.lastImage = UIImage(data: jpegData)
#endif
    self.statusMessage = "JPEG received (\(jpegData.count) bytes)"
  }
  print("[BLEJpegSample] JPEG transfer complete (\(jpegData.count) bytes)")
}

We extract the expected amount of data from the buffer based on the header, and convert it to a UIImage using UIImage(data:). This class is an ObservableObject, so the SwiftUI side can detect changes and display the updated data in the UI.

Displaying the Image
@StateObject private var ble = BLEJpegSample()

// -----------------------

if let image = ble.lastImage {
    Image(uiImage: image)
        .resizable()
        .scaledToFit()
        .frame(maxHeight: 240)
        .border(.gray)
}

Conclusion

This concludes the implementation explanation for transferring JPEG images via BLE.

While connecting between iPhones might have fewer pitfalls, using devices like the M5Stack introduces several nuanced issues that can be challenging. However, the joy of seeing it work with actual hardware is also extra special.

This implementation was actually created with the idea of sending the camera image from the M5Stack to a smartphone, and then possibly having an AI analyze it. In other words, I was thinking of using the smartphone as a base to control various things.

I plan to explore IoT x AI further, so I'll write another article when I implement something new.

Discussion