text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```restructuredtext .. _trickle_interface: Trickle Timer Library ##################### .. contents:: :local: :depth: 2 Overview ******** The Trickle timer library implements `IETF RFC6206 (Trickle Algorithm) <path_to_url`_. The Trickle algorithm allows nodes in a lossy shared medium (e.g., low-power and lossy networks) to exchange information in a highly robust, energy efficient, simple, and scalable manner. API Reference ************* .. doxygengroup:: trickle ```
/content/code_sandbox/doc/connectivity/networking/api/trickle.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
114
```restructuredtext .. _net_l2_interface: L2 Layer Management ################### .. contents:: :local: :depth: 2 Overview ******** The L2 stack is designed to hide the whole networking link-layer part and the related device drivers from the upper network stack. This is made through a :c:struct:`net_if` declared in :zephyr_file:`include/zephyr/net/net_if.h`. The upper layers are unaware of implementation details beyond the net_if object and the generic API provided by the L2 layer in :zephyr_file:`include/zephyr/net/net_l2.h` as :c:struct:`net_l2`. Only the L2 layer can talk to the device driver, linked to the net_if object. The L2 layer dictates the API provided by the device driver, specific for that device, and optimized for working together. Currently, there are L2 layers for :ref:`Ethernet <ethernet_interface>`, :ref:`IEEE 802.15.4 Soft-MAC <ieee802154_interface>`, :ref:`CANBUS <can_api>`, :ref:`OpenThread <thread_protocol_interface>`, Wi-Fi, and a dummy layer example that can be used as a template for writing a new one. L2 layer API ************ In order to create an L2 layer, or a driver for a specific L2 layer, one needs to understand how the L3 layer interacts with it and how the L2 layer is supposed to behave. See also :ref:`network stack architecture <network_stack_architecture>` for more details. The generic L2 API has these functions: - ``recv()``: All device drivers, once they receive a packet which they put into a :c:struct:`net_pkt`, will push this buffer to the network stack via :c:func:`net_recv_data`. At this point, the network stack does not know what to do with it. Instead, it passes the buffer along to the L2 stack's ``recv()`` function for handling. The L2 stack does what it needs to do with the packet, for example, parsing the link layer header, or handling link-layer only packets. The ``recv()`` function will return ``NET_DROP`` in case of an erroneous packet, ``NET_OK`` if the packet was fully consumed by the L2, or ``NET_CONTINUE`` if the network stack should then handle it. - ``send()``: Similar to receive function, the network stack will call this function to actually send a network packet. All relevant link-layer content will be generated and added by this function. The ``send()`` function returns the number of bytes sent, or a negative error code if there was a failure sending the network packet. - ``enable()``: This function is used to enable/disable traffic over a network interface. The function returns ``<0`` if error and ``>=0`` if no error. - ``get_flags()``: This function will return the capabilities of an L2 driver, for example whether the L2 supports multicast or promiscuous mode. Network Device drivers ********************** Network device drivers fully follows Zephyr device driver model as a basis. Please refer to :ref:`device_model_api`. There are, however, two differences: - The driver_api pointer must point to a valid :c:struct:`net_if_api` pointer. - The network device driver must use :c:macro:`NET_DEVICE_INIT_INSTANCE()` or :c:macro:`ETH_NET_DEVICE_INIT()` for Ethernet devices. These macros will call the :c:macro:`DEVICE_DEFINE()` macro, and also instantiate a unique :c:struct:`net_if` related to the created device driver instance. Implementing a network device driver depends on the L2 stack it belongs to: :ref:`Ethernet <ethernet_interface>`, :ref:`IEEE 802.15.4 <ieee802154_interface>`, etc. In the next section, we will describe how a device driver should behave when receiving or sending a network packet. The rest is hardware dependent and is not detailed here. Ethernet device driver ====================== On reception, it is up to the device driver to fill-in the network packet with as many data buffers as required. The network packet itself is a :c:struct:`net_pkt` and should be allocated through :c:func:`net_pkt_rx_alloc_with_buffer`. Then all data buffers will be automatically allocated and filled by :c:func:`net_pkt_write`. After all the network data has been received, the device driver needs to call :c:func:`net_recv_data`. If that call fails, it will be up to the device driver to unreference the buffer via :c:func:`net_pkt_unref`. On sending, the device driver send function will be called, and it is up to the device driver to send the network packet all at once, with all the buffers. Each Ethernet device driver will need, in the end, to call ``ETH_NET_DEVICE_INIT()`` like this: .. code-block:: c ETH_NET_DEVICE_INIT(..., CONFIG_ETH_INIT_PRIORITY, &the_valid_net_if_api_instance, 1500); IEEE 802.15.4 device driver =========================== Device drivers for IEEE 802.15.4 L2 work basically the same as for Ethernet. What has been described above, especially for ``recv()``, applies here as well. There are two specific differences however: - It requires a dedicated device driver API: :c:struct:`ieee802154_radio_api`, which overloads :c:struct:`net_if_api`. This is because 802.15.4 L2 needs more from the device driver than just ``send()`` and ``recv()`` functions. This dedicated API is declared in :zephyr_file:`include/zephyr/net/ieee802154_radio.h`. Each and every IEEE 802.15.4 device driver must provide a valid pointer on such relevantly filled-in API structure. - Sending a packet is slightly different than in Ethernet. Most IEEE 802.15.4 PHYs support relatively small frames only, 127 bytes all inclusive: frame header, payload and frame checksum. Buffers to be sent over the radio will often not fit this frame size limitation, e.g. a buffer containing an IPv6 packet will often have to be split into several fragments and IP6 packet headers and fragments need to be compressed using a protocol like 6LoWPAN before being passed on to the radio driver. Additionally the IEEE 802.15.4 standard defines medium access (e.g. CSMA/CA), frame retransmission, encryption and other pre- processing procedures (e.g. addition of information elements) that individual radio drivers should not have to care about. This is why the :c:struct:`ieee802154_radio_api` requires a tx function pointer which differs from the :c:struct:`net_if_api` send function pointer. Zephyr's native IEEE 802.15.4 L2 implementation provides a generic :c:func:`ieee802154_send` instead, meant to be given as :c:type:`net_if` send function. The implementation of :c:func:`ieee802154_send` takes care of IEEE 802.15.4 standard packet preparation procedures, splitting the packet into possibly compressed, encrypted and otherwise pre-processed fragment buffers, sending one buffer at a time through :c:struct:`ieee802154_radio_api` tx function and unreferencing the network packet only when the transmission as a whole was either successful or failed. Interaction between IEEE 802.15.4 radio device drivers and L2 is bidirectional: - L2 -> L1: Methods as :c:func:`ieee802154_send` and several IEEE 802.15.4 net management calls will call into the driver, e.g. to send a packet over the radio link or re-configure the driver at runtime. These incoming calls will all be handled by the methods in the :c:struct:`ieee802154_radio_api`. - L1 -> L2: There are several situations in which the driver needs to initiate calls into the L2/MAC layer. Zephyr's IEEE 802.15.4 L1 -> L2 adaptation API employs an "inversion-of-control" pattern in such cases avoids duplication of complex logic across independent driver implementations and ensures implementation agnostic loose coupling and clean separation of concerns between MAC (L2) and PHY (L1) whenever reverse information transfer or close co-operation between hardware and L2 is required. During driver initialization, for example, the driver calls :c:func:`ieee802154_init` to pass the interface's MAC address as well as other hardware-related configuration to L2. Similarly, drivers may indicate performance or timing critical radio events to L2 that require close integration with the hardware (e.g. :c:func:`ieee802154_handle_ack`). Calls from L1 into L2 are not implemented as methods in :c:struct:`ieee802154_radio_api` but are standalone functions declared and documented as such in :zephyr_file:`include/zephyr/net/ieee802154_radio.h`. The API documentation will clearly state which functions must be implemented by all L2 stacks as part of the L1 -> L2 "inversion-of-control" adaptation API. Note: Standalone functions in :zephyr_file:`include/zephyr/net/ieee802154_radio.h` that are not explicitly documented as callbacks are considered to be helper functions within the PHY (L1) layer implemented independently of any specific L2 stack, see for example :c:func:`ieee802154_is_ar_flag_set`. As all net interfaces, IEEE 802.15.4 device driver implementations will have to call ``NET_DEVICE_INIT_INSTANCE()`` in the end: .. code-block:: c NET_DEVICE_INIT_INSTANCE(..., the_device_init_prio, &the_valid_ieee802154_radio_api_instance, IEEE802154_L2, NET_L2_GET_CTX_TYPE(IEEE802154_L2), 125); API Reference ************* .. doxygengroup:: net_l2 ```
/content/code_sandbox/doc/connectivity/networking/api/net_l2.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,233
```restructuredtext .. _net_buf_interface: Network Buffer ############## .. contents:: :local: :depth: 2 Overview ******** Network buffers are a core concept of how the networking stack (as well as the Bluetooth stack) pass data around. The API for them is defined in :zephyr_file:`include/zephyr/net/buf.h`:. Creating buffers **************** Network buffers are created by first defining a pool of them: .. code-block:: c NET_BUF_POOL_DEFINE(pool_name, buf_count, buf_size, user_data_size, NULL); The pool is a static variable, so if it's needed to be exported to another module a separate pointer is needed. Once the pool has been defined, buffers can be allocated from it with: .. code-block:: c buf = net_buf_alloc(&pool_name, timeout); There is no explicit initialization function for the pool or its buffers, rather this is done implicitly as :c:func:`net_buf_alloc` gets called. If there is a need to reserve space in the buffer for protocol headers to be prepended later, it's possible to reserve this headroom with: .. code-block:: c net_buf_reserve(buf, headroom); In addition to actual protocol data and generic parsing context, network buffers may also contain protocol-specific context, known as user data. Both the maximum data and user data capacity of the buffers is compile-time defined when declaring the buffer pool. The buffers have native support for being passed through k_fifo kernel objects. Use :c:func:`k_fifo_put` and :c:func:`k_fifo_get` to pass buffer from one thread to another. Special functions exist for dealing with buffers in single linked lists, where the :c:func:`net_buf_slist_put` and :c:func:`net_buf_slist_get` functions must be used instead of :c:func:`sys_slist_append` and :c:func:`sys_slist_get`. Common Operations ***************** The network buffer API provides some useful helpers for encoding and decoding data in the buffers. To fully understand these helpers it's good to understand the basic names of operations used with them: Add Add data to the end of the buffer. Modifies the data length value while leaving the actual data pointer intact. Requires that there is enough tailroom in the buffer. Some examples of APIs for adding data: .. code-block:: c void *net_buf_add(struct net_buf *buf, size_t len); void *net_buf_add_mem(struct net_buf *buf, const void *mem, size_t len); uint8_t *net_buf_add_u8(struct net_buf *buf, uint8_t value); void net_buf_add_le16(struct net_buf *buf, uint16_t value); void net_buf_add_le32(struct net_buf *buf, uint32_t value); Remove Remove data from the end of the buffer. Modifies the data length value while leaving the actual data pointer intact. Some examples of APIs for removing data: .. code-block:: c void *net_buf_remove_mem(struct net_buf *buf, size_t len); uint8_t net_buf_remove_u8(struct net_buf *buf); uint16_t net_buf_remove_le16(struct net_buf *buf); uint32_t net_buf_remove_le32(struct net_buf *buf); Push Prepend data to the beginning of the buffer. Modifies both the data length value as well as the data pointer. Requires that there is enough headroom in the buffer. Some examples of APIs for pushing data: .. code-block:: c void *net_buf_push(struct net_buf *buf, size_t len); void *net_buf_push_mem(struct net_buf *buf, const void *mem, size_t len); void net_buf_push_u8(struct net_buf *buf, uint8_t value); void net_buf_push_le16(struct net_buf *buf, uint16_t value); Pull Remove data from the beginning of the buffer. Modifies both the data length value as well as the data pointer. Some examples of APIs for pulling data: .. code-block:: c void *net_buf_pull(struct net_buf *buf, size_t len); void *net_buf_pull_mem(struct net_buf *buf, size_t len); uint8_t net_buf_pull_u8(struct net_buf *buf); uint16_t net_buf_pull_le16(struct net_buf *buf); uint32_t net_buf_pull_le32(struct net_buf *buf); The Add and Push operations are used when encoding data into the buffer, whereas the Remove and Pull operations are used when decoding data from a buffer. Reference Counting ****************** Each network buffer is reference counted. The buffer is initially acquired from a free buffers pool by calling :c:func:`net_buf_alloc()`, resulting in a buffer with reference count 1. The reference count can be incremented with :c:func:`net_buf_ref()` or decremented with :c:func:`net_buf_unref()`. When the count drops to zero the buffer is automatically placed back to the free buffers pool. API Reference ************* .. doxygengroup:: net_buf ```
/content/code_sandbox/doc/connectivity/networking/api/net_buf.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,116
```restructuredtext .. _net_mgmt_interface: Network Management ################## .. contents:: :local: :depth: 2 Overview ******** The Network Management APIs allow applications, as well as network layer code itself, to call defined network routines at any level in the IP stack, or receive notifications on relevant network events. For example, by using these APIs, application code can request a scan be done on a Wi-Fi- or Bluetooth-based network interface, or request notification if a network interface IP address changes. The Network Management API implementation is designed to save memory by eliminating code at build time for management routines that are not used. Distinct and statically defined APIs for network management procedures are not used. Instead, defined procedure handlers are registered by using a :c:macro:`NET_MGMT_REGISTER_REQUEST_HANDLER` macro. Procedure requests are done through a single :c:func:`net_mgmt` API that invokes the registered handler for the corresponding request. The current implementation is experimental and may change and improve in future releases. Requesting a defined procedure ****************************** All network management requests are of the form ``net_mgmt(mgmt_request, ...)``. The ``mgmt_request`` parameter is a bit mask that tells which stack layer is targeted, if a ``net_if`` object is implied, and the specific management procedure being requested. The available procedure requests depend on what has been implemented in the stack. To avoid extra cost, all :c:func:`net_mgmt` calls are direct. Though this may change in a future release, it will not affect the users of this function. .. _net_mgmt_listening: Listening to network events *************************** You can receive notifications on network events by registering a callback function and specifying a set of events used to filter when your callback is invoked. The callback will have to be unique for a pair of layer and code, whereas on the command part it will be a mask of events. At runtime two functions are available, :c:func:`net_mgmt_add_event_callback` for registering the callback function, and :c:func:`net_mgmt_del_event_callback` for unregistering a callback. A helper function, :c:func:`net_mgmt_init_event_callback`, can be used to ease the initialization of the callback structure. Additionally :c:macro:`NET_MGMT_REGISTER_EVENT_HANDLER` can be used to register a callback handler at compile time. When an event occurs that matches a callback's event set, the associated callback function is invoked with the actual event code. This makes it possible for different events to be handled by the same callback function, if desired. .. warning:: Event set filtering allows false positives for events that have the same layer and layer code. A callback handler function **must** check the event code (passed as an argument) against the specific network events it will handle, **regardless** of how many events were in the set passed to :c:func:`net_mgmt_init_event_callback`. Note that in order to receive events from multiple layers, one must have multiple listeners registered, one for each layer being listened. The callback handler function can be shared between different layer events. (False positives can occur for events which have the same layer and layer code.) An example follows. .. code-block:: c /* * Set of events to handle. * See e.g. include/net/net_event.h for some NET_EVENT_xxx values. */ #define EVENT_IFACE_SET (NET_EVENT_IF_xxx | NET_EVENT_IF_yyy) #define EVENT_IPV4_SET (NET_EVENT_IPV4_xxx | NET_EVENT_IPV4_yyy) struct net_mgmt_event_callback iface_callback; struct net_mgmt_event_callback ipv4_callback; void callback_handler(struct net_mgmt_event_callback *cb, uint32_t mgmt_event, struct net_if *iface) { if (mgmt_event == NET_EVENT_IF_xxx) { /* Handle NET_EVENT_IF_xxx */ } else if (mgmt_event == NET_EVENT_IF_yyy) { /* Handle NET_EVENT_IF_yyy */ } else if (mgmt_event == NET_EVENT_IPV4_xxx) { /* Handle NET_EVENT_IPV4_xxx */ } else if (mgmt_event == NET_EVENT_IPV4_yyy) { /* Handle NET_EVENT_IPV4_yyy */ } else { /* Spurious (false positive) invocation. */ } } void register_cb(void) { net_mgmt_init_event_callback(&iface_callback, callback_handler, EVENT_IFACE_SET); net_mgmt_init_event_callback(&ipv4_callback, callback_handler, EVENT_IPV4_SET); net_mgmt_add_event_callback(&iface_callback); net_mgmt_add_event_callback(&ipv4_callback); } Or similarly using :c:macro:`NET_MGMT_REGISTER_EVENT_HANDLER`. .. note:: The ``info`` and ``info_length`` arguments are only usable if :kconfig:option:`CONFIG_NET_MGMT_EVENT_INFO` is enabled. Otherwise these are ``NULL`` and zero. .. code-block:: c /* * Set of events to handle. */ #define EVENT_IFACE_SET (NET_EVENT_IF_xxx | NET_EVENT_IF_yyy) #define EVENT_IPV4_SET (NET_EVENT_IPV4_xxx | NET_EVENT_IPV4_yyy) static void event_handler(uint32_t mgmt_event, struct net_if *iface, void *info, size_t info_length, void *user_data) { if (mgmt_event == NET_EVENT_IF_xxx) { /* Handle NET_EVENT_IF_xxx */ } else if (mgmt_event == NET_EVENT_IF_yyy) { /* Handle NET_EVENT_IF_yyy */ } else if (mgmt_event == NET_EVENT_IPV4_xxx) { /* Handle NET_EVENT_IPV4_xxx */ } else if (mgmt_event == NET_EVENT_IPV4_yyy) { /* Handle NET_EVENT_IPV4_yyy */ } else { /* Spurious (false positive) invocation. */ } } NET_MGMT_REGISTER_EVENT_HANDLER(iface_event_handler, EVENT_IFACE_SET, event_handler, NULL); NET_MGMT_REGISTER_EVENT_HANDLER(ipv4_event_handler, EVENT_IPV4_SET, event_handler, NULL); See :zephyr_file:`include/zephyr/net/net_event.h` for available generic core events that can be listened to. Defining a network management procedure *************************************** You can provide additional management procedures specific to your stack implementation by defining a handler and registering it with an associated mgmt_request code. Management request code are defined in relevant places depending on the targeted layer or eventually, if l2 is the layer, on the technology as well. For instance, all IP layer management request code will be found in the :zephyr_file:`include/zephyr/net/net_event.h` header file. But in case of an L2 technology, let's say Ethernet, these would be found in :zephyr_file:`include/zephyr/net/ethernet.h` You define your handler modeled with this signature: .. code-block:: c static int your_handler(uint32_t mgmt_event, struct net_if *iface, void *data, size_t len); and then register it with an associated mgmt_request code: .. code-block:: c NET_MGMT_REGISTER_REQUEST_HANDLER(<mgmt_request code>, your_handler); This new management procedure could then be called by using: .. code-block:: c net_mgmt(<mgmt_request code>, ...); Signaling a network event ************************* You can signal a specific network event using the :c:func:`net_mgmt_event_notify` function and provide the network event code. See :zephyr_file:`include/zephyr/net/net_mgmt.h` for details. As for the management request code, event code can be also found on specific L2 technology mgmt headers, for example :zephyr_file:`include/zephyr/net/ieee802154_mgmt.h` would be the right place if 802.15.4 L2 is the technology one wants to listen to events. API Reference ************* .. doxygengroup:: net_mgmt ```
/content/code_sandbox/doc/connectivity/networking/api/net_mgmt.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,763
```restructuredtext .. _net_tech: Networking Technologies ####################### .. toctree:: :maxdepth: 1 ethernet.rst ieee802154.rst thread.rst ppp.rst wifi.rst ```
/content/code_sandbox/doc/connectivity/networking/api/net_tech.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
54
```restructuredtext .. _net_if_interface: Network Interface ################# .. contents:: :local: :depth: 2 Overview ******** The network interface is a nexus that ties the network device drivers and the upper part of the network stack together. All the sent and received data is transferred via a network interface. The network interfaces cannot be created at runtime. A special linker section will contain information about them and that section is populated at linking time. Network interfaces are created by ``NET_DEVICE_INIT()`` macro. For Ethernet network, a macro called ``ETH_NET_DEVICE_INIT()`` should be used instead as it will create VLAN interfaces automatically if :kconfig:option:`CONFIG_NET_VLAN` is enabled. These macros are typically used in network device driver source code. The network interface can be turned ON by calling ``net_if_up()`` and OFF by calling ``net_if_down()``. When the device is powered ON, the network interface is also turned ON by default. The network interfaces can be referenced either by a ``struct net_if *`` pointer or by a network interface index. The network interface can be resolved from its index by calling ``net_if_get_by_index()`` and from interface pointer by calling ``net_if_get_by_iface()``. .. _net_if_interface_ip_management: The IP address for network devices must be set for them to be connectable. In a typical dynamic network environment, IP addresses are set automatically by DHCPv4, for example. If needed though, the application can set a device's IP address manually. See the API documentation below for functions such as ``net_if_ipv4_addr_add()`` that do that. The ``net_if_get_default()`` returns a *default* network interface. What this default interface means can be configured via options like :kconfig:option:`CONFIG_NET_DEFAULT_IF_FIRST` and :kconfig:option:`CONFIG_NET_DEFAULT_IF_ETHERNET`. See Kconfig file :zephyr_file:`subsys/net/ip/Kconfig` what options are available for selecting the default network interface. The transmitted and received network packets can be classified via a network packet priority. This is typically done in Ethernet networks when virtual LANs (VLANs) are used. Higher priority packets can be sent or received earlier than lower priority packets. The traffic class setup can be configured by :kconfig:option:`CONFIG_NET_TC_TX_COUNT` and :kconfig:option:`CONFIG_NET_TC_RX_COUNT` options. If the :kconfig:option:`CONFIG_NET_PROMISCUOUS_MODE` is enabled and if the underlying network technology supports promiscuous mode, then it is possible to receive all the network packets that the network device driver is able to receive. See :ref:`promiscuous_interface` API for more details. .. _net_if_interface_state_management: Network interface state management ********************************** Zephyr distinguishes between two interface states: administrative state and operational state, as described in RFC 2863. The administrative state indicate whether an interface is turned ON or OFF. This state is represented by :c:enumerator:`NET_IF_UP` flag and is controlled by the application. It can be changed by calling :c:func:`net_if_up` or :c:func:`net_if_down` functions. Network drivers or L2 implementations should not change administrative state on their own. Bringing an interface up however not always means that the interface is ready to transmit packets. Because of that, operational state, which represents the internal interface status, was implemented. The operational state is updated whenever one of the following conditions take place: * The interface is brought up/down by the application (administrative state changes). * The interface is notified by the driver/L2 that PHY status has changed. * The interface is notified by the driver/L2 that it joined/left a network. The PHY status is represented with :c:enumerator:`NET_IF_LOWER_UP` flag and can be changed with :c:func:`net_if_carrier_on` and :c:func:`net_if_carrier_off`. By default, the flag is set on a newly initialized interface. An example of an event that changes the carrier state is Ethernet cable being plugged in or out. The network association status is represented with :c:enumerator:`NET_IF_DORMANT` flag and can be changed with :c:func:`net_if_dormant_on` and :c:func:`net_if_dormant_off`. By default, the flag is cleared on a newly initialized interface. An example of an event that changes the dormant state is a Wi-Fi driver successfully connecting to an access point. In this scenario, driver should set the dormant state to ON during initialization, and once it detects that it connected to a Wi-Fi network, the dormant state should be set to OFF. The operational state of an interface is updated as follows: * ``!net_if_is_admin_up()`` Interface is in :c:enumerator:`NET_IF_OPER_DOWN`. * ``net_if_is_admin_up() && !net_if_is_carrier_ok()`` Interface is in :c:enumerator:`NET_IF_OPER_DOWN` or :c:enumerator:`NET_IF_OPER_LOWERLAYERDOWN` if the interface is stacked (virtual). * ``net_if_is_admin_up() && net_if_is_carrier_ok() && net_if_is_dormant()`` Interface is in :c:enumerator:`NET_IF_OPER_DORMANT`. * ``net_if_is_admin_up() && net_if_is_carrier_ok() && !net_if_is_dormant()`` Interface is in :c:enumerator:`NET_IF_OPER_UP`. Only after an interface enters :c:enumerator:`NET_IF_OPER_UP` state the :c:enumerator:`NET_IF_RUNNING` flag is set on the interface indicating that the interface is ready to be used by the application. API Reference ************* .. doxygengroup:: net_if ```
/content/code_sandbox/doc/connectivity/networking/api/net_if.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,265
```restructuredtext .. _net_system_mgmt: Network System Management ######################### .. toctree:: :maxdepth: 1 net_config.rst dhcpv4.rst dhcpv6.rst net_hostname.rst net_core.rst net_if.rst net_l2.rst net_offload.rst net_linkaddr.rst ethernet_mgmt.rst traffic-class.rst net_pkt_filter.rst net_shell.rst tls_credentials_shell.rst ```
/content/code_sandbox/doc/connectivity/networking/api/system_mgmt.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
117
```restructuredtext .. _net_buf_mgmt: Network Buffer Management ######################### .. toctree:: :maxdepth: 1 net_buf.rst net_pkt.rst ```
/content/code_sandbox/doc/connectivity/networking/api/buf_mgmt.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
38
```restructuredtext .. _ptp_time_interface: Precision Time Protocol (PTP) time format ######################################### .. contents:: :local: :depth: 2 Overview ******** The PTP time struct can store time information in high precision format (nanoseconds). The extended timestamp format can store the time in fractional nanoseconds accuracy. The PTP time format is used in :ref:`gptp_interface` implementation. API Reference ************* .. doxygengroup:: ptp_time ```
/content/code_sandbox/doc/connectivity/networking/api/ptp_time.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
106
```restructuredtext .. _ppp: Point-to-Point Protocol (PPP) Support ##################################### .. contents:: :local: :depth: 2 Overview ******** `Point-to-Point Protocol <path_to_url`_ (PPP) is a data link layer (layer 2) communications protocol used to establish a direct connection between two nodes. PPP is used over many types of serial links since IP packets cannot be transmitted over a modem line on their own, without some data link protocol. In Zephyr, each individual PPP link is modelled as a network interface. This is similar to how Linux implements PPP. PPP support must be enabled at compile time by setting option :kconfig:option:`CONFIG_NET_L2_PPP`. The PPP implementation supports only these protocols: * LCP (Link Control Protocol, `RFC1661 <path_to_url`__) * HDLC (High-level data link control, `RFC1662 <path_to_url`__) * IPCP (IP Control Protocol, `RFC1332 <path_to_url`__) * IPV6CP (IPv6 Control Protocol, `RFC5072 <path_to_url`__) For using PPP with a cellular modem, see :zephyr:code-sample:`cellular-modem` sample for additional information. Testing ******* See the `net-tools README`_ file for more details on how to test the Zephyr PPP against pppd running in Linux. .. _net-tools README: path_to_url#ppp-connectivity ```
/content/code_sandbox/doc/connectivity/networking/api/ppp.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
324
```restructuredtext .. _net_context_interface: Networking Context ################## The net_context API is not meant for application use. Application should use :ref:`bsd_sockets_interface` API instead. ```
/content/code_sandbox/doc/connectivity/networking/api/net_context.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
38
```restructuredtext .. _net_apis: Network APIs ############ .. toctree:: :maxdepth: 1 sockets.rst ip_4_6.rst dns_resolve.rst net_mgmt.rst net_stats.rst net_timeout.rst net_context.rst promiscuous.rst sntp.rst socks5.rst trickle.rst websocket.rst capture.rst ```
/content/code_sandbox/doc/connectivity/networking/api/apis.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
103
```restructuredtext .. _dns_resolve_interface: DNS Resolve ########### .. contents:: :local: :depth: 2 Overview ******** The DNS resolver implements a basic DNS resolver according to `IETF RFC1035 on Domain Implementation and Specification <path_to_url`_. Supported DNS answers are IPv4/IPv6 addresses and CNAME. If a CNAME is received, the DNS resolver will create another DNS query. The number of additional queries is controlled by the :kconfig:option:`CONFIG_DNS_RESOLVER_ADDITIONAL_QUERIES` Kconfig variable. The multicast DNS (mDNS) client resolver support can be enabled by setting :kconfig:option:`CONFIG_MDNS_RESOLVER` Kconfig option. See `IETF RFC6762 <path_to_url`_ for more details about mDNS. The link-local multicast name resolution (LLMNR) client resolver support can be enabled by setting the :kconfig:option:`CONFIG_LLMNR_RESOLVER` Kconfig variable. See `IETF RFC4795 <path_to_url`_ for more details about LLMNR. For more information about DNS configuration variables, see: :zephyr_file:`subsys/net/lib/dns/Kconfig`. The DNS resolver API can be found at :zephyr_file:`include/zephyr/net/dns_resolve.h`. Sample usage ************ See :zephyr:code-sample:`dns-resolve` sample application for details. API Reference ************* .. doxygengroup:: dns_resolve ```
/content/code_sandbox/doc/connectivity/networking/api/dns_resolve.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
322
```restructuredtext .. _net_timeout_interface: Network Timeout ############### .. contents:: :local: :depth: 2 Overview ******** Zephyr's network infrastructure mostly uses the millisecond-resolution uptime clock to track timeouts, with both deadlines and durations measured with 32-bit unsigned values. The 32-bit value rolls over at 49 days 17 hours 2 minutes 47.296 seconds. Timeout processing is often affected by latency, so that the time at which the timeout is checked may be some time after it should have expired. Handling this correctly without arbitrary expectations of maximum latency requires that the maximum delay that can be directly represented be a 31-bit non-negative number (``INT32_MAX``), which overflows at 24 days 20 hours 31 minutes 23.648 seconds. Most network timeouts are shorter than the delay rollover, but a few protocols allow for delays that are represented as unsigned 32-bit values counting seconds, which corresponds to a 42-bit millisecond count. The net_timeout API provides a generic timeout mechanism to correctly track the remaining time for these extended-duration timeouts. Use *** The simplest use of this API is: #. Configure a network timeout using :c:func:`net_timeout_set()`. #. Use :c:func:`net_timeout_evaluate()` to determine how long it is until the timeout occurs. Schedule a timeout to occur after this delay. #. When the timeout callback is invoked, use :c:func:`net_timeout_evaluate()` again to determine whether the timeout has completed, or whether there is additional time remaining. If the latter, reschedule the callback. #. While the timeout is running, use :c:func:`net_timeout_remaining` to get the number of seconds until the timeout expires. This may be used to explicitly update the timeout, which should be done by canceling any pending callback and restarting from step 1 with the new timeout. The :c:struct:`net_timeout` contains a ``sys_snode_t`` that allows multiple timeout instances to be aggregated to share a single kernel timer element. The application must use :c:func:`net_timeout_evaluate()` on all instances to determine the next timeout event to occur. :c:func:`net_timeout_deadline()` may be used to reconstruct the full-precision deadline of the timeout. This exists primarily for testing but may have use in some applications, as it does allow a millisecond-resolution calculation of remaining time. API Reference ************* .. doxygengroup:: net_timeout ```
/content/code_sandbox/doc/connectivity/networking/api/net_timeout.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
546
```restructuredtext .. _http_client_interface: HTTP Client ########### .. contents:: :local: :depth: 2 Overview ******** The HTTP client library allows you to send HTTP requests and parse HTTP responses. The library communicates over the sockets API but it does not create sockets on its own. It can be enabled with :kconfig:option:`CONFIG_HTTP_CLIENT` Kconfig option. The application must be responsible for creating a socket and passing it to the library. Therefore, depending on the application's needs, the library can communicate over either a plain TCP socket (HTTP) or a TLS socket (HTTPS). Sample Usage ************ The API of the HTTP client library has a single function. The following is an example of a request structure created correctly: .. code-block:: c struct http_request req = { 0 }; static uint8_t recv_buf[512]; req.method = HTTP_GET; req.url = "/"; req.host = "localhost"; req.protocol = "HTTP/1.1"; req.response = response_cb; req.recv_buf = recv_buf; req.recv_buf_len = sizeof(recv_buf); /* sock is a file descriptor referencing a socket that has been connected * to the HTTP server. */ ret = http_client_req(sock, &req, 5000, NULL); If the server responds to the request, the library provides the response to the application through the response callback registered in the request structure. As the library can provide the response in chunks, the application must be able to process these. Together with the structure containing the response data, the callback function also provides information about whether the library expects to receive more data. The following is an example of a very simple response handling function: .. code-block:: c static void response_cb(struct http_response *rsp, enum http_final_call final_data, void *user_data) { if (final_data == HTTP_DATA_MORE) { LOG_INF("Partial data received (%zd bytes)", rsp->data_len); } else if (final_data == HTTP_DATA_FINAL) { LOG_INF("All the data received (%zd bytes)", rsp->data_len); } LOG_INF("Response status %s", rsp->http_status); } See :zephyr:code-sample:`HTTP client sample application <sockets-http-client>` for more information about the library usage. API Reference ************* .. doxygengroup:: http_client ```
/content/code_sandbox/doc/connectivity/networking/api/http_client.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
516
```restructuredtext .. _ethernet_interface: Ethernet ######## .. contents:: :local: :depth: 2 .. toctree:: :maxdepth: 1 vlan.rst lldp.rst 8021Qav.rst Overview ******** Ethernet is a networking technology commonly used in local area networks (LAN). For more information, see this `Ethernet Wikipedia article <path_to_url`_. Zephyr supports following Ethernet features: * 10, 100 and 1000 Mbit/sec links * Auto negotiation * Half/full duplex * Promiscuous mode * TX and RX checksum offloading * MAC address filtering * :ref:`Virtual LANs <vlan_interface>` * :ref:`Priority queues <traffic-class-support>` * :ref:`IEEE 802.1AS (gPTP) <gptp_interface>` * :ref:`IEEE 802.1Qav (credit based shaping) <8021Qav>` * :ref:`LLDP (Link Layer Discovery Protocol) <lldp_interface>` Not all Ethernet device drivers support all of these features. You can see what is supported by ``net iface`` net-shell command. It will print currently supported Ethernet features. API Reference ************* .. doxygengroup:: ethernet .. doxygengroup:: ethernet_mii ```
/content/code_sandbox/doc/connectivity/networking/api/ethernet.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
290
```restructuredtext .. _net_linkaddr_interface: Link Layer Address Handling ########################### .. contents:: :local: :depth: 2 Overview ******** The link layer addresses are set for network interfaces so that L2 connectivity works correctly in the network stack. Typically the link layer addresses are 6 bytes long like in Ethernet but for IEEE 802.15.4 the link layer address length is 8 bytes. API Reference ************* .. doxygengroup:: net_linkaddr ```
/content/code_sandbox/doc/connectivity/networking/api/net_linkaddr.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
106
```restructuredtext .. _net_hostname_interface: Hostname Configuration ###################### .. contents:: :local: :depth: 2 Overview ******** A networked device might need a hostname, for example, if the device is configured to be a mDNS responder (see :ref:`dns_resolve_interface` for details) and needs to respond to ``<hostname>.local`` DNS queries. The :kconfig:option:`CONFIG_NET_HOSTNAME_ENABLE` must be set in order to store the hostname and enable the relevant APIs. If the option is enabled, then the default hostname is set to be ``zephyr`` by :kconfig:option:`CONFIG_NET_HOSTNAME` option. If the same firmware image is used to flash multiple boards, then it is not practical to use the same hostname in all of the boards. In that case, one can enable :kconfig:option:`CONFIG_NET_HOSTNAME_UNIQUE` which will add a unique postfix to the hostname. By default the link local address of the first network interface is used as a postfix. In Ethernet networks, the link local address refers to MAC address. For example, if the link local address is ``01:02:03:04:05:06``, then the unique hostname could be ``zephyr010203040506``. If you want to set the prefix yourself, then call ``net_hostname_set_postfix_str()`` before the network interfaces are created. Alternatively, if you prefer a hexadecimal conversion for the prefix, then call ``net_hostname_set_postfix()``. For example for the Ethernet networks, the initialization priority is set by :kconfig:option:`CONFIG_ETH_INIT_PRIORITY` so you would need to set the postfix before that. The postfix can be set only once. API Reference ************* .. doxygengroup:: net_hostname ```
/content/code_sandbox/doc/connectivity/networking/api/net_hostname.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
389
```restructuredtext .. _net_tsn: Time Sensitive Networking ######################### .. toctree:: :maxdepth: 1 gptp.rst net_time.rst ptp_time.rst ptp.rst ```
/content/code_sandbox/doc/connectivity/networking/api/tsn.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
53
```restructuredtext .. _net_pkt_interface: Packet Management ################# .. contents:: :local: :depth: 2 Overview ******** Network packets are the main data the networking stack manipulates. Such data is represented through the net_pkt structure which provides a means to hold the packet, write and read it, as well as necessary metadata for the core to hold important information. Such an object is called net_pkt in this document. The data structure and the whole API around it are defined in :zephyr_file:`include/zephyr/net/net_pkt.h`. Architectural notes =================== There are two network packets flows within the stack, **TX** for the transmission path, and **RX** for the reception one. In both paths, each net_pkt is written and read from the beginning to the end, or more specifically from the headers to the payload. Memory management ***************** Allocation ========== All net_pkt objects come from a pre-defined pool of struct net_pkt. Such pool is defined via .. code-block:: c NET_PKT_SLAB_DEFINE(name, count) Note, however, one will rarely have to use it, as the core provides already two pools, one for the TX path and one for the RX path. Allocating a raw net_pkt can be done through: .. code-block:: c pkt = net_pkt_alloc(timeout); However, by its nature, a raw net_pkt is useless without a buffer and needs various metadata information to become relevant as well. It requires at least to get the network interface it is meant to be sent through or through which it was received. As this is a very common operation, a helper exist: .. code-block:: c pkt = net_pkt_alloc_on_iface(iface, timeout); A more complete allocator exists, where both the net_pkt and its buffer can be allocated at once: .. code-block:: c pkt = net_pkt_alloc_with_buffer(iface, size, family, proto, timeout); See below how the buffer is allocated. Buffer allocation ================= The net_pkt object does not define its own buffer, but instead uses an existing object for this: :c:struct:`net_buf`. (See :ref:`net_buf_interface` for more information). However, it mostly hides the usage of such a buffer because net_pkt brings network awareness to buffer allocation and, as we will see later, its operation too. To allocate a buffer, a net_pkt needs to have at least its network interface set. This works if the family of the packet is unknown at the time of buffer allocation. Then one could do: .. code-block:: c net_pkt_alloc_buffer(pkt, size, proto, timeout); Where proto could be 0 if unknown (there is no IPPROTO_UNSPEC). As seen previously, the net_pkt and its buffer can be allocated at once via :c:func:`net_pkt_alloc_with_buffer`. It is actually the most widely used allocator. The network interface, the family, and the protocol of the packet are used by the buffer allocation to determine if the requested size can be allocated. Indeed, the allocator will use the network interface to know the MTU and then the family and protocol for the headers space (if only these 2 are specified). If the whole fits within the MTU, the allocated space will be of the requested size plus, eventually, the headers space. If there is insufficient MTU space, the requested size will be shrunk so the possible headers space and new size will fit within the MTU. For instance, on an Ethernet network interface, with an MTU of 1500 bytes: .. code-block:: c pkt = net_pkt_alloc_with_buffer(iface, 800, AF_INET4, IPPROTO_UDP, K_FOREVER); will successfully allocate 800 + 20 + 8 bytes of buffer for the new net_pkt where: .. code-block:: c pkt = net_pkt_alloc_with_buffer(iface, 1600, AF_INET4, IPPROTO_UDP, K_FOREVER); will successfully allocate 1500 bytes, and where 20 + 8 bytes (IPv4 + UDP headers) will not be used for the payload. On the receiving side, when the family and protocol are not known: .. code-block:: c pkt = net_pkt_rx_alloc_with_buffer(iface, 800, AF_UNSPEC, 0, K_FOREVER); will allocate 800 bytes and no extra header space. But a: .. code-block:: c pkt = net_pkt_rx_alloc_with_buffer(iface, 1600, AF_UNSPEC, 0, K_FOREVER); will allocate 1514 bytes, the MTU + Ethernet header space. One can increase the amount of buffer space allocated by calling :c:func:`net_pkt_alloc_buffer`, as it will take into account the existing buffer. It will also account for the header space if net_pkt's family is a valid one, as well as the proto parameter. In that case, the newly allocated buffer space will be appended to the existing one, and not inserted in the front. Note however such a use case is rather limited. Usually, one should know from the start how much size should be requested. Deallocation ============ Each net_pkt is reference counted. At allocation, the reference is set to 1. The reference count can be incremented with :c:func:`net_pkt_ref()` or decremented with :c:func:`net_pkt_unref()`. When the count drops to zero the buffer is also un-referenced and net_pkt is automatically placed back into the free net_pkt_slabs If net_pkt's buffer is needed even after net_pkt deallocation, one will need to reference once more all the chain of net_buf before calling last net_pkt_unref. See :ref:`net_buf_interface` for more information. Operations ********** There are two ways to access the net_pkt buffer, explained in the following sections: basic read/write access and data access, the latter being the preferred way. Read and Write access ===================== As said earlier, though net_pkt uses net_buf for its buffer, it provides its own API to access it. Indeed, a network packet might be scattered over a chain of net_buf objects, the functions provided by net_buf are then limited for such case. Instead, net_pkt provides functions which hide all the complexity of potential non-contiguous access. Data movement into the buffer is made through a cursor maintained within each net_pkt. All read/write operations affect this cursor. Note as well that read or write functions are strict on their length parameters: if it cannot r/w the given length it will fail. Length is not interpreted as an upper limit, it is instead the exact amount of data that must be read or written. As there are two paths, TX and RX, there are two access modes: write and overwrite. This might sound a bit unusual, but is in fact simple and provides flexibility. In write mode, whatever is written in the buffer affects the length of actual data present in the buffer. Buffer length should not be confused with the buffer size which is a limit any mode cannot pass. In overwrite mode then, whatever is written must happen on valid data, and will not affect the buffer length. By default, a newly allocated net_pkt is on write mode, and its cursor points to the beginning of its buffer. Let's see now, step by step, the functions and how they behave depending on the mode. When freshly allocated with a buffer of 500 bytes, a net_pkt has 0 length, which means no valid data is in its buffer. One could verify this by: .. code-block:: c len = net_pkt_get_len(pkt); Now, let's write 8 bytes: .. code-block:: c net_pkt_write(pkt, data, 8); The buffer length is now 8 bytes. There are various helpers to write a byte, or big endian uint16_t, uint32_t. .. code-block:: c net_pkt_write_u8(pkt, &foo); net_pkt_write_be16(pkt, &ba); net_pkt_write_be32(pkt, &bar); Logically, net_pkt's length is now 15. But if we try to read at this point, it will fail because there is nothing to read at the cursor where we are at in the net_pkt. It is possible, while in write mode, to read what has been already written by resetting the cursor of the net_pkt. For instance: .. code-block:: c net_pkt_cursor_init(pkt); net_pkt_read(pkt, data, 15); This will reset the cursor of the pkt to the beginning of the buffer and then let you read the actual 15 bytes present. The cursor is then again pointing at the end of the buffer. To set a large area with the same byte, a memset function is provided: .. code-block:: c net_pkt_memset(pkt, 0, 5); Our net_pkt has now a length of 20 bytes. Switching between modes can be achieved via :c:func:`net_pkt_set_overwrite` function. It is possible to switch mode back and forth at any time. The net_pkt will be set to overwrite and its cursor reset: .. code-block:: c net_pkt_set_overwrite(pkt, true); net_pkt_cursor_init(pkt); Now the same operators can be used, but it will be limited to the existing data in the buffer, i.e. 20 bytes. If it is necessary to know how much space is available in the net_pkt call: .. code-block:: c net_pkt_available_buffer(pkt); Or, if headers space needs to be accounted for, call: .. code-block:: c net_pkt_available_payload_buffer(pkt, proto); If you want to place the cursor at a known position use the function :c:func:`net_pkt_skip`. For example, to go after the IP header, use: .. code-block:: c net_pkt_cursor_init(pkt); net_pkt_skip(pkt, net_pkt_ip_header_len(pkt)); Data access =========== Though the API shown previously is rather simple, it involves always copying things to and from the net_pkt buffer. In many occasions, it is more relevant to access the information stored in the buffer contiguously, especially with network packets which embed headers. These headers are, most of the time, a known fixed set of bytes. It is then more natural to have a structure representing a certain type of header. In addition to this, if it is known the header size appears in a contiguous area of the buffer, it will be way more efficient to cast the actual position in the buffer to the type of header. Either for reading or writing the fields of such header, accessing it directly will save memory. Net pkt comes with a dedicated API for this, built on top of the previously described API. It is able to handle both contiguous and non-contiguous access transparently. There are two macros used to define a data access descriptor: :c:macro:`NET_PKT_DATA_ACCESS_DEFINE` when it is not possible to tell if the data will be in a contiguous area, and :c:macro:`NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE` when it is guaranteed the data is in a contiguous area. Let's take the example of IP and UDP. Both IPv4 and IPv6 headers are always found at the beginning of the packet and are small enough to fit in a net_buf of 128 bytes (for instance, though 64 bytes could be chosen). .. code-block:: c NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(ipv4_access, struct net_ipv4_hdr); struct net_ipv4_hdr *ipv4_hdr; ipv4_hdr = (struct net_ipv4_hdr *)net_pkt_get_data(pkt, &ipv4_access); It would be the same for struct net_ipv4_hdr. For a UDP header it is likely not to be in a contiguous area in IPv6 for instance so: .. code-block:: c NET_PKT_DATA_ACCESS_DEFINE(udp_access, struct net_udp_hdr); struct net_udp_hdr *udp_hdr; udp_hdr = (struct net_udp_hdr *)net_pkt_get_data(pkt, &udp_access); At this point, the cursor of the net_pkt points at the beginning of the requested data. On the RX path, these headers will be read but not modified so to proceed further the cursor needs to advance past the data. There is a function dedicated for this: .. code-block:: c net_pkt_acknowledge_data(pkt, &ipv4_access); On the TX path, however, the header fields have been modified. In such a case: .. code-block:: c net_pkt_set_data(pkt, &ipv4_access); If the data are in a contiguous area, it will advance the cursor relevantly. If not, it will write the data and the cursor will be updated. Note that :c:func:`net_pkt_set_data` could be used in the RX path as well, but it is slightly faster to use :c:func:`net_pkt_acknowledge_data` as this one does not care about contiguity at all, it just advances the cursor via :c:func:`net_pkt_skip` directly. API Reference ************* .. doxygengroup:: net_pkt ```
/content/code_sandbox/doc/connectivity/networking/api/net_pkt.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,858
```restructuredtext .. _gptp_interface: generic Precision Time Protocol (gPTP) ###################################### .. contents:: :local: :depth: 2 Overview ******** This gPTP stack supports the protocol and procedures as defined in the `IEEE 802.1AS-2011 standard`_ (Timing and Synchronization for Time-Sensitive Applications in Bridged Local Area Networks). Supported features ******************* The stack handles communications and state machines defined in the `IEEE 802.1AS-2011 standard`_. Mandatory requirements for a full-duplex point-to-point link endpoint, as defined in Annex A of the standard, are supported. The stack is in principle capable of handling communications on multiple network interfaces (also defined as "ports" in the standard) and thus act as a 802.1AS bridge. However, this mode of operation has not been validated on the Zephyr OS. Supported hardware ****************** Although the stack itself is hardware independent, Ethernet frame timestamping support must be enabled in ethernet drivers. Boards supported: - :ref:`frdm_k64f` - :ref:`nucleo_h743zi_board` - :ref:`nucleo_h745zi_q_board` - :ref:`nucleo_f767zi_board` - :ref:`sam_e70_xplained` - :ref:`native_sim` (only usable for simple testing, limited capabilities due to lack of hardware clock) - :ref:`qemu_x86` (emulated, limited capabilities due to lack of hardware clock) Enabling the stack ****************** The following configuration option must me enabled in :file:`prj.conf` file. - :kconfig:option:`CONFIG_NET_GPTP` Application interfaces ********************** Only two Application Interfaces as defined in section 9 of the standard are available: - ``ClockTargetPhaseDiscontinuity`` interface (:c:func:`gptp_register_phase_dis_cb`) - ``ClockTargetEventCapture`` interface (:c:func:`gptp_event_capture`) Testing ******* The stack has been informally tested using the `OpenAVnu gPTP <path_to_url`_ and `Linux ptp4l <path_to_url`_ daemons. The :zephyr:code-sample:`gPTP sample application <gptp>` from the Zephyr source distribution can be used for testing. .. _IEEE 802.1AS-2011 standard: path_to_url API Reference ************* .. doxygengroup:: gptp ```
/content/code_sandbox/doc/connectivity/networking/api/gptp.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
545
```restructuredtext .. _vlan_interface: Virtual LAN (VLAN) Support ########################## .. contents:: :local: :depth: 2 Overview ******** `Virtual LAN <path_to_url`_ (VLAN) is a partitioned and isolated computer network at the data link layer (OSI layer 2). For ethernet network this refers to `IEEE 802.1Q <path_to_url`_ In Zephyr, each individual VLAN is modeled as a virtual network interface. This means that there is an ethernet network interface that corresponds to a real physical ethernet port in the system. A virtual network interface is created for each VLAN, and this virtual network interface connects to the real network interface. This is similar to how Linux implements VLANs. The *eth0* is the real network interface and *vlan0* is a virtual network interface that is run on top of *eth0*. VLAN support must be enabled at compile time by setting option :kconfig:option:`CONFIG_NET_VLAN` and :kconfig:option:`CONFIG_NET_VLAN_COUNT` to reflect how many network interfaces there will be in the system. For example, if there is one network interface without VLAN support, and two with VLAN support, the :kconfig:option:`CONFIG_NET_VLAN_COUNT` option should be set to 3. Even if VLAN is enabled in a :file:`prj.conf` file, the VLAN needs to be activated at runtime by the application. The VLAN API provides a :c:func:`net_eth_vlan_enable` function to do that. The application needs to give the network interface and desired VLAN tag as a parameter to that function. The VLAN tagging for a given network interface can be disabled by a :c:func:`net_eth_vlan_disable` function. The application needs to configure the VLAN network interface itself, such as setting the IP address, etc. See also the :zephyr:code-sample:`VLAN sample application <vlan>` for API usage example. The source code for that sample application can be found at :zephyr_file:`samples/net/vlan`. The net-shell module contains *net vlan add* and *net vlan del* commands that can be used to enable or disable VLAN tags for a given network interface. See the `IEEE 802.1Q spec`_ for more information about ethernet VLANs. .. _IEEE 802.1Q spec: path_to_url API Reference ************* .. doxygengroup:: vlan_api ```
/content/code_sandbox/doc/connectivity/networking/api/vlan.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
528
```restructuredtext .. _net_offload_interface: Network Traffic Offloading ========================== .. contents:: :local: :depth: 2 Network Offloading ################## Overview ******** The network offloading API provides hooks that a device vendor can use to provide an alternate implementation for an IP stack. This means that the actual network connection creation, data transfer, etc., is done in the vendor HAL instead of the Zephyr network stack. API Reference ************* .. doxygengroup:: net_offload .. _net_socket_offloading: Socket Offloading ################# Overview ******** In addition to the network offloading API, Zephyr allows offloading of networking functionality at the socket API level. With this approach, vendors who provide an alternate implementation of the networking stack, exposing socket API for their networking devices, can easily integrate it with Zephyr. See :zephyr_file:`drivers/wifi/simplelink/simplelink_sockets.c` for a sample implementation on how to integrate network offloading at socket level. ```
/content/code_sandbox/doc/connectivity/networking/api/net_offload.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
223
```restructuredtext .. _mqtt_socket_interface: MQTT #### .. contents:: :local: :depth: 2 Overview ******** MQTT (Message Queuing Telemetry Transport) is an application layer protocol which works on top of the TCP/IP stack. It is a lightweight publish/subscribe messaging transport for machine-to-machine communication. For more information about the protocol itself, see path_to_url Zephyr provides an MQTT client library built on top of BSD sockets API. The library can be enabled with :kconfig:option:`CONFIG_MQTT_LIB` Kconfig option and is configurable at a per-client basis, with support for MQTT versions 3.1.0 and 3.1.1. The Zephyr MQTT implementation can be used with either plain sockets communicating over TCP, or with secure sockets communicating over TLS. See :ref:`bsd_sockets_interface` for more information about Zephyr sockets. MQTT clients require an MQTT server to connect to. Such a server, called an MQTT Broker, is responsible for managing client subscriptions and distributing messages published by clients. There are many implementations of MQTT brokers, one of them being Eclipse Mosquitto. See path_to_url for more information about the Eclipse Mosquitto project. Sample usage ************ To create an MQTT client, a client context structure and buffers need to be defined: .. code-block:: c /* Buffers for MQTT client. */ static uint8_t rx_buffer[256]; static uint8_t tx_buffer[256]; /* MQTT client context */ static struct mqtt_client client_ctx; Multiple MQTT client instances can be created in the application and managed independently. Additionally, a structure for MQTT Broker address information is needed. This structure must be accessible throughout the lifespan of the MQTT client and can be shared among MQTT clients: .. code-block:: c /* MQTT Broker address information. */ static struct sockaddr_storage broker; An MQTT client library will notify MQTT events to the application through a callback function created to handle respective events: .. code-block:: c void mqtt_evt_handler(struct mqtt_client *client, const struct mqtt_evt *evt) { switch (evt->type) { /* Handle events here. */ } } For a list of possible events, see :ref:`mqtt_api_reference`. The client context structure needs to be initialized and set up before it can be used. An example configuration for TCP transport is shown below: .. code-block:: c mqtt_client_init(&client_ctx); /* MQTT client configuration */ client_ctx.broker = &broker; client_ctx.evt_cb = mqtt_evt_handler; client_ctx.client_id.utf8 = (uint8_t *)"zephyr_mqtt_client"; client_ctx.client_id.size = sizeof("zephyr_mqtt_client") - 1; client_ctx.password = NULL; client_ctx.user_name = NULL; client_ctx.protocol_version = MQTT_VERSION_3_1_1; client_ctx.transport.type = MQTT_TRANSPORT_NON_SECURE; /* MQTT buffers configuration */ client_ctx.rx_buf = rx_buffer; client_ctx.rx_buf_size = sizeof(rx_buffer); client_ctx.tx_buf = tx_buffer; client_ctx.tx_buf_size = sizeof(tx_buffer); After the configuration is set up, the MQTT client can connect to the MQTT broker. Call the ``mqtt_connect`` function, which will create the appropriate socket, establish a TCP/TLS connection, and send an ``MQTT CONNECT`` message. When notified, the application should call the ``mqtt_input`` function to process the response received. Note, that ``mqtt_input`` is a non-blocking function, therefore the application should use socket ``poll`` to wait for the response. If the connection was successful, ``MQTT_EVT_CONNACK`` will be notified to the application through the callback function. .. code-block:: c rc = mqtt_connect(&client_ctx); if (rc != 0) { return rc; } fds[0].fd = client_ctx.transport.tcp.sock; fds[0].events = ZSOCK_POLLIN; poll(fds, 1, 5000); mqtt_input(&client_ctx); if (!connected) { mqtt_abort(&client_ctx); } In the above code snippet, the MQTT callback function should set the ``connected`` flag upon a successful connection. If the connection fails at the MQTT level or a timeout occurs, the connection will be aborted, and the underlying socket closed. After the connection is established, an application needs to call ``mqtt_input`` and ``mqtt_live`` functions periodically to process incoming data and upkeep the connection. If an MQTT message is received, an MQTT callback function will be called and an appropriate event notified. The connection can be closed by calling the ``mqtt_disconnect`` function. Zephyr provides sample code utilizing the MQTT client API. See :zephyr:code-sample:`mqtt-publisher` for more information. Using MQTT with TLS ******************* The Zephyr MQTT library can be used with TLS transport for secure communication by selecting a secure transport type (``MQTT_TRANSPORT_SECURE``) and some additional configuration information: .. code-block:: c client_ctx.transport.type = MQTT_TRANSPORT_SECURE; struct mqtt_sec_config *tls_config = &client_ctx.transport.tls.config; tls_config->peer_verify = TLS_PEER_VERIFY_REQUIRED; tls_config->cipher_list = NULL; tls_config->sec_tag_list = m_sec_tags; tls_config->sec_tag_count = ARRAY_SIZE(m_sec_tags); tls_config->hostname = MQTT_BROKER_HOSTNAME; In this sample code, the ``m_sec_tags`` array holds a list of tags, referencing TLS credentials that the MQTT library should use for authentication. We do not specify ``cipher_list``, to allow the use of all cipher suites available in the system. We set ``hostname`` field to broker hostname, which is required for server authentication. Finally, we enforce peer certificate verification by setting the ``peer_verify`` field. Note, that TLS credentials referenced by the ``m_sec_tags`` array must be registered in the system first. For more information on how to do that, refer to :ref:`secure sockets documentation <secure_sockets_interface>`. An example of how to use TLS with MQTT is also present in :zephyr:code-sample:`mqtt-publisher` sample application. .. _mqtt_api_reference: API Reference ************* .. doxygengroup:: mqtt_socket ```
/content/code_sandbox/doc/connectivity/networking/api/mqtt.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,372
```restructuredtext .. _zperf: zperf: Network Traffic Generator ################################ .. contents:: :local: :depth: 2 Overview ******** zperf is a shell utility which allows to generate network traffic in Zephyr. The tool may be used to evaluate network bandwidth. zperf is compatible with iPerf_2.0.5. Note that in newer iPerf versions, an error message like this is printed and the server reported statistics are missing. .. code-block:: console LAST PACKET NOT RECEIVED!!! zperf can be enabled in any application, a dedicated sample is also present in Zephyr. See :zephyr:code-sample:`zperf sample application <zperf>` for details. Sample Usage ************ If Zephyr acts as a client, iPerf must be executed in server mode. For example, the following command line must be used for UDP testing: .. code-block:: console $ iperf -s -l 1K -u -V -B 2001:db8::2 For TCP testing, the command line would look like this: .. code-block:: console $ iperf -s -l 1K -V -B 2001:db8::2 In the Zephyr console, zperf can be executed as follows: .. code-block:: console zperf udp upload 2001:db8::2 5001 10 1K 1M For TCP the zperf command would look like this: .. code-block:: console zperf tcp upload 2001:db8::2 5001 10 1K 1M If the IP addresses of Zephyr and the host machine are specified in the config file, zperf can be started as follows: .. code-block:: console zperf udp upload2 v6 10 1K 1M or like this if you want to test TCP: .. code-block:: console zperf tcp upload2 v6 10 1K 1M If Zephyr is acting as a server, set the download mode as follows for UDP: .. code-block:: console zperf udp download 5001 or like this for TCP: .. code-block:: console zperf tcp download 5001 and in the host side, iPerf must be executed with the following command line if you are testing UDP: .. code-block:: console $ iperf -l 1K -u -V -c 2001:db8::1 -p 5001 and this if you are testing TCP: .. code-block:: console $ iperf -l 1K -V -c 2001:db8::1 -p 5001 iPerf output can be limited by using the -b option if Zephyr is not able to receive all the packets in orderly manner. ```
/content/code_sandbox/doc/connectivity/networking/api/zperf.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
628
```restructuredtext .. _wifi_mgmt: Wi-Fi Management ################ Overview ======== The Wi-Fi management API is used to manage Wi-Fi networks. It supports below modes: * IEEE802.11 Station (STA) * IEEE802.11 Access Point (AP) Only personal mode security is supported with below types: * Open * WPA2-PSK * WPA3-PSK-256 * WPA3-SAE The Wi-Fi management API is implemented in the `wifi_mgmt` module as a part of the networking L2 stack. Currently, two types of Wi-Fi drivers are supported: * Networking or socket offloaded drivers * Native L2 Ethernet drivers Wi-Fi Enterprise test: X.509 Certificate header generation ********************************************************** Wi-Fi enterprise security requires use of X.509 certificates, test certificates in PEM format are committed to the repo at :zephyr_file:`samples/net/wifi/test_certs` and the during the build process the certificates are converted to a `C` header file that is included by the Wi-Fi shell module. .. code-block:: bash $ cp client.pem samples/net/wifi/test_certs/ $ cp client-key.pem samples/net/wifi/test_certs/ $ cp ca.pem samples/net/wifi/test_certs/ $ west build -p -b <board> samples/net/wifi To initiate Wi-Fi connection, the following command can be used: .. code-block:: console uart:~$ wifi connect -s <SSID> -k 5 -a anon -K whatever Server certificate is also provided in the same directory for testing purposes. Any `AAA` server can be used for testing purposes, for example, `FreeRADIUS` or `hostapd`. .. important:: The passphrase for the client-key.pem and the server-key.pem is `whatever`. .. note:: The certificates are for testing purposes only and should not be used in production. The certificates are generated using `FreeRADIUS raddb <path_to_url _` scripts. API Reference ************* .. doxygengroup:: wifi_mgmt ```
/content/code_sandbox/doc/connectivity/networking/api/wifi.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
440
```restructuredtext .. _promiscuous_interface: Promiscuous Mode ################ .. contents:: :local: :depth: 2 Overview ******** Promiscuous mode is a mode for a network interface controller that causes it to pass all traffic it receives to the application rather than passing only the frames that the controller is specifically programmed to receive. This mode is normally used for packet sniffing as used to diagnose network connectivity issues by showing an application all the data being transferred over the network. (See the `Wikipedia article on promiscuous mode <path_to_url`_ for more information.) The network promiscuous APIs are used to enable and disable this mode, and to wait for and receive a network data to arrive. Not all network technologies or network device drivers support promiscuous mode. Sample usage ************ First the promiscuous mode needs to be turned ON by the application like this: .. code-block:: c ret = net_promisc_mode_on(iface); if (ret < 0) { if (ret == -EALREADY) { printf("Promiscuous mode already enabled\n"); } else { printf("Cannot enable promiscuous mode for " "interface %p (%d)\n", iface, ret); } } If there is no error, then the application can start to wait for network data: .. code-block:: c while (true) { pkt = net_promisc_mode_wait_data(K_FOREVER); if (pkt) { print_info(pkt); } net_pkt_unref(pkt); } Finally the promiscuous mode can be turned OFF by the application like this: .. code-block:: c ret = net_promisc_mode_off(iface); if (ret < 0) { if (ret == -EALREADY) { printf("Promiscuous mode already disabled\n"); } else { printf("Cannot disable promiscuous mode for " "interface %p (%d)\n", iface, ret); } } See :zephyr:code-sample:`net-promiscuous-mode` for a more comprehensive example. API Reference ************* .. doxygengroup:: promiscuous ```
/content/code_sandbox/doc/connectivity/networking/api/promiscuous.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
476
```restructuredtext .. _bsd_sockets_interface: BSD Sockets ########### .. contents:: :local: :depth: 2 Overview ******** Zephyr offers an implementation of a subset of the BSD Sockets API (a part of the POSIX standard). This API allows to reuse existing programming experience and port existing simple networking applications to Zephyr. Here are the key requirements and concepts which governed BSD Sockets compatible API implementation for Zephyr: * Has minimal overhead, similar to the requirement for other Zephyr subsystems. * Is namespaced by default, to avoid name conflicts with well-known names like ``close()``, which may be part of libc or other POSIX compatibility libraries. If enabled by :kconfig:option:`CONFIG_POSIX_API`, it will also expose native POSIX names. BSD Sockets compatible API is enabled using :kconfig:option:`CONFIG_NET_SOCKETS` config option and implements the following operations: ``socket()``, ``close()``, ``recv()``, ``recvfrom()``, ``send()``, ``sendto()``, ``connect()``, ``bind()``, ``listen()``, ``accept()``, ``fcntl()`` (to set non-blocking mode), ``getsockopt()``, ``setsockopt()``, ``poll()``, ``select()``, ``getaddrinfo()``, ``getnameinfo()``. Based on the namespacing requirements above, these operations are by default exposed as functions with ``zsock_`` prefix, e.g. :c:func:`zsock_socket` and :c:func:`zsock_close`. If the config option :kconfig:option:`CONFIG_POSIX_API` is defined, all the functions will be also exposed as aliases without the prefix. This includes the functions like ``close()`` and ``fcntl()`` (which may conflict with functions in libc or other libraries, for example, with the filesystem libraries). Another entailment of the design requirements above is that the Zephyr API aggressively employs the short-read/short-write property of the POSIX API whenever possible (to minimize complexity and overheads). POSIX allows for calls like ``recv()`` and ``send()`` to actually process (receive or send) less data than requested by the user (on ``SOCK_STREAM`` type sockets). For example, a call ``recv(sock, 1000, 0)`` may return 100, meaning that only 100 bytes were read (short read), and the application needs to retry call(s) to receive the remaining 900 bytes. The BSD Sockets API uses file descriptors to represent sockets. File descriptors are small integers, consecutively assigned from zero, shared among sockets, files, special devices (like stdin/stdout), etc. Internally, there is a table mapping file descriptors to internal object pointers. The file descriptor table is used by the BSD Sockets API even if the rest of the POSIX subsystem (filesystem, stdin/stdout) is not enabled. See :zephyr:code-sample:`sockets-echo-server` and :zephyr:code-sample:`sockets-echo-client` sample applications to learn how to create a simple server or client BSD socket based application. .. _secure_sockets_interface: Secure Sockets ************** Zephyr provides an extension of standard POSIX socket API, allowing to create and configure sockets with TLS protocol types, facilitating secure communication. Secure functions for the implementation are provided by mbedTLS library. Secure sockets implementation allows use of both TLS and DTLS protocols with standard socket calls. See :c:enum:`net_ip_protocol_secure` type for supported secure protocol versions. To enable secure sockets, set the :kconfig:option:`CONFIG_NET_SOCKETS_SOCKOPT_TLS` option. To enable DTLS support, use :kconfig:option:`CONFIG_NET_SOCKETS_ENABLE_DTLS` option. .. _sockets_tls_credentials_subsys: TLS credentials subsystem ========================= TLS credentials must be registered in the system before they can be used with secure sockets. See :c:func:`tls_credential_add` for more information. When a specific TLS credential is registered in the system, it is assigned with numeric value of type :c:type:`sec_tag_t`, called a tag. This value can be used later on to reference the credential during secure socket configuration with socket options. The following TLS credential types can be registered in the system: - ``TLS_CREDENTIAL_CA_CERTIFICATE`` - ``TLS_CREDENTIAL_SERVER_CERTIFICATE`` - ``TLS_CREDENTIAL_PRIVATE_KEY`` - ``TLS_CREDENTIAL_PSK`` - ``TLS_CREDENTIAL_PSK_ID`` An example registration of CA certificate (provided in ``ca_certificate`` array) looks like this: .. code-block:: c ret = tls_credential_add(CA_CERTIFICATE_TAG, TLS_CREDENTIAL_CA_CERTIFICATE, ca_certificate, sizeof(ca_certificate)); By default certificates in DER format are supported. PEM support can be enabled in mbedTLS settings. Secure Socket Creation ====================== A secure socket can be created by specifying secure protocol type, for instance: .. code-block:: c sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TLS_1_2); Once created, it can be configured with socket options. For instance, the CA certificate and hostname can be set: .. code-block:: c sec_tag_t sec_tag_opt[] = { CA_CERTIFICATE_TAG, }; ret = setsockopt(sock, SOL_TLS, TLS_SEC_TAG_LIST, sec_tag_opt, sizeof(sec_tag_opt)); .. code-block:: c char host[] = "google.com"; ret = setsockopt(sock, SOL_TLS, TLS_HOSTNAME, host, sizeof(host)); Once configured, socket can be used just like a regular TCP socket. Several samples in Zephyr use secure sockets for communication. For a sample use see e.g. :zephyr:code-sample:`echo-server sample application <sockets-echo-server>` or :zephyr:code-sample:`HTTP GET sample application <sockets-http-get>`. Secure Sockets options ====================== Secure sockets offer the following options for socket management: .. doxygengroup:: secure_sockets_options Socket offloading ***************** Zephyr allows to register custom socket implementations (called offloaded sockets). This allows for seamless integration for devices which provide an external IP stack and expose socket-like API. Socket offloading can be enabled with :kconfig:option:`CONFIG_NET_SOCKETS_OFFLOAD` option. A network driver that wants to register a new socket implementation should use :c:macro:`NET_SOCKET_OFFLOAD_REGISTER` macro. The macro accepts the following parameters: * ``socket_name`` An arbitrary name for the socket implementation. * ``prio`` Socket implementation's priority. The higher the priority, the earlier this particular implementation will be processed when creating a new socket. Lower numeric value indicates higher priority. * ``_family`` Socket family implemented by the offloaded socket. ``AF_UNSPEC`` indicates any family. * ``_is_supported`` A filtering function, used to verify whether a particular socket family, type and protocol are supported by the offloaded socket implementation. * ``_handler`` A function compatible with :c:func:`socket` API, used to create an offloaded socket. Every offloaded socket implementation should also implement a set of socket APIs, specified in :c:struct:`socket_op_vtable` struct. The function registered for socket creation should allocate a new file descriptor using :c:func:`zvfs_reserve_fd` function. Any additional actions, specific to the creation of a particular offloaded socket implementation, should take place after the file descriptor is allocated. As a final step, if the offloaded socket was created successfully, the file descriptor should be finalized with :c:func:`zvfs_finalize_typed_fd`, or :c:func:`zvfs_finalize_fd` functions. The finalize function allows to register a :c:struct:`socket_op_vtable` structure implementing socket APIs for an offloaded socket along with an optional socket context data pointer. Finally, when an offloaded network interface is initialized, it should indicate that the interface is offloaded with :c:func:`net_if_socket_offload_set` function. The function registers the function used to create an offloaded socket (the same as the one provided in :c:macro:`NET_SOCKET_OFFLOAD_REGISTER`) at the network interface. Offloaded socket creation ========================= When application creates a new socket with :c:func:`socket` function, the network stack iterates over all registered socket implementations (native and offloaded). Higher priority socket implementations are processed first. For each registered socket implementation, an address family is verified, and if it matches (or the socket was registered as ``AF_UNSPEC``), the corresponding ``_is_supported`` function is called to verify the remaining socket parameters. The first implementation that fulfills the socket requirements (i. e. ``_is_supported`` returns true) will create a new socket with its ``_handler`` function. The above indicates the importance of the socket priority. If multiple socket implementations support the same set of socket family/type/protocol, the first implementation processed by the system will create a socket. Therefore it's important to give the highest priority to the implementation that should be the system default. The socket priority for native socket implementation is configured with Kconfig. Use :kconfig:option:`CONFIG_NET_SOCKETS_TLS_PRIORITY` to set the priority for the native TLS sockets. Use :kconfig:option:`CONFIG_NET_SOCKETS_PRIORITY_DEFAULT` to set the priority for the remaining native sockets. Dealing with multiple offloaded interfaces ========================================== As the :c:func:`socket` function does not allow to specify which network interface should be used by a socket, it's not possible to choose a specific implementation in case multiple offloaded socket implementations, supporting the same type of sockets, are available. The same problem arises when both native and offloaded sockets are available in the system. To address this problem, a special socket implementation (called socket dispatcher) was introduced. The sole reason for this module is to postpone the socket creation for until the first operation on a socket is performed. This leaves an opening to use ``SO_BINDTODEVICE`` socket option, to bind a socket to a particular network interface (and thus offloaded socket implementation). The socket dispatcher can be enabled with :kconfig:option:`CONFIG_NET_SOCKETS_OFFLOAD_DISPATCHER` Kconfig option. When enabled, the application can specify the network interface to use with :c:func:`setsockopt` function: .. code-block:: c /* A "dispatcher" socket is created */ sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); struct ifreq ifreq = { .ifr_name = "SimpleLink" }; /* The socket is "dispatched" to a particular network interface * (offloaded or not). */ setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, &ifreq, sizeof(ifreq)); Similarly, if TLS is supported by both native and offloaded sockets, ``TLS_NATIVE`` socket option can be used to indicate that a native TLS socket should be created. The underlying socket can then be bound to a particular network interface: .. code-block:: c /* A "dispatcher" socket is created */ sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TLS_1_2); int tls_native = 1; /* The socket is "dispatched" to a native TLS socket implmeentation. * The underlying socket is a "dispatcher" socket now. */ setsockopt(sock, SOL_TLS, TLS_NATIVE, &tls_native, sizeof(tls_native)); struct ifreq ifreq = { .ifr_name = "SimpleLink" }; /* The underlying socket is "dispatched" to a particular network interface * (offloaded or not). */ setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, &ifreq, sizeof(ifreq)); In case no ``SO_BINDTODEVICE`` socket option is used on a socket, the socket will be dispatched according to the default priority and filtering rules on a first socket API call. API Reference ************* BSD Sockets =========== .. doxygengroup:: bsd_sockets TLS Credentials =============== .. doxygengroup:: tls_credentials ```
/content/code_sandbox/doc/connectivity/networking/api/sockets.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,633
```restructuredtext .. _mqtt_sn_socket_interface: MQTT-SN ####### .. contents:: :local: :depth: 2 Overview ******** MQTT-SN is a variant of the well-known MQTT protocol - see :ref:`mqtt_socket_interface`. In contrast to MQTT, MQTT-SN does not require a TCP transport, but is designed to be used over any message-based transport. Originally, it was mainly created with ZigBee in mind, but others like Bluetooth, UDP or even a UART can be used just as well. Zephyr provides an MQTT-SN client library built on top of BSD sockets API. The library can be enabled with :kconfig:option:`CONFIG_MQTT_SN_LIB` Kconfig option and is configurable at a per-client basis, with support for MQTT-SN version 1.2. The Zephyr MQTT-SN implementation can be used with any message-based transport, but support for UDP is already built-in. MQTT-SN clients require an MQTT-SN gateway to connect to. These gateways translate between MQTT-SN and MQTT. The Eclipse Paho project offers an implementation of a MQTT-SN gateway, but others are available too. path_to_url The MQTT-SN spec v1.2 can be found here: path_to_url Sample usage ************ To create an MQTT-SN client, a client context structure and buffers need to be defined: .. code-block:: c /* Buffers for MQTT client. */ static uint8_t rx_buffer[256]; static uint8_t tx_buffer[256]; /* MQTT-SN client context */ static struct mqtt_sn_client client; Multiple MQTT-SN client instances can be created in the application and managed independently. Additionally, a structure for the transport is needed as well. The library already comes with an example implementation for UDP. .. code-block:: c /* MQTT Broker address information. */ static struct mqtt_sn_transport tp; The MQTT-SN library will inform clients about certain events using a callback. .. code-block:: c static void evt_cb(struct mqtt_sn_client *client, const struct mqtt_sn_evt *evt) { switch(evt->type) { { /* Handle events here. */ } } For a list of possible events, see :ref:`mqtt_sn_api_reference`. The client context structure needs to be initialized and set up before it can be used. An example configuration for UDP transport is shown below: .. code-block:: c struct mqtt_sn_data client_id = MQTT_SN_DATA_STRING_LITERAL("ZEPHYR"); struct sockaddr_in gateway = {0}; uint8_t tx_buf[256]; uint8_t rx_buf[256]; mqtt_sn_transport_udp_init(&tp, (struct sockaddr*)&gateway, sizeof((gateway))); mqtt_sn_client_init(&client, &client_id, &tp.tp, evt_cb, tx_buf, sizeof(tx_buf), rx_buf, sizeof(rx_buf)); After the configuration is set up, the MQTT-SN client can connect to the gateway. While the MQTT-SN protocol offers functionality to discover gateways through an advertisement mechanism, this is not implemented yet in the library. Call the ``mqtt_sn_connect`` function, which will send a ``CONNECT`` message. The application should periodically call the ``mqtt_sn_input`` function to process the response received. The application does not have to call ``mqtt_sn_input`` if it knows that no data has been received (e.g. when using Bluetooth). Note that ``mqtt_sn_input`` is a non-blocking function, if the transport struct contains a ``poll`` compatible function pointer. If the connection was successful, ``MQTT_SN_EVT_CONNECTED`` will be notified to the application through the callback function. .. code-block:: c err = mqtt_sn_connect(&client, false, true); __ASSERT(err == 0, "mqtt_sn_connect() failed %d", err); while (1) { mqtt_sn_input(&client); if (connected) { mqtt_sn_publish(&client, MQTT_SN_QOS_0, &topic_p, false, &pubdata); } k_sleep(K_MSEC(500)); } In the above code snippet, the event handler function should set the ``connected`` flag upon a successful connection. If the connection fails at the MQTT level or a timeout occurs, the connection will be aborted. After the connection is established, an application needs to call ``mqtt_input`` function periodically to process incoming data. Connection upkeep, on the other hand, is done automatically using a k_work item. If a MQTT message is received, an MQTT callback function will be called and an appropriate event notified. The connection can be closed by calling the ``mqtt_sn_disconnect`` function. This has no effect on the transport, however. If you want to close the transport (e.g. the socket), call ``mqtt_sn_client_deinit``, which will deinit the transport as well. Zephyr provides sample code utilizing the MQTT-SN client API. See :zephyr:code-sample:`mqtt-sn-publisher` for more information. Deviations from the standard **************************** Certain parts of the protocol are not yet supported in the library. * Pre-defined topic IDs * QoS -1 - it's most useful with predefined topics * Gateway discovery using ADVERTISE, SEARCHGW and GWINFO messages. * Setting the will topic and message after the initial connect * Forwarder Encapsulation .. _mqtt_sn_api_reference: API Reference ************* .. doxygengroup:: mqtt_sn_socket ```
/content/code_sandbox/doc/connectivity/networking/api/mqtt_sn.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,175
```restructuredtext .. _8021Qav: IEEE 802.1Qav ############# Overview ******** Credit-based shaping is an alternative scheduling algorithm used in network schedulers to achieve fairness when sharing a limited network resource. Zephyr has support for configuring a credit-based shaper described in the `IEEE 802.1Qav-2009 standard`_. Zephyr does not implement the actual shaper; it only provides a way to configure the shaper implemented by the Ethernet device driver. Enabling 802.1Qav ***************** To enable 802.1Qav shaper, the Ethernet device driver must declare that it supports credit-based shaping. The Ethernet driver's capability function must return ``ETHERNET_QAV`` value for this purpose. Typically also priority queues ``ETHERNET_PRIORITY_QUEUES`` need to be supported. .. code-block:: none static enum ethernet_hw_caps eth_get_capabilities(const struct device *dev) { ARG_UNUSED(dev); return ETHERNET_QAV | ETHERNET_PRIORITY_QUEUES | ETHERNET_HW_VLAN | ETHERNET_LINK_10BASE_T | ETHERNET_LINK_100BASE_T; } See ``sam-e70-xplained`` board Ethernet driver :zephyr_file:`drivers/ethernet/eth_sam_gmac.c` for an example. Configuring 802.1Qav ******************** The application can configure the credit-based shaper like this: .. code-block:: c #include <zephyr/net/net_if.h> #include <zephyr/net/ethernet.h> #include <zephyr/net/ethernet_mgmt.h> static void qav_set_status(struct net_if *iface, int queue_id, bool enable) { struct ethernet_req_params params; int ret; memset(&params, 0, sizeof(params)); params.qav_param.queue_id = queue_id; params.qav_param.enabled = enable; params.qav_param.type = ETHERNET_QAV_PARAM_TYPE_STATUS; /* Disable or enable Qav for a queue */ ret = net_mgmt(NET_REQUEST_ETHERNET_SET_QAV_PARAM, iface, &params, sizeof(struct ethernet_req_params)); if (ret) { LOG_ERR("Cannot %s Qav for queue %d for interface %p", enable ? "enable" : "disable", queue_id, iface); } } static void qav_set_bandwidth_and_slope(struct net_if *iface, int queue_id, unsigned int bandwidth, unsigned int idle_slope) { struct ethernet_req_params params; int ret; memset(&params, 0, sizeof(params)); params.qav_param.queue_id = queue_id; params.qav_param.delta_bandwidth = bandwidth; params.qav_param.type = ETHERNET_QAV_PARAM_TYPE_DELTA_BANDWIDTH; ret = net_mgmt(NET_REQUEST_ETHERNET_SET_QAV_PARAM, iface, &params, sizeof(struct ethernet_req_params)); if (ret) { LOG_ERR("Cannot set Qav delta bandwidth %u for " "queue %d for interface %p", bandwidth, queue_id, iface); } params.qav_param.idle_slope = idle_slope; params.qav_param.type = ETHERNET_QAV_PARAM_TYPE_IDLE_SLOPE; ret = net_mgmt(NET_REQUEST_ETHERNET_SET_QAV_PARAM, iface, &params, sizeof(struct ethernet_req_params)); if (ret) { LOG_ERR("Cannot set Qav idle slope %u for " "queue %d for interface %p", idle_slope, queue_id, iface); } } .. _IEEE 802.1Qav-2009 standard: path_to_url ```
/content/code_sandbox/doc/connectivity/networking/api/8021Qav.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
813
```restructuredtext .. _conn_mgr_docs: Connection Manager ################## .. toctree:: :maxdepth: 1 main.rst implementation.rst ```
/content/code_sandbox/doc/connectivity/networking/conn_mgr/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
35
```restructuredtext .. _conn_mgr_overview: Overview ######## Connection Manager is a collection of optional Zephyr features that aim to allow applications to monitor and control connectivity (access to IP-capable networks) with minimal concern for the specifics of underlying network technologies. Using Connection Manager, applications can use a single abstract API to control network association and monitor Internet access, and avoid excessive use of technology-specific boilerplate. This allows an application to potentially support several very different connectivity technologies (for example, Wi-Fi and LTE) with a single codebase. Applications can also use Connection Manager to generically manage and use multiple connectivity technologies simultaneously. Structure ========= Connection Manager is split into the following two subsystems: * :ref:`Connectivity monitoring <conn_mgr_monitoring>` (header file :file:`include/zephyr/net/conn_mgr_monitoring.h`) monitors all available :ref:`Zephyr network interfaces (ifaces) <net_if_interface>` and triggers :ref:`network management <net_mgmt_interface>` events indicating when IP connectivity is gained or lost. * :ref:`Connectivity control <conn_mgr_control>` (header file :file:`include/zephyr/net/conn_mgr_connectivity.h`) provides an abstract API for controlling iface network association. .. _conn_mgr_integration_diagram_simple: .. figure:: figures/integration_diagram_simplified.svg :alt: A simplified view of how Connection Manager integrates with Zephyr and the application. :figclass: align-center A simplified view of how Connection Manager integrates with Zephyr and the application. See :ref:`here <conn_mgr_integration_diagram_detailed>` for a more detailed version. .. _conn_mgr_monitoring: Connectivity monitoring ####################### Connectivity monitoring tracks all available ifaces (whether or not they support :ref:`Connectivity control <conn_mgr_control>`) as they transition through various :ref:`operational states <net_if_interface_state_management>` and acquire or lose assigned IP addresses. Each available iface is considered ready if it meets the following criteria: * The iface is admin-up * This means the iface has been instructed to become operational-up (ready for use). This is done by a call to :c:func:`net_if_up`. * The iface is oper-up * This means the interface is completely ready for use; It is online, and if applicable, has associated with a network. * See :ref:`net_if_interface_state_management` for details. * The iface has at least one assigned IP address * Both IPv4 and IPv6 addresses are acceptable. This condition is met as soon as one or both of these is assigned. * See :ref:`net_if_interface` for details on iface IP assignment. * The iface has not been ignored * Ignored ifaces are always treated as unready. * See :ref:`conn_mgr_monitoring_ignoring_ifaces` for more details. .. note:: Typically, iface state and IP assignment are updated either by the iface's :ref:`L2 implementation <net_l2_interface>` or bound :ref:`connectivity implementation <conn_mgr_impl>`. See :ref:`conn_mgr_impl_guidelines_iface_state_reporting` for details. A ready iface ceases to be ready the moment any of the above conditions is lost. When at least one iface is ready, the :c:macro:`NET_EVENT_L4_CONNECTED` :ref:`network management <net_mgmt_interface>` event is triggered, and IP connectivity is said to be ready. Afterwards, ifaces can become ready or unready without firing additional events, so long as there always remains at least one ready iface. When there are no longer any ready ifaces left, the :c:macro:`NET_EVENT_L4_DISCONNECTED` :ref:`network management <net_mgmt_interface>` event is triggered, and IP connectivity is said to be unready. .. note:: Connection Manager also fires the following more specific ``CONNECTED`` / ``DISCONNECTED`` events: - :c:macro:`NET_EVENT_L4_IPV4_CONNECTED` - :c:macro:`NET_EVENT_L4_IPV4_DISCONNECTED` - :c:macro:`NET_EVENT_L4_IPV6_CONNECTED` - :c:macro:`NET_EVENT_L4_IPV6_DISCONNECTED` These are similar to :c:macro:`NET_EVENT_L4_CONNECTED` and :c:macro:`NET_EVENT_L4_DISCONNECTED`, but specifically track whether IPv4- and IPv6-capable ifaces are ready. .. _conn_mgr_monitoring_usage: Usage ===== Connectivity monitoring is enabled if the :kconfig:option:`CONFIG_NET_CONNECTION_MANAGER` Kconfig option is enabled. To receive connectivity updates, create and register a listener for the :c:macro:`NET_EVENT_L4_CONNECTED` and :c:macro:`NET_EVENT_L4_DISCONNECTED` :ref:`network management <net_mgmt_interface>` events: .. code-block:: c /* Callback struct where the callback will be stored */ struct net_mgmt_event_callback l4_callback; /* Callback handler */ static void l4_event_handler(struct net_mgmt_event_callback *cb, uint32_t event, struct net_if *iface) { if (event == NET_EVENT_L4_CONNECTED) { LOG_INF("Network connectivity gained!"); } else if (event == NET_EVENT_L4_DISCONNECTED) { LOG_INF("Network connectivity lost!"); } /* Otherwise, it's some other event type we didn't register for. */ } /* Call this before Connection Manager monitoring initializes */ static void my_application_setup(void) { /* Configure the callback struct to respond to (at least) the L4_CONNECTED * and L4_DISCONNECTED events. * * * Note that the callback may also be triggered for events other than those specified here! * (See the net_mgmt documentation) */ net_mgmt_init_event_callback( &l4_callback, l4_event_handler, NET_EVENT_L4_CONNECTED | NET_EVENT_L4_DISCONNECTED ); /* Register the callback */ net_mgmt_add_event_callback(&l4_callback); } See :ref:`net_mgmt_listening` for more details on listening for net_mgmt events. .. note:: To avoid missing initial connectivity events, you should register your listener(s) before Connection Manager monitoring initializes. See :ref:`conn_mgr_monitoring_missing_notifications` for strategies to ensure this. .. _conn_mgr_monitoring_missing_notifications: Avoiding missed notifications ============================= Connectivity monitoring may trigger events immediately upon initialization. If your application registers its event listeners after connectivity monitoring initializes, it is possible to miss this first wave of events, and not be informed the first time network connectivity is gained. If this is a concern, your application should :ref:`register its event listeners <conn_mgr_monitoring_usage>` before connectivity monitoring initializes. Connectivity monitoring initializes using the :c:macro:`SYS_INIT` ``APPLICATION`` initialization priority specified by the :kconfig:option:`CONFIG_NET_CONNECTION_MANAGER_MONITOR_PRIORITY` Kconfig option. You can register your callbacks before this initialization by using :c:macro:`SYS_INIT` with an earlier initialization priority than this value, for instance priority 0: .. code-block:: C static int my_application_setup(void) { /* Register callbacks here */ return 0; } SYS_INIT(my_application_setup, APPLICATION, 0); If this is not feasible, you can instead request that connectivity monitoring resend the latest connectivity events at any time by calling :c:func:`conn_mgr_mon_resend_status`: .. code-block:: C static void my_late_application_setup(void) { /* Register callbacks here */ /* Once done, request that events be re-triggered */ conn_mgr_mon_resend_status(); } .. _conn_mgr_monitoring_ignoring_ifaces: Ignoring ifaces =============== Applications can request that ifaces be ignored by Connection Manager by calling :c:func:`conn_mgr_ignore_iface` with the iface to be ignored. Alternatively, an entire :ref:`L2 implementation <net_l2_interface>` can be ignored by calling :c:func:`conn_mgr_ignore_l2`. This has the effect of individually ignoring all the ifaces using that :ref:`L2 implementation <net_l2_interface>`. While ignored, the iface is treated by Connection Manager as though it were unready for network traffic, no matter its actual state. This may be useful, for instance, if your application has configured one or more ifaces that cannot (or for whatever reason should not) be used to contact the wider Internet. :ref:`Bulk convenience functions <conn_mgr_control_api_bulk>` optionally skip ignored ifaces. See :c:func:`conn_mgr_ignore_iface` and :c:func:`conn_mgr_watch_iface` for more details. .. _conn_mgr_monitoring_api: Connectivity monitoring API =========================== Include header file :file:`include/zephyr/net/conn_mgr_monitoring.h` to access these. .. doxygengroup:: conn_mgr .. _conn_mgr_control: Connectivity control #################### Many network interfaces require a network association procedure to be completed before being usable. For such ifaces, connectivity control can provide a generic API to request network association (:c:func:`conn_mgr_if_connect`) and disassociation (:c:func:`conn_mgr_if_disconnect`). Network interfaces implement support for this API by :ref:`binding themselves to a connectivity implementation <conn_mgr_impl_binding>`. Using this API, applications can associate with networks with minimal technology-specific boilerplate. Connectivity control also provides the following additional features: * Standardized :ref:`persistence and timeout <conn_mgr_control_persistence_timeouts>` behaviors during association. * :ref:`Bulk functions <conn_mgr_control_api_bulk>` for controlling the admin state and network association of all available ifaces simultaneously. * Optional :ref:`convenience automations <conn_mgr_control_automations>` for common connectivity actions. .. _conn_mgr_control_operation: Basic operation =============== The following sections outline the basic operation of Connection Manager's connectivity control. .. _conn_mgr_control_operation_binding: Binding ------- Before an iface can be commanded to associate or disassociate using Connection Manager, it must first be bound to a :ref:`connectivity implementation <conn_mgr_impl>`. Binding is performed by the provider of the iface, not by the application (see :ref:`conn_mgr_impl_binding`), and can be thought of as an extension of the iface declaration. Once an iface is bound, all connectivity commands passed to it (such as :c:func:`conn_mgr_if_connect` or :c:func:`conn_mgr_if_disconnect`) will be routed to the corresponding implementation function in the connectivity implementation. .. note:: To avoid inconsistent behavior, all connectivity implementations must adhere to the :ref:`implementation guidelines <conn_mgr_impl_guidelines>`. .. _conn_mgr_control_operation_connecting: Connecting ---------- Once a bound iface is admin-up (see :ref:`net_if_interface_state_management`), :c:func:`conn_mgr_if_connect` can be called to cause it to associate with a network. If association succeeds, the connectivity implementation will mark the iface as operational-up (see :ref:`net_if_interface_state_management`). If association fails unrecoverably, the :ref:`fatal error event <conn_mgr_control_events_fatal_error>` will be triggered. You can configure an optional :ref:`timeout <conn_mgr_control_timeouts>` for this process. .. note:: The :c:func:`conn_mgr_if_connect` function is intentionally minimalistic, and does not take any kind of configuration. Each connectivity implementation should provide a way to pre-configure or automatically configure any required association settings or credentials. See :ref:`conn_mgr_impl_guidelines_preconfig` for details. .. _conn_mgr_control_operation_loss: Connection loss --------------- If connectivity is lost due to external factors, the connectivity implementation will mark the iface as operational-down. Depending on whether :ref:`persistence <conn_mgr_control_persistence>` is set, the iface may then attempt to reconnect. .. _conn_mgr_control_operation_disconnection: Manual disconnection -------------------- The application can also request that connectivity be intentionally abandoned by calling :c:func:`conn_mgr_if_disconnect`. In this case, the connectivity implementation will disassociate the iface from its network and mark the iface as operational-down (see :ref:`net_if_interface_state_management`). A new connection attempt will not be initiated, regardless of whether persistence is enabled. .. _conn_mgr_control_persistence_timeouts: Timeouts and Persistence ======================== Connection Manager requires that all connectivity implementations support the following standard key features: * :ref:`Connection timeouts <conn_mgr_control_timeouts>` * :ref:`Connection persistence <conn_mgr_control_persistence>` These features describe how ifaces should behave during connect and disconnect events. You can individually set them for each iface. .. note:: It is left to connectivity implementations to successfully and accurately implement these two features as described below. See :ref:`conn_mgr_impl_timeout_persistence` for more details from the connectivity implementation perspective. .. _conn_mgr_control_timeouts: Connection Timeouts ------------------- When :c:func:`conn_mgr_if_connect` is called on an iface, a connection attempt begins. The connection attempt continues indefinitely until it succeeds, unless a timeout has been specified for the iface (using :c:func:`conn_mgr_if_set_timeout`). In that case, the connection attempt will be abandoned if the timeout elapses before it succeeds. If this happens, the :ref:`timeout event<conn_mgr_control_events_timeout>` is raised. .. _conn_mgr_control_persistence: Connection Persistence ---------------------- Each iface also has a connection persistence setting that you can enable or disable by setting the :c:enumerator:`CONN_MGR_IF_PERSISTENT` flag with :c:func:`conn_mgr_binding_set_flag`. This setting specifies how the iface should handle unintentional connection loss. If persistence is enabled, any unintentional connection loss will initiate a new connection attempt, with a new timeout if applicable. Otherwise, the iface will not attempt to reconnect. .. note:: Persistence not does affect connection attempt behavior. Only the timeout setting affects this. For instance, if a connection attempt on an iface times out, the iface will not attempt to reconnect, even if it is persistent. Conversely, if there is not a specified timeout, the iface will try to connect forever until it succeeds, even if it is not persistent. See :ref:`conn_mgr_impl_tp_persistence_during_connect` for the equivalent implementation guideline. .. _conn_mgr_control_events: Control events ============== Connectivity control triggers :ref:`network management <net_mgmt_interface>` events to inform the application of important state changes. See :ref:`conn_mgr_impl_guidelines_trigger_events` for the corresponding connectivity implementation guideline. .. _conn_mgr_control_events_fatal_error: Fatal Error ----------- The :c:macro:`NET_EVENT_CONN_IF_FATAL_ERROR` event is raised when an iface encounters an error from which it cannot recover (meaning any subsequent attempts to associate are guaranteed to fail, and all such attempts should be abandoned). Handlers of this event will be passed a pointer to the iface for which the fatal error occurred. Individual connectivity implementations may also pass an application-specific data pointer. .. _conn_mgr_control_events_timeout: Timeout ------- The :c:macro:`NET_EVENT_CONN_IF_TIMEOUT` event is raised when an :ref:`iface association <conn_mgr_control_operation_connecting>` attempt :ref:`times out <conn_mgr_control_timeouts>`. Handlers of this event will be passed a pointer to the iface that timed out attempting to associate. .. _conn_mgr_control_events_listening: Listening for control events ---------------------------- You can listen for control events as follows: .. code-block:: c /* Declare a net_mgmt callback struct to store the callback */ struct net_mgmt_event_callback my_conn_evt_callback; /* Declare a handler to receive control events */ static void my_conn_evt_handler(struct net_mgmt_event_callback *cb, uint32_t event, struct net_if *iface) { if (event == NET_EVENT_CONN_IF_TIMEOUT) { /* Timeout occurred, handle it */ } else if (event == NET_EVENT_CONN_IF_FATAL_ERROR) { /* Fatal error occurred, handle it */ } /* Otherwise, it's some other event type we didn't register for. */ } int main() { /* Configure the callback struct to respond to (at least) the CONN_IF_TIMEOUT * and CONN_IF_FATAL_ERROR events. * * Note that the callback may also be triggered for events other than those specified here! * (See the net_mgmt documentation) */ net_mgmt_init_event_callback( &conn_mgr_conn_callback, conn_mgr_conn_handler, NET_EVENT_CONN_IF_TIMEOUT | NET_EVENT_CONN_IF_FATAL_ERROR ); /* Register the callback */ net_mgmt_add_event_callback(&conn_mgr_conn_callback); return 0; } See :ref:`net_mgmt_listening` for more details on listening for net_mgmt events. .. _conn_mgr_control_automations: Automated behaviors =================== There are a few actions related to connectivity that are (by default at least) performed automatically for the user. .. _conn_mgr_control_automations_auto_up: .. topic:: Automatic admin-up In Zephyr, ifaces are automatically taken admin-up (see :ref:`net_if_interface_state_management` for details on iface states) during initialization. Applications can disable this behavior by setting the :c:enumerator:`NET_IF_NO_AUTO_START` interface flag with :c:func:`net_if_flag_set`. .. _conn_mgr_control_automations_auto_connect: .. topic:: Automatic connect By default, Connection Manager will automatically connect any :ref:`bound <conn_mgr_impl_binding>` iface that becomes admin-up. Applications can disable this by setting the :c:enumerator:`CONN_MGR_IF_NO_AUTO_CONNECT` connectivity flag with :c:func:`conn_mgr_if_set_flag`. .. _conn_mgr_control_automations_auto_down: .. topic:: Automatic admin-down By default, Connection Manager will automatically take any bound iface admin-down if it has given up on associating. Applications can disable this for all ifaces by disabling the :kconfig:option:`CONFIG_NET_CONNECTION_MANAGER_AUTO_IF_DOWN` Kconfig option, or for individual ifaces by setting the :c:enumerator:`CONN_MGR_IF_NO_AUTO_DOWN` connectivity flag with :c:func:`conn_mgr_if_set_flag`. .. _conn_mgr_control_api: Connectivity control API ======================== Include header file :file:`include/zephyr/net/conn_mgr_connectivity.h` to access these. .. doxygengroup:: conn_mgr_connectivity .. _conn_mgr_control_api_bulk: Bulk API -------- Connectivity control provides several bulk functions allowing all ifaces to be controlled at once. You can restrict these functions to operate only on non-:ref:`ignored <conn_mgr_monitoring_ignoring_ifaces>` ifaces if desired. Include header file :file:`include/zephyr/net/conn_mgr_connectivity.h` to access these. .. doxygengroup:: conn_mgr_connectivity_bulk ```
/content/code_sandbox/doc/connectivity/networking/conn_mgr/main.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
4,010
```restructuredtext .. _conn_mgr_impl: Connectivity Implementations ############################ .. _conn_mgr_impl_overview: Overview ======== Connectivity implementations are technology-specific modules that allow specific Zephyr ifaces to support :ref:`Connectivity Control <conn_mgr_control>`. They are responsible for translating generic :ref:`connectivity control API <conn_mgr_control_api>` calls into hardware-specific operations. They are also responsible for implementing standardized :ref:`persistence and timeout <conn_mgr_control_persistence_timeouts>` behaviors. See the :ref:`implementation guidelines <conn_mgr_impl_guidelines>` for details on writing conformant connectivity implementations. .. _conn_mgr_impl_architecture: Architecture ============ The :ref:`implementation API <conn_mgr_impl_api>` allows connectivity implementations to be :ref:`defined <conn_mgr_impl_defining>` at build time using :c:macro:`CONN_MGR_CONN_DEFINE`. This creates a static instance of the :c:struct:`conn_mgr_conn_impl` struct, which then stores a reference to the passed in :c:struct:`conn_mgr_conn_api` struct (which should be populated with implementation callbacks). Once defined, you can reference implementations by name and bind them to any unbound iface using :c:macro:`CONN_MGR_BIND_CONN`. Make sure not to accidentally bind two connectivity implementations to a single iface. Once the iface is bound, :ref:`connectivity control API <conn_mgr_control_api>` functions can be called on the iface, and they will be translated to the corresponding implementation functions in :c:struct:`conn_mgr_conn_api`. Binding an iface does not directly modify its :c:struct:`iface struct <net_if>`. Instead, an instance of :c:struct:`conn_mgr_conn_binding` is created and appended an internal :ref:`iterable section <iterable_sections_api>`. This binding structure will contain a reference to the bound iface, the connectivity implementation it is bound to, as well as a pointer to a per-iface :ref:`context pointer <conn_mgr_impl_ctx>`. This iterable section can then be iterated over to find out what (if any) connectivity implementation has been bound to a given iface. This search process is used by most of the functions in the :ref:`connectivity control API <conn_mgr_control_api>`. As such, these functions should be called sparingly, due to their relatively high search cost. A single connectivity implementation may be bound to multiple ifaces. See :ref:`conn_mgr_impl_guidelines_no_instancing` for more details. .. _conn_mgr_integration_diagram_detailed: .. figure:: figures/integration_diagram_detailed.svg :alt: A detailed view of how Connection Manager integrates with Zephyr and the application. :figclass: align-center A detailed view of how Connection Manager integrates with Zephyr and the application. See :ref:`here <conn_mgr_integration_diagram_simple>` for a simplified version. .. _conn_mgr_impl_ctx: Context Pointer =============== Since a single connectivity implementation may be shared by several Zephyr ifaces, each binding instantiates a context container (of :ref:`configurable type <conn_mgr_impl_declaring>`) unique to that binding. Each binding is then instantiated with a reference to that container, which implementations can then use to access per-iface state information. See also :ref:`conn_mgr_impl_guidelines_binding_access` and :ref:`conn_mgr_impl_guidelines_no_instancing`. .. _conn_mgr_impl_defining: Defining an implementation ========================== A connectivity implementation may be defined as follows: .. code-block:: c /* Create the API implementation functions */ int my_connect_impl(struct conn_mgr_conn_binding *const binding) { /* Cause your underlying technology to associate */ } int my_disconnect_impl(struct conn_mgr_conn_binding *const binding) { /* Cause your underlying technology to disassociate */ } void my_init_impl(struct conn_mgr_conn_binding *const binding) { /* Perform any required initialization for your underlying technology */ } /* Declare the API struct */ static struct conn_mgr_conn_api my_impl_api = { .connect = my_connect_impl, .disconnect = my_disconnect_impl, .init = my_init_impl, /* ... so on */ }; /* Define the implementation (named MY_CONNECTIVITY_IMPL) */ CONN_MGR_CONN_DEFINE(MY_CONNECTIVITY_IMPL, &my_impl_api); .. note:: This does not work unless you also :ref:`declare the context pointer type <conn_mgr_impl_declaring_ctx>`. .. _conn_mgr_impl_declaring: Declaring an implementation publicly ==================================== Once defined, you can make a connectivity implementation available to other compilation units by declaring it (in a header file) as follows: .. code-block:: c :caption: ``my_connectivity_header.h`` CONN_MGR_CONN_DECLARE_PUBLIC(MY_CONNECTIVITY_IMPL); The header file that contains this declaration must be included in any compilation units that need to reference the implementation. .. _conn_mgr_impl_declaring_ctx: Declaring a context type ======================== For :c:macro:`CONN_MGR_CONN_DEFINE` to work, you must declare a corresponding context pointer type. This is because all connectivity bindings contain a :ref:`conn_mgr_impl_ctx` of their associated context pointer type. If you are using :c:macro:`CONN_MGR_CONN_DECLARE_PUBLIC`, declare this type alongside the declaration: .. code-block:: c :caption: ``my_connectivity_impl.h`` #define MY_CONNECTIVITY_IMPL_CTX_TYPE struct my_context_type * CONN_MGR_CONN_DECLARE_PUBLIC(MY_CONNECTIVITY_IMPL); Then, make sure to include the header file before calling :c:macro:`CONN_MGR_CONN_DEFINE`: .. code-block:: c :caption: ``my_connectivity_impl.c`` #include "my_connectivity_impl.h" CONN_MGR_CONN_DEFINE(MY_CONNECTIVITY_IMPL, &my_impl_api); Otherwise, it is sufficient to simply declare the context pointer type immediately before the call to :c:macro:`CONN_MGR_CONN_DEFINE`: .. code-block:: c #define MY_CONNECTIVITY_IMPL_CTX_TYPE struct my_context_type * CONN_MGR_CONN_DEFINE(MY_CONNECTIVITY_IMPL, &my_impl_api); .. note:: Naming is important. Your context pointer type declaration must use the same name as your implementation declaration, but with ``_CTX_TYPE`` appended. In the previous example, the context type is named ``MY_CONNECTIVITY_IMPL_CTX_TYPE``, because ``MY_CONNECTIVITY_IMPL`` was used as the connectivity implementation name. If your connectivity implementation does not need a context pointer, simply declare the type as void: .. code-block:: c #define MY_CONNECTIVITY_IMPL_CTX_TYPE void * .. _conn_mgr_impl_binding: Binding an iface to an implementation ===================================== A defined connectivity implementation may be bound to an iface by calling :c:macro:`CONN_MGR_BIND_CONN` anywhere after the iface's device definition: .. code-block:: c /* Define an iface */ NET_DEVICE_INIT(my_iface, /* ... the specifics here don't matter ... */ ); /* Now bind MY_CONNECTIVITY_IMPL to that iface -- * the name used should match with the above */ CONN_MGR_BIND_CONN(my_iface, MY_CONNECTIVITY_IMPL); .. _conn_mgr_impl_guidelines: Connectivity implementation guidelines ====================================== Rather than implement all features centrally, Connection Manager relies on each connectivity implementation to implement many behaviors and features individually. This approach allows Connection Manager to remain lean, and allows each connectivity implementation to choose the most appropriate approach to these behaviors for itself. However, it relies on trust that all connectivity implementations will faithfully implement the features that have been delegated to them. To maintain consistency between all connectivity implementations, observe the following guidelines when writing your own implementation: .. _conn_mgr_impl_guidelines_timeout_persistence: *Completely implement timeout and persistence* ---------------------------------------------- All connectivity implementations must offer complete support for :ref:`timeout and persistence <conn_mgr_control_persistence_timeouts>`, such that a user can disable or enable these features, regardless of the inherent behavior of the underlying technology. In other words, no matter how the underlying technology behaves, your implementation must make it appear to the end user to behave exactly as specified in the :ref:`conn_mgr_control_persistence_timeouts` section. See :ref:`conn_mgr_impl_timeout_persistence` for a detailed technical discussion on implementing timeouts and persistence. .. _conn_mgr_impl_guidelines_conformity: *Conform to API specifications* ------------------------------- Each :c:struct:`implementation API function <conn_mgr_conn_api>` you implement should behave as-described in the corresponding connectivity control API function. For example, your implementation of :c:member:`conn_mgr_conn_api.connect` should conform to the behavior described for :c:func:`conn_mgr_if_connect`. .. _conn_mgr_impl_guidelines_preconfig: *Allow connectivity pre-configuration* -------------------------------------- Connectivity implementations should provide means for applications to pre-configure all necessary connection parameters (for example, network SSID, or PSK, if applicable), before the call to :c:func:`conn_mgr_if_connect`. It should not be necessary to provide this information as part of, or following the :c:func:`conn_mgr_if_connect` call, although implementations :ref:`should await this information if it is not provided <conn_mgr_impl_guidelines_await_config>`. .. _conn_mgr_impl_guidelines_await_config: *Await valid connectivity configuration* ---------------------------------------- If network association fails because the application pre-configured invalid connection parameters, or did not configure connection parameters at all, this should be treated as a network failure. In other words, the connectivity implementation should not give up on the connection attempt, even if valid connection parameters have not been configured. Instead, the connectivity implementation should asynchronously wait for valid connection parameters to be configured, either indefinitely, or until the configured :ref:`connectivity timeout <conn_mgr_control_timeouts>` elapses. .. _conn_mgr_impl_guidelines_iface_state_reporting: *Implement iface state reporting* --------------------------------- All connectivity implementations must keep bound iface state up to date. To be specific: * Set the iface to dormant, carrier-down, or both during :c:member:`binding init <conn_mgr_conn_api.init>`. * See :ref:`net_if_interface_state_management` for details regarding iface carrier and dormant states. * Update dormancy and carrier state so that the iface is non-dormant and carrier-up whenever (and only when) association is complete and connectivity is ready. * Set the iface either to dormant or to carrier-down as soon as interruption of service is detected. * It is acceptable to gate this behind a small timeout (separate from the connection timeout) for network technologies where service is commonly intermittent. * If the technology also handles IP assignment, ensure those IP addresses are :ref:`assigned to the iface <net_if_interface_ip_management>`. .. note:: iface state updates do not necessarily need to be performed directly by connectivity implementations. For instance: * IP assignment is not necessary if :ref:`DHCP <dhcpv4_interface>` is used for the iface. * The connectivity implementation does not need to update iface dormancy if the underlying :ref:`L2 implementation <net_l2_interface>` already does so. .. _conn_mgr_impl_guidelines_iface_state_writeonly: *Do not use iface state as implementation state* ------------------------------------------------ Zephyr ifaces may be accessed from other threads without respecting the binding mutex. As such, Zephyr iface state may change unpredictably during connectivity implementation callbacks. Therefore, do not base implementation behaviors on iface state. Keep iface state updated to reflect network availability, but do not read iface state for any purpose. If you need to keep track of dormancy or IP assignment, use a separate state variable stored in the :ref:`context pointer <conn_mgr_impl_ctx>`. .. _conn_mgr_impl_guidelines_non_interference: *Remain non-interferent* ------------------------ Connectivity implementations should not prevent applications from interacting directly with associated technology-specific APIs. In other words, it should be possible for an application to directly use your underlying technology without breaking your connectivity implementation. If exceptions to this are absolutely necessary, they should be constrained to specific API calls and should be documented. .. note:: While connectivity implementations must not break, it is acceptable for implementations to have potentially unexpected behavior if applications attempt to directly control the association state. For instance, if an application directly instructs an underlying technology to disassociate, it would be acceptable for the connectivity implementation to interpret this as an unexpected connection loss and immediately attempt to re-associate. .. _conn_mgr_impl_guidelines_non_blocking: *Remain non-blocking* --------------------- All connectivity implementation callbacks should be non-blocking. For instance, calls to :c:member:`conn_mgr_conn_api.connect` should initiate a connection process and return immediately. One exception is :c:member:`conn_mgr_conn_api.init`, whose implementations are permitted to block. However, bear in mind that blocking during this callback will delay system init, so still consider offloading time-consuming tasks to a background thread. .. _conn_mgr_impl_guidelines_immediate_api_readiness: *Make API immediately ready* ---------------------------- Connectivity implementations must be ready to receive API calls immediately after :c:member:`conn_mgr_conn_api.init`. For instance, a call to :c:member:`conn_mgr_conn_api.connect` must eventually lead to an association attempt, even if called immediately after :c:member:`conn_mgr_conn_api.init`. If the underlying technology cannot be made ready for connect commands immediately when :c:member:`conn_mgr_conn_api.init` is called, calls to :c:member:`conn_mgr_conn_api.connect` must be queued in a non-blocking fashion, and then executed later when ready. .. _conn_mgr_impl_guidelines_context_pointer: *Do not store state information outside the context pointer* ------------------------------------------------------------ Connection Manager provides a context pointer to each binding. Connectivity implementations should store all state information in this context pointer. The only exception is connectivity implementations that are meant to be bound to only a single iface. Such implementations may use statically declared state instead. See also :ref:`conn_mgr_impl_guidelines_no_instancing`. .. _conn_mgr_impl_guidelines_iface_access: *Access ifaces only through binding structs* -------------------------------------------- Do not use statically declared ifaces or externally acquire references to ifaces. For example, do not use :c:func:`net_if_get_default` under the assumption that the bound iface will be the default iface. Instead, always use the :c:member:`iface pointer <conn_mgr_conn_binding.iface>` provided by the relevant :c:struct:`binding struct <conn_mgr_conn_binding>`. See also :ref:`conn_mgr_impl_guidelines_binding_access`. .. _conn_mgr_impl_guidelines_bindings_optional: *Make implementations optional at compile-time* ----------------------------------------------- Connectivity implementations should provide a Kconfig option to enable or disable the implementation without affecting bound iface availability. In other words, it should be possible to configure builds that include Connectivity Manager, as well as the iface that would have been bound to the implementation, but not the implementation itself, nor its binding. .. _conn_mgr_impl_guidelines_no_instancing: *Do not instance implementations* --------------------------------- Do not declare a separate connectivity implementation for every iface you are going to bind to. Instead, bind one global connectivity implementation to all of your ifaces, and use the context pointer to store state relevant to individual ifaces. See also :ref:`conn_mgr_impl_guidelines_binding_access` and :ref:`conn_mgr_impl_guidelines_iface_access`. .. _conn_mgr_impl_guidelines_binding_access: *Do not access bindings without locking them* --------------------------------------------- Bindings may be accessed and modified at random by multiple threads, so modifying or reading from a binding without first :c:func:`locking it <conn_mgr_binding_lock>` may lead to unpredictable behavior. This applies to all descendents of the binding, including anything in the :ref:`context container <conn_mgr_impl_ctx>`. Make sure to :c:func:`unlock <conn_mgr_binding_unlock>` the binding when you are done accessing it. .. note:: A possible exception to this rule is if the resource in question is inherently thread-safe. However, be careful taking advantage of this exception. It may still be possible to create a race condition, for instance when accessing multiple thread-safe resources simultaneously. Therefore, it is recommended to simply always lock the binding, whether or not the resource being accessed is inherently thread-safe. .. _conn_mgr_impl_guidelines_support_builtins: *Do not disable built-in features* ---------------------------------- Do not attempt to prevent the use of built-in features (such as :ref:`conn_mgr_control_persistence_timeouts` or :ref:`conn_mgr_control_automations`). All connectivity implementations must fully support these features. Implementations must not attempt to force certain features to be always enabled or always disabled. .. _conn_mgr_impl_guidelines_trigger_events: *Trigger connectivity control events* ------------------------------------- Connectivity control :ref:`network management <net_mgmt_interface>` events are not triggered automatically by Connection Manager. Connectivity implementations must trigger these events themselves. Trigger :c:macro:`NET_EVENT_CONN_CMD_IF_TIMEOUT` when a connection :ref:`timeout <conn_mgr_control_timeouts>` occurs. See :ref:`conn_mgr_control_events_timeout` for details. Trigger :c:macro:`NET_EVENT_CONN_IF_FATAL_ERROR` when a fatal (non-recoverable) connection error occurs. See :ref:`conn_mgr_control_events_fatal_error` for details. See :ref:`net_mgmt_interface` for details on firing network management events. .. _conn_mgr_impl_timeout_persistence: Implementing timeouts and persistence ===================================== First, see :ref:`conn_mgr_control_persistence_timeouts` for a high-level description of the expected behavior of timeouts and persistence. Connectivity implementations must fully conform to that description, regardless of the behavior of the underlying connectivity technology. Sometimes this means writing extra logic in the connectivity implementation to fake certain behaviors. The following sections discuss various common edge-cases and nuances and how to handle them. .. _conn_mgr_impl_tp_inherent_persistence: *Inherently persistent technologies* ------------------------------------ If the underlying technology automatically attempts to reconnect or retry connection after connection loss or failure, the connectivity implementation must manually cancel such attempts when they are in conflict with timeout or persistence settings. For example: * If the underlying technology automatically attempts to reconnect after losing connection, and persistence is disabled for the iface, the connectivity implementation should immediately cancel this reconnection attempt. * If a connection attempt times out on an iface whose underlying technology does not have a built-in timeout, the connectivity implementation must simulate a timeout by cancelling the connection attempt manually. .. _conn_mgr_impl_tp_inherent_nonpersistence: *Technologiess that give up on connection attempts* --------------------------------------------------- If the underlying technology has no mechanism to retry connection attempts, or would give up on them before the user-configured timeout, or would not reconnect after connection loss, the connectivity implementation must manually re-request connection to counteract these deviances. * If your underlying technology is not persistent, you must manually trigger reconnect attempts when persistence is enabled. * If your underlying technology does not support a timeout, you must manually cancel connection attempts if the timeout is enabled. * If your underlying technology forces a timeout, you must manually trigger a new connection attempts if that timeout is shorter than the Connection Manager timeout. .. _conn_mgr_impl_tp_assoc_retry: *Technologies with association retry* ------------------------------------- Many underlying technologies do not usually associate in a single attempt. Instead, these underlying technologies may need to make multiple back-to-back association attempts in a row, usually with a small delay. In these situations, the connectivity implementation should treat this series of back-to-back association sub-attempts as a single unified connection attempt. For instance, after a sub-attempt failure, persistence being disabled should not prevent further sub-attempts, since they all count as one single overall connection attempt. See also :ref:`conn_mgr_impl_tp_persistence_during_connect`. At which point a series of failed sub-attempts should be considered a failure of the connection attempt as a whole is up to each implementation to decide. If the connection attempt crosses this threshold, but the configured timeout has not yet elapsed, or there is no timeout, sub-attempts should continue. .. _conn_mgr_impl_tp_persistence_during_connect: *Persistence during connection attempts* ---------------------------------------- Persistence should not affect any aspect of implementation behavior during a connection attempt. Persistence should only affect whether or not connection attempts are automatically triggered after a connection loss. The configured timeout should fully determine whether connection retry should be performed. .. _conn_mgr_impl_api: Implementation API ================== Include header file :file:`include/zephyr/net/conn_mgr_connectivity_impl.h` to access these. Only for use by connectivity implementations. .. doxygengroup:: conn_mgr_connectivity_impl ```
/content/code_sandbox/doc/connectivity/networking/conn_mgr/implementation.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
4,349
```unknown <mxfile host="Electron" modified="2023-08-28T23:41:19.284Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/21.6.8 Chrome/114.0.5735.289 Electron/25.5.0 Safari/537.36" etag="LLGj6geb5OPwGWt5pcNY" version="21.6.8" type="device"> <diagram id="W1R5wPltpbE_ZV7s-k6x" name="Page-1"> <mxGraphModel dx="1050" dy="1027" grid="0" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="0" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0"> <root> <mxCell id="0" /> <mxCell id="1" parent="0" /> <mxCell id="Db8zi3n4dXzB52SZQf6J-169" value="" style="rounded=0;whiteSpace=wrap;html=1;dashed=1;fontSize=16;fillColor=none;movable=1;resizable=1;rotatable=1;deletable=1;editable=1;locked=0;connectable=1;strokeColor=default;" parent="1" vertex="1"> <mxGeometry x="527" y="-207" width="195" height="261" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-10" value="&lt;div&gt;network&lt;/div&gt;&lt;div&gt;readiness&lt;/div&gt;&lt;div&gt;events&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="574" y="-81" width="164" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-11" value="&lt;div&gt;Application&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="271" y="-122" width="116" height="348" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-61" value="L2" style="rounded=0;whiteSpace=wrap;html=1;" parent="1" vertex="1"> <mxGeometry x="714" y="173" width="108" height="51" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-71" value="&lt;div&gt;connectivity&lt;/div&gt;&lt;div&gt;commands&lt;br&gt;&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="584" y="22" width="164" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-89" value="&lt;div&gt;iface commands&lt;/div&gt;&lt;div&gt;and events&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="596" y="128" width="164" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-113" value="&lt;div&gt;iface commands&lt;/div&gt;&lt;div&gt;and events&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="397" y="208" width="164" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-155" style="edgeStyle=orthogonalEdgeStyle;rounded=0;comic=0;sketch=0;jumpStyle=none;jumpSize=23;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;strokeColor=default;fontSize=16;startArrow=none;startFill=0;endArrow=classic;endFill=1;fillColor=#CCE5FF;elbow=vertical;" parent="1" source="Db8zi3n4dXzB52SZQf6J-122" target="Db8zi3n4dXzB52SZQf6J-150" edge="1"> <mxGeometry relative="1" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-122" value="Connectivity Control" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="552" y="-35" width="147" height="50" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-129" style="edgeStyle=orthogonalEdgeStyle;rounded=0;comic=0;sketch=0;jumpStyle=sharp;jumpSize=23;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.484;entryY=-0.006;entryDx=0;entryDy=0;strokeColor=default;startArrow=none;startFill=0;endArrow=classic;endFill=1;fillColor=default;elbow=vertical;entryPerimeter=0;" parent="1" source="Db8zi3n4dXzB52SZQf6J-124" target="Db8zi3n4dXzB52SZQf6J-122" edge="1"> <mxGeometry relative="1" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-124" value="Connectivity Monitoring" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="549" y="-148" width="147" height="50" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-135" value="&lt;div&gt;network&lt;/div&gt;&lt;div&gt;commands&lt;br&gt;&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="341" y="-8" width="164" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-136" style="edgeStyle=orthogonalEdgeStyle;rounded=0;comic=0;sketch=0;jumpStyle=none;jumpSize=23;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;strokeColor=default;startArrow=none;startFill=0;endArrow=classic;endFill=1;fillColor=#CCE5FF;elbow=vertical;noJump=0;" parent="1" source="Db8zi3n4dXzB52SZQf6J-124" edge="1"> <mxGeometry relative="1" as="geometry"> <mxPoint x="386" y="-59" as="targetPoint" /> <Array as="points"> <mxPoint x="622" y="-59" /> <mxPoint x="401" y="-59" /> </Array> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-139" value="&lt;font style=&quot;font-size: 16px;&quot;&gt;Connection Manager&lt;br&gt;&lt;/font&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;dashed=1;" parent="1" vertex="1"> <mxGeometry x="543" y="-198" width="171" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-141" style="edgeStyle=orthogonalEdgeStyle;rounded=0;comic=0;sketch=0;jumpStyle=none;jumpSize=23;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.004;exitY=0.631;exitDx=0;exitDy=0;entryX=1.017;entryY=0.937;entryDx=0;entryDy=0;entryPerimeter=0;strokeColor=default;fontSize=16;startArrow=classic;startFill=1;endArrow=classic;endFill=1;fillColor=#CCE5FF;elbow=vertical;exitPerimeter=0;" parent="1" source="Db8zi3n4dXzB52SZQf6J-144" target="Db8zi3n4dXzB52SZQf6J-11" edge="1"> <mxGeometry relative="1" as="geometry"> <mxPoint x="547" y="191.75" as="sourcePoint" /> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-166" style="edgeStyle=orthogonalEdgeStyle;rounded=0;comic=0;sketch=0;jumpStyle=none;jumpSize=23;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0.25;exitDx=0;exitDy=0;entryX=0;entryY=0.25;entryDx=0;entryDy=0;strokeColor=default;fontSize=16;startArrow=none;startFill=0;endArrow=classic;endFill=1;fillColor=#CCE5FF;elbow=vertical;" parent="1" source="Db8zi3n4dXzB52SZQf6J-144" target="Db8zi3n4dXzB52SZQf6J-124" edge="1"> <mxGeometry relative="1" as="geometry"> <Array as="points"> <mxPoint x="468" y="186" /> <mxPoint x="468" y="-135" /> </Array> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-144" value="&lt;div&gt;Zephyr ifaces&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="552" y="173" width="147" height="50" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-158" style="edgeStyle=orthogonalEdgeStyle;rounded=0;comic=0;sketch=0;jumpStyle=none;jumpSize=23;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;strokeColor=default;fontSize=16;startArrow=classic;startFill=1;endArrow=classic;endFill=1;fillColor=#CCE5FF;elbow=vertical;" parent="1" source="Db8zi3n4dXzB52SZQf6J-150" target="Db8zi3n4dXzB52SZQf6J-144" edge="1"> <mxGeometry relative="1" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-161" style="edgeStyle=orthogonalEdgeStyle;rounded=0;comic=0;sketch=0;jumpStyle=none;jumpSize=23;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.999;exitY=0.676;exitDx=0;exitDy=0;strokeColor=default;fontSize=16;startArrow=classic;startFill=1;endArrow=classic;endFill=1;fillColor=#CCE5FF;elbow=vertical;exitPerimeter=0;" parent="1" source="Db8zi3n4dXzB52SZQf6J-150" target="Db8zi3n4dXzB52SZQf6J-61" edge="1"> <mxGeometry relative="1" as="geometry"> <Array as="points"> <mxPoint x="700" y="103" /> <mxPoint x="768" y="102" /> </Array> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-150" value="Connectivity Implementations" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="552" y="69" width="147" height="50" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-153" value="" style="endArrow=classic;html=1;rounded=0;comic=0;sketch=0;strokeColor=default;fontSize=16;fillColor=#CCE5FF;elbow=vertical;jumpStyle=none;jumpSize=23;entryX=0;entryY=0.5;entryDx=0;entryDy=0;exitX=0.991;exitY=0.322;exitDx=0;exitDy=0;exitPerimeter=0;" parent="1" source="Db8zi3n4dXzB52SZQf6J-11" target="Db8zi3n4dXzB52SZQf6J-122" edge="1"> <mxGeometry width="50" height="50" relative="1" as="geometry"> <mxPoint x="413" y="18" as="sourcePoint" /> <mxPoint x="463" y="-32" as="targetPoint" /> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-162" value="&lt;div&gt;connectivity&lt;/div&gt;&lt;div&gt;commands&lt;/div&gt;&lt;div&gt;and events&lt;br&gt;&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="725" y="128" width="164" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-167" value="&lt;div&gt;iface events&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="426" y="162" width="164" height="30" as="geometry" /> </mxCell> </root> </mxGraphModel> </diagram> </mxfile> ```
/content/code_sandbox/doc/connectivity/networking/conn_mgr/figures/integration_diagram_simplified.drawio
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,954
```restructuredtext .. _can_isotp: ISO-TP Transport Protocol ######################### .. contents:: :local: :depth: 2 Overview ******** ISO-TP is a transport protocol defined in the ISO-Standard ISO15765-2 Road vehicles - Diagnostic communication over Controller Area Network (DoCAN). Part2: Transport protocol and network layer services. As its name already implies, it is originally designed, and still used in road vehicle diagnostic over Controller Area Networks. Nevertheless, it's not limited to applications in road vehicles or the automotive domain. This transport protocol extends the limited payload data size for classical CAN (8 bytes) and CAN FD (64 bytes) to theoretically four gigabytes. Additionally, it adds a flow control mechanism to influence the sender's behavior. ISO-TP segments packets into small fragments depending on the payload size of the CAN frame. The header of those segments is called Protocol Control Information (PCI). Packets smaller or equal to seven bytes on Classical CAN are called single-frames (SF). They don't need to fragment and do not have any flow-control. Packets larger than that are segmented into a first-frame (FF) and as many consecutive-frames (CF) as required. The FF contains information about the length of the entire payload data and additionally, the first few bytes of payload data. The receiving peer sends back a flow-control-frame (FC) to either deny, postpone, or accept the following consecutive frames. The FC also defines the conditions of sending, namely the block-size (BS) and the minimum separation time between frames (STmin). The block size defines how many CF the sender is allowed to send, before he has to wait for another FC. .. image:: isotp_sequence.svg :width: 20% :align: center :alt: ISO-TP Sequence API Reference ************* .. doxygengroup:: can_isotp ```
/content/code_sandbox/doc/connectivity/canbus/isotp.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
407
```restructuredtext .. _canbus: Controller Area Network (CAN) Bus Protocols ########################################### .. toctree:: :maxdepth: 2 isotp.rst ```
/content/code_sandbox/doc/connectivity/canbus/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
37
```restructuredtext .. _usb: USB ### **USB device support** .. toctree:: :maxdepth: 1 device/usb_device.rst device/api/index.rst **New experimental USB support** .. toctree:: :maxdepth: 1 device_next/usb_device.rst device_next/api/index.rst host/api/index.rst **USB Power Delivery support** .. toctree:: :maxdepth: 1 pd/ucds.rst **Common sections related to USB support** .. toctree:: :maxdepth: 1 api/hid.rst ```
/content/code_sandbox/doc/connectivity/usb/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
139
```unknown <mxfile host="Electron" modified="2023-08-28T23:43:21.842Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/21.6.8 Chrome/114.0.5735.289 Electron/25.5.0 Safari/537.36" etag="tYLSXPfTSRMTc84KCMcT" version="21.6.8" type="device"> <diagram id="W1R5wPltpbE_ZV7s-k6x" name="Page-1"> <mxGraphModel dx="1050" dy="1727" grid="0" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0"> <root> <mxCell id="0" /> <mxCell id="1" parent="0" /> <mxCell id="Db8zi3n4dXzB52SZQf6J-138" value="" style="rounded=0;whiteSpace=wrap;html=1;dashed=1;fillColor=none;" parent="1" vertex="1"> <mxGeometry x="516" y="-192" width="465" height="407" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-30" value="" style="rounded=0;whiteSpace=wrap;html=1;" parent="1" vertex="1"> <mxGeometry x="544" y="260" width="310" height="177" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-10" value="&lt;div&gt;network&lt;/div&gt;&lt;div&gt;readiness&lt;/div&gt;&lt;div&gt;events&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="646" y="-68" width="164" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-11" value="&lt;div&gt;Application&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="285" y="-122" width="116" height="559" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-22" value="&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Zephyr ifaces (bound)&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;dashed=1;" parent="1" vertex="1"> <mxGeometry x="634" y="273" width="208" height="75" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-23" value="iface" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="641" y="289" width="60" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-24" value="iface" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="775" y="289" width="60" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-25" value="iface" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="708" y="289" width="60" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-26" value="&lt;div&gt;Zephyr ifaces (unbound)&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;dashed=1;" parent="1" vertex="1"> <mxGeometry x="634" y="361" width="208" height="70" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-27" value="iface" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="641" y="389" width="60" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-28" value="iface" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="775" y="389" width="60" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-29" value="iface" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="708" y="389" width="60" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-31" value="" style="rounded=0;whiteSpace=wrap;html=1;" parent="1" vertex="1"> <mxGeometry x="549" y="138" width="293" height="61" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-32" value="&lt;div&gt;binding&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="708" y="154" width="60" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-50" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;fillColor=default;strokeColor=default;startArrow=classic;startFill=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" parent="1" source="Db8zi3n4dXzB52SZQf6J-33" target="Db8zi3n4dXzB52SZQf6J-46" edge="1"> <mxGeometry relative="1" as="geometry"> <mxPoint x="880" y="290" as="targetPoint" /> <Array as="points"> <mxPoint x="805" y="131" /> </Array> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-33" value="&lt;div&gt;binding&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="775" y="154" width="60" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-34" value="&lt;div&gt;binding&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="641" y="154" width="60" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-80" style="edgeStyle=orthogonalEdgeStyle;rounded=0;jumpStyle=sharp;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;strokeColor=default;startArrow=classic;startFill=1;fillColor=default;" parent="1" source="Db8zi3n4dXzB52SZQf6J-45" target="Db8zi3n4dXzB52SZQf6J-34" edge="1"> <mxGeometry relative="1" as="geometry"> <Array as="points"> <mxPoint x="671" y="62" /> </Array> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-45" value="&lt;div&gt;Connectivity&lt;/div&gt;&lt;div&gt;Implementation&lt;/div&gt;&lt;div&gt;(LTE)&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;" parent="1" vertex="1"> <mxGeometry x="859" y="32" width="95" height="60" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-79" style="edgeStyle=orthogonalEdgeStyle;rounded=0;jumpStyle=sharp;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0.25;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;strokeColor=default;startArrow=classic;startFill=1;fillColor=default;" parent="1" source="Db8zi3n4dXzB52SZQf6J-46" target="Db8zi3n4dXzB52SZQf6J-32" edge="1"> <mxGeometry relative="1" as="geometry"> <Array as="points"> <mxPoint x="738" y="116" /> </Array> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-46" value="&lt;div&gt;Connectivity&lt;/div&gt;&lt;div&gt;Implementation&lt;/div&gt;&lt;div&gt;(Wi-Fi)&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;" parent="1" vertex="1"> <mxGeometry x="859" y="101" width="95" height="60" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-55" value="&lt;div&gt;Connectivity&lt;/div&gt;&lt;div&gt;Bindings&lt;br&gt;&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="558" y="154" width="60" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-56" value="&lt;div&gt;Zephyr&lt;/div&gt;&lt;div&gt;ifaces&lt;br&gt;&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="563" y="270" width="33" height="36" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-61" value="LTE L2" style="rounded=0;whiteSpace=wrap;html=1;" parent="1" vertex="1"> <mxGeometry x="1009" y="32" width="58" height="60" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-62" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;entryX=0.5;entryY=1;entryDx=0;entryDy=0;strokeColor=default;startArrow=classic;startFill=1;fillColor=default;" parent="1" source="Db8zi3n4dXzB52SZQf6J-23" target="Db8zi3n4dXzB52SZQf6J-34" edge="1"> <mxGeometry relative="1" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-64" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;strokeColor=default;startArrow=classic;startFill=1;fillColor=default;" parent="1" source="Db8zi3n4dXzB52SZQf6J-24" target="Db8zi3n4dXzB52SZQf6J-33" edge="1"> <mxGeometry relative="1" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-63" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;entryX=0.5;entryY=1;entryDx=0;entryDy=0;strokeColor=default;startArrow=classic;startFill=1;fillColor=default;anchorPointDirection=1;" parent="1" source="Db8zi3n4dXzB52SZQf6J-25" target="Db8zi3n4dXzB52SZQf6J-32" edge="1"> <mxGeometry relative="1" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-68" value="" style="shape=flexArrow;endArrow=classic;html=1;rounded=0;strokeColor=#6c8ebf;fillColor=#dae8fc;exitX=0.003;exitY=0.199;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;edgeStyle=orthogonalEdgeStyle;exitPerimeter=0;" parent="1" source="Db8zi3n4dXzB52SZQf6J-30" target="Db8zi3n4dXzB52SZQf6J-124" edge="1"> <mxGeometry width="50" height="50" relative="1" as="geometry"> <mxPoint x="402" y="284" as="sourcePoint" /> <mxPoint x="117.5" y="192.5" as="targetPoint" /> <Array as="points"> <mxPoint x="483" y="295" /> <mxPoint x="483" y="-123" /> </Array> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-71" value="&lt;div&gt;network&lt;/div&gt;&lt;div&gt;commands&lt;br&gt;&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="510" y="68" width="164" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-72" value="&lt;div&gt;iface state&lt;/div&gt;&lt;div&gt;change events&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="420" y="303" width="164" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-74" value="Wi-Fi L2 " style="rounded=0;whiteSpace=wrap;html=1;" parent="1" vertex="1"> <mxGeometry x="1009" y="101.5" width="58" height="60" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-76" value="" style="shape=flexArrow;endArrow=classic;startArrow=classic;html=1;rounded=0;strokeColor=#6c8ebf;fillColor=#dae8fc;entryX=0;entryY=0.5;entryDx=0;entryDy=0;exitX=1;exitY=0.5;exitDx=0;exitDy=0;" parent="1" source="Db8zi3n4dXzB52SZQf6J-45" target="Db8zi3n4dXzB52SZQf6J-61" edge="1"> <mxGeometry width="100" height="100" relative="1" as="geometry"> <mxPoint x="970" y="338.5" as="sourcePoint" /> <mxPoint x="1070" y="238.5" as="targetPoint" /> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-77" value="" style="shape=flexArrow;endArrow=classic;startArrow=classic;html=1;rounded=0;strokeColor=#6c8ebf;fillColor=#dae8fc;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" parent="1" source="Db8zi3n4dXzB52SZQf6J-46" target="Db8zi3n4dXzB52SZQf6J-74" edge="1"> <mxGeometry width="100" height="100" relative="1" as="geometry"> <mxPoint x="1063" y="276.5" as="sourcePoint" /> <mxPoint x="1163" y="176.5" as="targetPoint" /> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-89" value="&lt;div&gt;iface commands and events,&lt;/div&gt;&lt;div&gt;binding state updates,&lt;/div&gt;&lt;div&gt;network commands&lt;br&gt;&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="684" y="72.5" width="164" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-91" value="&lt;div&gt;iface commands&lt;/div&gt;&lt;div&gt;and events&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="544" y="226" width="164" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-113" value="&lt;div&gt;iface commands&lt;/div&gt;&lt;div&gt;and events&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="405" y="395" width="164" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-122" value="Connectivity Control" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="549" y="-8" width="295" height="50" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-129" style="edgeStyle=orthogonalEdgeStyle;rounded=0;comic=0;sketch=0;jumpStyle=sharp;jumpSize=23;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;strokeColor=default;startArrow=none;startFill=0;endArrow=classic;endFill=1;fillColor=default;elbow=vertical;" parent="1" source="Db8zi3n4dXzB52SZQf6J-124" target="Db8zi3n4dXzB52SZQf6J-122" edge="1"> <mxGeometry relative="1" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-124" value="Connectivity Monitoring" style="rounded=0;whiteSpace=wrap;html=1;labelBackgroundColor=none;" parent="1" vertex="1"> <mxGeometry x="549" y="-148" width="295" height="50" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-128" value="" style="shape=flexArrow;endArrow=classic;html=1;rounded=0;comic=0;sketch=0;strokeColor=#6c8ebf;fillColor=#dae8fc;elbow=vertical;jumpStyle=sharp;jumpSize=23;edgeStyle=orthogonalEdgeStyle;entryX=0.285;entryY=0.021;entryDx=0;entryDy=0;entryPerimeter=0;exitX=0.281;exitY=1.003;exitDx=0;exitDy=0;exitPerimeter=0;" parent="1" source="Db8zi3n4dXzB52SZQf6J-122" target="Db8zi3n4dXzB52SZQf6J-31" edge="1"> <mxGeometry width="50" height="50" relative="1" as="geometry"> <mxPoint x="589" y="41" as="sourcePoint" /> <mxPoint x="591" y="140" as="targetPoint" /> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-131" value="" style="shape=flexArrow;endArrow=classic;html=1;rounded=0;strokeColor=#6c8ebf;fillColor=#dae8fc;exitX=0.003;exitY=0.199;exitDx=0;exitDy=0;edgeStyle=orthogonalEdgeStyle;exitPerimeter=0;" parent="1" target="Db8zi3n4dXzB52SZQf6J-11" edge="1"> <mxGeometry width="50" height="50" relative="1" as="geometry"> <mxPoint x="545.93" y="295.22299999999996" as="sourcePoint" /> <mxPoint x="416" y="-123" as="targetPoint" /> <Array as="points"> <mxPoint x="483" y="295" /> <mxPoint x="483" y="-101" /> </Array> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-132" value="" style="endArrow=classic;html=1;rounded=0;comic=0;sketch=0;strokeColor=default;fillColor=#CCE5FF;elbow=vertical;jumpStyle=sharp;jumpSize=23;edgeStyle=orthogonalEdgeStyle;entryX=0;entryY=0.5;entryDx=0;entryDy=0;startArrow=classic;startFill=1;exitX=1.002;exitY=0.906;exitDx=0;exitDy=0;exitPerimeter=0;" parent="1" source="Db8zi3n4dXzB52SZQf6J-11" target="Db8zi3n4dXzB52SZQf6J-23" edge="1"> <mxGeometry width="50" height="50" relative="1" as="geometry"> <mxPoint x="421" y="380" as="sourcePoint" /> <mxPoint x="515" y="376" as="targetPoint" /> <Array as="points"> <mxPoint x="406" y="385" /> <mxPoint x="606" y="384" /> <mxPoint x="606" y="304" /> </Array> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-133" value="" style="endArrow=classic;html=1;rounded=0;comic=0;sketch=0;strokeColor=default;fillColor=#CCE5FF;elbow=vertical;jumpStyle=sharp;jumpSize=23;edgeStyle=orthogonalEdgeStyle;entryX=0;entryY=0.5;entryDx=0;entryDy=0;exitX=1;exitY=0.922;exitDx=0;exitDy=0;exitPerimeter=0;startArrow=classic;startFill=1;" parent="1" source="Db8zi3n4dXzB52SZQf6J-11" target="Db8zi3n4dXzB52SZQf6J-27" edge="1"> <mxGeometry width="50" height="50" relative="1" as="geometry"> <mxPoint x="428.0440000000001" y="393.7649999999999" as="sourcePoint" /> <mxPoint x="651" y="314" as="targetPoint" /> <Array as="points"> <mxPoint x="607" y="393" /> <mxPoint x="607" y="404" /> </Array> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-134" value="" style="shape=flexArrow;endArrow=classic;html=1;rounded=0;comic=0;sketch=0;strokeColor=#6c8ebf;fillColor=#dae8fc;elbow=vertical;jumpStyle=sharp;jumpSize=23;entryX=0;entryY=0.5;entryDx=0;entryDy=0;exitX=1;exitY=0.25;exitDx=0;exitDy=0;" parent="1" source="Db8zi3n4dXzB52SZQf6J-11" target="Db8zi3n4dXzB52SZQf6J-122" edge="1"> <mxGeometry width="50" height="50" relative="1" as="geometry"> <mxPoint x="432" y="61" as="sourcePoint" /> <mxPoint x="482" y="11" as="targetPoint" /> </mxGeometry> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-135" value="&lt;div&gt;network&lt;/div&gt;&lt;div&gt;commands&lt;br&gt;&lt;/div&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"> <mxGeometry x="351" y="22" width="164" height="30" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-136" style="edgeStyle=orthogonalEdgeStyle;rounded=0;comic=0;sketch=0;jumpStyle=none;jumpSize=23;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.987;entryY=0.142;entryDx=0;entryDy=0;entryPerimeter=0;strokeColor=default;startArrow=none;startFill=0;endArrow=classic;endFill=1;fillColor=#CCE5FF;elbow=vertical;noJump=0;" parent="1" source="Db8zi3n4dXzB52SZQf6J-124" target="Db8zi3n4dXzB52SZQf6J-11" edge="1"> <mxGeometry relative="1" as="geometry" /> </mxCell> <mxCell id="Db8zi3n4dXzB52SZQf6J-139" value="&lt;font style=&quot;font-size: 16px;&quot;&gt;Connection Manager&lt;br&gt;&lt;/font&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;dashed=1;" parent="1" vertex="1"> <mxGeometry x="664" y="-194" width="171" height="30" as="geometry" /> </mxCell> </root> </mxGraphModel> </diagram> </mxfile> ```
/content/code_sandbox/doc/connectivity/networking/conn_mgr/figures/integration_diagram_detailed.drawio
unknown
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
7,528
```restructuredtext .. _usb_dc_api: USB device controller driver API ################################ The USB device controller driver API is described in :zephyr_file:`include/zephyr/drivers/usb/usb_dc.h` and sometimes referred to as the ``usb_dc`` API. This API has some limitations by design, it does not follow :ref:`device_model_api` and is being replaced by :ref:`udc_api`. API reference ************* .. doxygengroup:: _usb_device_controller_api ```
/content/code_sandbox/doc/connectivity/usb/device/api/usb_dc.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
105
```restructuredtext .. _usb_api: USB device support APIs ####################### .. toctree:: :maxdepth: 1 usb_dc.rst usb_device.rst usb_device_hid.rst usb_device_bos.rst ```
/content/code_sandbox/doc/connectivity/usb/device/api/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
54
```restructuredtext .. _usb_bos_api: Binary Device Object Store (BOS) support API ############################################ API reference ************* .. doxygengroup:: usb_bos ```
/content/code_sandbox/doc/connectivity/usb/device/api/usb_device_bos.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
38
```restructuredtext .. _usb_device_stack_api: USB device stack API #################### API reference ************* There are two ways to transmit data, using the 'low' level read/write API or the 'high' level transfer API. Low level API To transmit data to the host, the class driver should call usb_write(). Upon completion the registered endpoint callback will be called. Before sending another packet the class driver should wait for the completion of the previous write. When data is received, the registered endpoint callback is called. usb_read() should be used for retrieving the received data. For CDC ACM sample driver this happens via the OUT bulk endpoint handler (cdc_acm_bulk_out) mentioned in the endpoint array (cdc_acm_ep_data). High level API The usb_transfer method can be used to transfer data to/from the host. The transfer API will automatically split the data transmission into one or more USB transaction(s), depending endpoint max packet size. The class driver does not have to implement endpoint callback and should set this callback to the generic usb_transfer_ep_callback. .. doxygengroup:: _usb_device_core_api ```
/content/code_sandbox/doc/connectivity/usb/device/api/usb_device.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
248
```restructuredtext .. _usb_hid_device: USB HID Class API ################# USB device specific part for HID support defined in :zephyr_file:`include/zephyr/usb/class/usb_hid.h`. API Reference ************* .. doxygengroup:: usb_hid_device_api ```
/content/code_sandbox/doc/connectivity/usb/device/api/usb_device_hid.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
59
```restructuredtext .. _usbc_api: USB-C device stack ################## The USB-C device stack is a hardware independent interface between a Type-C Port Controller (TCPC) and customer applications. It is a port of the Google ChromeOS Type-C Port Manager (TCPM) stack. It provides the following functionalities: * Uses the APIs provided by the Type-C Port Controller drivers to interact with the Type-C Port Controller. * Provides a programming interface that's used by a customer applications. The APIs is described in :zephyr_file:`include/zephyr/usb_c/usbc.h` Currently the device stack supports implementation of Sink only and Source only devices. Dual Role Power (DRP) devices are not yet supported. :ref:`List<usbc-samples>` of samples for different purposes. Implementing a Sink Type-C and Power Delivery USB-C device ********************************************************** The configuration of a USB-C Device is done in the stack layer and devicetree. The following devicetree, structures and callbacks need to be defined: * Devicetree usb-c-connector node referencing a TCPC * Devicetree vbus node referencing a VBUS measurement device * User defined structure that encapsulates application specific data * Policy callbacks For example, for the Sample USB-C Sink application: Each Physical Type-C port is represented in the devicetree by a usb-c-connector compatible node: .. literalinclude:: ../../../../samples/subsys/usb_c/sink/boards/b_g474e_dpow1.overlay :language: dts :start-after: usbc.rst usbc-port start :end-before: usbc.rst usbc-port end :linenos: VBUS is measured by a device that's referenced in the devicetree by a usb-c-vbus-adc compatible node: .. literalinclude:: ../../../../samples/subsys/usb_c/sink/boards/b_g474e_dpow1.overlay :language: dts :start-after: usbc.rst vbus-voltage-divider-adc start :end-before: usbc.rst vbus-voltage-divider-adc end :linenos: A user defined structure is defined and later registered with the subsystem and can be accessed from callback through an API: .. literalinclude:: ../../../../samples/subsys/usb_c/sink/src/main.c :language: c :start-after: usbc.rst port data object start :end-before: usbc.rst port data object end :linenos: These callbacks are used by the subsystem to set or get application specific data: .. literalinclude:: ../../../../samples/subsys/usb_c/sink/src/main.c :language: c :start-after: usbc.rst callbacks start :end-before: usbc.rst callbacks end :linenos: This callback is used by the subsystem to query if a certain action can be taken: .. literalinclude:: ../../../../samples/subsys/usb_c/sink/src/main.c :language: c :start-after: usbc.rst check start :end-before: usbc.rst check end :linenos: This callback is used by the subsystem to notify the application of an event: .. literalinclude:: ../../../../samples/subsys/usb_c/sink/src/main.c :language: c :start-after: usbc.rst notify start :end-before: usbc.rst notify end :linenos: Registering the callbacks: .. literalinclude:: ../../../../samples/subsys/usb_c/sink/src/main.c :language: c :start-after: usbc.rst register start :end-before: usbc.rst register end :linenos: Register the user defined structure: .. literalinclude:: ../../../../samples/subsys/usb_c/sink/src/main.c :language: c :start-after: usbc.rst user data start :end-before: usbc.rst user data end :linenos: Start the USB-C subsystem: .. literalinclude:: ../../../../samples/subsys/usb_c/sink/src/main.c :language: c :start-after: usbc.rst usbc start :end-before: usbc.rst usbc end :linenos: Implementing a Source Type-C and Power Delivery USB-C device ************************************************************ The configuration of a USB-C Device is done in the stack layer and devicetree. Define the following devicetree, structures and callbacks: * Devicetree ``usb-c-connector`` node referencing a TCPC * Devicetree ``vbus`` node referencing a VBUS measurement device * User defined structure that encapsulates application specific data * Policy callbacks For example, for the Sample USB-C Source application: Each Physical Type-C port is represented in the devicetree by a ``usb-c-connector`` compatible node: .. literalinclude:: ../../../../samples/subsys/usb_c/source/boards/stm32g081b_eval.overlay :language: dts :start-after: usbc.rst usbc-port start :end-before: usbc.rst usbc-port end :linenos: VBUS is measured by a device that's referenced in the devicetree by a ``usb-c-vbus-adc`` compatible node: .. literalinclude:: ../../../../samples/subsys/usb_c/source/boards/stm32g081b_eval.overlay :language: dts :start-after: usbc.rst vbus-voltage-divider-adc start :end-before: usbc.rst vbus-voltage-divider-adc end :linenos: A user defined structure is defined and later registered with the subsystem and can be accessed from callback through an API: .. literalinclude:: ../../../../samples/subsys/usb_c/source/src/main.c :language: c :start-after: usbc.rst port data object start :end-before: usbc.rst port data object end :linenos: These callbacks are used by the subsystem to set or get application specific data: .. literalinclude:: ../../../../samples/subsys/usb_c/source/src/main.c :language: c :start-after: usbc.rst callbacks start :end-before: usbc.rst callbacks end :linenos: This callback is used by the subsystem to query if a certain action can be taken: .. literalinclude:: ../../../../samples/subsys/usb_c/source/src/main.c :language: c :start-after: usbc.rst check start :end-before: usbc.rst check end :linenos: This callback is used by the subsystem to notify the application of an event: .. literalinclude:: ../../../../samples/subsys/usb_c/source/src/main.c :language: c :start-after: usbc.rst notify start :end-before: usbc.rst notify end :linenos: Registering the callbacks: .. literalinclude:: ../../../../samples/subsys/usb_c/source/src/main.c :language: c :start-after: usbc.rst register start :end-before: usbc.rst register end :linenos: Register the user defined structure: .. literalinclude:: ../../../../samples/subsys/usb_c/source/src/main.c :language: c :start-after: usbc.rst user data start :end-before: usbc.rst user data end :linenos: Start the USB-C subsystem: .. literalinclude:: ../../../../samples/subsys/usb_c/source/src/main.c :language: c :start-after: usbc.rst usbc start :end-before: usbc.rst usbc end :linenos: API reference ************* .. doxygengroup:: _usbc_device_api SINK callback reference *********************** .. doxygengroup:: sink_callbacks SOURCE callback reference ************************* .. doxygengroup:: source_callbacks ```
/content/code_sandbox/doc/connectivity/usb/pd/ucds.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,738
```restructuredtext .. _usb_device_stack: USB device support ################## .. contents:: :local: :depth: 3 Overview ******** The USB device stack is a hardware independent interface between USB device controller driver and USB device class drivers or customer applications. It is a port of the LPCUSB device stack and has been modified and expanded over time. It provides the following functionalities: * Uses the :ref:`usb_dc_api` provided by the device controller drivers to interact with the USB device controller. * Responds to standard device requests and returns standard descriptors, essentially handling 'Chapter 9' processing, specifically the standard device requests in table 9-3 from the universal serial bus specification revision 2.0. * Provides a programming interface to be used by USB device classes or customer applications. The APIs is described in :zephyr_file:`include/zephyr/usb/usb_device.h` .. note:: It is planned to deprecate all APIs listed in :ref:`usb_api` and the functions that depend on them between Zephyr v3.7.0 and v4.0.0, and remove them in v4.2.0. The new USB device support, represented by the APIs in :ref:`usb_device_next_api`, will become the default in Zephyr v4.0.0. Supported USB classes ********************* Audio ===== There is an experimental implementation of the Audio class. It follows specification version 1.00 (``bcdADC 0x0100``) and supports synchronous synchronisation type only. See :zephyr:code-sample:`usb-audio-headphones-microphone` and :zephyr:code-sample:`usb-audio-headset` samples for reference. Bluetooth HCI USB transport layer ================================= Bluetooth HCI USB transport layer implementation uses :ref:`bt_hci_raw` to expose HCI interface to the host. It is not fully in line with the description in the Bluetooth specification and consists only of an interface with the endpoint configuration: * HCI commands through control endpoint (host-to-device only) * HCI events through interrupt IN endpoint * ACL data through one bulk IN and one bulk OUT endpoints A second interface for the voice channels has not been implemented as there is no support for this type in :ref:`bluetooth`. It is not a big problem under Linux if HCI USB transport layer is the only interface that appears in the configuration, the btusb driver would not try to claim a second (isochronous) interface. The consequence is that if HCI USB is used in a composite configuration and is the first interface, then the Linux btusb driver will claim both the first and the next interface, preventing other composite functions from working. Because of this problem, HCI USB should not be used in a composite configuration. This problem is fixed in the implementation for new USB support. See :ref:`bluetooth-hci-usb-sample` sample for reference. .. _usb_device_cdc_acm: CDC ACM ======= The CDC ACM class is used as backend for different subsystems in Zephyr. However, its configuration may not be easy for the inexperienced user. Below is a description of the different use cases and some pitfalls. The interface for CDC ACM user is :ref:`uart_api` driver API. But there are two important differences in behavior to a real UART controller: * Data transfer is only possible after the USB device stack has been initialized and started, until then any data is discarded * If device is connected to the host, it still needs an application on the host side which requests the data * The CDC ACM poll out implementation follows the API and blocks when the TX ring buffer is full only if the hw-flow-control property is enabled and called from a non-ISR context. The devicetree compatible property for CDC ACM UART is :dtcompatible:`zephyr,cdc-acm-uart`. CDC ACM support is automatically selected when USB device support is enabled and a compatible node in the devicetree sources is present. If necessary, CDC ACM support can be explicitly disabled by :kconfig:option:`CONFIG_USB_CDC_ACM`. About four CDC ACM UART instances can be defined and used, limited by the maximum number of supported endpoints on the controller. CDC ACM UART node is supposed to be child of a USB device controller node. Since the designation of the controller nodes varies from vendor to vendor, and our samples and application should be as generic as possible, the default USB device controller is usually assigned an ``zephyr_udc0`` node label. Often, CDC ACM UART is described in a devicetree overlay file and looks like this: .. code-block:: devicetree &zephyr_udc0 { cdc_acm_uart0: cdc_acm_uart0 { compatible = "zephyr,cdc-acm-uart"; label = "CDC_ACM_0"; }; }; Sample :zephyr:code-sample:`usb-cdc-acm` has similar overlay files. And since no special properties are present, it may seem overkill to use devicetree to describe CDC ACM UART. The motivation behind using devicetree is the easy interchangeability of a real UART controller and CDC ACM UART in applications. Console over CDC ACM UART ------------------------- With the CDC ACM UART node from above and ``zephyr,console`` property of the chosen node, we can describe that CDC ACM UART is to be used with the console. A similar overlay file is used by the :zephyr:code-sample:`usb-cdc-acm-console` sample. .. code-block:: devicetree / { chosen { zephyr,console = &cdc_acm_uart0; }; }; &zephyr_udc0 { cdc_acm_uart0: cdc_acm_uart0 { compatible = "zephyr,cdc-acm-uart"; label = "CDC_ACM_0"; }; }; Before the application uses the console, it is recommended to wait for the DTR signal: .. code-block:: c const struct device *const dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_console)); uint32_t dtr = 0; if (usb_enable(NULL)) { return; } while (!dtr) { uart_line_ctrl_get(dev, UART_LINE_CTRL_DTR, &dtr); k_sleep(K_MSEC(100)); } printk("nuqneH\n"); CDC ACM UART as backend ----------------------- As for the console sample, it is possible to configure CDC ACM UART as backend for other subsystems by setting :ref:`devicetree-chosen-nodes` properties. List of few Zephyr specific chosen properties which can be used to select CDC ACM UART as backend for a subsystem or application: * ``zephyr,bt-c2h-uart`` used in Bluetooth, for example see :ref:`bluetooth-hci-uart-sample` * ``zephyr,ot-uart`` used in OpenThread, for example see :zephyr:code-sample:`coprocessor` * ``zephyr,shell-uart`` used by shell for serial backend, for example see :zephyr_file:`samples/subsys/shell/shell_module` * ``zephyr,uart-mcumgr`` used by :zephyr:code-sample:`smp-svr` sample POSIX default tty ECHO mitigation --------------------------------- POSIX systems, like Linux, default to enabling ECHO on tty devices. Host side application can disable ECHO by calling ``open()`` on the tty device and issuing ``ioctl()`` (preferably via ``tcsetattr()``) to disable echo if it is not desired. Unfortunately, there is an inherent race between the ``open()`` and ``ioctl()`` where the ECHO is enabled and any characters received (even if host application does not call ``read()``) will be echoed back. This issue is especially visible when the CDC ACM port is used without any real UART on the other side because there is no arbitrary delay due to baud rate. To mitigate the issue, Zephyr CDC ACM implementation arms IN endpoint with ZLP after device is configured. When the host reads the ZLP, which is pretty much the best indication that host application has opened the tty device, Zephyr will force :kconfig:option:`CONFIG_CDC_ACM_TX_DELAY_MS` millisecond delay before real payload is sent. This should allow sufficient time for first, and only first, application that opens the tty device to disable ECHO if ECHO is not desired. If ECHO is not desired at all from CDC ACM device it is best to set up udev rule to disable ECHO as soon as device is connected. ECHO is particurarly unwanted when CDC ACM instance is used for Zephyr shell, because the control characters to set color sent back to shell are interpreted as (invalid) command and user will see garbage as a result. While minicom does disable ECHO by default, on exit with reset it will restore the termios settings to whatever was set on entry. Therefore, if minicom is the first application to open the tty device, the exit with reset will enable ECHO back and thus set up a problem for the next application (which cannot be mitigated at Zephyr side). To prevent the issue it is recommended either to leave minicom without reset or to disable ECHO before minicom is started. DFU === USB DFU class implementation is tightly coupled to :ref:`dfu` and :ref:`mcuboot_api`. This means that the target platform must support the :ref:`flash_img_api` API. See :zephyr:code-sample:`usb-dfu` sample for reference. USB Human Interface Devices (HID) support ========================================= HID support abuses :ref:`device_model_api` simply to allow applications to use the :c:func:`device_get_binding`. Note that there is no HID device API as such, instead the interface is provided by :c:struct:`hid_ops`. The default instance name is ``HID_n``, where n can be {0, 1, 2, ...} depending on the :kconfig:option:`CONFIG_USB_HID_DEVICE_COUNT`. Each HID instance requires a HID report descriptor. The interface to the core and the report descriptor must be registered using :c:func:`usb_hid_register_device`. As the USB HID specification is not only used by the USB subsystem, the USB HID API reference is split into two parts, :ref:`usb_hid_common` and :ref:`usb_hid_device`. HID helper macros from :ref:`usb_hid_common` should be used to compose a HID report descriptor. Macro names correspond to those used in the USB HID specification. For the HID class interface, an IN interrupt endpoint is required for each instance, an OUT interrupt endpoint is optional. Thus, the minimum implementation requirement for :c:struct:`hid_ops` is to provide ``int_in_ready`` callback. .. code-block:: c #define REPORT_ID 1 static bool configured; static const struct device *hdev; static void int_in_ready_cb(const struct device *dev) { static uint8_t report[2] = {REPORT_ID, 0}; if (hid_int_ep_write(hdev, report, sizeof(report), NULL)) { LOG_ERR("Failed to submit report"); } else { report[1]++; } } static void status_cb(enum usb_dc_status_code status, const uint8_t *param) { if (status == USB_DC_RESET) { configured = false; } if (status == USB_DC_CONFIGURED && !configured) { int_in_ready_cb(hdev); configured = true; } } static const uint8_t hid_report_desc[] = { HID_USAGE_PAGE(HID_USAGE_GEN_DESKTOP), HID_USAGE(HID_USAGE_GEN_DESKTOP_UNDEFINED), HID_COLLECTION(HID_COLLECTION_APPLICATION), HID_LOGICAL_MIN8(0x00), HID_LOGICAL_MAX16(0xFF, 0x00), HID_REPORT_ID(REPORT_ID), HID_REPORT_SIZE(8), HID_REPORT_COUNT(1), HID_USAGE(HID_USAGE_GEN_DESKTOP_UNDEFINED), HID_INPUT(0x02), HID_END_COLLECTION, }; static const struct hid_ops my_ops = { .int_in_ready = int_in_ready_cb, }; int main(void) { int ret; hdev = device_get_binding("HID_0"); if (hdev == NULL) { return -ENODEV; } usb_hid_register_device(hdev, hid_report_desc, sizeof(hid_report_desc), &my_ops); ret = usb_hid_init(hdev); if (ret) { return ret; } return usb_enable(status_cb); } If the application wishes to receive output reports via the OUT interrupt endpoint, it must enable :kconfig:option:`CONFIG_ENABLE_HID_INT_OUT_EP` and provide ``int_out_ready`` callback. The disadvantage of this is that Kconfig options such as :kconfig:option:`CONFIG_ENABLE_HID_INT_OUT_EP` or :kconfig:option:`CONFIG_HID_INTERRUPT_EP_MPS` apply to all instances. This design issue will be fixed in the HID class implementation for the new USB support. See :zephyr:code-sample:`usb-hid-mouse` sample for reference. Mass Storage Class ================== MSC follows Bulk-Only Transport specification and uses :ref:`disk_access_api` to access and expose a RAM disk, emulated block device on a flash partition, or SD Card to the host. Only one disk instance can be exported at a time. The disc to be used by the implementation is set by the :kconfig:option:`CONFIG_MASS_STORAGE_DISK_NAME` and should be the same as the name used by the disc access driver that the application wants to expose to the host. SD card disk drivers use options :kconfig:option:`CONFIG_MMC_VOLUME_NAME` or :kconfig:option:`CONFIG_SDMMC_VOLUME_NAME`, and flash and RAM disk drivers use node property ``disk-name`` to set the disk name. For the emulated block device on a flash partition, the flash partition and flash disk to be used must be described in the devicetree. If a storage partition is already described at the board level, application devicetree overlay must also delete ``storage_partition`` node first. :kconfig:option:`CONFIG_MASS_STORAGE_DISK_NAME` should be the same as ``disk-name`` property. .. code-block:: devicetree /delete-node/ &storage_partition; &mx25r64 { partitions { compatible = "fixed-partitions"; #address-cells = <1>; #size-cells = <1>; storage_partition: partition@0 { label = "storage"; reg = <0x00000000 0x00020000>; }; }; }; / { msc_disk0 { compatible = "zephyr,flash-disk"; partition = <&storage_partition>; disk-name = "NAND"; cache-size = <4096>; }; }; The ``disk-property`` "NAND" may be confusing, but it is simply how some file systems identifies the disc. Therefore, if the application also accesses the file system on the exposed disc, default names should be used, see :zephyr:code-sample:`usb-mass` sample for reference. Networking ========== There are three implementations that work in a similar way, providing a virtual Ethernet connection between the remote (USB host) and Zephyr network support. * CDC ECM class, enabled with :kconfig:option:`CONFIG_USB_DEVICE_NETWORK_ECM` * CDC EEM class, enabled with :kconfig:option:`CONFIG_USB_DEVICE_NETWORK_EEM` * RNDIS support, enabled with :kconfig:option:`CONFIG_USB_DEVICE_NETWORK_RNDIS` See :zephyr:code-sample:`zperf` or :zephyr:code-sample:`socket-dumb-http-server` for reference. Typically, users will need to add a configuration file overlay to the build, such as :zephyr_file:`samples/net/zperf/overlay-netusb.conf`. Applications using RNDIS support should enable :kconfig:option:`CONFIG_USB_DEVICE_OS_DESC` for a better user experience on a host running Microsoft Windows OS. Binary Device Object Store (BOS) support **************************************** BOS handling can be enabled with Kconfig option :kconfig:option:`CONFIG_USB_DEVICE_BOS`. This option also has the effect of changing device descriptor ``bcdUSB`` to ``0210``. The application should register descriptors such as Capability Descriptor using :c:func:`usb_bos_register_cap`. Registered descriptors are added to the root BOS descriptor and handled by the stack. See :zephyr:code-sample:`webusb` sample for reference. Implementing a non-standard USB class ************************************* The configuration of USB device is done in the stack layer. The following structures and callbacks need to be defined: * Part of USB Descriptor table * USB Endpoint configuration table * USB Device configuration structure * Endpoint callbacks * Optionally class, vendor and custom handlers For example, for the USB loopback application: .. literalinclude:: ../../../../subsys/usb/device/class/loopback.c :language: c :start-after: usb.rst config structure start :end-before: usb.rst config structure end :linenos: Endpoint configuration: .. literalinclude:: ../../../../subsys/usb/device/class/loopback.c :language: c :start-after: usb.rst endpoint configuration start :end-before: usb.rst endpoint configuration end :linenos: USB Device configuration structure: .. literalinclude:: ../../../../subsys/usb/device/class/loopback.c :language: c :start-after: usb.rst device config data start :end-before: usb.rst device config data end :linenos: The vendor device requests are forwarded by the USB stack core driver to the class driver through the registered vendor handler. For the loopback class driver, :c:func:`loopback_vendor_handler` processes the vendor requests: .. literalinclude:: ../../../../subsys/usb/device/class/loopback.c :language: c :start-after: usb.rst vendor handler start :end-before: usb.rst vendor handler end :linenos: The class driver waits for the :makevar:`USB_DC_CONFIGURED` device status code before transmitting any data. .. _testing_USB_native_sim: Interface number and endpoint address assignment ************************************************ In USB terminology, a ``function`` is a device that provides a capability to the host, such as a HID class device that implements a keyboard. A function contains a collection of ``interfaces``; at least one interface is required. An interface may contain device ``endpoints``; for example, at least one input endpoint is required to implement a HID class device, and no endpoints are required to implement a USB DFU class. A USB device that combines functions is a multifunction USB device, for example, a combination of a HID class device and a CDC ACM device. With Zephyr RTOS USB support, various combinations are possible with built-in USB classes/functions or custom user implementations. The limitation is the number of available device endpoints. Each device endpoint is uniquely addressable. The endpoint address is a combination of endpoint direction and endpoint number, a four-bit value. Endpoint number zero is used for the default control method to initialize and configure a USB device. By specification, a maximum of ``15 IN`` and ``15 OUT`` device endpoints are also available for use in functions. The actual number depends on the device controller used. Not all controllers support the maximum number of endpoints and all endpoint types. For example, a device controller might support one IN and one OUT isochronous endpoint, but only for endpoint number 8, resulting in endpoint addresses 0x88 and 0x08. Also, one controller may be able to have IN/OUT endpoints on the same endpoint number, interrupt IN endpoint 0x81 and bulk OUT endpoint 0x01, while the other may only be able to handle one endpoint per endpoint number. Information about the number of interfaces, interface associations, endpoint types, and addresses is provided to the host by the interface, interface specific, and endpoint descriptors. Host driver for specific function, uses interface and endpoint descriptor to obtain endpoint addresses, types, and other properties. This allows function host drivers to be generic, for example, a multi-function device consisting of one or more CDC ACM and one or more CDC ECM class implementations is possible and no specific drivers are required. Interface and endpoint descriptors of built-in USB class/function implementations in Zephyr RTOS typically have default interface numbers and endpoint addresses assigned in ascending order. During initialization, default interface numbers may be reassigned based on the number of interfaces in a given configuration. Endpoint addresses are reassigned based on controller capabilities, since certain endpoint combinations are not possible with every controller, and the number of interfaces in a given configuration. This also means that the device side class/function in the Zephyr RTOS must check the actual interface and endpoint descriptor values at runtime. This mechanism also allows as to provide generic samples and generic multifunction samples that are limited only by the resources provided by the controller, such as the number of endpoints and the size of the endpoint FIFOs. There may be host drivers for a specific function, for example in the Linux Kernel, where the function driver does not read interface and endpoint descriptors to check interface numbers or endpoint addresses, but instead uses hardcoded values. Therefore, the host driver cannot be used in a generic way, meaning it cannot be used with different device controllers and different device configurations in combination with other functions. This may also be because the driver is designed for a specific hardware and is not intended to be used with a clone of this specific hardware. On the contrary, if the driver is generic in nature and should work with different hardware variants, then it must not use hardcoded interface numbers and endpoint addresses. It is not possible to disable endpoint reassignment in Zephyr RTOS, which may prevent you from implementing a hardware-clone firmware. Instead, if possible, the host driver implementation should be fixed to use values from the interface and endpoint descriptor. Testing over USPIP in native_sim ******************************** A virtual USB controller implemented through USBIP might be used to test the USB device stack. Follow the general build procedure to build the USB sample for the :ref:`native_sim <native_sim>` configuration. Run built sample with: .. code-block:: console west build -t run In a terminal window, run the following command to list USB devices: .. code-block:: console $ usbip list -r localhost Exportable USB devices ====================== - 127.0.0.1 1-1: unknown vendor : unknown product (2fe3:0100) : /sys/devices/pci0000:00/0000:00:01.2/usb1/1-1 : (Defined at Interface level) (00/00/00) : 0 - Vendor Specific Class / unknown subclass / unknown protocol (ff/00/00) In a terminal window, run the following command to attach the USB device: .. code-block:: console $ sudo usbip attach -r localhost -b 1-1 The USB device should be connected to your Linux host, and verified with the following commands: .. code-block:: console $ sudo usbip port Imported USB devices ==================== Port 00: <Port in Use> at Full Speed(12Mbps) unknown vendor : unknown product (2fe3:0100) 7-1 -> usbip://localhost:3240/1-1 -> remote bus/dev 001/002 $ lsusb -d 2fe3:0100 Bus 007 Device 004: ID 2fe3:0100 USB Vendor and Product identifiers ********************************** The USB Vendor ID for the Zephyr project is ``0x2FE3``. This USB Vendor ID must not be used when a vendor integrates Zephyr USB device support into its own product. Each USB :ref:`sample<usb-samples>` has its own unique Product ID. The USB maintainer, if one is assigned, or otherwise the Zephyr Technical Steering Committee, may allocate other USB Product IDs based on well-motivated and documented requests. The following Product IDs are currently used: +----------------------------------------------------+--------+ | Sample | PID | +====================================================+========+ | :zephyr:code-sample:`usb-cdc-acm` | 0x0001 | +----------------------------------------------------+--------+ | Reserved (previously: usb-cdc-acm-composite) | 0x0002 | +----------------------------------------------------+--------+ | Reserved (previously: usb-hid-cdc) | 0x0003 | +----------------------------------------------------+--------+ | :zephyr:code-sample:`usb-cdc-acm-console` | 0x0004 | +----------------------------------------------------+--------+ | :zephyr:code-sample:`usb-dfu` (Run-Time) | 0x0005 | +----------------------------------------------------+--------+ | Reserved (previously: usb-hid) | 0x0006 | +----------------------------------------------------+--------+ | :zephyr:code-sample:`usb-hid-mouse` | 0x0007 | +----------------------------------------------------+--------+ | :zephyr:code-sample:`usb-mass` | 0x0008 | +----------------------------------------------------+--------+ | :zephyr:code-sample:`testusb-app` | 0x0009 | +----------------------------------------------------+--------+ | :zephyr:code-sample:`webusb` | 0x000A | +----------------------------------------------------+--------+ | :ref:`bluetooth-hci-usb-sample` | 0x000B | +----------------------------------------------------+--------+ | :ref:`bluetooth-hci-usb-h4-sample` | 0x000C | +----------------------------------------------------+--------+ | Reserved (previously: wpan-usb) | 0x000D | +----------------------------------------------------+--------+ | :zephyr:code-sample:`uac2-explicit-feedback` | 0x000E | +----------------------------------------------------+--------+ | :zephyr:code-sample:`usb-dfu` (DFU Mode) | 0xFFFF | +----------------------------------------------------+--------+ The USB device descriptor field ``bcdDevice`` (Device Release Number) represents the Zephyr kernel major and minor versions as a binary coded decimal value. ```
/content/code_sandbox/doc/connectivity/usb/device/usb_device.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
5,816
```restructuredtext .. _usbd_msc_device: USB Mass Storage Class device API ################################# USB Mass Storage Class device API defined in :zephyr_file:`include/zephyr/usb/class/usbd_msc.h`. API Reference ************* .. doxygengroup:: usbd_msc_device ```
/content/code_sandbox/doc/connectivity/usb/device_next/api/usbd_msc_device.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
64
```restructuredtext .. _usb_device_next_api: New USB device support APIs ########################### .. toctree:: :maxdepth: 1 udc.rst usbd.rst usbd_hid_device.rst uac2_device.rst usbd_msc_device.rst ```
/content/code_sandbox/doc/connectivity/usb/device_next/api/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
66
```restructuredtext .. _uac2_device: Audio Class 2 device API ######################## USB Audio Class 2 device specific API defined in :zephyr_file:`include/zephyr/usb/class/usbd_uac2.h`. API Reference ************* .. doxygengroup:: uac2_device ```
/content/code_sandbox/doc/connectivity/usb/device_next/api/uac2_device.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
64
```restructuredtext .. _usbd_hid_device: HID device API ############## HID device specific API defined in :zephyr_file:`include/zephyr/usb/class/usbd_hid.h`. API Reference ************* .. doxygengroup:: usbd_hid_device ```
/content/code_sandbox/doc/connectivity/usb/device_next/api/usbd_hid_device.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
57
```restructuredtext .. _usbd_api: USB device stack (next) API ########################### New USB device stack API is experimental and is subject to change without notice. API reference ************* .. doxygengroup:: usbd_api .. doxygengroup:: usbd_msg_api ```
/content/code_sandbox/doc/connectivity/usb/device_next/api/usbd.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
60
```restructuredtext .. _udc_api: USB device controller (UDC) driver API ###################################### The USB device controller driver API is described in :zephyr_file:`include/zephyr/drivers/usb/udc.h` and referred to as the ``UDC driver`` API. UDC driver API is experimental and is subject to change without notice. It is a replacement for :ref:`usb_dc_api`. If you wish to port an existing driver to UDC driver API, or add a new driver, please use :zephyr_file:`drivers/usb/udc/udc_skeleton.c` as a starting point. API reference ************* .. doxygengroup:: udc_api .. doxygengroup:: udc_buf ```
/content/code_sandbox/doc/connectivity/usb/device_next/api/udc.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
162
```restructuredtext .. _usb_host_api: USB host support APIs ##################### .. toctree:: :maxdepth: 1 uhc.rst ```
/content/code_sandbox/doc/connectivity/usb/host/api/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
34
```restructuredtext .. _usb_device_stack_next: New USB device support ###################### Overview ******** USB device support consists of the USB device controller (UDC) drivers , :ref:`udc_api`, and USB device stack, :ref:`usbd_api`. The :ref:`udc_api` provides a generic and vendor independent interface to USB device controllers, and although, there a is clear separation between these layers, the purpose of :ref:`udc_api` is to serve new Zephyr's USB device stack exclusively. The new device stack supports multiple device controllers, meaning that if a SoC has multiple controllers, they can be used simultaneously. Full and high-speed device controllers are supported. It also provides support for registering multiple function or class instances to a configuration at runtime, or changing the configuration later. It has built-in support for several USB classes and provides an API to implement custom USB functions. The new USB device support is considered experimental and will replace :ref:`usb_device_stack`. Built-in functions ================== The USB device stack has built-in USB functions. Some can be used directly in the user application through a special API, such as HID or Audio class devices, while others use a general Zephyr RTOS driver API, such as MSC and CDC class implementations. The *Identification string* identifies a class or function instance (`n`) and is used as an argument to the :c:func:`usbd_register_class`. +-----------------------------------+-------------------------+-------------------------+ | Class or function | User API (if any) | Identification string | +===================================+=========================+=========================+ | USB Audio 2 class | :ref:`uac2_device` | :samp:`uac2_{n}` | +-----------------------------------+-------------------------+-------------------------+ | USB CDC ACM class | :ref:`uart_api` | :samp:`cdc_acm_{n}` | +-----------------------------------+-------------------------+-------------------------+ | USB CDC ECM class | Ethernet device | :samp:`cdc_ecm_{n}` | +-----------------------------------+-------------------------+-------------------------+ | USB Mass Storage Class (MSC) | :ref:`usbd_msc_device` | :samp:`msc_{n}` | +-----------------------------------+-------------------------+-------------------------+ | USB Human Interface Devices (HID) | :ref:`usbd_hid_device` | :samp:`hid_{n}` | +-----------------------------------+-------------------------+-------------------------+ | Bluetooth HCI USB transport layer | :ref:`bt_hci_raw` | :samp:`bt_hci_{n}` | +-----------------------------------+-------------------------+-------------------------+ Samples ======= * :zephyr:code-sample:`usb-hid-keyboard` * :zephyr:code-sample:`uac2-explicit-feedback` Samples ported to new USB device support ---------------------------------------- To build a sample that supports both the old and new USB device stack, set the configuration ``-DCONF_FILE=usbd_next_prj.conf`` either directly or via ``west``. * :ref:`bluetooth-hci-usb-sample` * :zephyr:code-sample:`usb-cdc-acm` * :zephyr:code-sample:`usb-cdc-acm-console` * :zephyr:code-sample:`usb-mass` * :zephyr:code-sample:`usb-hid-mouse` * :zephyr:code-sample:`zperf` To build the sample for the new device support, set the configuration overlay file ``-DDEXTRA_CONF_FILE=overlay-usbd_next_ecm.conf`` and devicetree overlay file ``-DDTC_OVERLAY_FILE="usbd_next_ecm.overlay`` either directly or via ``west``. How to configure and enable USB device support ********************************************** For the USB device support samples in the Zephyr project repository, we have a common file for instantiation, configuration and initialization, :zephyr_file:`samples/subsys/usb/common/sample_usbd_init.c`. The following code snippets from this file are used as examples. USB Samples Kconfig options used in the USB samples and prefixed with ``SAMPLE_USBD_`` have default values specific to the Zephyr project and the scope is limited to the project samples. In the examples below, you will need to replace these Kconfig options and other defaults with values appropriate for your application or hardware. The USB device stack requires a context structure to manage its properties and runtime data. The preferred way to define a device context is to use the :c:macro:`USBD_DEVICE_DEFINE` macro. This creates a static :c:struct:`usbd_context` variable with a given name. Any number of contexts may be instantiated. A USB controller device can be assigned to multiple contexts, but only one context can be initialized and used at a time. Context properties must not be directly accessed or manipulated by the application. .. literalinclude:: ../../../../samples/subsys/usb/common/sample_usbd_init.c :language: c :dedent: :start-after: doc device instantiation start :end-before: doc device instantiation end Your USB device may have manufacturer, product, and serial number string descriptors. To instantiate these string descriptors, the application should use the appropriate :c:macro:`USBD_DESC_MANUFACTURER_DEFINE`, :c:macro:`USBD_DESC_PRODUCT_DEFINE`, and :c:macro:`USBD_DESC_SERIAL_NUMBER_DEFINE` macros. String descriptors also require a single instantiation of the language descriptor using the :c:macro:`USBD_DESC_LANG_DEFINE` macro. .. literalinclude:: ../../../../samples/subsys/usb/common/sample_usbd_init.c :language: c :dedent: :start-after: doc string instantiation start :end-before: doc string instantiation end String descriptors must be added to the device context at runtime before initializing the USB device with :c:func:`usbd_add_descriptor`. .. literalinclude:: ../../../../samples/subsys/usb/common/sample_usbd_init.c :language: c :dedent: :start-after: doc add string descriptor start :end-before: doc add string descriptor end USB device requires at least one configuration instance per supported speed. The application should use :c:macro:`USBD_CONFIGURATION_DEFINE` to instantiate a configuration. Later, USB device functions are assigned to a configuration. .. literalinclude:: ../../../../samples/subsys/usb/common/sample_usbd_init.c :language: c :dedent: :start-after: doc configuration instantiation start :end-before: doc configuration instantiation end Each configuration instance for a specific speed must be added to the device context at runtime before the USB device is initialized using :c:func:`usbd_add_configuration`. Note :c:enumerator:`USBD_SPEED_FS` and :c:enumerator:`USBD_SPEED_HS`. The first full-speed or high-speed configuration will get ``bConfigurationValue`` one, and then further upward. .. literalinclude:: ../../../../samples/subsys/usb/common/sample_usbd_init.c :language: c :dedent: :start-after: doc configuration register start :end-before: doc configuration register end Although we have already done a lot, this USB device has no function. A device can have multiple configurations with different set of functions at different speeds. A function or class can be registered on a USB device before it is initialized using :c:func:`usbd_register_class`. The desired configuration is specified using :c:enumerator:`USBD_SPEED_FS` or :c:enumerator:`USBD_SPEED_HS` and the configuration number. For simple cases, :c:func:`usbd_register_all_classes` can be used to register all available instances. .. literalinclude:: ../../../../samples/subsys/usb/common/sample_usbd_init.c :language: c :dedent: :start-after: doc functions register start :end-before: doc functions register end The last step in the preparation is to initialize the device with :c:func:`usbd_init`. After this, the configuration of the device cannot be changed. A device can be deinitialized with :c:func:`usbd_shutdown` and all instances can be reused, but the previous steps must be repeated. So it is possible to shutdown a device, register another type of configuration or function, and initialize it again. At the USB controller level, :c:func:`usbd_init` does only what is necessary to detect VBUS changes. There are controller types where the next step is only possible if a VBUS signal is present. A function or class implementation may require its own specific configuration steps, which should be performed prior to initializing the USB device. .. literalinclude:: ../../../../samples/subsys/usb/common/sample_usbd_init.c :language: c :dedent: :start-after: doc device init start :end-before: doc device init end The final step to enable the USB device is :c:func:`usbd_enable`, after that, if the USB device is connected to a USB host controller, the host can start enumerating the device. The application can disable the USB device using :c:func:`usbd_disable`. .. literalinclude:: ../../../../samples/subsys/usb/hid-keyboard/src/main.c :language: c :dedent: :start-after: doc device enable start :end-before: doc device enable end USB Message notifications ========================= The application can register a callback using :c:func:`usbd_msg_register_cb` to receive message notification from the USB device support subsystem. The messages are mostly about the common device state changes, and a few specific types from the USB CDC ACM implementation. .. literalinclude:: ../../../../samples/subsys/usb/common/sample_usbd_init.c :language: c :dedent: :start-after: doc device init-and-msg start :end-before: doc device init-and-msg end The helper function :c:func:`usbd_msg_type_string()` can be used to convert :c:enumerator:`usbd_msg_type` to a human readable form for logging. If the controller supports VBUS state change detection, the battery-powered application may want to enable the USB device only when it is connected to a host. A generic application should use :c:func:`usbd_can_detect_vbus` to check for this capability. .. literalinclude:: ../../../../samples/subsys/usb/hid-keyboard/src/main.c :language: c :dedent: :start-after: doc device msg-cb start :end-before: doc device msg-cb end ```
/content/code_sandbox/doc/connectivity/usb/device_next/usb_device.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,300
```restructuredtext .. _uhc_api: USB host controller (UHC) driver API #################################### The USB host controller driver API is described in :zephyr_file:`include/zephyr/drivers/usb/uhc.h` and referred to as the ``UHC driver`` API. UHC driver API is experimental and is subject to change without notice. Driver API reference ******************** .. doxygengroup:: uhc_api ```
/content/code_sandbox/doc/connectivity/usb/host/api/uhc.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
92
```restructuredtext .. _usb_hid_common: Human Interface Devices (HID) ############################# Common USB HID part that can be used outside of USB support, defined in header file :zephyr_file:`include/zephyr/usb/class/hid.h`. HID types reference ******************* .. doxygengroup:: usb_hid_definitions HID items reference ******************* .. doxygengroup:: usb_hid_items HID Mouse and Keyboard report descriptors ***************************************** The pre-defined Mouse and Keyboard report descriptors can be used by a HID device implementation or simply as examples. .. doxygengroup:: usb_hid_mk_report_desc ```
/content/code_sandbox/doc/connectivity/usb/api/hid.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
132
```restructuredtext .. _bluetooth-qual: Qualification ############# Qualification setup ******************* .. _auto_pts_repository: path_to_url The Zephyr Bluetooth host can be qualified using Bluetooth's PTS (Profile Tuning Suite) software. It is originally a manual process, but is automated by using the `AutoPTS automation software <auto_pts_repository>`_. The setup is described in more details in the pages linked below. .. toctree:: :maxdepth: 1 autopts/autopts-win10.rst autopts/autopts-linux.rst ICS Features ************ .. _bluetooth_qualification_website: path_to_url The Zephyr ICS file for the Host features can be downloaded here: :download:`ICS_Zephyr_Bluetooth_Host.pts </tests/bluetooth/qualification/ICS_Zephyr_Bluetooth_Host.pts>`. Use the `Bluetooth Qualification website <bluetooth_qualification_website>`_ to view and edit the ICS. ```
/content/code_sandbox/doc/connectivity/bluetooth/bluetooth-qual.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
213
```restructuredtext .. _bluetooth-ctlr-arch: LE Controller ############# Overview ******** .. image:: img/ctlr_overview.png #. HCI * Host Controller Interface, Bluetooth standard * Provides Zephyr Bluetooth HCI Driver #. HAL * Hardware Abstraction Layer * Vendor Specific, and Zephyr Driver usage #. Ticker * Soft real time radio/resource scheduling #. LL_SW * Software-based Link Layer implementation * States and roles, control procedures, packet controller #. Util * Bare metal memory pool management * Queues of variable count, lockless usage * FIFO of fixed count, lockless usage * Mayfly concept based deferred ISR executions Architecture ************ Execution Overview ================== .. image:: img/ctlr_exec_overview.png Architecture Overview ===================== .. image:: img/ctlr_arch_overview.png Scheduling ********** .. image:: img/ctlr_sched.png Ticker ====== .. image:: img/ctlr_sched_ticker.png Upper Link Layer and Lower Link Layer ===================================== .. image:: img/ctlr_sched_ull_lll.png Scheduling Variants =================== .. image:: img/ctlr_sched_variant.png ULL and LLL Timing ================== .. image:: img/ctlr_sched_ull_lll_timing.png Event Handling ************** .. image:: img/ctlr_sched_event_handling.png Scheduling Closely Spaced Events ================================ .. image:: img/ctlr_sched_msc_close_events.png Aborting Active Event ===================== .. image:: img/ctlr_sched_msc_event_abort.png Cancelling Pending Event ======================== .. image:: img/ctlr_sched_msc_event_cancel.png Pre-emption of Active Event =========================== .. image:: img/ctlr_sched_msc_event_preempt.png Data Flow ********* Transmit Data Flow ================== .. image:: img/ctlr_dataflow_tx.png Receive Data Flow ================= .. image:: img/ctlr_dataflow_rx.png Execution Priorities ******************** .. image:: img/ctlr_exec_prio.png - Event handle (0, 1) < Event preparation (2, 3) < Event/Rx done (4) < Tx request (5) < Role management (6) < Host (7). - LLL is vendor ISR, ULL is Mayfly ISR concept, Host is kernel thread. Lower Link Layer **************** LLL Execution ============= .. image:: img/ctlr_exec_lll.png LLL Resume ---------- .. image:: img/ctlr_exec_lll_resume_top.png .. image:: img/ctlr_exec_lll_resume_bottom.png Bare metal utilities ******************** Memory FIFO and Memory Queue ============================ .. image:: img/ctlr_mfifo_memq.png Mayfly ====== .. image:: img/ctlr_mayfly.png * Mayfly are multi-instance scalable ISR execution contexts * What a Work is to a Thread, Mayfly is to an ISR * List of functions executing in ISRs * Execution priorities map to IRQ priorities * Facilitate cross execution context scheduling * Race-to-idle execution * Lock-less, bare metal Legacy Controller ***************** .. image:: img/ctlr_legacy.png Bluetooth Low Energy Controller - Vendor Specific Details ********************************************************* Hardware Requirements ===================== Nordic Semiconductor -------------------- The Nordic Semiconductor Bluetooth Low Energy Controller implementation requires the following hardware peripherals. .. list-table:: SoC Peripheral Use :header-rows: 1 :widths: 15 15 15 10 50 * - Resource - nRF Peripheral - # instances - Zephyr Driver Accessible - Description * - Clock - NRF_CLOCK - 1 - Yes - * A Low Frequency Clock (LFCLOCK) or sleep clock, for low power consumption between Bluetooth radio events * A High Frequency Clock (HFCLOCK) or active clock, for high precision packet timing and software based transceiver state switching with inter-frame space (tIFS) timing inside Bluetooth radio events * - RTC [a]_ - NRF_RTC0 - 1 - **No** - * Uses 2 capture/compare registers * - Timer - NRF_TIMER0 or NRF_TIMER4 [1]_, and NRF_TIMER1 [0]_ - 2 or 1 [1]_ - **No** - * 2 instances, one each for packet timing and tIFS software switching, respectively * 7 capture/compare registers (3 mandatory, 1 optional for ISR profiling, 4 for single timer tIFS switching) on first instance * 4 capture/compare registers for second instance, if single tIFS timer is not used. * - PPI [b]_ - NRF_PPI - 21 channels (20 [2]_), and 2 channel groups [3]_ - Yes [4]_ - * Used for radio mode switching to achieve tIFS timings, for PA/LNA control * - DPPI [c]_ - NRF_DPPI - 20 channels, and 2 channel groups [3]_ - Yes [4]_ - * Used for radio mode switching to achieve tIFS timings, for PA/LNA control * - SWI [d]_ - NRF_SWI4 and NRF_SWI5, or NRF_SWI2 and NRF_SWI3 [5]_ - 2 - **No** - * 2 instances, for Lower Link Layer and Upper Link Layer Low priority execution context * - Radio - NRF_RADIO - 1 - **No** - * 2.4 GHz radio transceiver with multiple radio standards such as 1 Mbps, 2 Mbps and Coded PHY S2/S8 Long Range Bluetooth Low Energy technology * - RNG [e]_ - NRF_RNG - 1 - Yes - * - ECB [f]_ - NRF_ECB - 1 - **No** - * - CBC-CCM [g]_ - NRF_CCM - 1 - **No** - * - AAR [h]_ - NRF_AAR - 1 - **No** - * - GPIO [i]_ - NRF_GPIO - 2 GPIO pins for PA and LNA, 1 each - Yes - * Additionally, 10 Debug GPIO pins (optional) * - GPIOTE [j]_ - NRF_GPIOTE - 1 - Yes - * Used for PA/LNA * - TEMP [k]_ - NRF_TEMP - 1 - Yes - * For RC sourced LFCLOCK calibration * - UART [l]_ - NRF_UART0 - 1 - Yes - * For HCI interface in Controller only builds * - IPC [m]_ - NRF_IPC [5]_ - 1 - Yes - * For HCI interface in Controller only builds .. [a] Real Time Counter (RTC) .. [b] Programmable Peripheral Interconnect (PPI) .. [c] Distributed Programmable Peripheral Interconnect (DPPI) .. [d] Software Interrupt (SWI) .. [e] Random Number Generator (RNG) .. [f] AES Electronic Codebook Mode Encryption (ECB) .. [g] Cipher Block Chaining (CBC) - Message Authentication Code with Counter Mode encryption (CCM) .. [h] Accelerated Address Resolver (AAR) .. [i] General Purpose Input Output (GPIO) .. [j] GPIO tasks and events (GPIOTE) .. [k] Temperature sensor (TEMP) .. [l] Universal Asynchronous Receiver Transmitter (UART) .. [m] Interprocess Communication peripheral (IPC) .. [0] :kconfig:option:`CONFIG_BT_CTLR_TIFS_HW` ``=n`` .. [1] :kconfig:option:`CONFIG_BT_CTLR_SW_SWITCH_SINGLE_TIMER` ``=y`` .. [2] When not using pre-defined PPI channels .. [3] For software-based tIFS switching .. [4] Drivers that use nRFx interfaces .. [5] For nRF53x Series ```
/content/code_sandbox/doc/connectivity/bluetooth/bluetooth-ctlr-arch.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,863
```restructuredtext .. _bluetooth: Bluetooth ######### This section contains information regarding the Bluetooth stack of the Zephyr OS. You can use this information to understand the principles behind the operation of the layers and how they were implemented. Zephyr includes a complete Bluetooth Low Energy stack from application to radio hardware, as well as portions of a Classical Bluetooth (BR/EDR) Host layer. .. toctree:: :maxdepth: 1 features.rst bluetooth-qual.rst bluetooth-arch.rst bluetooth-le-host.rst api/audio/bluetooth-le-audio-arch.rst bluetooth-ctlr-arch.rst bluetooth-dev.rst api/index.rst bluetooth-tools.rst bluetooth-shell.rst ```
/content/code_sandbox/doc/connectivity/bluetooth/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
168
```restructuredtext .. _bluetooth-arch: Stack Architecture ################## Overview ******** This page describes the software architecture of Zephyr's Bluetooth protocol stack. .. note:: Zephyr supports mainly Bluetooth Low Energy (BLE), the low-power version of the Bluetooth specification. Zephyr also has limited support for portions of the BR/EDR Host. Throughout this architecture document we use BLE interchangeably for Bluetooth except when noted. .. _bluetooth-layers: BLE Layers ========== There are 3 main layers that together constitute a full Bluetooth Low Energy protocol stack: * **Host**: This layer sits right below the application, and is comprised of multiple (non real-time) network and transport protocols enabling applications to communicate with peer devices in a standard and interoperable way. * **Controller**: The Controller implements the Link Layer (LE LL), the low-level, real-time protocol which provides, in conjunction with the Radio Hardware, standard-interoperable over-the-air communication. The LL schedules packet reception and transmission, guarantees the delivery of data, and handles all the LL control procedures. * **Radio Hardware**: Hardware implements the required analog and digital baseband functional blocks that permit the Link Layer firmware to send and receive in the 2.4GHz band of the spectrum. .. _bluetooth-hci: Host Controller Interface ========================= The `Bluetooth Specification`_ describes the format in which a Host must communicate with a Controller. This is called the Host Controller Interface (HCI) protocol. HCI can be implemented over a range of different physical transports like UART, SPI, or USB. This protocol defines the commands that a Host can send to a Controller and the events that it can expect in return, and also the format for user and protocol data that needs to go over the air. The HCI ensures that different Host and Controller implementations can communicate in a standard way making it possible to combine Hosts and Controllers from different vendors. .. _bluetooth-configs: Configurations ============== The three separate layers of the protocol and the standardized interface make it possible to implement the Host and Controller on different platforms. The two following configurations are commonly used: * **Single-chip configuration**: In this configuration, a single microcontroller implements all three layers and the application itself. This can also be called a system-on-chip (SoC) implementation. In this case the BLE Host and the BLE Controller communicate directly through function calls and queues in RAM. The Bluetooth specification does not specify how HCI is implemented in this single-chip configuration and so how HCI commands, events, and data flows between the two can be implementation-specific. This configuration is well suited for those applications and designs that require a small footprint and the lowest possible power consumption, since everything runs on a single IC. * **Dual-chip configuration**: This configuration uses two separate ICs, one running the Application and the Host, and a second one with the Controller and the Radio Hardware. This is sometimes also called a connectivity-chip configuration. This configuration allows for a wider variety of combinations of Hosts when using the Zephyr OS as a Controller. Since HCI ensures interoperability among Host and Controller implementations, including of course Zephyr's very own BLE Host and Controller, users of the Zephyr Controller can choose to use whatever Host running on any platform they prefer. For example, the host can be the Linux BLE Host stack (BlueZ) running on any processor capable of supporting Linux. The Host processor may of course also run Zephyr and the Zephyr OS BLE Host. Conversely, combining an IC running the Zephyr Host with an external Controller that does not run Zephyr is also supported. .. _bluetooth-build-types: Build Types =========== The Zephyr software stack as an RTOS is highly configurable, and in particular, the BLE subsystem can be configured in multiple ways during the build process to include only the features and layers that are required to reduce RAM and ROM footprint as well as power consumption. Here's a short list of the different BLE-enabled builds that can be produced from the Zephyr project codebase: * **Controller-only build**: When built as a BLE Controller, Zephyr includes the Link Layer and a special application. This application is different depending on the physical transport chosen for HCI: * :ref:`hci_uart <bluetooth-hci-uart-sample>` * :ref:`hci_usb <bluetooth-hci-usb-sample>` * :ref:`hci_spi <bluetooth-hci-spi-sample>` This application acts as a bridge between the UART, SPI or USB peripherals and the Controller subsystem, listening for HCI commands, sending application data and responding with events and received data. A build of this type sets the following Kconfig option values: * :kconfig:option:`CONFIG_BT` ``=y`` * :kconfig:option:`CONFIG_BT_HCI` ``=y`` * :kconfig:option:`CONFIG_BT_HCI_RAW` ``=y`` * :kconfig:option:`CONFIG_BT_CTLR` ``=y`` * :kconfig:option:`CONFIG_BT_LL_SW_SPLIT` ``=y`` (if using the open source Link Layer) * **Host-only build**: A Zephyr OS Host build will contain the Application and the BLE Host, along with an HCI driver (UART or SPI) to interface with an external Controller chip. A build of this type sets the following Kconfig option values: * :kconfig:option:`CONFIG_BT` ``=y`` * :kconfig:option:`CONFIG_BT_HCI` ``=y`` * :kconfig:option:`CONFIG_BT_CTLR` ``=n`` All of the samples located in ``samples/bluetooth`` except for the ones used for Controller-only builds can be built as Host-only * **Combined build**: This includes the Application, the Host and the Controller, and it is used exclusively for single-chip (SoC) configurations. A build of this type sets the following Kconfig option values: * :kconfig:option:`CONFIG_BT` ``=y`` * :kconfig:option:`CONFIG_BT_HCI` ``=y`` * :kconfig:option:`CONFIG_BT_CTLR` ``=y`` * :kconfig:option:`CONFIG_BT_LL_SW_SPLIT` ``=y`` (if using the open source Link Layer) All of the samples located in ``samples/bluetooth`` except for the ones used for Controller-only builds can be built as Combined The picture below shows the SoC or single-chip configuration when using a Zephyr combined build (a build that includes both a BLE Host and a Controller in the same firmware image that is programmed onto the chip): .. figure:: img/ble_cfg_single.png :align: center :alt: BLE Combined build on a single chip A Combined build on a Single-Chip configuration When using connectivity or dual-chip configurations, several Host and Controller combinations are possible, some of which are depicted below: .. figure:: img/ble_cfg_dual.png :align: center :alt: BLE dual-chip configuration builds Host-only and Controller-only builds on dual-chip configurations When using a Zephyr Host (left side of image), two instances of Zephyr OS must be built with different configurations, yielding two separate images that must be programmed into each of the chips respectively. The Host build image contains the application, the BLE Host and the selected HCI driver (UART or SPI), while the Controller build runs either the :ref:`hci_uart <bluetooth-hci-uart-sample>`, or the :ref:`hci_spi <bluetooth-hci-spi-sample>` app to provide an interface to the BLE Controller. This configuration is not limited to using a Zephyr OS Host, as the right side of the image shows. One can indeed take one of the many existing GNU/Linux distributions, most of which include Linux's own BLE Host (BlueZ), to connect it via UART or USB to one or more instances of the Zephyr OS Controller build. BlueZ as a Host supports multiple Controllers simultaneously for applications that require more than one BLE radio operating at the same time but sharing the same Host stack. Source tree layout ****************** The stack is split up as follows in the source tree: ``subsys/bluetooth/host`` :ref:`The host stack <bluetooth_le_host>`. This is where the HCI command and event handling as well as connection tracking happens. The implementation of the core protocols such as L2CAP, ATT, and SMP is also here. ``subsys/bluetooth/controller`` :ref:`Bluetooth LE Controller <bluetooth-ctlr-arch>` implementation. Implements the controller-side of HCI, the Link Layer as well as access to the radio transceiver. ``include/bluetooth/`` :ref:`Public API <bluetooth_api>` header files. These are the header files applications need to include in order to use Bluetooth functionality. ``drivers/bluetooth/`` HCI transport drivers. Every HCI transport needs its own driver. For example, the two common types of UART transport protocols (3-Wire and 5-Wire) have their own drivers. ``samples/bluetooth/`` :ref:`Sample Bluetooth code <bluetooth-samples>`. This is a good reference to get started with Bluetooth application development. ``tests/bluetooth/`` Test applications. These applications are used to verify the functionality of the Bluetooth stack, but are not necessary the best source for sample code (see ``samples/bluetooth`` instead). ``doc/connectivity/bluetooth/`` Extra documentation, such as PICS documents. .. _Bluetooth Specification: path_to_url ```
/content/code_sandbox/doc/connectivity/bluetooth/bluetooth-arch.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,138
```restructuredtext .. _bluetooth_le_host: LE Host ####### The Bluetooth Host implements all the higher-level protocols and profiles, and most importantly, provides a high-level API for applications. The following diagram depicts the main protocol & profile layers of the host. .. figure:: img/ble_host_layers.png :align: center :alt: Bluetooth Host protocol & profile layers Bluetooth Host protocol & profile layers. Lowest down in the host stack sits a so-called HCI driver, which is responsible for abstracting away the details of the HCI transport. It provides a basic API for delivering data from the controller to the host, and vice-versa. Perhaps the most important block above the HCI handling is the Generic Access Profile (GAP). GAP simplifies Bluetooth LE access by defining four distinct roles of BLE usage: * Connection-oriented roles * Peripheral (e.g. a smart sensor, often with a limited user interface) * Central (typically a mobile phone or a PC) * Connection-less roles * Broadcaster (sending out BLE advertisements, e.g. a smart beacon) * Observer (scanning for BLE advertisements) Each role comes with its own build-time configuration option: :kconfig:option:`CONFIG_BT_PERIPHERAL`, :kconfig:option:`CONFIG_BT_CENTRAL`, :kconfig:option:`CONFIG_BT_BROADCASTER` & :kconfig:option:`CONFIG_BT_OBSERVER`. Of the connection-oriented roles central implicitly enables observer role, and peripheral implicitly enables broadcaster role. Usually the first step when creating an application is to decide which roles are needed and go from there. Bluetooth Mesh is a slightly special case, requiring at least the observer and broadcaster roles, and possibly also the Peripheral role. This will be described in more detail in a later section. Peripheral role =============== Most Zephyr-based BLE devices will most likely be peripheral-role devices. This means that they perform connectable advertising and expose one or more GATT services. After registering services using the :c:func:`bt_gatt_service_register` API the application will typically start connectable advertising using the :c:func:`bt_le_adv_start` API. There are several peripheral sample applications available in the tree, such as :zephyr_file:`samples/bluetooth/peripheral_hr`. Central role ============ Central role may not be as common for Zephyr-based devices as peripheral role, but it is still a plausible one and equally well supported in Zephyr. Rather than accepting connections from other devices a central role device will scan for available peripheral device and choose one to connect to. Once connected, a central will typically act as a GATT client, first performing discovery of available services and then accessing one or more supported services. To initially discover a device to connect to the application will likely use the :c:func:`bt_le_scan_start` API, wait for an appropriate device to be found (using the scan callback), stop scanning using :c:func:`bt_le_scan_stop` and then connect to the device using :c:func:`bt_conn_le_create`. If the central wants to keep automatically reconnecting to the peripheral it should use the :c:func:`bt_le_set_auto_conn` API. There are some sample applications for the central role available in the tree, such as :zephyr_file:`samples/bluetooth/central_hr`. Observer role ============= An observer role device will use the :c:func:`bt_le_scan_start` API to scan for device, but it will not connect to any of them. Instead it will simply utilize the advertising data of found devices, combining it optionally with the received signal strength (RSSI). Broadcaster role ================ A broadcaster role device will use the :c:func:`bt_le_adv_start` API to advertise specific advertising data, but the type of advertising will be non-connectable, i.e. other device will not be able to connect to it. Connections =========== Connection handling and the related APIs can be found in the :ref:`Connection Management <bluetooth_connection_mgmt>` section. Security ======== To achieve a secure relationship between two Bluetooth devices a process called pairing is used. This process can either be triggered implicitly through the security properties of GATT services, or explicitly using the :c:func:`bt_conn_security` API on a connection object. To achieve a higher security level, and protect against Man-In-The-Middle (MITM) attacks, it is recommended to use some out-of-band channel during the pairing. If the devices have a sufficient user interface this "channel" is the user itself. The capabilities of the device are registered using the :c:func:`bt_conn_auth_cb_register` API. The :c:struct:`bt_conn_auth_cb` struct that's passed to this API has a set of optional callbacks that can be used during the pairing - if the device lacks some feature the corresponding callback may be set to NULL. For example, if the device does not have an input method but does have a display, the ``passkey_entry`` and ``passkey_confirm`` callbacks would be set to NULL, but the ``passkey_display`` would be set to a callback capable of displaying a passkey to the user. Depending on the local and remote security requirements & capabilities, there are four possible security levels that can be reached: :c:enumerator:`BT_SECURITY_L1` No encryption and no authentication. :c:enumerator:`BT_SECURITY_L2` Encryption but no authentication (no MITM protection). :c:enumerator:`BT_SECURITY_L3` Encryption and authentication using the legacy pairing method from Bluetooth 4.0 and 4.1. :c:enumerator:`BT_SECURITY_L4` Encryption and authentication using the LE Secure Connections feature available since Bluetooth 4.2. .. note:: Mesh has its own security solution through a process called provisioning. It follows a similar procedure as pairing, but is done using separate mesh-specific APIs. L2CAP ===== L2CAP stands for the Logical Link Control and Adaptation Protocol. It is a common layer for all communication over Bluetooth connections, however an application comes in direct contact with it only when using it in the so-called Connection-oriented Channels (CoC) mode. More information on this can be found in the :ref:`L2CAP API section <bt_l2cap>`. Terminology ----------- The definitions are from the Core Specification version 5.4, volume 3, part A 1.4. .. list-table:: :header-rows: 1 * - Term - Description * - Upper layer - Layer above L2CAP, it exchanges data in form of SDUs. It may be an application or a higher level protocol. * - Lower layer - Layer below L2CAP, it exchanges data in form of PDUs (or fragments). It is usually the HCI. * - Service Data Unit (SDU) - Packet of data that L2CAP exchanges with the upper layer. This term is relevant only in Enhanced Retransmission mode, Streaming mode, Retransmission mode and Flow Control Mode, not in Basic L2CAP mode. * - Protocol Data Unit (PDU) - Packet of data containing L2CAP data. PDUs always start with Basic L2CAP header. Types of PDUs for LE: :ref:`B-frames <bluetooth_l2cap_b_frame>` and :ref:`K-frames <bluetooth_l2cap_k_frame>`. Types of PDUs for BR/EDR: I-frames, S-frames, C-frames and G-frames. * - Maximum Transmission Unit (MTU) - Maximum size of an SDU that the upper layer is capable of accepting. * - Maximum Payload Size (MPS) - Maximum payload size that the L2CAP layer is capable of accepting. In Basic L2CAP mode, the MTU size is equal to MPS. In credit-based channels without segmentation, the MTU is MPS minus 2. * - Basic L2CAP header - Present at the beginning of each PDU. It contains two fields, the PDU length and the Channel Identifier (CID). PDU Types --------- .. _bluetooth_l2cap_b_frame: B-frame: Basic information frame ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PDU used in Basic L2CAP mode. It contains the payload received from the upper layer or delivered to the upper layer as its payload. .. image:: img/l2cap_b_frame.drawio.svg :align: center :width: 45% :alt: Representation of a B-frame PDU. The PDU is split into two rectangles, the first one being the L2CAP header, its size is 4 octets and its made of the PDU length and the channel ID. The second rectangle represents the information payload and its size is less or equal to MPS. .. _bluetooth_l2cap_k_frame: K-frame: Credit-based frame ^^^^^^^^^^^^^^^^^^^^^^^^^^^ PDU used in LE Credit Based Flow Control mode and Enhanced Credit Based Flow Control mode. It contains a SDU segment and additional protocol information. .. image:: img/l2cap_k_frame_1.drawio.svg :width: 45% :alt: Representation of a starting K-frame PDU. The PDU is split into three rectangles, the first one being the L2CAP header, its size is 4 octets and its made of the PDU length and the channel ID. The second rectangle represents the L2CAP SDU length, its size is 2 octets. The third rectangle represents the information payload and its size is less or equal to MPS minus 2 octets. The information payload contains the L2CAP SDU. .. image:: img/l2cap_k_frame.drawio.svg :align: right :width: 45% :alt: Representation of K-frames PDUs after the starting one. The PDU is split into two rectangles, the first one being the L2CAP header, its size is 4 octets and its made of the PDU length and the channel ID. The second rectangle represents the information payload and its size is less or equal to MPS. The information payload contains the L2CAP SDU. Relevant Kconfig ---------------- .. list-table:: :header-rows: 1 * - Kconfig symbol - Description * - :kconfig:option:`CONFIG_BT_BUF_ACL_RX_SIZE` - Represents the MPS * - :kconfig:option:`CONFIG_BT_L2CAP_TX_MTU` - Represents the L2CAP MTU * - :kconfig:option:`CONFIG_BT_L2CAP_DYNAMIC_CHANNEL` - Enables LE Credit Based Flow Control and thus the stack may use :ref:`K-frame <bluetooth_l2cap_k_frame>` PDUs GATT ==== The Generic Attribute Profile is the most common means of communication over LE connections. A more detailed description of this layer and the API reference can be found in the :ref:`GATT API reference section <bt_gatt>`. Mesh ==== Mesh is a little bit special when it comes to the needed GAP roles. By default, mesh requires both observer and broadcaster role to be enabled. If the optional GATT Proxy feature is desired, then peripheral role should also be enabled. The API reference for mesh can be found in the :ref:`Mesh API reference section <bluetooth_mesh>`. LE Audio ======== The LE audio is a set of profiles and services that utilizes GATT and Isochronous Channel to provide audio over Bluetooth Low Energy. The architecture and API references can be found in :ref:`Bluetooth Audio Architecture <bluetooth_le_audio_arch>`. .. _bluetooth-persistent-storage: Persistent storage ================== The Bluetooth host stack uses the settings subsystem to implement persistent storage to flash. This requires the presence of a flash driver and a designated "storage" partition on flash. A typical set of configuration options needed will look something like the following: .. code-block:: cfg CONFIG_BT_SETTINGS=y CONFIG_FLASH=y CONFIG_FLASH_PAGE_LAYOUT=y CONFIG_FLASH_MAP=y CONFIG_NVS=y CONFIG_SETTINGS=y Once enabled, it is the responsibility of the application to call settings_load() after having initialized Bluetooth (using the :c:func:`bt_enable` API). ```
/content/code_sandbox/doc/connectivity/bluetooth/bluetooth-le-host.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,711
```restructuredtext .. _bluetooth-features: Supported features ################## .. contents:: :local: :depth: 2 Since its inception, Zephyr has had a strong focus on Bluetooth and, in particular, on Bluetooth Low Energy (BLE). Through the contributions of several companies and individuals involved in existing open source implementations of the Bluetooth specification (Linux's BlueZ) as well as the design and development of BLE radio hardware, the protocol stack in Zephyr has grown to be mature and feature-rich, as can be seen in the section below. * Bluetooth v5.3 compliant * Highly configurable * Features, buffer sizes/counts, stack sizes, etc. * Portable to all architectures supported by Zephyr (including big and little endian, alignment flavors and more) * Support for :ref:`all combinations <bluetooth-hw-setup>` of Host and Controller builds: * Controller-only (HCI) over UART, SPI, USB and IPC physical transports * Host-only over UART, SPI, and IPC (shared memory) * Combined (Host + Controller) * :ref:`Bluetooth-SIG qualifiable <bluetooth-qual>` * Conformance tests run regularly on all layers (Controller and Host, except BT Classic) on Nordic Semiconductor hardware. * :ref:`Bluetooth Low Energy Controller <bluetooth-ctlr-arch>` (LE Link Layer) * Unlimited role and connection count, all roles supported * All v5.3 specification features supported (except a few minor items) * Concurrent multi-protocol support ready * Intelligent scheduling of roles to minimize overlap * Portable design to any open BLE radio, currently supports Nordic Semiconductor nRF52x and nRF53x SoC Series, as well as proprietary radios * Supports little and big endian architectures, and abstracts the hard real-time specifics so that they can be encapsulated in a hardware-specific module * Support for Controller (HCI) builds over different physical transports * Isochronous channels * :ref:`Bluetooth Host <bluetooth_le_host>` * Generic Access Profile (GAP) with all possible LE roles * Peripheral & Central * Observer & Broadcaster * Multiple PHY support (2Mbit/s, Coded) * Extended Advertising * Periodic Advertising (including Sync Transfer) * GATT (Generic Attribute Profile) * Server (to be a sensor) * Client (to connect to sensors) * Enhanced ATT (EATT) * GATT Database Hash * GATT Multiple Notifications * Pairing support, including the Secure Connections feature from Bluetooth 4.2 * Non-volatile storage support for permanent storage of Bluetooth-specific settings and data * Bluetooth Mesh support * Relay, Friend Node, Low-Power Node (LPN) and GATT Proxy features * Both Provisioning roles and bearers supported (PB-ADV & PB-GATT) * Foundation Models included * Highly configurable, fits as small as 16k RAM devices * Basic Bluetooth BR/EDR (Classic) support * Generic Access Profile (GAP) * Logical Link Control and Adaptation Protocol (L2CAP) * Serial Port emulation (RFCOMM protocol) * Service Discovery Protocol (SDP) * Clean HCI driver abstraction * 3-Wire (H:5) & 5-Wire (H:4) UART * SPI * Local controller support as a virtual HCI driver * Verified with multiple popular controllers * Isochronous channels * :ref:`LE Audio <bluetooth_le_audio_arch>` ```
/content/code_sandbox/doc/connectivity/bluetooth/features.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
794
```restructuredtext .. _bluetooth-dev: Application Development ####################### Bluetooth applications are developed using the common infrastructure and approach that is described in the :ref:`application` section of the documentation. Additional information that is only relevant to Bluetooth applications can be found on this page. .. contents:: :local: :depth: 2 Thread safety ************* Calling into the Bluetooth API is intended to be thread safe, unless otherwise noted in the documentation of the API function. The effort to ensure that this is the case for all API calls is an ongoing one, but the overall goal is formally stated in this paragraph. Bug reports and Pull Requests that move the subsystem in the direction of such goal are welcome. .. _bluetooth-hw-setup: Hardware setup ************** This section describes the options you have when building and debugging Bluetooth applications with Zephyr. Depending on the hardware that is available to you, the requirements you have and the type of development you prefer you may pick one or another setup to match your needs. There are 3 possible setups: #. :ref:`Embedded <bluetooth-hw-setup-embedded>` #. :ref:`External controller <bluetooth-hw-setup-external-ll>` - :ref:`QEMU host <bluetooth-hw-setup-qemu-host>` - :ref:`native_sim host <bluetooth-hw-setup-native-sim-host>` #. :ref:`Simulated nRF5x with BabbleSim <bluetooth-hw-setup-bsim>` .. _bluetooth-hw-setup-embedded: Embedded ======== This setup relies on all software running directly on the embedded platform(s) that the application is targeting. All the :ref:`bluetooth-configs` and :ref:`bluetooth-build-types` are supported but you might need to build Zephyr more than once if you are using a dual-chip configuration or if you have multiple cores in your SoC each running a different build type (e.g., one running the Host, the other the Controller). To start developing using this setup follow the :ref:`Getting Started Guide <getting_started>`, choose one (or more if you are using a dual-chip solution) boards that support Bluetooth and then :ref:`run the application <application_run_board>`). There is a way to access the :ref:`HCI <bluetooth-hci>` traffic between the Host and Controller, even if there is no physical transport. See :ref:`Embedded HCI tracing <bluetooth-embedded-hci-tracing>` for instructions. .. _bluetooth-hw-setup-external-ll: Host on Linux with an external Controller ========================================= .. note:: This is currently only available on GNU/Linux This setup relies on a "dual-chip" :ref:`configuration <bluetooth-configs>` which is comprised of the following devices: #. A :ref:`Host-only <bluetooth-build-types>` application running in the :ref:`QEMU <application_run_qemu>` emulator or the :ref:`native_sim <native_sim>` native port of Zephyr #. A Controller, which can be one of the following types: * A commercially available Controller * A :ref:`Controller-only <bluetooth-build-types>` build of Zephyr * A :ref:`Virtual controller <bluetooth_virtual_posix>` .. warning:: Certain external Controllers are either unable to accept the Host to Controller flow control parameters that Zephyr sets by default (Qualcomm), or do not transmit any data from the Controller to the Host (Realtek). If you see a message similar to:: <wrn> bt_hci_core: opcode 0x0c33 status 0x12 when booting your sample of choice (make sure you have enabled :kconfig:option:`CONFIG_LOG` in your :file:`prj.conf` before running the sample), or if there is no data flowing from the Controller to the Host, then you need to disable Host to Controller flow control. To do so, set ``CONFIG_BT_HCI_ACL_FLOW_CONTROL=n`` in your :file:`prj.conf`. .. _bluetooth-hw-setup-qemu-host: QEMU ---- You can run the Zephyr Host on the :ref:`QEMU emulator<application_run_qemu>` and have it interact with a physical external Bluetooth Controller. Refer to :ref:`bluetooth_qemu_native` for full instructions on how to build and run an application in this setup. .. _bluetooth-hw-setup-native-sim-host: native_sim ---------- .. note:: This is currently only available on GNU/Linux The :ref:`native_sim <native_sim>` target builds your Zephyr application with the Zephyr kernel, and some minimal HW emulation as a native Linux executable. This executable is a normal Linux program, which can be debugged and instrumented like any other, and it communicates with a physical or virtual external Controller. Refer to: - :ref:`bluetooth_qemu_native` for the physical controller - :ref:`bluetooth_virtual_posix` for the virtual controller .. _bluetooth-hw-setup-bsim: Simulated nRF5x with BabbleSim ============================== .. note:: This is currently only available on GNU/Linux The :ref:`nrf52_bsim <nrf52_bsim>` and :ref:`nrf5340bsim <nrf5340bsim>` boards, are simulated target boards which emulate the necessary peripherals of a nRF52/53 SOC to be able to develop and test BLE applications. These boards, use: * `BabbleSim`_ to simulate the nRF5x modem and the radio environment. * The POSIX arch and native simulator to emulate the processor, and run natively on your host. * `Models of the nrf5x HW <path_to_url`_ Just like with the :ref:`native_sim <native_sim>` target, the build result is a normal Linux executable. You can find more information on how to run simulations with one or several devices in either of :ref:`these boards's documentation <nrf52bsim_build_and_run>`. With the :ref:`nrf52_bsim <nrf52_bsim>`, typically you do :ref:`Combined builds <bluetooth-build-types>`, but it is also possible to build the controller with one of the :ref:`HCI UART <bluetooth-hci-uart-sample>` samples in one simulated device, and the host with the H4 driver instead of the integrated controller in another simulated device. With the :ref:`nrf5340bsim <nrf5340bsim>`, you can build with either, both controller and host on its network core, or, with the network core running only the controller, the application core running the host and your application, and the HCI transport over IPC. Initialization ************** The Bluetooth subsystem is initialized using the :c:func:`bt_enable` function. The caller should ensure that function succeeds by checking the return code for errors. If a function pointer is passed to :c:func:`bt_enable`, the initialization happens asynchronously, and the completion is notified through the given function. Bluetooth Application Example ***************************** A simple Bluetooth beacon application is shown below. The application initializes the Bluetooth Subsystem and enables non-connectable advertising, effectively acting as a Bluetooth Low Energy broadcaster. .. literalinclude:: ../../../samples/bluetooth/beacon/src/main.c :language: c :lines: 19- :linenos: The key APIs employed by the beacon sample are :c:func:`bt_enable` that's used to initialize Bluetooth and then :c:func:`bt_le_adv_start` that's used to start advertising a specific combination of advertising and scan response data. More Examples ************* More :ref:`sample Bluetooth applications <bluetooth-samples>` are available in ``samples/bluetooth/``. .. _BabbleSim: path_to_url ```
/content/code_sandbox/doc/connectivity/bluetooth/bluetooth-dev.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,708
```restructuredtext .. _bluetooth_shell: Shell ##### The Bluetooth Shell is an application based on the :ref:`shell_api` module. It offer a collection of commands made to easily interact with the Bluetooth stack. Bluetooth Shell Setup and Usage ******************************* First you need to build and flash your board with the Bluetooth shell. For how to do that, see the :ref:`getting_started`. The Bluetooth shell itself is located in :zephyr_file:`tests/bluetooth/shell/`. When it's done, connect to the CLI using your favorite serial terminal application. You should see the following prompt: .. code-block:: console uart:~$ For more details on general usage of the shell, see :ref:`shell_api`. The first step is enabling Bluetooth. To do so, use the :code:`bt init` command. The following message is printed to confirm Bluetooth has been initialized. .. code-block:: console uart:~$ bt init Bluetooth initialized Settings Loaded [00:02:26.771,148] <inf> fs_nvs: nvs_mount: 8 Sectors of 4096 bytes [00:02:26.771,148] <inf> fs_nvs: nvs_mount: alloc wra: 0, fe8 [00:02:26.771,179] <inf> fs_nvs: nvs_mount: data wra: 0, 0 [00:02:26.777,984] <inf> bt_hci_core: hci_vs_init: HW Platform: Nordic Semiconductor (0x0002) [00:02:26.778,015] <inf> bt_hci_core: hci_vs_init: HW Variant: nRF52x (0x0002) [00:02:26.778,045] <inf> bt_hci_core: hci_vs_init: Firmware: Standard Bluetooth controller (0x00) Version 3.2 Build 99 [00:02:26.778,656] <inf> bt_hci_core: bt_init: No ID address. App must call settings_load() [00:02:26.794,738] <inf> bt_hci_core: bt_dev_show_info: Identity: EB:BF:36:26:42:09 (random) [00:02:26.794,769] <inf> bt_hci_core: bt_dev_show_info: HCI: version 5.3 (0x0c) revision 0x0000, manufacturer 0x05f1 [00:02:26.794,799] <inf> bt_hci_core: bt_dev_show_info: LMP: version 5.3 (0x0c) subver 0xffff Identities ********** Identities are a Zephyr host concept, allowing a single physical device to behave like multiple logical Bluetooth devices. The shell allows the creation of multiple identities, to a maximum that is set by the Kconfig symbol :kconfig:option:`CONFIG_BT_ID_MAX`. To create a new identity, use :code:`bt id-create` command. You can then use it by selecting it with its ID :code:`bt id-select <id>`. Finally, you can list all the available identities with :code:`id-show`. Scan for devices **************** Start scanning by using the :code:`bt scan on` command. Depending on the environment you're in, you may see a lot of lines printed on the shell. To stop the scan, run :code:`bt scan off`, the scrolling should stop. Here is an example of what you can expect: .. code-block:: console uart:~$ bt scan on Bluetooth active scan enabled [DEVICE]: CB:01:1A:2D:6E:AE (random), AD evt type 0, RSSI -78 C:1 S:1 D:0 SR:0 E:0 Prim: LE 1M, Secn: No packets, Interval: 0x0000 (0 us), SID: 0xff [DEVICE]: 20:C2:EE:59:85:5B (random), AD evt type 3, RSSI -62 C:0 S:0 D:0 SR:0 E:0 Prim: LE 1M, Secn: No packets, Interval: 0x0000 (0 us), SID: 0xff [DEVICE]: E3:72:76:87:2F:E8 (random), AD evt type 3, RSSI -74 C:0 S:0 D:0 SR:0 E:0 Prim: LE 1M, Secn: No packets, Interval: 0x0000 (0 us), SID: 0xff [DEVICE]: 1E:19:25:8A:CB:84 (random), AD evt type 3, RSSI -67 C:0 S:0 D:0 SR:0 E:0 Prim: LE 1M, Secn: No packets, Interval: 0x0000 (0 us), SID: 0xff [DEVICE]: 26:42:F3:D5:A0:86 (random), AD evt type 3, RSSI -73 C:0 S:0 D:0 SR:0 E:0 Prim: LE 1M, Secn: No packets, Interval: 0x0000 (0 us), SID: 0xff [DEVICE]: 0C:61:D1:B9:5D:9E (random), AD evt type 3, RSSI -87 C:0 S:0 D:0 SR:0 E:0 Prim: LE 1M, Secn: No packets, Interval: 0x0000 (0 us), SID: 0xff [DEVICE]: 20:C2:EE:59:85:5B (random), AD evt type 3, RSSI -66 C:0 S:0 D:0 SR:0 E:0 Prim: LE 1M, Secn: No packets, Interval: 0x0000 (0 us), SID: 0xff [DEVICE]: 25:3F:7A:EE:0F:55 (random), AD evt type 3, RSSI -83 C:0 S:0 D:0 SR:0 E:0 Prim: LE 1M, Secn: No packets, Interval: 0x0000 (0 us), SID: 0xff uart:~$ bt scan off Scan successfully stopped As you can see, this can lead to a high number of results. To reduce that number and easily find a specific device, you can enable scan filters. There are four types of filters: by name, by RSSI, by address and by periodic advertising interval. To apply a filter, use the :code:`bt scan-set-filter` command followed by the type of filters. You can add multiple filters by using the commands again. For example, if you want to look only for devices with the name *test shell*: .. code-block:: console uart:~$ bt scan-filter-set name "test shell" Or if you want to look for devices at a very close range: .. code-block:: console uart:~$ bt scan-filter-set rssi -40 RSSI cutoff set at -40 dB Finally, if you want to remove all filters: .. code-block:: console uart:~$ bt scan-filter-clear all You can use the command :code:`bt scan on` to create an *active* scanner, meaning that the scanner will ask the advertisers for more information by sending a *scan request* packet. Alternatively, you can create a *passive scanner* by using the :code:`bt scan passive` command, so the scanner will not ask the advertiser for more information. Connecting to a device ********************** To connect to a device, you need to know its address and type of address and use the :code:`bt connect` command with the address and the type as arguments. Here is an example: .. code-block:: console uart:~$ bt connect 52:84:F6:BD:CE:48 random Connection pending Connected: 52:84:F6:BD:CE:48 (random) Remote LMP version 5.3 (0x0c) subversion 0xffff manufacturer 0x05f1 LE Features: 0x000000000001412f LE PHY updated: TX PHY LE 2M, RX PHY LE 2M LE conn param req: int (0x0018, 0x0028) lat 0 to 42 LE conn param updated: int 0x0028 lat 0 to 42 You can list the active connections of the shell using the :code:`bt connections` command. The shell maximum number of connections is defined by :kconfig:option:`CONFIG_BT_MAX_CONN`. You can disconnect from a connection with the :code:`bt disconnect <address: XX:XX:XX:XX:XX:XX> <type: (public|random)>` command. .. note:: If you were scanning just before, you can connect to the last scanned device by simply running the :code:`bt connect` command. Alternatively, you can use the :code:`bt connect-name <name>` command to automatically enable scanning with a name filter and connect to the first match. Advertising *********** Begin advertising by using the :code:`bt advertise on` command. This will use the default parameters and advertise a resolvable private address with the name of the device. You can choose to use the identity address instead by running the :code:`bt advertise on identity` command. To stop advertising use the :code:`bt advertise off` command. To enable more advanced features of advertising, you should create an advertiser using the :code:`bt adv-create` command. Parameters for the advertiser can be passed either at the creation of it or by using the :code:`bt adv-param` command. To begin advertising with this newly created advertiser, use the :code:`bt adv-start` command, and then the :code:`bt adv-stop` command to stop advertising. When using the custom advertisers, you can choose if it will be connectable or scannable. This leads to four options: :code:`conn-scan`, :code:`conn-nscan`, :code:`nconn-scan` and :code:`nconn-nscan`. Those parameters are mandatory when creating an advertiser or updating its parameters. For example, if you want to create a connectable and scannable advertiser and start it: .. code-block:: console uart:~$ bt adv-create conn-scan Created adv id: 0, adv: 0x200022f0 uart:~$ bt adv-start Advertiser[0] 0x200022f0 set started You may notice that with this, the custom advertiser does not advertise the device name; you need to add it. Continuing from the previous example: .. code-block:: console uart:~$ bt adv-stop Advertiser set stopped uart:~$ bt adv-data dev-name uart:~$ bt adv-start Advertiser[0] 0x200022f0 set started You should now see the name of the device in the advertising data. You can also set a custom name by using :code:`name <custom name>` instead of :code:`dev-name`. It is also possible to set the advertising data manually with the :code:`bt adv-data` command. The following example shows how to set the advertiser name with it using raw advertising data: .. code-block:: console uart:~$ bt adv-create conn-scan Created adv id: 0, adv: 0x20002348 uart:~$ bt adv-data 1009426C7565746F6F74682D5368656C6C uart:~$ bt adv-start Advertiser[0] 0x20002348 set started The data must be formatted according to the Bluetooth Core Specification (see version 5.3, vol. 3, part C, 11). In this example, the first octet is the size of the data (the data and one octet for the data type), the second one is the type of data, ``0x09`` is the Complete Local Name and the remaining data are the name in ASCII. So, on the other device you should see the name *Bluetooth-Shell*. When advertising, if others devices use an *active* scanner, you may receive *scan request* packets. To visualize those packets, you can add :code:`scan-reports` to the parameters of your advertiser. Directed Advertising ==================== It is possible to use directed advertising on the shell if you want to reconnect to a device. The following example demonstrates how to create a directed advertiser with the address specified right after the parameter :code:`directed`. The :code:`low` parameter indicates that we want to use the low duty cycle mode, and the :code:`dir-rpa` parameter is required if the remote device is privacy-enabled and supports address resolution of the target address in directed advertisement. .. code-block:: console uart:~$ bt adv-create conn-scan directed D7:54:03:CE:F3:B4 random low dir-rpa Created adv id: 0, adv: 0x20002348 After that, you can start the advertiser and then the target device will be able to reconnect. Extended Advertising ==================== Let's now have a look at some extended advertising features. To enable extended advertising, use the `ext-adv` parameter. .. code-block:: console uart:~$ bt adv-create conn-nscan ext-adv name-ad Created adv id: 0, adv: 0x200022f0 uart:~$ bt adv-start Advertiser[0] 0x200022f0 set started This will create an extended advertiser, that is connectable and non-scannable. Encrypted Advertising Data ========================== Zephyr has support for the Encrypted Advertising Data feature. The :code:`bt encrypted-ad` sub-commands allow managing the advertising data of a given advertiser. To encrypt the advertising data, key materials need to be provided, that can be done with :code:`bt encrypted-ad set-keys <session key> <init vector>`. The session key is 16 bytes long and the initialisation vector is 8 bytes long. You can add advertising data by using :code:`bt encrypted-ad add-ad` and :code:`bt encrypted-ad add-ead`. The former will take add one advertising data structure (as defined in the Core Specification), when the later will read the given data, encrypt them and then add the generated encrypted advertising data structure. It's possible to mix encrypted and non-encrypted data, when done adding advertising data, :code:`bt encrypted-ad commit-ad` can be used to apply the change to the data to the selected advertiser. After that the advertiser can be started as described previously. It's possible to clear the advertising data by using :code:`bt encrypted-ad clear-ad`. On the Central side, it's possible to decrypt the received encrypted advertising data by setting the correct keys material as described earlier and then enabling the decrypting of the data with :code:`bt encrypted-ad decrypt-scan on`. .. note:: To see the advertising data in the scan report :code:`bt scan-verbose-output` need to be enabled. .. note:: It's possible to increase the length of the advertising data by increasing the value of :kconfig:option:`CONFIG_BT_CTLR_ADV_DATA_LEN_MAX` and :kconfig:option:`CONFIG_BT_CTLR_SCAN_DATA_LEN_MAX`. Here is a simple example demonstrating the usage of EAD: .. tabs:: .. group-tab:: Peripheral .. code-block:: console uart:~$ bt init ... uart:~$ bt adv-create conn-nscan ext-adv Created adv id: 0, adv: 0x81769a0 uart:~$ bt encrypted-ad set-keys 9ba22d3824efc70feb800c80294cba38 2e83f3d4d47695b6 session key set to: 00000000: 9b a2 2d 38 24 ef c7 0f eb 80 0c 80 29 4c ba 38 |..-8$... ....)L.8| initialisation vector set to: 00000000: 2e 83 f3 d4 d4 76 95 b6 |.....v.. | uart:~$ bt encrypted-ad add-ad 06097368656C6C uart:~$ bt encrypted-ad add-ead 03ffdead03ffbeef uart:~$ bt encrypted-ad commit-ad Advertising data for Advertiser[0] 0x81769a0 updated. uart:~$ bt adv-start Advertiser[0] 0x81769a0 set started .. group-tab:: Central .. code-block:: console uart:~$ bt init ... uart:~$ bt scan-verbose-output on uart:~$ bt encrypted-ad set-keys 9ba22d3824efc70feb800c80294cba38 2e83f3d4d47695b6 session key set to: 00000000: 9b a2 2d 38 24 ef c7 0f eb 80 0c 80 29 4c ba 38 |..-8$... ....)L.8| initialisation vector set to: 00000000: 2e 83 f3 d4 d4 76 95 b6 |.....v.. | uart:~$ bt encrypted-ad decrypt-scan on Received encrypted advertising data will now be decrypted using provided key materials. uart:~$ bt scan on Bluetooth active scan enabled [DEVICE]: 68:49:30:68:49:30 (random), AD evt type 5, RSSI -59 shell C:1 S:0 D:0 SR:0 E:1 Prim: LE 1M, Secn: LE 2M, Interval: 0x0000 (0 us), SID: 0x0 [SCAN DATA START - EXT_ADV] Type 0x09: shell Type 0x31: Encrypted Advertising Data: 0xe2, 0x17, 0xed, 0x04, 0xe7, 0x02, 0x1d, 0xc9, 0x40, 0x07, uart:~0x18, 0x90, 0x6c, 0x4b, 0xfe, 0x34, 0xad [START DECRYPTED DATA] Type 0xff: 0xde, 0xad Type 0xff: 0xbe, 0xef [END DECRYPTED DATA] [SCAN DATA END] ... Filter Accept List ****************** It's possible to create a list of allowed addresses that can be used to connect to those addresses automatically. Here is how to do it: .. code-block:: console uart:~$ bt fal-add 47:38:76:EA:29:36 random uart:~$ bt fal-add 66:C8:80:2A:05:73 random uart:~$ bt fal-connect on The shell will then connect to the first available device. In the example, if both devices are advertising at the same time, we will connect to the first address added to the list. The Filter Accept List can also be used for scanning or advertising by using the option :code:`fal`. For example, if we want to scan for a bunch of selected addresses, we can set up a Filter Accept List: .. code-block:: console uart:~$ bt fal-add 65:4B:9E:83:AF:73 random uart:~$ bt fal-add 73:72:82:B4:8F:B9 random uart:~$ bt fal-add 5D:85:50:1C:72:64 random uart:~$ bt scan on fal You should see only those three addresses reported by the scanner. Enabling security ***************** When connected to a device, you can enable multiple levels of security, here is the list for Bluetooth LE: * **1** No encryption and no authentication; * **2** Encryption and no authentication; * **3** Encryption and authentication; * **4** Bluetooth LE Secure Connection. To enable security, use the :code:`bt security <level>` command. For levels requiring authentication (level 3 and above), you must first set the authentication method. To do it, you can use the :code:`bt auth all` command. After that, when you will set the security level, you will be asked to confirm the passkey on both devices. On the shell side, do it with the command :code:`bt auth-passkey-confirm`. Pairing ======= Enabling authentication requires the devices to be bondable. By default the shell is bondable. You can make the shell not bondable using :code:`bt bondable off`. You can list all the devices you are paired with using the command :code:`bt bonds`. The maximum number of paired devices is set using :kconfig:option:`CONFIG_BT_MAX_PAIRED`. You can remove a paired device using :code:`bt clear <address: XX:XX:XX:XX:XX:XX> <type: (public|random)>` or remove all paired devices with the command :code:`bt clear all`. GATT **** The following examples assume that you have two devices already connected. To perform service discovery on the client side, use the :code:`gatt discover` command. This should print all the services that are available on the GATT server. On the server side, you can register pre-defined test services using the :code:`gatt register` command. When done, you should see the newly added services on the client side when running the discovery command. You can now subscribe to those new services on the client side. Here is an example on how to subscribe to the test service: .. code-block:: console uart:~$ gatt subscribe 26 25 Subscribed The server can now notify the client with the command :code:`gatt notify`. Another option available through the GATT command is initiating the MTU exchange. To do it, use the :code:`gatt exchange-mtu` command. To update the shell maximum MTU, you need to update Kconfig symbols in the configuration file of the shell. For more details, see :ref:`bluetooth_mtu_update_sample`. L2CAP ***** The :code:`l2cap` command exposes parts of the L2CAP API. The following example shows how to register a LE PSM, connect to it from another device and send 3 packets of 14 octets each. The example assumes that the two devices are already connected. On device A, register the LE PSM: .. code-block:: console uart:~$ l2cap register 29 L2CAP psm 41 sec_level 1 registered On device B, connect to the registered LE PSM and send data: .. code-block:: console uart:~$ l2cap connect 29 Chan sec: 1 L2CAP connection pending Channel 0x20000210 connected Channel 0x20000210 status 1 uart:~$ l2cap send 3 14 Rem 2 Rem 1 Rem 0 Outgoing data channel 0x20000210 transmitted Outgoing data channel 0x20000210 transmitted Outgoing data channel 0x20000210 transmitted On device A, you should have received the data: .. code-block:: console Incoming conn 0x20002398 Channel 0x20000210 status 1 Channel 0x20000210 connected Channel 0x20000210 requires buffer Incoming data channel 0x20000210 len 14 00000000: ff ff ff ff ff ff ff ff ff ff ff ff ff ff |........ ...... | Channel 0x20000210 requires buffer Incoming data channel 0x20000210 len 14 00000000: ff ff ff ff ff ff ff ff ff ff ff ff ff ff |........ ...... | Channel 0x20000210 requires buffer Incoming data channel 0x20000210 len 14 00000000: ff ff ff ff ff ff ff ff ff ff ff ff ff ff |........ ...... | A2DP ***** The :code:`a2dp` command exposes parts of the A2DP API. The following examples assume that you have two devices already connected. Here is a example connecting two devices: * Source and Sink sides register a2dp callbacks. using :code:`a2dp register_cb`. * Source and Sink sides register stream endpoints. using :code:`a2dp register_ep source sbc` and :code:`a2dp register_ep sink sbc`. * Source establish A2dp connection. It will create the AVDTP Signaling and Media L2CAP channels. using :code:`a2dp connect`. * Source and Sink side can discover remote device's stream endpoints. using :code:`a2dp discover_peer_eps` * Source or Sink configure the stream to create the stream after discover remote's endpoints. using :code:`a2dp configure`. * Source or Sink establish the stream. using :code:`a2dp establish`. * Source or Sink start the media. using :code:`a2dp start`. * Source test the media sending. using :code:`a2dp send_media` to send one test packet data. .. tabs:: .. group-tab:: Device A (Audio Source Side) .. code-block:: console uart:~$ a2dp register_cb success uart:~$ a2dp register_ep source sbc SBC source endpoint is registered uart:~$ a2dp connect Bonded with XX:XX:XX:XX:XX:XX Security changed: XX:XX:XX:XX:XX:XX level 2 a2dp connected uart:~$ a2dp discover_peer_eps endpoint id: 1, (sink), (idle): codec type: SBC sample frequency: 44100 48000 channel mode: Mono Stereo Joint-Stereo Block Length: 16 Subbands: 8 Allocation Method: Loudness Bitpool Range: 18 - 35 uart:~$ a2dp configure success to configure stream configured uart:~$ a2dp establish success to establish stream established uart:~$ a2dp start success to start stream started uart:~$ a2dp send_media frames num: 1, data length: 160 data: 1, 2, 3, 4, 5, 6 ...... .. group-tab:: Device B (Audio Sink Side) .. code-block:: console uart:~$ a2dp register_cb success uart:~$ a2dp register_ep sink sbc SBC sink endpoint is registered <after a2dp connect> Connected: XX:XX:XX:XX:XX:XX Bonded with XX:XX:XX:XX:XX:XX Security changed: XX:XX:XX:XX:XX:XX level 2 a2dp connected <after a2dp configure of source side> receive requesting config and accept SBC configure success sample rate 44100Hz stream configured <after a2dp establish of source side> receive requesting establishment and accept stream established <after a2dp start of source side> receive requesting start and accept stream started <after a2dp send_media of source side> received, num of frames: 1, data length: 160 data: 1, 2, 3, 4, 5, 6 ...... ... Logging ******* You can configure the logging level per module at runtime. This depends on the maximum logging level that is compiled in. To configure, use the :code:`log` command. Here are some examples: * List the available modules and their current logging level .. code-block:: console uart:~$ log status * Disable logging for *bt_hci_core* .. code-block:: console uart:~$ log disable bt_hci_core * Enable error logs for *bt_att* and *bt_smp* .. code-block:: console uart:~$ log enable err bt_att bt_smp * Disable logging for all modules .. code-block:: console uart:~$ log disable * Enable warning logs for all modules .. code-block:: console uart:~$ log enable wrn ```
/content/code_sandbox/doc/connectivity/bluetooth/bluetooth-shell.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
6,464
```restructuredtext .. _bluetooth-tools: Tools ##### This page lists and describes tools that can be used to assist during Bluetooth stack or application development in order to help, simplify and speed up the development process. .. contents:: :local: :depth: 2 .. _bluetooth-mobile-apps: Mobile applications ******************* It is often useful to make use of existing mobile applications to interact with hardware running Zephyr, to test functionality without having to write any additional code or requiring extra hardware. The recommended mobile applications for interacting with Zephyr are: * Android: * `nRF Connect for Android`_ * `nRF Mesh for Android`_ * `LightBlue for Android`_ * iOS: * `nRF Connect for iOS`_ * `nRF Mesh for iOS`_ * `LightBlue for iOS`_ .. _bluetooth_bluez: Using BlueZ with Zephyr *********************** The Linux Bluetooth Protocol Stack, BlueZ, comes with a very useful set of tools that can be used to debug and interact with Zephyr's BLE Host and Controller. In order to benefit from these tools you will need to make sure that you are running a recent version of the Linux Kernel and BlueZ: * Linux Kernel 4.10+ * BlueZ 4.45+ Additionally, some of the BlueZ tools might not be bundled by default by your Linux distribution. If you need to build BlueZ from scratch to update to a recent version or to obtain all of its tools you can follow the steps below: .. code-block:: console git clone git://git.kernel.org/pub/scm/bluetooth/bluez.git cd bluez ./bootstrap-configure --disable-android --disable-midi make You can then find :file:`btattach`, :file:`btmgt` and :file:`btproxy` in the :file:`tools/` folder and :file:`btmon` in the :file:`monitor/` folder. You'll need to enable BlueZ's experimental features so you can access its most recent BLE functionality. Do this by editing the file :file:`/lib/systemd/system/bluetooth.service` and making sure to include the :literal:`-E` option in the daemon's execution start line: .. code-block:: console ExecStart=/usr/libexec/bluetooth/bluetoothd -E Finally, reload and restart the daemon: .. code-block:: console sudo systemctl daemon-reload sudo systemctl restart bluetooth .. _bluetooth_qemu_native: Running on QEMU or native_sim ***************************** It's possible to run Bluetooth applications using either the :ref:`QEMU emulator<application_run_qemu>` or :ref:`native_sim <native_sim>`. In either case, a Bluetooth controller needs to be exported from the host OS (Linux) to the emulator. For this purpose you will need some tools described in the :ref:`bluetooth_bluez` section. Using the Host System Bluetooth Controller ========================================== The host OS's Bluetooth controller is connected in the following manner: * To the second QEMU serial line using a UNIX socket. This socket gets used with the help of the QEMU option :literal:`-serial unix:/tmp/bt-server-bredr`. This option gets passed to QEMU through :makevar:`QEMU_EXTRA_FLAGS` automatically whenever an application has enabled Bluetooth support. * To :ref:`native_sim's BT User Channel driver <nsim_bt_host_cont>` through the use of a command-line option passed to the native_sim executable: ``--bt-dev=hci0`` On the host side, BlueZ allows you to export its Bluetooth controller through a so-called user channel for QEMU and :ref:`native_sim <native_sim>` to use. .. note:: You only need to run ``btproxy`` when using QEMU. native_sim handles the UNIX socket proxying automatically If you are using QEMU, in order to make the Controller available you will need one additional step using ``btproxy``: #. Make sure that the Bluetooth controller is down #. Use the btproxy tool to open the listening UNIX socket, type: .. code-block:: console sudo tools/btproxy -u -i 0 Listening on /tmp/bt-server-bredr You might need to replace :literal:`-i 0` with the index of the Controller you wish to proxy. If you see ``Received unknown host packet type 0x00`` when running QEMU, then add :literal:`-z` to the ``btproxy`` command line to ignore any null bytes transmitted at startup. Once the hardware is connected and ready to use, you can then proceed to building and running a sample: * Choose one of the Bluetooth sample applications located in :literal:`samples/bluetooth`. * To run a Bluetooth application in QEMU, type: .. zephyr-app-commands:: :zephyr-app: samples/bluetooth/<sample> :host-os: unix :board: qemu_x86 :goals: run :compact: Running QEMU now results in a connection with the second serial line to the :literal:`bt-server-bredr` UNIX socket, letting the application access the Bluetooth controller. * To run a Bluetooth application in :ref:`native_sim <native_sim>`, first build it: .. zephyr-app-commands:: :zephyr-app: samples/bluetooth/<sample> :host-os: unix :board: native_sim :goals: build :compact: And then run it with:: $ sudo ./build/zephyr/zephyr.exe --bt-dev=hci0 Using a Zephyr-based BLE Controller =================================== Depending on which hardware you have available, you can choose between two transports when building a single-mode, Zephyr-based BLE Controller: * UART: Use the :ref:`hci_uart <bluetooth-hci-uart-sample>` sample and follow the instructions in :ref:`bluetooth-hci-uart-qemu-posix`. * USB: Use the :ref:`hci_usb <bluetooth-hci-usb-sample>` sample and then treat it as a Host System Bluetooth Controller (see previous section) .. _bluetooth-hci-tracing: HCI Tracing =========== When running the Host on a computer connected to an external Controller, it is very useful to be able to see the full log of exchanges between the two, in the format of a :ref:`bluetooth-hci` log. In order to see those logs, you can use the built-in ``btmon`` tool from BlueZ: .. code-block:: console $ btmon The output looks like this:: = New Index: 00:00:00:00:00:00 (Primary,Virtual,Control) 0.274200 = Open Index: 00:00:00:00:00:00 0.274500 < HCI Command: Reset (0x03|0x0003) plen 0 #1 0.274600 > HCI Event: Command Complete (0x0e) plen 4 #2 0.274700 Reset (0x03|0x0003) ncmd 1 Status: Success (0x00) < HCI Command: Read Local Supported Features (0x04|0x0003) plen 0 #3 0.274800 > HCI Event: Command Complete (0x0e) plen 12 #4 0.274900 Read Local Supported Features (0x04|0x0003) ncmd 1 Status: Success (0x00) Features: 0x00 0x00 0x00 0x00 0x60 0x00 0x00 0x00 BR/EDR Not Supported LE Supported (Controller) .. _bluetooth-embedded-hci-tracing: Embedded HCI tracing -------------------- When running both Host and Controller in actual Integrated Circuits, you will only see normal log messages on the console by default, without any way of accessing the HCI traffic between the Host and the Controller. However, there is a special Bluetooth logging mode that converts the console to use a binary protocol that interleaves both normal log messages as well as the HCI traffic. Set the following Kconfig options to enable this protocol before building your application: .. code-block:: cfg CONFIG_BT_DEBUG_MONITOR_UART=y CONFIG_UART_CONSOLE=n - Setting :kconfig:option:`CONFIG_BT_DEBUG_MONITOR_UART` activates the formatting - Clearing :kconfig:option:`CONFIG_UART_CONSOLE` makes the UART unavailable for the system console. E.g. for ``printk`` and the :kconfig:option:`boot banner <CONFIG_BOOT_BANNER>` To decode the binary protocol that will now be sent to the console UART you need to use the btmon tool from :ref:`BlueZ <bluetooth_bluez>`: .. code-block:: console $ btmon --tty <console TTY> --tty-speed 115200 If UART is not available (or you still want non-binary logs), you can set :kconfig:option:`CONFIG_BT_DEBUG_MONITOR_RTT` instead, which will use Segger RTT. For example, if trying to connect to a nRF52840DK with S/N 683578642: .. code-block:: console $ btmon --jlink nRF52840_xxAA,683578642 .. _bluetooth_virtual_posix: Running on a Virtual Controller and native_sim ********************************************** An alternative to a Bluetooth physical controller is the use of a virtual controller. This controller can be connected over an HCI TCP server. This TCP server must support the HCI H4 protocol. In comparison to the physical controller variant, the virtual controller allows to test a Zephyr application running on the native boards without a physical Bluetooth controller. The main use case for a virtual controller is to do Bluetooth connectivity tests without the need of Bluetooth hardware. This allows to automate Bluetooth integration tests with external applications such as a Bluetooth gateway or a mobile application. To demonstrate this functionality an example is given to interact with a virtual controller. For this purpose, the experimental python module `Bumble`_ from Google is used as it allows to create a TCP Bluetooth virtual controller and connect with the Zephyr Bluetooth host. To install bumble follow the `Bumble Getting Started Guide`_. .. note:: If your Zephyr application requires the use of the HCI LE Set extended commands, install the branch ``controller-extended-advertising`` from Bumble. Android Emulator ================= You can test the virtual controller by connecting a Bluetooth Zephyr application to the `Android Emulator`_. To connect your application to the Android Emulator follow the next steps: #. Build your Zephyr application and disable the HCI ACL flow control (i.e. ``CONFIG_BT_HCI_ACL_FLOW_CONTROL=n``) as the virtual controller from android does not support it at the moment. #. Install Android Emulator version >= 33.1.4.0. The easiest way to do this is by installing the latest `Android Studio Preview`_ version. #. Create a new Android Virtual Device (AVD) with the `Android Device Manager`_. The AVD should use at least SDK API 34. #. Run the Android Emulator via terminal as follows: ``emulator avd YOUR_AVD -packet-streamer-endpoint default`` #. Create a Bluetooth bridge between the Zephyr application and the virtual controller from Android Emulator with the `Bumble`_ utility ``hci-bridge``. ``bumble-hci-bridge tcp-server:_:1234 android-netsim`` This command will create a TCP server bridge on the local host IP address ``127.0.0.1`` and port number ``1234``. #. Run the Zephyr application and connect to the TCP server created in the last step. ``./zephyr.exe --bt-dev=127.0.0.1:1234`` After following these steps the Zephyr application will be available to the Android Emulator over the virtual Bluetooth controller that was bridged with Bumble. You can verify that the Zephyr application can communicate over Bluetooth by opening the Bluetooth settings in your AVD and scanning for your Zephyr application device. To test this you can build the Bluetooth peripheral samples such as :ref:`Peripheral HR <peripheral_hr>` or :ref:`Peripheral DIS <peripheral_dis>` .. _bluetooth_ctlr_bluez: Using Zephyr-based Controllers with BlueZ ***************************************** If you want to test a Zephyr-powered BLE Controller using BlueZ's Bluetooth Host, you will need a few tools described in the :ref:`bluetooth_bluez` section. Once you have installed the tools you can then use them to interact with your Zephyr-based controller: .. code-block:: console sudo tools/btmgmt --index 0 [hci0]# auto-power [hci0]# find -l You might need to replace :literal:`--index 0` with the index of the Controller you wish to manage. Additional information about :file:`btmgmt` can be found in its manual pages. .. _nRF Connect for Android: path_to_url .. _nRF Connect for iOS: path_to_url .. _LightBlue for Android: path_to_url .. _LightBlue for iOS: path_to_url .. _nRF Mesh for Android: path_to_url .. _nRF Mesh for iOS: path_to_url .. _Bumble: path_to_url .. _Bumble Getting Started Guide: path_to_url .. _Android Emulator: path_to_url .. _Android Device Manager: path_to_url .. _Android Studio Preview: path_to_url ```
/content/code_sandbox/doc/connectivity/bluetooth/bluetooth-tools.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,029
```restructuredtext .. _autopts-linux: AutoPTS on Linux ################ This tutorial shows how to setup AutoPTS client on Linux with AutoPTS server running on Windows 10 virtual machine. Tested with Ubuntu 20.4 and Linux Mint 20.4. You must have a Zephyr development environment set up. See :ref:`getting_started` for details. Supported methods to test zephyr bluetooth host: - Testing Zephyr Host Stack on QEMU - Testing Zephyr Host Stack on :ref:`native_sim <native_sim>` - Testing Zephyr combined (controller + host) build on Real hardware (such as nRF52) For running with QEMU or :ref:`native_sim <native_sim>`, see :ref:`bluetooth_qemu_native`. .. contents:: :local: :depth: 2 Setup Linux =========== Install nrftools (only required in the actual hardware test mode) ================================================================= Download latest nrftools (version >= 10.12.1) from site path_to_url .. image:: download_nrftools_linux.png :height: 350 :width: 600 :align: center After you extract archive, you will see 2 .deb files, e.g.: - JLink_Linux_V688a_x86_64.deb - nRF-Command-Line-Tools_10_12_1_Linux-amd64.deb and README.md. To install the tools, double click on each .deb file or follow instructions from README.md. Setup Windows 10 virtual machine ================================== Choose and install your hypervisor like VMWare Workstation(preferred) or VirtualBox. On VirtualBox could be some issues, if your host has fewer than 6 CPU. Create Windows virtual machine instance. Make sure it has at least 2 cores and installed guest extensions. Setup tested with VirtualBox 6.1.18 and VMWare Workstation 16.1.1 Pro. Update Windows --------------- Update Windows in: Start -> Settings -> Update & Security -> Windows Update Setup static IP ---------------- WMWare Works ^^^^^^^^^^^^^ On Linux, open Virtual Network Editor app and create network: .. image:: vmware_static_ip_1.png :height: 400 :width: 500 :align: center Open virtual machine network settings. Add custom adapter: .. image:: vmware_static_ip_2.png :height: 400 :width: 500 :align: center If you type 'ifconfig' in terminal, you should be able to find your host IP: .. image:: vmware_static_ip_3.png :height: 150 :width: 550 :align: center VirtualBox ^^^^^^^^^^^^^ Go to: File -> Host Network Manager and create network: .. image:: virtualbox_static_ip_1.png :height: 400 :width: 500 :align: center Open virtual machine network settings. On adapter 1 you will have created by default NAT. Add adapter 2: .. image:: virtualbox_static_ip_2.png :height: 400 :width: 500 :align: center Windows ^^^^^^^^ Setup static IP on Windows virtual machine. Go to Settings -> Network & Internet -> Ethernet -> Unidentified network -> Edit and set: .. image:: windows_static_ip.png :height: 400 :width: 400 :align: center Install Python 3 ----------------- Download and install latest `Python 3 <path_to_url`_ on Windows. Let the installer add the Python installation directory to the PATH and disable the path length limitation. .. image:: install_python1.png :height: 300 :width: 450 :align: center .. image:: install_python2.png :height: 300 :width: 450 :align: center Install Git ------------ Download and install `Git <path_to_url`_. During installation enable option: Enable experimental support for pseudo consoles. We will use Git Bash as Windows terminal. .. image:: install_git.png :height: 350 :width: 400 :align: center Install PTS 8 -------------- On Windows virtual machine, install latest PTS from path_to_url Remember to install drivers from installation directory "C:/Program Files (x86)/Bluetooth SIG/Bluetooth PTS/PTS Driver/win64/CSRBlueCoreUSB.inf" .. image:: install_pts_drivers.png :height: 250 :width: 850 :align: center .. note:: Starting with PTS 8.0.1 the Bluetooth Protocol Viewer is no longer included. So to capture Bluetooth events, you have to download it separately. Connect PTS dongle -------------------- With VirtualBox there should be no problem. Just find dongle in Devices -> USB and connect. With VMWare you might need to use some trick, if you cannot find dongle in VM -> Removable Devices. Type in Linux terminal: .. code-block:: usb-devices and find in output your PTS Bluetooth USB dongle .. image:: usb-devices_output.png :height: 100 :width: 500 :align: center Note Vendor and ProdID number. Close VMWare Workstation and open .vmx of your virtual machine (path similar to /home/codecoup/vmware/Windows 10/Windows 10.vmx) in text editor. Write anywhere in the file following line: .. code-block:: usb.autoConnect.device0 = "0x0a12:0x0001" just replace 0x0a12 with Vendor number and 0x0001 with ProdID number you found earlier. Connect devices (only required in the actual hardware test mode) ================================================================ .. image:: devices_1.png :height: 400 :width: 600 :align: center .. image:: devices_2.png :height: 700 :width: 500 :align: center Flash board (only required in the actual hardware test mode) ============================================================ On Linux, go to ~/zephyrproject. There should be already ~/zephyrproject/build directory. Flash board: .. code-block:: west flash Setup auto-pts project ======================= AutoPTS client on Linux ------------------------ Clone auto-pts project: .. code-block:: git clone path_to_url Install socat, that is used to transfer BTP data stream from UART's tty file: .. code-block:: sudo apt-get install python-setuptools socat Install required python modules: .. code-block:: cd auto-pts pip3 install --user wheel pip3 install --user -r autoptsclient_requirements.txt Autopts server on Windows virtual machine ------------------------------------------ In Git Bash, clone auto-pts project repo: .. code-block:: git clone path_to_url Install required python modules: .. code-block:: cd auto-pts pip3 install --user wheel pip3 install --user -r autoptsserver_requirements.txt Restart virtual machine. Running AutoPTS ================ Server and client by default will run on localhost address. Run server: .. code-block:: python ./autoptsserver.py .. image:: autoptsserver_run_2.png :height: 120 :width: 700 :align: center Testing Zephyr Host Stack on QEMU: .. code-block:: # A Bluetooth controller needs to be mounted. # For running with HCI UART, please visit: path_to_url#bluetooth-hci-uart python ./autoptsclient-zephyr.py "C:\Users\USER_NAME\Documents\Profile Tuning Suite\PTS_PROJECT\PTS_PROJECT.pqw6" \ ~/zephyrproject/build/zephyr/zephyr.elf -i SERVER_IP -l LOCAL_IP Testing Zephyr Host Stack on :ref:`native_sim <native_sim>`: .. code-block:: # A Bluetooth controller needs to be mounted. # For running with HCI UART, please visit: path_to_url#bluetooth-hci-uart west build -b native_sim zephyr/tests/bluetooth/tester/ -DEXTRA_CONF_FILE=overlay-native.conf sudo python ./autoptsclient-zephyr.py "C:\Users\USER_NAME\Documents\Profile Tuning Suite\PTS_PROJECT\PTS_PROJECT.pqw6" \ ~/zephyrproject/build/zephyr/zephyr.exe -i SERVER_IP -l LOCAL_IP --hci 0 Testing Zephyr combined (controller + host) build on nRF52: .. note:: If the error "ImportError: No module named pywintypes" appeared after the fresh setup, uninstall and install the pywin32 module: .. code-block:: pip install --upgrade --force-reinstall pywin32 Run client: .. code-block:: python ./autoptsclient-zephyr.py zephyr-master ~/zephyrproject/build/zephyr/zephyr.elf -t /dev/ACM0 \ -b nrf52 -l 192.168.2.1 -i 192.168.2.2 .. image:: autoptsclient_run_2.png :height: 100 :width: 800 :align: center At the first run, when Windows asks, enable connection through firewall: .. image:: allow_firewall_2.png :height: 450 :width: 600 :align: center Troubleshooting ================ - "After running one test, I need to restart my Windows virtual machine to run another, because of fail verdict from APICOM in PTS logs." It means your virtual machine has not enough processor cores or memory. Try to add more in settings. Note that a host with 4 CPUs could be not enough with VirtualBox as hypervisor. In this case, choose rather VMWare Workstation. - "I cannot start autoptsserver-zephyr.py. I always got error:" .. image:: autoptsserver_typical_error.png :height: 300 :width: 650 :align: center One or more of the following steps should help: - Close all PTS Windows. - Replug PTS bluetooth dongle. - Delete temporary workspace. You will find it in auto-pts-code/workspaces/zephyr/zephyr-master/ as temp_zephyr-master. Be careful, do not remove the original one zephyr-master.pqw6. - Restart Windows virtual machine. ```
/content/code_sandbox/doc/connectivity/bluetooth/autopts/autopts-linux.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,296
```restructuredtext .. _autopts-win10: AutoPTS on Windows 10 with nRF52 board ####################################### This tutorial shows how to setup AutoPTS client and server to run both on Windows 10. We use WSL1 with Ubuntu only to build a Zephyr project to an elf file, because Zephyr SDK is not available on Windows yet. Tutorial covers only nrf52840dk. .. contents:: :local: :depth: 2 Update Windows and drivers =========================== Update Windows in: Start -> Settings -> Update & Security -> Windows Update Update drivers, following the instructions from your hardware vendor. Install Python 3 ================= Download and install `Python 3 <path_to_url`_. Setup was tested with versions >=3.8. Let the installer add the Python installation directory to the PATH and disable the path length limitation. .. image:: install_python1.png :height: 300 :width: 450 :align: center .. image:: install_python2.png :height: 300 :width: 450 :align: center Install Git ============ Download and install `Git <path_to_url`_. During installation enable option: Enable experimental support for pseudo consoles. We will use Git Bash as Windows terminal. .. image:: install_git.png :height: 350 :width: 400 :align: center Install PTS 8 ============== Install latest PTS from path_to_url Remember to install drivers from installation directory "C:/Program Files (x86)/Bluetooth SIG/Bluetooth PTS/PTS Driver/win64/CSRBlueCoreUSB.inf" .. image:: install_pts_drivers.png :height: 250 :width: 850 :align: center .. note:: Starting with PTS 8.0.1 the Bluetooth Protocol Viewer is no longer included. So to capture Bluetooth events, you have to download it separately. Setup Zephyr project for Windows ================================= Perform Windows setup from `Getting Started Guide <path_to_url`_. Install nrftools ================= On Windows download latest nrftools (version >= 10.12.1) from site path_to_url and run default install. .. image:: download_nrftools_windows.png :height: 350 :width: 500 :align: center Connect devices ================ .. image:: devices_1.png :height: 400 :width: 600 :align: center .. image:: devices_2.png :height: 700 :width: 500 :align: center Flash board ============ In Device Manager find COM port of your nrf board. In my case it is COM3. .. image:: device_manager.png :height: 400 :width: 450 :align: center In Git Bash, go to zephyrproject .. code-block:: cd ~/zephyrproject Build the auto-pts tester app .. code-block:: west build -p auto -b nrf52840dk/nrf52840 zephyr/tests/bluetooth/tester/ You can display flashing options with: .. code-block:: west flash --help and flash board with built earlier elf file: .. code-block:: west flash --skip-rebuild --board-dir /dev/ttyS2 --elf-file ~/zephyrproject/build/zephyr/zephyr.elf Note that west does not accept COMs, so use /dev/ttyS2 as the COM3 equivalent, /dev/ttyS2 as the COM3 equivalent, etc.(/dev/ttyS + decremented COM number). Setup auto-pts project ======================= In Git Bash, clone project repo: .. code-block:: git clone path_to_url Go into the project folder: .. code-block:: cd auto-pts Install required python modules: .. code-block:: pip3 install --user wheel pip3 install --user -r autoptsserver_requirements.txt pip3 install --user -r autoptsclient_requirements.txt Install socat.exe ================== Download and extract socat.exe from path_to_url into folder ~/socat-1.7.3.2-1-x86_64/. .. image:: download_socat.png :height: 400 :width: 450 :align: center Add path to directory of socat.exe to PATH: .. image:: add_socat_to_path.png :height: 400 :width: 450 :align: center Running AutoPTS ================ Server and client by default will run on localhost address. Run server: .. code-block:: python ./autoptsserver.py -S 65000 .. image:: autoptsserver_run.png :height: 200 :width: 800 :align: center .. note:: If the error "ImportError: No module named pywintypes" appeared after the fresh setup, uninstall and install the pywin32 module: .. code-block:: pip install --upgrade --force-reinstall pywin32 Run client: .. code-block:: python ./autoptsclient-zephyr.py zephyr-master ~/zephyrproject/build/zephyr/zephyr.elf -t COM3 -b nrf52 -S 65000 -C 65001 .. image:: autoptsclient_run.png :height: 200 :width: 800 :align: center At the first run, when Windows asks, enable connection through firewall: .. image:: allow_firewall.png :height: 450 :width: 600 :align: center Troubleshooting ================ - "When running actual hardware test mode, I have only BTP TIMEOUTs." This is a problem with connection between auto-pts client and board. There are many possible causes. Try: - Clean your auto-pts and zephyr repos with .. warning:: This command will force the irreversible removal of all uncommitted files in the repo. .. code-block:: git clean -fdx then build and flash tester elf again. - If you have set up Windows on virtual machine, check if guest extensions are installed properly or change USB compatibility mode in VM settings to USB 2.0. - Check, if firewall in not blocking python.exe or socat.exe. - Check if board sends ready event after restart (hex 00 00 80 ff 00 00). Open serial connection to board with e.g. PuTTy with proper COM and baud rate. After board reset you should see some strings in console. - Check if socat.exe creates tunnel to board. Run in console .. code-block:: socat.exe -x -v tcp-listen:65123 /dev/ttyS2,raw,b115200 where /dev/ttyS2 is the COM3 equivalent. Open PuTTY, set connection type to Raw, IP to 127.0.0.1, port to 65123. After board reset you should see some strings in console. ```
/content/code_sandbox/doc/connectivity/bluetooth/autopts/autopts-win10.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,528
```xml <mxfile modified="2019-03-10T18:05:58.030Z" host="www.draw.io" agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36" version="10.4.0" etag="qj9h1H4cknFImv2OSCJO" type="device"><diagram id="6d4cab90-ed26-a4b1-f389-1cd79fba1c83" name="Page-1">3ZZtb5swEMc/DdL2olLAeeIlJVmaqZGikWovJxccsGI4apxA9ulnsHkadKrUdlLLG+7+your_sha256_hashRKtnGpCslygAmKBpX/QhSYgvehrmHPJ+2hFYf9cUh2QgeD5mQ/UnDUSk1KU1b/your_sha256_hashsam1r37Zlo896cJOIlC5BacMHsrEu/c7dSWHF6IVwaXx68W8NypfXg/Dgoy9tvlXGhXJwxUw4R/lddlLjWICsUpNxsYqDbPKKCeCn2y2guR0dqkYiZ9ExpNjDK3ExwODX0y/AREqFHxVxIf1irLl++uSBFR9K1bwjERPCrTNHRpW6DHlM01X7eNn0601rUaXidh/your_sha256_hashyour_sha256_hash_sha512_hashHNfmBP0H1+XbjKt021+VKtb5H0TrPw==</diagram></mxfile> ```
/content/code_sandbox/doc/connectivity/bluetooth/img/ble_host_layers.xml
xml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
418
```xml <mxfile userAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36" version="7.3.5" editor="www.draw.io" type="dropbox"><diagram id="f687c37f-e7c2-666e-7406-977a52d8b595" name="Page-1">7VhNc9owEP01zLSHdGwLDByBJk1nkplMObTpTdjC1kRYriwH6K/vWh/Gls2EaZ1MDoUD0ltpJb19u5YZodXu8EXgPL3nMWGjwIsPI/R5FAT+your_sha256_hashs/aqOU5IB1hHmHXR7zSWqUZnE++your_sha256_hashyour_sha256_hashWyh2Dng/NGBepGlt1MKNJBm1GtrCZ5ZYytuKMC+XX8oKWhRT8iTQsc/UBi9kcEZIczh7Qr2kDORK+I1IcYYiZEIRITzFKDIK57u9PcUXBRGNpI6ZoakKEjZaS2veJT2gYSvvpRS/TCwrIqyY5VBzFvNwoi/your_sha256_hashDPb8dj2o1HYPOsFQ9vgHiMe+your_sha256_hashAyqBclhdJkRsLuN+5swPqcAqx2bFFHVFKrqSGWdpJlPCNORhrIydmzUujT5hDy8B15zMKOPPw+eQQDqGPSUccizxkcXyXMcHVxCJ6CNk/ISruZRn4PT2Pyour_sha512_hash+your_sha256_hashP6vqpnMUEYFKnn9ib6wmFWeOAUFq4jP/your_sha256_hashh+your_sha512_hash</diagram></mxfile> ```
/content/code_sandbox/doc/connectivity/bluetooth/img/ble_cfg_single.xml
xml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
478
```xml <mxfile modified="2019-03-07T14:48:10.055Z" host="www.draw.io" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36" version="10.3.5" etag="e-D3ClfASJyunx5gBdFe" type="dropbox"><diagram id="3d368da2-d055-8685-6f25-468c73dcbdd0" name="Page-1">7Vtbcyour_sha512_hash/RgNEOpYRrDr2545lmXbfgS8meSskXY8LZjEO+your_sha256_hashour_sha512_hash/vDtEFSuM3OIXPOvwKbomW5Rbj5UavtpDNSzp1hbJ9bkuz9dIbPOGAQ/oOvK4GXo8wMAL8KsHs/ZMxpQ9hW+kVB24AZ+TYrWfhaMa/81WSyA+your_sha256_hashyour_sha256_hashyour_sha256_hash_sha512_hash+SDJ/your_sha512_hash/mJwXrti+your_sha256_hashdz8Do8Uw5OsFWsZtqRZ13XkJRKaxRPErypXUzsWcvqevBAAN0OpslCu/fW26xlEVzGI+9EXEHx6Hnz9o0jwT49f1EhznLQs+WI160zALlBcJ+your_sha256_hashatfdojAz63t61UV66ryf3a6spowh3U9mgyour_sha512_hash+DSe6your_sha512_hash/7QTfeu2sFa/AZBrtLDnTjXv5podHbzNcM1HzW47uOa735/h+R9wmK06F8K5ajdeDca5tdiny3pn3Fc1oY/+your_sha256_hashdC58srR4fT7ZteU64D/zydWFWuSTBZW3jU9+fhpe+GTFjQVyW/hkkU+azt2Oyon+iuIwfxmn0F6hvIJKA/XB/your_sha256_hashLgVDDXUstm1WyoRzo1arqKl45bbQ6vt7nvdJEut9M/HE7rGESli50IRH5MncWQH13LEoldvXPVqW/your_sha512_hash/xjdRNvhvp9KpjTXpJpL2MRVkv9agqUS2P6qRiq5vr7ekS2KG55UujidBr/bq7A54sct5b/your_sha256_hashrd9S4MFp7q9Rzq6+Ja9gYUWZJmUD8iuRDStW9/7pf68kd4CPNp+cvmDmE4ySSg8HOJrSlRz1+M6yElUO1w57Xle2xpxYmfU2f5rl7WyMMN79JLdLW5oe/9s0P</diagram></mxfile> ```
/content/code_sandbox/doc/connectivity/bluetooth/img/ble_cfg_dual.xml
xml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
748
```restructuredtext .. _bt_sdp: Service Discovery Protocol (SDP) ################################ API Reference ************** .. doxygengroup:: bt_sdp ```
/content/code_sandbox/doc/connectivity/bluetooth/api/sdp.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
32
```restructuredtext .. _bt_crypto: Cryptography ############ API Reference ************* .. doxygengroup:: bt_crypto ```
/content/code_sandbox/doc/connectivity/bluetooth/api/crypto.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
26
```restructuredtext .. _bluetooth_mesh: Bluetooth Mesh Profile ###################### The Bluetooth Mesh profile adds secure wireless multi-hop communication for Bluetooth Low Energy. This module implements the `Bluetooth Mesh Protocol Specification v1.1 <path_to_url`_. Read more about Bluetooth Mesh on the `Bluetooth SIG Website <path_to_url`_. .. toctree:: :maxdepth: 1 mesh/core.rst mesh/access.rst mesh/models.rst mesh/msg.rst mesh/sar_cfg.rst mesh/provisioning.rst mesh/proxy.rst mesh/heartbeat.rst mesh/cfg.rst mesh/statistic.rst mesh/shell.rst ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
158
```restructuredtext .. _bt_hci_drivers: HCI Drivers ########### API Reference ************* .. doxygengroup:: bt_hci_driver ```
/content/code_sandbox/doc/connectivity/bluetooth/api/hci_drivers.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
32
```restructuredtext .. _bt_uuid_api: Universal Unique Identifiers (UUIDs) ##################################### API Reference ************* .. doxygengroup:: bt_uuid ```
/content/code_sandbox/doc/connectivity/bluetooth/api/uuid.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
33
```restructuredtext .. _bt_hci_raw: HCI RAW channel ############### Overview ******** HCI RAW channel API is intended to expose HCI interface to the remote entity. The local Bluetooth controller gets owned by the remote entity and host Bluetooth stack is not used. RAW API provides direct access to packets which are sent and received by the Bluetooth HCI driver. API Reference ************* .. doxygengroup:: hci_raw ```
/content/code_sandbox/doc/connectivity/bluetooth/api/hci_raw.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
87
```restructuredtext .. _bluetooth_api: API ### Bluetooth Classic Host and profiles =================================== .. toctree:: :maxdepth: 1 hfp.rst rfcomm.rst sdp.rst Bluetooth LE Audio ================== .. toctree:: :maxdepth: 1 audio/audio.rst audio/bap.rst audio/cap.rst audio/coordinated_sets.rst audio/media.rst audio/microphone.rst audio/volume.rst audio/shell/bap.rst audio/shell/bap_broadcast_assistant.rst audio/shell/bap_scan_delegator.rst audio/shell/cap.rst audio/shell/ccp.rst audio/shell/csip.rst audio/shell/gmap.rst audio/shell/mcp.rst audio/shell/tmap.rst audio/shell/pbp.rst Bluetooth LE Host ================= .. toctree:: :maxdepth: 1 services.rst gap.rst shell/iso.rst gatt.rst att.rst Bluetooth Mesh ============== .. toctree:: :maxdepth: 1 mesh.rst Core Host and drivers ===================== .. toctree:: :maxdepth: 1 l2cap.rst connection_mgmt.rst data_buffer.rst hci_drivers.rst hci_raw.rst crypto.rst Other ===== .. toctree:: :maxdepth: 1 controller.rst uuid.rst ```
/content/code_sandbox/doc/connectivity/bluetooth/api/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
373
```restructuredtext .. _bt_hfp: Hands Free Profile (HFP) ######################## API Reference ************* .. doxygengroup:: bt_hfp ```
/content/code_sandbox/doc/connectivity/bluetooth/api/hfp.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
32
```restructuredtext .. _bluetooth_connection_mgmt: Connection Management ##################### The Zephyr Bluetooth stack uses an abstraction called :c:struct:`bt_conn` to represent connections to other devices. The internals of this struct are not exposed to the application, but a limited amount of information (such as the remote address) can be acquired using the :c:func:`bt_conn_get_info` API. Connection objects are reference counted, and the application is expected to use the :c:func:`bt_conn_ref` API whenever storing a connection pointer for a longer period of time, since this ensures that the object remains valid (even if the connection would get disconnected). Similarly the :c:func:`bt_conn_unref` API is to be used when releasing a reference to a connection. An application may track connections by registering a :c:struct:`bt_conn_cb` struct using the :c:func:`bt_conn_cb_register` or :c:macro:`BT_CONN_CB_DEFINE` APIs. This struct lets the application define callbacks for connection & disconnection events, as well as other events related to a connection such as a change in the security level or the connection parameters. When acting as a central the application will also get hold of the connection object through the return value of the :c:func:`bt_conn_le_create` API. API Reference ************* .. doxygengroup:: bt_conn ```
/content/code_sandbox/doc/connectivity/bluetooth/api/connection_mgmt.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
297
```restructuredtext .. _bt_att: Attribute Protocol (ATT) ######################## API Reference ************* .. doxygengroup:: bt_att ```
/content/code_sandbox/doc/connectivity/bluetooth/api/att.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
28
```restructuredtext .. _bt_gatt: Generic Attribute Profile (GATT) ################################ GATT layer manages the service database providing APIs for service registration and attribute declaration. Services can be registered using :c:func:`bt_gatt_service_register` API which takes the :c:struct:`bt_gatt_service` struct that provides the list of attributes the service contains. The helper macro :c:macro:`BT_GATT_SERVICE()` can be used to declare a service. Attributes can be declared using the :c:struct:`bt_gatt_attr` struct or using one of the helper macros: :c:macro:`BT_GATT_PRIMARY_SERVICE` Declares a Primary Service. :c:macro:`BT_GATT_SECONDARY_SERVICE` Declares a Secondary Service. :c:macro:`BT_GATT_INCLUDE_SERVICE` Declares a Include Service. :c:macro:`BT_GATT_CHARACTERISTIC` Declares a Characteristic. :c:macro:`BT_GATT_DESCRIPTOR` Declares a Descriptor. :c:macro:`BT_GATT_ATTRIBUTE` Declares an Attribute. :c:macro:`BT_GATT_CCC` Declares a Client Characteristic Configuration. :c:macro:`BT_GATT_CEP` Declares a Characteristic Extended Properties. :c:macro:`BT_GATT_CUD` Declares a Characteristic User Format. Each attribute contain a ``uuid``, which describes their type, a ``read`` callback, a ``write`` callback and a set of permission. Both read and write callbacks can be set to NULL if the attribute permission don't allow their respective operations. .. note:: 32-bit UUIDs are not supported in GATT. All 32-bit UUIDs shall be converted to 128-bit UUIDs when the UUID is contained in an ATT PDU. .. note:: Attribute ``read`` and ``write`` callbacks are called directly from RX Thread thus it is not recommended to block for long periods of time in them. Attribute value changes can be notified using :c:func:`bt_gatt_notify` API, alternatively there is :c:func:`bt_gatt_notify_cb` where it is possible to pass a callback to be called when it is necessary to know the exact instant when the data has been transmitted over the air. Indications are supported by :c:func:`bt_gatt_indicate` API. Client procedures can be enabled with the configuration option: :kconfig:option:`CONFIG_BT_GATT_CLIENT` Discover procedures can be initiated with the use of :c:func:`bt_gatt_discover` API which takes the :c:struct:`bt_gatt_discover_params` struct which describes the type of discovery. The parameters also serves as a filter when setting the ``uuid`` field only attributes which matches will be discovered, in contrast setting it to NULL allows all attributes to be discovered. .. note:: Caching discovered attributes is not supported. Read procedures are supported by :c:func:`bt_gatt_read` API which takes the :c:struct:`bt_gatt_read_params` struct as parameters. In the parameters one or more attributes can be set, though setting multiple handles requires the option: :kconfig:option:`CONFIG_BT_GATT_READ_MULTIPLE` Write procedures are supported by :c:func:`bt_gatt_write` API and takes :c:struct:`bt_gatt_write_params` struct as parameters. In case the write operation don't require a response :c:func:`bt_gatt_write_without_response` or :c:func:`bt_gatt_write_without_response_cb` APIs can be used, with the later working similarly to :c:func:`bt_gatt_notify_cb`. Subscriptions to notification and indication can be initiated with use of :c:func:`bt_gatt_subscribe` API which takes :c:struct:`bt_gatt_subscribe_params` as parameters. Multiple subscriptions to the same attribute are supported so there could be multiple ``notify`` callback being triggered for the same attribute. Subscriptions can be removed with use of :c:func:`bt_gatt_unsubscribe` API. .. note:: When subscriptions are removed ``notify`` callback is called with the data set to NULL. API Reference ************* .. doxygengroup:: bt_gatt GATT Server =========== .. doxygengroup:: bt_gatt_server GATT Client =========== .. doxygengroup:: bt_gatt_client ```
/content/code_sandbox/doc/connectivity/bluetooth/api/gatt.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
951
```restructuredtext .. _bluetooth_services: Bluetooth standard services ########################### Battery Service *************** .. doxygengroup:: bt_bas Heart Rate Service ****************** .. doxygengroup:: bt_hrs Immediate Alert Service *********************** .. doxygengroup:: bt_ias Object Transfer Service *********************** .. doxygengroup:: bt_ots ```
/content/code_sandbox/doc/connectivity/bluetooth/api/services.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
82
```restructuredtext .. _bt_data_buffers: Data Buffers ############# API Reference ************* .. doxygengroup:: bt_buf ```
/content/code_sandbox/doc/connectivity/bluetooth/api/data_buffer.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
28
```restructuredtext .. _bt_l2cap: Logical Link Control and Adaptation Protocol (L2CAP) #################################################### L2CAP layer enables connection-oriented channels which can be enable with the configuration option: :kconfig:option:`CONFIG_BT_L2CAP_DYNAMIC_CHANNEL`. This channels support segmentation and reassembly transparently, they also support credit based flow control making it suitable for data streams. Channels instances are represented by the :c:struct:`bt_l2cap_chan` struct which contains the callbacks in the :c:struct:`bt_l2cap_chan_ops` struct to inform when the channel has been connected, disconnected or when the encryption has changed. In addition to that it also contains the ``recv`` callback which is called whenever an incoming data has been received. Data received this way can be marked as processed by returning 0 or using :c:func:`bt_l2cap_chan_recv_complete` API if processing is asynchronous. .. note:: The ``recv`` callback is called directly from RX Thread thus it is not recommended to block for long periods of time. For sending data the :c:func:`bt_l2cap_chan_send` API can be used noting that it may block if no credits are available, and resuming as soon as more credits are available. Servers can be registered using :c:func:`bt_l2cap_server_register` API passing the :c:struct:`bt_l2cap_server` struct which informs what ``psm`` it should listen to, the required security level ``sec_level``, and the callback ``accept`` which is called to authorize incoming connection requests and allocate channel instances. Client channels can be initiated with use of :c:func:`bt_l2cap_chan_connect` API and can be disconnected with the :c:func:`bt_l2cap_chan_disconnect` API. Note that the later can also disconnect channel instances created by servers. API Reference ************* .. doxygengroup:: bt_l2cap ```
/content/code_sandbox/doc/connectivity/bluetooth/api/l2cap.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
418
```restructuredtext .. _bluetooth_controller: Bluetooth Controller #################### API Reference ************* .. doxygengroup:: bt_ctrl ```
/content/code_sandbox/doc/connectivity/bluetooth/api/controller.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
28
```restructuredtext .. _bt_rfcomm: Serial Port Emulation (RFCOMM) ############################## API Reference ************* .. doxygengroup:: bt_rfcomm ```
/content/code_sandbox/doc/connectivity/bluetooth/api/rfcomm.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
35
```restructuredtext .. _bt_gap: Generic Access Profile (GAP) ############################ API Reference ************* .. doxygengroup:: bt_gap .. doxygengroup:: bt_addr .. doxygengroup:: bt_gap_defines ```
/content/code_sandbox/doc/connectivity/bluetooth/api/gap.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
52
```restructuredtext .. _bluetooth_mesh_od_cli: On-Demand Private Proxy Client ############################## The On-Demand Private Proxy Client model is a foundation model defined by the Bluetooth Mesh specification. The model is optional, and is enabled with the :kconfig:option:`CONFIG_BT_MESH_OD_PRIV_PROXY_CLI` option. The On-Demand Private Proxy Client model was introduced in the Bluetooth Mesh Protocol Specification version 1.1, and is used to set and retrieve the On-Demand Private GATT Proxy state. The state defines how long a node will advertise Mesh Proxy Service with Private Network Identity type after it receives a Solicitation PDU. The On-Demand Private Proxy Client model communicates with an On-Demand Private Proxy Server model using the device key of the node containing the target On-Demand Private Proxy Server model instance. If present, the On-Demand Private Proxy Client model must only be instantiated on the primary element. Configurations ************** The On-Demand Private Proxy Client model behavior can be configured with the transmission timeout option :kconfig:option:`CONFIG_BT_MESH_OD_PRIV_PROXY_CLI_TIMEOUT`. The :kconfig:option:`CONFIG_BT_MESH_OD_PRIV_PROXY_CLI_TIMEOUT` controls how long the Client waits for a state response message to arrive in milliseconds. This value can be changed at runtime using :c:func:`bt_mesh_od_priv_proxy_cli_timeout_set`. API reference ************* .. doxygengroup:: bt_mesh_od_priv_proxy_cli ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/od_cli.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
307
```restructuredtext .. _bluetooth_mesh_sar_cfg_cli: SAR Configuration Client ######################## The SAR Configuration Client model is a foundation model defined by the Bluetooth Mesh specification. It is an optional model, enabled with the :kconfig:option:`CONFIG_BT_MESH_SAR_CFG_CLI` configuration option. The SAR Configuration Client model is introduced in the Bluetooth Mesh Protocol Specification version 1.1, and it supports the configuration of the lower transport layer behavior of a node that supports the :ref:`bluetooth_mesh_sar_cfg_srv` model. The model can send messages to query or change the states supported by the SAR Configuration Server (SAR Transmitter and SAR Receiver) using SAR Configuration messages. The SAR Transmitter procedure is used to determine and configure the SAR Transmitter state of a SAR Configuration Server. Function calls :c:func:`bt_mesh_sar_cfg_cli_transmitter_get` and :c:func:`bt_mesh_sar_cfg_cli_transmitter_set` are used to get and set the SAR Transmitter state of the Target node respectively. The SAR Receiver procedure is used to determine and configure the SAR Receiver state of a SAR Configuration Server. Function calls :c:func:`bt_mesh_sar_cfg_cli_receiver_get` and :c:func:`bt_mesh_sar_cfg_cli_receiver_set` are used to get and set the SAR Receiver state of the Target node respectively. For more information about the two states, see :ref:`bt_mesh_sar_cfg_states`. An element can send any SAR Configuration Client message at any time to query or change the states supported by the SAR Configuration Server model of a peer node. The SAR Configuration Client model only accepts messages encrypted with the device key of the node supporting the SAR Configuration Server model. If present, the SAR Configuration Client model must only be instantiated on the primary element. API reference ************* .. doxygengroup:: bt_mesh_sar_cfg_cli ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/sar_cfg_cli.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
400
```restructuredtext .. _bluetooth_mesh_blob_cli: BLOB Transfer Client #################### The Binary Large Object (BLOB) Transfer Client is the sender of the BLOB transfer. It supports sending BLOBs of any size to any number of Target nodes, in both Push BLOB Transfer Mode and Pull BLOB Transfer Mode. Usage ***** Initialization ============== The BLOB Transfer Client is instantiated on an element with a set of event handler callbacks: .. code-block:: C static const struct bt_mesh_blob_cli_cb blob_cb = { /* Callbacks */ }; static struct bt_mesh_blob_cli blob_cli = { .cb = &blob_cb, }; static const struct bt_mesh_model models[] = { BT_MESH_MODEL_BLOB_CLI(&blob_cli), }; Transfer context ================ Both the transfer capabilities retrieval procedure and the BLOB transfer uses an instance of a :c:struct:`bt_mesh_blob_cli_inputs` to determine how to perform the transfer. The BLOB Transfer Client Inputs structure must at least be initialized with a list of targets, an application key and a time to live (TTL) value before it is used in a procedure: .. code-block:: c static struct bt_mesh_blob_target targets[3] = { { .addr = 0x0001 }, { .addr = 0x0002 }, { .addr = 0x0003 }, }; static struct bt_mesh_blob_cli_inputs inputs = { .app_idx = MY_APP_IDX, .ttl = BT_MESH_TTL_DEFAULT, }; sys_slist_init(&inputs.targets); sys_slist_append(&inputs.targets, &targets[0].n); sys_slist_append(&inputs.targets, &targets[1].n); sys_slist_append(&inputs.targets, &targets[2].n); Note that all BLOB Transfer Servers in the transfer must be bound to the chosen application key. Group address ------------- The application may additionally specify a group address in the context structure. If the group is not :c:macro:`BT_MESH_ADDR_UNASSIGNED`, the messages in the transfer will be sent to the group address, instead of being sent individually to each Target node. Mesh Manager must ensure that all Target nodes having the BLOB Transfer Server model subscribe to this group address. Using group addresses for transferring the BLOBs can generally increase the transfer speed, as the BLOB Transfer Client sends each message to all Target nodes at the same time. However, sending large, segmented messages to group addresses in Bluetooth Mesh is generally less reliable than sending them to unicast addresses, as there is no transport layer acknowledgment mechanism for groups. This can lead to longer recovery periods at the end of each block, and increases the risk of losing Target nodes. Using group addresses for BLOB transfers will generally only pay off if the list of Target nodes is extensive, and the effectiveness of each addressing strategy will vary heavily between different deployments and the size of the chunks. Transfer timeout ---------------- If a Target node fails to respond to an acknowledged message within the BLOB Transfer Client's time limit, the Target node is dropped from the transfer. The application can reduce the chances of this by giving the BLOB Transfer Client extra time through the context structure. The extra time may be set in 10-second increments, up to 182 hours, in addition to the base time of 20 seconds. The wait time scales automatically with the transfer TTL. Note that the BLOB Transfer Client only moves forward with the transfer in following cases: * All Target nodes have responded. * A node has been removed from the list of Target nodes. * The BLOB Transfer Client times out. Increasing the wait time will increase this delay. BLOB transfer capabilities retrieval ==================================== It is generally recommended to retrieve BLOB transfer capabilities before starting a transfer. The procedure populates the transfer capabilities from all Target nodes with the most liberal set of parameters that allows all Target nodes to participate in the transfer. Any Target nodes that fail to respond, or respond with incompatible transfer parameters, will be dropped. Target nodes are prioritized according to their order in the list of Target nodes. If a Target node is found to be incompatible with any of the previous Target nodes, for instance by reporting a non-overlapping block size range, it will be dropped. Lost Target nodes will be reported through the :c:member:`lost_target <bt_mesh_blob_cli_cb.lost_target>` callback. The end of the procedure is signalled through the :c:member:`caps <bt_mesh_blob_cli_cb.caps>` callback, and the resulting capabilities can be used to determine the block and chunk sizes required for the BLOB transfer. BLOB transfer ============= The BLOB transfer is started by calling :c:func:`bt_mesh_blob_cli_send` function, which (in addition to the aforementioned transfer inputs) requires a set of transfer parameters and a BLOB stream instance. The transfer parameters include the 64-bit BLOB ID, the BLOB size, the transfer mode, the block size in logarithmic representation and the chunk size. The BLOB ID is application defined, but must match the BLOB ID the BLOB Transfer Servers have been started with. The transfer runs until it either completes successfully for at least one Target node, or it is cancelled. The end of the transfer is communicated to the application through the :c:member:`end <bt_mesh_blob_cli_cb.end>` callback. Lost Target nodes will be reported through the :c:member:`lost_target <bt_mesh_blob_cli_cb.lost_target>` callback. API reference ************* .. doxygengroup:: bt_mesh_blob_cli ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/blob_cli.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,196
```restructuredtext .. _bluetooth_mesh_models_cfg_cli: Configuration Client #################### The Configuration Client model is a foundation model defined by the Bluetooth Mesh specification. It provides functionality for configuring most parameters of a mesh node, including encryption keys, model configuration and feature enabling. The Configuration Client model communicates with a :ref:`bluetooth_mesh_models_cfg_srv` model using the device key of the target node. The Configuration Client model may communicate with servers on other nodes or self-configure through the local Configuration Server model. All configuration functions in the Configuration Client API have ``net_idx`` and ``addr`` as their first parameters. These should be set to the network index and primary unicast address that the target node was provisioned with. The Configuration Client model is optional, and it must only be instantiated on the primary element if present in the Composition Data. API reference ************* .. doxygengroup:: bt_mesh_cfg_cli ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/cfg_cli.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
197
```restructuredtext .. _bluetooth_mesh_sar_cfg_srv: SAR Configuration Server ######################## The SAR Configuration Server model is a foundation model defined by the Bluetooth Mesh specification. It is an optional model, enabled with the :kconfig:option:`CONFIG_BT_MESH_SAR_CFG_SRV` configuration option. The SAR Configuration Server model is introduced in the Bluetooth Mesh Protocol Specification version 1.1, and it supports the configuration of the :ref:`segmentation and reassembly (SAR) <bluetooth_mesh_sar_cfg>` behavior of a Bluetooth Mesh node. The model defines a set of states and messages for the SAR configuration. The SAR Configuration Server model defines two states, SAR Transmitter state and SAR Receiver state. For more information about the two states, see :ref:`bt_mesh_sar_cfg_states`. The model also supports the SAR Transmitter and SAR Receiver get and set messages. The SAR Configuration Server model does not have an API of its own, but relies on a :ref:`bluetooth_mesh_sar_cfg_cli` to control it. The SAR Configuration Server model only accepts messages encrypted with the nodes device key. If present, the SAR Configuration Server model must only be instantiated on the primary element. API reference ************* .. doxygengroup:: bt_mesh_sar_cfg_srv ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/sar_cfg_srv.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
271
```restructuredtext .. _bluetooth_mesh_models_health_srv: Health Server ############# The Health Server model provides attention callbacks and node diagnostics for :ref:`bluetooth_mesh_models_health_cli` models. It is primarily used to report faults in the mesh node and map the mesh nodes to their physical location. If present, the Health Server model must be instantiated on the primary element. Faults ****** The Health Server model may report a list of faults that have occurred in the device's lifetime. Typically, the faults are events or conditions that may alter the behavior of the node, like power outages or faulty peripherals. Faults are split into warnings and errors. Warnings indicate conditions that are close to the limits of what the node is designed to withstand, but not necessarily damaging to the device. Errors indicate conditions that are outside of the node's design limits, and may have caused invalid behavior or permanent damage to the device. Fault values ``0x01`` to ``0x7f`` are reserved for the Bluetooth Mesh specification, and the full list of specification defined faults are available in :ref:`bluetooth_mesh_health_faults`. Fault values ``0x80`` to ``0xff`` are vendor specific. The list of faults are always reported with a company ID to help interpreting the vendor specific faults. .. _bluetooth_mesh_models_health_srv_attention: Attention state *************** The attention state is used to make the device call attention to itself through some physical behavior like blinking, playing a sound or vibrating. The attention state may be used during provisioning to let the user know which device they're provisioning, as well as through the Health models at runtime. The attention state is always assigned a timeout in the range of one to 255 seconds when enabled. The Health Server API provides two callbacks for the application to run their attention calling behavior: :c:member:`bt_mesh_health_srv_cb.attn_on` is called at the beginning of the attention period, :c:member:`bt_mesh_health_srv_cb.attn_off` is called at the end. The remaining time for the attention period may be queried through :c:member:`bt_mesh_health_srv.attn_timer`. API reference ************* .. doxygengroup:: bt_mesh_health_srv .. _bluetooth_mesh_health_faults: Health faults ============= Fault values defined by the Bluetooth Mesh specification. .. doxygengroup:: bt_mesh_health_faults ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/health_srv.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
510
```restructuredtext .. _bluetooth_mesh_dfu_srv: Firmware Update Server ###################### The Firmware Update Server model implements the Target node functionality of the :ref:`bluetooth_mesh_dfu` subsystem. It extends the :ref:`bluetooth_mesh_blob_srv`, which it uses to receive the firmware image binary from the Distributor node. Together with the extended BLOB Transfer Server model, the Firmware Update Server model implements all the required functionality for receiving firmware updates over the mesh network, but does not provide any functionality for storing, applying or verifying the images. Firmware images *************** The Firmware Update Server holds a list of all the updatable firmware images on the device. The full list shall be passed to the server through the ``_imgs`` parameter in :c:macro:`BT_MESH_DFU_SRV_INIT`, and must be populated before the Bluetooth Mesh subsystem is started. Each firmware image in the image list must be independently updatable, and should have its own firmware ID. For instance, a device with an upgradable bootloader, an application and a peripheral chip with firmware update capabilities could have three entries in the firmware image list, each with their own separate firmware ID. Receiving transfers ******************* The Firmware Update Server model uses a BLOB Transfer Server model on the same element to transfer the binary image. The interaction between the Firmware Update Server, BLOB Transfer Server and application is described below: .. figure:: images/dfu_srv.svg :align: center :alt: Bluetooth Mesh Firmware Update Server transfer Bluetooth Mesh Firmware Update Server transfer Transfer check ============== The transfer check is an optional pre-transfer check the application can perform on incoming firmware image metadata. The Firmware Update Server performs the transfer check by calling the :c:member:`check <bt_mesh_dfu_srv_cb.check>` callback. The result of the transfer check is a pass/fail status return and the expected :c:enum:`bt_mesh_dfu_effect`. The DFU effect return parameter will be communicated back to the Distributor, and should indicate what effect the firmware update will have on the mesh state of the device. .. _bluetooth_mesh_dfu_srv_comp_data_and_models_metadata: Composition Data and Models Metadata ------------------------------------ If the transfer will cause the device to change its Composition Data or become unprovisioned, this should be communicated through the effect parameter of the metadata check. When the transfer will cause the Composition Data to change, and the :ref:`bluetooth_mesh_models_rpr_srv` is supported, the Composition Data of the new firmware image will be represented by Composition Data Pages 128, 129, and 130. The Models Metadata of the new firmware image will be represented by Models Metadata Page 128. Composition Data Pages 0, 1 and 2, and Models Metadata Page 0, will represent the Composition Data and the Models Metadata of the old firmware image until the device is reprovisioned with Node Provisioning Protocol Interface (NPPI) procedures using the :ref:`bluetooth_mesh_models_rpr_cli`. The application must call functions :c:func:`bt_mesh_comp_change_prepare` and :c:func:`bt_mesh_models_metadata_change_prepare` to store the existing Composition Data and Models Metadata pages before booting into the firmware with the updated Composition Data and Models Metadata. The old Composition Data will then be loaded into Composition Data Pages 0, 1 and 2, while the Composition Data in the new firmware will be loaded into Composition Data Pages 128, 129 and 130. The Models Metadata for the old image will be loaded into Models Metadata Page 0, and the Models Metadata for the new image will be loaded into Models Metadata Page 128. Limitation: * It is not possible to change the Composition Data of the device and keep the device provisioned and working with the old firmware after the new firmware image is applied. Start ===== The Start procedure prepares the application for the incoming transfer. It'll contain information about which image is being updated, as well as the update metadata. The Firmware Update Server :c:member:`start <bt_mesh_dfu_srv_cb.start>` callback must return a pointer to the BLOB Writer the BLOB Transfer Server will send the BLOB to. BLOB transfer ============= After the setup stage, the Firmware Update Server prepares the BLOB Transfer Server for the incoming transfer. The entire firmware image is transferred to the BLOB Transfer Server, which passes the image to its assigned BLOB Writer. At the end of the BLOB transfer, the Firmware Update Server calls its :c:member:`end <bt_mesh_dfu_srv_cb.end>` callback. Image verification ================== After the BLOB transfer has finished, the application should verify the image in any way it can to ensure that it is ready for being applied. Once the image has been verified, the application calls :c:func:`bt_mesh_dfu_srv_verified`. If the image can't be verified, the application calls :c:func:`bt_mesh_dfu_srv_rejected`. Applying the image ================== Finally, if the image was verified, the Distributor may instruct the Firmware Update Server to apply the transfer. This is communicated to the application through the :c:member:`apply <bt_mesh_dfu_srv_cb.apply>` callback. The application should swap the image and start running with the new firmware. The firmware image table should be updated to reflect the new firmware ID of the updated image. When the transfer applies to the mesh application itself, the device might have to reboot as part of the swap. This restart can be performed from inside the apply callback, or done asynchronously. After booting up with the new firmware, the firmware image table should be updated before the Bluetooth Mesh subsystem is started. The Distributor will read out the firmware image table to confirm that the transfer was successfully applied. If the metadata check indicated that the device would become unprovisioned, the Target node is not required to respond to this check. API reference ************* .. doxygengroup:: bt_mesh_dfu_srv ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/dfu_srv.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,282
```restructuredtext .. _bluetooth_mesh_models_op_agg_cli: Opcodes Aggregator Client ######################### The Opcodes Aggregator Client model is a foundation model defined by the Bluetooth Mesh specification. It is an optional model, enabled with the :kconfig:option:`CONFIG_BT_MESH_OP_AGG_CLI` option. The Opcodes Aggregator Client model is introduced in the Bluetooth Mesh Protocol Specification version 1.1, and is used to support the functionality of dispatching a sequence of access layer messages to nodes supporting the :ref:`bluetooth_mesh_models_op_agg_srv` model. The Opcodes Aggregator Client model communicates with an Opcodes Aggregator Server model using the device key of the target node or the application keys configured by the Configuration Client. If present, the Opcodes Aggregator Client model must only be instantiated on the primary element. The Opcodes Aggregator Client model is implicitly bound to the device key on initialization. It should be bound to the same application keys as the client models that are used to produce the sequence of messages. To be able to aggregate a message from a client model, it should support an asynchronous API, for example through callbacks. API reference ************* .. doxygengroup:: bt_mesh_op_agg_cli ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/op_agg_cli.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
259
```restructuredtext .. _bluetooth_mesh_blob_flash: BLOB Flash ########## The BLOB Flash Readers and Writers implement BLOB reading to and writing from flash partitions defined in the :ref:`flash map <flash_map_api>`. BLOB Flash Reader ***************** The BLOB Flash Reader interacts with the BLOB Transfer Client to read BLOB data directly from flash. It must be initialized by calling :c:func:`bt_mesh_blob_flash_rd_init` before being passed to the BLOB Transfer Client. Each BLOB Flash Reader only supports one transfer at the time. BLOB Flash Writer ***************** The BLOB Flash Writer interacts with the BLOB Transfer Server to write BLOB data directly to flash. It must be initialized by calling :c:func:`bt_mesh_blob_flash_rd_init` before being passed to the BLOB Transfer Server. Each BLOB Flash Writer only supports one transfer at the time, and requires a block size that is a multiple of the flash page size. If a transfer is started with a block size lower than the flash page size, the transfer will be rejected. The BLOB Flash Writer copies chunk data into a buffer to accommodate chunks that are unaligned with the flash write block size. The buffer data is padded with ``0xff`` if either the start or length of the chunk is unaligned. API Reference ************* .. doxygengroup:: bt_mesh_blob_io_flash ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/blob_flash.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
294
```restructuredtext .. _bluetooth_mesh_lcd_srv: Large Composition Data Server ############################# The Large Composition Data Server model is a foundation model defined by the Bluetooth Mesh specification. The model is optional, and is enabled through the :kconfig:option:`CONFIG_BT_MESH_LARGE_COMP_DATA_SRV` option. The Large Composition Data Server model was introduced in the Bluetooth Mesh Protocol Specification version 1.1, and is used to support the functionality of exposing pages of Composition Data that do not fit in a Config Composition Data Status message and to expose metadata of the model instances. The Large Composition Data Server does not have an API of its own and relies on a :ref:`bluetooth_mesh_lcd_cli` to control it. The model only accepts messages encrypted with the node's device key. If present, the Large Composition Data Server model must only be instantiated on the primary element. Models metadata =============== The Large Composition Data Server model allows each model to have a list of model's specific metadata that can be read by the Large Composition Data Client model. The metadata list can be associated with the :c:struct:`bt_mesh_model` through the :c:member:`bt_mesh_model.metadata` field. The metadata list consists of one or more entries defined by the :c:struct:`bt_mesh_models_metadata_entry` structure. Each entry contains the length and ID of the metadata, and a pointer to the raw data. Entries can be created using the :c:macro:`BT_MESH_MODELS_METADATA_ENTRY` macro. The :c:macro:`BT_MESH_MODELS_METADATA_END` macro marks the end of the metadata list and must always be present. If the model has no metadata, the helper macro :c:macro:`BT_MESH_MODELS_METADATA_NONE` can be used instead. API reference ************* .. doxygengroup:: bt_mesh_large_comp_data_srv ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/lcd_srv.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
391
```restructuredtext .. _bluetooth_mesh_dfu: Device Firmware Update (DFU) ############################ Bluetooth Mesh supports the distribution of firmware images across a mesh network. The Bluetooth mesh DFU subsystem implements the Bluetooth Mesh Device Firmware Update Model specification version 1.0. Bluetooth Mesh DFU implements a distribution mechanism for firmware images, and does not put any restrictions on the size, format or usage of the images. The primary design goal of the subsystem is to provide the qualifiable parts of the Bluetooth Mesh DFU specification, and leave the usage, firmware validation and deployment to the application. The DFU specification is implemented in the Zephyr Bluetooth Mesh DFU subsystem as three separate models: .. toctree:: :maxdepth: 1 dfu_srv dfu_cli dfd_srv Overview ******** DFU roles ========= The Bluetooth Mesh DFU subsystem defines three different roles the mesh nodes have to assume in the distribution of firmware images: Target node Target node is the receiver and user of the transferred firmware images. All its functionality is implemented by the :ref:`bluetooth_mesh_dfu_srv` model. A transfer may be targeting any number of Target nodes, and they will all be updated concurrently. Distributor The Distributor role serves two purposes in the DFU process. First, it's acting as the Target node in the Upload Firmware procedure, then it distributes the uploaded image to other Target nodes as the Distributor. The Distributor does not select the parameters of the transfer, but relies on an Initiator to give it a list of Target nodes and transfer parameters. The Distributor functionality is implemented in two models, :ref:`bluetooth_mesh_dfd_srv` and :ref:`bluetooth_mesh_dfu_cli`. The :ref:`bluetooth_mesh_dfd_srv` is responsible for communicating with the Initiator, and the :ref:`bluetooth_mesh_dfu_cli` is responsible for distributing the image to the Target nodes. Initiator The Initiator role is typically implemented by the same device that implements the Bluetooth Mesh :ref:`Provisioner <bluetooth_mesh_provisioning>` and :ref:`Configurator <bluetooth_mesh_models_cfg_cli>` roles. The Initiator needs a full overview of the potential Target nodes and their firmware, and will control (and initiate) all firmware updates. The Initiator role is not implemented in the Zephyr Bluetooth Mesh DFU subsystem. .. figure:: images/dfu_roles_mesh.svg :align: center :alt: Graphic overview of the DFU roles mesh nodes can have during the process of image distribution DFU roles and the associated Bluetooth Mesh models Bluetooth Mesh applications may combine the DFU roles in any way they'd like, and even take on multiple instances of the same role by instantiating the models on separate elements. For instance, the Distributor and Initiator role can be combined by instantiating the :ref:`bluetooth_mesh_dfu_cli` on the Initiator node and calling its API directly. It's also possible to combine the Initiator and Distributor devices into a single device, and replace the Firmware Distribution Server model with a proprietary mechanism that will access the Firmware Update Client model directly, e.g. over a serial protocol. .. note:: All DFU models instantiate one or more :ref:`bluetooth_mesh_blob`, and may need to be spread over multiple elements for certain role combinations. Stages ====== The Bluetooth Mesh DFU process is designed to act in three stages: Upload stage First, the image is uploaded to a Distributor in a mesh network by an external entity, such as a phone or gateway (the Initiator). During the Upload stage, the Initiator transfers the firmware image and all its metadata to the Distributor node inside the mesh network. The Distributor stores the firmware image and its metadata persistently, and awaits further instructions from the Initiator. The time required to complete the upload process depends on the size of the image. After the upload completes, the Initiator can disconnect from the network during the much more time-consuming Distribution stage. Once the firmware has been uploaded to the Distributor, the Initiator may trigger the Distribution stage at any time. Firmware Capability Check stage (optional) Before starting the Distribution stage, the Initiator may optionally check if Target nodes can accept the new firmware. Nodes that do not respond, or respond that they can't receive the new firmware, are excluded from the firmware distribution process. Distribution stage Before the firmware image can be distributed, the Initiator transfers the list of Target nodes and their designated firmware image index to the Distributor. Next, it tells the Distributor to start the firmware distributon process, which runs in the background while the Initiator and the mesh network perform other duties. Once the firmware image has been transferred to the Target nodes, the Distributor may ask them to apply the firmware image immediately and report back with their status and new firmware IDs. Firmware images =============== All updatable parts of a mesh node's firmware should be represented as a firmware image. Each Target node holds a list of firmware images, each of which should be independently updatable and identifiable. Firmware images are represented as a BLOB (the firmware itself) with the following additional information attached to it: Firmware ID The firmware ID is used to identify a firmware image. The Initiator node may ask the Target nodes for a list of its current firmware IDs to determine whether a newer version of the firmware is available. The format of the firmware ID is vendor specific, but generally, it should include enough information for an Initiator node with knowledge of the format to determine the type of image as well as its version. The firmware ID is optional, and its max length is determined by :kconfig:option:`CONFIG_BT_MESH_DFU_FWID_MAXLEN`. Firmware metadata The firmware metadata is used by the Target node to determine whether it should accept an incoming firmware update, and what the effect of the update would be. The metadata format is vendor specific, and should contain all information the Target node needs to verify the image, as well as any preparation the Target node has to make before the image is applied. Typical metadata information can be image signatures, changes to the node's Composition Data and the format of the BLOB. The Target node may perform a metadata check before accepting incoming transfers to determine whether the transfer should be started. The firmware metadata can be discarded by the Target node after the metadata check, as other nodes will never request the metadata from the Target node. The firmware metadata is optional, and its maximum length is determined by :kconfig:option:`CONFIG_BT_MESH_DFU_METADATA_MAXLEN`. The Bluetooth Mesh DFU subsystem in Zephyr provides its own metadata format (:c:struct:`bt_mesh_dfu_metadata`) together with a set of related functions that can be used by an end product. The support for it is enabled using the :kconfig:option:`CONFIG_BT_MESH_DFU_METADATA` option. The format of the metadata is presented in the table below. +------------------------+--------------+----------------------------------------+ | Field | Size (Bytes) | Description | +========================+==============+========================================+ | New firmware version | 8 B | 1 B: Major version | | | | 1 B: Minor version | | | | 2 B: Revision | | | | 4 B: Build number | +------------------------+--------------+----------------------------------------+ | New firmware size | 3 B | Size in bytes for a new firmware | +------------------------+--------------+----------------------------------------+ | New firmware core type | 1 B | Bit field: | | | | Bit 0: Application core | | | | Bit 1: Network core | | | | Bit 2: Applications specific BLOB. | | | | Other bits: RFU | +------------------------+--------------+----------------------------------------+ | Hash of incoming | 4 B | Lower 4 octets of AES-CMAC | | composition data | (Optional) | (app-specific-key, composition data). | | | | This field is present, if Bit 0 is set | | | | in the New firmware core type field. | +------------------------+--------------+----------------------------------------+ | New number of elements | 2 B | Number of elements on the node | | | (Optional) | after firmware is applied. | | | | This field is present, if Bit 0 is set | | | | in the New firmware core type field. | +------------------------+--------------+----------------------------------------+ | Application-specific | <variable> | Application-specific data to allow | | data for new firmware | (Optional) | application to execute some | | | | vendor-specific behaviors using | | | | this data before it can respond | | | | with a status message. | +------------------------+--------------+----------------------------------------+ .. note:: The AES-CMAC algorithm serves as a hashing function with a fixed key and is not used for encryption in Bluetooth Mesh DFU metadata. The resulting hash is not secure since the key is known. Firmware URI The firmware URI gives the Initiator information about where firmware updates for the image can be found. The URI points to an online resource the Initiator can interact with to get new versions of the firmware. This allows Initiators to perform updates for any node in the mesh network by interacting with the web server pointed to in the URI. The URI must point to a resource using the ``http`` or ``https`` schemes, and the targeted web server must behave according to the Firmware Check Over HTTPS procedure defined by the specification. The firmware URI is optional, and its max length is determined by :kconfig:option:`CONFIG_BT_MESH_DFU_URI_MAXLEN`. .. note:: The out-of-band distribution mechanism is not supported. .. _bluetooth_mesh_dfu_firmware_effect: Firmware effect --------------- A new image may have the Composition Data Page 0 different from the one allocated on a Target node. This may have an effect on the provisioning data of the node and how the Distributor finalizes the DFU. Depending on the availability of the Remote Provisioning Server model on the old and new image, the device may either boot up unprovisioned after applying the new firmware or require to be re-provisioned. The complete list of available options is defined in :c:enum:`bt_mesh_dfu_effect`: :c:enumerator:`BT_MESH_DFU_EFFECT_NONE` The device stays provisioned after the new firmware is programmed. This effect is chosen if the composition data of the new firmware doesn't change. :c:enumerator:`BT_MESH_DFU_EFFECT_COMP_CHANGE_NO_RPR` This effect is chosen when the composition data changes and the device doesn't support the remote provisioning. The new composition data takes place only after re-provisioning. :c:enumerator:`BT_MESH_DFU_EFFECT_COMP_CHANGE` This effect is chosen when the composition data changes and the device supports the remote provisioning. In this case, the device stays provisioned and the new composition data takes place after re-provisioning using the Remote Provisioning models. :c:enumerator:`BT_MESH_DFU_EFFECT_UNPROV` This effect is chosen if the composition data in the new firmware changes, the device doesn't support the remote provisioning, and the new composition data takes effect after applying the firmware. When the Target node receives the Firmware Update Firmware Metadata Check message, the Firmware Update Server model calls the :c:member:`bt_mesh_dfu_srv_cb.check` callback, the application can then process the metadata and provide the effect value. If the effect is :c:enumerator:`BT_MESH_DFU_EFFECT_COMP_CHANGE`, the application must call functions :c:func:`bt_mesh_comp_change_prepare` and :c:func:`bt_mesh_models_metadata_change_prepare` to prepare the Composition Data Page and Models Metadata Page contents before applying the new firmware image. See :ref:`bluetooth_mesh_dfu_srv_comp_data_and_models_metadata` for more information. DFU procedures ************** The DFU protocol is implemented as a set of procedures that must be performed in a certain order. The Initiator controls the Upload stage of the DFU protocol, and all Distributor side handling of the upload subprocedures is implemented in the :ref:`bluetooth_mesh_dfd_srv`. The Distribution stage is controlled by the Distributor, as implemented by the :ref:`bluetooth_mesh_dfu_cli`. The Target node implements all handling of these procedures in the :ref:`bluetooth_mesh_dfu_srv`, and notifies the application through a set of callbacks. .. figure:: images/dfu_stages_procedures_mesh.svg :align: center :alt: Overview of DFU stages and procedures DFU stages and procedures as seen from the Distributor Uploading the firmware ====================== The Upload Firmware procedure uses the :ref:`bluetooth_mesh_blob` to transfer the firmware image from the Initiator to the Distributor. The Upload Firmware procedure works in two steps: 1. The Initiator generates a BLOB ID, and sends it to the Distributor's Firmware Distribution Server along with the firmware information and other input parameters of the BLOB transfer. The Firmware Distribution Server stores the information, and prepares its BLOB Transfer Server for the incoming transfer before it responds with a status message to the Initiator. #. The Initiator's BLOB Transfer Client model transfers the firmware image to the Distributor's BLOB Transfer Server, which stores the image in a predetermined flash partition. When the BLOB transfer finishes, the firmware image is ready for distribution. The Initiator may upload several firmware images to the Distributor, and ask it to distribute them in any order or at any time. Additional procedures are available for querying and deleting firmware images from the Distributor. The following Distributor's capabilities related to firmware images can be configured using the configuration options: * :kconfig:option:`CONFIG_BT_MESH_DFU_SLOT_CNT`: Amount of image slots available on the device. * :kconfig:option:`CONFIG_BT_MESH_DFD_SRV_SLOT_MAX_SIZE`: Maximum allowed size for each image. * :kconfig:option:`CONFIG_BT_MESH_DFD_SRV_SLOT_SPACE`: Available space for all images. Populating the Distributor's receivers list =========================================== Before the Distributor can start distributing the firmware image, it needs a list of Target nodes to send the image to. The Initiator gets the full list of Target nodes either by querying the potential targets directly, or through some external authority. The Initiator uses this information to populate the Distributor's receivers list with the address and relevant firmware image index of each Target node. The Initiator may send one or more Firmware Distribution Receivers Add messages to build the Distributor's receivers list, and a Firmware Distribution Receivers Delete All message to clear it. The maximum number of receivers that can be added to the Distributor is configured through the :kconfig:option:`CONFIG_BT_MESH_DFD_SRV_TARGETS_MAX` configuration option. Initiating the distribution =========================== Once the Distributor has stored a firmware image and received a list of Target nodes, the Initiator may initiate the distribution procedure. The BLOB transfer parameters for the distribution are passed to the Distributor along with an update policy. The update policy decides whether the Distributor should request that the firmware is applied on the Target nodes or not. The Distributor stores the transfer parameters and starts distributing the firmware image to its list of Target nodes. Firmware distribution --------------------- The Distributor's Firmware Update Client model uses its BLOB Transfer Client model's broadcast subsystem to communicate with all Target nodes. The firmware distribution is performed with the following steps: 1. The Distributor's Firmware Update Client model generates a BLOB ID and sends it to each Target node's Firmware Update Server model, along with the other BLOB transfer parameters, the Target node firmware image index and the firmware image metadata. Each Target node performs a metadata check and prepares their BLOB Transfer Server model for the transfer, before sending a status response to the Firmware Update Client, indicating if the firmware update will have any effect on the Bluetooth Mesh state of the node. #. The Distributor's BLOB Transfer Client model transfers the firmware image to all Target nodes. #. Once the BLOB transfer has been received, the Target nodes' applications verify that the firmware is valid by performing checks such as signature verification or image checksums against the image metadata. #. The Distributor's Firmware Update Client model queries all Target nodes to ensure that they've all verified the firmware image. If the distribution procedure completed with at least one Target node reporting that the image has been received and verified, the distribution procedure is considered successful. .. note:: The firmware distribution procedure only fails if *all* Target nodes are lost. It is up to the Initiator to request a list of failed Target nodes from the Distributor and initiate additional attempts to update the lost Target nodes after the current attempt is finished. Suspending the distribution --------------------------- The Initiator can also request the Distributor to suspend the firmware distribution. In this case, the Distributor will stop sending any messages to Target nodes. When the firmware distribution is resumed, the Distributor will continue sending the firmware from the last successfully transferred block. Applying the firmware image =========================== If the Initiator requested it, the Distributor can initiate the Apply Firmware on Target Node procedure on all Target nodes that successfully received and verified the firmware image. The Apply Firmware on Target Node procedure takes no parameters, and to avoid ambiguity, it should be performed before a new transfer is initiated. The Apply Firmware on Target Node procedure consists of the following steps: 1. The Distributor's Firmware Update Client model instructs all Target nodes that have verified the firmware image to apply it. The Target nodes' Firmware Update Server models respond with a status message before calling their application's ``apply`` callback. #. The Target node's application performs any preparations needed before applying the transfer, such as storing a snapshot of the Composition Data or clearing its configuration. #. The Target node's application swaps the current firmware with the new image and updates its firmware image list with the new firmware ID. #. The Distributor's Firmware Update Client model requests the full list of firmware images from each Target node, and scans through the list to make sure that the new firmware ID has replaced the old. .. note:: During the metadata check in the distribution procedure, the Target node may have reported that it will become unprovisioned after the firmware image is applied. In this case, the Distributor's Firmware Update Client model will send a request for the full firmware image list, and expect no response. Cancelling the distribution =========================== The firmware distribution can be cancelled at any time by the Initiator. In this case, the Distributor starts the cancelling procedure by sending a cancelling message to all Target nodes. The Distributor waits for the response from all Target nodes. Once all Target nodes have replied, or the request has timed out, the distribution procedure is cancelled. After this the distribution procedure can be started again from the ``Firmware distribution`` section. API reference ************* This section lists the types common to the Device Firmware Update mesh models. .. doxygengroup:: bt_mesh_dfd .. doxygengroup:: bt_mesh_dfu .. doxygengroup:: bt_mesh_dfu_metadata ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/dfu.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
4,279
```restructuredtext .. _bluetooth_mesh_models_priv_beacon_cli: Private Beacon Client ##################### The Private Beacon Client model is a foundation model defined by the Bluetooth mesh specification. It is enabled with the :kconfig:option:`CONFIG_BT_MESH_PRIV_BEACON_CLI` option. The Private Beacon Client model is introduced in the Bluetooth Mesh Protocol Specification version 1.1, and provides functionality for configuring the :ref:`bluetooth_mesh_models_priv_beacon_srv` models. The Private Beacons feature adds privacy to the different Bluetooth Mesh beacons by periodically randomizing the beacon input data. This protects the mesh node from being tracked by devices outside the mesh network, and hides the network's IV index, IV update and the Key Refresh state. The Private Beacon Client model communicates with a :ref:`bluetooth_mesh_models_priv_beacon_srv` model using the device key of the target node. The Private Beacon Client model may communicate with servers on other nodes or self-configure through the local Private Beacon Server model. All configuration functions in the Private Beacon Client API have ``net_idx`` and ``addr`` as their first parameters. These should be set to the network index and the primary unicast address the target node was provisioned with. If present, the Private Beacon Client model must only be instantiated on the primary element. API reference ************* .. doxygengroup:: bt_mesh_priv_beacon_cli ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/priv_beacon_cli.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
299
```restructuredtext .. _bluetooth_mesh_models: Mesh models ########### Foundation models ***************** The Bluetooth Mesh specification defines foundation models that can be used by network administrators to configure and diagnose mesh nodes. .. toctree:: :maxdepth: 1 cfg_cli cfg_srv health_cli health_srv lcd_cli lcd_srv od_cli od_srv op_agg_cli op_agg_srv priv_beacon_cli priv_beacon_srv rpr_cli rpr_srv sar_cfg_cli sar_cfg_srv srpl_cli srpl_srv Model specification models ************************** In addition to the foundation models defined in the Bluetooth Mesh specification, the Bluetooth Mesh Model Specification defines several models, some of which are implemented in Zephyr: .. toctree:: :maxdepth: 1 blob dfu ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/models.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
198
```restructuredtext .. _bluetooth_mesh_blob: BLOB Transfer models #################### The Binary Large Object (BLOB) Transfer models implement the Bluetooth Mesh Binary Large Object Transfer Model specification version 1.0 and provide functionality for sending large binary objects from a single source to many Target nodes over the Bluetooth Mesh network. It is the underlying transport method for the :ref:`bluetooth_mesh_dfu`, but may be used for other object transfer purposes. The implementation is in experimental state. The BLOB Transfer models support transfers of continuous binary objects of up to 4 GB (2 \ :sup:`32` bytes). The BLOB transfer protocol has built-in recovery procedures for packet losses, and sets up checkpoints to ensure that all targets have received all the data before moving on. Data transfer order is not guaranteed. BLOB transfers are constrained by the transfer speed and reliability of the underlying mesh network. Under ideal conditions, the BLOBs can be transferred at a rate of up to 1 kbps, allowing a 100 kB BLOB to be transferred in 10-15 minutes. However, network conditions, transfer capabilities and other limiting factors can easily degrade the data rate by several orders of magnitude. Tuning the parameters of the transfer according to the application and network configuration, as well as scheduling it to periods with low network traffic, will offer significant improvements on the speed and reliability of the protocol. However, achieving transfer rates close to the ideal rate is unlikely in actual deployments. There are two BLOB Transfer models: .. toctree:: :maxdepth: 1 blob_srv blob_cli The BLOB Transfer Client is instantiated on the sender node, and the BLOB Transfer Server is instantiated on the receiver nodes. Concepts ******** The BLOB transfer protocol introduces several new concepts to implement the BLOB transfer. BLOBs ===== BLOBs are binary objects up to 4 GB in size, that can contain any data the application would like to transfer through the mesh network. The BLOBs are continuous data objects, divided into blocks and chunks to make the transfers reliable and easy to process. No limitations are put on the contents or structure of the BLOB, and applications are free to define any encoding or compression they'd like on the data itself. The BLOB transfer protocol does not provide any built-in integrity checks, encryption or authentication of the BLOB data. However, the underlying encryption of the Bluetooth Mesh protocol provides data integrity checks and protects the contents of the BLOB from third parties using network and application level encryption. Blocks ------ The binary objects are divided into blocks, typically from a few hundred to several thousand bytes in size. Each block is transmitted separately, and the BLOB Transfer Client ensures that all BLOB Transfer Servers have received the full block before moving on to the next. The block size is determined by the transfer's ``block_size_log`` parameter, and is the same for all blocks in the transfer except the last, which may be smaller. For a BLOB stored in flash memory, the block size is typically a multiple of the flash page size of the Target devices. Chunks ------ Each block is divided into chunks. A chunk is the smallest data unit in the BLOB transfer, and must fit inside a single Bluetooth Mesh access message excluding the opcode (379 bytes or less). The mechanism for transferring chunks depends on the transfer mode. When operating in Push BLOB Transfer Mode, the chunks are sent as unacknowledged packets from the BLOB Transfer Client to all targeted BLOB Transfer Servers. Once all chunks in a block have been sent, the BLOB Transfer Client asks each BLOB Transfer Server if they're missing any chunks, and resends them. This is repeated until all BLOB Transfer Servers have received all chunks, or the BLOB Transfer Client gives up. When operating in Pull BLOB Transfer Mode, the BLOB Transfer Server will request a small number of chunks from the BLOB Transfer Client at a time, and wait for the BLOB Transfer Client to send them before requesting more chunks. This repeats until all chunks have been transferred, or the BLOB Transfer Server gives up. Read more about the transfer modes in :ref:`bluetooth_mesh_blob_transfer_modes` section. .. _bluetooth_mesh_blob_stream: BLOB streams ============ In the BLOB Transfer models' APIs, the BLOB data handling is separated from the high-level transfer handling. This split allows reuse of different BLOB storage and transfer strategies for different applications. While the high level transfer is controlled directly by the application, the BLOB data itself is accessed through a *BLOB stream*. The BLOB stream is comparable to a standard library file stream. Through opening, closing, reading and writing, the BLOB Transfer model gets full access to the BLOB data, whether it's kept in flash, RAM, or on a peripheral. The BLOB stream is opened with an access mode (read or write) before it's used, and the BLOB Transfer models will move around inside the BLOB's data in blocks and chunks, using the BLOB stream as an interface. Interaction ----------- Before the BLOB is read or written, the stream is opened by calling its :c:member:`open <bt_mesh_blob_io.open>` callback. When used with a BLOB Transfer Server, the BLOB stream is always opened in write mode, and when used with a BLOB Transfer Client, it's always opened in read mode. For each block in the BLOB, the BLOB Transfer model starts by calling :c:member:`block_start <bt_mesh_blob_io.block_start>`. Then, depending on the access mode, the BLOB stream's :c:member:`wr <bt_mesh_blob_io.wr>` or :c:member:`rd <bt_mesh_blob_io.rd>` callback is called repeatedly to move data to or from the BLOB. When the model is done processing the block, it calls :c:member:`block_end <bt_mesh_blob_io.block_end>`. When the transfer is complete, the BLOB stream is closed by calling :c:member:`close <bt_mesh_blob_io.close>`. Implementations --------------- The application may implement their own BLOB stream, or use the implementations provided by Zephyr: .. toctree:: :maxdepth: 2 blob_flash Transfer capabilities ===================== Each BLOB Transfer Server may have different transfer capabilities. The transfer capabilities of each device are controlled through the following configuration options: * :kconfig:option:`CONFIG_BT_MESH_BLOB_SIZE_MAX` * :kconfig:option:`CONFIG_BT_MESH_BLOB_BLOCK_SIZE_MIN` * :kconfig:option:`CONFIG_BT_MESH_BLOB_BLOCK_SIZE_MAX` * :kconfig:option:`CONFIG_BT_MESH_BLOB_CHUNK_COUNT_MAX` The :kconfig:option:`CONFIG_BT_MESH_BLOB_CHUNK_COUNT_MAX` option is also used by the BLOB Transfer Client and affects memory consumption by the BLOB Transfer Client model structure. To ensure that the transfer can be received by as many servers as possible, the BLOB Transfer Client can retrieve the capabilities of each BLOB Transfer Server before starting the transfer. The client will transfer the BLOB with the highest possible block and chunk size. .. _bluetooth_mesh_blob_transfer_modes: Transfer modes ============== BLOBs can be transferred using two transfer modes, Push BLOB Transfer Mode and Pull BLOB Transfer Mode. In most cases, the transfer should be conducted in Push BLOB Transfer Mode. In Push BLOB Transfer Mode, the send rate is controlled by the BLOB Transfer Client, which will push all the chunks of each block without any high level flow control. Push BLOB Transfer Mode supports any number of Target nodes, and should be the default transfer mode. In Pull BLOB Transfer Mode, the BLOB Transfer Server will "pull" the chunks from the BLOB Transfer Client at its own rate. Pull BLOB Transfer Mode can be conducted with multiple Target nodes, and is intended for transferring BLOBs to Target nodes acting as :ref:`bluetooth_mesh_lpn`. When operating in Pull BLOB Transfer Mode, the BLOB Transfer Server will request chunks from the BLOB Transfer Client in small batches, and wait for them all to arrive before requesting more chunks. This process is repeated until the BLOB Transfer Server has received all chunks in a block. Then, the BLOB Transfer Client starts the next block, and the BLOB Transfer Server requests all chunks of that block. .. _bluetooth_mesh_blob_timeout: Transfer timeout ================ The timeout of the BLOB transfer is based on a Timeout Base value. Both client and server use the same Timeout Base value, but they calculate timeout differently. The BLOB Transfer Server uses the following formula to calculate the BLOB transfer timeout:: 10 * (Timeout Base + 1) seconds For the BLOB Transfer Client, the following formula is used:: (10000 * (Timeout Base + 2)) + (100 * TTL) milliseconds where TTL is time to live value set in the transfer. API reference ************* This section contains types and defines common to the BLOB Transfer models. .. doxygengroup:: bt_mesh_blob ```
/content/code_sandbox/doc/connectivity/bluetooth/api/mesh/blob.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,953