Files
controller-wisetopdataserver/python/biopro/impl/cc2650/gap.py
T
2021-12-20 14:52:55 +08:00

675 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from biopro.util.console import pc, pp
from .error_code import *
T = TypeVar('T')
@unique
class GapParameters(IntEnum):
TGAP_GEN_DISC_ADV_MIN = 0x00
"""Minimum time to remain advertising, when in Discoverable mode (mSec).
Setting this parameter to 0 turns off the timer (default)."""
TGAP_LIM_ADV_TIMEOUT = 0x01
"""Maximum time to remain advertising, when in Limited Discoverable mode.
In seconds (default 180 seconds)."""
TGAP_GEN_DISC_SCAN = 0x02
"""Minimum time to perform scanning, when performing General Discovery proc (mSec)."""
TGAP_LIM_DISC_SCAN = 0x03
"""Minimum time to perform scanning, when performing Limited Discovery proc (mSec)."""
TGAP_CONN_EST_ADV_TIMEOUT = 0x04
"""Advertising performing Connection Establishment proc (mSec)."""
TGAP_CONN_PARAM_TIMEOUT = 0x05
"""Link Layer connection parameter update notification timer, connection parameter update proc (mSec)."""
TGAP_LIM_DISC_ADV_INT_MIN = 0x06
"""Minimum advertising interval, when in limited discoverable mode (mSec)."""
TGAP_LIM_DISC_ADV_INT_MAX = 0x07
"""Maximum advertising interval, when in limited discoverable mode (mSec)."""
TGAP_GEN_DISC_ADV_INT_MIN = 0x08
"""Minimum advertising interval, when in General discoverable mode (mSec)."""
TGAP_GEN_DISC_ADV_INT_MAX = 0x09
"""Maximum advertising interval, when in General discoverable mode (mSec)."""
TGAP_CONN_ADV_INT_MIN = 0x0A
"""Minimum advertising interval, when in Connect-able mode (mSec)."""
TGAP_CONN_ADV_INT_MAX = 0x0B
"""Maximum advertising interval, when in Connect-able mode (mSec)."""
TGAP_CONN_SCAN_INT = 0x0C
"""Scan interval used during Link Layer Initiating state, when in Connect-able mode (mSec)."""
TGAP_CONN_SCAN_WIND = 0x0D
"""Scan window used during Link Layer Initiating state, when in Connect-able mode (mSec)."""
TGAP_CONN_HIGH_SCAN_INT = 0x0E
"""Scan interval used during Link Layer Initiating state, when in Connect-able mode,
high duty scan cycle scan parameters (mSec)."""
TGAP_CONN_HIGH_SCAN_WIND = 0x0F
"""Scan window used during Link Layer Initiating state, when in Connectable mode,
high duty scan cycle scan parameters (mSec)."""
TGAP_GEN_DISC_SCAN_INT = 0x10
"""Scan interval used during Link Layer Scanning state, when in General Discovery proc (mSec)."""
TGAP_GEN_DISC_SCAN_WIND = 0x11
"""Scan window used during Link Layer Scanning state, when in General Discovery proc (mSec)."""
TGAP_LIM_DISC_SCAN_INT = 0x12
"""Scan interval used during Link Layer Scanning state, when in Limited Discovery proc (mSec)."""
TGAP_LIM_DISC_SCAN_WIND = 0x13
"""Scan window used during Link Layer Scanning state, when in Limited Discovery proc (mSec)."""
TGAP_CONN_EST_ADV = 0x14
"""Advertising interval, when using Connection Establishment proc (mSec)."""
TGAP_CONN_EST_INT_MIN = 0x15
"""Minimum Link Layer connection interval, when using Connection Establishment proc (mSec)."""
TGAP_CONN_EST_INT_MAX = 0x16
"""Maximum Link Layer connection interval, when using Connection Establishment proc (mSec)."""
TGAP_CONN_EST_SCAN_INT = 0x017
"""Scan interval used during Link Layer Initiating state, when using Connection Establishment proc (mSec)."""
TGAP_CONN_EST_SCAN_WIND = 0x18
"""Scan window used during Link Layer Initiating state, when using Connection Establishment proc (mSec)."""
TGAP_CONN_EST_SUPERV_TIMEOUT = 0x19
"""Link Layer connection supervision timeout, when using Connection Establishment proc (mSec)."""
TGAP_CONN_EST_LATENCY = 0x1A
"""Link Layer connection slave latency, when using Connection Establishment proc (mSec)"""
TGAP_CONN_EST_MIN_CE_LEN = 0x1B
"""Local informational parameter about min len of connection needed,
when using Connection Establishment proc (mSec)."""
TGAP_CONN_EST_MAX_CE_LEN = 0x1C
"""Local informational parameter about max len of connection needed,
when using Connection Establishment proc (mSec)."""
TGAP_PRIVATE_ADDR_INT = 0x1D
"""Minimum Time Interval between private (resolvable) address changes. In minutes (default 15 minutes)."""
TGAP_CONN_PAUSE_CENTRAL = 0x1E
"""Central idle timer. In seconds (default 1 second)."""
TGAP_CONN_PAUSE_PERIPHERAL = 0x1F
"""Minimum time upon connection establishment before the peripheral starts a connection update procedure.
In seconds (default 5 seconds)."""
TGAP_SM_TIMEOUT = 0x20
"""SM Message Timeout (milliseconds). (default 30 seconds)."""
TGAP_SM_MIN_KEY_LEN = 0x21
"""SM Minimum Key Length supported (default 7)."""
TGAP_SM_MAX_KEY_LEN = 0x22
"""SM Maximum Key Length supported (default 16)."""
TGAP_FILTER_ADV_REPORTS = 0x23
"""Filter duplicate advertising reports (Default TRUE)."""
TGAP_SCAN_RSP_RSSI_MIN = 0x24
"""Minimum RSSI responses to be reported to the app (Default -127)."""
TGAP_REJECT_CONN_PARAMS = 0x25
"""Whether or not to reject Connection Parameter Update Request received on Central device. Default FALSE."""
TGAP_GAP_TESTCODE = 0x26
"""GAP Test Modes:
===== ==============
value mean
===== ==============
0x00 Test Mode Off
0x01 No Response
===== ==============
"""
TGAP_SM_TESTCODE = 0x27
"""SM Test Modes:
===== =========================
value mean
===== =========================
0x00 Test Mode Off
0x01 No Response
0x02 Send Bad Confirm
0x03 Bad Confirm Verify
0x04 Send SMP Confirm Message
===== =========================
"""
TGAP_GATT_TESTCODE = 0x64
"""GATT Test Modes:
===== ================================================
value mean
===== ================================================
0x00 Test Mode Off
0x01 Ignore incoming request
0x02 Forward Prepare Write Request right away
0x03 Use Max ATT MTU size with Exchange MTU Response
0x04 Corrupt incoming Prepare Write Request data
===== ================================================
"""
TGAP_ATT_TESTCODE = 0x65
"""ATT Test Modes:
===== ======================================
value mean
===== ======================================
0x00 Test Mode Off
0x01 Do Not authenticate incoming signature
===== ======================================
"""
TGAP_GGS_TESTCODE = 0x66
"""GGS Test Modes:
===== ===================================================================
value mean
===== ===================================================================
0x00 Test Mode Off
0x01 Make Device Name attribute writable
0x02 Make Appearance attribute writable
0x03 Make Peripheral Privacy Flag attribute writable with authentication
===== ===================================================================
"""
__slots__ = ()
# recognized by run-setup-modify @overload
@staticmethod
@overload
def parameter_str(parameter: uint8, default: None = None) -> Optional[str]:
pass
# recognized by run-setup-modify @overload
@staticmethod
@overload
def parameter_str(parameter: uint8, default: T) -> Union[str, T]:
pass
@staticmethod
def parameter_str(parameter: uint8, default=None):
try:
return GapParameters(parameter).name
except ValueError:
return default
@unique
class GapAdvertisingDataType(IntEnum):
FLAGS = 0x01
"""Discovery Mode"""
BIT16_MORE = 0x02
"""Service: More 16-bit UUIDs available"""
BIT16_COMPLETE = 0x03
"""Service: Complete list of 16-bit UUIDs"""
BIT32_MORE = 0x04
"""Service: More 32-bit UUIDs available"""
BIT32_COMPLETE = 0x05
"""Service: Complete list of 32-bit UUIDs"""
BIT128_MORE = 0x06
"""Service: More 128-bit UUIDs available"""
BIT128_COMPLETE = 0x07
"""Service: Complete list of 128-bit UUIDs"""
LOCAL_NAME_SHORT = 0x08
"""Shortened local name"""
LOCAL_NAME_COMPLETE = 0x09
"""Complete local name"""
POWER_LEVEL = 0x0A
"""TX Power Level"""
# 0xXX: -127 to +127 dBm
OOB_CLASS_OF_DEVICE = 0x0D
"""Simple Pairing OOB Tag"""
# Class of device (3 octets)
OOB_SIMPLE_PAIRING_HASHC = 0x0E
"""Simple Pairing OOB Tag"""
# Simple Pairing Hash C (16 octets)
OOB_SIMPLE_PAIRING_RANDR = 0x0F
"""Simple Pairing OOB Tag"""
# Simple Pairing Randomizer R (16 octets)
SM_TK = 0x10
"""Security Manager TK Value"""
SM_OOB_FLAG = 0x11
"""Security Manager OOB Flags"""
SLAVE_CONN_INTERVAL_RANGE = 0x12
"""Min and Max values of the connection interval"""
# (2 octets Min, 2 octets Max) (0xFFFF indicates no conn interval min or max)
SIGNED_DATA = 0x13
"""Signed Data field"""
SERVICES_LIST_16BIT = 0x14
"""Service Solicitation"""
# list of 16-bit Service UUIDs
SERVICES_LIST_128BIT = 0x15
"""Service Solicitation"""
# list of 128-bit Service UUIDs
SERVICE_DATA = 0x16
"""Service Data"""
APPEARANCE = 0x19
"""Appearance"""
MANUFACTURER_SPECIFIC = 0xFF
"""Manufacturer Specific Data"""
# first 2 octets contain the Company Identifier Code followed by the additional manufacturer specific data
__slots__ = ()
# recognized by run-setup-modify @overload
@staticmethod
@overload
def type_str(ad_type: uint8, default: None = None) -> Optional[str]:
pass
# recognized by run-setup-modify @overload
@staticmethod
@overload
def type_str(ad_type: uint8, default: T) -> Union[str, T]:
pass
@staticmethod
def type_str(ad_type: uint8, default=None):
try:
return GapAdvertisingDataType(ad_type).name
except ValueError:
return default
@unique
class GapBondParameters(IntEnum):
PAIRING_MODE = 0x400
"""Pairing Mode.
Read/Write.
Size is uint8.
==== ================================================================================
0x00 Pairing Not allowed
0x01 Wait for Request (default)
0x02 Dont wait, initiate a Slave Requested Security command (not available yet).
==== ================================================================================
"""
INITIATE_WAIT = 0x401
"""Pairing Mode Initiate wait timeout.
This is the time it will wait for a Pairing Request before sending the Slave Initiate Request.
Read/Write.
Size is uint16.
Default is 1000(in milliseconds)."""
MITM_PROTECTION = 0x402
"""Man-In-The-Middle (MITM) basically turns on Passkey protection in the pairing algorithm.
Read/Write.
Size is uint8.
Default is 0(disabled)."""
IO_CAPABILITIES = 0x403
"""I/O capabilities.
Read/Write.
Size is uint8.
==== ===============================
0x00 Display Only Device (default)
0x01 Display Yes an No capable
0x02 Keyboard only
0x03 No Input, No Output
0x04 Keyboard and Display
==== ===============================
"""
OOB_ENABLED = 0x404
"""OOB data available for pairing algorithm.
Read/Write.
Size is uint8.
Default is 0(disabled)."""
OOB_DATA = 0x405
"""OOB Data.
Read/Write.
size uint8[16].
Default is all 0's."""
BONDING_ENABLED = 0x406
"""Request Bonding during the pairing process if enabled.
Read/Write.
Size is uint8.
Default is 0(disabled)."""
KEY_DIST_LIST = 0x407
"""The key distribution list for bonding.
size is uint8.
Default is sEncKey, sIdKey, mIdKey, mSign enabled.
===== =========================================
Bit 0 Slave LTK and key information (default)
Bit 1 Slave IRK and ID information (default)
Bit 2 Slave CSRK
Bit 3 Master LTK and key information
Bit 4 Master IRK and ID information (default).
Bit 5 Master CSRK (default)
===== =========================================
"""
DEFAULT_PASSCODE = 0x408
"""The default passcode for MITM protection.
size is uint32.
Range is 0 - 999,999.
Default is 0."""
ERASE_ALL_BONDS = 0x409
"""Erase all of the bonded devices.
Write Only.
No Size."""
KEY_SIZE = 0x40C
"""Key Size used in pairing.
Read/Write.
size is uint8.
Default is 16."""
AUTO_SYNC_WL = 0x40D
"""Clears the White List adds to it each unique address stored by bonds in NV.
Read/Write.
Size is uint8.
Default is FALSE."""
BOND_COUNT = 0x40E
"""Gets the total number of bonds stored in NV.
Read Only.
Size is uint8.
Default is 0 (no bonds)."""
BOND_FAIL_ACTION = 0x40F
"""Possible actions Central may take upon an unsuccessful bonding.
Write Only.
Size is uint8.
Default is 0x02 (Terminate link upon unsuccessful bonding)."""
ERASE_SINGLE_BOND = 0x410
"""Erase a single bonded device.
Write only.
Must provide address type followed by device address."""
SECURE_CONNECTION = 0x411
"""Defines Secure Connections usage.
Read/Write.
size is uint8.
Secure Connections only. """
ECC_KEY_REGEN_POLICY = 0x412
"""Count of how many times an ECC key-pair may be reused before regeneration.
Write only.
Range is 0-254.
Default is 0.
Secure Connections only. """
ECC_KEYS = 0x413
"""Use application requested public-private key-pair for Secure Connections.
Read/Write.
size is gapBondEccKeys_t.
Secure Connections only."""
REMOTE_OOB_SC_ENABLED = 0x414
"""Secure Connections OOB data from remote device available.
Read/Write.
Size is uint8.
Default is 0 (disabled).
Secure Connections only."""
REMOTE_OOB_SC_DATA = 0x415
"""Secure Connections OOB data.
Read/Write.
Size is gapBondOobSC_t.
Default is all 0's.
Secure Connections only."""
LOCAL_OOB_SC_ENABLED = 0x416
"""Secure Connection local OOB data is available.
Read/Write.
Size is uint8.
Default is 0 (disabled).
Secure Connections only."""
LOCAL_OOB_SC_DATA = 0x417
"""Local OOB Data.
Read/Write.
size uint8[16].
Default is all 0's.
Secure Connections only."""
LRU_BOND_REPLACEMENT = 0x418
"""Remote Least Recently Used Bond when newly bonded device is added and the all entries are full.
Read/Write.
size uint8.
Default is FALSE."""
__slots__ = ()
# recognized by run-setup-modify @overload
@staticmethod
@overload
def parameter_str(parameter: uint8, default: None = None) -> Optional[str]:
pass
# recognized by run-setup-modify @overload
@staticmethod
@overload
def parameter_str(parameter: uint8, default: T) -> Union[str, T]:
pass
@staticmethod
def parameter_str(parameter: uint8, default=None):
try:
return GapBondParameters(parameter).name
except ValueError:
return default
# noinspection PyPep8Naming
class GAP_Authentication:
"""
============ ======================
io_caps
============ ======================
0x00 Display Only
0x01 Display Yes or No
0x02 Keyboard Only
0x03 No Input and No Output
0x04 Keyboard and Display
0x05 .. 0xFF reserved
============ ======================
============= ===== =========================================
oob_available value mean
============= ===== =========================================
False 0x00 Out-Of-Bounds (OOB) data is NOT available
True 0x01 Out-Of-Bounds (OOB) data is available
============= ===== =========================================
================ ======================================
max_enc_key_size mean
================ ======================================
7 .. 16 Maximum encryption key size to support
================ ======================================
============ ==========================
key_dist mean
============ ==========================
0x00 Slave Encryption Key
0x01 Slave Identification Key
0x02 Slave Signing Key
0x03 Master Encryption Key
0x04 Master Identification Key
0x05 Master Signing Key
0x06 .. 0x07 Reserved
============ ==========================
"""
IO_CAPS = {
0x00: 'Display Only',
0x01: 'Display Yes/No',
0x02: 'Keyboard Only',
0x03: 'No IO',
0x04: 'Keyboard and Display',
}
KEY_DIST = {
0x00: 'Slave Encryption Key',
0x01: 'Slave Identification Key',
0x02: 'Slave Signing Key',
0x03: 'Master Encryption Key',
0x04: 'Master Identification Key',
0x05: 'Master Signing Key',
}
__slots__ = ('io_caps', 'oob_available', 'oob', 'auth_request', 'max_enc_key_size', 'key_dist')
def __init__(self):
# XXX data struct not correct
self.io_caps: uint8 = 0
self.oob_available: bool = False
self.oob: OOB = None
self.auth_request: uint8 = 0
self.max_enc_key_size: uint8 = 7
self.key_dist: uint8 = 0
def dump(self, c: int):
print(pc('io_caps', c), self.io_caps, pp(self.IO_CAPS.get(self.io_caps, 'reserved')))
print(pc('oob_available', c), self.oob_available, pp(True if self.oob_available else False))
print(pc('oob', c), address_str(self.oob))
print(pc('auth_request', c), self.auth_request, pp(AUTHENTICATION_REQUEST.get(self.auth_request, None)))
print(pc('max_enc_key_size', c), self.max_enc_key_size)
print(pc('key_dist', c), self.key_dist, pp(self.KEY_DIST.get(self.key_dist, 'reserved')))
# noinspection PyPep8Naming
class GAP_Pair:
"""
============ ======================
io_caps
============ ======================
0x00 Display Only
0x01 Display Yes or No
0x02 Keyboard Only
0x03 No Input and No Output
0x04 Keyboard and Display
0x05 .. 0xFF reserved
============ ======================
============= ===== =========================================
oob_data_flag value mean
============= ===== =========================================
False 0x00 Out-Of-Bounds (OOB) data is NOT available
True 0x01 Out-Of-Bounds (OOB) data is available
============= ===== =========================================
================ ======================================
max_enc_key_size mean
================ ======================================
7 .. 16 Maximum encryption key size to support
================ ======================================
============ ==========================
key_dist mean
============ ==========================
0x00 Slave Encryption Key
0x01 Slave Identification Key
0x02 Slave Signing Key
0x03 Master Encryption Key
0x04 Master Identification Key
0x05 Master Signing Key
0x06 .. 0x07 Reserved
============ ==========================
"""
__slots__ = ('io_caps', 'oob_data_flag', 'auth_request', 'max_enc_key_size', 'key_dist')
def __init__(self):
self.io_caps: uint8 = 0
self.oob_data_flag: bool = False
self.auth_request: uint8 = 0
self.max_enc_key_size: uint8 = 7
self.key_dist: uint8 = 0
def dump(self, c: int):
print(pc('io_caps', c), self.io_caps,
pp(GAP_Authentication.IO_CAPS.get(self.io_caps, 'reserved')))
print(pc('oob_available', c), self.oob_data_flag, pp(True if self.oob_data_flag else False))
print(pc('auth_request', c), self.auth_request, pp(AUTHENTICATION_REQUEST.get(self.auth_request, None)))
print(pc('max_enc_key_size', c), self.max_enc_key_size)
print(pc('key_dist', c), self.key_dist,
pp(GAP_Authentication.KEY_DIST.get(self.key_dist, 'reserved')))
class GattValuePermission(IntEnum):
BROADCAST = 0x01
"""Permits broadcasts of the Characteristic Value"""
READ = 0x02
"""Permits reads of the Characteristic Value"""
WRITE_NO_RSP = 0x04
"""Permits writes of the Characteristic Value without response"""
WRITE = 0x08
"""Permits writes of the Characteristic Value with response"""
NOTIFY = 0x10
"""Permits notifications of a Characteristic Value without acknowledgement"""
INDICATE = 0x20
"""Permits indications of a Characteristic Value with acknowledgement"""
AUTHENTICATION = 0x40
"""Permits signed writes to the Characteristic Value"""
EXTENDED = 0x80
"""Additional characteristic properties are defined in the Characteristic Extended Properties Descriptor"""
__slots__ = ()
@staticmethod
def permission_str(permissions: uint8) -> str:
return ''.join([
'x' if (permissions & 0x80) else '-',
'a' if (permissions & 0x40) else '-',
'i' if (permissions & 0x20) else '-',
'n' if (permissions & 0x10) else '-',
'w' if (permissions & 0x08) else '-',
'W' if (permissions & 0x04) else '-',
'r' if (permissions & 0x02) else '-',
'b' if (permissions & 0x01) else '-',
])