Skip to content

Add GATT Peripheral example for ESP32 #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
3 changes: 3 additions & 0 deletions esp32-ble-peripheral-sdk/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
cmake_minimum_required(VERSION 3.29)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(main)
39 changes: 39 additions & 0 deletions esp32-ble-peripheral-sdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# esp32-ble-peripheral-sdk

This example demonstrates how to integrate with the ESP-IDF SDK via CMake and how to use the the SDK to advertise as a Bluetooth iBeacon from Swift. This example is specifically made for the RISC-V MCUs from ESP32 (the Xtensa MCUs are not currently supported by Swift).

## Requirements

- Set up the [ESP-IDF](https://docs.espressif.com/projects/esp-idf/en/stable/esp32/) development environment. Follow the steps in the [ESP32-C6 "Get Started" guide](https://docs.espressif.com/projects/esp-idf/en/v5.2/esp32c6/get-started/index.html).
- Make sure you specifically set up development for the RISC-V ESP32-C6, and not the Xtensa based products.

- Before trying to use Swift with the ESP-IDF SDK, make sure your environment works and can build the provided C/C++ sample projects, in particular:
- Try building and running the "get-started/blink" example from ESP-IDF written in C.

## Building

- Make sure you have a recent nightly Swift toolchain that has Embedded Swift support.
- If needed, run export.sh to get access to the idf.py script from ESP-IDF.
- Specify the nightly toolchain to be used via the `TOOLCHAINS` environment variable and the target board type by using `idf.py set-target`.
``` console
$ cd esp32-ble-peripheral-sdk
$ export TOOLCHAINS=...
$ . <path-to-esp-idf>/export.sh
$ idf.py set-target esp32c6
$ idf.py build
```

## Running

- Connect the Esp32-C6-Bug board over a USB cable to your Mac. Alternatively you can just connect external LED to GPIO pin 8 on any other board.
- Connect RX pin of USB-UART converter to TX0 pin of your board if you need serial ouput. You may also need to connect GND converter pin to the GND pin of the board.
- Use `idf.py` to upload the firmware and to run it:

```console
$ idf.py flash
```

- Find the peripheral advertised as `ESP32-C6 XX:XX:XX:XX:XX:XX` in a Bluetooth scanner app like LightBlue or nRF Connect.

![LightBlue](assets/images/lightblue.jpg)
![nRF Connect](assets/images/nrfconnect.jpg)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
69 changes: 69 additions & 0 deletions esp32-ble-peripheral-sdk/main/ATTAttributePermissions.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors.
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//

/// ATT attribute permission bitfield values. Permissions are grouped as
/// "Access", "Encryption", "Authentication", and "Authorization". A bitmask of
/// permissions is a byte that encodes a combination of these.
@frozen
public struct ATTAttributePermissions: OptionSet, Equatable, Hashable, Sendable {

public var rawValue: UInt8

public init(rawValue: UInt8) {
self.rawValue = rawValue
}
}

// MARK: - ExpressibleByIntegerLiteral

extension ATTAttributePermissions: ExpressibleByIntegerLiteral {

public init(integerLiteral value: UInt8) {
self.rawValue = value
}
}

// MARK: - CustomStringConvertible

extension ATTAttributePermissions: CustomStringConvertible, CustomDebugStringConvertible {

public var description: String {
"0x" + rawValue.toHexadecimal()
}

/// A textual representation of the file permissions, suitable for debugging.
public var debugDescription: String { self.description }
}

// MARK: - Options

public extension ATTAttributePermissions {

// Access
static var read: ATTAttributePermissions { 0x01 }
static var write: ATTAttributePermissions { 0x02 }

// Encryption
static var encrypt: ATTAttributePermissions { [.readEncrypt, .writeEncrypt] }
static var readEncrypt: ATTAttributePermissions { 0x04 }
static var writeEncrypt: ATTAttributePermissions { 0x08 }

// The following have no effect on Darwin

// Authentication
static var authentication: ATTAttributePermissions { [.readAuthentication, .writeAuthentication] }
static var readAuthentication: ATTAttributePermissions { 0x10 }
static var writeAuthentication: ATTAttributePermissions { 0x20 }

// Authorization
static var authorized: ATTAttributePermissions { 0x40 }
static var noAuthorization: ATTAttributePermissions { 0x80 }
}
225 changes: 225 additions & 0 deletions esp32-ble-peripheral-sdk/main/ATTError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors.
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//

/**
The possible errors returned by a GATT server (a remote peripheral) during Bluetooth low energy ATT transactions.

These error constants are based on the Bluetooth ATT error codes, defined in the Bluetooth 4.0 specification.
For more information about these errors, see the Bluetooth 4.0 specification, Volume 3, Part F, Section 3.4.1.1.
*/
@frozen
public enum ATTError: UInt8, Error {

/// Invalid Handle
///
/// The attribute handle given was not valid on this server.
case invalidHandle = 0x01

/// Read Not Permitted
///
/// The attribute cannot be read.
case readNotPermitted = 0x02

/// Write Not Permitted
///
/// The attribute cannot be written.
case writeNotPermitted = 0x03

/// Invalid PDU
///
/// The attribute PDU was invalid.
case invalidPDU = 0x04

/// Insufficient Authentication
///
/// The attribute requires authentication before it can be read or written.
case insufficientAuthentication = 0x05

/// Request Not Supported
///
/// Attribute server does not support the request received from the client.
case requestNotSupported = 0x06

/// Invalid Offset
///
/// Offset specified was past the end of the attribute.
case invalidOffset = 0x07

/// Insufficient Authorization
///
/// The attribute requires authorization before it can be read or written.
case insufficientAuthorization = 0x08

/// Prepare Queue Full
///
/// Too many prepare writes have been queued.
case prepareQueueFull = 0x09

/// Attribute Not Found
///
/// No attribute found within the given attribute handle range.
case attributeNotFound = 0x0A

/// Attribute Not Long
///
/// The attribute cannot be read or written using the *Read Blob Request*.
case attributeNotLong = 0x0B

/// Insufficient Encryption Key Size
///
/// The *Encryption Key Size* used for encrypting this link is insufficient.
case insufficientEncryptionKeySize = 0x0C

/// Invalid Attribute Value Length
///
/// The attribute value length is invalid for the operation.
case invalidAttributeValueLength = 0x0D

/// Unlikely Error
///
/// The attribute request that was requested has encountered an error that was unlikely,
/// and therefore could not be completed as requested.
case unlikelyError = 0x0E

/// Insufficient Encryption
///
/// The attribute requires encryption before it can be read or written.
case insufficientEncryption = 0x0F

/// Unsupported Group Type
///
/// The attribute type is not a supported grouping attribute as defined by a higher layer specification.
case unsupportedGroupType = 0x10

/// Insufficient Resources
///
/// Insufficient Resources to complete the request.
case insufficientResources = 0x11
}

// MARK: - CustomStringConvertible

extension ATTError: CustomStringConvertible {

public var description: String {
return name
}
}

// MARK: - Description Values

public extension ATTError {

var name: String {

switch self {
case .invalidHandle:
return "Invalid Handle"
case .readNotPermitted:
return "Read Not Permitted"
case .writeNotPermitted:
return "Write Not Permitted"
case .invalidPDU:
return "Invalid PDU"
case .insufficientAuthentication:
return "Insufficient Authentication"
case .requestNotSupported:
return "Request Not Supported"
case .invalidOffset:
return "Invalid Offset"
case .insufficientAuthorization:
return "Insufficient Authorization"
case .prepareQueueFull:
return "Prepare Queue Full"
case .attributeNotFound:
return "Attribute Not Found"
case .attributeNotLong:
return "Attribute Not Long"
case .insufficientEncryptionKeySize:
return "Insufficient Encryption Key Size"
case .invalidAttributeValueLength:
return "Invalid Attribute Value Length"
case .unlikelyError:
return "Unlikely Error"
case .insufficientEncryption:
return "Insufficient Encryption"
case .unsupportedGroupType:
return "Unsupported Group Type"
case .insufficientResources:
return "Insufficient Resources"
}
}

#if !hasFeature(Embedded)
var errorDescription: String {

switch self {
case .invalidHandle:
return "The attribute handle given was not valid on this server."
case .readNotPermitted:
return "The attribute cannot be read."
case .writeNotPermitted:
return "The attribute cannot be written."
case .invalidPDU:
return "The attribute PDU was invalid."
case .insufficientAuthentication:
return "The attribute requires authentication before it can be read or written."
case .requestNotSupported:
return "Attribute server does not support the request received from the client."
case .invalidOffset:
return "Offset specified was past the end of the attribute."
case .insufficientAuthorization:
return "The attribute requires authorization before it can be read or written."
case .prepareQueueFull:
return "Too many prepare writes have been queued."
case .attributeNotFound:
return "No attribute found within the given attri- bute handle range."
case .attributeNotLong:
return "The attribute cannot be read using the Read Blob Request."
case .insufficientEncryptionKeySize:
return "The Encryption Key Size used for encrypting this link is insufficient."
case .invalidAttributeValueLength:
return "The attribute value length is invalid for the operation."
case .unlikelyError:
return "The attribute request that was requested has encountered an error that was unlikely, and therefore could not be completed as requested."
case .insufficientEncryption:
return "The attribute requires encryption before it can be read or written."
case .unsupportedGroupType:
return "The attribute type is not a supported grouping attribute as defined by a higher layer specification."
case .insufficientResources:
return "Insufficient Resources to complete the request."
}
}
#endif
}

// MARK: - CustomNSError

#if canImport(Foundation)
extension ATTError: CustomNSError {

public static var errorDomain: String {
return "org.pureswift.Bluetooth.ATTError"
}

public var errorCode: Int {
return Int(rawValue)
}

public var errorUserInfo: [String: Any] {

return [
NSLocalizedDescriptionKey: name,
NSLocalizedFailureReasonErrorKey: errorDescription
]
}
}
#endif
Loading