Microchip ATWINC3400-IC Manual


Læs nedenfor 📖 manual på dansk for Microchip ATWINC3400-IC (149 sider) i kategorien Ikke kategoriseret. Denne guide var nyttig for 26 personer og blev bedømt med 4.5 stjerner i gennemsnit af 2 brugere

Side 1/149
ATWINC3400
ATWINC3400 Wi-Fi/BLE Network Controller - Software
Design Guide
User Guide
Introduction
Atmel® SmartConnect ATWINC3400 SoC is an IEEE® 802.11 b/g/n and
Bluetooth® Smart BLE network controller for applications in the Internet-of-
Things. It is an ideal add-on to existing MCU solutions bringing Wi-Fi® and
network capabilities through an SPI- -to Wi-Fi interface. The WINC3400 AT
connects to any Atmel AVR® or Atmel | SMART MCU with minimal resource
requirement s.
Features
Wi-Fi IEEE® 802.11 b/g/n STA AP modes and
Wi-Fi Protected Setup (WPS)
Discovery and provisioning via Smartphone using BLE
Support of WEP WPA/WPA2 personal security and
Embedded network stack protocols to ooad work from the host MCU. This
allows operation with a wide range of MCUs including low end MCUs.
Embedded TCP/IP stack with BSD-style socket API
Embedded network protocols
DHCP client/server
DNS resolver client
SNTP client for UTC time synchronization
Embedded TLS security abstracted behind BSD-style socket API
HTTP Server for optional provisioning using AP mode
Ultra-low cost IEEE 802.11 b/g/n RF/PH/MAC SoC
Ultra-low power Bluetooth SMART (BLE 4.0 SoC with Integrated MCU, )
Transceiver, Modem, MAC, PA, TR Switch, and Power Management Unit
Fast boot from on-chip Boot ROM
8Mb internal Flash memory
Low power consumption with dierent power saving modes
SPI, I2C, and UART support
Low footprint host driver with the following capabilities:
Can run on 8, 16, and 32 bit MCU
Little and Big endian support
Consumes about 8KB of code memory and 1KB of data memory on host
MCU
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
2
Table of Contents
1 Icon Key Identiers .............................................................................................. 7
2 Glossary ................................................................................................................ 7
3 References ............................................................................................................ 7
4 Host Driver Architecture ...................................................................................... 8
4.1 WLAN API ......................................................................................................................................... 8
4.2 Socket API ......................................................................................................................................... 8
4.3 Host Interface (HIF) ........................................................................................................................... 9
4.4 Board Support Package (BSP) .......................................................................................................... 9
4.5 Serial Bus Interface ........................................................................................................................... 9
5 WINC System Architecture ................................................................................ 10
5.1 Bus Interface ................................................................................................................................... 10
5.2 Non-volatile Storage ........................................................................................................................ 11
5.3 CPUs ............................................................................................................................................... 11
5.4 IEEE 802.11 MAC Hardware ........................................................................................................... 11
5.5 Bluetooth BLE V4.0 MAC Hardware ................................................................................................ 11
5.6 Program Memory ............................................................................................................................. 11
5.7 Data Memory ................................................................................................................................... 11
5.8 Shared Packet Memory ................................................................................................................... 11
5.9 IEEE 802.11 MAC Firmware ............................................................................................................ 11
5.10 Bluetooth V2.1 MAC Firmware ........................................................................................................ 12
5.11 Memory Managers ........................................................................................................................... 12
5.12 Power Managements ....................................................................................................................... 12
5.13 ATWINC RTOS ............................................................................................................................... 12
5.14 ATWINC IoT Library ........................................................................................................................ 13
6 ATWINC Initialization and Simple Application ................................................. 14
6.1 BSP Initialization .............................................................................................................................. 14
6.2 ATWINC Host Driver Initialization .................................................................................................... 14
6.3 Socket Layer Initialization ................................................................................................................ 14
6.4 ATWINC Event Handling ................................................................................................................. 14
6.4.1 Asynchronous Events ............................................................................................................. 15
6.4.2 Interrupt Handling ................................................................................................................... 15
6.5 Code Example ................................................................................................................................. 16
7 ATWINC Conguration ....................................................................................... 17
7.1 Device Parameters .......................................................................................................................... 17
7.1.1 System Time ........................................................................................................................... 17
7.1.2 Firmware and HIF Version ...................................................................................................... 17
7.2 ATWINC Modes of Operation .......................................................................................................... 17
7.2.1 Idle Mode ................................................................................................................................ 18
7.2.2 Wi-Fi Station M ode................................................................................................................. 18
7.2.3 Wi-Fi Hotspot (AP) Mode ........................................................................................................ 18
7.3 Network Parameters ........................................................................................................................ 19
7.3.1 Wi-Fi MAC Address ................................................................................................................ 19
7.3.2 IP Address .............................................................................................................................. 19
7.4 Power Saving Parameters ............................................................................................................... 19
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
3
7.4.1 Power Saving Modes .............................................................................................................. 19
7.4.1.1 M2M_PS_MANUAL ................................................................................................ 20
7.4.1.2 M2M_PS_AUTOMATIC .......................................................................................... 21
7.4.1.3 M2M_PS_H_AUTOMATIC ..................................................................................... 21
7.4.1.4 M2M_PS_DEEP_AUTOMATIC .............................................................................. 21
7.4.2 Conguring Listen Interval and DTIM Monitoring .................................................................... 21
8 -Fi Station Mode Wi ............................................................................................. 22
8.1 Scan Conguration Parameters .......................................................................................................22
8.1.1 Scan Region ........................................................................................................................... 22
8.1.2 Scan Options .......................................................................................................................... 22
8.2 Wi-Fi Scan ....................................................................................................................................... 22
8.3 On Demand Wi-Fi Connection ......................................................................................................... 23
8.4 Default Connection .......................................................................................................................... 24
8.5 Wi-Fi Security .................................................................................................................................. 25
8.6 Example Code ................................................................................................................................. 26
9 ATWINC Socket Programming .......................................................................... 27
9.1 Overview .........................................................................................................................................27
9.1.1 ATWINC Socket Types ........................................................................................................... 27
9.1.2 Socket Properties ................................................................................................................... 27
9.1.3 Limitations .............................................................................................................................. 27
9.2 ATWINC Sockets API ...................................................................................................................... 27
9.2.1 API Prerequisites .................................................................................................................... 27
9.2.2 Non-blocking Asynchronous Socket APIs ..............................................................................28
9.2.3 Socket API Functions ............................................................................................................. 28
9.2.3.1 socketInit ................................................................................................................ 28
9.2.3.2 registerSocketCallback ........................................................................................... 28
9.2.3.3 socket ..................................................................................................................... 28
9.2.3.4 connect ................................................................................................................... 28
9.2.3.5 bind......................................................................................................................... 29
9.2.3.6 listen ....................................................................................................................... 29
9.2.3.7 accept ..................................................................................................................... 29
9.2.3.8 send ........................................................................................................................ 30
9.2.3.9 sendto ..................................................................................................................... 30
9.2.3.10 recv / recvfrom ........................................................................................................ 31
9.2.3.11 close ....................................................................................................................... 31
9.2.3.12 setsockopt ..............................................................................................................31
9.2.3.13 gethostbyname ....................................................................................................... 31
9.2.4 Summary ................................................................................................................................ 32
9.3 Socket Connection Flow .................................................................................................................. 33
9.3.1 TCP Client Operation .............................................................................................................34
9.3.2 TCP Server Operati on ............................................................................................................ 35
9.3.3 UDP Client Operation ............................................................................................................. 36
9.3.4 UDP Server Operation ............................................................................................................ 37
9.3.5 DNS Host Name Resolution ................................................................................................... 38
9.4 Example Code ................................................................................................................................. 39
9.4.1 TCP Client Example Code ...................................................................................................... 39
9.4.2 TCP Server Example Code .................................................................................................... 40
9.4.3 UDP Client Example Code ..................................................................................................... 42
9.4.4 UDP Server Example Code .................................................................................................... 43
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
4
10 Transport Layer Security (TLS) ......................................................................... 45
10.1 TLS Connection Establishment ....................................................................................................... 45
10.2 Server Certicate Installation ........................................................................................................... 46
10.2.1 Technical Background ............................................................................................................ 46
10.2.1.1 Public Key Infrastructure ......................................................................................... 46
10.2.1.2 TLS Server Authentication ...................................................................................... 46
10.2.2 Adding a Certicate to the ATWINC Trusted Root Certicate Store ....................................... 46
10.3 ATWINC TLS Limitations ................................................................................................................. 46
10.3.1 Modes of Operation ................................................................................................................ 46
10.3.2 Concurrent Connections ......................................................................................................... 46
10.3.3 Supported Cipher Suites .........................................................................................................46
10.3.4 Supported Hash Algorithms .................................................................................................... 46
10.4 SSL Client Code Example ............................................................................................................... 47
11 Wi-Fi AP Mode .................................................................................................... 49
11.1 Overview .........................................................................................................................................49
11.2 Setting ATWINC AP Mode ..............................................................................................................49
11.3 Limitations ....................................................................................................................................... 49
11.4 Sequence Diagram .......................................................................................................................... 49
11.5 AP Mode Code Example ................................................................................................................. 50
12 Provisioning ........................................................................................................ 51
12.1 BLE Provisioning ............................................................................................................................. 51
12.1.1 BLE Provisioning Code Example ............................................................................................ 53
12.2 HTTP Provisioning ........................................................................................................................... 54
12.2.1 Introduction ............................................................................................................................. 54
12.2.2 Limitations .............................................................................................................................. 54
12.2.3 Basic Approach ......................................................................................................................54
12.2.4 Provisioning Control Flow ....................................................................................................... 55
12.2.5 HTTP Redirect Feature ...........................................................................................................56
12.2.6 HTTP Provisioning Code Example ......................................................................................... 56
12.3 Wi-Fi Protected Setup (WPS) .......................................................................................................... 57
12.3.1 WPS Conguration Methods .................................................................................................. 57
12.3.2 WPS Limitations ..................................................................................................................... 57
12.3.3 WPS Control Flow .................................................................................................................. 58
12.3.4 WPS Code Example ............................................................................................................... 59
13 Multicast Sockets ............................................................................................... 60
13.1 Overview .........................................................................................................................................60
13.2 How to use Filters ............................................................................................................................ 60
13.3 Multicast Socket Code Example ...................................................................................................... 60
14 ATWINC Serial Flash Memory ........................................................................... 65
14.1 Overview and Features ...................................................................................................................65
14.2 Accessing to Serial Flash ................................................................................................................ 65
14.3 Read/Write/Erase Operations .......................................................................................................... 65
14.4 Serial (SPI) Flash Map ....................................................................................................................66
14.5 Flash Read, Erase, Write Code Example ........................................................................................ 66
15 Writing a Simple Networking Application ......................................................... 68
15.1 Prerequisites ....................................................................................................................................68
15.2 Solution Overview ............................................................................................................................ 68
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
6
E.1 Introduction .................................................................................................................................... 145
E.2 Preparing Environment .................................................................................................................. 145
E.3 How to use .....................................................................................................................................145
E.3.1 Method 1 ............................................................................................................................... 145
E.3.2 Method 2 ............................................................................................................................... 145
Appendix F. Revision History ........................................................................ 147
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
7
1 Icon Key Identiers
Delivers contextual information about a specific topic.
Highlights useful tips and techniques.
Highlights objectives to be completed.
Highlights the expected result of an assignment step.
Indicates important information.
2 Glossary
BSD Berkeley Software Distribution
BSP Board Support Package
HIF Host Interface Layer
IoT Internet of Things
OTA Over The Air
OTP One Time Programmable
TLS Transport Layer Security
WINC Wi-Fi Network Controller
3 References
[R01] . Atmel-42640-Getting-Started-Guide-for-ATWINC3400WiFi-using-SAMD21-Xplained-Pro_UserGuide
[R02] Atmel-42639-Software-Programming-Guide-for-ATWINC3400-WiFi-using-SAMD21-Xplained-
Pro_UserGuide.
[R03] Atmel-42535-ATWINC3400-MR210-IEEE80211bgn-Link-Ctlr-with-Integrated-Low-Energy-
Bluetooth40_Datasheet
[R04] Atmel-42683-ATWINC3400-BLE-WiFi-Scan- -Connect-Services-Guide_UserGuideand
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
10
5 WINC System Architecture
Figure 5-1 shows the WINC system architecture. The Soc contains two 32-bit CPUs APS3S-Cortus for Wi-: an
Fi and an APS3-Cortus for BLE. In addition it has separate built-in Wi-Fi IEEE-802.11 and BLE 4.0 physical
layers sharing a single nal RF front end. The firmware for Wi-Fi comprises the Wi-Fi IEEE-802.11 MAC layer
and embedded protocol stacks which ooad the host MCU. The firmware for BLE implements the entrie BLE
stack and privides an application supporting a prole defined for device provisioning. The components of the
system are described in the following sub-sections.
Figure 5- WINC System Architecture 1.
WINC3400 SOC
APS3S-Cortus
Power
Management
IEEE 802.11 MAC
WINC RTOS
Memory
Manager
WINC Host Interface
WINC IoT Library
WINC TCP/IP Stack
Transport
Layer Security
(TLS)
Wi-Fi
Protected
Setup (WPS)
Radio
Coexistence
DHCP
Client/
Server
DNS
Resolver SNTP SSL
Manager
Crypto Library
BUS Interface
I2
CSPI Master/Slave
IEEE 802.11 MAC HW
IEEE 802.11 PHY Shared PKT
Memory
Program
Memory
Data
Memory
SPI FLASH
APS3-Cortus
Power
Management
Bluetooth V4.1 MAC Memory
Manager
WINC BLE Library
AT Bluetooth SmartConnect
Stack: SAP, SMT, ATT, GATT,
L2CAP
Wi-Fi cross
comms
BLE cross
comms
Shared Radio
Bluetooth V4.1 MAC HW
Bluetooth V4.1 PHY
Shared PKT
Memory
Program
Memory
Data
Memory
Corus - Cortus
Radio
Coexistence
Provisioning
App support
5.1 Bus Interface
Hardware logic for the supported bus types for WINC communications.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
11
5.2 Non-volatile Storage
The SoC has an integrated 8 serial ash inside the WINC package (SIP). This stores the WINC Mb both Wi-Fi
rmware image and the BLE rmware image. It also stores information used by WINC firmware in the run-time.
The detailed description of the serial flash is provided in Chapter 14: ATWINC Serial Flash Memory.
5.3 CPUs
The SoC contains two 32-bit CPUs:
An APS3S-Cortus 32-bit CPU running at 40MHz clock speed, which executes the embedded WINC Wi-
Fi rmware
An APS3-Cortus 32-bit CPU running at MHz clock speed, which executes the embedded WINC BLE 26
rmware
5.4 IEEE 802.11 MAC Hardware
The SoC contains a hardware accelerator to ensure fast and compliant implementation of the IEEE 802.11
MAC layer and associated timing. It ooads IEEE 802.11 MAC functionality fromrmware to improve
performance and boost the MAC throughput. The accelerator includes hardware encryption/decryption of Wi-Fi
trac and traic ltering mechanisms to avoid unnecessary processing in software.
5.5 Bluetooth BLE V4.0 MAC Hardware
The BLE Medium Access Controller (MAC) encodes and decodes HCI packets, constructs baseband data
packages, schedules frames and manages and monitors connection status, slot usage, data ow, routing,
segmentation, and buer control.
The core performs Link Control Layer management supporting the main BLE states, including advertising and
connection.
5.6 Program Memory
128KB Instruction RAM is provided for execution of the WINC Wi-Fi rmware code.
292KB Instruction RAM is provided for execution of the WINC BLE rmware code.
5.7 Data Memory
64KB Data RAM is provided for WINC Wi-Fi rmware data storage.
64KB Data RAM is provided for WINC BLE rmware data storage.
5.8 Shared Packet Memory
128KB memory is provided for Wi-Fi TX/RX packet management. It is shared between the Wi-Fi MAC
hardware and the CPU. This memory is managed by the Wi-Fi Memory Manager SW component.
32KB memory is provided for BLE TX/RX packet management. It is shared between the BLE MAC hardware
and the CPU. This memory is managed by the BLE Memory Manager SW component.
5.9 IEEE 802.11 MAC Firmware
The system supports IEEE 802.11 b/g/n Wi-Fi MAC including WEP and WPA/WPA2 security supplicant.
Between the MAC hardware and firmware, a full range of IEEE 802.11 features are implemented and
supported including beacon generation and reception, control packet generation and reception and packet
aggregation and de-aggregation.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
12
5.10 Bluetooth V2.1 MAC Firmware
The BLE subsystem implements all the critical real-time functions required for full compliance with Specication
of the Bluetooth System, v4.1, Bluetooth SIG. The rmware implements an integrated Bluetooth Low Energy
stack which is Bluetooth V4.1 compliant. The rmware supports access to the GAP, SMP, ATT, GATT client /
server and L2CAP service layer protocols. In the WINC3400 these services are used by a built-in AT
application for WI-Fi provisioning.
5.11 Memory Managers
The memory managers on both the Wi-Fi and BLE sides are responsible for the allocation and de-allocation of
memory chunks in both shared packet memory and data memory.
5.12 Power Managements
The Power Management modules on both the Wi-Fi and BLE sides are responsible for handling dierent power
saving modes supported by the WINC and coordinating these modes with the Wi-Fi and BLE transceiver. AT
5.13 WINC RTOS AT
The rmware includes a low-footprint real-time scheduler which allows concurrent multi-tasking on WINC AT
Wi-Fi CPU. The WINC RTOS provides semaphores and timer functionality. AT
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
13
5.14 WINC IoT Library AT
The WINC IoT library provides a set of networking protocols in WINC rmware. It ooads the host MCU AT AT
from networking and transport layer protocols. The following sections describe the components of WINC IoT AT
library.
ATWINC TCP/IP STACK
The WINC TCP/IP is an IPv4.0 stack based on the µIP TCP/IP stack (pronounced micro-IP). AT
µIP is a low footprint TCP/IP stack which has the ability to run on a memory-constrained microcontroller
platform. It was originally developed by Adam Dunkels, licensed under a BSD style license, and further
developed by a wide group of developers. The WINC TCP/IP stack adds to the original µIP AT
implementation several enhancements to boost TCP and UDP throughput.
DHCP CLIENT/SERVER
A DHCP client is embedded in ATWINC rmware that can obtain an IP conguration automatically after
connecting to a Wi-Fi network.
ATWINC rmware provides an instance of a DHCP server that starts automatically when ATWINC AP
mode is enabled. When the host MCU application activates the AP mode, it is allowed to configure the
DHCP Server IP address pool range within the AP configuration parameters.
DNS RESOLVER
ATWINC rmware contains an instance of an embedded DNS resolver. This module can return an IP
address by resolving the host domain names supplied with the socket API call gethostbyname.
SNTP
The SNTP (Simple Network Time Protocol) module implements an SNTP client used to synchronize the
ATWINC internal clock to the UTC clock.
TRANSPORT LAYER SECURITY
For TLS implementation, see C Transport Layer Security (TLS) for details. hapter 10:
WI-FI PROTECTED SETUP
For WPS protocol implementation, see Section 12.3: Wi-Fi Protected Setup (WPS) for details.
CRYPTO LIBRARY
The Crypto Library contains a set of cryptographic algorithms used by common security protocols. This
library has an implementation of the following algorithms:
MD4 Hash algorithm (used only for MsChapv2.0 digest calculation)
MD5 Hash algorithm
SHA-1 Hash algorithm
SHA-256 Hash algorithm
DES Encryption (used only for MsChapv2.0 digest calculation)
MS-CHAPv2.0 (used as the EAP-TTLS inner authentication algorithm)
AES-128, AES-256 Encryption (used for securing WPS and TLS trafc)
BigInt module for large integer arithmetic (for Public Key Cryptographic computations)
RSA Public Key cryptography algorithms (includes RSA Signature and RSA Encryption algorithms)
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
14
6 WINC Initialization and Simple Application AT
After powering up the WINC device, a set of synchronous initialization sequences must be executed for the AT
correct operation of the Wi-Fi functions and BLE functions. This chapter aims to explain the dierent steps
required during the initialization phase of the system. The host MCU does not communicate directly with the
BLE function but controls it through messages to the Wi-Fi MCU. This allows a single interface and driver to be
used to communicate to the WINC device. AT
After initialization, the host MCU application is required to call the WINC driver entry point to handle events AT
from ATWINC rmware.
BSP Initialization
ATWINC Host Driver Initialization
Socket Layer Initialization
Call ATWINC driver entry point
Failure to complete any of the initialization steps will result in failure in ATWINC startup.
6.1 BSP Initialization
The BSP is initialized by calling the API. The BSP initialization routine performs the following nm_bsp_init
steps:
Resets the ATWINC1 using corresponding host MCU control GPIOs
Initializes the host MCU GPIO which connects to ATWINC interrupt line. It congures the GPIO as an
interrupt source to the host MCU. During runtime, ATWINC interrupts the host to notify the application of
events and data pending inside ATWINC rmware.
Initializes the host MCU delay function used within implementation nm_bsp_sleep
6.2 ATWINC Host Driver Initialization
The ATWINC host driver is initialized by calling the API. The Host driver initialization routine m2m_wifi_init
performs the following steps:
Initializes the bus wrapper, I2C, SPI, or UART, depending on the host driver software bus interface
conguration compilation ag respectively USE_I2C, USE_SPI or USE_UART
Registers an application-defined Wi-Fi event handler
Initializes the driver and ensures that the current ATWINC rmware matches the current driver version
Initializes the host interface and the Wi-Fi layer and registers the BSP Interrupt
A Wi-Fi event handler is required for the correct operation of any ATWINC application.
6.3 Socket Layer Initialization
Socket layer initialization is carried out by calling the API. It must be called prior to any socket socketInit
activity. Refer to S for more information about socket initialization and programming. ection 9.2.1
6.4 ATWINC Event Handling
The ATWINC host driver API allows the host MCU application to interact with the ATWINC rmware. To
facilitate interaction, the ATWINC driver implements the described in CHost Interface (HIF) Protocol hapter 16:
1 Refer to ATWINC3400 datasheet [R02] for more information about ATWINC hardware reset sequence.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
15
Host Interface Protocol. The HIF protocol denes how to serialize and de-serializes API requests and response
callbacks over the serial bus interface: I2C, UART, or SPI.
Figure 6- ATWINC System Architecture 1.
Host Interface Protocol
HOST MCU
WINC Host Driver
Host MCU Application
WINC
WINC Hardware
WINC Firmware
ATWINC host driver API provides services to the host MCU applications that are mainly divided in two major
categories: Wi-Fi control services and Socket services. The Wi-Fi control services allow actions such as
channel scanning, network identication, connection, and disconnection. The Socket control services allow
application data transfer once a Wi-Fi connection has been established.
6.4.1 Asynchronous Events
Some ATWINC host driver APIs are synchronous function calls, where the result is ready by the return of the
function. However, most ATWINC host driver API functions are asynchronous. This means that when the
application calls an API to request a service, the call is non-blocking and returns immediately, most often
before the requested action is completed. When completed, a notication is provided in the form of a HIF
protocol message from the ATWINC rmware to the host which, in turn, is delivered to the application via a
callback2 function. Asynchronous operation is essential when the requested service such as Wi-Fi connection
may take signicant time to complete. In general, the ATWINC rmware uses asynchronous events to signal
the host driver about status change or pending data.
The HIF uses “push” architecture, where data and events are pushed from ATWINC firmware to the host MCU
in FCFS manner. For instance, suppose that host MCU application has two open sockets; socket 1 and socket
2. If ATWINC receives socket 1 data followed by socket 2 data, then HIF shall deliver socket data in two HIF
protocol messages in the order they were received. HIF does not allow reading socket 2 data before socket 1
data.
6.4.2 Interrupt Handling
The HIF interrupts the host MCU when one or more events are pending in ATWINC rmware. The host MCU
application is a big state machine which processes received data and events when ATWINC driver calls the
event callback function(s). In order to receive event callbacks, the host MCU application is required to call the
2 The callback is C function, which contains an application-dened logic. The callback is registered using the ATWINC host
driver registration API to handle the result of the requested service.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
16
m2m_wifi_handle_events API to let the host driver retrieve and process the pending events from the
ATWINC rmware. It is recommended to call this function either:
Host MCU application polls the API in main loop or a dedicated task
Or at least once when host MCU receives an interrupt from ATWINC rmware
All the application-dened event callback functions registered with ATWINC driver run
in the context API. m2m_wifi_handle_events
The above HIF architecture allows the ATWINC host driver to be exible to run in the following congurations:
Host MCU with no operating system configuration: In this configuration, the MCU main loop is
responsible to handle deferred work from interrupt handler.
Host MCU with operating system configuration: In this conguration, a dedicated task or thread is
required to call ed work from interrupt handler. m2m_wifi_handle_events to handle deferr
Host driver entry point is . In the operating m2m_wifi_handle_events non-reentrant
system conguration, it is required to protect the host driver from reentrance by a syn-
chronization object.
When host MCU is polling , the API checks for pending un-m2m_wifi_handle_events
handled interrupt from ATWINC. If no interrupt is pending, it returns immediately. If an
interrupt is pending, reads all the pending HIF messages m2m_wifi_handle_events
sequentially and dispatches the HIF message content to the respective registered
callback. If a callback is not registered to handle the type of message, the HIF mes-
sage content is discarded.
6.5 Code Example
The code example below shows the initialization ow as described in previous sections.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
17
7 ATWINC Configuration
ATWINC firmware has a set of configurable parameters that control its behavior. There is a set of APIs
provided to host MCU application to configure these parameters. The configuration APIs are categorized
according to their functionality into: device, network, and power saving parameters.
Any parameters left unset by the host MCU application shall use their default values assigned during the
initialization of the ATWINC firmware. A host MCU application needs to configure its parameters when coming
out of cold boot or when a specific configuration change is required.
7.1 Device Parameters
7.1.1 System Time
It is important to set the ATWINC system to UTC time to ensure proper validity check of the X509 certificate
expiration date. Since ATWINC does not contain a built-in real-time clock (RTC), there are two ways to obtain
UTC time:
Using the internal SNTP client: Which is enabled by default in the ATWINC firmware at start-up. The
SNTP client synchronizes the ATWINC system clock to the UTC time from well-known time servers, e.g.
" ". The SNTP client uses a default update cycle of one day. time-c.nist.gov
From host MCU RTC: If the host MCU has an RTC, the application may disable the SNTP client by
calling after ATWINC initialization. The application shall provision the ATWINC m2m_wifi_disable_sntp
system time by calling API. m2m_wifi_set_system_time
7.1.2 Firmware and HIF Version
During startup, the host driver requests the firmware version through m2m_wifi_get_firmware_version API
which returns the structure containing the version number and host interface (HIF) level of the tstrM2mRev
current ATWINC firmware.
If the HIF level of the current driver is not equal to the HIF level of the current ATWINC
firmware, the driver initialization will fail.
The version parameters provided are:
M2M_HIF_LEVEL: Host Interface Level for driver/firmware compatibility
M2M_FIRMWARE_VERSION_MAJOR_NO: Firmware Major release version number
M2M_FIRMWARE_VERSION_MINOR_NO: Firmware Minor release version number
M2M_FIRMWARE_VERSION_PATCH_NO: Firmware Patch release version number
7.2 ATWINC Modes of Operation
The ATWINC firmware supports the following modes of operation:
Idle Mode
Wi-Fi STA Mode
Wi-Fi Hotspot (AP)
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
18
Figure 7- ATWINC Modes of Operation 1.
IDLE
STA AP
7.2.1 Idle Mode
After the host MCU application calls the ATWINC driver initialization API, ATWINC remains in m2m_wifi_init
idle mode waiting for any command to change the mode or to update the configuration parameters. In this
mode ATWINC will enter the power save mode in which it disables the IEEE 802.11 radio and all unneeded
peripherals and suspends the ATWINC CPU. If ATWINC receives any configuration commands from the host
MCU, ATWINC will update the configuration, send back the response to the host MCU, and then go back the
power save mode.
7.2.2 -Fi Station Mode Wi
ATWINC enters station (STA) mode when the host MCU requests connection to an AP using the
m2m_wifi_connect or APIs. ATWINC exits STA mode when it receives a m2m_wifi_default_connect
disconnect request from the Wi-Fi AP conveyed to the host MCU application via the event callback
M2M_WIFI_RESP_CON_STATE_CHANGED or when the host MCU application decides to terminate the connection
via m2m_wifi_disconnect API. ATWINC firmware ignores mode change requests while in this mode until
ATWINC exits the mode.
The supported API functions in this mode use the HIF command types: tenuM2mCon-
figCmd tenuM2mStaCmd and . See the full list of commands in the header file
m2m_types.h.
For more information about this mode, refer to Chapter 8: Wi-Fi Station Mode.
7.2.3 -Fi Hotspot (AP) Mode Wi
In AP mode, ATWINC allows Wi-Fi stations to connect to ATWINC and obtain IP address from ATWINC DHCP
server. To enter AP mode, host MCU application calls API. To exit AP mode, the m2m_wifi_enable_ap
application calls API. ATWINC firmware ignores mode change requests while in this m2m_wifi_disable_ap
m ATWINC exits the mode. ode until
The supported API functions in this mode use the HIF command types:
tenuM2mApCmd tenuM2mConfigCmdand . See the full list of commands in the
header file . m2m_types.h
For more information about this mode, refer to Chapter 11: Wi-Fi AP Mode.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
19
7.3 Network Parameters
7.3.1 -Fi MAC Address Wi
The ATWINC firmware provides two methods to assign the ATWINC MAC address:
Assignment from host MCU: When host MCU application calls the API m2m_wifi_set_mac_address
after initialization using . m2m_wifi_init API
Assignment from ATWINC OTP (One Time Programmable) memory: ATWINC supports an internal
MAC address assignment method through a built-in OTP memory. If MAC address is programmed in the
ATWI OTP memory, the ATWINC working MAC address defaults to the OTP MAC address unless NC
the host MCU application sets a different MAC address programmatically after initialization using the API
m2m_wifi_set_mac_address.
OTP MAC address is programmed in ATWINC OTP memory at manufacturing time.
For more details, refer to descripti the WINC3400_IoT_SW_APIs.chm that was on of the following APIs in
supplied in the WINC3400_IoT_REL software package.
m2m_wifi_get_otp_mac_address
m2m_wifi_set_mac_address
m2m_wifi_get_mac_address
Use m2m_wifi_get_otp_mac_address API to check if there is a valid programmed
MAC address in ATWINC OTP memory. The host MCU application can also use the
same API to read the OTP MAC address octets. The m2m_wifi_get_otp_mac_address
API must be confused with the , which reads the not m2m_wifi_get_mac_address API
working ATWINC MAC address in ATWINC firmware regardless from whether it is as-
signed from the host MCU or from ATWINC OTP.
7.3.2 IP Address
ATWINC firmware uses the embedded DHCP client to obtain an IP configuration automatically after a
successful Wi-Fi connection. After the IP configuration is obtained, the host MCU application is notified by the
asynchronous event M2M_WIFI_RESP_IP_CONFIGURED.
Alternatively, the host MCU application can set a static IP configuration by calling the
m2m_wifi_set_static_ip API. Setting a static IP address will cancel any pending DHCP requests and
disable the DHCP client until the next Wi-Fi connection attempt to the same AP or any other AP.
7.4 Power Saving Parameters
When a Wi-Fi station is idle, it disables the Wi-Fi radio and enters power saving mode. The AP is required to
buffer data while stations are in power save mode and transmit data later when stations wake up. The AP
transmits a beacon frame periodically to synchronize the network every . A station which is in beacon period
power save wakes up periodically to receive the beacon and monitor the signaling information included in the
beacon. The beacon conveys information to the station about unicast data, which belong to the station and
currently buffered inside the AP while the station was sleeping. The beacon also provides information to the
station when the AP is going to send broadcast/multicast data.
7.4.1 Power Saving Modes
ATWINC firmware supports multiple power saving modes which provide flexibility to the host MCU application
to tweak the system power consumption. The host MCU can configure the ATWINC power saving policy using
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
20
the m2m_wifi_set_sleep_mode m2m_wifi_set_lsn_int and APIs. ATWINC supports the following power
saving modes:
M2M_PS_MANUAL
M2M_PS_AUTOMATIC
M2M_PS_H_AUTOMATIC
M2M_PS_DEEP_AUTOMATIC
M2M_PS_DEEP_AUTOMATIC mode recommended for most applications.
7.4.1.1 M2M_PS_MANUAL
This is a fully host-driven power saving mode.
ATWINC sleeps when the host instructs it to do so using the API. During m2m_wifi_request_sleep
ATWINC sleep, the host MCU can decide to sleep also for extended durations.
ATWINC wakes up when the host MCU application requests services from ATWINC by calling any host
driver API function, e.g. Wi-Fi or socket operation
In , M2M_PS_MANUAL mode when ATWINC sleeps due to m2m_wifi_request_sleep
API. ATWINC does not wake up to receive and monitor AP beacon. Beacon monitor-
ing is resumed when host MCU application wakes up the ATWINC.
For an active Wi-Fi connection, the AP may decide to drop the connection if ATWINC is absent because it
sleeps for long time duration. If connection is dropped, ATWINC detects the disconnection on the next wake-up
cycle and notifies the host to reconnect to the AP again. In order to maintain an active Wi-Fi connection for
extended durations, the host MCU application should wake up the ATWINC periodically so that ATWINC can
send a keep-alive Wi-Fi frame to the AP. The host should choose the sleep period carefully to satisfy the
tradeoff between keeping the Wi-Fi connection uninterrupted and minimizing the system power consumption.
This mode is useful for applications which send notifications very rarely due to a certain trigger. It fits also
applications which send notifications periodically with a very long spacing between notifications. Careful power
planning is required when using this mode. If the host MCU decides to sleep for very long period, it may use
M2M_PS_MANUAL or may power off WINCAT 3 completely. The advantage of this mode compared to powering off
ATWINC is that saves the time required for ATWINC firmware to boot since the firmware is M2M_PS_MANUAL
always loaded in ATWINC memory. The real pros and cons depend on the nature of the application. In some
applications, the sleep duration could be long enough to be a power-efficient decision to power off ATWINC
and power it on again and reconnect to the AP when host MCU wakes up. In other situations, a latency-
sensitive application may choose to use to avoid ATWINC firmware boot latency on the M2M_PS_MANUAL
expense of slightly increased power consumption.
During ATWINC sleep, ATWINC in mode saves more power than M2M_PS_MANUAL M2M_PS_DEEP_AUTOMATIC
mode since in the former mode ATWINC skips beacon monitoring while the latter it wakes up to receive
beacons. The comparison should also include the effect of host MCU sleep duration: If host MCU sleep period
is too long, the Wi-Fi connection may drop frequently and the power advantage of is lost due M2M_PS_MANUAL
to the power consumed in Wi-Fi reconnection. In contrast, M2M_PS_DEEP_AUTOMATIC can keep the Wi-Fi
connection for long durations at the expense of waking up ATWINC to monitor the AP beacon.
3 Refer to ATWINC datasheet in for hardware power off sequence. [R02]
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
21
7.4.1.2 M2M_PS_AUTOMATIC
This mode is deprecated and kept for backward compatibility and development reasons. It should not be used
in new implementations.
7.4.1.3 M2M_PS_H_AUTOMATIC
This mode implements the Wi-Fi standard power saving method in which ATWINC will sleep and wake up
periodically to monitor AP beacons. In contrast to , this mode does not involve the host MCU M2M_PS_MANUAL
application.
In this mode, when ATWINC enters sleep state, it only turns off the IEEE 802.11 radio, MAC, and PHY. All
system clocks and the APS3S-Cortus CPU are on.
This mode is useful for a low-latency packet transmission because ATWINC clocks are on and ready to
transmit packets immediately, unlike the M2M_PS_DEEP_AUTOMATIC which may require time to wake up the
ATWINC to transmit a packet if ATWINC was sleep mode.
M2M_PS_H_AUTOMATIC mode is very similar to except that the former power M2M_PS_DEEP_AUTOMATIC
consumption is higher than the latter the since ATWINC system clock is on.
7.4.1.4 M2M_PS_DEEP_AUTOMATIC
Like M2M_PS_HS_AUTOMATIC, this mode implements the Wi-Fi standard power saving method. However, when
ATWINC enters sleep sta system clock is turned off. te, the
Before sleep, the ATWINC programs a hardware timer (running on an internal low-power oscillator) with a
sleep period determined by the ATWINC firmware power management module.
While sleeping, the ATWINC will wake up if one of the following events happens:
Expiry of the hardware sleep timer. ATWINC wakes up to receive the upcoming beacon from AP.
ATWINC wakes up 4 when the host MCU application requests services from ATWINC by calling any host
driver API function, e.g. Wi-Fi or socket operation
7.4.2 Configuring Listen Interval and DTIM Monitoring
ATWINC allows the host MCU application to tweak the system power consumption by configuring beacon s
monitoring parameters. The AP sends beacons periodically every (e.g. 100ms). The beacon beacon period
contains a which informs the station about presence of unicast data for the station buffer in the TIM element
AP. The station negotiates with the AP a which is how many beacon periods the station can listen interval
sleep before it wakes up to receive data buffer in AP. The AP beacon also contains the which contains DTIM,
information to the station about the presence of broadcast/multicast data. Which the AP is ready to transmit
following this beacon after normal channel access rules (CSMA/CA).
The ATWINC driver allows the host MCU application to configure beacon monitoring parameters as follows:
Configure DTIM monitoring: I.e. enable or disable reception of broadcast/multicast data using the API:
m2m_wifi_set_sleep_mode(desired_mode, 1) to receive broadcast data
m2m_wifi_set_sleep_mode(desired_mode, 0) to ignore broadcast data
Configure the listen interval: using the m2m_wifi_set_lsn_int API
Listen interval value provided to the API is expressed in the m2m_wifi_set_lsn_int
unit of beacon period.
4 The wakeup sequence is handled internally in the ATWINC host driver in the API. Refer to the reference hif_chip_wake
Chapter for more information. 16
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
22
8 -Fi Station Mode Wi
This chapter provides information about ATWINC Wi-Fi station (STA) mode . Wi-Fi described in Section 7.2.2
station mode involves scan operation; association to an AP using parameters (SSID and credentials) provided
by host MCU or using AP parameters stored in ATWINC -volatile storage (default connection). This chapter non
also provides information about supported security modes along with code examples.
8.1 Scan Configuration Parameters
8.1.1 Scan Region
The number of RF channels supported varies by geographical region. For example, 14 channels are supported
in Asia while 11 channels are supported in North America. By default the ATWINC initial region configuration is
equal to 14 channels (Asia), but this can be changed by setting the scan region using the
m2m_wifi_set_scan_region API.
8.1.2 Scan Options
During Wi- scan operation, ATWINC sends probe request Wi-Fi frames and waits for some time on the Fi
current Wi-Fi channel to receive probe response frames from nearby APs before it switches to the next
channel. Increasing the scan wait time has a positive effect on the number of access pointed detected during
scan. However, it has a negative effect on the power consumption and overall scan duration. ATWINC
firmware default scan wait time is optimized to provide the tradeoff between power consumption and scan
accuracy. ATWINC firmware provides flexible configuration options to the host MCU application to increase the
scan time. For more detail, refer to the API. m2m_wifi_set_scan_options
8.2 -Fi Scan Wi
A Wi-Fi scan operation can be initiated by calling the API. The scan can be m2m_wifi_request_scan
performed on all 2.4GHz Wi-Fi channels or on a specific requested channel.
The scan response time depends on the scan options. For instance, if the host MCU application requests to
scan all channels, the scan time will be equal to NoOfChannels (14) * M2M_SCAN_MIN_NUM_SLOTS*
M2M_SCAN_MIN_SLOT_TIME efer the WINC3400_IoT_SW_APIs.chm that was supplied in the (r to
WINC3400_IoT_REL software package how to customize the scan parameters). on
The scan operation is illustrated in . Figure 8-1
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
23
Figure 8- -Fi Scan Operation 1. Wi
M2M APPLICATION M2M HOST DRIVER
m2m_wifi_request_scan( )WiFi_Channel_ID
wifi_cb(M2M_WIFI_RESP_SCAN_DONE,
tstrM2mScanDone* );
Read the number of found APs(N).
Start reading the SCAN result list.
m2m_wifi_req_scan_result(0)
wifi_cb(M2M_WIFI_RESP_SCAN_RESULT,
tstrM2mWifiscanResult* );
m2m_wifi_req_scan_result(N - 1)
Process the Scan
result (*)
8.3 On Demand Wi-Fi Connection
The host MCU application may establish a Wi-Fi connection on demand if all the required connection
parameters (SSID, security credentials, etc.) are known to the application. To start a Wi-Fi connection on
demand, the application shall call the API . m2m_wifi_connect
Using implies that the host MCU application has prior knowledge of m2m_wifi_connect
the connection parameters. For instance, connection parameters can be stored on non-
volatile storage attached to the host MCU.
The Wi-Fi on demand connection operation is described in . Figure 8-2
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
24
Figure 8- On Demand Wi-Fi Connection 2.
M2M APPLICATION M2M HOST DRIVER
m2m_wifi_connect(Sec_Type, SSID,SSID_Len,
Key,Key_Len ,Channel_ID (*) );
wifi_cb(M2M_WIFI_REQ_CON_STATE_CHANGED,
tstrM2mWifiStateChanged* );
wifi_cb(M2M_WIFI_REQ_DHCP_CONF, uint8* );
Set the IP Address.
Start M2M socket Application.
8.4 Default Connection
The host MCU application may establish a Wi-Fi connection without prior knowledge to the AP information by
calling the . m2m_wifi_default_connect API
Default connection relies on the connection profiles provisioned into ATWINC serial flash via the provisioning
method Provisioning. Alternatively, connection profiles are created and stored in described in Chapter 12:
ATWINC serial flash when the host MCU application successfully connects once to an AP using the
m2m_wifi_connect API described in Section . If there are no cached profiles or if a connection cannot be 8.3
established with any of the cached profiles, an event of type M2M_WIFI_RESP_DEFAULT_CONNECT is delivered to
the host driver indicating failure.
Upon successful default connection, the host application can read the current Wi-Fi connection status
information by calling the API. The m2m_wifi_get_connection_info m2m_wifi_get_connection_info is an
asynchronous API. The actual connection information is provided in the asynchronous event
M2M_WIFI_RESP_CONN_INFO in Wi-Fi callback. The callback parameter of type provides tstrM2MConnInfo
information about AP SSID, RSSI (AP received power level), security type, and IP address obtained by DHCP.
A connection profile is cached in the serial flash if and only if the connection is success-
fully established with the target AP.
The Wi-Fi default connection operation is described in . Figure 8-3
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
25
Figure 8- -Fi Default Connection 3. Wi
M2M APPLICATION M2M HOST DRIVER
m2m_wifi_default_connect();
wifi_cb(M2M_WIFI_REQ_CON_STATE_CHANGED,
tstrM2mWifiStateChanged* );
wifi_cb(M2M_WIFI_REQ_DHCP_CONF, uint8* );
Set the IP Address.
Start M2M socket Application.
8.5 -Fi Security Wi
The following types of security are supported in ATWINC Wi-Fi STA mode.
M2M_WIFI_SEC_OPEN
M2M_WIFI_SEC_WEP
M2M_WIFI_SEC_WPA_PSK (WPA/WPA2-Personal Security Mode i.e. Passphrase)
M2M_WIFI_SEC_802_1X (WPA-Enterprise security)
The currently supported 802.1x authentication algorithm is EAP-TTLS with MsChapv2.0
authentication.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
26
8.6 Example Code
#define M2M_802_1X_USR_NAME "user_name"
#define M2M_802_1X_PWD "password"
#define AUTH_CREDENTIALS {M2M_802_1X_USR_NAME M2M_802_1X_PWD, }
int main (void)
{
tstrWifiInitParam param;
tstr1xAuthCredentials gstrCred1x =AUTH_CREDENTIALS;
nm_bsp_init();
m2m_memset((uint8*)& ,param 0, sizeof(param));
param pfAppWifiCb. = wifi_event_cb;
/* intilize the WINC Driver
*/
ret =m2m_wifi_init(&param);
if (M2M_SUCCESS != ret)
{
"Driver Init Failed <%d>\M2M_ERR(n", ret);
while(1);
}
/* Connect to a WPA-Enterprise AP
*/
m2m_wifi_connect( ,"DEMO_AP" sizeof("DEMO_AP" ), M2M_WIFI_SEC_802_1X,
( *)&uint8 gstrCred1x, M2M_WIFI_CH_ALL);
while(1)
{
/************************************************************************/
/* Handle the app state machine plus the WINC event handler */
/************************************************************************/
while(m2m_wifi_handle_events( )NULL != M2M_SUCCESS)
{
}
}
}
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
27
9 ATWINC Socket Programming
9.1 Overview
The ATWINC socket application programming interface (API) provides a method that allows host MCU
application to interact with intranet and remote internet hosts. The ATWINC sockets API is based on the BSD
(Berkeley) sockets. This chapter explains the ATWINC socket programming and how it differs from regular
BSD sockets.
This chapter assumes the reader to have a basic understanding of the BSD sockets,
TCP Internet protocols, UDP, and the . Follow the online references provided in link in
the name of each topic for more information.
9.1.1 ATWINC Socket Types
The ATWINC sockets API provides two types of sockets:
Datagram sockets (connection-less sockets) - which use the UDP protocol
Stream sockets TCP (connection oriented sockets) - which use the protocol
9.1.2 Socket Properties
Each ATWINC socket is identified by a unique combination of:
Socket ID: It is a unique identifier for each socket. This is the return value of the " " API. socket
Local socket address: A combination of ATWINC IP address and port number assigned by the
ATWINC firmware for the socket.
Protocol: This is the transport layer protocol, either TCP or UDP.
Note that TCP port 53 and UDP port 53 represent two different sockets.
Remote socket address: Applicable only for TCP stream sockets. This is necessary since TCP is
connection oriented. Each connection is made to a specific IP address and port number requires a
separate socket. The remote socket address can be obtained in the socket event callback as discussed
later.
9.1.3 Limitations
The ATWINC ckets API support a maximum of seven TCP sockets and 4 for UDP sockets so
The ATWINC sockets API support only IPv4. It does not support IPv6.
9.2 ATWINC Sockets API
9.2.1 API Prerequisites
The C header file ncludes all the necessary socket API function declarations. When using : Isocket.h
any ATWINC sockets API described in the following sections, the host MCU application should to include
the socket.h header file.
Initialization: The ATWINC socket API shall be initialized once before calling any sockets API function.
This is done by using the " . socketInit" API described in the Section 9.2.3
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
28
9.2.2 Non-blocking Asynchronous Socket APIs
Most ATWINC socket APIs are asynchronous function calls that do not block the host MCU application. The
behavior of ATWINC asynchronous APIs is described in Section . 6.4.1
For example, the host MCU application can register an application-defined socket event callback function using
the ATWINC socket API . When the host MCU application calls the socket API registerSocketCallback
connect SUCCES, the API returns a zero value ( S) immediately indicating that the request is accepted. The host
MCU application must then wait for the ATWINC socket API to call the registered socket callback when the
connection is established or if there was a connection timeout. The socket callback function provides the
necessary information to determine if the connection was successful or not.
9.2.3 Socket API Functions
ATWINC sockets API provide the following functions (see the subsections below).
9.2.3.1 socketInit
The host MCU application must call the API once during initialization. The API is a synchronous socketInit
API.
9.2.3.2 registerSocketCallback
The function allows the host MCU application to provide the ATWINC sockets with registerSocketCallback
application-defined event callbacks for socket operations. The API is a synchronous API. The API registers the
following callbacks:
The socket event callback
The DNS resolve callback
The socket event callback is an application-defined function that is called by the ATWINC socket API whenever
a socket event occurs. Within this handler, the host MCU application should provide an application-defined
logic that handles the events of interest.
The DNS resolve event handler is the application-defined function that is called by the ATWINC socket API to
return the results of . By implication, this will only occur after the host MCU application has gethostbyname
called the function. If successful, the callback provides the IP address for the desired domain gethostbyname
name.
9.2.3.3 socket
The function creates a new socket of a specified type and returns the corresponding socket ID. The socket
API is a synchronous API.
The socket ID is required by most other socket functions and is also passed as an argument to the socket
event callback function to identify which socket generated the event.
9.2.3.4 connect
The function is used with TCP sockets to establish a new connection to a TCP server. connect
The function will result in a connect SOCKET_MSG_CONNECT sent to the socket event handler callback upon
completion. The connect event will be sent when the TCP server accepts the connection or, if no remote host
response is received, after a timeout interval of approximately 30 seconds.
The event callback provides a contain-SOCKET_MSG_CONNECT tstrSocketConnectMsg
ing an error code. The error code is 0 if the connection was successful or a negative
value to indicate an error due to a timeout condition or if is used with UDP connect
socket.
Figure 9-1 shows the ATWINC socket API connect to remote server host.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
29
Figure 9- TCP Client API Call Sequence 1.
9.2.3.5 bind
The function can be used for server operation for both UDP and TCP sockets. Its purpose is to associate bind
a socket with an address structure (port number and IP address).
The bind function call will result a event sent to the socket callback handler with the bind SOCKET_MSG_BIND
status. Calls to functions should not be issued until the bind listen, , , send sendto recv, and recvfrom
callback is received.
9.2.3.6 listen
The function is used for server operations with TCP stream sockets. After calling the API the listen listen
socket will accept a connection request from a remote host. The function causes a listen
SOCKET_MSG_LISTEN event notification to be sent to the host after the socket port is ready to indicate listen
operation success or failure.
When a remote peer establishes a connection, a event notification is sent to the SOCKET_MSG_ACCEPT
application.
9.2.3.7 accept
The function is deprecated and calling this API has no effect. It is kept only for backward compatibility. accept
The listen API will implicitly accepts accept connections from a TCP remote peer.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
30
Figure 9- TCP Server API Call Sequence 2.
Although the function is deprecated, the event occurs whenever a remote host accept SOCKET_MSG_ACCEPT
connects to the ATWINC TCP server. The event message will contain the IP address and port number of the
connected remote host.
9.2.3.8 send
The function is used by the application to send data to a remote host. The function can be used to send send
send either UDP or TCP data depending on the type of socket. For a TCP socket a connection must be
established first. For a UDP socket, the target remote host must be specified as part of the address structure
during the function. bind
The function will generate a event callback after the data is transmitted to the remote send SOCKET_MSG_SEND
host. For TCP sockets, this event guarantees that the data has been delivered to the remote host TCP/IP stack
(the remote application must use the function to be able to read the data though). For UDP sockets it recv
means that the data has been transmitted but there are no guarantees that the data has arrived to the remote
host as per UDP protocol nature. The application is responsible to guarantee data delivery in the UDP sockets
case.
The event callback will return the size of the data transmitted if the transmission in the SOCKET_MSG_SEND
success case and zero or negative value in case of an error.
9.2.3.9 sendto
The function is used by the application to send UDP data to a remote host. It can only be used with sendto
UDP sockets. The IP address and port of the destination remote host is included as a parameter to the sendto
function.
The event callback returns the size of the data transmitted in the success case and zero SOCKET_MSG_SENDTO
or negative value in case of an error.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
31
9.2.3.10 recv / recvfrom
The a functions are used to read data from TCP and UDP sockets respectively. Their recv nd recvfrom
operation is otherwise identical.
The host MCU application calls the or function with a pre allocated buffer. When the recv recvfrom
SOCKET_MSG_RECV or event callback arrives this buffer will contain the received data. SOCKET_MSG_RECVFROM
The received data size indicates the status:
Positive: Data received.
Zero: Socket connection is terminated.
Negative value: This indicates an error.
In the case of TCP sockets, it i recommended to call the function after each successful socket s recv
connection (client or server). Otherwise, received data will be buffered in the ATWINC firmware wasting the
systems resources until the socket is explicitly closed using a function call. close
9.2.3.11 close
The function is used to release the resources allocated to the socket and, for a TCP stream socket, also close
terminate an open connection.
Each call to the function should be match with a call to the function. In addition, sockets that socket ed close
have been accepted on a server socket port should also be closed using this function.
9.2.3.12 setsockopt
The function may be used to set socket options to control the socket behavior. setsockopt
The options supported are:
SO_SET_UDP_SEND_CALLBACK send sendto: Enables or disables the / event callbacks. The user might
want to disable the event callback for UDP sockets to enhance the socket connection sendto
throughput.
IP_ADD_MEMBERSHIP: Used to subscribe to IP Multicast addresses.
IP_DROP_MEMBERSHIP: Used to unsubscribe to IP Multicast addresses.
Disabling send/sendto callbacks using is recommended in high through-setsockopts
put applications.
9.2.3.13 gethostbyname
The function is used to resolve a host name (e.g. URL) to a host IP address via the Domain gethostbyname
Name System ( ). This is limited for IPv4 addresses only. Operation depends on having configured a DNS DNS
server IP address and having access to the DNS hierarchy through the internet.
After has been called, a callback to the DNS resolver handler will be made. If the IP address gethostbyname
has been determined it will be returned. If it cannot be determined or if the DNS server is not accessible (30
second timeout) an IP address value of zero will be indicated.
A return IP value of zero indicates an error (e.g. the internet connection is down or DNS
is unavailable) and the host MCU application may try the function call gethostbyname
again later.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
32
9.2.4 Summary
Table 9-1 summarizes the ATWINC socket API and shows its compatibility with BSD socket APIs:
Table 9- ATWINC Socket API Summary 1.
BSD API
ATWINC API
ATWINC API
Type
Server/
Client
TCP/UDP
Brief
socket
socket
Synchronous
Both
both
Creates a new socket
connect
connect
Asynchronous
Client
TCP
Initialize a TCP connection request to a re-
mote server
bind
bind
Asynchronous
Server
both
Binds a socket to an address (address/port)
listen
listen
Asynchronous
Server
TCP
Allow a bound socket to listen to remote con-
nections for its local port
accept
accept
Depreciated, Implicit accept in listen
send
send
Asynchronous
Both
Both
Sends packet
sendto
sendto
Asynchronous
Both
UDP
Sends packet over UDP sockets
write
Not supported
recv
recv
Asynchronous
Both
Both
Receive packet
recvfrom
recvfrom
Asynchronous
Both
Both
Receive packet
read
Not supported
close
close
Synchronous
Both
Both
Terminate TCP connection and release sys-
tem resources
gethostbyname
gethostbyname
Asynchronous
Both
Both
Get IP address of certain host name
gethostbyaddr
Not supported
select
Not supported
poll
Not supported
setsockopt
setsockopt
Synchronous
Both
Both
Sets socket opti on
getsockopt
Not supported
htons/ntohs
_htons/_ntohs
Synchronous
Both
Both
Convert a 2-byte integer from the host repre-
sentation to the Network byte order represen-
tation (and vice versa)
htonl/ntohl
_htonl/_ntohl
Synchronous
Both
Both
Convert a 4-byte integer from the host repre-
sentation to the Network byte order represen-
tation (and vice versa)
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
33
9.3 Socket Connection Flow
In the following sub-sections the TCP and UDP (client and server) operations are described in detail.
Figure 9- Typical Socket Connection Flow 3.
socketInit
registerSocketCallback
bind
Socket
Accept event
callback
connect
listen
Bind event
callback
Listen event
callback
socketInit
registerSocketCallback
Socket
recv
send
Send event
callback
Recv event
callback
send
recv
close
recv
Recv event
callback
close
Server Operations
Data Exchange
End Connection
Client Operations
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
34
9.3.1 TCP Client Operation
Figure 9-4 shows the message flow for transferring data with a TCP client.
Figure 9- TCP C ent Sequence Diagram 4. li
APPLICATION
connect(clientSocketHdl)
SOCKET_MSG_CONNECT SOCKET_CMD_CONNECT
HOST
DRIVER WINC
SOCKET_CMD_CONNECT
socket(SOCK_STREAM)
clientSocketHdl
Data Exchange (send/recv)
close(clientSocketHdl)
SOCKET_CMD_CLOSE
TCP(SYN,ACK)
TCP(SYN)
send(clientSocketHdl, data) SOCKET_CMD_SEND
recv(clientSocketHdl)
SOCKET_CMD_RECV
SOCKET_CMD_RECV
TCP Packet
TCP Packet
SOCKET_MSG_RECV
TCP(FIN)
Notes: 1. The host application must register a socket notification callback function. The function must be of
type and must handle socket event notifications appropriately. tpfAppSocketCb
2. If the client knows the IP of the server, it may call directly as shown in . If only connect Figure 9-4
the server URL is known, then the application should resolve the server URL first calling the
gethostbyname API.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
35
9.3.2 TCP Server Operation
Figure 9- TCP Server Sequence Diagram 5.
APPLICATION
bind(listenSocketHdl,port)
SOCKET_MSG_BIND
SOCKET_CMD_BIND
HOST
DRIVER WINC
SOCKET_CMD_BIND
socket(SOCK_STREAM)
listenSocketHdl
Data Exchange (send/recv)
close(acceptedSocketHdl) SOCKET_CMD_CLOSE
TCP(SYN)
send(acceptedSocketHdl, data) SOCKET_CMD_SEND
recv(acceptedSocketHdl) SOCKET_CMD_RECV
SOCKET_CMD_RECV
TCP Packet
TCP Packet
SOCKET_MSG_RECV
TCP(FIN)
listen(listenSocketHdl)
SOCKET_CMD_LISTEN
SOCKET_CMD_LISTEN
SOCKET_MSG_LISTEN
TCP(SYN,ACK)
SOCKET_CMD_ACCEPT
SOCKET_MSG_ACCEPT
Get the accepted
socket handle
è
è
è
èè
acceptedSocketHdl
close(listenSocketHdl) SOCKET_CMD_CLOSE
Note: The host application must register a socket notification callback function. The function must be of type:
tpfAppSocketCb and must handle socket event notifications appropriately.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
36
9.3.3 UDP Client Operation
Figure 9-6 shows the message ow for transferring data with a UDP client.
Figure 9- UDP Client Sequence Diagram 6.
APPLICATION HOST
DRIVER WINC
socket(SOCK_DGRAM)
clientSocketHdl
Data Exchange (send/recv)
close(clientSocketHdl)
SOCKET_CMD_CLOSE
sendto(clientSocketHdl,data,addr) SOCKET_CMD_SENDTO
recvfrom(clientSocketHdl) SOCKET_CMD_RECVFROM
SOCKET_CMD_RECVFROM UDP Packet
SOCKET_MSG_RECVFROM
UDP Packet
Notes: 1. The rst send message must be performed with the API with the destination address sendto
specied.
2. If further messages are to be sent to the same address, the API can be used. send
3. can be used instead of . recv recvfrom
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
37
9.3.4 UDP Server Operation
Figure 9-7 shows the message ow for transferring data after establishing a UDP server.
Figure 9- UDP Server Sequence Diagram 7.
APPLICATION HOST
DRIVER WINC
socket(SOCK_DGRAM)
serverSocketHdl
Data Exchange (send/recv)
close(serverSocketHdl)
SOCKET_CMD_CLOSE
sendto(serverSocketHdl, data) SOCKET_CMD_SENDTO
recvfrom(serverSocketHdl) SOCKET_CMD_RECVFROM
UDP Packet
SOCKET_MSG_RECVFROM
UDP Packet
bind(serverSocketHdl,port)
SOCKET_MSG_BIND
SOCKET_CMD_BIND
SOCKET_CMD_BIND
SOCKET_CMD_RECVFROM
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
38
9.3.5 DNS Host Name Resolution
Figure 9-8 shows the message ow for resolving a URL to and IP address.
Figure 9- DNS Resolution Sequence 8.
APPLICATION HOST
DRIVER WINC
gethostbyname(hostName)
dnsResolveCB(hostName, hostIP)
SOCKET_CMD_DNS_RESOLVE
DNS Query
DNS_Resolver
formats a DNS
Query with the
given hostName
DNS Answer
SOCKET_CMD_DNS_RESOLVE
DNS_Resolver
Extracts the
hostIP for
hostName from
the DNS Answer
registerSocketCallback(dnsResolveCB)
Notes: 1. The host application requests to resolve hostname (e.g. www.foobar.com), by calling the function
gethostbyname.
2. Before calling the gethostbyname, the application must register a DNS response callback function
using the function . registerSocketCallback
3. After the ATWINC DNS_Resolver module obtains the IP a ress (hostIP) corresponding to the dd
given HostName, the will be called with the hostIP. dnsResolveCB
4. If an error occurs or if the DNS request encounters a timeout, the is called with IdnsResolveCB P
address value zero indicating a failure to resolve the domain name.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
39
9.4 Example Code
This section provides code samples for dierent socket applications. For additional socket code example, refer
to WINC3400 Software Programming Guide. [R03] AT
9.4.1 TCP Client Example Code
SOCKET clientSocketHdl;
uint8 rxBuffer[256];
/* Socket event handler.
*/
void tcpClientSocketEventHandler(SOCKET sock u8Msg pvMsg, uint8 , * void )
{
if(sock clientSocketHdl == )
{
if(u8Msg == SOCKET_MSG_CONNECT)
{
// Connect Event Handler.
tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg;
if(pstrConnect s8Error-> == 0)
{
// Perform data exchange.
uint8acSendBuffer[256];
uint16 u16MsgSize;
// Fill in the acSendBuffer with some data here
// send data
send(clientSocketHdl acSendBuffer u16MsgSize, , , 0);
// Recv response from server.
recv(clientSocketHdl rxBuffer rxBuffer, , ( sizeof ), 0);
}
else
{
"TCP Connection Failed\printf(n");
}
}
else if(u8Msg == SOCKET_MSG_RECV)
{
tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
if((pstrRecvMsg pu8Buffer-> != NULL) && (pstrRecvMsg s16BufferSize-> > 0))
{
// Process the received message.
// Close the socket.
close(clientSocketHdl);
}
}
}
}
// This is the DNS callback. The response of gethostbyname is here.
void dnsResolveCallback( *uint8 pu8HostName u32ServerIP, uint32 )
{
struct sockaddr_in strAddr;
if(u32ServerIP != 0)
{
clientSocketHdl =socket( ,AF_INET SOCK_STREAM,u8Flags);
if(clientSocketHdl >= 0)
{
strAddr.sin_family =AF_INET;
strAddr.sin_port =_htons(443);
strAddr. .sin_addr s_addr u32ServerIP = ;
connect(clientSocketHdl, ( struct sockaddr strAddr sizeof struct sockaddr_in *)& , ( ));
}
}
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
41
recv(acceptedSocketHdl rxBuffer rxBuffer, , ( sizeof ), 0);
}
else
{
"Accept Failed\printf(n");
}
}
else if(u8Msg == SOCKET_MSG_RECV)
{
tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
if((pstrRecvMsg pu8Buffer pstrRecvMsg s16BufferSize-> != NULL) && ( -> > 0))
{
// Process the received message
// Perform data exchange
uint8 acSendBuffer[256];
uint16 u16MsgSize;
// Fill in the acSendBuffer with some data here
// Send some data.
send(acceptedSocketHdl, acSendBuffer u16MsgSize, , 0);
// Recv response from client.
recv(acceptedSocketHdl rxBuffer rxBuffer, , ( sizeof ), 0);
// Close the socket when finished.
if(bIsfinished)
{
close(acceptedSocketHdl);
close(listenSocketHdl);
}
}
}
}
/* This function needs to be called from main function. For the callbacks to be invoked correctly, the API
m2m_wifi_handle_events should be called continuously from main. */
void tcpStartServer(uint16 u16ServerPort)
{
struct sockaddr_in strAddr;
// Initialize the socket layer.
socketInit();
// Register socket application callbacks.
registerSocketCallback tcpServerSocketEventHandler NULL( , );
// Create the server listen socket.
listenSocketHdl =socket(AF_INET SOCK_STREAM, , 0);
if(listenSocketHdl >= 0)
{
strAddr.sin_family =AF_INET;
strAddr.sin_port u16ServerPort =_htons( );
strAddr.sin_addr s_addr 0. = ; //INADDR_ANY
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
42
bind(listenSocketHdl, ( struct sockaddr strAddr sizeof struct sockaddr_in *)& , ( ));
}
}
9.4.3 UDP Client Example Code
SOCKET clientSocketHdl;
uint8 rxBuffer[256], [256]; acSendBuffer
/* Socket event handler */
void udpClientSocketEventHandler(SOCKET sock u8Msg pvMsg, uint8 , * void )
{
if((u8Msg == SOCKET_MSG_RECV) || (u8Msg == SOCKET_MSG_RECVFROM))
{
tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
if((pstrRecvMsg pu8Buffer pstrRecvMsg s16BufferSize-> != NULL) && ( -> > 0))
{
uint16 len;
// Format a message in the acSendBuffer and put its length in len
sendto(clientSocketHdl acSendBuffer len, 0, , ,
( *)&struct sockaddr strAddr sizeof struct sockaddr_in, ( ));
recvfrom(clientSocketHdl rxBuffer rxBuffer, , ( sizeof ), 0);
// Close the socket after finished
close(clientSocketHdl);
}
}
}
/* This function needs to be called from main function. For the callbacks to be invoked correctly, the API
m2m_wifi_handle_events should be called continuously from main.
*/
void udpClientStart(char * ) pcServerIP
{
struct sockaddr_in strAddr ;
// Initialize the socket layer.
socketInit();
// Register socket application callbacks.
registerSocketCallback udpClientSocketEventHandler NULL( , );
clientSocketHdl =socket(AF_INET SOCK_STREAM, ,u8Flags);
if(clientSocketHdl >= 0)
{
uint16 len;
strAddr.sin_family =AF_INET;
strAddr.sin_port =_htons(1234);
strAddr.sin_addr s_addr. =nmi_inet_addr(pcServerIP);
// Format some message in the acSendBuffer and put its length in len
sendto(clientSocketHdl acSendBuffer len, 0, , , (struct sockaddr strAddr*)& ,
sizeof struct sockaddr_in( ));
recvfrom(clientSocketHdl rxBuffer rxBuffer, , ( sizeof ), 0);
}
}
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
43
9.4.4 UDP Server Example Code
SOCKET serverSocketHdl;
uint8 rxBuffer[256];
/* Socket event handler.
*/
void udpServerSocketEventHandler(SOCKET sock u8Msg pvMsg, uint8 , * void )
{
if(u8Msg == SOCKET_MSG_BIND)
{
tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg;
if(pstrBind status-> == 0)
{
// call Recv
recvfrom(serverSocketHdl rxBuffer rxBuffer, , ( sizeof ), 0);
}
else
{
"Bind Failed\printf(n");
}
}
else if(u8Msg == SOCKET_MSG_RECV)
{
tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
if((pstrRecvMsg pu8Buffer pstrRecvMsg s16BufferSize-> != NULL) && ( -> > 0))
{
// Perform data exchange.
uint8 acSendBuffer[256];
uint16 u16MsgSize;
// Fill in the acSendBuffer with some data
// Send some data to the same address.
sendto(acceptedSocketHdl acSendBuffer u16MsgSize, , , 0,
pstrRecvMsg-> strRemoteAddr, (pstrRecvMsg-> strRemoteAddr) sizeof );
// call Recv
recvfrom(serverSocketHdl rxBuffer rxBuffer, , ( sizeof ), 0);
// Close the socket when finished.
close(serverSocketHdl);
}
}
}
/* This function needs to be called from main function. For the callbacks to be invoked correctly, the API
m2m_wifi_handle_events should be called continuously from main.
*/
void udpStartServer(uint16 u16ServerPort)
{
struct sockaddr_in strAddr;
// Initialize the socket layer.
socketInit();
// Register socket application callbacks.
registerSocketCallback udpServerSocketEventHandler NULL( , );
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
44
// Create the server listen socket.
listenSocketHdl =socket(AF_INET SOCK_DGRAM, , 0);
if(listenSocketHdl >= 0)
{
strAddr.sin_family =AF_INET;
strAddr.sin_port u16ServerPort =_htons( );
strAddr.sin_addr s_addr 0. = ; //INADDR_ANY
bind(serverSocketHdl, ( struct sockaddr strAddr sizeof struct sockaddr_in *)& , ( ));
}
}
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
45
10 Transport Layer Security (TLS)
T ransport Layer Security layer sits on top of TCP and provides security services including privacy, he T
authenticity, and message integrity. Various security methods are available with TLS in ATWINC rmware.
ATWINC implements the Transport Layer Security protocol TLS v1.0, client mode.
10.1 TLS Connection Establishment
From the application’s point of view, the TLS functionality is wrapped behind the socket APIs. This hides the
complexity of TLS from the application which could use the TLS in the same fashion as the TCP client. The
main dierence between TLS sockets and regular TCP sockets is that the application sets the
SOCKET_FLAGS_SSL while creating the TLS client socket. The detailed sequence of TLS connection
establishment is described in . Figure 10-1
Do not miss both the ag and the correct port number in your TLS SOCKET_FLAGS_SSL
application. For instance an HTTP client application shall use no ags when calling
socket API function and connect to port 80. The same application source code be-
comes an HTTPS client application if you use the ag and change SOCKET_FLAGS_SSL
the port number to to port 433. connect
Figure 10- TLS Connection Establishment 1.
APPLICATION
Create SSL Session
connect(sslSocketHdl)
SOCKET_MSG_CONNECT SOCKET_CMD_SSL_CONNECT
HOST
DRIVER WINC
SOCKET_CMD_SSL_CONNECT
TLS Handshake
socket(SOCK_FLAGS_SSL)
sslSocketHdl
Data Exchange (send/recv)
close(sslSocketHdl) SOCKET_CMD_SSL_CLOSE
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
46
10.2 Server Certicate Installation
10.2.1 Technical Background
10.2.1.1 Public Key Infrastructure
The TLS security is based on the , in which: Public Key Infrastructure PKI
A server has its public key stored in a digital certicate with X.509 standard format
Certicate AuthorityThe server must have its X.509 certicate issued by CA which is in turn might be
certied by another CA
This structure forms a chain of X.509 certicates known as chain of trust
The top most CA of the Chain is known to be the of the chain Trusted Root Certificate Authority
10.2.1.2 TLS Server Authentication
When a TLS client initiates a connection with a server, the server sends its X.509 certificate chain (may
or may not include the root certicate) to the client
The client must authenticate the Server (verify the Server identity) before starting data exchange
The client must verify the entire certicate chain and also verify that the root certicate authority of the
chain is in the client’s trusted root certificate store
10.2.2 Adding a Certicate to the WINC Trusted Root Certicate Store AT
Before connecting to a TLS Server, the root certificate of the server must be installed on the
AT ATWINC3400. If this is not done, the TLS Connection to the server is aborted locally by WINC.
The root certicate must be in format. If it is not provided in format, it must be converted before DER DER
installation. See for certicate formats and conversion methods. Appendix A
To install the certicate, execute with the following syntax: root_certicate_downloader.exe
Refer to Appendix C for more information on how to download X509 certificates on WINC serial ash. AT
10.3 WINC TLS Limitations AT
10.3.1 Modes of Operation
The current TLS implementation supports TLSv1.0 Client operation only. TLS Server is not supported.
10.3.2 Concurrent Connections
Only two TLS concurrent connections are allowed.
10.3.3 Supported Cipher Suites
The current implementation is limited to the following cipher suites:
TLS_RSA_WITH_AES_128_CBC_SHA
TLS_RSA_WITH_AES_256_CBC_SHA
TLS_RSA_WITH_AES_128_CBC_SHA256
TLS_RSA_WITH_AES_256_CBC_SHA256
10.3.4 Supported Hash Algorithms
The current implementation supports MD5, SHA-1, and SHA256 hash algorithms.
root_certificate_downloader.exe -n N File1.cer File2.cer .. FileN.cer
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
47
10.4 SSL Client Code Example
SOCKET sslSocketHdl;
uint8 rxBuffer[256];
/* Socket event handler.
*/
void SSL_SocketEventHandler( ,SOCKET sock uint8 u8Msg,void *pvMsg)
{
if(sock == sslSocketHdl)
{
if(u8Msg == SOCKET_MSG_CONNECT)
{
// Connect event
tstrSocketConnectMsg *pstrConnect = ( tstrSocketConnectMsg*)pvMsg;
if(pstrConnect s8Error-> == 0)
{
// Perform data exchange.
uint8 acSendBuffer[256];
uint16 u16MsgSize;
// Fill in the acSendBuffer with some data here
// Send some data.
send( ,sock acSendBuffer, u16MsgSize, 0);
// Recv response from server.
recv(sslSocketHdl rxBuffer rxBuffer, , ( sizeof ), 0);
}
else
{
"SSL Connection Failed\printf(n");
}
}
else if(u8Msg == SOCKET_MSG_RECV)
{
tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
if((pstrRecvMsg pu8Buffer-> != NULL) ( && pstrRecvMsg-> > 0)) s16BufferSize
{
// Process the received message here
// Close the socket if finished.
close(sslSocketHdl);
}
}
}
}
/* This is the DNS callback. The response of gethostbyname is here.
*/
void dnsResolveCallback( *uint8 pu8HostName u32ServerIP, uint32 )
{
struct sockaddr_in rAddr st ;
if(u32ServerIP != 0)
{
sslSocketHdl =socket(AF_INET SOCK_STREAM, ,u8Flags);
if(sslSocketHdl >= 0)
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
48
{
strAddr.sin_family =AF_INET;
strAddr. = (443); sin_port _htons
strAddr. .sin_addr s_addr u32ServerIP = ;
connect(sslSocketHdl, ( struct sockaddr strAddr *)& , ( sizeof struct sockaddr_in));
}
}
else
{
"DNS Resolution Failed\printf(n");
}
}
/* This function needs to be called from main function. For the callbacks to be invoked correctly, the API
m2m_wifi_handle_events should be called continuously from main.
*/
void SSL_Connect( *char pcServerURL)
{
// Initialize the socket layer.
socketInit();
// Register socket application callbacks.
registerSocketCallback SSL_SocketEventHandler dnsResolveCallback( , );
// Resolve Server URL.
gethostbyname((uint8*)pcServerURL);
}
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
51
12 Provisioning
For normal operation the WINC device needs certain parameters to be loaded. In particular, when operating AT
in station mode, it needs to know the identity (SSID) and credentials of the access point to which it will connect.
The entry of this information is facilitated through the following provisioning steps.
The WINC software supports three methods of provisioning: AT 3400
BLE based in which a SmartPhone detects the WINC and uses an APP to transfer the information AT
from the user to the WINC3400 AT
HTTP-based (browser) provisioning while WINC is in AP mode AT
Wi-Fi Protected Setup (WPS)
12.1 BLE Provisioning
This mode of provisioning is a major feature of the WINC3400 and is likely to be the method of choice. It has AT
the advantage that it is simple and intuitive for the user and does not disrupt normal SmartPhone operation
during the process.
In this method the host MCU instructs the WINC3400 to enable the BLE provisioning mode using API AT
m2m_wifi_start_ble_provision_mode. This causes the BLE to be activated and to start issuing BLE
beacons. The beacons will be detected by a suitable SmartPhone, which will inform the user that the device is
available for provisioning and provide information about the APP required to complete the process. When the
user obtains/runs the APP it will request the provisioning information and transfer to the WINC3400. The AT
ATWINC3400 will store the information and then connect to the specified AP, thus making itself ready for use.
The user needs to load the Atmel_IoT APP on either iOS or Andorid Smartphone. Upon launching the APP will
search for WINC3400 based products that are available for provisioning. A list of products will be displayed AT
using their user-friendly names:
When the user selects a product and clicks the ‘>’ symbol, the Access Points visible to the IoT device will be
shown on the screen:
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
52
The user may then select the Access Point to which he wants to connect the IoT device and enter the
Passphrase at the top of the screen. After the information is entered, the provisioning information is passed to
the device using BLE and then passed on to the Wi-Fi component of the ATWINC3400. The Wi-Fi component
passes the credentials to the host using the callback M2M_WIFI_RESP_PROVISION_INFO and placing the
information in the structure tstrM2MProvisionInfo.
Figure 12- BLE Provisioning Sequence Diagram 1.
APPLICATION
BLE hardware activated
Beaconing
Beacons detected by User device and
presented to user
User selects device and
observes list of Aps
seen by device
User selects AP and
enter PassPhrase
Credentials passed to
BLE in WINC3400
Credentials passed to
Wi-Fi in WINC3400
Credentials passed to Wi-
Fi in WINC3400
Turn off BLE module
m2m_wifi_start_ble_provision_mode
M2M_WIFI_RESP_PROVISION_INFO
M2M_WIFI_REQ_START_BLE_PROVISION_MODE
Run Atmel_IoT
App
BLE
M2M_WIFI_RESP_PROVISION_INFO
HOST
DRIVER WINC USER DEVICE
Wi-Fi Connection
Procedure
Figure 12-1 shows the provisioning operation for an WINC device. The detailed steps are described in the AT
code example below.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
53
12.1.1 BLE Provisioning Code Example
void wifi_event_cb(uint8 u8WiFiEvent,void * ) pvMsg
{
if(u8WiFiEvent == M2M_WIFI_RESP_PROVISION_INFO)
{
tstrM2MProvisionInfo *provInfo = (tstrM2MProvisionInfo*)pvMsg;
if(provInfo u8Status-> == M2M_SUCCESS)
{
// connect to the provisioned AP.
m2m_wifi_connect((char*)provInfo au8SSID-> , strlen(provInfo au8SSID -> ),
p ->rovInfo u8SecType rovInfo au8Password, p -> , M2M_WIFI_CH_ALL);
"PROV SSID : %s\printf(n", p ->rovInfo au8SSID);
"PROV PSK : %s\printf(n", p ->rovInfo au8Password);
}
else
{
"(ERR) Provisioning Failed\n"printf( );
}
}
}
int main()
{
tstrWifiInitParam param;
// Platform specific initializations.
// Driver initialization.
param pfAppWifiCb. =wifi_event_cb;
if(!m2m_wifi_init(&param))
{
m2m_wifi_start_ble_provision_mode();
while(1)
{
m2m_wifi_handle_events(NULL);
}
}
}
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
54
12.2 HTTP Provisioning
12.2.1 Introduction
In this method, the WINC is placed in AP mode and another device with a browser capability (mobile phone, AT
tablet, PC, etc.) is instructed to connect to the WINC HTTP server. Once connected, the desired AT
conguration can be entered.
12.2.2 Limitations
The current implementation of the HTTP Provisioning has the following limitations:
ATWINC AP limitations apply in provisioning mode. See Section 11.3: Limitations for a list of AP mode
limitations.
Provisioning uses AP mode with open security. No Wi-Fi security nor application level security (e.g. TLS)
is used and therefore the AP credentials entered by the user are sent on the clear and can be seen by
eavesdroppers.
The WINC Provisioning home page is a static HTML page. No server-side scripting allowed in the AT
ATWINC HTTP server.
Only APs with WPA-personal security (passphrase based) and no security (Open network) can be
provisioned. WEP and WPA-Enterprise APs cannot be provisioned.
The Provisioning is responsible to deliver the connection parameters to the application, the connection
procedure and the connection parameters validity its application responsibility
12.2.3 Basic Approach
The HTTP provisioning home page is as shown in . Figure 12-2
Figure 12- WINC HTTP Provisioning Page 2. AT
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
56
10. The user presses “Connect”.
The WINC will then turn o AP mode and start connecting to the provisioned AP. AT
12.2.5 HTTP Redirect Feature
The WINC HTTP provisioning server supports the HTTP redirect feature, which forces all HTTP trac AT
originating from the associated user device to be redirected to the WINC provisioning home page. AT
This simplies the mechanism of loading the provisioning page instead of typing the exact web address of the
http provisioning server.
To enable this feature, the redirect ag should be set when calling the API
m2m_wifi_start_provision_mode. See the below code example for details.
12.2.6 HTTP Provisioning Code Example
void wifi_event_cb(uint8 u8WiFiEvent,void * ) pvMsg
{
if(u8WiFiEvent == M2M_WIFI_RESP_PROVISION_INFO)
{
tstrM2MProvisionInfo *provInfo = (tstrM2MProvisionInfo*)pvMsg;
if(provInfo u8Status-> == M2M_SUCCESS)
{
// connect to the provisioned AP.
m2m_wifi_connect((char*)provInfo au8SSID-> , strlen(provInfo au8SSID -> ),
p ->rovInfo u8SecType rovInfo Password, p ->au8 , M2M_WIFI_CH_ALL);
"PROV SSID : %s\printf(n", p ->rovInfo au8SSID);
"PROV PSK : %s\printf(n", p ->rovInfo au8Password);
}
else
{
"(ERR) Provisioning Failed\printf(n");
}
}
}
int main()
{
tstrWifiInitParam param;
// Platform specific initializations.
// Driver initialization.
param pfAppWifiCb. =wifi_event_cb;
if(!m2m_wifi_init(&param))
{
tstrM2MAPConfig apConfig;
uint8 bEnableRedirect = 1;
strcpy(apConfig au8SSID. , "WINC_AP");
apConfig u8ListenChannel . = 1;
apConfig u8SecType. =M2M_WIFI_SEC_OPEN;
apConfig u8SsidHide. = 0;
// IP Address
apConfig au8DHCPServerIP. [0] = 192;
apConfig au8DHCPServerIP. [1] = 168;
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
57
apConfig au8DHCPServerIP. [2] = 1;
apConfig au8DHCPServerIP. [0] = 1;
m2m_wifi_start_provision_mode(&apConfig, "atmelconfig.com" ,bEnableRedirect);
while(1)
{
m2m_wifi_handle_events(NULL);
}
}
}
12.3 -Fi Protected Setup (WPS) Wi
Most modern Access Points support the Wi-Fi Protected Setup method, typically using the push button
method. From the user’s perspective WPS is a simple mechanism to make a device connect securely to an AP
without remembering passwords or passphrases. WPS uses asymmetric cryptography to form a temporary
secure link which is then used to transfer a passphrase (and other information) from the AP to the new station.
After the transfer, secure connections are made as for normal static PSK configuration.
12.3.1 WPS Conguration Methods
There are two authentication methods that can be used with WPS:
1. PBC (Push button) method
A physical button is pressed on the AP, which puts the AP into WPS mode for a limited period of time.
WPS is initiated on the WINC3400 by calling with input parameter . AT m2m_wifi_wps WPS_PBC_TRIGGER
2. PIN method
The AP is always available for WPS initiation but requires proof that the user has knowledge of an 8-digit
PIN, usually printed on the body of the AP. Because ATWINC is often used in “headless” devices (no
user interface) it is necessary to reverse this process and force the AP to use a PIN number provided
with the WINC device. Some APs allow the PIN to be changed through conguration. WPS is initiated AT
on the WINC3400 by calling with input parameter . Given the AT m2m_wifi_wps WPS_PIN_TRIGGER
diculty of this approach it is not recommend for most applications.
The ow of messages and actions for WPS operation is shown in . Figure 12-4
12.3.2 WPS Limitations
WPS is used to transfer the WPA/WPA2 key only; other security types are not supported
The WPS standard will reject the session (WPS response fail) if the WPS button pressed on more than
one AP in the same proximity, and the application should try after couple of minutes
If no WPS button pressed on the AP, the WPS scan will timeout after two minutes since the initial WPS
trigger
The WPS is responsible to deliver the connection parameters to the application, the connection
procedure and the connection parameters validity is the application responsibility
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
58
12.3.3 WPS Control Flow
Figure 12- WPS Operation for Push Button Trigger 4.
APPLICATION
Start WPS Scan
WPS Session Ends
and AP credentials
are obtained
m2m_wifi_wps
M2M_WIFI_REQ_WPS
M2M_WIFI_REQ_WPS
M2M_WIFI_REQ_WPS
HOST
DRIVER WINC
WPS Button
Pressed on AP
WPS Registration
Protocol
Wi-Fi Connection
Procedure
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
59
12.3.4 WPS Code Example
void wifi_event_cb(uint8 u8WiFiEvent,void * ) pvMsg
{
if(u8WiFiEvent == M2M_WIFI_REQ_WPS)
{
tstrM2MWPSInfo * = (pstrWPS tstrM2MWPSInfo*)pvMsg;
if( ->pstrWPS u8AuthType != 0)
{
"WPS SSID : %s\printf(n", ->pstrWPS au8SSID);
"WPS PSK : %s\printf(n", -> pstrWPS au8PSK);
"WPS SSID Auth Type : %s\printf(n",
pstrWPS u8AuthType-> == M2M_WIFI_SEC_OPEN "OPEN" "WPA/WPA2"? : );
"WPS Channel : %d\printf(n", -> +pstrWPS u8Ch 1);
// Establish Wi-Fi connection
m2m_wifi_connect((char*)pstrWPS au8SSID-> , ( uint8)m2m_strlen( ->pstrWPS au8SSID),
pstrWPS u8AuthType pstrWPS au8PSK pstrWPS-> , -> , -> u8Ch);
}
else
{
"(ERR) WPS Is not enabled OR Timedout\printf(n");
}
}
}
int main()
{
tstrWifiInitParam param;
// Platform specific initializations.
// Driver initialization.
param pfAppWifiCb. =wifi_event_cb;
if(!m2m_wifi_init(&param))
{
// Trigger WPS in Push button mode.
m2m_wifi_wps(WPS_PBC_TRIGGER NULL, );
while(1)
{
m2m_wifi_handle_events(NULL);
}
}
}
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
60
13 Multicast Sockets
13.1 Overview
The purpose of the multicast filters is to provide the ability to send/receive messages to/from multicast
addresses. This feature is useful for one- -many communication over networks, whether is intended to send to it
Internet Protocol (IP) datagrams to a group of interested receivers in a single transmission, participate in a
zero-configuration networking or listening to a multicast stream or any other application.
13.2 How to use Filters
Whenever the application wishes to use a multicast IP address, for either sending or receiving, a filter is
needed. The application can establish this through setting the option for the required IP_ADD_MEMBERSHIP
socket accompanied by the multicast address that the application wants to use. If subsequently the host wants
to stop receiving the multicast stream it should set the option for the required socket IP_DROP_MEMBERSHIP
accompanied with the multicast address.
Adding or removing a multicast address filter will cause WINC chip firmware to add/remove both MAC layer AT
filter and IP layer filter in order to pass or prevent messages from reaching to host.
13.3 Multicast Socket Code Example
In order to illustrate the functionality, a simple example is implemented where the host application responds to
mDNS (Multicast Domain Name System) queries sent from a Computer/Mobile application. The
Computer/Mobile is looking for devices which support the service as indicated by mDNS zero configuration an
response. The WINC responds, announcing its presence and its capability of sending and receiving AT
multicast messages.
The example consists of a UDP server that binds on port 5353 (mDNS port) and waits for messages, parsing
them and replying with a previously saved response message.
Server Initialization
void MDNS_ServerInit()
{
tstrSockAddr strAddr ;
unsigned int MULTICAST_IP = 0xE00000FB; //224.0.0.251
socketInit();
dns_server_sock =socket(AF_INET SOCK_DGRAM, ,0);
"DNS_server_init \MDNS_INFO(n");
setsockopt(dns_server_sock,1,IP_ADD_MEMBERSHIP,&MULTICAST_IP MULTICAST_IP, (sizeof ));
strAddr u16Port. = (HTONS MDNS_SERVER_PORT);
bind(dns_server_sock,(struct sockaddr *)&strAddr,sizeof( )); strAddr
registerSocketCallback UDP_SocketEventHandler AppServerCb( , );
}
Sockets Events Handler
void MDNS_RecvfromCB(signed char unsigned char sock, *pu8RxBuffer,signed short s16DataSize,
*unsigned char pu8IPAddr,unsigned short u16Port pvArg, *void )
{
"DnsServer_RecvfromCB \MDNS_INFO(n");
if((pu8RxBuffer != 0) && (s16DataSize > 0))
{
tstrDnsHdr strDnsHdr;
strdnsquery;
"DNS Packet Recieved \MDNS_INFO(n");
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
61
if(MDNS_ParseQuery(&pu8RxBuffer strDnsHdr strDnsQuery[0], & ,& ))
MDNS_SendResp (sock pu8IPAddr u16Port strDnsHdr strDnsQuery, , ,& ,& );
}
else
{
"DnsServer_RecvfromCB Error !\MDNS_INFO(n");
}
}
Server Socket Callback
void signed char unsigned char signed short MDNS_RecvfromCB( sock, * ,pu8RxBuffer
s16DataSize pu8IPAddr u16Port pvArg, *unsigned char ,unsigned short , *void )
{
"DnsServer_RecvfromCB \MDNS_INFO(n");
if((pu8RxBuffer != 0) && (s16DataSize > 0))
{
tstrDnsHdr strDnsHdr ;
strdnsquery ;
"DNS Packet Recieved \MDNS_INFO(n");
if( [0],MDNS_ParseQuery(&pu8RxBuffer & strDnsHdr,&strDnsQuery))
MDNS_SendResp ( , ,sock pu8IPAddr u16Port strDnsHdr strDnsQuery,& ,& );
}
else
{
"DnsServer_RecvfromCB Error !\MDNS_INFO(n");
}
}
Parse mDNS Query
int MDNS_ParseQuery(unsigned char *pu8RxBuffer, tstrDnsHdr *pstrDnsHdr pstrDnsQuery, * strdnsquery )
{
unsigned char dot_size temp, =0;
unsigned short n=0, =0,i u16index=0;
int bDNSmatch = 0;
/* ----Identification--------------------------|QR| Opcode |AA|TC|RD|RA|Z|AD|CD|Rcode | */
/* Total Questions------------------------|-----------------Total Answer R ------------ ----- Rs --
*/
/* Total Authority RRs --------------------|----------------Total Additional RRs----------------
*/
/* --------------------------------- Questions ---------------------------------
*/
/* ------------------------------------ wer RRs Ans ------------------------------------------*/
/* ----------------------------------- Authority RRs -------------- ------------------ --
*/
/* -----------------------------------Additional RRs ----------------------------------
*/
MDNS_INFO("Parsing DNS Packet\n");
pstrDnsHdr pu8RxBuffer u16index pu8RxBuffer u16index->id = (( [ ]<<8)| ( [ +1]));
MDNS_INFO "id = %.4x \(n",pstrDnsHdr->id);
u16index+=2;
pstrDnsHdr flags1-> = [ pu8RxBuffer u16index++];
pstrDnsHdr flags2-> = [ pu8RxBuffer u16index++];
MDNS_INFO "flags = %.2x %.2x \(n",pstrDnsHdr flags1 pstrDnsHdr flags2-> , -> );
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
62
pstrDnsHdr numquestions pu8RxBuffer u16index pu8RxBuffer u16index-> = (( [ ]<<8)| ( [ +1]));
"numquestions = %.4x \MDNS_INFO (n",pstrDnsHdr numquestions-> );
u16index+=2;
pstrDnsHdr numanswers-> = ((pu8RxBuffer u16index pu8RxBuffer u16index[ ]<<8)| ( [ +1]));
"numanswers = %.4x \MDNS_INFO (n",pstrDnsHdr numanswers-> );
u16index+=2;
pstrDnsHdr numauthrr pu8RxBuffer u16index pu8RxBuffer u16index-> = (( [ ]<<8)| ( [ +1]));
"numauthrr = %.4x \MDNS_INFO (n",pstrDnsHdr numauthrr-> );
u16index+=2;
pstrDnsHdr numextrarr-> = ((pu8RxBuffer u16index pu8RxBuffer u16index[ ]<<8)| ( [ +1]));
"numextrarr = %.4x \MDNS_INFO (n",pstrDnsHdr numextrarr-> );
u16index+=2;
dot_size =pstrDnsQuery query n pu8RxBuffer u16index-> [ ++]= [ ++];
pstrDnsQuery->u16size=1;
while (dot_size--!=0) //(pu8RxBuffer[++u16index] != 0)
{
pstrDnsQuery query n pstrDnsQuery queryForChecking i-> [ ++]= -> [ ++]=pu8RxBuffer u16index[ ++] ;
pstrDnsQuery u16size-> ++;
gu8pos temp= ;
if (dot_size == 0 )
{
pstrDnsQuery queryForChecking i-> [ ++]= ; '.'
temp=u16index;
dot_size =pstrDnsQuery query n pu8RxBuffer u16index-> [ ++]= [ ++];
pstrDnsQuery u16size-> ++;
}
}
pstrDnsQuery queryForChecking i-> [-- ] = 0;
"parsed query <%s>\MDNS_INFO(n",pstrDnsQuery queryForChecking-> );
// Search for any match in the local DNS table.
for(n= 0; n<DNS_SERVER_CACHE_SIZE; ++) n
{
"Saved URL <%s>\MDNS_INFO(n",gpacDnsServerCache n[ ]);
if( (strcmp gpacDnsServerCache n pstrDnsQuery queryForChecking[ ], -> ) ==0)
{
bDNSmatch= 1;
"MATCH \MDNS_INFO(n");
}
else
{
"Mismatch\MDNS_INFO(n");
}
}
pstrDnsQuery u16class-> = ((pu8RxBuffer u16index pu8RxBuffer u16index[ ]<<8)| ( [ +1]));
u16index+=2;
pstrDnsQuery u16type pu8RxBuffer u16index pu8RxBuffer u16index-> = (( [ ]<<8)| ( [ +1]));
return bDNSmatch;
}
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
63
Send mDNS Response:
void MDNS_SendResp (signed char sock,unsigned char * , pu8IPAddr
unsigned short tstrDnsHdr u16Port, *pstrDnsHdr pstrDnsQuery, *strdnsquery )
{
unsigned short u16index=0;
tstrSockAddr strclientAddr ;
unsigned char *pu8sendBuf;
char *serviceName2 = (char sizeof*)malloc( (serviceName)+1);
unsigned int MULTICAST_IP = 0xFB0000E0;
pu8sendBuf=gPu8Buf;
memcpy(&strclientAddr u32IPAddr MULTICAST_IP. ,& ,IPV4_DATA_LENGTH);
strclientAddr u16Port u16Port. = ;
"%s \MDNS_INFO(n",pstrDnsQu queryery-> );
"Query Size = %d \MDNS_INFO(n",pstrDnsQuery u16size-> );
"class = %.4x \MDNS_INFO(n", ->pstrDnsQuery u16class);
"type = %.4x \MDNS_INFO(n", ->pstrDnsQuery u16type);
"PREPARING DNS ANSWER BEFORE SENDING\MDNS_INFO(n");
/*----------------------------ID 2 Bytes -----------------------------*/
pu8sendBuf [u16index++] =0; //( pstrDnsHdr->id>>8);
pu8sendBuf [u16index++] = 0;//( pstrDnsHdr->id)&(0xFF);
"(ResPonse) id = %.2x %.2x \MDNS_INFO (n", pu8sendBuf u16index pu8sendBuf u16index[ -2], [ -1]);
/*----------------------------Flags 2 Bytes----------------------------*/
pu8sendBuf [u16index++] = DNS_RSP_FLAG_1;
pu8sendBuf [u16index++] = DNS_RSP_FLAG_2;
"(ResPonse) Flags = %.2x %.2x \ MDNS_INFO (n",pu8sendBuf[u16index pu8sendBuf u16index-2], [ -1]);
/*----------------------------No of Questions--------------------------*/
pu8sendBuf [u16index++] =0x00;
pu8sendBuf [u16index++] =0x01;
"(ResPonse) Questions = %.2x %.2x \ MDNS_INFO (n",pu8sendBuf u16index[ -2],pu8sendBuf u16index[ -
1]);
/*---------------------------No of Answers----------------------------*/
pu8sendBuf [u16index++] =0x00;
pu8sendBuf [u16index++] =0x01;
"(ResPonse) Answers = %.2x %.2x \ MDNS_INFO (n",pu8sendBuf u16index[ -2],pu8sendBuf u16index[ -1]);
/*---------------------------No of Authority RRs------------------------*/
pu8sendBuf [u16index++] =0x00;
pu8sendBuf [u16index++] =0x00;
"(ResPonse) Authority RRs = %.2x %.2x \ MDNS_INFO (n",pu8sendBuf u16index pu8sendBuf u16index[ -2], [ -
1]);
/*----------------------------No of Additional RRs----------------------*/
pu8sendBuf [u16index++] =0x00;
pu8sendBuf [u16index++] =0x00;
"(ResPonse) Additional RRs = %.2x %.2x \ MDNS_INFO (n",pu8sendBuf u16index[ -
2],pu8sendBuf u16index[ -1]);
/*--------------------------------Query-----------------------------*/
memcpy(&pu8sendBuf u16index pstrDnsQuery query pstrDnsQuery u16size[ ], -> , -> );
"\nsize = %d \MDNS_INFO(n",pstrDnsQuery u16size-> );
u16index pstrDnsQuery u16size+= -> ;
/*-------------------------------Query Type----------------------------*/
pu8sendBuf [u16index++] = ( pstrDnsQuery u16type-> >>8);//MDNS_TYPE>>8;
pu8sendBuf [u16index pstrDnsQuery u16type++] = ( -> )&(0xFF);//(MDNS_TYPE&0xFF);
"Query Type = %.2x %.2x \ MDNS_INFO (n",pu8sendBuf u16index pu8sendBuf u16index[ -2], [ -1]);
/*------------------------------Query Class-----------------------------------*/
pu8sendBuf [u16index++] = MDNS_CLASS>>8;//(( pstrDnsQuery->u16class>>8)|0x80);
pu8sendBuf [u16index++] = ( MDNS_CLASS & 0xFF);//( pstrDnsQuery->u16class)&(0xFF);
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
65
14 WINC Serial Flash Memory AT
14.1 Overview and Features
The WINC has internal serial (SPI) flash memory of either 4 or 8 capacity. The flash memory is used to AT Mb
store:
User configuration
Wi-Fi Firmware
BLE Firmware
Connection Profiles
During startup and mode changes the firmware is loaded from the serial flash into program memory (IRAM) in
which the firmware is executed. First the Wi-Fi firmware is loaded and started while holding the BLE processor
in reset. Then the BLE firmware is loaded and placed into the BLE memory prior to releasing reset. The flash is
accessed at other points during runtime to retrieve configuration and profile data.
The flash memory can be read, written to, and erased directly from the host without cooperation with the
ATWINC firmware. However, if operational firmware is already loaded, it is necessary to first halt any running
AT ATWINC firmware before accessing the serial flash to avoid access conflict between host and the WINC
processor.
14.2 Accessing to Serial Flash
The host has transparent access to the serial (SPI) flash through WINC SPI master AT
The host can program the serial (SPI) flash without need for operational firmware in the WINC. The AT
function m2m_wifi_download_mode must be called first.
Figure 14- System Block Diagram showing SPI Flash Connection 1.
WINC
Serial Flash
SPI Master
Wi-Fi ASICHost MCU I2C, SPI, UART
14.3 Read/Write/Erase Operations
SPI Flash can be accessed to be read, written, and erased.
It is required to first change the ATWINC’s mode to “ ” before any attempt to access the SPI download mode
Flash by calling:
sint32 m2m_wifi_download_mode();
All SPI flash functions are blocking. A return of indicates that the requested operation has been M2M_SUCCESS
completed successfully.
The following is a list of flash functions that may be used:
Query the size of the SPI Flash:
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
66
uint32 spi_flash_get_size();
This function returns with size of SPI Flash in Mb.
Read data from the SPI Flash:
sint8 uint32 uint32 spi_flash_read(uint8 *pu8Buf, u32offset, u32Sz)
Where the size of data is limited by SPI Flash size.
Erase sectors in the SPI Flash:
sint8 uint32 spi_flash_erase(uint32 u32Offset, u32Sz)
Note: The size is limited by the SPI Flash size.
Before writing to any sector, this sector has to be erased first. So if some data needs to be changed
within a sector, it is advised to read the sector first, modify the data, then erase and write the whole
sector again.
Write data to the SPI Flash:
sint8 uint32 uint32 spi_flash_write(uint8* pu8Buf, u32Offset, u32Sz)
If the application wants to write any number of bytes within any sector, it has to erase the entire sector
first. It may be necessary to read the entire sector, erase the sector, and then write back with
modifications. It is also recommended to verify that data had been written after it returns success by
reading data again and compare it with the original.
14.4 Serial (SPI) Flash Map
The following map is valid for SPI Flash with size equals 8 ( Mb 1MB)
Section
Offset [KB]
Size [KB]
Boot firmware
0
4
Control Section
4
8
Configuration
12
8
Certificate
20
4
Scratch Section
24
4
Firmware Image – Wi- Fi
28
196
HTTP Files
224
8
Connection Parameters
232
4
Firmware Image BLE
236
128
[Unused]
[364]
[148]
OTA Image – Wi-Fi and BLE
512
324
[Unused]
[836]
[188]
Total used
684
14.5 Flash Read, Erase, Write Code Example
#include "spi_flash.h"
#define DATA_TO_REPLACE "THIS IS A NEW SECTOR IN FLASH"
int main()
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
67
{
uint8au8FlashContent[FLASH_SECTOR_SZ] = {0};
uint32u32FlashTotalSize = 0, =u32FlashOffset 0;
// Platform specific initializations.
ret =m2m_wifi_download_mode();
if(M2M_SUCCESS != ret)
{
"Unable to enter download mode\r\printf(n");
}
else
{
u32FlashTotalSize =spi_flash_get_size();
}
while((u32FlashTotalSize u32FlashOffset > ) ( && M2M_SUCCESS == ret))
{
ret =spi_flash_read(au8FlashContent u32FlashOffset, , FLASH_SECTOR_SZ);
if(M2M_SUCCESS != ret)
{
"Unable to read SPI sector\r\printf(n");
break;
}
memcpy(au8FlashContent, DATA_TO_REPLACE, strlen(DATA_TO_REPLACE));
ret =spi_flash_erase(u32FlashOffset, FLASH_SECTOR_SZ);
if(M2M_SUCCESS != ret)
{
"Unable to erase SPI sector\r\printf(n");
break;
}
ret =spi_flash_write(au8FlashContent u32FlashOffset, , FLASH_SECTOR_SZ);
if(M2M_SUCCESS != ret)
{
"Unable to write SPI sector\r\printf(n");
break;
}
u32FlashOffset += FLASH_SECTOR_SZ;
}
if(M2M_SUCCESS == ret)
{
"Successful operations\r\printf(n");
}
else
{
"Failed operations\r\printf(n");
}
while(1);
return M2M_SUCCESS;
}
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
68
15 Writing a Simple Networking Application
This chapter provides a step-by-step tutorial on how to build a networking application from scratch. For details
on getting started with the Atmel Studio and how to setup the environment and obtain the example application
and AtmelWirelessConnect APK smart phone application, refer to . [R01]
15.1 Prerequisites
Hardware Prerequisites
Atmel SAMD21-XPRO Evaluation kit
Atmel I/O1 Xplained ATIO1-XPRO board
Atmel WINC3400 Xplained Pro Extension board AT
Micro-USB Cable (Micro-A / Micro- B)
Android Phone
Software Prerequisites
Atmel Studio 6.2 (build 1153) or higher
Atmel Software Frameworks 3.15.0
Wi-Fi Network Controller demo for SAM D21
Android apk AtmelWirelessConnect application
15.2 Solution Overview
The goal of this project is to develop an IoT application, capable of sending temperature information to any
phone or tablet on the network while offering a way to remotely control the LED on the SAM D21 Xplained Pro
board.
To develop and run this project you need to start with the downloaded empty Wi-Fi example project.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
69
If you cannot use an Android phone to test the solution, you can still use Wireshark to
see the traffic generated by the IoT sensor application.
ATWINC3400 Wi-Fi extension and I/O1 extension should be plugged into SAM D21
Xplained Pro EXT1 and EXT2 respectively.
15.3 Project Creation
Open the empty Wi-Fi example Project.
Open Atmel Studio 6.2
Click on “File” then “Open Project/Solution…”
Select the Empty Wi-Fi example project on your hard drive
15.4 Wi-Fi Software API Files
The table below lists the main files from the Wi-Fi Software API located.
File
Description
m2m_wifi.h
m2m_wifi.c
Provide entry point, Wi-Fi configuration API
socket.h
socket.c
Provide socket API
nmbsp.h
nm_bsp_samd21.c
Provide BSP APIs needed by Host Driver
nm_bus_wrap-
per_samd21.c
Provide bus wrapper APIs needed by Host Driver
In order to add Wi-Fi connectivity into an existing user example project, the complete “wifi_nmi” folder should
be added to the user project.
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
70
Locate these files in your project:
m2m_wifi_type.h is an internal type definition header file.
The configuration of the Wi-Fi Software API is fairly easy and relies on three configuration files.
The file provides configuration for the following: conf_winc.h
Reset pin definition (RESET_N) CONF_WIFI_M2M_RESET_PIN:
Reset pin definition (CHIP_EN) CONF_WIFI_M2M_CHIP_ENABLE_PIN:
Interrupt line (IRQN) CONF_WIFI_M2M_INT_PIN:
Debug enable CONF_WIFI_M2M_DEUG:
ATWINC3400 Wi-Fi/BLE Network Controller Software Design Guide [USER GUIDE]
Atmel- -ATWINC3400-WiFi-BLE-Network-Controller-Software-Design-Guide_UserGuide 42016 42566A _0
71
15.5 Reading Temperature Sensor and Controlling LED Status
The empty Wi-Fi example Project comes with a specific driver for the AT30TSE temperature sensor, located on
the I/O1 extension.
The driver implementation can be found in the “ASF at30tse75x” folder of the \sam0\components\sensor\
Solution Explorer.
Retrieving the temperature information is easy and can be performed in three steps:
1. Include the driver header file.
#include “asf.h”
2. Initialize the temperature sensor driver.
at30tse_init();
3. Retrieve the current temperature value.
double ; temp = ()at30tse_read_temperature
The empty Wi-Fi example Project already includes the peripheral dependencies for the
temperature sensor.
The temperature sensor configuration file “conf_at30tse75x.h” is already configured to
use the peripheral on EXT2.


Produkt Specifikationer

Mærke: Microchip
Kategori: Ikke kategoriseret
Model: ATWINC3400-IC

Har du brug for hjælp?

Hvis du har brug for hjælp til Microchip ATWINC3400-IC stil et spørgsmål nedenfor, og andre brugere vil svare dig




Ikke kategoriseret Microchip Manualer

Ikke kategoriseret Manualer

Nyeste Ikke kategoriseret Manualer