diff --git a/CODECONVENTIONS.md b/CODECONVENTIONS.md deleted file mode 100644 index a80d5ec92e..0000000000 --- a/CODECONVENTIONS.md +++ /dev/null @@ -1,210 +0,0 @@ -Git commit conventions -====================== - -Each commit message should start with a directory or full file path -prefix, so it was clear which part of codebase a commit affects. If -a change affects one file, it's better to use path to a file. If it -affects few files in a subdirectory, using subdirectory as a prefix -is ok. For longish paths, it's acceptable to drop intermediate -components, which still should provide good context of a change. -It's also ok to drop file extensions. - -Besides prefix, first line of a commit message should describe a -change clearly and to the point, and be a grammatical sentence with -final full stop. First line should fit within 78 characters. Examples -of good first line of commit messages: - - py/objstr: Add splitlines() method. - py: Rename FOO to BAR. - docs/machine: Fix typo in reset() description. - ports: Switch to use lib/foo instead of duplicated code. - -After the first line, add an empty line and in following lines describe -a change in a detail, if needed. Any change beyond 5 lines would likely -require such detailed description. - -To get good practical examples of good commits and their messages, browse -the `git log` of the project. - -MicroPython doesn't require explicit sign-off for patches ("Signed-off-by" -lines and similar). Instead, the commit message, and your name and email -address on it construes your sign-off of the following: - -* That you wrote the change yourself, or took it from a project with - a compatible license (in the latter case the commit message, and possibly - source code should provide reference where the implementation was taken - from and give credit to the original author, as required by the license). -* That you are allowed to release these changes to an open-source project - (for example, changes done during paid work for a third party may require - explicit approval from that third party). -* That you (or your employer) agree to release the changes under - MicroPython's license, which is the MIT license. Note that you retain - copyright for your changes (for smaller changes, the commit message - conveys your copyright; if you make significant changes to a particular - source module, you're welcome to add your name to the file header). -* Your signature for all of the above, which is the 'Author' line in - the commit message, and which should include your full real name and - a valid and active email address by which you can be contacted in the - foreseeable future. - -Python code conventions -======================= - -Python code follows [PEP 8](http://legacy.python.org/dev/peps/pep-0008/). - -Naming conventions: -- Module names are short and all lowercase; eg pyb, stm. -- Class names are CamelCase, with abbreviations all uppercase; eg I2C, not - I2c. -- Function and method names are all lowercase with words separated by - a single underscore as necessary to improve readability; eg mem_read. -- Constants are all uppercase with words separated by a single underscore; - eg GPIO_IDR. - -C code conventions -================== - -When writing new C code, please adhere to the following conventions. - -White space: -- Expand tabs to 4 spaces. -- Don't leave trailing whitespace at the end of a line. -- For control blocks (if, for, while), put 1 space between the - keyword and the opening parenthesis. -- Put 1 space after a comma, and 1 space around operators. - -Braces: -- Use braces for all blocks, even no-line and single-line pieces of - code. -- Put opening braces on the end of the line it belongs to, not on - a new line. -- For else-statements, put the else on the same line as the previous - closing brace. - -Header files: -- Header files should be protected from multiple inclusion with #if - directives. See an existing header for naming convention. - -Names: -- Use underscore_case, not camelCase for all names. -- Use CAPS_WITH_UNDERSCORE for enums and macros. -- When defining a type use underscore_case and put '_t' after it. - -Integer types: MicroPython runs on 16, 32, and 64 bit machines, so it's -important to use the correctly-sized (and signed) integer types. The -general guidelines are: -- For most cases use mp_int_t for signed and mp_uint_t for unsigned - integer values. These are guaranteed to be machine-word sized and - therefore big enough to hold the value from a MicroPython small-int - object. -- Use size_t for things that count bytes / sizes of objects. -- You can use int/uint, but remember that they may be 16-bits wide. -- If in doubt, use mp_int_t/mp_uint_t. - -Comments: -- Be concise and only write comments for things that are not obvious. -- Use `// ` prefix, NOT `/* ... */`. No extra fluff. - -Memory allocation: -- Use m_new, m_renew, m_del (and friends) to allocate and free heap memory. - These macros are defined in py/misc.h. - -Examples --------- - -Braces, spaces, names and comments: - - #define TO_ADD (123) - - // This function will always recurse indefinitely and is only used to show - // coding style - int foo_function(int x, int some_value) { - if (x < some_value) { - foo(some_value, x); - } else { - foo(x + TO_ADD, some_value - 1); - } - - for (int my_counter = 0; my_counter < x; my_counter++) { - } - } - -Type declarations: - - typedef struct _my_struct_t { - int member; - void *data; - } my_struct_t; - -Documentation conventions -========================= - -MicroPython generally follows CPython in documentation process and -conventions. reStructuredText syntax is used for the documention. - -Specific conventions/suggestions: - -* Use `*` markup to refer to arguments of a function, e.g.: - -``` -.. method:: poll.unregister(obj) - - Unregister *obj* from polling. -``` - -* Use following syntax for cross-references/cross-links: - -``` -:func:`foo` - function foo in current module -:func:`module1.foo` - function foo in module "module1" - (similarly for other referent types) -:class:`Foo` - class Foo -:meth:`Class.method1` - method1 in Class -:meth:`~Class.method1` - method1 in Class, but rendered just as "method1()", - not "Class.method1()" -:meth:`title ` - reference method1, but render as "title" (use only - if really needed) -:mod:`module1` - module module1 - -`symbol` - generic xref syntax which can replace any of the above in case - the xref is unambiguous. If there's ambiguity, there will be a warning - during docs generation, which need to be fixed using one of the syntaxes - above -``` - -* Cross-referencing arbitrary locations -~~~ -.. _xref_target: - -Normal non-indented text. - -This is :ref:`reference `. - -(If xref target is followed by section title, can be just -:ref:`xref_target`). -~~~ - -* Linking to external URL: -``` -`link text `_ -``` - -* Referencing builtin singleton objects: -``` -``None``, ``True``, ``False`` -``` - -* Use following syntax to create common description for more than one element: -~~~ -.. function:: foo(x) - bar(y) - - Description common to foo() and bar(). -~~~ - - -More detailed guides and quickrefs: - -* http://www.sphinx-doc.org/en/stable/rest.html -* http://www.sphinx-doc.org/en/stable/markup/inline.html -* http://docutils.sourceforge.net/docs/user/rst/quickref.html diff --git a/README.md b/README.md deleted file mode 100644 index 269adc2f0d..0000000000 --- a/README.md +++ /dev/null @@ -1,217 +0,0 @@ -# Adafruit CircuitPython - -[![Build Status](https://travis-ci.org/adafruit/circuitpython.svg?branch=master)](https://travis-ci.org/adafruit/circuitpython) -[![Doc Status](https://readthedocs.org/projects/circuitpython/badge/?version=latest)](http://circuitpython.readthedocs.io/) -[![Gitter](https://badges.gitter.im/adafruit/circuitpython.svg)](https://gitter.im/adafruit/circuitpython?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) -[![Discord](https://img.shields.io/discord/327254708534116352.svg)](https://discord.gg/nBQh6qu) - -**[Status](#status)** | -**[Supported Boards](#supported-boards)** | -**[Download](#download)** | -**[Documentation](#documentation)** | -**[Contributing](#contributing)** | -**[Differences from Micropython](#differences-from-micropython)** | -**[Project Structure](#project-structure)** - -**Adafruit CircuitPython** is an open source derivative of -[MicroPython](http://www.micropython.org) for use on educational -development boards designed and sold by [Adafruit](https://www.adafruit.com). - -**CircuitPython**, a MicroPython derivative, implements Python 3.x on -microcontrollers such as the SAMD21 and ESP8266. - -## Status - -This project is in beta. Most APIs should be stable going forward. - -## Supported Boards - -### Designed for CircuitPython - -* [Adafruit CircuitPlayground Express][] -* [Adafruit Feather M0 Express][] -* [Adafruit Metro M0 Express][] -* [Adafruit Gemma M0][] -* [Adafruit Trinket M0][] - -### Other - -* [Adafruit Feather HUZZAH][] -* [Adafruit Feather M0 Basic][] -* [Adafruit Feather M0 Bluefruit LE][] (uses M0 Basic binaries) -* [Adafruit Feather M0 Adalogger][] (MicroSD card supported using the [Adafruit CircuitPython SD library](https://github.com/adafruit/Adafruit_CircuitPython_SD)) -* [Arduino Zero][] - -## Download - -Official binaries are available through the -[latest GitHub releases](https://github.com/adafruit/circuitpython/releases). -Continuous (one per commit) builds are available -[here](https://adafruit-circuit-python.s3.amazonaws.com/index.html?prefix=bin) -and includes experimental hardware support. - -## Documentation - -Guides and videos are available through the [Adafruit Learning System](https://learn.adafruit.com/) -under the [CircuitPython category](https://learn.adafruit.com/category/circuitpython) -and [MicroPython category](https://learn.adafruit.com/category/micropython). -An API reference is also available on [Read the Docs](http://circuitpython.readthedocs.io/en/latest/?). - -## Contributing - -See [CONTRIBUTING.md](https://github.com/adafruit/circuitpython/blob/master/CONTRIBUTING.md) -for full guidelines but please be aware that by contributing to this -project you are agreeing to the [Code of Conduct][]. Contributors who -follow the [Code of Conduct][] are welcome to submit pull requests and -they will be promptly reviewed by project admins. Please join the -[Gitter chat](https://gitter.im/adafruit/circuitpython) or -[Discord](https://discord.gg/nBQh6qu) too. - ---- - -## Differences from [MicroPython][] - -CircuitPython: - -* includes a port for Atmel SAMD21 (Commonly known as M0 - in Adafruit product names.) -* supports only Atmel SAMD21 and ESP8266 ports. -* tracks MicroPython's releases (not master). - -### Behavior - -* The order that files are run and the state that is shared between them. - CircuitPython's goal is to clarify the role of each file and make each - file independent from each other. - * `boot.py` (or `settings.py`) runs only once on start up before - USB is initialized. This lays the ground work for configuring USB - at startup rather than it being fixed. Since serial is not - available, output is written to `boot_out.txt`. - * `code.py` (or `main.py`) is run after every reload until it - finishes or is interrupted. After it is done running, the vm and hardware is - reinitialized. **This means you cannot read state from `code.py` - in the REPL anymore.** CircuitPython's goal for this change includes - reduce confusion about pins and memory being used. - * After `code.py` the REPL can be entered by pressing any key. It no - longer shares state with `code.py` so it is a fresh vm. - * Autoreload state will be maintained across reload. -* Adds a safe mode that does not run user code after a hard crash or - brown out. The hope is that this will make it easier to fix code that - causes nasty crashes by making it available through mass storage after - the crash. A reset (the button) is needed after its fixed to get back - into normal mode. - -### API - -* Unified hardware APIs: - [`audioio`](https://circuitpython.readthedocs.io/en/latest/shared-bindings/audioio/__init__.html), - [`analogio`](https://circuitpython.readthedocs.io/en/latest/shared-bindings/analogio/__init__.html), - [`busio`](https://circuitpython.readthedocs.io/en/latest/shared-bindings/busio/__init__.html), - [`digitalio`](https://circuitpython.readthedocs.io/en/latest/shared-bindings/digitalio/__init__.html), - [`pulseio`](https://circuitpython.readthedocs.io/en/latest/shared-bindings/pulseio/__init__.html), - [`touchio`](https://circuitpython.readthedocs.io/en/latest/shared-bindings/touchio/__init__.html), - [`microcontroller`](https://circuitpython.readthedocs.io/en/latest/shared-bindings/microcontroller/__init__.html), - [`board`](https://circuitpython.readthedocs.io/en/latest/shared-bindings/board/__init__.html), - [`bitbangio`](https://circuitpython.readthedocs.io/en/latest/shared-bindings/bitbangio/__init__.html) (Only available on atmel-samd21 and ESP8266 currently.) -* No `machine` API on Atmel SAMD21 port. - -### Modules - -* No module aliasing. (`uos` and `utime` are not available as `os` and - `time` respectively.) Instead `os`, `time`, and `random` are CPython - compatible. -* New `storage` module which manages file system mounts. (Functionality - from `uos` in MicroPython.) -* Modules with a CPython counterpart, such as `time`, `os` and `random`, - are strict [subsets](https://circuitpython.readthedocs.io/en/latest/shared-bindings/time/__init__.html) - of their [CPython version](https://docs.python.org/3.4/library/time.html?highlight=time#module-time). - Therefore, code from CircuitPython is runnable on CPython but not - necessarily the reverse. -* tick count is available as [`time.monotonic()`](https://circuitpython.readthedocs.io/en/latest/shared-bindings/time/__init__.html#time.monotonic) - -### atmel-samd21 features - -* RGB status LED -* Auto-reload after file write over mass storage. (Disable with - `samd.disable_autoreload()`) -* Wait state after boot and main run, before REPL. -* Main is one of these: `code.txt`, `code.py`, `main.py`, `main.txt` -* Boot is one of these: `settings.txt`, `settings.py`, `boot.py`, - `boot.txt` - ---- - -## Project Structure - -Here is an overview of the top-level source code directories. - -### Core - -The core code of [MicroPython][] is shared amongst ports including -CircuitPython: - -* `docs` High level user documentation in Sphinx reStructuredText - format. -* `drivers` External device drivers written in Python. -* `examples` A few example Python scripts. -* `extmod` Shared C code used in multiple ports' modules. -* `lib` Shared core C code including externally developed libraries such - as FATFS. -* `logo` The MicroPython logo. -* `mpy-cross` A cross compiler that converts Python files to byte code - prior to being run in MicroPython. Useful for reducing library size. -* `py` Core Python implementation, including compiler, runtime, and - core library. -* `shared-bindings` Shared definition of Python modules, their docs and - backing C APIs. Ports must implement the C API to support the - corresponding module. -* `shared-module` Shared implementation of Python modules that may be - based on `common-hal`. -* `supervisor` Code and headers related to the supervisor which monitors and - runs individual MicroPython virtual machines (from code in `py`). -* `tests` Test framework and test scripts. -* `tools` Various tools, including the pyboard.py module. - -### Ports - -Ports include the code unique to a microcontroller line and also -variations based on the board. - -* `ports/atmel-samd` Support for SAMD21 based boards such as [Arduino Zero][], - [Adafruit Feather M0 Basic][], and [Adafruit Feather M0 Bluefruit LE][]. -* `ports/bare-arm` A bare minimum version of MicroPython for ARM MCUs. -* `ports/cc3200` Support for boards based [CC3200](http://www.ti.com/product/CC3200) - from TI such as the [WiPy 1.0](https://www.pycom.io/solutions/py-boards/wipy1/). -* `ports/esp8266` Support for boards based on ESP8266 WiFi modules such as the - [Adafruit Feather HUZZAH][]. -* `ports/minimal` A minimal MicroPython port. Start with this if you want - to port MicroPython to another microcontroller. -* `ports/pic16bit` Support for 16-bit PIC microcontrollers. -* `ports/qemu-arm` Support for ARM emulation through [QEMU](https://qemu.org). -* `ports/stm32` Support for boards based on STM32 microcontrollers including - the MicroPython flagship [PyBoard](https://store.micropython.org/store/#/products/PYBv1_1). -* `ports/teensy` Support for the Teensy line of boards such as the - [Teensy 3.1](https://www.pjrc.com/teensy/teensy31.html). -* `ports/unix` Support for UNIX. -* `ports/windows` Support for [Windows](https://www.microsoft.com/en-us/windows/). -* `ports/zephyr` Support for [Zephyr](https://www.zephyrproject.org/), a - real-time operating system by the Linux Foundation. - -CircuitPython only maintains the `atmel-samd` and `esp8266` ports. The -rest are here to maintain compatibility with the -[MicroPython][] parent project. - -**[⬆ back to top](#adafruit-circuitpython)** - -[Adafruit CircuitPlayground Express]: https://www.adafruit.com/product/3333 -[Adafruit Feather M0 Express]: https://www.adafruit.com/product/3403 -[Adafruit Metro M0 Express]: https://www.adafruit.com/product/3505 -[Adafruit Gemma M0]: https://www.adafruit.com/product/3501 -[Adafruit Trinket M0]: https://www.adafruit.com/product/3500 -[Adafruit Feather HUZZAH]: https://www.adafruit.com/products/2821 -[Adafruit Feather M0 Basic]: https://www.adafruit.com/products/2772 -[Adafruit Feather M0 Bluefruit LE]: https://www.adafruit.com/products/2995 -[Adafruit Feather M0 Adalogger]: https://www.adafruit.com/product/2796 -[Arduino Zero]: https://www.arduino.cc/en/Main/ArduinoBoardZero -[MicroPython]: https://github.com/micropython/micropython -[Code of Conduct]: https://github.com/adafruit/circuitpython/blob/master/CODE_OF_CONDUCT.md diff --git a/README.rst b/README.rst new file mode 100644 index 0000000000..7e234331ee --- /dev/null +++ b/README.rst @@ -0,0 +1,243 @@ +Adafruit CircuitPython +====================== + +|Build Status| |Doc Status| |Discord| + +`Status <#status>`__ \| `Supported Boards <#supported-boards>`__ +\| `Download <#download>`__ \| +`Documentation <#documentation>`__ \| +`Contributing <#contributing>`__ \| `Differences from +Micropython <#differences-from-micropython>`__ \| `Project +Structure <#project-structure>`__ + +**CircuitPython** is an *education friendly* open source derivative of +`MicroPython `_. CircuitPython supports use +on educational development boards designed and sold by +`Adafruit `_. Adafruit CircuitPython features +unified Python core APIs and a growing list of Adafruit libraries and +drivers of that work with it. + +Status +------ + +This project is stable. Most APIs should be stable going forward. Those +that change will change on major version numbers such as 2.0.0 and +3.0.0. + +Supported Boards +---------------- + +Designed for CircuitPython +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- `Adafruit CircuitPlayground + Express `__ +- `Adafruit Feather M0 + Express `__ +- `Adafruit Metro M0 Express `__ +- `Adafruit Gemma M0 `__ + +Other +~~~~~ + +- `Adafruit Feather HUZZAH `__ +- `Adafruit Feather M0 + Basic `__ +- `Adafruit Feather M0 Bluefruit + LE `__ (uses M0 Basic + binaries) +- `Adafruit Feather M0 + Adalogger `__ (MicroSD card + supported using the `Adafruit CircuitPython SD + library `__) +- `Arduino Zero `__ + +Download +-------- + +Official binaries are available through the `latest GitHub +releases `__. +Continuous (one per commit) builds are available +`here `__ +and includes experimental hardware support. + +Documentation +------------- + +Guides and videos are available through the `Adafruit Learning +System `__ under the `CircuitPython +category `__ and +`MicroPython +category `__. An API +reference is also available on `Read the +Docs `__. + +Contributing +------------ + +See +`CONTRIBUTING.md `__ +for full guidelines but please be aware that by contributing to this +project you are agreeing to the `Code of +Conduct `__. +Contributors who follow the `Code of +Conduct `__ +are welcome to submit pull requests and they will be promptly reviewed +by project admins. Please join the `Gitter +chat `__ or +`Discord `__ too. + +-------------- + +Differences from `MicroPython `__ +----------------------------------------------------------------------------- + +CircuitPython: + +- includes a port for Atmel SAMD21 (Commonly known as M0 in Adafruit + product names.) +- supports only Atmel SAMD21 and ESP8266 ports. +- tracks MicroPython's releases (not master). + +Behavior +~~~~~~~~ + +- The order that files are run and the state that is shared between + them. CircuitPython's goal is to clarify the role of each file and + make each file independent from each other. +- ``boot.py`` (or ``settings.py``) runs only once on start up before + USB is initialized. This lays the ground work for configuring USB at + startup rather than it being fixed. Since serial is not available, + output is written to ``boot_out.txt``. +- ``code.py`` (or ``main.py``) is run after every reload until it + finishes or is interrupted. After it is done running, the vm and + hardware is reinitialized. **This means you cannot read state from + ``code.py`` in the REPL anymore.** CircuitPython's goal for this + change includes reduce confusion about pins and memory being used. +- After ``code.py`` the REPL can be entered by pressing any key. It no + longer shares state with ``code.py`` so it is a fresh vm. +- Autoreload state will be maintained across reload. +- Adds a safe mode that does not run user code after a hard crash or + brown out. The hope is that this will make it easier to fix code that + causes nasty crashes by making it available through mass storage + after the crash. A reset (the button) is needed after its fixed to + get back into normal mode. + +API +~~~ + +- Unified hardware APIs: `audioio `_, `analogio `_, `busio `_, `digitalio `_, `pulseio `_, `touchio `_, `microcontroller `_, `board `_, `bitbangio `_ +- No ``machine`` API on Atmel SAMD21 port. + +Modules +~~~~~~~ + +- No module aliasing. (``uos`` and ``utime`` are not available as + ``os`` and ``time`` respectively.) Instead ``os``, ``time``, and + ``random`` are CPython compatible. +- New ``storage`` module which manages file system mounts. + (Functionality from ``uos`` in MicroPython.) +- Modules with a CPython counterpart, such as ``time``, ``os`` and + ``random``, are strict + `subsets `__ + of their `CPython + version `__. + Therefore, code from CircuitPython is runnable on CPython but not + necessarily the reverse. +- tick count is available as + `time.monotonic() `__ + +atmel-samd21 features +~~~~~~~~~~~~~~~~~~~~~ + +- RGB status LED +- Auto-reload after file write over mass storage. (Disable with + ``samd.disable_autoreload()``) +- Wait state after boot and main run, before REPL. +- Main is one of these: ``code.txt``, ``code.py``, ``main.py``, + ``main.txt`` +- Boot is one of these: ``settings.txt``, ``settings.py``, ``boot.py``, + ``boot.txt`` + +-------------- + +Project Structure +----------------- + +Here is an overview of the top-level source code directories. + +Core +~~~~ + +The core code of +`MicroPython `__ is shared +amongst ports including CircuitPython: + +- ``docs`` High level user documentation in Sphinx reStructuredText + format. +- ``drivers`` External device drivers written in Python. +- ``examples`` A few example Python scripts. +- ``extmod`` Shared C code used in multiple ports' modules. +- ``lib`` Shared core C code including externally developed libraries + such as FATFS. +- ``logo`` The MicroPython logo. +- ``mpy-cross`` A cross compiler that converts Python files to byte + code prior to being run in MicroPython. Useful for reducing library + size. +- ``py`` Core Python implementation, including compiler, runtime, and + core library. +- ``shared-bindings`` Shared definition of Python modules, their docs + and backing C APIs. Ports must implement the C API to support the + corresponding module. +- ``shared-module`` Shared implementation of Python modules that may be + based on ``common-hal``. +- ``tests`` Test framework and test scripts. +- ``tools`` Various tools, including the pyboard.py module. + +Ports +~~~~~ + +Ports include the code unique to a microcontroller line and also +variations based on the board. + +- ``atmel-samd`` Support for SAMD21 based boards such as `Arduino + Zero `__, `Adafruit + Feather M0 Basic `__, and + `Adafruit Feather M0 Bluefruit + LE `__. +- ``bare-arm`` A bare minimum version of MicroPython for ARM MCUs. +- ``cc3200`` Support for boards based + `CC3200 `__ from TI such as the + `WiPy 1.0 `__. +- ``esp8266`` Support for boards based on ESP8266 WiFi modules such as + the `Adafruit Feather + HUZZAH `__. +- ``minimal`` A minimal MicroPython port. Start with this if you want + to port MicroPython to another microcontroller. +- ``pic16bit`` Support for 16-bit PIC microcontrollers. +- ``qemu-arm`` Support for ARM emulation through + `QEMU `__. +- ``stmhal`` Support for boards based on STM32 microcontrollers + including the MicroPython flagship + `PyBoard `__. +- ``teensy`` Support for the Teensy line of boards such as the `Teensy + 3.1 `__. +- ``unix`` Support for UNIX. +- ``windows`` Support for + `Windows `__. +- ``zephyr`` Support for `Zephyr `__, a + real-time operating system by the Linux Foundation. + +CircuitPython only maintains the ``atmel-samd`` and ``esp8266`` ports. +The rest are here to maintain compatibility with the +`MicroPython `__ parent +project. + +`⬆ back to top <#adafruit-circuitpython>`__ + +.. |Build Status| image:: https://travis-ci.org/adafruit/circuitpython.svg?branch=master + :target: https://travis-ci.org/adafruit/circuitpython +.. |Doc Status| image:: https://readthedocs.org/projects/circuitpython/badge/?version=latest + :target: http://circuitpython.readthedocs.io/ +.. |Discord| image:: https://img.shields.io/discord/327254708534116352.svg + :target: https://discord.gg/nBQh6qu diff --git a/conf.py b/conf.py index 0068a6d905..8264a9166d 100644 --- a/conf.py +++ b/conf.py @@ -23,9 +23,7 @@ from recommonmark.parser import CommonMarkParser # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('.')) - -# Specify a custom master document based on the port name -master_doc = 'index' +master_doc = 'docs/index' # -- General configuration ------------------------------------------------ @@ -83,13 +81,15 @@ version = release = '0.0.0' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ["**/build-*", +exclude_patterns = ["**/build*", ".venv", + "docs/README.md", "drivers", "examples", "extmod", "frozen", "lib", + "main.c", "mpy-cross", "ports/*/*.c", "ports/*/*.h", @@ -98,12 +98,17 @@ exclude_patterns = ["**/build-*", "ports/*/supervisor", "ports/atmel-samd/asf4", "ports/atmel-samd/asf4_conf", + "ports/atmel-samd/external_flash", + "ports/atmel-samd/freetouch", "ports/atmel-samd/QTouch", + "ports/atmel-samd/tools", "ports/bare-arm", "ports/cc3200", "ports/cc3200/FreeRTOS", "ports/cc3200/hal", - "ports/esp8266", + "ports/esp8266/boards", + "ports/esp8266/common-hal", + "ports/esp8266/modules", "ports/minimal", "ports/nrf/device", "ports/nrf/drivers", @@ -121,7 +126,9 @@ exclude_patterns = ["**/build-*", "ports/windows", "ports/zephyr", "py", + "shared-bindings/util.*", "shared-module", + "supervisor", "tests", "tools"] @@ -153,7 +160,7 @@ pygments_style = 'sphinx' # of rst_prolog, so we follow. Absolute paths below mean "from the base # of the doctree". rst_epilog = """ -.. include:: /templates/replace.inc +.. include:: /docs/templates/replace.inc """ # -- Options for HTML output ---------------------------------------------- diff --git a/docs/design_guide.rst b/docs/design_guide.rst index 3b25ccbf7a..a1524eaa2b 100644 --- a/docs/design_guide.rst +++ b/docs/design_guide.rst @@ -215,7 +215,7 @@ Renders as: Attributes ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Attributes are state on objects. (See `Getters/Setters` above for more discussion +Attributes are state on objects. (See `Getters/Setters`_ above for more discussion about when to use them.) They can be defined internally in a number of different ways. Each approach is enumerated below with an explanation of where the comment goes. @@ -400,10 +400,11 @@ For example, if you are writing a driver for an I2C device, then take in an I2C object instead of the pins themselves. This allows the calling code to provide any object with the appropriate methods such as an I2C expansion board. -Another example is to expect a `DigitalInOut` for a pin to toggle instead of a -`microcontroller.Pin` from `board`. Taking in the `~microcontroller.Pin` object -alone would limit the driver to pins on the actual microcontroller instead of pins -provided by another driver such as an IO expander. +Another example is to expect a :py:class:`~digitalio.DigitalInOut` for a pin to +toggle instead of a :py:class:`~microcontroller.Pin` from `board`. Taking in the +:py:class:`~microcontroller.Pin` object alone would limit the driver to pins on +the actual microcontroller instead of pins provided by another driver such as an +IO expander. Lots of small modules -------------------------------------------------------------------------------- @@ -441,7 +442,7 @@ Examples ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ustruct.pack -"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Use `ustruct.pack_into` instead of `ustruct.pack`. diff --git a/docs/differences/index_template.txt b/docs/differences/index_template.txt deleted file mode 100644 index eb8b3ba640..0000000000 --- a/docs/differences/index_template.txt +++ /dev/null @@ -1,10 +0,0 @@ -.. _cpython_diffs: - -MicroPython differences from CPython -==================================== - -The operations listed in this section produce conflicting results in MicroPython when compared to standard Python. - -.. toctree:: - :maxdepth: 2 - diff --git a/docs/esp8266/general.rst b/docs/esp8266/general.rst deleted file mode 100644 index 96a4545323..0000000000 --- a/docs/esp8266/general.rst +++ /dev/null @@ -1,187 +0,0 @@ -General information about the ESP8266 port -========================================== - -ESP8266 is a popular WiFi-enabled System-on-Chip (SoC) by Espressif Systems. - -Multitude of boards -------------------- - -There are a multitude of modules and boards from different sources which carry -the ESP8266 chip. MicroPython tries to provide a generic port which would run on -as many boards/modules as possible, but there may be limitations. Adafruit -Feather HUZZAH board is taken as a reference board for the port (for example, -testing is performed on it). If you have another board, please make sure you -have datasheet, schematics and other reference materials for your board -handy to look up various aspects of your board functioning. - -To make a generic ESP8266 port and support as many boards as possible, -following design and implementation decision were made: - -* GPIO pin numbering is based on ESP8266 chip numbering, not some "logical" - numbering of a particular board. Please have the manual/pin diagram of your board - at hand to find correspondence between your board pins and actual ESP8266 pins. - We also encourage users of various boards to share this mapping via MicroPython - forum, with the idea to collect community-maintained reference materials - eventually. -* All pins which make sense to support, are supported by MicroPython - (for example, pins which are used to connect SPI flash - are not exposed, as they're unlikely useful for anything else, and - operating on them will lead to board lock-up). However, any particular - board may expose only subset of pins. Consult your board reference manual. -* Some boards may lack external pins/internal connectivity to support - ESP8266 deepsleep mode. - - -Technical specifications and SoC datasheets -------------------------------------------- - -The datasheets and other reference material for ESP8266 chip are available -from the vendor site: http://bbs.espressif.com/viewtopic.php?f=67&t=225 . -They are the primary reference for the chip technical specifications, capabilities, -operating modes, internal functioning, etc. - -For your convenience, some of technical specifications are provided below: - -* Architecture: Xtensa lx106 -* CPU frequency: 80MHz overclockable to 160MHz -* Total RAM available: 96KB (part of it reserved for system) -* BootROM: 64KB -* Internal FlashROM: None -* External FlashROM: code and data, via SPI Flash. Normal sizes 512KB-4MB. -* GPIO: 16 + 1 (GPIOs are multiplexed with other functions, including - external FlashROM, UART, deep sleep wake-up, etc.) -* UART: One RX/TX UART (no hardware handshaking), one TX-only UART. -* SPI: 2 SPI interfaces (one used for FlashROM). -* I2C: No native external I2C (bitbang implementation available on any pins). -* I2S: 1. -* Programming: using BootROM bootloader from UART. Due to external FlashROM - and always-available BootROM bootloader, ESP8266 is not brickable. - - -Scarcity of runtime resources ------------------------------ - -ESP8266 has very modest resources (first of all, RAM memory). So, please -avoid allocating too big container objects (lists, dictionaries) and -buffers. There is also no full-fledged OS to keep track of resources -and automatically clean them up, so that's the task of a user/user -application: please be sure to close open files, sockets, etc. as soon -as possible after use. - - -Boot process ------------- - -On boot, MicroPython EPS8266 port executes ``_boot.py`` script from internal -frozen modules. It mounts filesystem in FlashROM, or if it's not available, -performs first-time setup of the module and creates the filesystem. This -part of the boot process is considered fixed, and not available for customization -for end users (even if you build from source, please refrain from changes to -it; customization of early boot process is available only to advanced users -and developers, who can diagnose themselves any issues arising from -modifying the standard process). - -Once the filesystem is mounted, ``boot.py`` is executed from it. The standard -version of this file is created during first-time module set up and has -commands to start a WebREPL daemon (disabled by default, configurable -with ``webrepl_setup`` module), etc. This -file is customizable by end users (for example, you may want to set some -parameters or add other services which should be run on -a module start-up). But keep in mind that incorrect modifications to boot.py -may still lead to boot loops or lock ups, requiring to reflash a module -from scratch. (In particular, it's recommended that you use either -``webrepl_setup`` module or manual editing to configure WebREPL, but not -both). - -As a final step of boot procedure, ``main.py`` is executed from filesystem, -if exists. This file is a hook to start up a user application each time -on boot (instead of going to REPL). For small test applications, you may -name them directly as ``main.py``, and upload to module, but instead it's -recommended to keep your application(s) in separate files, and have just -the following in ``main.py``:: - - import my_app - my_app.main() - -This will allow to keep the structure of your application clear, as well as -allow to install multiple applications on a board, and switch among them. - - -Known Issues ------------- - -Real-time clock -~~~~~~~~~~~~~~~ - -RTC in ESP8266 has very bad accuracy, drift may be seconds per minute. As -a workaround, to measure short enough intervals you can use -``utime.time()``, etc. functions, and for wall clock time, synchronize from -the net using included ``ntptime.py`` module. - -Due to limitations of the ESP8266 chip the internal real-time clock (RTC) -will overflow every 7:45h. If a long-term working RTC time is required then -``time()`` or ``localtime()`` must be called at least once within 7 hours. -MicroPython will then handle the overflow. - -Sockets and WiFi buffers overflow -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Socket instances remain active until they are explicitly closed. This has two -consequences. Firstly they occupy RAM, so an application which opens sockets -without closing them may eventually run out of memory. Secondly not properly -closed socket can cause the low-level part of the vendor WiFi stack to emit -``Lmac`` errors. This occurs if data comes in for a socket and is not -processed in a timely manner. This can overflow the WiFi stack input queue -and lead to a deadlock. The only recovery is by a hard reset. - -The above may also happen after an application terminates and quits to the REPL -for any reason including an exception. Subsequent arrival of data provokes the -failure with the above error message repeatedly issued. So, sockets should be -closed in any case, regardless whether an application terminates successfully -or by an exeption, for example using try/finally:: - - sock = socket(...) - try: - # Use sock - finally: - sock.close() - - -SSL/TLS limitations -~~~~~~~~~~~~~~~~~~~ - -ESP8266 uses `axTLS `_ library, which is one -of the smallest TLS libraries with the compatible licensing. However, it -also has some known issues/limitations: - -1. No support for Diffie-Hellman (DH) key exchange and Elliptic-curve - cryptography (ECC). This means it can't work with sites which force - the use of these features (it works ok with classic RSA certifactes). -2. Half-duplex communication nature. axTLS uses a single buffer for both - sending and receiving, which leads to considerable memory saving and - works well with protocols like HTTP. But there may be problems with - protocols which don't follow classic request-response model. - -Besides axTLS own limitations, the configuration used for MicroPython is -highly optimized for code size, which leads to additional limitations -(these may be lifted in the future): - -3. Optimized RSA algorithms are not enabled, which may lead to slow - SSL handshakes. -4. Stored sessions are not supported (may allow faster repeated connections - to the same site in some circumstances). - -Besides axTLS specific limitations described above, there's another generic -limitation with usage of TLS on the low-memory devices: - -5. The TLS standard specifies the maximum length of the TLS record (unit - of TLS communication, the entire record must be buffered before it can - be processed) as 16KB. That's almost half of the available ESP8266 memory, - and inside a more or less advanced application would be hard to allocate - due to memory fragmentation issues. As a compromise, a smaller buffer is - used, with the idea that the most interesting usage for SSL would be - accessing various REST APIs, which usually require much smaller messages. - The buffers size is on the order of 5KB, and is adjusted from time to - time, taking as a reference being able to access https://google.com . - The smaller buffer hower means that some sites can't be accessed using - it, and it's not possible to stream large amounts of data. diff --git a/docs/esp8266/img/adafruit_products_pinoutstop.jpg b/docs/esp8266/img/adafruit_products_pinoutstop.jpg deleted file mode 100644 index 655e27aee3..0000000000 Binary files a/docs/esp8266/img/adafruit_products_pinoutstop.jpg and /dev/null differ diff --git a/docs/esp8266/index.rst b/docs/esp8266/index.rst deleted file mode 100644 index 63cf65c614..0000000000 --- a/docs/esp8266/index.rst +++ /dev/null @@ -1,8 +0,0 @@ -ESP8266 -======================================== - -.. toctree:: - - quickref.rst - general.rst - tutorial/index.rst diff --git a/docs/esp8266/quickref.rst b/docs/esp8266/quickref.rst deleted file mode 100644 index c510e40640..0000000000 --- a/docs/esp8266/quickref.rst +++ /dev/null @@ -1,375 +0,0 @@ -.. _quickref: - -Quick reference for the ESP8266 -=============================== - -.. image:: img/adafruit_products_pinoutstop.jpg - :alt: Adafruit Feather HUZZAH board - :width: 640px - -The Adafruit Feather HUZZAH board (image attribution: Adafruit). - -Installing MicroPython ----------------------- - -See the corresponding section of tutorial: :ref:`intro`. It also includes -a troubleshooting subsection. - -General board control ---------------------- - -The MicroPython REPL is on UART0 (GPIO1=TX, GPIO3=RX) at baudrate 115200. -Tab-completion is useful to find out what methods an object has. -Paste mode (ctrl-E) is useful to paste a large slab of Python code into -the REPL. - -The :mod:`machine` module:: - - import machine - - machine.freq() # get the current frequency of the CPU - machine.freq(160000000) # set the CPU frequency to 160 MHz - -The :mod:`esp` module:: - - import esp - - esp.osdebug(None) # turn off vendor O/S debugging messages - esp.osdebug(0) # redirect vendor O/S debugging messages to UART(0) - -Networking ----------- - -The :mod:`network` module:: - - import network - - wlan = network.WLAN(network.STA_IF) # create station interface - wlan.active(True) # activate the interface - wlan.scan() # scan for access points - wlan.isconnected() # check if the station is connected to an AP - wlan.connect('essid', 'password') # connect to an AP - wlan.config('mac') # get the interface's MAC adddress - wlan.ifconfig() # get the interface's IP/netmask/gw/DNS addresses - - ap = network.WLAN(network.AP_IF) # create access-point interface - ap.active(True) # activate the interface - ap.config(essid='ESP-AP') # set the ESSID of the access point - -A useful function for connecting to your local WiFi network is:: - - def do_connect(): - import network - wlan = network.WLAN(network.STA_IF) - wlan.active(True) - if not wlan.isconnected(): - print('connecting to network...') - wlan.connect('essid', 'password') - while not wlan.isconnected(): - pass - print('network config:', wlan.ifconfig()) - -Once the network is established the :mod:`socket ` module can be used -to create and use TCP/UDP sockets as usual. - -Delay and timing ----------------- - -Use the :mod:`time ` module:: - - import time - - time.sleep(1) # sleep for 1 second - time.sleep_ms(500) # sleep for 500 milliseconds - time.sleep_us(10) # sleep for 10 microseconds - start = time.ticks_ms() # get millisecond counter - delta = time.ticks_diff(time.ticks_ms(), start) # compute time difference - -Timers ------- - -Virtual (RTOS-based) timers are supported. Use the :ref:`machine.Timer ` class -with timer ID of -1:: - - from machine import Timer - - tim = Timer(-1) - tim.init(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(1)) - tim.init(period=2000, mode=Timer.PERIODIC, callback=lambda t:print(2)) - -The period is in milliseconds. - -Pins and GPIO -------------- - -Use the :ref:`machine.Pin ` class:: - - from machine import Pin - - p0 = Pin(0, Pin.OUT) # create output pin on GPIO0 - p0.on() # set pin to "on" (high) level - p0.off() # set pin to "off" (low) level - p0.value(1) # set pin to on/high - - p2 = Pin(2, Pin.IN) # create input pin on GPIO2 - print(p2.value()) # get value, 0 or 1 - - p4 = Pin(4, Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor - p5 = Pin(5, Pin.OUT, value=1) # set pin high on creation - -Available pins are: 0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16, which correspond -to the actual GPIO pin numbers of ESP8266 chip. Note that many end-user -boards use their own adhoc pin numbering (marked e.g. D0, D1, ...). As -MicroPython supports different boards and modules, physical pin numbering -was chosen as the lowest common denominator. For mapping between board -logical pins and physical chip pins, consult your board documentation. - -Note that Pin(1) and Pin(3) are REPL UART TX and RX respectively. -Also note that Pin(16) is a special pin (used for wakeup from deepsleep -mode) and may be not available for use with higher-level classes like -``Neopixel``. - -PWM (pulse width modulation) ----------------------------- - -PWM can be enabled on all pins except Pin(16). There is a single frequency -for all channels, with range between 1 and 1000 (measured in Hz). The duty -cycle is between 0 and 1023 inclusive. - -Use the ``machine.PWM`` class:: - - from machine import Pin, PWM - - pwm0 = PWM(Pin(0)) # create PWM object from a pin - pwm0.freq() # get current frequency - pwm0.freq(1000) # set frequency - pwm0.duty() # get current duty cycle - pwm0.duty(200) # set duty cycle - pwm0.deinit() # turn off PWM on the pin - - pwm2 = PWM(Pin(2), freq=500, duty=512) # create and configure in one go - -ADC (analog to digital conversion) ----------------------------------- - -ADC is available on a dedicated pin. -Note that input voltages on the ADC pin must be between 0v and 1.0v. - -Use the :ref:`machine.ADC ` class:: - - from machine import ADC - - adc = ADC(0) # create ADC object on ADC pin - adc.read() # read value, 0-1024 - -Software SPI bus ----------------- - -There are two SPI drivers. One is implemented in software (bit-banging) -and works on all pins, and is accessed via the :ref:`machine.SPI ` -class:: - - from machine import Pin, SPI - - # construct an SPI bus on the given pins - # polarity is the idle state of SCK - # phase=0 means sample on the first edge of SCK, phase=1 means the second - spi = SPI(-1, baudrate=100000, polarity=1, phase=0, sck=Pin(0), mosi=Pin(2), miso=Pin(4)) - - spi.init(baudrate=200000) # set the baudrate - - spi.read(10) # read 10 bytes on MISO - spi.read(10, 0xff) # read 10 bytes while outputing 0xff on MOSI - - buf = bytearray(50) # create a buffer - spi.readinto(buf) # read into the given buffer (reads 50 bytes in this case) - spi.readinto(buf, 0xff) # read into the given buffer and output 0xff on MOSI - - spi.write(b'12345') # write 5 bytes on MOSI - - buf = bytearray(4) # create a buffer - spi.write_readinto(b'1234', buf) # write to MOSI and read from MISO into the buffer - spi.write_readinto(buf, buf) # write buf to MOSI and read MISO back into buf - - -Hardware SPI bus ----------------- - -The hardware SPI is faster (up to 80Mhz), but only works on following pins: -``MISO`` is GPIO12, ``MOSI`` is GPIO13, and ``SCK`` is GPIO14. It has the same -methods as the bitbanging SPI class above, except for the pin parameters for the -constructor and init (as those are fixed):: - - from machine import Pin, SPI - - hspi = SPI(1, baudrate=80000000, polarity=0, phase=0) - -(``SPI(0)`` is used for FlashROM and not available to users.) - -I2C bus -------- - -The I2C driver is implemented in software and works on all pins, -and is accessed via the :ref:`machine.I2C ` class:: - - from machine import Pin, I2C - - # construct an I2C bus - i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000) - - i2c.readfrom(0x3a, 4) # read 4 bytes from slave device with address 0x3a - i2c.writeto(0x3a, '12') # write '12' to slave device with address 0x3a - - buf = bytearray(10) # create a buffer with 10 bytes - i2c.writeto(0x3a, buf) # write the given buffer to the slave - -Real time clock (RTC) ---------------------- - -See :ref:`machine.RTC ` :: - - from machine import RTC - - rtc = RTC() - rtc.datetime((2017, 8, 23, 1, 12, 48, 0, 0)) # set a specific date and time - rtc.datetime() # get date and time - -Deep-sleep mode ---------------- - -Connect GPIO16 to the reset pin (RST on HUZZAH). Then the following code -can be used to sleep, wake and check the reset cause:: - - import machine - - # configure RTC.ALARM0 to be able to wake the device - rtc = machine.RTC() - rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) - - # check if the device woke from a deep sleep - if machine.reset_cause() == machine.DEEPSLEEP_RESET: - print('woke from a deep sleep') - - # set RTC.ALARM0 to fire after 10 seconds (waking the device) - rtc.alarm(rtc.ALARM0, 10000) - - # put the device to sleep - machine.deepsleep() - -OneWire driver --------------- - -The OneWire driver is implemented in software and works on all pins:: - - from machine import Pin - import onewire - - ow = onewire.OneWire(Pin(12)) # create a OneWire bus on GPIO12 - ow.scan() # return a list of devices on the bus - ow.reset() # reset the bus - ow.readbyte() # read a byte - ow.writebyte(0x12) # write a byte on the bus - ow.write('123') # write bytes on the bus - ow.select_rom(b'12345678') # select a specific device by its ROM code - -There is a specific driver for DS18S20 and DS18B20 devices:: - - import time, ds18x20 - ds = ds18x20.DS18X20(ow) - roms = ds.scan() - ds.convert_temp() - time.sleep_ms(750) - for rom in roms: - print(ds.read_temp(rom)) - -Be sure to put a 4.7k pull-up resistor on the data line. Note that -the ``convert_temp()`` method must be called each time you want to -sample the temperature. - -NeoPixel driver ---------------- - -Use the ``neopixel`` module:: - - from machine import Pin - from neopixel import NeoPixel - - pin = Pin(0, Pin.OUT) # set GPIO0 to output to drive NeoPixels - np = NeoPixel(pin, 8) # create NeoPixel driver on GPIO0 for 8 pixels - np[0] = (255, 255, 255) # set the first pixel to white - np.write() # write data to all pixels - r, g, b = np[0] # get first pixel colour - -For low-level driving of a NeoPixel:: - - import esp - esp.neopixel_write(pin, grb_buf, is800khz) - -APA102 driver -------------- - -Use the ``apa102`` module:: - - from machine import Pin - from apa102 import APA102 - - clock = Pin(14, Pin.OUT) # set GPIO14 to output to drive the clock - data = Pin(13, Pin.OUT) # set GPIO13 to output to drive the data - apa = APA102(clock, data, 8) # create APA102 driver on the clock and the data pin for 8 pixels - apa[0] = (255, 255, 255, 31) # set the first pixel to white with a maximum brightness of 31 - apa.write() # write data to all pixels - r, g, b, brightness = apa[0] # get first pixel colour - -For low-level driving of an APA102:: - - import esp - esp.apa102_write(clock_pin, data_pin, rgbi_buf) - -DHT driver ----------- - -The DHT driver is implemented in software and works on all pins:: - - import dht - import machine - - d = dht.DHT11(machine.Pin(4)) - d.measure() - d.temperature() # eg. 23 (°C) - d.humidity() # eg. 41 (% RH) - - d = dht.DHT22(machine.Pin(4)) - d.measure() - d.temperature() # eg. 23.6 (°C) - d.humidity() # eg. 41.3 (% RH) - -WebREPL (web browser interactive prompt) ----------------------------------------- - -WebREPL (REPL over WebSockets, accessible via a web browser) is an -experimental feature available in ESP8266 port. Download web client -from https://github.com/micropython/webrepl (hosted version available -at http://micropython.org/webrepl), and configure it by executing:: - - import webrepl_setup - -and following on-screen instructions. After reboot, it will be available -for connection. If you disabled automatic start-up on boot, you may -run configured daemon on demand using:: - - import webrepl - webrepl.start() - -The supported way to use WebREPL is by connecting to ESP8266 access point, -but the daemon is also started on STA interface if it is active, so if your -router is set up and works correctly, you may also use WebREPL while connected -to your normal Internet access point (use the ESP8266 AP connection method -if you face any issues). - -Besides terminal/command prompt access, WebREPL also has provision for file -transfer (both upload and download). Web client has buttons for the -corresponding functions, or you can use command-line client ``webrepl_cli.py`` -from the repository above. - -See the MicroPython forum for other community-supported alternatives -to transfer files to ESP8266. diff --git a/docs/esp8266/tutorial/adc.rst b/docs/esp8266/tutorial/adc.rst deleted file mode 100644 index fa6fdaba73..0000000000 --- a/docs/esp8266/tutorial/adc.rst +++ /dev/null @@ -1,19 +0,0 @@ -Analog to Digital Conversion -============================ - -The ESP8266 has a single pin (separate to the GPIO pins) which can be used to -read analog voltages and convert them to a digital value. You can construct -such an ADC pin object using:: - - >>> import machine - >>> adc = machine.ADC(0) - -Then read its value with:: - - >>> adc.read() - 58 - -The values returned from the ``read()`` function are between 0 (for 0.0 volts) -and 1024 (for 1.0 volts). Please note that this input can only tolerate a -maximum of 1.0 volts and you must use a voltage divider circuit to measure -larger voltages. diff --git a/docs/esp8266/tutorial/dht.rst b/docs/esp8266/tutorial/dht.rst deleted file mode 100644 index 1602e8a337..0000000000 --- a/docs/esp8266/tutorial/dht.rst +++ /dev/null @@ -1,65 +0,0 @@ -Temperature and Humidity -======================== - -DHT (Digital Humidity & Temperature) sensors are low cost digital sensors with -capacitive humidity sensors and thermistors to measure the surrounding air. -They feature a chip that handles analog to digital conversion and provide a -1-wire interface. Newer sensors additionally provide an I2C interface. - -The DHT11 (blue) and DHT22 (white) sensors provide the same 1-wire interface, -however, the DHT22 requires a separate object as it has more complex -calculation. DHT22 have 1 decimal place resolution for both humidity and -temperature readings. DHT11 have whole number for both. - -A custom 1-wire protocol, which is different to Dallas 1-wire, is used to get -the measurements from the sensor. The payload consists of a humidity value, -a temperature value and a checksum. - -To use the 1-wire interface, construct the objects referring to their data pin:: - - >>> import dht - >>> import machine - >>> d = dht.DHT11(machine.Pin(4)) - - >>> import dht - >>> import machine - >>> d = dht.DHT22(machine.Pin(4)) - -Then measure and read their values with:: - - >>> d.measure() - >>> d.temperature() - >>> d.humidity() - -Values returned from ``temperature()`` are in degrees Celsius and values -returned from ``humidity()`` are a percentage of relative humidity. - -The DHT11 can be called no more than once per second and the DHT22 once every -two seconds for most accurate results. Sensor accuracy will degrade over time. -Each sensor supports a different operating range. Refer to the product -datasheets for specifics. - -In 1-wire mode, only three of the four pins are used and in I2C mode, all four -pins are used. Older sensors may still have 4 pins even though they do not -support I2C. The 3rd pin is simply not connected. - -Pin configurations: - -Sensor without I2C in 1-wire mode (eg. DHT11, DHT22, AM2301, AM2302): - - 1=VDD, 2=Data, 3=NC, 4=GND - -Sensor with I2C in 1-wire mode (eg. DHT12, AM2320, AM2321, AM2322): - - 1=VDD, 2=Data, 3=GND, 4=GND - -Sensor with I2C in I2C mode (eg. DHT12, AM2320, AM2321, AM2322): - - 1=VDD, 2=SDA, 3=GND, 4=SCL - -You should use pull-up resistors for the Data, SDA and SCL pins. - -To make newer I2C sensors work in backwards compatible 1-wire mode, you must -connect both pins 3 and 4 to GND. This disables the I2C interface. - -DHT22 sensors are now sold under the name AM2302 and are otherwise identical. diff --git a/docs/esp8266/tutorial/filesystem.rst b/docs/esp8266/tutorial/filesystem.rst deleted file mode 100644 index 27b0d2608c..0000000000 --- a/docs/esp8266/tutorial/filesystem.rst +++ /dev/null @@ -1,69 +0,0 @@ -The internal filesystem -======================= - -If your devices has 1Mbyte or more of storage then it will be set up (upon first -boot) to contain a filesystem. This filesystem uses the FAT format and is -stored in the flash after the MicroPython firmware. - -Creating and reading files --------------------------- - -MicroPython on the ESP8266 supports the standard way of accessing files in -Python, using the built-in ``open()`` function. - -To create a file try:: - - >>> f = open('data.txt', 'w') - >>> f.write('some data') - 9 - >>> f.close() - -The "9" is the number of bytes that were written with the ``write()`` method. -Then you can read back the contents of this new file using:: - - >>> f = open('data.txt') - >>> f.read() - 'some data' - >>> f.close() - -Note that the default mode when opening a file is to open it in read-only mode, -and as a text file. Specify ``'wb'`` as the second argument to ``open()`` to -open for writing in binary mode, and ``'rb'`` to open for reading in binary -mode. - -Listing file and more ---------------------- - -The os module can be used for further control over the filesystem. First -import the module:: - - >>> import os - -Then try listing the contents of the filesystem:: - - >>> os.listdir() - ['boot.py', 'port_config.py', 'data.txt'] - -You can make directories:: - - >>> os.mkdir('dir') - -And remove entries:: - - >>> os.remove('data.txt') - -Start up scripts ----------------- - -There are two files that are treated specially by the ESP8266 when it starts up: -boot.py and main.py. The boot.py script is executed first (if it exists) and -then once it completes the main.py script is executed. You can create these -files yourself and populate them with the code that you want to run when the -device starts up. - -Accessing the filesystem via WebREPL ------------------------------------- - -You can access the filesystem over WebREPL using the web client in a browser -or via the command-line tool. Please refer to Quick Reference and Tutorial -sections for more information about WebREPL. diff --git a/docs/esp8266/tutorial/index.rst b/docs/esp8266/tutorial/index.rst deleted file mode 100644 index 39b4592600..0000000000 --- a/docs/esp8266/tutorial/index.rst +++ /dev/null @@ -1,33 +0,0 @@ -.. _tutorial-index: - -MicroPython tutorial for ESP8266 -================================ - -This tutorial is intended to get you started using MicroPython on the ESP8266 -system-on-a-chip. If it is your first time it is recommended to follow the -tutorial through in the order below. Otherwise the sections are mostly self -contained, so feel free to skip to those that interest you. - -The tutorial does not assume that you know Python, but it also does not attempt -to explain any of the details of the Python language. Instead it provides you -with commands that are ready to run, and hopes that you will gain a bit of -Python knowledge along the way. To learn more about Python itself please refer -to ``__. - -.. toctree:: - :maxdepth: 1 - :numbered: - - intro.rst - repl.rst - filesystem.rst - network_basics.rst - network_tcp.rst - pins.rst - pwm.rst - adc.rst - powerctrl.rst - onewire.rst - neopixel.rst - dht.rst - nextsteps.rst diff --git a/docs/esp8266/tutorial/intro.rst b/docs/esp8266/tutorial/intro.rst deleted file mode 100644 index 711db3fceb..0000000000 --- a/docs/esp8266/tutorial/intro.rst +++ /dev/null @@ -1,202 +0,0 @@ -.. _intro: - -Getting started with MicroPython on the ESP8266 -=============================================== - -Using MicroPython is a great way to get the most of your ESP8266 board. And -vice versa, the ESP8266 chip is a great platform for using MicroPython. This -tutorial will guide you through setting up MicroPython, getting a prompt, using -WebREPL, connecting to the network and communicating with the Internet, using -the hardware peripherals, and controlling some external components. - -Let's get started! - -Requirements ------------- - -The first thing you need is a board with an ESP8266 chip. The MicroPython -software supports the ESP8266 chip itself and any board should work. The main -characteristic of a board is how much flash it has, how the GPIO pins are -connected to the outside world, and whether it includes a built-in USB-serial -convertor to make the UART available to your PC. - -The minimum requirement for flash size is 1Mbyte. There is also a special -build for boards with 512KB, but it is highly limited comparing to the -normal build: there is no support for filesystem, and thus features which -depend on it won't work (WebREPL, upip, etc.). As such, 512KB build will -be more interesting for users who build from source and fine-tune parameters -for their particular application. - -Names of pins will be given in this tutorial using the chip names (eg GPIO0) -and it should be straightforward to find which pin this corresponds to on your -particular board. - -Powering the board ------------------- - -If your board has a USB connector on it then most likely it is powered through -this when connected to your PC. Otherwise you will need to power it directly. -Please refer to the documentation for your board for further details. - -Getting the firmware --------------------- - -The first thing you need to do is download the most recent MicroPython firmware -.bin file to load onto your ESP8266 device. You can download it from the -`MicroPython downloads page `_. -From here, you have 3 main choices - -* Stable firmware builds for 1024kb modules and above. -* Daily firmware builds for 1024kb modules and above. -* Daily firmware builds for 512kb modules. - -If you are just starting with MicroPython, the best bet is to go for the Stable -firmware builds. If you are an advanced, experienced MicroPython ESP8266 user -who would like to follow development closely and help with testing new -features, there are daily builds (note: you actually may need some -development experience, e.g. being ready to follow git history to know -what new changes and features were introduced). - -Support for 512kb modules is provided on a feature preview basis. For end -users, it's recommended to use modules with flash of 1024kb or more. As -such, only daily builds for 512kb modules are provided. - -Deploying the firmware ----------------------- - -Once you have the MicroPython firmware (compiled code), you need to load it onto -your ESP8266 device. There are two main steps to do this: first you -need to put your device in boot-loader mode, and second you need to copy across -the firmware. The exact procedure for these steps is highly dependent on the -particular board and you will need to refer to its documentation for details. - -If you have a board that has a USB connector, a USB-serial convertor, and has -the DTR and RTS pins wired in a special way then deploying the firmware should -be easy as all steps can be done automatically. Boards that have such features -include the Adafruit Feather HUZZAH and NodeMCU boards. - -For best results it is recommended to first erase the entire flash of your -device before putting on new MicroPython firmware. - -Currently we only support esptool.py to copy across the firmware. You can find -this tool here: ``__, or install it -using pip:: - - pip install esptool - -Versions starting with 1.3 support both Python 2.7 and Python 3.4 (or newer). -An older version (at least 1.2.1 is needed) works fine but will require Python -2.7. - -Any other flashing program should work, so feel free to try them out or refer -to the documentation for your board to see its recommendations. - -Using esptool.py you can erase the flash with the command:: - - esptool.py --port /dev/ttyUSB0 erase_flash - -And then deploy the new firmware using:: - - esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect 0 esp8266-20170108-v1.8.7.bin - -You might need to change the "port" setting to something else relevant for your -PC. You may also need to reduce the baudrate if you get errors when flashing -(eg down to 115200). The filename of the firmware should also match the file -that you have. - -For some boards with a particular FlashROM configuration (e.g. some variants of -a NodeMCU board) you may need to use the following command to deploy -the firmware (note the ``-fm dio`` option):: - - esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect -fm dio 0 esp8266-20170108-v1.8.7.bin - -If the above commands run without error then MicroPython should be installed on -your board! - -Serial prompt -------------- - -Once you have the firmware on the device you can access the REPL (Python prompt) -over UART0 (GPIO1=TX, GPIO3=RX), which might be connected to a USB-serial -convertor, depending on your board. The baudrate is 115200. The next part of -the tutorial will discuss the prompt in more detail. - -WiFi ----- - -After a fresh install and boot the device configures itself as a WiFi access -point (AP) that you can connect to. The ESSID is of the form MicroPython-xxxxxx -where the x's are replaced with part of the MAC address of your device (so will -be the same everytime, and most likely different for all ESP8266 chips). The -password for the WiFi is micropythoN (note the upper-case N). Its IP address -will be 192.168.4.1 once you connect to its network. WiFi configuration will -be discussed in more detail later in the tutorial. - -Troubleshooting installation problems -------------------------------------- - -If you experience problems during flashing or with running firmware immediately -after it, here are troubleshooting recommendations: - -* Be aware of and try to exclude hardware problems. There are 2 common problems: - bad power source quality and worn-out/defective FlashROM. Speaking of power - source, not just raw amperage is important, but also low ripple and noise/EMI - in general. If you experience issues with self-made or wall-wart style power - supply, try USB power from a computer. Unearthed power supplies are also known - to cause problems as they source of increased EMI (electromagnetic interference) - - at the very least, and may lead to electrical devices breakdown. So, you are - advised to avoid using unearthed power connections when working with ESP8266 - and other boards. In regard to FlashROM hardware problems, there are independent - (not related to MicroPython in any way) reports - `(e.g.) `_ - that on some ESP8266 modules, FlashROM can be programmed as little as 20 times - before programming errors occur. This is *much* less than 100,000 programming - cycles cited for FlashROM chips of a type used with ESP8266 by reputable - vendors, which points to either production rejects, or second-hand worn-out - flash chips to be used on some (apparently cheap) modules/boards. You may want - to use your best judgement about source, price, documentation, warranty, - post-sales support for the modules/boards you purchase. - -* The flashing instructions above use flashing speed of 460800 baud, which is - good compromise between speed and stability. However, depending on your - module/board, USB-UART convertor, cables, host OS, etc., the above baud - rate may be too high and lead to errors. Try a more common 115200 baud - rate instead in such cases. - -* If lower baud rate didn't help, you may want to try older version of - esptool.py, which had a different programming algorithm:: - - pip install esptool==1.0.1 - - This version doesn't support ``--flash_size=detect`` option, so you will - need to specify FlashROM size explicitly (in megabits). It also requires - Python 2.7, so you may need to use ``pip2`` instead of ``pip`` in the - command above. - -* The ``--flash_size`` option in the commands above is mandatory. Omitting - it will lead to a corrupted firmware. - -* To catch incorrect flash content (e.g. from a defective sector on a chip), - add ``--verify`` switch to the commands above. - -* Additionally, you can check the firmware integrity from a MicroPython REPL - prompt (assuming you were able to flash it and ``--verify`` option doesn't - report errors):: - - import esp - esp.check_fw() - - If the last output value is True, the firmware is OK. Otherwise, it's - corrupted and need to be reflashed correctly. - -* If you experience any issues with another flashing application (not - esptool.py), try esptool.py, it is a generally accepted flashing - application in the ESP8266 community. - -* If you still experience problems with even flashing the firmware, please - refer to esptool.py project page, https://github.com/espressif/esptool - for additional documentation and bug tracker where you can report problems. - -* If you are able to flash firmware, but ``--verify`` option or - ``esp.check_fw()`` return errors even after multiple retries, you - may have a defective FlashROM chip, as explained above. diff --git a/docs/esp8266/tutorial/neopixel.rst b/docs/esp8266/tutorial/neopixel.rst deleted file mode 100644 index a1537526f3..0000000000 --- a/docs/esp8266/tutorial/neopixel.rst +++ /dev/null @@ -1,84 +0,0 @@ -Controlling NeoPixels -===================== - -NeoPixels, also known as WS2812 LEDs, are full-colour LEDs that are connected in -serial, are individually addressable, and can have their red, green and blue -components set between 0 and 255. They require precise timing to control them -and there is a special neopixel module to do just this. - -To create a NeoPixel object do the following:: - - >>> import machine, neopixel - >>> np = neopixel.NeoPixel(machine.Pin(4), 8) - -This configures a NeoPixel strip on GPIO4 with 8 pixels. You can adjust the -"4" (pin number) and the "8" (number of pixel) to suit your set up. - -To set the colour of pixels use:: - - >>> np[0] = (255, 0, 0) # set to red, full brightness - >>> np[1] = (0, 128, 0) # set to green, half brightness - >>> np[2] = (0, 0, 64) # set to blue, quarter brightness - -For LEDs with more than 3 colours, such as RGBW pixels or RGBY pixels, the -NeoPixel class takes a ``bpp`` parameter. To setup a NeoPixel object for an -RGBW Pixel, do the following:: - - >>> import machine, neopixel - >>> np = neopixel.NeoPixel(machine.Pin(4), 8, bpp=4) - -In a 4-bpp mode, remember to use 4-tuples instead of 3-tuples to set the colour. -For example to set the first three pixels use:: - - >>> np[0] = (255, 0, 0, 128) # Orange in an RGBY Setup - >>> np[1] = (0, 255, 0, 128) # Yellow-green in an RGBY Setup - >>> np[2] = (0, 0, 255, 128) # Green-blue in an RGBY Setup - -Then use the ``write()`` method to output the colours to the LEDs:: - - >>> np.write() - -The following demo function makes a fancy show on the LEDs:: - - import time - - def demo(np): - n = np.n - - # cycle - for i in range(4 * n): - for j in range(n): - np[j] = (0, 0, 0) - np[i % n] = (255, 255, 255) - np.write() - time.sleep_ms(25) - - # bounce - for i in range(4 * n): - for j in range(n): - np[j] = (0, 0, 128) - if (i // n) % 2 == 0: - np[i % n] = (0, 0, 0) - else: - np[n - 1 - (i % n)] = (0, 0, 0) - np.write() - time.sleep_ms(60) - - # fade in/out - for i in range(0, 4 * 256, 8): - for j in range(n): - if (i // 256) % 2 == 0: - val = i & 0xff - else: - val = 255 - (i & 0xff) - np[j] = (val, 0, 0) - np.write() - - # clear - for i in range(n): - np[i] = (0, 0, 0) - np.write() - -Execute it using:: - - >>> demo(np) diff --git a/docs/esp8266/tutorial/network_basics.rst b/docs/esp8266/tutorial/network_basics.rst deleted file mode 100644 index 95d8cba4f9..0000000000 --- a/docs/esp8266/tutorial/network_basics.rst +++ /dev/null @@ -1,81 +0,0 @@ -Network basics -============== - -The network module is used to configure the WiFi connection. There are two WiFi -interfaces, one for the station (when the ESP8266 connects to a router) and one -for the access point (for other devices to connect to the ESP8266). Create -instances of these objects using:: - - >>> import network - >>> sta_if = network.WLAN(network.STA_IF) - >>> ap_if = network.WLAN(network.AP_IF) - -You can check if the interfaces are active by:: - - >>> sta_if.active() - False - >>> ap_if.active() - True - -You can also check the network settings of the interface by:: - - >>> ap_if.ifconfig() - ('192.168.4.1', '255.255.255.0', '192.168.4.1', '8.8.8.8') - -The returned values are: IP address, netmask, gateway, DNS. - -Configuration of the WiFi -------------------------- - -Upon a fresh install the ESP8266 is configured in access point mode, so the -AP_IF interface is active and the STA_IF interface is inactive. You can -configure the module to connect to your own network using the STA_IF interface. - -First activate the station interface:: - - >>> sta_if.active(True) - -Then connect to your WiFi network:: - - >>> sta_if.connect('', '') - -To check if the connection is established use:: - - >>> sta_if.isconnected() - -Once established you can check the IP address:: - - >>> sta_if.ifconfig() - ('192.168.0.2', '255.255.255.0', '192.168.0.1', '8.8.8.8') - -You can then disable the access-point interface if you no longer need it:: - - >>> ap_if.active(False) - -Here is a function you can run (or put in your boot.py file) to automatically -connect to your WiFi network:: - - def do_connect(): - import network - sta_if = network.WLAN(network.STA_IF) - if not sta_if.isconnected(): - print('connecting to network...') - sta_if.active(True) - sta_if.connect('', '') - while not sta_if.isconnected(): - pass - print('network config:', sta_if.ifconfig()) - -Sockets -------- - -Once the WiFi is set up the way to access the network is by using sockets. -A socket represents an endpoint on a network device, and when two sockets are -connected together communication can proceed. -Internet protocols are built on top of sockets, such as email (SMTP), the web -(HTTP), telnet, ssh, among many others. Each of these protocols is assigned -a specific port, which is just an integer. Given an IP address and a port -number you can connect to a remote device and start talking with it. - -The next part of the tutorial discusses how to use sockets to do some common -and useful network tasks. diff --git a/docs/esp8266/tutorial/network_tcp.rst b/docs/esp8266/tutorial/network_tcp.rst deleted file mode 100644 index 26a2f469ce..0000000000 --- a/docs/esp8266/tutorial/network_tcp.rst +++ /dev/null @@ -1,122 +0,0 @@ -Network - TCP sockets -===================== - -The building block of most of the internet is the TCP socket. These sockets -provide a reliable stream of bytes between the connected network devices. -This part of the tutorial will show how to use TCP sockets in a few different -cases. - -Star Wars Asciimation ---------------------- - -The simplest thing to do is to download data from the internet. In this case -we will use the Star Wars Asciimation service provided by the blinkenlights.nl -website. It uses the telnet protocol on port 23 to stream data to anyone that -connects. It's very simple to use because it doesn't require you to -authenticate (give a username or password), you can just start downloading data -straight away. - -The first thing to do is make sure we have the socket module available:: - - >>> import socket - -Then get the IP address of the server:: - - >>> addr_info = socket.getaddrinfo("towel.blinkenlights.nl", 23) - -The ``getaddrinfo`` function actually returns a list of addresses, and each -address has more information than we need. We want to get just the first valid -address, and then just the IP address and port of the server. To do this use:: - - >>> addr = addr_info[0][-1] - -If you type ``addr_info`` and ``addr`` at the prompt you will see exactly what -information they hold. - -Using the IP address we can make a socket and connect to the server:: - - >>> s = socket.socket() - >>> s.connect(addr) - -Now that we are connected we can download and display the data:: - - >>> while True: - ... data = s.recv(500) - ... print(str(data, 'utf8'), end='') - ... - -When this loop executes it should start showing the animation (use ctrl-C to -interrupt it). - -You should also be able to run this same code on your PC using normal Python if -you want to try it out there. - -HTTP GET request ----------------- - -The next example shows how to download a webpage. HTTP uses port 80 and you -first need to send a "GET" request before you can download anything. As part -of the request you need to specify the page to retrieve. - -Let's define a function that can download and print a URL:: - - def http_get(url): - _, _, host, path = url.split('/', 3) - addr = socket.getaddrinfo(host, 80)[0][-1] - s = socket.socket() - s.connect(addr) - s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8')) - while True: - data = s.recv(100) - if data: - print(str(data, 'utf8'), end='') - else: - break - s.close() - -Make sure that you import the socket module before running this function. Then -you can try:: - - >>> http_get('http://micropython.org/ks/test.html') - -This should retrieve the webpage and print the HTML to the console. - -Simple HTTP server ------------------- - -The following code creates an simple HTTP server which serves a single webpage -that contains a table with the state of all the GPIO pins:: - - import machine - pins = [machine.Pin(i, machine.Pin.IN) for i in (0, 2, 4, 5, 12, 13, 14, 15)] - - html = """ - - ESP8266 Pins -

ESP8266 Pins

- %s
PinValue
- - - """ - - import socket - addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] - - s = socket.socket() - s.bind(addr) - s.listen(1) - - print('listening on', addr) - - while True: - cl, addr = s.accept() - print('client connected from', addr) - cl_file = cl.makefile('rwb', 0) - while True: - line = cl_file.readline() - if not line or line == b'\r\n': - break - rows = ['%s%d' % (str(p), p.value()) for p in pins] - response = html % '\n'.join(rows) - cl.send(response) - cl.close() diff --git a/docs/esp8266/tutorial/nextsteps.rst b/docs/esp8266/tutorial/nextsteps.rst deleted file mode 100644 index 318bd7ddf8..0000000000 --- a/docs/esp8266/tutorial/nextsteps.rst +++ /dev/null @@ -1,12 +0,0 @@ -Next steps -========== - -That brings us to the end of the tutorial! Hopefully by now you have a good -feel for the capabilities of MicroPython on the ESP8266 and understand how to -control both the WiFi and IO aspects of the chip. - -There are many features that were not covered in this tutorial. The best way -to learn about them is to read the full documentation of the modules, and to -experiment! - -Good luck creating your Internet of Things devices! diff --git a/docs/esp8266/tutorial/onewire.rst b/docs/esp8266/tutorial/onewire.rst deleted file mode 100644 index c2cede9e38..0000000000 --- a/docs/esp8266/tutorial/onewire.rst +++ /dev/null @@ -1,37 +0,0 @@ -Controlling 1-wire devices -========================== - -The 1-wire bus is a serial bus that uses just a single wire for communication -(in addition to wires for ground and power). The DS18B20 temperature sensor -is a very popular 1-wire device, and here we show how to use the onewire module -to read from such a device. - -For the following code to work you need to have at least one DS18S20 or DS18B20 temperature -sensor with its data line connected to GPIO12. You must also power the sensors -and connect a 4.7k Ohm resistor between the data pin and the power pin. :: - - import time - import machine - import onewire, ds18x20 - - # the device is on GPIO12 - dat = machine.Pin(12) - - # create the onewire object - ds = ds18x20.DS18X20(onewire.OneWire(dat)) - - # scan for devices on the bus - roms = ds.scan() - print('found devices:', roms) - - # loop 10 times and print all temperatures - for i in range(10): - print('temperatures:', end=' ') - ds.convert_temp() - time.sleep_ms(750) - for rom in roms: - print(ds.read_temp(rom), end=' ') - print() - -Note that you must execute the ``convert_temp()`` function to initiate a -temperature reading, then wait at least 750ms before reading the value. diff --git a/docs/esp8266/tutorial/pins.rst b/docs/esp8266/tutorial/pins.rst deleted file mode 100644 index cd45c83cd3..0000000000 --- a/docs/esp8266/tutorial/pins.rst +++ /dev/null @@ -1,75 +0,0 @@ -GPIO Pins -========= - -The way to connect your board to the external world, and control other -components, is through the GPIO pins. Not all pins are available to use, -in most cases only pins 0, 2, 4, 5, 12, 13, 14, 15, and 16 can be used. - -The pins are available in the machine module, so make sure you import that -first. Then you can create a pin using:: - - >>> pin = machine.Pin(0) - -Here, the "0" is the pin that you want to access. Usually you want to -configure the pin to be input or output, and you do this when constructing -it. To make an input pin use:: - - >>> pin = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP) - -You can either use PULL_UP or None for the input pull-mode. If it's -not specified then it defaults to None, which is no pull resistor. -You can read the value on the pin using:: - - >>> pin.value() - 0 - -The pin on your board may return 0 or 1 here, depending on what it's connected -to. To make an output pin use:: - - >>> pin = machine.Pin(0, machine.Pin.OUT) - -Then set its value using:: - - >>> pin.value(0) - >>> pin.value(1) - -Or:: - - >>> pin.off() - >>> pin.on() - -External interrupts -------------------- - -All pins except number 16 can be configured to trigger a hard interrupt if their -input changes. You can set code (a callback function) to be executed on the -trigger. - -Let's first define a callback function, which must take a single argument, -being the pin that triggered the function. We will make the function just print -the pin:: - - >>> def callback(p): - ... print('pin change', p) - -Next we will create two pins and configure them as inputs:: - - >>> from machine import Pin - >>> p0 = Pin(0, Pin.IN) - >>> p2 = Pin(2, Pin.IN) - -An finally we need to tell the pins when to trigger, and the function to call -when they detect an event:: - - >>> p0.irq(trigger=Pin.IRQ_FALLING, handler=callback) - >>> p2.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=callback) - -We set pin 0 to trigger only on a falling edge of the input (when it goes from -high to low), and set pin 2 to trigger on both a rising and falling edge. After -entering this code you can apply high and low voltages to pins 0 and 2 to see -the interrupt being executed. - -A hard interrupt will trigger as soon as the event occurs and will interrupt any -running code, including Python code. As such your callback functions are -limited in what they can do (they cannot allocate memory, for example) and -should be as short and simple as possible. diff --git a/docs/esp8266/tutorial/powerctrl.rst b/docs/esp8266/tutorial/powerctrl.rst deleted file mode 100644 index 3502624ab5..0000000000 --- a/docs/esp8266/tutorial/powerctrl.rst +++ /dev/null @@ -1,61 +0,0 @@ -Power control -============= - -The ESP8266 provides the ability to change the CPU frequency on the fly, and -enter a deep-sleep state. Both can be used to manage power consumption. - -Changing the CPU frequency --------------------------- - -The machine module has a function to get and set the CPU frequency. To get the -current frequency use:: - - >>> import machine - >>> machine.freq() - 80000000 - -By default the CPU runs at 80MHz. It can be change to 160MHz if you need more -processing power, at the expense of current consumption:: - - >>> machine.freq(160000000) - >>> machine.freq() - 160000000 - -You can change to the higher frequency just while your code does the heavy -processing and then change back when it's finished. - -Deep-sleep mode ---------------- - -The deep-sleep mode will shut down the ESP8266 and all its peripherals, -including the WiFi (but not including the real-time-clock, which is used to wake -the chip). This drastically reduces current consumption and is a good way to -make devices that can run for a while on a battery. - -To be able to use the deep-sleep feature you must connect GPIO16 to the reset -pin (RST on the Adafruit Feather HUZZAH board). Then the following code can be -used to sleep and wake the device:: - - import machine - - # configure RTC.ALARM0 to be able to wake the device - rtc = machine.RTC() - rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) - - # set RTC.ALARM0 to fire after 10 seconds (waking the device) - rtc.alarm(rtc.ALARM0, 10000) - - # put the device to sleep - machine.deepsleep() - -Note that when the chip wakes from a deep-sleep it is completely reset, -including all of the memory. The boot scripts will run as usual and you can -put code in them to check the reset cause to perhaps do something different if -the device just woke from a deep-sleep. For example, to print the reset cause -you can use:: - - if machine.reset_cause() == machine.DEEPSLEEP_RESET: - print('woke from a deep sleep') - else: - print('power on or hard reset') - diff --git a/docs/esp8266/tutorial/pwm.rst b/docs/esp8266/tutorial/pwm.rst deleted file mode 100644 index 17f8ede356..0000000000 --- a/docs/esp8266/tutorial/pwm.rst +++ /dev/null @@ -1,87 +0,0 @@ -Pulse Width Modulation -====================== - -Pulse width modulation (PWM) is a way to get an artificial analog output on a -digital pin. It achieves this by rapidly toggling the pin from low to high. -There are two parameters associated with this: the frequency of the toggling, -and the duty cycle. The duty cycle is defined to be how long the pin is high -compared with the length of a single period (low plus high time). Maximum -duty cycle is when the pin is high all of the time, and minimum is when it is -low all of the time. - -On the ESP8266 the pins 0, 2, 4, 5, 12, 13, 14 and 15 all support PWM. The -limitation is that they must all be at the same frequency, and the frequency -must be between 1Hz and 1kHz. - -To use PWM on a pin you must first create the pin object, for example:: - - >>> import machine - >>> p12 = machine.Pin(12) - -Then create the PWM object using:: - - >>> pwm12 = machine.PWM(p12) - -You can set the frequency and duty cycle using:: - - >>> pwm12.freq(500) - >>> pwm12.duty(512) - -Note that the duty cycle is between 0 (all off) and 1023 (all on), with 512 -being a 50% duty. If you print the PWM object then it will tell you its current -configuration:: - - >>> pwm12 - PWM(12, freq=500, duty=512) - -You can also call the ``freq()`` and ``duty()`` methods with no arguments to -get their current values. - -The pin will continue to be in PWM mode until you deinitialise it using:: - - >>> pwm12.deinit() - -Fading an LED -------------- - -Let's use the PWM feature to fade an LED. Assuming your board has an LED -connected to pin 2 (ESP-12 modules do) we can create an LED-PWM object using:: - - >>> led = machine.PWM(machine.Pin(2), freq=1000) - -Notice that we can set the frequency in the PWM constructor. - -For the next part we will use timing and some math, so import these modules:: - - >>> import time, math - -Then create a function to pulse the LED:: - - >>> def pulse(l, t): - ... for i in range(20): - ... l.duty(int(math.sin(i / 10 * math.pi) * 500 + 500)) - ... time.sleep(t/1000) - -You can try this function out using:: - - >>> pulse(led, 50) - -For a nice effect you can pulse many times in a row:: - - >>> for i in range(10): - ... pulse(led, 20) - -Remember you can use ctrl-C to interrupt the code. - -Control a hobby servo ---------------------- - -Hobby servo motors can be controlled using PWM. They require a frequency of -50Hz and then a duty between about 40 and 115, with 77 being the centre value. -If you connect a servo to the power and ground pins, and then the signal line -to pin 12 (other pins will work just as well), you can control the motor using:: - - >>> servo = machine.PWM(machine.Pin(12), freq=50) - >>> servo.duty(40) - >>> servo.duty(115) - >>> servo.duty(77) diff --git a/docs/esp8266/tutorial/repl.rst b/docs/esp8266/tutorial/repl.rst deleted file mode 100644 index ba64fcccbe..0000000000 --- a/docs/esp8266/tutorial/repl.rst +++ /dev/null @@ -1,212 +0,0 @@ -Getting a MicroPython REPL prompt -================================= - -REPL stands for Read Evaluate Print Loop, and is the name given to the -interactive MicroPython prompt that you can access on the ESP8266. Using the -REPL is by far the easiest way to test out your code and run commands. - -There are two ways to access the REPL: either via a wired connection through the -UART serial port, or via WiFi. - -REPL over the serial port -------------------------- - -The REPL is always available on the UART0 serial peripheral, which is connected -to the pins GPIO1 for TX and GPIO3 for RX. The baudrate of the REPL is 115200. -If your board has a USB-serial convertor on it then you should be able to access -the REPL directly from your PC. Otherwise you will need to have a way of -communicating with the UART. - -To access the prompt over USB-serial you need to use a terminal emulator program. -On Windows TeraTerm is a good choice, on Mac you can use the built-in screen -program, and Linux has picocom and minicom. Of course, there are many other -terminal programs that will work, so pick your favourite! - -For example, on Linux you can try running:: - - picocom /dev/ttyUSB0 -b115200 - -Once you have made the connection over the serial port you can test if it is -working by hitting enter a few times. You should see the Python REPL prompt, -indicated by ``>>>``. - -WebREPL - a prompt over WiFi ----------------------------- - -WebREPL allows you to use the Python prompt over WiFi, connecting through a -browser. The latest versions of Firefox and Chrome are supported. - -For your convenience, WebREPL client is hosted at -``__ . Alternatively, you can install it -locally from the the GitHub repository -``__ . - -Before connecting to WebREPL, you should set a password and enable it via -a normal serial connection. Initial versions of MicroPython for ESP8266 -came with WebREPL automatically enabled on the boot and with the -ability to set a password via WiFi on the first connection, but as WebREPL -was becoming more widely known and popular, the initial setup has switched -to a wired connection for improved security:: - - import webrepl_setup - -Follow the on-screen instructions and prompts. To make any changes active, -you will need to reboot your device. - -To use WebREPL connect your computer to the ESP8266's access point -(MicroPython-xxxxxx, see the previous section about this). If you have -already reconfigured your ESP8266 to connect to a router then you can -skip this part. - -Once you are on the same network as the ESP8266 you click the "Connect" button -(if you are connecting via a router then you may need to change the IP address, -by default the IP address is correct when connected to the ESP8266's access -point). If the connection succeeds then you should see a password prompt. - -Once you type the password configured at the setup step above, press Enter once -more and you should get a prompt looking like ``>>>``. You can now start -typing Python commands! - -Using the REPL --------------- - -Once you have a prompt you can start experimenting! Anything you type at the -prompt will be executed after you press the Enter key. MicroPython will run -the code that you enter and print the result (if there is one). If there is an -error with the text that you enter then an error message is printed. - -Try typing the following at the prompt:: - - >>> print('hello esp8266!') - hello esp8266! - -Note that you shouldn't type the ``>>>`` arrows, they are there to indicate that -you should type the text after it at the prompt. And then the line following is -what the device should respond with. In the end, once you have entered the text -``print("hello esp8266!")`` and pressed the Enter key, the output on your screen -should look exactly like it does above. - -If you already know some python you can now try some basic commands here. For -example:: - - >>> 1 + 2 - 3 - >>> 1 / 2 - 0.5 - >>> 12**34 - 4922235242952026704037113243122008064 - -If your board has an LED attached to GPIO2 (the ESP-12 modules do) then you can -turn it on and off using the following code:: - - >>> import machine - >>> pin = machine.Pin(2, machine.Pin.OUT) - >>> pin.on() - >>> pin.off() - -Note that ``on`` method of a Pin might turn the LED off and ``off`` might -turn it on (or vice versa), depending on how the LED is wired on your board. -To resolve this, machine.Signal class is provided. - -Line editing -~~~~~~~~~~~~ - -You can edit the current line that you are entering using the left and right -arrow keys to move the cursor, as well as the delete and backspace keys. Also, -pressing Home or ctrl-A moves the cursor to the start of the line, and pressing -End or ctrl-E moves to the end of the line. - -Input history -~~~~~~~~~~~~~ - -The REPL remembers a certain number of previous lines of text that you entered -(up to 8 on the ESP8266). To recall previous lines use the up and down arrow -keys. - -Tab completion -~~~~~~~~~~~~~~ - -Pressing the Tab key will do an auto-completion of the current word that you are -entering. This can be very useful to find out functions and methods that a -module or object has. Try it out by typing "ma" and then pressing Tab. It -should complete to "machine" (assuming you imported machine in the above -example). Then type "." and press Tab again to see a list of all the functions -that the machine module has. - -Line continuation and auto-indent -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Certain things that you type will need "continuing", that is, will need more -lines of text to make a proper Python statement. In this case the prompt will -change to ``...`` and the cursor will auto-indent the correct amount so you can -start typing the next line straight away. Try this by defining the following -function:: - - >>> def toggle(p): - ... p.value(not p.value()) - ... - ... - ... - >>> - -In the above, you needed to press the Enter key three times in a row to finish -the compound statement (that's the three lines with just dots on them). The -other way to finish a compound statement is to press backspace to get to the -start of the line, then press the Enter key. (If you did something wrong and -want to escape the continuation mode then press ctrl-C; all lines will be -ignored.) - -The function you just defined allows you to toggle a pin. The pin object you -created earlier should still exist (recreate it if it doesn't) and you can -toggle the LED using:: - - >>> toggle(pin) - -Let's now toggle the LED in a loop (if you don't have an LED then you can just -print some text instead of calling toggle, to see the effect):: - - >>> import time - >>> while True: - ... toggle(pin) - ... time.sleep_ms(500) - ... - ... - ... - >>> - -This will toggle the LED at 1Hz (half a second on, half a second off). To stop -the toggling press ctrl-C, which will raise a KeyboardInterrupt exception and -break out of the loop. - -The time module provides some useful functions for making delays and doing -timing. Use tab completion to find out what they are and play around with them! - -Paste mode -~~~~~~~~~~ - -Pressing ctrl-E will enter a special paste mode. This allows you to copy and -paste a chunk of text into the REPL. If you press ctrl-E you will see the -paste-mode prompt:: - - paste mode; Ctrl-C to cancel, Ctrl-D to finish - === - -You can then paste (or type) your text in. Note that none of the special keys -or commands work in paste mode (eg Tab or backspace), they are just accepted -as-is. Press ctrl-D to finish entering the text and execute it. - -Other control commands -~~~~~~~~~~~~~~~~~~~~~~ - -There are four other control commands: - -* Ctrl-A on a blank line will enter raw REPL mode. This is like a permanent - paste mode, except that characters are not echoed back. - -* Ctrl-B on a blank like goes to normal REPL mode. - -* Ctrl-C cancels any input, or interrupts the currently running code. - -* Ctrl-D on a blank line will do a soft reset. - -Note that ctrl-A and ctrl-D do not work with WebREPL. diff --git a/docs/esp8266_index.rst b/docs/esp8266_index.rst deleted file mode 100644 index 519acecda5..0000000000 --- a/docs/esp8266_index.rst +++ /dev/null @@ -1,12 +0,0 @@ -MicroPython documentation and references -======================================== - -.. toctree:: - - esp8266/quickref.rst - esp8266/general.rst - esp8266/tutorial/index.rst - library/index.rst - reference/index.rst - genrst/index.rst - license.rst diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000000..a85772fdc9 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,54 @@ +Adafruit CircuitPython API Reference +==================================== + +Welcome to the API reference documentation for Adafruit CircuitPython. +This contains low-level API reference docs which may link out to separate +*"getting started"* guides. `Adafruit `_ has many +excellent tutorials available through the +`Adafruit Learning System `_. + +.. include:: ../README.rst + +.. _contents: + +Full Table of Contents +---------------------- + +.. toctree:: + :maxdepth: 3 + :caption: API and Usage + + ../shared-bindings/index.rst + supported_ports.rst + troubleshooting.rst + drivers.rst + +.. toctree:: + :maxdepth: 1 + :caption: Design and porting reference + + design_guide + porting + common_hal + +.. toctree:: + :maxdepth: 2 + :caption: MicroPython specific + + library/index.rst + +.. toctree:: + :maxdepth: 1 + :caption: About the project + + ../README + ../CONTRIBUTING + ../CODE_OF_CONDUCT + ../license.rst + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/library/array.rst b/docs/library/array.rst index d096c6ec48..dfaef0ff6c 100644 --- a/docs/library/array.rst +++ b/docs/library/array.rst @@ -1,10 +1,12 @@ :mod:`array` -- arrays of numeric data ====================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: array :synopsis: efficient arrays of numeric data -|see_cpython_module| :mod:`python:array`. +|see_cpython_module| :mod:`cpython:array`. Supported format codes: ``b``, ``B``, ``h``, ``H``, ``i``, ``I``, ``l``, ``L``, ``q``, ``Q``, ``f``, ``d`` (the latter 2 depending on the diff --git a/docs/library/btree.rst b/docs/library/btree.rst index 8fac67e8d4..303a936ad9 100644 --- a/docs/library/btree.rst +++ b/docs/library/btree.rst @@ -1,6 +1,8 @@ :mod:`btree` -- simple BTree database ===================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: btree :synopsis: simple BTree database @@ -78,7 +80,7 @@ Functions .. function:: open(stream, \*, flags=0, pagesize=0, cachesize=0, minkeypage=0) - Open a database from a random-access `stream` (like an open file). All + Open a database from a random-access ``stream`` (like an open file). All other parameters are optional and keyword-only, and allow to tweak advanced parameters of the database operation (most users will not need them): diff --git a/docs/library/builtins.rst b/docs/library/builtins.rst index 365248dc76..b45b6fe380 100644 --- a/docs/library/builtins.rst +++ b/docs/library/builtins.rst @@ -1,6 +1,12 @@ Builtin functions and exceptions ================================ +.. warning:: + + These builtins are inherited from MicroPython and may not work in CircuitPython + as documented or at all! If work differently from CPython, then their behavior + may change. + All builtin functions and exceptions are described here. They are also available via ``builtins`` module. @@ -21,7 +27,7 @@ Functions and types .. class:: bytes() - |see_cpython| `python:bytes`. + |see_cpython| `bytes`. .. function:: callable() @@ -176,7 +182,7 @@ Exceptions .. exception:: OSError - |see_cpython| `python:OSError`. MicroPython doesn't implement ``errno`` + |see_cpython| `OSError`. MicroPython doesn't implement ``errno`` attribute, instead use the standard way to access exception arguments: ``exc.args[0]``. @@ -188,11 +194,11 @@ Exceptions .. exception:: SystemExit - |see_cpython| `python:SystemExit`. + |see_cpython| :py:class:`python:SystemExit`. .. exception:: TypeError - |see_cpython| `python:TypeError`. + |see_cpython| :py:class:`python:TypeError`. .. exception:: ValueError diff --git a/docs/library/cmath.rst b/docs/library/cmath.rst deleted file mode 100644 index 59e4ec1722..0000000000 --- a/docs/library/cmath.rst +++ /dev/null @@ -1,63 +0,0 @@ -:mod:`cmath` -- mathematical functions for complex numbers -========================================================== - -.. module:: cmath - :synopsis: mathematical functions for complex numbers - -|see_cpython_module| :mod:`python:cmath`. - -The ``cmath`` module provides some basic mathematical functions for -working with complex numbers. - -Availability: not available on WiPy and ESP8266. Floating point support -required for this module. - -Functions ---------- - -.. function:: cos(z) - - Return the cosine of ``z``. - -.. function:: exp(z) - - Return the exponential of ``z``. - -.. function:: log(z) - - Return the natural logarithm of ``z``. The branch cut is along the negative real axis. - -.. function:: log10(z) - - Return the base-10 logarithm of ``z``. The branch cut is along the negative real axis. - -.. function:: phase(z) - - Returns the phase of the number ``z``, in the range (-pi, +pi]. - -.. function:: polar(z) - - Returns, as a tuple, the polar form of ``z``. - -.. function:: rect(r, phi) - - Returns the complex number with modulus ``r`` and phase ``phi``. - -.. function:: sin(z) - - Return the sine of ``z``. - -.. function:: sqrt(z) - - Return the square-root of ``z``. - -Constants ---------- - -.. data:: e - - base of the natural logarithm - -.. data:: pi - - the ratio of a circle's circumference to its diameter diff --git a/docs/library/esp.rst b/docs/library/esp.rst index 121a80d42e..125aaa890f 100644 --- a/docs/library/esp.rst +++ b/docs/library/esp.rst @@ -1,6 +1,8 @@ :mod:`esp` --- functions related to the ESP8266 =============================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: esp :synopsis: functions related to the ESP8266 diff --git a/docs/library/framebuf.rst b/docs/library/framebuf.rst index 74c9f85649..80961b8724 100644 --- a/docs/library/framebuf.rst +++ b/docs/library/framebuf.rst @@ -1,6 +1,8 @@ :mod:`framebuf` --- Frame buffer manipulation ============================================= +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: framebuf :synopsis: Frame buffer manipulation diff --git a/docs/library/gc.rst b/docs/library/gc.rst index c823aed3e6..01bd925e99 100644 --- a/docs/library/gc.rst +++ b/docs/library/gc.rst @@ -1,10 +1,12 @@ :mod:`gc` -- control the garbage collector ========================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: gc :synopsis: control the garbage collector -|see_cpython_module| :mod:`python:gc`. +|see_cpython_module| :mod:`cpython:gc`. Functions --------- diff --git a/docs/library/index.rst b/docs/library/index.rst index bf72c5ffa8..647a25c8a5 100644 --- a/docs/library/index.rst +++ b/docs/library/index.rst @@ -5,159 +5,34 @@ MicroPython libraries .. warning:: - Important summary of this section + These modules are inherited from MicroPython and may not work in CircuitPython + as documented or at all! If they do work, they may change at any time. - * MicroPython implements a subset of Python functionality for each module. - * To ease extensibility, MicroPython versions of standard Python modules - usually have ``u`` (micro) prefix. - * Any particular MicroPython variant or port may miss any feature/function - described in this general documentation, due to resource constraints. - - -This chapter describes modules (function and class libraries) which are built -into MicroPython and CircuitPython. There are a few categories of modules: - -* Modules which implement a subset of standard Python functionality and are not - intended to be extended by the user. -* Modules which implement a subset of Python functionality, with a provision - for extension by the user (via Python code). -* Modules which implement MicroPython extensions to the Python standard libraries. -* Modules specific to a particular port and thus not portable. - -Note about the availability of modules and their contents: This documentation -in general aspires to describe all modules and functions/classes which are -implemented in MicroPython. However, MicroPython is highly configurable, and -each port to a particular board/embedded system makes available only a subset -of MicroPython libraries. For officially supported ports, there is an effort -to either filter out non-applicable items, or mark individual descriptions -with "Availability:" clauses describing which ports provide a given feature. -With that in mind, please still be warned that some functions/classes -in a module (or even the entire module) described in this documentation may be -unavailable in a particular build of MicroPython on a particular board. The -best place to find general information of the availability/non-availability -of a particular feature is the "General Information" section which contains -information pertaining to a specific port. - -Beyond the built-in libraries described in this documentation, many more -modules from the Python standard library, as well as further MicroPython -extensions to it, can be found in `micropython-lib`. Python standard libraries and micro-libraries --------------------------------------------- -The following standard Python libraries have been "micro-ified" to fit in with -the philosophy of MicroPython. They provide the core functionality of that -module and are intended to be a drop-in replacement for the standard Python -library. Some modules below use a standard Python name, but prefixed with "u", -e.g. ``ujson`` instead of ``json``. This is to signify that such a module is -micro-library, i.e. implements only a subset of CPython module functionality. -By naming them differently, a user has a choice to write a Python-level module -to extend functionality for better compatibility with CPython (indeed, this is -what done by the `micropython-lib` project mentioned above). -On some embedded platforms, where it may be cumbersome to add Python-level -wrapper modules to achieve naming compatibility with CPython, micro-modules -are available both by their u-name, and also by their non-u-name. The -non-u-name can be overridden by a file of that name in your package path. -For example, ``import json`` will first search for a file ``json.py`` or -directory ``json`` and load that package if it is found. If nothing is found, -it will fallback to loading the built-in ``ujson`` module. +.. toctree:: + :maxdepth: 1 -.. only:: port_unix - - .. toctree:: - :maxdepth: 1 - - builtins.rst - array.rst - cmath.rst - gc.rst - math.rst - sys.rst - ubinascii.rst - ucollections.rst - uerrno.rst - uhashlib.rst - uheapq.rst - uio.rst - ujson.rst - uos.rst - ure.rst - uselect.rst - usocket.rst - ustruct.rst - utime.rst - uzlib.rst - -.. only:: port_pyboard - - .. toctree:: - :maxdepth: 1 - - builtins.rst - array.rst - cmath.rst - gc.rst - math.rst - sys.rst - ubinascii.rst - ucollections.rst - uerrno.rst - uhashlib.rst - uheapq.rst - uio.rst - ujson.rst - uos.rst - ure.rst - uselect.rst - usocket.rst - ustruct.rst - utime.rst - uzlib.rst - -.. only:: port_wipy - - .. toctree:: - :maxdepth: 1 - - builtins.rst - array.rst - gc.rst - sys.rst - ubinascii.rst - ujson.rst - uos.rst - ure.rst - uselect.rst - usocket.rst - ussl.rst - utime.rst - -.. only:: port_esp8266 - - .. toctree:: - :maxdepth: 1 - - builtins.rst - array.rst - gc.rst - math.rst - sys.rst - ubinascii.rst - ucollections.rst - uerrno.rst - uhashlib.rst - uheapq.rst - uio.rst - ujson.rst - uos.rst - ure.rst - uselect.rst - usocket.rst - ussl.rst - ustruct.rst - utime.rst - uzlib.rst + builtins.rst + array.rst + gc.rst + sys.rst + ubinascii.rst + ucollections.rst + uerrno.rst + uhashlib.rst + uheapq.rst + uio.rst + ujson.rst + ure.rst + uselect.rst + usocket.rst + ussl.rst + ustruct.rst + uzlib.rst MicroPython-specific libraries @@ -171,46 +46,16 @@ the following libraries. btree.rst framebuf.rst - machine.rst micropython.rst network.rst uctypes.rst +Libraries specific to the ESP8266 +--------------------------------- -.. only:: port_pyboard +The following libraries are specific to the ESP8266. - Libraries specific to the pyboard - --------------------------------- +.. toctree:: + :maxdepth: 2 - The following libraries are specific to the pyboard. - - .. toctree:: - :maxdepth: 2 - - pyb.rst - lcd160cr.rst - -.. only:: port_wipy - - Libraries specific to the WiPy - --------------------------------- - - The following libraries are specific to the WiPy. - - .. toctree:: - :maxdepth: 2 - - wipy.rst - - -.. only:: port_esp8266 - - Libraries specific to the ESP8266 - --------------------------------- - - The following libraries are specific to the ESP8266. - - .. toctree:: - :maxdepth: 2 - - esp.rst + esp.rst diff --git a/docs/library/lcd160cr.rst b/docs/library/lcd160cr.rst deleted file mode 100644 index 567994640b..0000000000 --- a/docs/library/lcd160cr.rst +++ /dev/null @@ -1,394 +0,0 @@ -:mod:`lcd160cr` --- control of LCD160CR display -=============================================== - -.. module:: lcd160cr - :synopsis: control of LCD160CR display - -This module provides control of the MicroPython LCD160CR display. - -.. image:: http://micropython.org/resources/LCD160CRv10-persp.jpg - :alt: LCD160CRv1.0 picture - :width: 640px - -Further resources are available via the following links: - -* `LCD160CRv1.0 reference manual `_ (100KiB PDF) -* `LCD160CRv1.0 schematics `_ (1.6MiB PDF) - -class LCD160CR --------------- - -The LCD160CR class provides an interface to the display. Create an -instance of this class and use its methods to draw to the LCD and get -the status of the touch panel. - -For example:: - - import lcd160cr - - lcd = lcd160cr.LCD160CR('X') - lcd.set_orient(lcd160cr.PORTRAIT) - lcd.set_pos(0, 0) - lcd.set_text_color(lcd.rgb(255, 0, 0), lcd.rgb(0, 0, 0)) - lcd.set_font(1) - lcd.write('Hello MicroPython!') - print('touch:', lcd.get_touch()) - -Constructors ------------- - -.. class:: LCD160CR(connect=None, \*, pwr=None, i2c=None, spi=None, i2c_addr=98) - - Construct an LCD160CR object. The parameters are: - - - *connect* is a string specifying the physical connection of the LCD - display to the board; valid values are "X", "Y", "XY", "YX". - Use "X" when the display is connected to a pyboard in the X-skin - position, and "Y" when connected in the Y-skin position. "XY" - and "YX" are used when the display is connected to the right or - left side of the pyboard, respectively. - - *pwr* is a Pin object connected to the LCD's power/enabled pin. - - *i2c* is an I2C object connected to the LCD's I2C interface. - - *spi* is an SPI object connected to the LCD's SPI interface. - - *i2c_addr* is the I2C address of the display. - - One must specify either a valid *connect* or all of *pwr*, *i2c* and *spi*. - If a valid *connect* is given then any of *pwr*, *i2c* or *spi* which are - not passed as parameters (i.e. they are ``None``) will be created based on the - value of *connect*. This allows to override the default interface to the - display if needed. - - The default values are: - - - "X" is for the X-skin and uses: - ``pwr=Pin("X4")``, ``i2c=I2C("X")``, ``spi=SPI("X")`` - - "Y" is for the Y-skin and uses: - ``pwr=Pin("Y4")``, ``i2c=I2C("Y")``, ``spi=SPI("Y")`` - - "XY" is for the right-side and uses: - ``pwr=Pin("X4")``, ``i2c=I2C("Y")``, ``spi=SPI("X")`` - - "YX" is for the left-side and uses: - ``pwr=Pin("Y4")``, ``i2c=I2C("X")``, ``spi=SPI("Y")`` - - See `this image `_ - for how the display can be connected to the pyboard. - -Static methods --------------- - -.. staticmethod:: LCD160CR.rgb(r, g, b) - - Return a 16-bit integer representing the given rgb color values. The - 16-bit value can be used to set the font color (see - :meth:`LCD160CR.set_text_color`) pen color (see :meth:`LCD160CR.set_pen`) - and draw individual pixels. - -.. staticmethod:: LCD160CR.clip_line(data, w, h): - - Clip the given line data. This is for internal use. - -Instance members ----------------- - -The following instance members are publicly accessible. - -.. data:: LCD160CR.w -.. data:: LCD160CR.h - - The width and height of the display, respectively, in pixels. These - members are updated when calling :meth:`LCD160CR.set_orient` and should - be considered read-only. - -Setup commands --------------- - -.. method:: LCD160CR.set_power(on) - - Turn the display on or off, depending on the given value of *on*: 0 or ``False`` - will turn the display off, and 1 or ``True`` will turn it on. - -.. method:: LCD160CR.set_orient(orient) - - Set the orientation of the display. The *orient* parameter can be one - of `PORTRAIT`, `LANDSCAPE`, `PORTRAIT_UPSIDEDOWN`, `LANDSCAPE_UPSIDEDOWN`. - -.. method:: LCD160CR.set_brightness(value) - - Set the brightness of the display, between 0 and 31. - -.. method:: LCD160CR.set_i2c_addr(addr) - - Set the I2C address of the display. The *addr* value must have the - lower 2 bits cleared. - -.. method:: LCD160CR.set_uart_baudrate(baudrate) - - Set the baudrate of the UART interface. - -.. method:: LCD160CR.set_startup_deco(value) - - Set the start-up decoration of the display. The *value* parameter can be a - logical or of `STARTUP_DECO_NONE`, `STARTUP_DECO_MLOGO`, `STARTUP_DECO_INFO`. - -.. method:: LCD160CR.save_to_flash() - - Save the following parameters to flash so they persist on restart and power up: - initial decoration, orientation, brightness, UART baud rate, I2C address. - -Pixel access methods --------------------- - -The following methods manipulate individual pixels on the display. - -.. method:: LCD160CR.set_pixel(x, y, c) - - Set the specified pixel to the given color. The color should be a 16-bit - integer and can be created by :meth:`LCD160CR.rgb`. - -.. method:: LCD160CR.get_pixel(x, y) - - Get the 16-bit value of the specified pixel. - -.. method:: LCD160CR.get_line(x, y, buf) - - Low-level method to get a line of pixels into the given buffer. - To read *n* pixels *buf* should be *2*n+1* bytes in length. The first byte - is a dummy byte and should be ignored, and subsequent bytes represent the - pixels in the line starting at coordinate *(x, y)*. - -.. method:: LCD160CR.screen_dump(buf, x=0, y=0, w=None, h=None) - - Dump the contents of the screen to the given buffer. The parameters *x* and *y* - specify the starting coordinate, and *w* and *h* the size of the region. If *w* - or *h* are ``None`` then they will take on their maximum values, set by the size - of the screen minus the given *x* and *y* values. *buf* should be large enough - to hold ``2*w*h`` bytes. If it's smaller then only the initial horizontal lines - will be stored. - -.. method:: LCD160CR.screen_load(buf) - - Load the entire screen from the given buffer. - -Drawing text ------------- - -To draw text one sets the position, color and font, and then uses -`write` to draw the text. - -.. method:: LCD160CR.set_pos(x, y) - - Set the position for text output using :meth:`LCD160CR.write`. The position - is the upper-left corner of the text. - -.. method:: LCD160CR.set_text_color(fg, bg) - - Set the foreground and background color of the text. - -.. method:: LCD160CR.set_font(font, scale=0, bold=0, trans=0, scroll=0) - - Set the font for the text. Subsequent calls to `write` will use the newly - configured font. The parameters are: - - - *font* is the font family to use, valid values are 0, 1, 2, 3. - - *scale* is a scaling value for each character pixel, where the pixels - are drawn as a square with side length equal to *scale + 1*. The value - can be between 0 and 63. - - *bold* controls the number of pixels to overdraw each character pixel, - making a bold effect. The lower 2 bits of *bold* are the number of - pixels to overdraw in the horizontal direction, and the next 2 bits are - for the vertical direction. For example, a *bold* value of 5 will - overdraw 1 pixel in both the horizontal and vertical directions. - - *trans* can be either 0 or 1 and if set to 1 the characters will be - drawn with a transparent background. - - *scroll* can be either 0 or 1 and if set to 1 the display will do a - soft scroll if the text moves to the next line. - -.. method:: LCD160CR.write(s) - - Write text to the display, using the current position, color and font. - As text is written the position is automatically incremented. The - display supports basic VT100 control codes such as newline and backspace. - -Drawing primitive shapes ------------------------- - -Primitive drawing commands use a foreground and background color set by the -`set_pen` method. - -.. method:: LCD160CR.set_pen(line, fill) - - Set the line and fill color for primitive shapes. - -.. method:: LCD160CR.erase() - - Erase the entire display to the pen fill color. - -.. method:: LCD160CR.dot(x, y) - - Draw a single pixel at the given location using the pen line color. - -.. method:: LCD160CR.rect(x, y, w, h) -.. method:: LCD160CR.rect_outline(x, y, w, h) -.. method:: LCD160CR.rect_interior(x, y, w, h) - - Draw a rectangle at the given location and size using the pen line - color for the outline, and the pen fill color for the interior. - The `rect` method draws the outline and interior, while the other methods - just draw one or the other. - -.. method:: LCD160CR.line(x1, y1, x2, y2) - - Draw a line between the given coordinates using the pen line color. - -.. method:: LCD160CR.dot_no_clip(x, y) -.. method:: LCD160CR.rect_no_clip(x, y, w, h) -.. method:: LCD160CR.rect_outline_no_clip(x, y, w, h) -.. method:: LCD160CR.rect_interior_no_clip(x, y, w, h) -.. method:: LCD160CR.line_no_clip(x1, y1, x2, y2) - - These methods are as above but don't do any clipping on the input - coordinates. They are faster than the clipping versions and can be - used when you know that the coordinates are within the display. - -.. method:: LCD160CR.poly_dot(data) - - Draw a sequence of dots using the pen line color. - The *data* should be a buffer of bytes, with each successive pair of - bytes corresponding to coordinate pairs (x, y). - -.. method:: LCD160CR.poly_line(data) - - Similar to :meth:`LCD160CR.poly_dot` but draws lines between the dots. - -Touch screen methods --------------------- - -.. method:: LCD160CR.touch_config(calib=False, save=False, irq=None) - - Configure the touch panel: - - - If *calib* is ``True`` then the call will trigger a touch calibration of - the resistive touch sensor. This requires the user to touch various - parts of the screen. - - If *save* is ``True`` then the touch parameters will be saved to NVRAM - to persist across reset/power up. - - If *irq* is ``True`` then the display will be configured to pull the IRQ - line low when a touch force is detected. If *irq* is ``False`` then this - feature is disabled. If *irq* is ``None`` (the default value) then no - change is made to this setting. - -.. method:: LCD160CR.is_touched() - - Returns a boolean: ``True`` if there is currently a touch force on the screen, - `False` otherwise. - -.. method:: LCD160CR.get_touch() - - Returns a 3-tuple of: *(active, x, y)*. If there is currently a touch force - on the screen then *active* is 1, otherwise it is 0. The *x* and *y* values - indicate the position of the current or most recent touch. - -Advanced commands ------------------ - -.. method:: LCD160CR.set_spi_win(x, y, w, h) - - Set the window that SPI data is written to. - -.. method:: LCD160CR.fast_spi(flush=True) - - Ready the display to accept RGB pixel data on the SPI bus, resetting the location - of the first byte to go to the top-left corner of the window set by - :meth:`LCD160CR.set_spi_win`. - The method returns an SPI object which can be used to write the pixel data. - - Pixels should be sent as 16-bit RGB values in the 5-6-5 format. The destination - counter will increase as data is sent, and data can be sent in arbitrary sized - chunks. Once the destination counter reaches the end of the window specified by - :meth:`LCD160CR.set_spi_win` it will wrap around to the top-left corner of that window. - -.. method:: LCD160CR.show_framebuf(buf) - - Show the given buffer on the display. *buf* should be an array of bytes containing - the 16-bit RGB values for the pixels, and they will be written to the area - specified by :meth:`LCD160CR.set_spi_win`, starting from the top-left corner. - - The `framebuf `_ module can be used to construct frame buffers - and provides drawing primitives. Using a frame buffer will improve - performance of animations when compared to drawing directly to the screen. - -.. method:: LCD160CR.set_scroll(on) - - Turn scrolling on or off. This controls globally whether any window regions will - scroll. - -.. method:: LCD160CR.set_scroll_win(win, x=-1, y=0, w=0, h=0, vec=0, pat=0, fill=0x07e0, color=0) - - Configure a window region for scrolling: - - - *win* is the window id to configure. There are 0..7 standard windows for - general purpose use. Window 8 is the text scroll window (the ticker). - - *x*, *y*, *w*, *h* specify the location of the window in the display. - - *vec* specifies the direction and speed of scroll: it is a 16-bit value - of the form ``0bF.ddSSSSSSSSSSSS``. *dd* is 0, 1, 2, 3 for +x, +y, -x, - -y scrolling. *F* sets the speed format, with 0 meaning that the window - is shifted *S % 256* pixel every frame, and 1 meaning that the window - is shifted 1 pixel every *S* frames. - - *pat* is a 16-bit pattern mask for the background. - - *fill* is the fill color. - - *color* is the extra color, either of the text or pattern foreground. - -.. method:: LCD160CR.set_scroll_win_param(win, param, value) - - Set a single parameter of a scrolling window region: - - - *win* is the window id, 0..8. - - *param* is the parameter number to configure, 0..7, and corresponds - to the parameters in the `set_scroll_win` method. - - *value* is the value to set. - -.. method:: LCD160CR.set_scroll_buf(s) - - Set the string for scrolling in window 8. The parameter *s* must be a string - with length 32 or less. - -.. method:: LCD160CR.jpeg(buf) - - Display a JPEG. *buf* should contain the entire JPEG data. JPEG data should - not include EXIF information. The following encodings are supported: Baseline - DCT, Huffman coding, 8 bits per sample, 3 color components, YCbCr4:2:2. - The origin of the JPEG is set by :meth:`LCD160CR.set_pos`. - -.. method:: LCD160CR.jpeg_start(total_len) -.. method:: LCD160CR.jpeg_data(buf) - - Display a JPEG with the data split across multiple buffers. There must be - a single call to `jpeg_start` to begin with, specifying the total number of - bytes in the JPEG. Then this number of bytes must be transferred to the - display using one or more calls to the `jpeg_data` command. - -.. method:: LCD160CR.feed_wdt() - - The first call to this method will start the display's internal watchdog - timer. Subsequent calls will feed the watchdog. The timeout is roughly 30 - seconds. - -.. method:: LCD160CR.reset() - - Reset the display. - -Constants ---------- - -.. data:: lcd160cr.PORTRAIT - lcd160cr.LANDSCAPE - lcd160cr.PORTRAIT_UPSIDEDOWN - lcd160cr.LANDSCAPE_UPSIDEDOWN - - Orientations of the display, used by :meth:`LCD160CR.set_orient`. - -.. data:: lcd160cr.STARTUP_DECO_NONE - lcd160cr.STARTUP_DECO_MLOGO - lcd160cr.STARTUP_DECO_INFO - - Types of start-up decoration, can be OR'ed together, used by - :meth:`LCD160CR.set_startup_deco`. diff --git a/docs/library/machine.ADC.rst b/docs/library/machine.ADC.rst deleted file mode 100644 index 4c7a04d74f..0000000000 --- a/docs/library/machine.ADC.rst +++ /dev/null @@ -1,74 +0,0 @@ -.. currentmodule:: machine -.. _machine.ADC: - -class ADC -- analog to digital conversion -========================================= - -Usage:: - - import machine - - adc = machine.ADC() # create an ADC object - apin = adc.channel(pin='GP3') # create an analog pin on GP3 - val = apin() # read an analog value - -Constructors ------------- - -.. class:: ADC(id=0, \*, bits=12) - - Create an ADC object associated with the given pin. - This allows you to then read analog values on that pin. - For more info check the `pinout and alternate functions - table. `_ - - .. warning:: - - ADC pin input range is 0-1.4V (being 1.8V the absolute maximum that it - can withstand). When GP2, GP3, GP4 or GP5 are remapped to the - ADC block, 1.8 V is the maximum. If these pins are used in digital mode, - then the maximum allowed input is 3.6V. - -Methods -------- - -.. method:: ADC.channel(id, \*, pin) - - Create an analog pin. If only channel ID is given, the correct pin will - be selected. Alternatively, only the pin can be passed and the correct - channel will be selected. Examples:: - - # all of these are equivalent and enable ADC channel 1 on GP3 - apin = adc.channel(1) - apin = adc.channel(pin='GP3') - apin = adc.channel(id=1, pin='GP3') - -.. method:: ADC.init() - - Enable the ADC block. - -.. method:: ADC.deinit() - - Disable the ADC block. - -class ADCChannel --- read analog values from internal or external sources -========================================================================= - -ADC channels can be connected to internal points of the MCU or to GPIO pins. -ADC channels are created using the ADC.channel method. - -.. method:: adcchannel() - - Fast method to read the channel value. - -.. method:: adcchannel.value() - - Read the channel value. - -.. method:: adcchannel.init() - - Re-init (and effectively enable) the ADC channel. - -.. method:: adcchannel.deinit() - - Disable the ADC channel. diff --git a/docs/library/machine.I2C.rst b/docs/library/machine.I2C.rst deleted file mode 100644 index a69c58999f..0000000000 --- a/docs/library/machine.I2C.rst +++ /dev/null @@ -1,172 +0,0 @@ -.. currentmodule:: machine -.. _machine.I2C: - -class I2C -- a two-wire serial protocol -======================================= - -I2C is a two-wire protocol for communicating between devices. At the physical -level it consists of 2 wires: SCL and SDA, the clock and data lines respectively. - -I2C objects are created attached to a specific bus. They can be initialised -when created, or initialised later on. - -Printing the I2C object gives you information about its configuration. - -Example usage:: - - from machine import I2C - - i2c = I2C(freq=400000) # create I2C peripheral at frequency of 400kHz - # depending on the port, extra parameters may be required - # to select the peripheral and/or pins to use - - i2c.scan() # scan for slaves, returning a list of 7-bit addresses - - i2c.writeto(42, b'123') # write 3 bytes to slave with 7-bit address 42 - i2c.readfrom(42, 4) # read 4 bytes from slave with 7-bit address 42 - - i2c.readfrom_mem(42, 8, 3) # read 3 bytes from memory of slave 42, - # starting at memory-address 8 in the slave - i2c.writeto_mem(42, 2, b'\x10') # write 1 byte to memory of slave 42 - # starting at address 2 in the slave - -Constructors ------------- - -.. class:: I2C(id=-1, \*, scl, sda, freq=400000) - - Construct and return a new I2C object using the following parameters: - - - *id* identifies a particular I2C peripheral. The default - value of -1 selects a software implementation of I2C which can - work (in most cases) with arbitrary pins for SCL and SDA. - If *id* is -1 then *scl* and *sda* must be specified. Other - allowed values for *id* depend on the particular port/board, - and specifying *scl* and *sda* may or may not be required or - allowed in this case. - - *scl* should be a pin object specifying the pin to use for SCL. - - *sda* should be a pin object specifying the pin to use for SDA. - - *freq* should be an integer which sets the maximum frequency - for SCL. - -General Methods ---------------- - -.. method:: I2C.init(scl, sda, \*, freq=400000) - - Initialise the I2C bus with the given arguments: - - - *scl* is a pin object for the SCL line - - *sda* is a pin object for the SDA line - - *freq* is the SCL clock rate - -.. method:: I2C.deinit() - - Turn off the I2C bus. - - Availability: WiPy. - -.. method:: I2C.scan() - - Scan all I2C addresses between 0x08 and 0x77 inclusive and return a list of - those that respond. A device responds if it pulls the SDA line low after - its address (including a write bit) is sent on the bus. - -Primitive I2C operations ------------------------- - -The following methods implement the primitive I2C master bus operations and can -be combined to make any I2C transaction. They are provided if you need more -control over the bus, otherwise the standard methods (see below) can be used. - -.. method:: I2C.start() - - Generate a START condition on the bus (SDA transitions to low while SCL is high). - - Availability: ESP8266. - -.. method:: I2C.stop() - - Generate a STOP condition on the bus (SDA transitions to high while SCL is high). - - Availability: ESP8266. - -.. method:: I2C.readinto(buf, nack=True) - - Reads bytes from the bus and stores them into *buf*. The number of bytes - read is the length of *buf*. An ACK will be sent on the bus after - receiving all but the last byte. After the last byte is received, if *nack* - is true then a NACK will be sent, otherwise an ACK will be sent (and in this - case the slave assumes more bytes are going to be read in a later call). - - Availability: ESP8266. - -.. method:: I2C.write(buf) - - Write the bytes from *buf* to the bus. Checks that an ACK is received - after each byte and stops transmitting the remaining bytes if a NACK is - received. The function returns the number of ACKs that were received. - - Availability: ESP8266. - -Standard bus operations ------------------------ - -The following methods implement the standard I2C master read and write -operations that target a given slave device. - -.. method:: I2C.readfrom(addr, nbytes, stop=True) - - Read *nbytes* from the slave specified by *addr*. - If *stop* is true then a STOP condition is generated at the end of the transfer. - Returns a `bytes` object with the data read. - -.. method:: I2C.readfrom_into(addr, buf, stop=True) - - Read into *buf* from the slave specified by *addr*. - The number of bytes read will be the length of *buf*. - If *stop* is true then a STOP condition is generated at the end of the transfer. - - The method returns ``None``. - -.. method:: I2C.writeto(addr, buf, stop=True) - - Write the bytes from *buf* to the slave specified by *addr*. If a - NACK is received following the write of a byte from *buf* then the - remaining bytes are not sent. If *stop* is true then a STOP condition is - generated at the end of the transfer, even if a NACK is received. - The function returns the number of ACKs that were received. - -Memory operations ------------------ - -Some I2C devices act as a memory device (or set of registers) that can be read -from and written to. In this case there are two addresses associated with an -I2C transaction: the slave address and the memory address. The following -methods are convenience functions to communicate with such devices. - -.. method:: I2C.readfrom_mem(addr, memaddr, nbytes, \*, addrsize=8) - - Read *nbytes* from the slave specified by *addr* starting from the memory - address specified by *memaddr*. - The argument *addrsize* specifies the address size in bits. - Returns a `bytes` object with the data read. - -.. method:: I2C.readfrom_mem_into(addr, memaddr, buf, \*, addrsize=8) - - Read into *buf* from the slave specified by *addr* starting from the - memory address specified by *memaddr*. The number of bytes read is the - length of *buf*. - The argument *addrsize* specifies the address size in bits (on ESP8266 - this argument is not recognised and the address size is always 8 bits). - - The method returns ``None``. - -.. method:: I2C.writeto_mem(addr, memaddr, buf, \*, addrsize=8) - - Write *buf* to the slave specified by *addr* starting from the - memory address specified by *memaddr*. - The argument *addrsize* specifies the address size in bits (on ESP8266 - this argument is not recognised and the address size is always 8 bits). - - The method returns ``None``. diff --git a/docs/library/machine.Pin.rst b/docs/library/machine.Pin.rst deleted file mode 100644 index 05ceb4ad33..0000000000 --- a/docs/library/machine.Pin.rst +++ /dev/null @@ -1,248 +0,0 @@ -.. currentmodule:: machine -.. _machine.Pin: - -class Pin -- control I/O pins -============================= - -A pin object is used to control I/O pins (also known as GPIO - general-purpose -input/output). Pin objects are commonly associated with a physical pin that can -drive an output voltage and read input voltages. The pin class has methods to set the mode of -the pin (IN, OUT, etc) and methods to get and set the digital logic level. -For analog control of a pin, see the :class:`ADC` class. - -A pin object is constructed by using an identifier which unambiguously -specifies a certain I/O pin. The allowed forms of the identifier and the -physical pin that the identifier maps to are port-specific. Possibilities -for the identifier are an integer, a string or a tuple with port and pin -number. - -Usage Model:: - - from machine import Pin - - # create an output pin on pin #0 - p0 = Pin(0, Pin.OUT) - - # set the value low then high - p0.value(0) - p0.value(1) - - # create an input pin on pin #2, with a pull up resistor - p2 = Pin(2, Pin.IN, Pin.PULL_UP) - - # read and print the pin value - print(p2.value()) - - # reconfigure pin #0 in input mode - p0.mode(p0.IN) - - # configure an irq callback - p0.irq(lambda p:print(p)) - -Constructors ------------- - -.. class:: Pin(id, mode=-1, pull=-1, \*, value, drive, alt) - - Access the pin peripheral (GPIO pin) associated with the given ``id``. If - additional arguments are given in the constructor then they are used to initialise - the pin. Any settings that are not specified will remain in their previous state. - - The arguments are: - - - ``id`` is mandatory and can be an arbitrary object. Among possible value - types are: int (an internal Pin identifier), str (a Pin name), and tuple - (pair of [port, pin]). - - - ``mode`` specifies the pin mode, which can be one of: - - - ``Pin.IN`` - Pin is configured for input. If viewed as an output the pin - is in high-impedance state. - - - ``Pin.OUT`` - Pin is configured for (normal) output. - - - ``Pin.OPEN_DRAIN`` - Pin is configured for open-drain output. Open-drain - output works in the following way: if the output value is set to 0 the pin - is active at a low level; if the output value is 1 the pin is in a high-impedance - state. Not all ports implement this mode, or some might only on certain pins. - - - ``Pin.ALT`` - Pin is configured to perform an alternative function, which is - port specific. For a pin configured in such a way any other Pin methods - (except :meth:`Pin.init`) are not applicable (calling them will lead to undefined, - or a hardware-specific, result). Not all ports implement this mode. - - - ``Pin.ALT_OPEN_DRAIN`` - The Same as ``Pin.ALT``, but the pin is configured as - open-drain. Not all ports implement this mode. - - - ``pull`` specifies if the pin has a (weak) pull resistor attached, and can be - one of: - - - ``None`` - No pull up or down resistor. - - ``Pin.PULL_UP`` - Pull up resistor enabled. - - ``Pin.PULL_DOWN`` - Pull down resistor enabled. - - - ``value`` is valid only for Pin.OUT and Pin.OPEN_DRAIN modes and specifies initial - output pin value if given, otherwise the state of the pin peripheral remains - unchanged. - - - ``drive`` specifies the output power of the pin and can be one of: ``Pin.LOW_POWER``, - ``Pin.MED_POWER`` or ``Pin.HIGH_POWER``. The actual current driving capabilities - are port dependent. Not all ports implement this argument. - - - ``alt`` specifies an alternate function for the pin and the values it can take are - port dependent. This argument is valid only for ``Pin.ALT`` and ``Pin.ALT_OPEN_DRAIN`` - modes. It may be used when a pin supports more than one alternate function. If only - one pin alternate function is supported the this argument is not required. Not all - ports implement this argument. - - As specified above, the Pin class allows to set an alternate function for a particular - pin, but it does not specify any further operations on such a pin. Pins configured in - alternate-function mode are usually not used as GPIO but are instead driven by other - hardware peripherals. The only operation supported on such a pin is re-initialising, - by calling the constructor or :meth:`Pin.init` method. If a pin that is configured in - alternate-function mode is re-initialised with ``Pin.IN``, ``Pin.OUT``, or - ``Pin.OPEN_DRAIN``, the alternate function will be removed from the pin. - -Methods -------- - -.. method:: Pin.init(mode=-1, pull=-1, \*, value, drive, alt) - - Re-initialise the pin using the given parameters. Only those arguments that - are specified will be set. The rest of the pin peripheral state will remain - unchanged. See the constructor documentation for details of the arguments. - - Returns ``None``. - -.. method:: Pin.value([x]) - - This method allows to set and get the value of the pin, depending on whether - the argument ``x`` is supplied or not. - - If the argument is omitted then this method gets the digital logic level of - the pin, returning 0 or 1 corresponding to low and high voltage signals - respectively. The behaviour of this method depends on the mode of the pin: - - - ``Pin.IN`` - The method returns the actual input value currently present - on the pin. - - ``Pin.OUT`` - The behaviour and return value of the method is undefined. - - ``Pin.OPEN_DRAIN`` - If the pin is in state '0' then the behaviour and - return value of the method is undefined. Otherwise, if the pin is in - state '1', the method returns the actual input value currently present - on the pin. - - If the argument is supplied then this method sets the digital logic level of - the pin. The argument ``x`` can be anything that converts to a boolean. - If it converts to ``True``, the pin is set to state '1', otherwise it is set - to state '0'. The behaviour of this method depends on the mode of the pin: - - - ``Pin.IN`` - The value is stored in the output buffer for the pin. The - pin state does not change, it remains in the high-impedance state. The - stored value will become active on the pin as soon as it is changed to - ``Pin.OUT`` or ``Pin.OPEN_DRAIN`` mode. - - ``Pin.OUT`` - The output buffer is set to the given value immediately. - - ``Pin.OPEN_DRAIN`` - If the value is '0' the pin is set to a low voltage - state. Otherwise the pin is set to high-impedance state. - - When setting the value this method returns ``None``. - -.. method:: Pin.__call__([x]) - - Pin objects are callable. The call method provides a (fast) shortcut to set - and get the value of the pin. It is equivalent to Pin.value([x]). - See :meth:`Pin.value` for more details. - -.. method:: Pin.on() - - Set pin to "1" output level. - -.. method:: Pin.off() - - Set pin to "0" output level. - -.. method:: Pin.mode([mode]) - - Get or set the pin mode. - See the constructor documentation for details of the ``mode`` argument. - -.. method:: Pin.pull([pull]) - - Get or set the pin pull state. - See the constructor documentation for details of the ``pull`` argument. - -.. method:: Pin.drive([drive]) - - Get or set the pin drive strength. - See the constructor documentation for details of the ``drive`` argument. - - Not all ports implement this method. - - Availability: WiPy. - -.. method:: Pin.irq(handler=None, trigger=(Pin.IRQ_FALLING | Pin.IRQ_RISING), \*, priority=1, wake=None) - - Configure an interrupt handler to be called when the trigger source of the - pin is active. If the pin mode is ``Pin.IN`` then the trigger source is - the external value on the pin. If the pin mode is ``Pin.OUT`` then the - trigger source is the output buffer of the pin. Otherwise, if the pin mode - is ``Pin.OPEN_DRAIN`` then the trigger source is the output buffer for - state '0' and the external pin value for state '1'. - - The arguments are: - - - ``handler`` is an optional function to be called when the interrupt - triggers. - - - ``trigger`` configures the event which can generate an interrupt. - Possible values are: - - - ``Pin.IRQ_FALLING`` interrupt on falling edge. - - ``Pin.IRQ_RISING`` interrupt on rising edge. - - ``Pin.IRQ_LOW_LEVEL`` interrupt on low level. - - ``Pin.IRQ_HIGH_LEVEL`` interrupt on high level. - - These values can be OR'ed together to trigger on multiple events. - - - ``priority`` sets the priority level of the interrupt. The values it - can take are port-specific, but higher values always represent higher - priorities. - - - ``wake`` selects the power mode in which this interrupt can wake up the - system. It can be ``machine.IDLE``, ``machine.SLEEP`` or ``machine.DEEPSLEEP``. - These values can also be OR'ed together to make a pin generate interrupts in - more than one power mode. - - This method returns a callback object. - -Constants ---------- - -The following constants are used to configure the pin objects. Note that -not all constants are available on all ports. - -.. data:: Pin.IN - Pin.OUT - Pin.OPEN_DRAIN - Pin.ALT - Pin.ALT_OPEN_DRAIN - - Selects the pin mode. - -.. data:: Pin.PULL_UP - Pin.PULL_DOWN - - Selects whether there is a pull up/down resistor. Use the value - ``None`` for no pull. - -.. data:: Pin.LOW_POWER - Pin.MED_POWER - Pin.HIGH_POWER - - Selects the pin drive strength. - -.. data:: Pin.IRQ_FALLING - Pin.IRQ_RISING - Pin.IRQ_LOW_LEVEL - Pin.IRQ_HIGH_LEVEL - - Selects the IRQ trigger type. diff --git a/docs/library/machine.RTC.rst b/docs/library/machine.RTC.rst deleted file mode 100644 index 95fa2b4ce6..0000000000 --- a/docs/library/machine.RTC.rst +++ /dev/null @@ -1,69 +0,0 @@ -.. currentmodule:: machine -.. _machine.RTC: - -class RTC -- real time clock -============================ - -The RTC is and independent clock that keeps track of the date -and time. - -Example usage:: - - rtc = machine.RTC() - rtc.init((2014, 5, 1, 4, 13, 0, 0, 0)) - print(rtc.now()) - - -Constructors ------------- - -.. class:: RTC(id=0, ...) - - Create an RTC object. See init for parameters of initialization. - -Methods -------- - -.. method:: RTC.init(datetime) - - Initialise the RTC. Datetime is a tuple of the form: - - ``(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])`` - -.. method:: RTC.now() - - Get get the current datetime tuple. - -.. method:: RTC.deinit() - - Resets the RTC to the time of January 1, 2015 and starts running it again. - -.. method:: RTC.alarm(id, time, \*, repeat=False) - - Set the RTC alarm. Time might be either a millisecond value to program the alarm to - current time + time_in_ms in the future, or a datetimetuple. If the time passed is in - milliseconds, repeat can be set to ``True`` to make the alarm periodic. - -.. method:: RTC.alarm_left(alarm_id=0) - - Get the number of milliseconds left before the alarm expires. - -.. method:: RTC.cancel(alarm_id=0) - - Cancel a running alarm. - -.. method:: RTC.irq(\*, trigger, handler=None, wake=machine.IDLE) - - Create an irq object triggered by a real time clock alarm. - - - ``trigger`` must be ``RTC.ALARM0`` - - ``handler`` is the function to be called when the callback is triggered. - - ``wake`` specifies the sleep mode from where this interrupt can wake - up the system. - -Constants ---------- - -.. data:: RTC.ALARM0 - - irq trigger source diff --git a/docs/library/machine.SD.rst b/docs/library/machine.SD.rst deleted file mode 100644 index 608e958317..0000000000 --- a/docs/library/machine.SD.rst +++ /dev/null @@ -1,42 +0,0 @@ -.. currentmodule:: machine -.. _machine.SD: - -class SD -- secure digital memory card -====================================== - -The SD card class allows to configure and enable the memory card -module of the WiPy and automatically mount it as ``/sd`` as part -of the file system. There are several pin combinations that can be -used to wire the SD card socket to the WiPy and the pins used can -be specified in the constructor. Please check the `pinout and alternate functions -table. `_ for -more info regarding the pins which can be remapped to be used with a SD card. - -Example usage:: - - from machine import SD - import os - # clk cmd and dat0 pins must be passed along with - # their respective alternate functions - sd = machine.SD(pins=('GP10', 'GP11', 'GP15')) - os.mount(sd, '/sd') - # do normal file operations - -Constructors ------------- - -.. class:: SD(id,... ) - - Create a SD card object. See ``init()`` for parameters if initialization. - -Methods -------- - -.. method:: SD.init(id=0, pins=('GP10', 'GP11', 'GP15')) - - Enable the SD card. In order to initialize the card, give it a 3-tuple: - ``(clk_pin, cmd_pin, dat0_pin)``. - -.. method:: SD.deinit() - - Disable the SD card. diff --git a/docs/library/machine.SPI.rst b/docs/library/machine.SPI.rst deleted file mode 100644 index 080f6fdfb2..0000000000 --- a/docs/library/machine.SPI.rst +++ /dev/null @@ -1,97 +0,0 @@ -.. currentmodule:: machine -.. _machine.SPI: - -class SPI -- a Serial Peripheral Interface bus protocol (master side) -===================================================================== - -SPI is a synchronous serial protocol that is driven by a master. At the -physical level, a bus consists of 3 lines: SCK, MOSI, MISO. Multiple devices -can share the same bus. Each device should have a separate, 4th signal, -SS (Slave Select), to select a particular device on a bus with which -communication takes place. Management of an SS signal should happen in -user code (via machine.Pin class). - -Constructors ------------- - -.. class:: SPI(id, ...) - - Construct an SPI object on the given bus, ``id``. Values of ``id`` depend - on a particular port and its hardware. Values 0, 1, etc. are commonly used - to select hardware SPI block #0, #1, etc. Value -1 can be used for - bitbanging (software) implementation of SPI (if supported by a port). - - With no additional parameters, the SPI object is created but not - initialised (it has the settings from the last initialisation of - the bus, if any). If extra arguments are given, the bus is initialised. - See ``init`` for parameters of initialisation. - -Methods -------- - -.. method:: SPI.init(baudrate=1000000, \*, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=None, mosi=None, miso=None, pins=(SCK, MOSI, MISO)) - - Initialise the SPI bus with the given parameters: - - - ``baudrate`` is the SCK clock rate. - - ``polarity`` can be 0 or 1, and is the level the idle clock line sits at. - - ``phase`` can be 0 or 1 to sample data on the first or second clock edge - respectively. - - ``bits`` is the width in bits of each transfer. Only 8 is guaranteed to be supported by all hardware. - - ``firstbit`` can be ``SPI.MSB`` or ``SPI.LSB``. - - ``sck``, ``mosi``, ``miso`` are pins (machine.Pin) objects to use for bus signals. For most - hardware SPI blocks (as selected by ``id`` parameter to the constructor), pins are fixed - and cannot be changed. In some cases, hardware blocks allow 2-3 alternative pin sets for - a hardware SPI block. Arbitrary pin assignments are possible only for a bitbanging SPI driver - (``id`` = -1). - - ``pins`` - WiPy port doesn't ``sck``, ``mosi``, ``miso`` arguments, and instead allows to - specify them as a tuple of ``pins`` parameter. - -.. method:: SPI.deinit() - - Turn off the SPI bus. - -.. method:: SPI.read(nbytes, write=0x00) - - Read a number of bytes specified by ``nbytes`` while continuously writing - the single byte given by ``write``. - Returns a ``bytes`` object with the data that was read. - -.. method:: SPI.readinto(buf, write=0x00) - - Read into the buffer specified by ``buf`` while continuously writing the - single byte given by ``write``. - Returns ``None``. - - Note: on WiPy this function returns the number of bytes read. - -.. method:: SPI.write(buf) - - Write the bytes contained in ``buf``. - Returns ``None``. - - Note: on WiPy this function returns the number of bytes written. - -.. method:: SPI.write_readinto(write_buf, read_buf) - - Write the bytes from ``write_buf`` while reading into ``read_buf``. The - buffers can be the same or different, but both buffers must have the - same length. - Returns ``None``. - - Note: on WiPy this function returns the number of bytes written. - -Constants ---------- - -.. data:: SPI.MASTER - - for initialising the SPI bus to master; this is only used for the WiPy - -.. data:: SPI.MSB - - set the first bit to be the most significant bit - -.. data:: SPI.LSB - - set the first bit to be the least significant bit diff --git a/docs/library/machine.Signal.rst b/docs/library/machine.Signal.rst deleted file mode 100644 index a1a29164b2..0000000000 --- a/docs/library/machine.Signal.rst +++ /dev/null @@ -1,123 +0,0 @@ -.. currentmodule:: machine -.. _machine.Signal: - -class Signal -- control and sense external I/O devices -====================================================== - -The Signal class is a simple extension of the `Pin` class. Unlike Pin, which -can be only in "absolute" 0 and 1 states, a Signal can be in "asserted" -(on) or "deasserted" (off) states, while being inverted (active-low) or -not. In other words, it adds logical inversion support to Pin functionality. -While this may seem a simple addition, it is exactly what is needed to -support wide array of simple digital devices in a way portable across -different boards, which is one of the major MicroPython goals. Regardless -of whether different users have an active-high or active-low LED, a normally -open or normally closed relay - you can develop a single, nicely looking -application which works with each of them, and capture hardware -configuration differences in few lines in the config file of your app. - -Example:: - - from machine import Pin, Signal - - # Suppose you have an active-high LED on pin 0 - led1_pin = Pin(0, Pin.OUT) - # ... and active-low LED on pin 1 - led2_pin = Pin(1, Pin.OUT) - - # Now to light up both of them using Pin class, you'll need to set - # them to different values - led1_pin.value(1) - led2_pin.value(0) - - # Signal class allows to abstract away active-high/active-low - # difference - led1 = Signal(led1_pin, invert=False) - led2 = Signal(led2_pin, invert=True) - - # Now lighting up them looks the same - led1.value(1) - led2.value(1) - - # Even better: - led1.on() - led2.on() - -Following is the guide when Signal vs Pin should be used: - -* Use Signal: If you want to control a simple on/off (including software - PWM!) devices like LEDs, multi-segment indicators, relays, buzzers, or - read simple binary sensors, like normally open or normally closed buttons, - pulled high or low, Reed switches, moisture/flame detectors, etc. etc. - Summing up, if you have a real physical device/sensor requiring GPIO - access, you likely should use a Signal. - -* Use Pin: If you implement a higher-level protocol or bus to communicate - with more complex devices. - -The split between Pin and Signal come from the usecases above and the -architecture of MicroPython: Pin offers the lowest overhead, which may -be important when bit-banging protocols. But Signal adds additional -flexibility on top of Pin, at the cost of minor overhead (much smaller -than if you implemented active-high vs active-low device differences in -Python manually!). Also, Pin is a low-level object which needs to be -implemented for each support board, while Signal is a high-level object -which comes for free once Pin is implemented. - -If in doubt, give the Signal a try! Once again, it is offered to save -developers from the need to handle unexciting differences like active-low -vs active-high signals, and allow other users to share and enjoy your -application, instead of being frustrated by the fact that it doesn't -work for them simply because their LEDs or relays are wired in a slightly -different way. - -Constructors ------------- - -.. class:: Signal(pin_obj, invert=False) - Signal(pin_arguments..., \*, invert=False) - - Create a Signal object. There're two ways to create it: - - * By wrapping existing Pin object - universal method which works for - any board. - * By passing required Pin parameters directly to Signal constructor, - skipping the need to create intermediate Pin object. Available on - many, but not all boards. - - The arguments are: - - - ``pin_obj`` is existing Pin object. - - - ``pin_arguments`` are the same arguments as can be passed to Pin constructor. - - - ``invert`` - if True, the signal will be inverted (active low). - -Methods -------- - -.. method:: Signal.value([x]) - - This method allows to set and get the value of the signal, depending on whether - the argument ``x`` is supplied or not. - - If the argument is omitted then this method gets the signal level, 1 meaning - signal is asserted (active) and 0 - signal inactive. - - If the argument is supplied then this method sets the signal level. The - argument ``x`` can be anything that converts to a boolean. If it converts - to ``True``, the signal is active, otherwise it is inactive. - - Correspondence between signal being active and actual logic level on the - underlying pin depends on whether signal is inverted (active-low) or not. - For non-inverted signal, active status corresponds to logical 1, inactive - - to logical 0. For inverted/active-low signal, active status corresponds - to logical 0, while inactive - to logical 1. - -.. method:: Signal.on() - - Activate signal. - -.. method:: Signal.off() - - Deactivate signal. diff --git a/docs/library/machine.Timer.rst b/docs/library/machine.Timer.rst deleted file mode 100644 index ef46f9dd7c..0000000000 --- a/docs/library/machine.Timer.rst +++ /dev/null @@ -1,160 +0,0 @@ -.. currentmodule:: machine -.. _machine.Timer: - -class Timer -- control hardware timers -====================================== - -Hardware timers deal with timing of periods and events. Timers are perhaps -the most flexible and heterogeneous kind of hardware in MCUs and SoCs, -differently greatly from a model to a model. MicroPython's Timer class -defines a baseline operation of executing a callback with a given period -(or once after some delay), and allow specific boards to define more -non-standard behavior (which thus won't be portable to other boards). - -See discussion of :ref:`important constraints ` on -Timer callbacks. - -.. note:: - - Memory can't be allocated inside irq handlers (an interrupt) and so - exceptions raised within a handler don't give much information. See - :func:`micropython.alloc_emergency_exception_buf` for how to get around this - limitation. - -Constructors ------------- - -.. class:: Timer(id, ...) - - Construct a new timer object of the given id. Id of -1 constructs a - virtual timer (if supported by a board). - -Methods -------- - -.. only:: port_wipy - - .. method:: Timer.init(mode, \*, width=16) - - Initialise the timer. Example:: - - tim.init(Timer.PERIODIC) # periodic 16-bit timer - tim.init(Timer.ONE_SHOT, width=32) # one shot 32-bit timer - - Keyword arguments: - - - ``mode`` can be one of: - - - ``Timer.ONE_SHOT`` - The timer runs once until the configured - period of the channel expires. - - ``Timer.PERIODIC`` - The timer runs periodically at the configured - frequency of the channel. - - ``Timer.PWM`` - Output a PWM signal on a pin. - - - ``width`` must be either 16 or 32 (bits). For really low frequencies < 5Hz - (or large periods), 32-bit timers should be used. 32-bit mode is only available - for ``ONE_SHOT`` AND ``PERIODIC`` modes. - -.. method:: Timer.deinit() - - Deinitialises the timer. Stops the timer, and disables the timer peripheral. - -.. only:: port_wipy - - .. method:: Timer.channel(channel, \**, freq, period, polarity=Timer.POSITIVE, duty_cycle=0) - - If only a channel identifier passed, then a previously initialized channel - object is returned (or ``None`` if there is no previous channel). - - Otherwise, a TimerChannel object is initialized and returned. - - The operating mode is is the one configured to the Timer object that was used to - create the channel. - - - ``channel`` if the width of the timer is 16-bit, then must be either ``TIMER.A``, ``TIMER.B``. - If the width is 32-bit then it **must be** ``TIMER.A | TIMER.B``. - - Keyword only arguments: - - - ``freq`` sets the frequency in Hz. - - ``period`` sets the period in microseconds. - - .. note:: - - Either ``freq`` or ``period`` must be given, never both. - - - ``polarity`` this is applicable for ``PWM``, and defines the polarity of the duty cycle - - ``duty_cycle`` only applicable to ``PWM``. It's a percentage (0.00-100.00). Since the WiPy - doesn't support floating point numbers the duty cycle must be specified in the range 0-10000, - where 10000 would represent 100.00, 5050 represents 50.50, and so on. - - .. note:: - - When the channel is in PWM mode, the corresponding pin is assigned automatically, therefore - there's no need to assign the alternate function of the pin via the ``Pin`` class. The pins which - support PWM functionality are the following: - - - ``GP24`` on Timer 0 channel A. - - ``GP25`` on Timer 1 channel A. - - ``GP9`` on Timer 2 channel B. - - ``GP10`` on Timer 3 channel A. - - ``GP11`` on Timer 3 channel B. - -.. only:: port_wipy - - class TimerChannel --- setup a channel for a timer - ================================================== - - Timer channels are used to generate/capture a signal using a timer. - - TimerChannel objects are created using the Timer.channel() method. - - Methods - ------- - - .. method:: timerchannel.irq(\*, trigger, priority=1, handler=None) - - The behavior of this callback is heavily dependent on the operating - mode of the timer channel: - - - If mode is ``Timer.PERIODIC`` the callback is executed periodically - with the configured frequency or period. - - If mode is ``Timer.ONE_SHOT`` the callback is executed once when - the configured timer expires. - - If mode is ``Timer.PWM`` the callback is executed when reaching the duty - cycle value. - - The accepted params are: - - - ``priority`` level of the interrupt. Can take values in the range 1-7. - Higher values represent higher priorities. - - ``handler`` is an optional function to be called when the interrupt is triggered. - - ``trigger`` must be ``Timer.TIMEOUT`` when the operating mode is either ``Timer.PERIODIC`` or - ``Timer.ONE_SHOT``. In the case that mode is ``Timer.PWM`` then trigger must be equal to - ``Timer.MATCH``. - - Returns a callback object. - -.. only:: port_wipy - - .. method:: timerchannel.freq([value]) - - Get or set the timer channel frequency (in Hz). - - .. method:: timerchannel.period([value]) - - Get or set the timer channel period (in microseconds). - - .. method:: timerchannel.duty_cycle([value]) - - Get or set the duty cycle of the PWM signal. It's a percentage (0.00-100.00). Since the WiPy - doesn't support floating point numbers the duty cycle must be specified in the range 0-10000, - where 10000 would represent 100.00, 5050 represents 50.50, and so on. - -Constants ---------- - -.. data:: Timer.ONE_SHOT -.. data:: Timer.PERIODIC - - Timer operating mode. diff --git a/docs/library/machine.UART.rst b/docs/library/machine.UART.rst deleted file mode 100644 index 983ef0a947..0000000000 --- a/docs/library/machine.UART.rst +++ /dev/null @@ -1,142 +0,0 @@ -.. currentmodule:: machine -.. _machine.UART: - -class UART -- duplex serial communication bus -============================================= - -UART implements the standard UART/USART duplex serial communications protocol. At -the physical level it consists of 2 lines: RX and TX. The unit of communication -is a character (not to be confused with a string character) which can be 8 or 9 -bits wide. - -UART objects can be created and initialised using:: - - from machine import UART - - uart = UART(1, 9600) # init with given baudrate - uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters - -Supported parameters differ on a board: - -Pyboard: Bits can be 7, 8 or 9. Stop can be 1 or 2. With *parity=None*, -only 8 and 9 bits are supported. With parity enabled, only 7 and 8 bits -are supported. - -WiPy/CC3200: Bits can be 5, 6, 7, 8. Stop can be 1 or 2. - -A UART object acts like a stream object and reading and writing is done -using the standard stream methods:: - - uart.read(10) # read 10 characters, returns a bytes object - uart.read() # read all available characters - uart.readline() # read a line - uart.readinto(buf) # read and store into the given buffer - uart.write('abc') # write the 3 characters - -Constructors ------------- - -.. class:: UART(id, ...) - - Construct a UART object of the given id. - -Methods -------- - -.. only:: port_wipy - - .. method:: UART.init(baudrate=9600, bits=8, parity=None, stop=1, \*, pins=(TX, RX, RTS, CTS)) - - Initialise the UART bus with the given parameters: - - - ``baudrate`` is the clock rate. - - ``bits`` is the number of bits per character, 7, 8 or 9. - - ``parity`` is the parity, ``None``, 0 (even) or 1 (odd). - - ``stop`` is the number of stop bits, 1 or 2. - - ``pins`` is a 4 or 2 item list indicating the TX, RX, RTS and CTS pins (in that order). - Any of the pins can be None if one wants the UART to operate with limited functionality. - If the RTS pin is given the the RX pin must be given as well. The same applies to CTS. - When no pins are given, then the default set of TX and RX pins is taken, and hardware - flow control will be disabled. If pins=None, no pin assignment will be made. - -.. method:: UART.deinit() - - Turn off the UART bus. - -.. method:: UART.any() - - Returns an integer counting the number of characters that can be read without - blocking. It will return 0 if there are no characters available and a positive - number if there are characters. The method may return 1 even if there is more - than one character available for reading. - - For more sophisticated querying of available characters use select.poll:: - - poll = select.poll() - poll.register(uart, select.POLLIN) - poll.poll(timeout) - -.. method:: UART.read([nbytes]) - - Read characters. If ``nbytes`` is specified then read at most that many bytes, - otherwise read as much data as possible. - - Return value: a bytes object containing the bytes read in. Returns ``None`` - on timeout. - -.. method:: UART.readinto(buf[, nbytes]) - - Read bytes into the ``buf``. If ``nbytes`` is specified then read at most - that many bytes. Otherwise, read at most ``len(buf)`` bytes. - - Return value: number of bytes read and stored into ``buf`` or ``None`` on - timeout. - -.. method:: UART.readline() - - Read a line, ending in a newline character. - - Return value: the line read or ``None`` on timeout. - -.. method:: UART.write(buf) - - Write the buffer of bytes to the bus. - - Return value: number of bytes written or ``None`` on timeout. - -.. method:: UART.sendbreak() - - Send a break condition on the bus. This drives the bus low for a duration - longer than required for a normal transmission of a character. - -.. only:: port_wipy - - .. method:: UART.irq(trigger, priority=1, handler=None, wake=machine.IDLE) - - Create a callback to be triggered when data is received on the UART. - - - ``trigger`` can only be ``UART.RX_ANY`` - - ``priority`` level of the interrupt. Can take values in the range 1-7. - Higher values represent higher priorities. - - ``handler`` an optional function to be called when new characters arrive. - - ``wake`` can only be ``machine.IDLE``. - - .. note:: - - The handler will be called whenever any of the following two conditions are met: - - - 8 new characters have been received. - - At least 1 new character is waiting in the Rx buffer and the Rx line has been - silent for the duration of 1 complete frame. - - This means that when the handler function is called there will be between 1 to 8 - characters waiting. - - Returns an irq object. - - Constants - --------- - - .. data:: UART.RX_ANY - - IRQ trigger sources diff --git a/docs/library/machine.WDT.rst b/docs/library/machine.WDT.rst deleted file mode 100644 index 5ca6dce45d..0000000000 --- a/docs/library/machine.WDT.rst +++ /dev/null @@ -1,36 +0,0 @@ -.. currentmodule:: machine -.. _machine.WDT: - -class WDT -- watchdog timer -=========================== - -The WDT is used to restart the system when the application crashes and ends -up into a non recoverable state. Once started it cannot be stopped or -reconfigured in any way. After enabling, the application must "feed" the -watchdog periodically to prevent it from expiring and resetting the system. - -Example usage:: - - from machine import WDT - wdt = WDT(timeout=2000) # enable it with a timeout of 2s - wdt.feed() - -Availability of this class: pyboard, WiPy. - -Constructors ------------- - -.. class:: WDT(id=0, timeout=5000) - - Create a WDT object and start it. The timeout must be given in seconds and - the minimum value that is accepted is 1 second. Once it is running the timeout - cannot be changed and the WDT cannot be stopped either. - -Methods -------- - -.. method:: wdt.feed() - - Feed the WDT to prevent it from resetting the system. The application - should place this call in a sensible place ensuring that the WDT is - only fed after verifying that everything is functioning correctly. diff --git a/docs/library/machine.rst b/docs/library/machine.rst deleted file mode 100644 index 087f19cc6c..0000000000 --- a/docs/library/machine.rst +++ /dev/null @@ -1,170 +0,0 @@ -:mod:`machine` --- functions related to the hardware -==================================================== - -.. module:: machine - :synopsis: functions related to the hardware - -The ``machine`` module contains specific functions related to the hardware -on a particular board. Most functions in this module allow to achieve direct -and unrestricted access to and control of hardware blocks on a system -(like CPU, timers, buses, etc.). Used incorrectly, this can lead to -malfunction, lockups, crashes of your board, and in extreme cases, hardware -damage. - -.. _machine_callbacks: - -A note of callbacks used by functions and class methods of :mod:`machine` module: -all these callbacks should be considered as executing in an interrupt context. -This is true for both physical devices with IDs >= 0 and "virtual" devices -with negative IDs like -1 (these "virtual" devices are still thin shims on -top of real hardware and real hardware interrupts). See :ref:`isr_rules`. - -Reset related functions ------------------------ - -.. function:: reset() - - Resets the device in a manner similar to pushing the external RESET - button. - -.. function:: reset_cause() - - Get the reset cause. See :ref:`constants ` for the possible return values. - -Interrupt related functions ---------------------------- - -.. function:: disable_irq() - - Disable interrupt requests. - Returns the previous IRQ state which should be considered an opaque value. - This return value should be passed to the `enable_irq()` function to restore - interrupts to their original state, before `disable_irq()` was called. - -.. function:: enable_irq(state) - - Re-enable interrupt requests. - The *state* parameter should be the value that was returned from the most - recent call to the `disable_irq()` function. - -Power related functions ------------------------ - -.. function:: freq() - - Returns CPU frequency in hertz. - -.. function:: idle() - - Gates the clock to the CPU, useful to reduce power consumption at any time during - short or long periods. Peripherals continue working and execution resumes as soon - as any interrupt is triggered (on many ports this includes system timer - interrupt occurring at regular intervals on the order of millisecond). - -.. function:: sleep() - - Stops the CPU and disables all peripherals except for WLAN. Execution is resumed from - the point where the sleep was requested. For wake up to actually happen, wake sources - should be configured first. - -.. function:: deepsleep() - - Stops the CPU and all peripherals (including networking interfaces, if any). Execution - is resumed from the main script, just as with a reset. The reset cause can be checked - to know that we are coming from `machine.DEEPSLEEP`. For wake up to actually happen, - wake sources should be configured first, like `Pin` change or `RTC` timeout. - -.. only:: port_wipy - - .. function:: wake_reason() - - Get the wake reason. See :ref:`constants ` for the possible return values. - -Miscellaneous functions ------------------------ - -.. only:: port_wipy - - .. function:: rng() - - Return a 24-bit software generated random number. - -.. function:: unique_id() - - Returns a byte string with a unique identifier of a board/SoC. It will vary - from a board/SoC instance to another, if underlying hardware allows. Length - varies by hardware (so use substring of a full value if you expect a short - ID). In some MicroPython ports, ID corresponds to the network MAC address. - -.. function:: time_pulse_us(pin, pulse_level, timeout_us=1000000) - - Time a pulse on the given *pin*, and return the duration of the pulse in - microseconds. The *pulse_level* argument should be 0 to time a low pulse - or 1 to time a high pulse. - - If the current input value of the pin is different to *pulse_level*, - the function first (*) waits until the pin input becomes equal to *pulse_level*, - then (**) times the duration that the pin is equal to *pulse_level*. - If the pin is already equal to *pulse_level* then timing starts straight away. - - The function will return -2 if there was timeout waiting for condition marked - (*) above, and -1 if there was timeout during the main measurement, marked (**) - above. The timeout is the same for both cases and given by *timeout_us* (which - is in microseconds). - -.. _machine_constants: - -Constants ---------- - -.. data:: machine.IDLE - machine.SLEEP - machine.DEEPSLEEP - - IRQ wake values. - -.. data:: machine.PWRON_RESET - machine.HARD_RESET - machine.WDT_RESET - machine.DEEPSLEEP_RESET - machine.SOFT_RESET - - Reset causes. - -.. data:: machine.WLAN_WAKE - machine.PIN_WAKE - machine.RTC_WAKE - - Wake-up reasons. - -Classes -------- - -.. only:: not port_wipy - - .. toctree:: - :maxdepth: 1 - - machine.Pin.rst - machine.Signal.rst - machine.UART.rst - machine.SPI.rst - machine.I2C.rst - machine.RTC.rst - machine.Timer.rst - machine.WDT.rst - -.. only:: port_wipy - - .. toctree:: - :maxdepth: 1 - - machine.Pin.rst - machine.UART.rst - machine.SPI.rst - machine.I2C.rst - machine.RTC.rst - machine.Timer.rst - machine.WDT.rst - machine.ADC.rst - machine.SD.rst diff --git a/docs/library/math.rst b/docs/library/math.rst deleted file mode 100644 index a6f13d48c1..0000000000 --- a/docs/library/math.rst +++ /dev/null @@ -1,185 +0,0 @@ -:mod:`math` -- mathematical functions -===================================== - -.. module:: math - :synopsis: mathematical functions - -|see_cpython_module| :mod:`python:math`. - -The ``math`` module provides some basic mathematical functions for -working with floating-point numbers. - -*Note:* On the pyboard, floating-point numbers have 32-bit precision. - -Availability: not available on WiPy. Floating point support required -for this module. - -Functions ---------- - -.. function:: acos(x) - - Return the inverse cosine of ``x``. - -.. function:: acosh(x) - - Return the inverse hyperbolic cosine of ``x``. - -.. function:: asin(x) - - Return the inverse sine of ``x``. - -.. function:: asinh(x) - - Return the inverse hyperbolic sine of ``x``. - -.. function:: atan(x) - - Return the inverse tangent of ``x``. - -.. function:: atan2(y, x) - - Return the principal value of the inverse tangent of ``y/x``. - -.. function:: atanh(x) - - Return the inverse hyperbolic tangent of ``x``. - -.. function:: ceil(x) - - Return an integer, being ``x`` rounded towards positive infinity. - -.. function:: copysign(x, y) - - Return ``x`` with the sign of ``y``. - -.. function:: cos(x) - - Return the cosine of ``x``. - -.. function:: cosh(x) - - Return the hyperbolic cosine of ``x``. - -.. function:: degrees(x) - - Return radians ``x`` converted to degrees. - -.. function:: erf(x) - - Return the error function of ``x``. - -.. function:: erfc(x) - - Return the complementary error function of ``x``. - -.. function:: exp(x) - - Return the exponential of ``x``. - -.. function:: expm1(x) - - Return ``exp(x) - 1``. - -.. function:: fabs(x) - - Return the absolute value of ``x``. - -.. function:: floor(x) - - Return an integer, being ``x`` rounded towards negative infinity. - -.. function:: fmod(x, y) - - Return the remainder of ``x/y``. - -.. function:: frexp(x) - - Decomposes a floating-point number into its mantissa and exponent. - The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` - exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise - the relation ``0.5 <= abs(m) < 1`` holds. - -.. function:: gamma(x) - - Return the gamma function of ``x``. - -.. function:: isfinite(x) - - Return ``True`` if ``x`` is finite. - -.. function:: isinf(x) - - Return ``True`` if ``x`` is infinite. - -.. function:: isnan(x) - - Return ``True`` if ``x`` is not-a-number - -.. function:: ldexp(x, exp) - - Return ``x * (2**exp)``. - -.. function:: lgamma(x) - - Return the natural logarithm of the gamma function of ``x``. - -.. function:: log(x) - - Return the natural logarithm of ``x``. - -.. function:: log10(x) - - Return the base-10 logarithm of ``x``. - -.. function:: log2(x) - - Return the base-2 logarithm of ``x``. - -.. function:: modf(x) - - Return a tuple of two floats, being the fractional and integral parts of - ``x``. Both return values have the same sign as ``x``. - -.. function:: pow(x, y) - - Returns ``x`` to the power of ``y``. - -.. function:: radians(x) - - Return degrees ``x`` converted to radians. - -.. function:: sin(x) - - Return the sine of ``x``. - -.. function:: sinh(x) - - Return the hyperbolic sine of ``x``. - -.. function:: sqrt(x) - - Return the square root of ``x``. - -.. function:: tan(x) - - Return the tangent of ``x``. - -.. function:: tanh(x) - - Return the hyperbolic tangent of ``x``. - -.. function:: trunc(x) - - Return an integer, being ``x`` rounded towards 0. - -Constants ---------- - -.. data:: e - - base of the natural logarithm - -.. data:: pi - - the ratio of a circle's circumference to its diameter diff --git a/docs/library/micropython.rst b/docs/library/micropython.rst index c13a7391bb..59e1886fa2 100644 --- a/docs/library/micropython.rst +++ b/docs/library/micropython.rst @@ -1,6 +1,8 @@ :mod:`micropython` -- access and control MicroPython internals ============================================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: micropython :synopsis: access and control MicroPython internals diff --git a/docs/library/network.rst b/docs/library/network.rst index 99a7c242c0..60c9756dbb 100644 --- a/docs/library/network.rst +++ b/docs/library/network.rst @@ -2,6 +2,8 @@ :mod:`network` --- network configuration **************************************** +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: network :synopsis: network configuration @@ -39,7 +41,7 @@ Common network adapter interface ================================ This section describes an (implied) abstract base class for all network -interface classes implemented by `MicroPython ports ` +interface classes implemented by ``MicroPython ports `` for different hardware. This means that MicroPython does not actually provide ``AbstractNIC`` class, but any actual NIC class, as described in the following sections, implements methods as described here. @@ -131,461 +133,145 @@ parameter should be `id`. # Extended status information also available this way print(sta.config('rssi')) -.. only:: port_pyboard - - class CC3K - ========== - - This class provides a driver for CC3000 WiFi modules. Example usage:: - - import network - nic = network.CC3K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3) - nic.connect('your-ssid', 'your-password') - while not nic.isconnected(): - pyb.delay(50) - print(nic.ifconfig()) - - # now use socket as usual - ... - - For this example to work the CC3000 module must have the following connections: - - - MOSI connected to Y8 - - MISO connected to Y7 - - CLK connected to Y6 - - CS connected to Y5 - - VBEN connected to Y4 - - IRQ connected to Y3 - - It is possible to use other SPI busses and other pins for CS, VBEN and IRQ. - - Constructors - ------------ - - .. class:: CC3K(spi, pin_cs, pin_en, pin_irq) - - Create a CC3K driver object, initialise the CC3000 module using the given SPI bus - and pins, and return the CC3K object. - - Arguments are: - - - *spi* is an :ref:`SPI object ` which is the SPI bus that the CC3000 is - connected to (the MOSI, MISO and CLK pins). - - *pin_cs* is a :ref:`Pin object ` which is connected to the CC3000 CS pin. - - *pin_en* is a :ref:`Pin object ` which is connected to the CC3000 VBEN pin. - - *pin_irq* is a :ref:`Pin object ` which is connected to the CC3000 IRQ pin. - - All of these objects will be initialised by the driver, so there is no need to - initialise them yourself. For example, you can use:: - - nic = network.CC3K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3) - - Methods - ------- - - .. method:: cc3k.connect(ssid, key=None, \*, security=WPA2, bssid=None) - - Connect to a WiFi access point using the given SSID, and other security - parameters. - - .. method:: cc3k.disconnect() - - Disconnect from the WiFi access point. - - .. method:: cc3k.isconnected() - - Returns True if connected to a WiFi access point and has a valid IP address, - False otherwise. - - .. method:: cc3k.ifconfig() - - Returns a 7-tuple with (ip, subnet mask, gateway, DNS server, DHCP server, - MAC address, SSID). - - .. method:: cc3k.patch_version() - - Return the version of the patch program (firmware) on the CC3000. - - .. method:: cc3k.patch_program('pgm') - - Upload the current firmware to the CC3000. You must pass 'pgm' as the first - argument in order for the upload to proceed. - - Constants - --------- - - .. data:: CC3K.WEP - .. data:: CC3K.WPA - .. data:: CC3K.WPA2 - - security type to use - - class WIZNET5K - ============== - - This class allows you to control WIZnet5x00 Ethernet adaptors based on - the W5200 and W5500 chipsets. The particular chipset that is supported - by the firmware is selected at compile-time via the MICROPY_PY_WIZNET5K - option. - - Example usage:: - - import network - nic = network.WIZNET5K(pyb.SPI(1), pyb.Pin.board.X5, pyb.Pin.board.X4) - print(nic.ifconfig()) - - # now use socket as usual - ... - - For this example to work the WIZnet5x00 module must have the following connections: - - - MOSI connected to X8 - - MISO connected to X7 - - SCLK connected to X6 - - nSS connected to X5 - - nRESET connected to X4 - - It is possible to use other SPI busses and other pins for nSS and nRESET. - - Constructors - ------------ - - .. class:: WIZNET5K(spi, pin_cs, pin_rst) - - Create a WIZNET5K driver object, initialise the WIZnet5x00 module using the given - SPI bus and pins, and return the WIZNET5K object. - - Arguments are: - - - *spi* is an :ref:`SPI object ` which is the SPI bus that the WIZnet5x00 is - connected to (the MOSI, MISO and SCLK pins). - - *pin_cs* is a :ref:`Pin object ` which is connected to the WIZnet5x00 nSS pin. - - *pin_rst* is a :ref:`Pin object ` which is connected to the WIZnet5x00 nRESET pin. - - All of these objects will be initialised by the driver, so there is no need to - initialise them yourself. For example, you can use:: - - nic = network.WIZNET5K(pyb.SPI(1), pyb.Pin.board.X5, pyb.Pin.board.X4) - - Methods - ------- - - .. method:: wiznet5k.isconnected() - - Returns ``True`` if the physical Ethernet link is connected and up. - Returns ``False`` otherwise. - - .. method:: wiznet5k.ifconfig([(ip, subnet, gateway, dns)]) - - Get/set IP address, subnet mask, gateway and DNS. - - When called with no arguments, this method returns a 4-tuple with the above information. - - To set the above values, pass a 4-tuple with the required information. For example:: - - nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8')) - - .. method:: wiznet5k.regs() - - Dump the WIZnet5x00 registers. Useful for debugging. - .. _network.WLAN: -.. only:: port_esp8266 +Functions +========= - Functions - ========= +.. function:: phy_mode([mode]) - .. function:: phy_mode([mode]) + Get or set the PHY mode. - Get or set the PHY mode. + If the *mode* parameter is provided, sets the mode to its value. If + the function is called without parameters, returns the current mode. - If the *mode* parameter is provided, sets the mode to its value. If - the function is called without parameters, returns the current mode. + The possible modes are defined as constants: + * ``MODE_11B`` -- IEEE 802.11b, + * ``MODE_11G`` -- IEEE 802.11g, + * ``MODE_11N`` -- IEEE 802.11n. - The possible modes are defined as constants: - * ``MODE_11B`` -- IEEE 802.11b, - * ``MODE_11G`` -- IEEE 802.11g, - * ``MODE_11N`` -- IEEE 802.11n. +class WLAN +========== - class WLAN - ========== +This class provides a driver for WiFi network processor in the ESP8266. Example usage:: - This class provides a driver for WiFi network processor in the ESP8266. Example usage:: + import network + # enable station interface and connect to WiFi access point + nic = network.WLAN(network.STA_IF) + nic.active(True) + nic.connect('your-ssid', 'your-password') + # now use sockets as usual - import network - # enable station interface and connect to WiFi access point - nic = network.WLAN(network.STA_IF) - nic.active(True) - nic.connect('your-ssid', 'your-password') - # now use sockets as usual +Constructors +------------ +.. class:: WLAN(interface_id) - Constructors - ------------ - .. class:: WLAN(interface_id) +Create a WLAN network interface object. Supported interfaces are +``network.STA_IF`` (station aka client, connects to upstream WiFi access +points) and ``network.AP_IF`` (access point, allows other WiFi clients to +connect). Availability of the methods below depends on interface type. +For example, only STA interface may `connect()` to an access point. - Create a WLAN network interface object. Supported interfaces are - ``network.STA_IF`` (station aka client, connects to upstream WiFi access - points) and ``network.AP_IF`` (access point, allows other WiFi clients to - connect). Availability of the methods below depends on interface type. - For example, only STA interface may `connect()` to an access point. +Methods +------- - Methods - ------- +.. method:: wlan.active([is_active]) - .. method:: wlan.active([is_active]) + Activate ("up") or deactivate ("down") network interface, if boolean + argument is passed. Otherwise, query current state if no argument is + provided. Most other methods require active interface. - Activate ("up") or deactivate ("down") network interface, if boolean - argument is passed. Otherwise, query current state if no argument is - provided. Most other methods require active interface. +.. method:: wlan.connect(ssid=None, password=None, \*, bssid=None) - .. method:: wlan.connect(ssid=None, password=None, \*, bssid=None) + Connect to the specified wireless network, using the specified password. + If *bssid* is given then the connection will be restricted to the + access-point with that MAC address (the *ssid* must also be specified + in this case). - Connect to the specified wireless network, using the specified password. - If *bssid* is given then the connection will be restricted to the - access-point with that MAC address (the *ssid* must also be specified - in this case). +.. method:: wlan.disconnect() - .. method:: wlan.disconnect() + Disconnect from the currently connected wireless network. - Disconnect from the currently connected wireless network. +.. method:: wlan.scan() - .. method:: wlan.scan() + Scan for the available wireless networks. - Scan for the available wireless networks. + Scanning is only possible on STA interface. Returns list of tuples with + the information about WiFi access points: - Scanning is only possible on STA interface. Returns list of tuples with - the information about WiFi access points: + (ssid, bssid, channel, RSSI, authmode, hidden) - (ssid, bssid, channel, RSSI, authmode, hidden) + *bssid* is hardware address of an access point, in binary form, returned as + bytes object. You can use `ubinascii.hexlify()` to convert it to ASCII form. - *bssid* is hardware address of an access point, in binary form, returned as - bytes object. You can use `ubinascii.hexlify()` to convert it to ASCII form. + There are five values for authmode: - There are five values for authmode: + * 0 -- open + * 1 -- WEP + * 2 -- WPA-PSK + * 3 -- WPA2-PSK + * 4 -- WPA/WPA2-PSK - * 0 -- open - * 1 -- WEP - * 2 -- WPA-PSK - * 3 -- WPA2-PSK - * 4 -- WPA/WPA2-PSK + and two for hidden: - and two for hidden: + * 0 -- visible + * 1 -- hidden - * 0 -- visible - * 1 -- hidden +.. method:: wlan.status() - .. method:: wlan.status() + Return the current status of the wireless connection. - Return the current status of the wireless connection. + The possible statuses are defined as constants: - The possible statuses are defined as constants: + * ``STAT_IDLE`` -- no connection and no activity, + * ``STAT_CONNECTING`` -- connecting in progress, + * ``STAT_WRONG_PASSWORD`` -- failed due to incorrect password, + * ``STAT_NO_AP_FOUND`` -- failed because no access point replied, + * ``STAT_CONNECT_FAIL`` -- failed due to other problems, + * ``STAT_GOT_IP`` -- connection successful. - * ``STAT_IDLE`` -- no connection and no activity, - * ``STAT_CONNECTING`` -- connecting in progress, - * ``STAT_WRONG_PASSWORD`` -- failed due to incorrect password, - * ``STAT_NO_AP_FOUND`` -- failed because no access point replied, - * ``STAT_CONNECT_FAIL`` -- failed due to other problems, - * ``STAT_GOT_IP`` -- connection successful. +.. method:: wlan.isconnected() - .. method:: wlan.isconnected() + In case of STA mode, returns ``True`` if connected to a WiFi access + point and has a valid IP address. In AP mode returns ``True`` when a + station is connected. Returns ``False`` otherwise. - In case of STA mode, returns ``True`` if connected to a WiFi access - point and has a valid IP address. In AP mode returns ``True`` when a - station is connected. Returns ``False`` otherwise. +.. method:: wlan.ifconfig([(ip, subnet, gateway, dns)]) - .. method:: wlan.ifconfig([(ip, subnet, gateway, dns)]) + Get/set IP-level network interface parameters: IP address, subnet mask, + gateway and DNS server. When called with no arguments, this method returns + a 4-tuple with the above information. To set the above values, pass a + 4-tuple with the required information. For example:: - Get/set IP-level network interface parameters: IP address, subnet mask, - gateway and DNS server. When called with no arguments, this method returns - a 4-tuple with the above information. To set the above values, pass a - 4-tuple with the required information. For example:: + nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8')) - nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8')) +.. method:: wlan.config('param') +.. method:: wlan.config(param=value, ...) - .. method:: wlan.config('param') - .. method:: wlan.config(param=value, ...) + Get or set general network interface parameters. These methods allow to work + with additional parameters beyond standard IP configuration (as dealt with by + `wlan.ifconfig()`). These include network-specific and hardware-specific + parameters. For setting parameters, keyword argument syntax should be used, + multiple parameters can be set at once. For querying, parameters name should + be quoted as a string, and only one parameter can be queries at time:: - Get or set general network interface parameters. These methods allow to work - with additional parameters beyond standard IP configuration (as dealt with by - `wlan.ifconfig()`). These include network-specific and hardware-specific - parameters. For setting parameters, keyword argument syntax should be used, - multiple parameters can be set at once. For querying, parameters name should - be quoted as a string, and only one parameter can be queries at time:: + # Set WiFi access point name (formally known as ESSID) and WiFi channel + ap.config(essid='My AP', channel=11) + # Query params one by one + print(ap.config('essid')) + print(ap.config('channel')) - # Set WiFi access point name (formally known as ESSID) and WiFi channel - ap.config(essid='My AP', channel=11) - # Query params one by one - print(ap.config('essid')) - print(ap.config('channel')) + Following are commonly supported parameters (availability of a specific parameter + depends on network technology type, driver, and ``MicroPython port``). - Following are commonly supported parameters (availability of a specific parameter - depends on network technology type, driver, and `MicroPython port`). - - ============= =========== - Parameter Description - ============= =========== - mac MAC address (bytes) - essid WiFi access point name (string) - channel WiFi channel (integer) - hidden Whether ESSID is hidden (boolean) - authmode Authentication mode supported (enumeration, see module constants) - password Access password (string) - dhcp_hostname The DHCP hostname to use - ============= =========== - - - -.. only:: port_wipy - - class WLAN - ========== - - This class provides a driver for the WiFi network processor in the WiPy. Example usage:: - - import network - import time - # setup as a station - wlan = network.WLAN(mode=WLAN.STA) - wlan.connect('your-ssid', auth=(WLAN.WPA2, 'your-key')) - while not wlan.isconnected(): - time.sleep_ms(50) - print(wlan.ifconfig()) - - # now use socket as usual - ... - - Constructors - ------------ - - .. class:: WLAN(id=0, ...) - - Create a WLAN object, and optionally configure it. See `init()` for params of configuration. - - .. note:: - - The ``WLAN`` constructor is special in the sense that if no arguments besides the id are given, - it will return the already existing ``WLAN`` instance without re-configuring it. This is - because ``WLAN`` is a system feature of the WiPy. If the already existing instance is not - initialized it will do the same as the other constructors an will initialize it with default - values. - - Methods - ------- - - .. method:: wlan.init(mode, \*, ssid, auth, channel, antenna) - - Set or get the WiFi network processor configuration. - - Arguments are: - - - *mode* can be either ``WLAN.STA`` or ``WLAN.AP``. - - *ssid* is a string with the ssid name. Only needed when mode is ``WLAN.AP``. - - *auth* is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``, - ``WLAN.WPA`` or ``WLAN.WPA2``. The key is a string with the network password. - If ``sec`` is ``WLAN.WEP`` the key must be a string representing hexadecimal - values (e.g. 'ABC1DE45BF'). Only needed when mode is ``WLAN.AP``. - - *channel* a number in the range 1-11. Only needed when mode is ``WLAN.AP``. - - *antenna* selects between the internal and the external antenna. Can be either - ``WLAN.INT_ANT`` or ``WLAN.EXT_ANT``. - - For example, you can do:: - - # create and configure as an access point - wlan.init(mode=WLAN.AP, ssid='wipy-wlan', auth=(WLAN.WPA2,'www.wipy.io'), channel=7, antenna=WLAN.INT_ANT) - - or:: - - # configure as an station - wlan.init(mode=WLAN.STA) - - .. method:: wlan.connect(ssid, \*, auth=None, bssid=None, timeout=None) - - Connect to a WiFi access point using the given SSID, and other security - parameters. - - - *auth* is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``, - ``WLAN.WPA`` or ``WLAN.WPA2``. The key is a string with the network password. - If ``sec`` is ``WLAN.WEP`` the key must be a string representing hexadecimal - values (e.g. 'ABC1DE45BF'). - - *bssid* is the MAC address of the AP to connect to. Useful when there are several - APs with the same ssid. - - *timeout* is the maximum time in milliseconds to wait for the connection to succeed. - - .. method:: wlan.scan() - - Performs a network scan and returns a list of named tuples with (ssid, bssid, sec, channel, rssi). - Note that channel is always ``None`` since this info is not provided by the WiPy. - - .. method:: wlan.disconnect() - - Disconnect from the WiFi access point. - - .. method:: wlan.isconnected() - - In case of STA mode, returns ``True`` if connected to a WiFi access point and has a valid IP address. - In AP mode returns ``True`` when a station is connected, ``False`` otherwise. - - .. method:: wlan.ifconfig(if_id=0, config=['dhcp' or configtuple]) - - With no parameters given returns a 4-tuple of *(ip, subnet_mask, gateway, DNS_server)*. - - if ``'dhcp'`` is passed as a parameter then the DHCP client is enabled and the IP params - are negotiated with the AP. - - If the 4-tuple config is given then a static IP is configured. For instance:: - - wlan.ifconfig(config=('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8')) - - .. method:: wlan.mode([mode]) - - Get or set the WLAN mode. - - .. method:: wlan.ssid([ssid]) - - Get or set the SSID when in AP mode. - - .. method:: wlan.auth([auth]) - - Get or set the authentication type when in AP mode. - - .. method:: wlan.channel([channel]) - - Get or set the channel (only applicable in AP mode). - - .. method:: wlan.antenna([antenna]) - - Get or set the antenna type (external or internal). - - .. method:: wlan.mac([mac_addr]) - - Get or set a 6-byte long bytes object with the MAC address. - - .. method:: wlan.irq(\*, handler, wake) - - Create a callback to be triggered when a WLAN event occurs during ``machine.SLEEP`` - mode. Events are triggered by socket activity or by WLAN connection/disconnection. - - - *handler* is the function that gets called when the IRQ is triggered. - - *wake* must be ``machine.SLEEP``. - - Returns an IRQ object. - - Constants - --------- - - .. data:: WLAN.STA - .. data:: WLAN.AP - - selects the WLAN mode - - .. data:: WLAN.WEP - .. data:: WLAN.WPA - .. data:: WLAN.WPA2 - - selects the network security - - .. data:: WLAN.INT_ANT - .. data:: WLAN.EXT_ANT - - selects the antenna type + ============= =========== + Parameter Description + ============= =========== + mac MAC address (bytes) + essid WiFi access point name (string) + channel WiFi channel (integer) + hidden Whether ESSID is hidden (boolean) + authmode Authentication mode supported (enumeration, see module constants) + password Access password (string) + dhcp_hostname The DHCP hostname to use + ============= =========== diff --git a/docs/library/pyb.ADC.rst b/docs/library/pyb.ADC.rst deleted file mode 100644 index 51021fdc1a..0000000000 --- a/docs/library/pyb.ADC.rst +++ /dev/null @@ -1,143 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.ADC: - -class ADC -- analog to digital conversion -========================================= - -.. only:: port_pyboard - - Usage:: - - import pyb - - adc = pyb.ADC(pin) # create an analog object from a pin - val = adc.read() # read an analog value - - adc = pyb.ADCAll(resolution) # create an ADCAll object - val = adc.read_channel(channel) # read the given channel - val = adc.read_core_temp() # read MCU temperature - val = adc.read_core_vbat() # read MCU VBAT - val = adc.read_core_vref() # read MCU VREF - - -Constructors ------------- - - -.. only:: port_pyboard - - .. class:: pyb.ADC(pin) - - Create an ADC object associated with the given pin. - This allows you to then read analog values on that pin. - -Methods -------- - -.. only:: port_pyboard - - .. method:: ADC.read() - - Read the value on the analog pin and return it. The returned value - will be between 0 and 4095. - - .. method:: ADC.read_timed(buf, timer) - - Read analog values into ``buf`` at a rate set by the ``timer`` object. - - ``buf`` can be bytearray or array.array for example. The ADC values have - 12-bit resolution and are stored directly into ``buf`` if its element size is - 16 bits or greater. If ``buf`` has only 8-bit elements (eg a bytearray) then - the sample resolution will be reduced to 8 bits. - - ``timer`` should be a Timer object, and a sample is read each time the timer - triggers. The timer must already be initialised and running at the desired - sampling frequency. - - To support previous behaviour of this function, ``timer`` can also be an - integer which specifies the frequency (in Hz) to sample at. In this case - Timer(6) will be automatically configured to run at the given frequency. - - Example using a Timer object (preferred way):: - - adc = pyb.ADC(pyb.Pin.board.X19) # create an ADC on pin X19 - tim = pyb.Timer(6, freq=10) # create a timer running at 10Hz - buf = bytearray(100) # creat a buffer to store the samples - adc.read_timed(buf, tim) # sample 100 values, taking 10s - - Example using an integer for the frequency:: - - adc = pyb.ADC(pyb.Pin.board.X19) # create an ADC on pin X19 - buf = bytearray(100) # create a buffer of 100 bytes - adc.read_timed(buf, 10) # read analog values into buf at 10Hz - # this will take 10 seconds to finish - for val in buf: # loop over all values - print(val) # print the value out - - This function does not allocate any memory. - -The ADCAll Object ------------------ - -.. only:: port_pyboard - - Instantiating this changes all ADC pins to analog inputs. The raw MCU temperature, - VREF and VBAT data can be accessed on ADC channels 16, 17 and 18 respectively. - Appropriate scaling will need to be applied. The temperature sensor on the chip - has poor absolute accuracy and is suitable only for detecting temperature changes. - - The ``ADCAll`` ``read_core_vbat()`` and ``read_core_vref()`` methods read - the backup battery voltage and the (1.21V nominal) reference voltage using the - 3.3V supply as a reference. Assuming the ``ADCAll`` object has been Instantiated with - ``adc = pyb.ADCAll(12)`` the 3.3V supply voltage may be calculated: - - ``v33 = 3.3 * 1.21 / adc.read_core_vref()`` - - If the 3.3V supply is correct the value of ``adc.read_core_vbat()`` will be - valid. If the supply voltage can drop below 3.3V, for example in in battery - powered systems with a discharging battery, the regulator will fail to preserve - the 3.3V supply resulting in an incorrect reading. To produce a value which will - remain valid under these circumstances use the following: - - ``vback = adc.read_core_vbat() * 1.21 / adc.read_core_vref()`` - - It is possible to access these values without incurring the side effects of ``ADCAll``:: - - def adcread(chan): # 16 temp 17 vbat 18 vref - assert chan >= 16 and chan <= 18, 'Invalid ADC channel' - start = pyb.millis() - timeout = 100 - stm.mem32[stm.RCC + stm.RCC_APB2ENR] |= 0x100 # enable ADC1 clock.0x4100 - stm.mem32[stm.ADC1 + stm.ADC_CR2] = 1 # Turn on ADC - stm.mem32[stm.ADC1 + stm.ADC_CR1] = 0 # 12 bit - if chan == 17: - stm.mem32[stm.ADC1 + stm.ADC_SMPR1] = 0x200000 # 15 cycles - stm.mem32[stm.ADC + 4] = 1 << 23 - elif chan == 18: - stm.mem32[stm.ADC1 + stm.ADC_SMPR1] = 0x1000000 - stm.mem32[stm.ADC + 4] = 0xc00000 - else: - stm.mem32[stm.ADC1 + stm.ADC_SMPR1] = 0x40000 - stm.mem32[stm.ADC + 4] = 1 << 23 - stm.mem32[stm.ADC1 + stm.ADC_SQR3] = chan - stm.mem32[stm.ADC1 + stm.ADC_CR2] = 1 | (1 << 30) | (1 << 10) # start conversion - while not stm.mem32[stm.ADC1 + stm.ADC_SR] & 2: # wait for EOC - if pyb.elapsed_millis(start) > timeout: - raise OSError('ADC timout') - data = stm.mem32[stm.ADC1 + stm.ADC_DR] # clear down EOC - stm.mem32[stm.ADC1 + stm.ADC_CR2] = 0 # Turn off ADC - return data - - def v33(): - return 4096 * 1.21 / adcread(17) - - def vbat(): - return 1.21 * 2 * adcread(18) / adcread(17) # 2:1 divider on Vbat channel - - def vref(): - return 3.3 * adcread(17) / 4096 - - def temperature(): - return 25 + 400 * (3.3 * adcread(16) / 4096 - 0.76) - - \ No newline at end of file diff --git a/docs/library/pyb.Accel.rst b/docs/library/pyb.Accel.rst deleted file mode 100644 index 9ade5c5c81..0000000000 --- a/docs/library/pyb.Accel.rst +++ /dev/null @@ -1,57 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.Accel: - -class Accel -- accelerometer control -==================================== - -Accel is an object that controls the accelerometer. Example usage:: - - accel = pyb.Accel() - for i in range(10): - print(accel.x(), accel.y(), accel.z()) - -Raw values are between -32 and 31. - - -Constructors ------------- - -.. class:: pyb.Accel() - - Create and return an accelerometer object. - -Methods -------- - -.. method:: Accel.filtered_xyz() - - Get a 3-tuple of filtered x, y and z values. - - Implementation note: this method is currently implemented as taking the - sum of 4 samples, sampled from the 3 previous calls to this function along - with the sample from the current call. Returned values are therefore 4 - times the size of what they would be from the raw x(), y() and z() calls. - -.. method:: Accel.tilt() - - Get the tilt register. - -.. method:: Accel.x() - - Get the x-axis value. - -.. method:: Accel.y() - - Get the y-axis value. - -.. method:: Accel.z() - - Get the z-axis value. - -Hardware Note -------------- - -The accelerometer uses I2C bus 1 to communicate with the processor. Consequently -when readings are being taken pins X9 and X10 should be unused (other than for -I2C). Other devices using those pins, and which therefore cannot be used -concurrently, are UART 1 and Timer 4 channels 1 and 2. diff --git a/docs/library/pyb.CAN.rst b/docs/library/pyb.CAN.rst deleted file mode 100644 index 232d04d962..0000000000 --- a/docs/library/pyb.CAN.rst +++ /dev/null @@ -1,223 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.CAN: - -class CAN -- controller area network communication bus -====================================================== - -CAN implements the standard CAN communications protocol. At -the physical level it consists of 2 lines: RX and TX. Note that -to connect the pyboard to a CAN bus you must use a CAN transceiver -to convert the CAN logic signals from the pyboard to the correct -voltage levels on the bus. - -Example usage (works without anything connected):: - - from pyb import CAN - can = CAN(1, CAN.LOOPBACK) - can.setfilter(0, CAN.LIST16, 0, (123, 124, 125, 126)) # set a filter to receive messages with id=123, 124, 125 and 126 - can.send('message!', 123) # send a message with id 123 - can.recv(0) # receive message on FIFO 0 - - -Constructors ------------- - -.. class:: pyb.CAN(bus, ...) - - Construct a CAN object on the given bus. ``bus`` can be 1-2, or 'YA' or 'YB'. - With no additional parameters, the CAN object is created but not - initialised (it has the settings from the last initialisation of - the bus, if any). If extra arguments are given, the bus is initialised. - See ``init`` for parameters of initialisation. - - The physical pins of the CAN busses are: - - - ``CAN(1)`` is on ``YA``: ``(RX, TX) = (Y3, Y4) = (PB8, PB9)`` - - ``CAN(2)`` is on ``YB``: ``(RX, TX) = (Y5, Y6) = (PB12, PB13)`` - -Class Methods -------------- -.. classmethod:: CAN.initfilterbanks(nr) - - Reset and disable all filter banks and assign how many banks should be available for CAN(1). - - STM32F405 has 28 filter banks that are shared between the two available CAN bus controllers. - This function configures how many filter banks should be assigned to each. ``nr`` is the number of banks - that will be assigned to CAN(1), the rest of the 28 are assigned to CAN(2). - At boot, 14 banks are assigned to each controller. - -Methods -------- - -.. method:: CAN.init(mode, extframe=False, prescaler=100, \*, sjw=1, bs1=6, bs2=8) - - Initialise the CAN bus with the given parameters: - - - ``mode`` is one of: NORMAL, LOOPBACK, SILENT, SILENT_LOOPBACK - - if ``extframe`` is True then the bus uses extended identifiers in the frames - (29 bits); otherwise it uses standard 11 bit identifiers - - ``prescaler`` is used to set the duration of 1 time quanta; the time quanta - will be the input clock (PCLK1, see :meth:`pyb.freq()`) divided by the prescaler - - ``sjw`` is the resynchronisation jump width in units of the time quanta; - it can be 1, 2, 3, 4 - - ``bs1`` defines the location of the sample point in units of the time quanta; - it can be between 1 and 1024 inclusive - - ``bs2`` defines the location of the transmit point in units of the time quanta; - it can be between 1 and 16 inclusive - - The time quanta tq is the basic unit of time for the CAN bus. tq is the CAN - prescaler value divided by PCLK1 (the frequency of internal peripheral bus 1); - see :meth:`pyb.freq()` to determine PCLK1. - - A single bit is made up of the synchronisation segment, which is always 1 tq. - Then follows bit segment 1, then bit segment 2. The sample point is after bit - segment 1 finishes. The transmit point is after bit segment 2 finishes. - The baud rate will be 1/bittime, where the bittime is 1 + BS1 + BS2 multiplied - by the time quanta tq. - - For example, with PCLK1=42MHz, prescaler=100, sjw=1, bs1=6, bs2=8, the value of - tq is 2.38 microseconds. The bittime is 35.7 microseconds, and the baudrate - is 28kHz. - - See page 680 of the STM32F405 datasheet for more details. - -.. method:: CAN.deinit() - - Turn off the CAN bus. - -.. method:: CAN.setfilter(bank, mode, fifo, params, \*, rtr) - - Configure a filter bank: - - - ``bank`` is the filter bank that is to be configured. - - ``mode`` is the mode the filter should operate in. - - ``fifo`` is which fifo (0 or 1) a message should be stored in, if it is accepted by this filter. - - ``params`` is an array of values the defines the filter. The contents of the array depends on the ``mode`` argument. - - +-----------+---------------------------------------------------------+ - |``mode`` |contents of parameter array | - +===========+=========================================================+ - |CAN.LIST16 |Four 16 bit ids that will be accepted | - +-----------+---------------------------------------------------------+ - |CAN.LIST32 |Two 32 bit ids that will be accepted | - +-----------+---------------------------------------------------------+ - |CAN.MASK16 |Two 16 bit id/mask pairs. E.g. (1, 3, 4, 4) | - | | | The first pair, 1 and 3 will accept all ids | - | | | that have bit 0 = 1 and bit 1 = 0. | - | | | The second pair, 4 and 4, will accept all ids | - | | | that have bit 2 = 1. | - +-----------+---------------------------------------------------------+ - |CAN.MASK32 |As with CAN.MASK16 but with only one 32 bit id/mask pair.| - +-----------+---------------------------------------------------------+ - - - ``rtr`` is an array of booleans that states if a filter should accept a - remote transmission request message. If this argument is not given - then it defaults to False for all entries. The length of the array - depends on the ``mode`` argument. - - +-----------+----------------------+ - |``mode`` |length of rtr array | - +===========+======================+ - |CAN.LIST16 |4 | - +-----------+----------------------+ - |CAN.LIST32 |2 | - +-----------+----------------------+ - |CAN.MASK16 |2 | - +-----------+----------------------+ - |CAN.MASK32 |1 | - +-----------+----------------------+ - -.. method:: CAN.clearfilter(bank) - - Clear and disables a filter bank: - - - ``bank`` is the filter bank that is to be cleared. - -.. method:: CAN.any(fifo) - - Return ``True`` if any message waiting on the FIFO, else ``False``. - -.. method:: CAN.recv(fifo, \*, timeout=5000) - - Receive data on the bus: - - - ``fifo`` is an integer, which is the FIFO to receive on - - ``timeout`` is the timeout in milliseconds to wait for the receive. - - Return value: A tuple containing four values. - - - The id of the message. - - A boolean that indicates if the message is an RTR message. - - The FMI (Filter Match Index) value. - - An array containing the data. - -.. method:: CAN.send(data, id, \*, timeout=0, rtr=False) - - Send a message on the bus: - - - ``data`` is the data to send (an integer to send, or a buffer object). - - ``id`` is the id of the message to be sent. - - ``timeout`` is the timeout in milliseconds to wait for the send. - - ``rtr`` is a boolean that specifies if the message shall be sent as - a remote transmission request. If ``rtr`` is True then only the length - of ``data`` is used to fill in the DLC slot of the frame; the actual - bytes in ``data`` are unused. - - If timeout is 0 the message is placed in a buffer in one of three hardware - buffers and the method returns immediately. If all three buffers are in use - an exception is thrown. If timeout is not 0, the method waits until the - message is transmitted. If the message can't be transmitted within the - specified time an exception is thrown. - - Return value: ``None``. - -.. method:: CAN.rxcallback(fifo, fun) - - Register a function to be called when a message is accepted into a empty fifo: - - - ``fifo`` is the receiving fifo. - - ``fun`` is the function to be called when the fifo becomes non empty. - - The callback function takes two arguments the first is the can object it self the second is - a integer that indicates the reason for the callback. - - +--------+------------------------------------------------+ - | Reason | | - +========+================================================+ - | 0 | A message has been accepted into a empty FIFO. | - +--------+------------------------------------------------+ - | 1 | The FIFO is full | - +--------+------------------------------------------------+ - | 2 | A message has been lost due to a full FIFO | - +--------+------------------------------------------------+ - - Example use of rxcallback:: - - def cb0(bus, reason): - print('cb0') - if reason == 0: - print('pending') - if reason == 1: - print('full') - if reason == 2: - print('overflow') - - can = CAN(1, CAN.LOOPBACK) - can.rxcallback(0, cb0) - -Constants ---------- - -.. data:: CAN.NORMAL -.. data:: CAN.LOOPBACK -.. data:: CAN.SILENT -.. data:: CAN.SILENT_LOOPBACK - - the mode of the CAN bus - -.. data:: CAN.LIST16 -.. data:: CAN.MASK16 -.. data:: CAN.LIST32 -.. data:: CAN.MASK32 - - the operation mode of a filter diff --git a/docs/library/pyb.DAC.rst b/docs/library/pyb.DAC.rst deleted file mode 100644 index fd786b63b6..0000000000 --- a/docs/library/pyb.DAC.rst +++ /dev/null @@ -1,109 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.DAC: - -class DAC -- digital to analog conversion -========================================= - -The DAC is used to output analog values (a specific voltage) on pin X5 or pin X6. -The voltage will be between 0 and 3.3V. - -*This module will undergo changes to the API.* - -Example usage:: - - from pyb import DAC - - dac = DAC(1) # create DAC 1 on pin X5 - dac.write(128) # write a value to the DAC (makes X5 1.65V) - - dac = DAC(1, bits=12) # use 12 bit resolution - dac.write(4095) # output maximum value, 3.3V - -To output a continuous sine-wave:: - - import math - from pyb import DAC - - # create a buffer containing a sine-wave - buf = bytearray(100) - for i in range(len(buf)): - buf[i] = 128 + int(127 * math.sin(2 * math.pi * i / len(buf))) - - # output the sine-wave at 400Hz - dac = DAC(1) - dac.write_timed(buf, 400 * len(buf), mode=DAC.CIRCULAR) - -To output a continuous sine-wave at 12-bit resolution:: - - import math - from array import array - from pyb import DAC - - # create a buffer containing a sine-wave, using half-word samples - buf = array('H', 2048 + int(2047 * math.sin(2 * math.pi * i / 128)) for i in range(128)) - - # output the sine-wave at 400Hz - dac = DAC(1, bits=12) - dac.write_timed(buf, 400 * len(buf), mode=DAC.CIRCULAR) - -Constructors ------------- - -.. class:: pyb.DAC(port, bits=8) - - Construct a new DAC object. - - ``port`` can be a pin object, or an integer (1 or 2). - DAC(1) is on pin X5 and DAC(2) is on pin X6. - - ``bits`` is an integer specifying the resolution, and can be 8 or 12. - The maximum value for the write and write_timed methods will be - 2\*\*``bits``-1. - -Methods -------- - -.. method:: DAC.init(bits=8) - - Reinitialise the DAC. ``bits`` can be 8 or 12. - -.. method:: DAC.deinit() - - De-initialise the DAC making its pin available for other uses. - -.. method:: DAC.noise(freq) - - Generate a pseudo-random noise signal. A new random sample is written - to the DAC output at the given frequency. - -.. method:: DAC.triangle(freq) - - Generate a triangle wave. The value on the DAC output changes at - the given frequency, and the frequency of the repeating triangle wave - itself is 2048 times smaller. - -.. method:: DAC.write(value) - - Direct access to the DAC output. The minimum value is 0. The maximum - value is 2\*\*``bits``-1, where ``bits`` is set when creating the DAC - object or by using the ``init`` method. - -.. method:: DAC.write_timed(data, freq, \*, mode=DAC.NORMAL) - - Initiates a burst of RAM to DAC using a DMA transfer. - The input data is treated as an array of bytes in 8-bit mode, and - an array of unsigned half-words (array typecode 'H') in 12-bit mode. - - ``freq`` can be an integer specifying the frequency to write the DAC - samples at, using Timer(6). Or it can be an already-initialised - Timer object which is used to trigger the DAC sample. Valid timers - are 2, 4, 5, 6, 7 and 8. - - ``mode`` can be ``DAC.NORMAL`` or ``DAC.CIRCULAR``. - - Example using both DACs at the same time:: - - dac1 = DAC(1) - dac2 = DAC(2) - dac1.write_timed(buf1, pyb.Timer(6, freq=100), mode=DAC.CIRCULAR) - dac2.write_timed(buf2, pyb.Timer(7, freq=200), mode=DAC.CIRCULAR) diff --git a/docs/library/pyb.ExtInt.rst b/docs/library/pyb.ExtInt.rst deleted file mode 100644 index 814217cef0..0000000000 --- a/docs/library/pyb.ExtInt.rst +++ /dev/null @@ -1,114 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.ExtInt: - -class ExtInt -- configure I/O pins to interrupt on external events -================================================================== - -There are a total of 22 interrupt lines. 16 of these can come from GPIO pins -and the remaining 6 are from internal sources. - -For lines 0 through 15, a given line can map to the corresponding line from an -arbitrary port. So line 0 can map to Px0 where x is A, B, C, ... and -line 1 can map to Px1 where x is A, B, C, ... :: - - def callback(line): - print("line =", line) - -Note: ExtInt will automatically configure the gpio line as an input. :: - - extint = pyb.ExtInt(pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, callback) - -Now every time a falling edge is seen on the X1 pin, the callback will be -called. Caution: mechanical pushbuttons have "bounce" and pushing or -releasing a switch will often generate multiple edges. -See: http://www.eng.utah.edu/~cs5780/debouncing.pdf for a detailed -explanation, along with various techniques for debouncing. - -Trying to register 2 callbacks onto the same pin will throw an exception. - -If pin is passed as an integer, then it is assumed to map to one of the -internal interrupt sources, and must be in the range 16 through 22. - -All other pin objects go through the pin mapper to come up with one of the -gpio pins. :: - - extint = pyb.ExtInt(pin, mode, pull, callback) - -Valid modes are pyb.ExtInt.IRQ_RISING, pyb.ExtInt.IRQ_FALLING, -pyb.ExtInt.IRQ_RISING_FALLING, pyb.ExtInt.EVT_RISING, -pyb.ExtInt.EVT_FALLING, and pyb.ExtInt.EVT_RISING_FALLING. - -Only the IRQ_xxx modes have been tested. The EVT_xxx modes have -something to do with sleep mode and the WFE instruction. - -Valid pull values are pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN, pyb.Pin.PULL_NONE. - -There is also a C API, so that drivers which require EXTI interrupt lines -can also use this code. See extint.h for the available functions and -usrsw.h for an example of using this. - - -Constructors ------------- - -.. class:: pyb.ExtInt(pin, mode, pull, callback) - - Create an ExtInt object: - - - ``pin`` is the pin on which to enable the interrupt (can be a pin object or any valid pin name). - - ``mode`` can be one of: - - ``ExtInt.IRQ_RISING`` - trigger on a rising edge; - - ``ExtInt.IRQ_FALLING`` - trigger on a falling edge; - - ``ExtInt.IRQ_RISING_FALLING`` - trigger on a rising or falling edge. - - ``pull`` can be one of: - - ``pyb.Pin.PULL_NONE`` - no pull up or down resistors; - - ``pyb.Pin.PULL_UP`` - enable the pull-up resistor; - - ``pyb.Pin.PULL_DOWN`` - enable the pull-down resistor. - - ``callback`` is the function to call when the interrupt triggers. The - callback function must accept exactly 1 argument, which is the line that - triggered the interrupt. - - -Class methods -------------- - -.. classmethod:: ExtInt.regs() - - Dump the values of the EXTI registers. - - -Methods -------- - -.. method:: ExtInt.disable() - - Disable the interrupt associated with the ExtInt object. - This could be useful for debouncing. - -.. method:: ExtInt.enable() - - Enable a disabled interrupt. - -.. method:: ExtInt.line() - - Return the line number that the pin is mapped to. - -.. method:: ExtInt.swint() - - Trigger the callback from software. - - -Constants ---------- - -.. data:: ExtInt.IRQ_FALLING - - interrupt on a falling edge - -.. data:: ExtInt.IRQ_RISING - - interrupt on a rising edge - -.. data:: ExtInt.IRQ_RISING_FALLING - - interrupt on a rising or falling edge diff --git a/docs/library/pyb.I2C.rst b/docs/library/pyb.I2C.rst deleted file mode 100644 index 7400318902..0000000000 --- a/docs/library/pyb.I2C.rst +++ /dev/null @@ -1,175 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.I2C: - -class I2C -- a two-wire serial protocol -======================================= - -I2C is a two-wire protocol for communicating between devices. At the physical -level it consists of 2 wires: SCL and SDA, the clock and data lines respectively. - -I2C objects are created attached to a specific bus. They can be initialised -when created, or initialised later on. - -.. only:: port_pyboard - - Example:: - - from pyb import I2C - - i2c = I2C(1) # create on bus 1 - i2c = I2C(1, I2C.MASTER) # create and init as a master - i2c.init(I2C.MASTER, baudrate=20000) # init as a master - i2c.init(I2C.SLAVE, addr=0x42) # init as a slave with given address - i2c.deinit() # turn off the peripheral - -Printing the i2c object gives you information about its configuration. - -.. only:: port_pyboard - - The basic methods are send and recv:: - - i2c.send('abc') # send 3 bytes - i2c.send(0x42) # send a single byte, given by the number - data = i2c.recv(3) # receive 3 bytes - - To receive inplace, first create a bytearray:: - - data = bytearray(3) # create a buffer - i2c.recv(data) # receive 3 bytes, writing them into data - - You can specify a timeout (in ms):: - - i2c.send(b'123', timeout=2000) # timeout after 2 seconds - - A master must specify the recipient's address:: - - i2c.init(I2C.MASTER) - i2c.send('123', 0x42) # send 3 bytes to slave with address 0x42 - i2c.send(b'456', addr=0x42) # keyword for address - - Master also has other methods:: - - i2c.is_ready(0x42) # check if slave 0x42 is ready - i2c.scan() # scan for slaves on the bus, returning - # a list of valid addresses - i2c.mem_read(3, 0x42, 2) # read 3 bytes from memory of slave 0x42, - # starting at address 2 in the slave - i2c.mem_write('abc', 0x42, 2, timeout=1000) # write 'abc' (3 bytes) to memory of slave 0x42 - # starting at address 2 in the slave, timeout after 1 second - -Constructors ------------- - -.. only:: port_pyboard - - .. class:: pyb.I2C(bus, ...) - - Construct an I2C object on the given bus. ``bus`` can be 1 or 2, 'X' or - 'Y'. With no additional parameters, the I2C object is created but not - initialised (it has the settings from the last initialisation of - the bus, if any). If extra arguments are given, the bus is initialised. - See ``init`` for parameters of initialisation. - - The physical pins of the I2C busses on Pyboards V1.0 and V1.1 are: - - - ``I2C(1)`` is on the X position: ``(SCL, SDA) = (X9, X10) = (PB6, PB7)`` - - ``I2C(2)`` is on the Y position: ``(SCL, SDA) = (Y9, Y10) = (PB10, PB11)`` - - On the Pyboard Lite: - - - ``I2C(1)`` is on the X position: ``(SCL, SDA) = (X9, X10) = (PB6, PB7)`` - - ``I2C(3)`` is on the Y position: ``(SCL, SDA) = (Y9, Y10) = (PA8, PB8)`` - - Calling the constructor with 'X' or 'Y' enables portability between Pyboard - types. - -Methods -------- - -.. method:: I2C.deinit() - - Turn off the I2C bus. - -.. only:: port_pyboard - - .. method:: I2C.init(mode, \*, addr=0x12, baudrate=400000, gencall=False, dma=False) - - Initialise the I2C bus with the given parameters: - - - ``mode`` must be either ``I2C.MASTER`` or ``I2C.SLAVE`` - - ``addr`` is the 7-bit address (only sensible for a slave) - - ``baudrate`` is the SCL clock rate (only sensible for a master) - - ``gencall`` is whether to support general call mode - - ``dma`` is whether to allow the use of DMA for the I2C transfers (note - that DMA transfers have more precise timing but currently do not handle bus - errors properly) - - .. method:: I2C.is_ready(addr) - - Check if an I2C device responds to the given address. Only valid when in master mode. - - .. method:: I2C.mem_read(data, addr, memaddr, \*, timeout=5000, addr_size=8) - - Read from the memory of an I2C device: - - - ``data`` can be an integer (number of bytes to read) or a buffer to read into - - ``addr`` is the I2C device address - - ``memaddr`` is the memory location within the I2C device - - ``timeout`` is the timeout in milliseconds to wait for the read - - ``addr_size`` selects width of memaddr: 8 or 16 bits - - Returns the read data. - This is only valid in master mode. - - .. method:: I2C.mem_write(data, addr, memaddr, \*, timeout=5000, addr_size=8) - - Write to the memory of an I2C device: - - - ``data`` can be an integer or a buffer to write from - - ``addr`` is the I2C device address - - ``memaddr`` is the memory location within the I2C device - - ``timeout`` is the timeout in milliseconds to wait for the write - - ``addr_size`` selects width of memaddr: 8 or 16 bits - - Returns ``None``. - This is only valid in master mode. - - .. method:: I2C.recv(recv, addr=0x00, \*, timeout=5000) - - Receive data on the bus: - - - ``recv`` can be an integer, which is the number of bytes to receive, - or a mutable buffer, which will be filled with received bytes - - ``addr`` is the address to receive from (only required in master mode) - - ``timeout`` is the timeout in milliseconds to wait for the receive - - Return value: if ``recv`` is an integer then a new buffer of the bytes received, - otherwise the same buffer that was passed in to ``recv``. - - .. method:: I2C.send(send, addr=0x00, \*, timeout=5000) - - Send data on the bus: - - - ``send`` is the data to send (an integer to send, or a buffer object) - - ``addr`` is the address to send to (only required in master mode) - - ``timeout`` is the timeout in milliseconds to wait for the send - - Return value: ``None``. - -.. method:: I2C.scan() - - Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond. - Only valid when in master mode. - -Constants ---------- - -.. data:: I2C.MASTER - - for initialising the bus to master mode - -.. only:: port_pyboard - - .. data:: I2C.SLAVE - - for initialising the bus to slave mode diff --git a/docs/library/pyb.LCD.rst b/docs/library/pyb.LCD.rst deleted file mode 100644 index 5ab127edcd..0000000000 --- a/docs/library/pyb.LCD.rst +++ /dev/null @@ -1,97 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.LCD: - -class LCD -- LCD control for the LCD touch-sensor pyskin -======================================================== - -The LCD class is used to control the LCD on the LCD touch-sensor pyskin, -LCD32MKv1.0. The LCD is a 128x32 pixel monochrome screen, part NHD-C12832A1Z. - -The pyskin must be connected in either the X or Y positions, and then -an LCD object is made using:: - - lcd = pyb.LCD('X') # if pyskin is in the X position - lcd = pyb.LCD('Y') # if pyskin is in the Y position - -Then you can use:: - - lcd.light(True) # turn the backlight on - lcd.write('Hello world!\n') # print text to the screen - -This driver implements a double buffer for setting/getting pixels. -For example, to make a bouncing dot, try:: - - x = y = 0 - dx = dy = 1 - while True: - # update the dot's position - x += dx - y += dy - - # make the dot bounce of the edges of the screen - if x <= 0 or x >= 127: dx = -dx - if y <= 0 or y >= 31: dy = -dy - - lcd.fill(0) # clear the buffer - lcd.pixel(x, y, 1) # draw the dot - lcd.show() # show the buffer - pyb.delay(50) # pause for 50ms - - -Constructors ------------- - -.. class:: pyb.LCD(skin_position) - - Construct an LCD object in the given skin position. ``skin_position`` can be 'X' or 'Y', and - should match the position where the LCD pyskin is plugged in. - - -Methods -------- - -.. method:: LCD.command(instr_data, buf) - - Send an arbitrary command to the LCD. Pass 0 for ``instr_data`` to send an - instruction, otherwise pass 1 to send data. ``buf`` is a buffer with the - instructions/data to send. - -.. method:: LCD.contrast(value) - - Set the contrast of the LCD. Valid values are between 0 and 47. - -.. method:: LCD.fill(colour) - - Fill the screen with the given colour (0 or 1 for white or black). - - This method writes to the hidden buffer. Use ``show()`` to show the buffer. - -.. method:: LCD.get(x, y) - - Get the pixel at the position ``(x, y)``. Returns 0 or 1. - - This method reads from the visible buffer. - -.. method:: LCD.light(value) - - Turn the backlight on/off. True or 1 turns it on, False or 0 turns it off. - -.. method:: LCD.pixel(x, y, colour) - - Set the pixel at ``(x, y)`` to the given colour (0 or 1). - - This method writes to the hidden buffer. Use ``show()`` to show the buffer. - -.. method:: LCD.show() - - Show the hidden buffer on the screen. - -.. method:: LCD.text(str, x, y, colour) - - Draw the given text to the position ``(x, y)`` using the given colour (0 or 1). - - This method writes to the hidden buffer. Use ``show()`` to show the buffer. - -.. method:: LCD.write(str) - - Write the string ``str`` to the screen. It will appear immediately. diff --git a/docs/library/pyb.LED.rst b/docs/library/pyb.LED.rst deleted file mode 100644 index 1ab73a69c9..0000000000 --- a/docs/library/pyb.LED.rst +++ /dev/null @@ -1,46 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.LED: - -class LED -- LED object -======================= - -The LED object controls an individual LED (Light Emitting Diode). - - -Constructors ------------- - -.. class:: pyb.LED(id) - - Create an LED object associated with the given LED: - - - ``id`` is the LED number, 1-4. - - -Methods -------- - -.. method:: LED.intensity([value]) - - Get or set the LED intensity. Intensity ranges between 0 (off) and 255 (full on). - If no argument is given, return the LED intensity. - If an argument is given, set the LED intensity and return ``None``. - - *Note:* Only LED(3) and LED(4) can have a smoothly varying intensity, and - they use timer PWM to implement it. LED(3) uses Timer(2) and LED(4) uses - Timer(3). These timers are only configured for PWM if the intensity of the - relevant LED is set to a value between 1 and 254. Otherwise the timers are - free for general purpose use. - -.. method:: LED.off() - - Turn the LED off. - -.. method:: LED.on() - - Turn the LED on, to maximum intensity. - -.. method:: LED.toggle() - - Toggle the LED between on (maximum intensity) and off. If the LED is at - non-zero intensity then it is considered "on" and toggle will turn it off. diff --git a/docs/library/pyb.Pin.rst b/docs/library/pyb.Pin.rst deleted file mode 100644 index b766c5280c..0000000000 --- a/docs/library/pyb.Pin.rst +++ /dev/null @@ -1,280 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.Pin: - -class Pin -- control I/O pins -============================= - -A pin is the basic object to control I/O pins. It has methods to set -the mode of the pin (input, output, etc) and methods to get and set the -digital logic level. For analog control of a pin, see the ADC class. - -Usage Model: - -.. only:: port_pyboard - - All Board Pins are predefined as pyb.Pin.board.Name:: - - x1_pin = pyb.Pin.board.X1 - - g = pyb.Pin(pyb.Pin.board.X1, pyb.Pin.IN) - - CPU pins which correspond to the board pins are available - as ``pyb.cpu.Name``. For the CPU pins, the names are the port letter - followed by the pin number. On the PYBv1.0, ``pyb.Pin.board.X1`` and - ``pyb.Pin.cpu.A0`` are the same pin. - - You can also use strings:: - - g = pyb.Pin('X1', pyb.Pin.OUT_PP) - - Users can add their own names:: - - MyMapperDict = { 'LeftMotorDir' : pyb.Pin.cpu.C12 } - pyb.Pin.dict(MyMapperDict) - g = pyb.Pin("LeftMotorDir", pyb.Pin.OUT_OD) - - and can query mappings:: - - pin = pyb.Pin("LeftMotorDir") - - Users can also add their own mapping function:: - - def MyMapper(pin_name): - if pin_name == "LeftMotorDir": - return pyb.Pin.cpu.A0 - - pyb.Pin.mapper(MyMapper) - - So, if you were to call: ``pyb.Pin("LeftMotorDir", pyb.Pin.OUT_PP)`` - then ``"LeftMotorDir"`` is passed directly to the mapper function. - - To summarise, the following order determines how things get mapped into - an ordinal pin number: - - 1. Directly specify a pin object - 2. User supplied mapping function - 3. User supplied mapping (object must be usable as a dictionary key) - 4. Supply a string which matches a board pin - 5. Supply a string which matches a CPU port/pin - - You can set ``pyb.Pin.debug(True)`` to get some debug information about - how a particular object gets mapped to a pin. - - When a pin has the ``Pin.PULL_UP`` or ``Pin.PULL_DOWN`` pull-mode enabled, - that pin has an effective 40k Ohm resistor pulling it to 3V3 or GND - respectively (except pin Y5 which has 11k Ohm resistors). - - Now every time a falling edge is seen on the gpio pin, the callback will be - executed. Caution: mechanical push buttons have "bounce" and pushing or - releasing a switch will often generate multiple edges. - See: http://www.eng.utah.edu/~cs5780/debouncing.pdf for a detailed - explanation, along with various techniques for debouncing. - - All pin objects go through the pin mapper to come up with one of the - gpio pins. - -Constructors ------------- - -.. class:: pyb.Pin(id, ...) - - Create a new Pin object associated with the id. If additional arguments are given, - they are used to initialise the pin. See :meth:`pin.init`. - -.. only:: port_pyboard - - Class methods - ------------- - - .. classmethod:: Pin.debug([state]) - - Get or set the debugging state (``True`` or ``False`` for on or off). - - .. classmethod:: Pin.dict([dict]) - - Get or set the pin mapper dictionary. - - .. classmethod:: Pin.mapper([fun]) - - Get or set the pin mapper function. - - -Methods -------- - -.. only:: port_pyboard - - .. method:: Pin.init(mode, pull=Pin.PULL_NONE, af=-1) - - Initialise the pin: - - - ``mode`` can be one of: - - - ``Pin.IN`` - configure the pin for input; - - ``Pin.OUT_PP`` - configure the pin for output, with push-pull control; - - ``Pin.OUT_OD`` - configure the pin for output, with open-drain control; - - ``Pin.AF_PP`` - configure the pin for alternate function, pull-pull; - - ``Pin.AF_OD`` - configure the pin for alternate function, open-drain; - - ``Pin.ANALOG`` - configure the pin for analog. - - - ``pull`` can be one of: - - - ``Pin.PULL_NONE`` - no pull up or down resistors; - - ``Pin.PULL_UP`` - enable the pull-up resistor; - - ``Pin.PULL_DOWN`` - enable the pull-down resistor. - - - when mode is ``Pin.AF_PP`` or ``Pin.AF_OD``, then af can be the index or name - of one of the alternate functions associated with a pin. - - Returns: ``None``. - -.. method:: Pin.value([value]) - - Get or set the digital logic level of the pin: - - - With no argument, return 0 or 1 depending on the logic level of the pin. - - With ``value`` given, set the logic level of the pin. ``value`` can be - anything that converts to a boolean. If it converts to ``True``, the pin - is set high, otherwise it is set low. - -.. only:: port_pyboard - - .. method:: Pin.__str__() - - Return a string describing the pin object. - - .. method:: Pin.af() - - Returns the currently configured alternate-function of the pin. The - integer returned will match one of the allowed constants for the af - argument to the init function. - - .. method:: Pin.af_list() - - Returns an array of alternate functions available for this pin. - - .. method:: Pin.gpio() - - Returns the base address of the GPIO block associated with this pin. - - .. method:: Pin.mode() - - Returns the currently configured mode of the pin. The integer returned - will match one of the allowed constants for the mode argument to the init - function. - - .. method:: Pin.name() - - Get the pin name. - - .. method:: Pin.names() - - Returns the cpu and board names for this pin. - - .. method:: Pin.pin() - - Get the pin number. - - .. method:: Pin.port() - - Get the pin port. - -.. method:: Pin.pull() - - Returns the currently configured pull of the pin. The integer returned - will match one of the allowed constants for the pull argument to the init - function. - -Constants ---------- - -.. only:: port_pyboard - - .. data:: Pin.AF_OD - - initialise the pin to alternate-function mode with an open-drain drive - - .. data:: Pin.AF_PP - - initialise the pin to alternate-function mode with a push-pull drive - - .. data:: Pin.ANALOG - - initialise the pin to analog mode - - .. data:: Pin.IN - - initialise the pin to input mode - - .. data:: Pin.OUT_OD - - initialise the pin to output mode with an open-drain drive - - .. data:: Pin.OUT_PP - - initialise the pin to output mode with a push-pull drive - - .. data:: Pin.PULL_DOWN - - enable the pull-down resistor on the pin - - .. data:: Pin.PULL_NONE - - don't enable any pull up or down resistors on the pin - - .. data:: Pin.PULL_UP - - enable the pull-up resistor on the pin - -.. only:: port_pyboard - - class PinAF -- Pin Alternate Functions - ====================================== - - A Pin represents a physical pin on the microprocessor. Each pin - can have a variety of functions (GPIO, I2C SDA, etc). Each PinAF - object represents a particular function for a pin. - - Usage Model:: - - x3 = pyb.Pin.board.X3 - x3_af = x3.af_list() - - x3_af will now contain an array of PinAF objects which are available on - pin X3. - - For the pyboard, x3_af would contain: - [Pin.AF1_TIM2, Pin.AF2_TIM5, Pin.AF3_TIM9, Pin.AF7_USART2] - - Normally, each peripheral would configure the af automatically, but sometimes - the same function is available on multiple pins, and having more control - is desired. - - To configure X3 to expose TIM2_CH3, you could use:: - - pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=pyb.Pin.AF1_TIM2) - - or:: - - pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=1) - - Methods - ------- - - .. method:: pinaf.__str__() - - Return a string describing the alternate function. - - .. method:: pinaf.index() - - Return the alternate function index. - - .. method:: pinaf.name() - - Return the name of the alternate function. - - .. method:: pinaf.reg() - - Return the base register associated with the peripheral assigned to this - alternate function. For example, if the alternate function were TIM2_CH3 - this would return stm.TIM2 diff --git a/docs/library/pyb.RTC.rst b/docs/library/pyb.RTC.rst deleted file mode 100644 index 2628554526..0000000000 --- a/docs/library/pyb.RTC.rst +++ /dev/null @@ -1,83 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.RTC: - -class RTC -- real time clock -============================ - -The RTC is and independent clock that keeps track of the date -and time. - -Example usage:: - - rtc = pyb.RTC() - rtc.datetime((2014, 5, 1, 4, 13, 0, 0, 0)) - print(rtc.datetime()) - - -Constructors ------------- - -.. class:: pyb.RTC() - - Create an RTC object. - - -Methods -------- - -.. method:: RTC.datetime([datetimetuple]) - - Get or set the date and time of the RTC. - - With no arguments, this method returns an 8-tuple with the current - date and time. With 1 argument (being an 8-tuple) it sets the date - and time. - - .. only:: port_pyboard - - The 8-tuple has the following format: - - (year, month, day, weekday, hours, minutes, seconds, subseconds) - - ``weekday`` is 1-7 for Monday through Sunday. - - ``subseconds`` counts down from 255 to 0 - -.. only:: port_pyboard - - .. method:: RTC.wakeup(timeout, callback=None) - - Set the RTC wakeup timer to trigger repeatedly at every ``timeout`` - milliseconds. This trigger can wake the pyboard from both the sleep - states: :meth:`pyb.stop` and :meth:`pyb.standby`. - - If ``timeout`` is ``None`` then the wakeup timer is disabled. - - If ``callback`` is given then it is executed at every trigger of the - wakeup timer. ``callback`` must take exactly one argument. - - .. method:: RTC.info() - - Get information about the startup time and reset source. - - - The lower 0xffff are the number of milliseconds the RTC took to - start up. - - Bit 0x10000 is set if a power-on reset occurred. - - Bit 0x20000 is set if an external reset occurred - - .. method:: RTC.calibration(cal) - - Get or set RTC calibration. - - With no arguments, ``calibration()`` returns the current calibration - value, which is an integer in the range [-511 : 512]. With one - argument it sets the RTC calibration. - - The RTC Smooth Calibration mechanism adjusts the RTC clock rate by - adding or subtracting the given number of ticks from the 32768 Hz - clock over a 32 second period (corresponding to 2^20 clock ticks.) - Each tick added will speed up the clock by 1 part in 2^20, or 0.954 - ppm; likewise the RTC clock it slowed by negative values. The - usable calibration range is: - (-511 * 0.954) ~= -487.5 ppm up to (512 * 0.954) ~= 488.5 ppm - diff --git a/docs/library/pyb.SPI.rst b/docs/library/pyb.SPI.rst deleted file mode 100644 index fd110be190..0000000000 --- a/docs/library/pyb.SPI.rst +++ /dev/null @@ -1,132 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.SPI: - -class SPI -- a master-driven serial protocol -============================================ - -SPI is a serial protocol that is driven by a master. At the physical level -there are 3 lines: SCK, MOSI, MISO. - -.. only:: port_pyboard - - See usage model of I2C; SPI is very similar. Main difference is - parameters to init the SPI bus:: - - from pyb import SPI - spi = SPI(1, SPI.MASTER, baudrate=600000, polarity=1, phase=0, crc=0x7) - - Only required parameter is mode, SPI.MASTER or SPI.SLAVE. Polarity can be - 0 or 1, and is the level the idle clock line sits at. Phase can be 0 or 1 - to sample data on the first or second clock edge respectively. Crc can be - None for no CRC, or a polynomial specifier. - - Additional methods for SPI:: - - data = spi.send_recv(b'1234') # send 4 bytes and receive 4 bytes - buf = bytearray(4) - spi.send_recv(b'1234', buf) # send 4 bytes and receive 4 into buf - spi.send_recv(buf, buf) # send/recv 4 bytes from/to buf - -Constructors ------------- - -.. only:: port_pyboard - - .. class:: pyb.SPI(bus, ...) - - Construct an SPI object on the given bus. ``bus`` can be 1 or 2, or - 'X' or 'Y'. With no additional parameters, the SPI object is created but - not initialised (it has the settings from the last initialisation of - the bus, if any). If extra arguments are given, the bus is initialised. - See ``init`` for parameters of initialisation. - - The physical pins of the SPI busses are: - - - ``SPI(1)`` is on the X position: ``(NSS, SCK, MISO, MOSI) = (X5, X6, X7, X8) = (PA4, PA5, PA6, PA7)`` - - ``SPI(2)`` is on the Y position: ``(NSS, SCK, MISO, MOSI) = (Y5, Y6, Y7, Y8) = (PB12, PB13, PB14, PB15)`` - - At the moment, the NSS pin is not used by the SPI driver and is free - for other use. - -Methods -------- - -.. method:: SPI.deinit() - - Turn off the SPI bus. - -.. only:: port_pyboard - - .. method:: SPI.init(mode, baudrate=328125, \*, prescaler, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False, crc=None) - - Initialise the SPI bus with the given parameters: - - - ``mode`` must be either ``SPI.MASTER`` or ``SPI.SLAVE``. - - ``baudrate`` is the SCK clock rate (only sensible for a master). - - ``prescaler`` is the prescaler to use to derive SCK from the APB bus frequency; - use of ``prescaler`` overrides ``baudrate``. - - ``polarity`` can be 0 or 1, and is the level the idle clock line sits at. - - ``phase`` can be 0 or 1 to sample data on the first or second clock edge - respectively. - - ``bits`` can be 8 or 16, and is the number of bits in each transferred word. - - ``firstbit`` can be ``SPI.MSB`` or ``SPI.LSB``. - - ``crc`` can be None for no CRC, or a polynomial specifier. - - Note that the SPI clock frequency will not always be the requested baudrate. - The hardware only supports baudrates that are the APB bus frequency - (see :meth:`pyb.freq`) divided by a prescaler, which can be 2, 4, 8, 16, 32, - 64, 128 or 256. SPI(1) is on AHB2, and SPI(2) is on AHB1. For precise - control over the SPI clock frequency, specify ``prescaler`` instead of - ``baudrate``. - - Printing the SPI object will show you the computed baudrate and the chosen - prescaler. - -.. only:: port_pyboard - - .. method:: SPI.recv(recv, \*, timeout=5000) - - Receive data on the bus: - - - ``recv`` can be an integer, which is the number of bytes to receive, - or a mutable buffer, which will be filled with received bytes. - - ``timeout`` is the timeout in milliseconds to wait for the receive. - - Return value: if ``recv`` is an integer then a new buffer of the bytes received, - otherwise the same buffer that was passed in to ``recv``. - - .. method:: SPI.send(send, \*, timeout=5000) - - Send data on the bus: - - - ``send`` is the data to send (an integer to send, or a buffer object). - - ``timeout`` is the timeout in milliseconds to wait for the send. - - Return value: ``None``. - - .. method:: SPI.send_recv(send, recv=None, \*, timeout=5000) - - Send and receive data on the bus at the same time: - - - ``send`` is the data to send (an integer to send, or a buffer object). - - ``recv`` is a mutable buffer which will be filled with received bytes. - It can be the same as ``send``, or omitted. If omitted, a new buffer will - be created. - - ``timeout`` is the timeout in milliseconds to wait for the receive. - - Return value: the buffer with the received bytes. - -Constants ---------- - -.. only:: port_pyboard - - .. data:: SPI.MASTER - .. data:: SPI.SLAVE - - for initialising the SPI bus to master or slave mode - - .. data:: SPI.LSB - .. data:: SPI.MSB - - set the first bit to be the least or most significant bit diff --git a/docs/library/pyb.Servo.rst b/docs/library/pyb.Servo.rst deleted file mode 100644 index b3ce71d11a..0000000000 --- a/docs/library/pyb.Servo.rst +++ /dev/null @@ -1,80 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.Servo: - -class Servo -- 3-wire hobby servo driver -======================================== - -Servo objects control standard hobby servo motors with 3-wires (ground, power, -signal). There are 4 positions on the pyboard where these motors can be plugged -in: pins X1 through X4 are the signal pins, and next to them are 4 sets of power -and ground pins. - -Example usage:: - - import pyb - - s1 = pyb.Servo(1) # create a servo object on position X1 - s2 = pyb.Servo(2) # create a servo object on position X2 - - s1.angle(45) # move servo 1 to 45 degrees - s2.angle(0) # move servo 2 to 0 degrees - - # move servo1 and servo2 synchronously, taking 1500ms - s1.angle(-60, 1500) - s2.angle(30, 1500) - -.. note:: The Servo objects use Timer(5) to produce the PWM output. You can - use Timer(5) for Servo control, or your own purposes, but not both at the - same time. - -Constructors ------------- - -.. class:: pyb.Servo(id) - - Create a servo object. ``id`` is 1-4, and corresponds to pins X1 through X4. - - -Methods -------- - -.. method:: Servo.angle([angle, time=0]) - - If no arguments are given, this function returns the current angle. - - If arguments are given, this function sets the angle of the servo: - - - ``angle`` is the angle to move to in degrees. - - ``time`` is the number of milliseconds to take to get to the specified - angle. If omitted, then the servo moves as quickly as possible to its - new position. - -.. method:: Servo.speed([speed, time=0]) - - If no arguments are given, this function returns the current speed. - - If arguments are given, this function sets the speed of the servo: - - - ``speed`` is the speed to change to, between -100 and 100. - - ``time`` is the number of milliseconds to take to get to the specified - speed. If omitted, then the servo accelerates as quickly as possible. - -.. method:: Servo.pulse_width([value]) - - If no arguments are given, this function returns the current raw pulse-width - value. - - If an argument is given, this function sets the raw pulse-width value. - -.. method:: Servo.calibration([pulse_min, pulse_max, pulse_centre, [pulse_angle_90, pulse_speed_100]]) - - If no arguments are given, this function returns the current calibration - data, as a 5-tuple. - - If arguments are given, this function sets the timing calibration: - - - ``pulse_min`` is the minimum allowed pulse width. - - ``pulse_max`` is the maximum allowed pulse width. - - ``pulse_centre`` is the pulse width corresponding to the centre/zero position. - - ``pulse_angle_90`` is the pulse width corresponding to 90 degrees. - - ``pulse_speed_100`` is the pulse width corresponding to a speed of 100. diff --git a/docs/library/pyb.Switch.rst b/docs/library/pyb.Switch.rst deleted file mode 100644 index e5ab6bd844..0000000000 --- a/docs/library/pyb.Switch.rst +++ /dev/null @@ -1,46 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.Switch: - -class Switch -- switch object -============================= - -A Switch object is used to control a push-button switch. - -Usage:: - - sw = pyb.Switch() # create a switch object - sw.value() # get state (True if pressed, False otherwise) - sw() # shorthand notation to get the switch state - sw.callback(f) # register a callback to be called when the - # switch is pressed down - sw.callback(None) # remove the callback - -Example:: - - pyb.Switch().callback(lambda: pyb.LED(1).toggle()) - - -Constructors ------------- - -.. class:: pyb.Switch() - - Create and return a switch object. - - -Methods -------- - -.. method:: Switch.__call__() - - Call switch object directly to get its state: ``True`` if pressed down, - ``False`` otherwise. - -.. method:: Switch.value() - - Get the switch state. Returns `True` if pressed down, otherwise `False`. - -.. method:: Switch.callback(fun) - - Register the given function to be called when the switch is pressed down. - If ``fun`` is ``None``, then it disables the callback. diff --git a/docs/library/pyb.Timer.rst b/docs/library/pyb.Timer.rst deleted file mode 100644 index 052bce2efd..0000000000 --- a/docs/library/pyb.Timer.rst +++ /dev/null @@ -1,286 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.Timer: - -class Timer -- control internal timers -====================================== - -.. only:: port_pyboard - - Timers can be used for a great variety of tasks. At the moment, only - the simplest case is implemented: that of calling a function periodically. - - Each timer consists of a counter that counts up at a certain rate. The rate - at which it counts is the peripheral clock frequency (in Hz) divided by the - timer prescaler. When the counter reaches the timer period it triggers an - event, and the counter resets back to zero. By using the callback method, - the timer event can call a Python function. - - Example usage to toggle an LED at a fixed frequency:: - - tim = pyb.Timer(4) # create a timer object using timer 4 - tim.init(freq=2) # trigger at 2Hz - tim.callback(lambda t:pyb.LED(1).toggle()) - - Example using named function for the callback:: - - def tick(timer): # we will receive the timer object when being called - print(timer.counter()) # show current timer's counter value - tim = pyb.Timer(4, freq=1) # create a timer object using timer 4 - trigger at 1Hz - tim.callback(tick) # set the callback to our tick function - - Further examples:: - - tim = pyb.Timer(4, freq=100) # freq in Hz - tim = pyb.Timer(4, prescaler=0, period=99) - tim.counter() # get counter (can also set) - tim.prescaler(2) # set prescaler (can also get) - tim.period(199) # set period (can also get) - tim.callback(lambda t: ...) # set callback for update interrupt (t=tim instance) - tim.callback(None) # clear callback - - *Note:* Timer(2) and Timer(3) are used for PWM to set the intensity of LED(3) - and LED(4) respectively. But these timers are only configured for PWM if - the intensity of the relevant LED is set to a value between 1 and 254. If - the intensity feature of the LEDs is not used then these timers are free for - general purpose use. Similarly, Timer(5) controls the servo driver, and - Timer(6) is used for timed ADC/DAC reading/writing. It is recommended to - use the other timers in your programs. - -*Note:* Memory can't be allocated during a callback (an interrupt) and so -exceptions raised within a callback don't give much information. See -:func:`micropython.alloc_emergency_exception_buf` for how to get around this -limitation. - - -Constructors ------------- - -.. class:: pyb.Timer(id, ...) - - .. only:: port_pyboard - - Construct a new timer object of the given id. If additional - arguments are given, then the timer is initialised by ``init(...)``. - ``id`` can be 1 to 14. - -Methods -------- - -.. only:: port_pyboard - - .. method:: Timer.init(\*, freq, prescaler, period) - - Initialise the timer. Initialisation must be either by frequency (in Hz) - or by prescaler and period:: - - tim.init(freq=100) # set the timer to trigger at 100Hz - tim.init(prescaler=83, period=999) # set the prescaler and period directly - - Keyword arguments: - - - ``freq`` --- specifies the periodic frequency of the timer. You might also - view this as the frequency with which the timer goes through one complete cycle. - - - ``prescaler`` [0-0xffff] - specifies the value to be loaded into the - timer's Prescaler Register (PSC). The timer clock source is divided by - (``prescaler + 1``) to arrive at the timer clock. Timers 2-7 and 12-14 - have a clock source of 84 MHz (pyb.freq()[2] \* 2), and Timers 1, and 8-11 - have a clock source of 168 MHz (pyb.freq()[3] \* 2). - - - ``period`` [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5. - Specifies the value to be loaded into the timer's AutoReload - Register (ARR). This determines the period of the timer (i.e. when the - counter cycles). The timer counter will roll-over after ``period + 1`` - timer clock cycles. - - - ``mode`` can be one of: - - - ``Timer.UP`` - configures the timer to count from 0 to ARR (default) - - ``Timer.DOWN`` - configures the timer to count from ARR down to 0. - - ``Timer.CENTER`` - configures the timer to count from 0 to ARR and - then back down to 0. - - - ``div`` can be one of 1, 2, or 4. Divides the timer clock to determine - the sampling clock used by the digital filters. - - - ``callback`` - as per Timer.callback() - - - ``deadtime`` - specifies the amount of "dead" or inactive time between - transitions on complimentary channels (both channels will be inactive) - for this time). ``deadtime`` may be an integer between 0 and 1008, with - the following restrictions: 0-128 in steps of 1. 128-256 in steps of - 2, 256-512 in steps of 8, and 512-1008 in steps of 16. ``deadtime`` - measures ticks of ``source_freq`` divided by ``div`` clock ticks. - ``deadtime`` is only available on timers 1 and 8. - - You must either specify freq or both of period and prescaler. - -.. method:: Timer.deinit() - - Deinitialises the timer. - - .. only:: port_pyboard - - Disables the callback (and the associated irq). - - Disables any channel callbacks (and the associated irq). - Stops the timer, and disables the timer peripheral. - -.. only:: port_pyboard - - .. method:: Timer.callback(fun) - - Set the function to be called when the timer triggers. - ``fun`` is passed 1 argument, the timer object. - If ``fun`` is ``None`` then the callback will be disabled. - -.. only:: port_pyboard - - .. method:: Timer.channel(channel, mode, ...) - - If only a channel number is passed, then a previously initialized channel - object is returned (or ``None`` if there is no previous channel). - - Otherwise, a TimerChannel object is initialized and returned. - - Each channel can be configured to perform pwm, output compare, or - input capture. All channels share the same underlying timer, which means - that they share the same timer clock. - - Keyword arguments: - - - ``mode`` can be one of: - - - ``Timer.PWM`` --- configure the timer in PWM mode (active high). - - ``Timer.PWM_INVERTED`` --- configure the timer in PWM mode (active low). - - ``Timer.OC_TIMING`` --- indicates that no pin is driven. - - ``Timer.OC_ACTIVE`` --- the pin will be made active when a compare match occurs (active is determined by polarity) - - ``Timer.OC_INACTIVE`` --- the pin will be made inactive when a compare match occurs. - - ``Timer.OC_TOGGLE`` --- the pin will be toggled when an compare match occurs. - - ``Timer.OC_FORCED_ACTIVE`` --- the pin is forced active (compare match is ignored). - - ``Timer.OC_FORCED_INACTIVE`` --- the pin is forced inactive (compare match is ignored). - - ``Timer.IC`` --- configure the timer in Input Capture mode. - - ``Timer.ENC_A`` --- configure the timer in Encoder mode. The counter only changes when CH1 changes. - - ``Timer.ENC_B`` --- configure the timer in Encoder mode. The counter only changes when CH2 changes. - - ``Timer.ENC_AB`` --- configure the timer in Encoder mode. The counter changes when CH1 or CH2 changes. - - - ``callback`` - as per TimerChannel.callback() - - - ``pin`` None (the default) or a Pin object. If specified (and not None) - this will cause the alternate function of the the indicated pin - to be configured for this timer channel. An error will be raised if - the pin doesn't support any alternate functions for this timer channel. - - Keyword arguments for Timer.PWM modes: - - - ``pulse_width`` - determines the initial pulse width value to use. - - ``pulse_width_percent`` - determines the initial pulse width percentage to use. - - Keyword arguments for Timer.OC modes: - - - ``compare`` - determines the initial value of the compare register. - - - ``polarity`` can be one of: - - - ``Timer.HIGH`` - output is active high - - ``Timer.LOW`` - output is active low - - Optional keyword arguments for Timer.IC modes: - - - ``polarity`` can be one of: - - - ``Timer.RISING`` - captures on rising edge. - - ``Timer.FALLING`` - captures on falling edge. - - ``Timer.BOTH`` - captures on both edges. - - Note that capture only works on the primary channel, and not on the - complimentary channels. - - Notes for Timer.ENC modes: - - - Requires 2 pins, so one or both pins will need to be configured to use - the appropriate timer AF using the Pin API. - - Read the encoder value using the timer.counter() method. - - Only works on CH1 and CH2 (and not on CH1N or CH2N) - - The channel number is ignored when setting the encoder mode. - - PWM Example:: - - timer = pyb.Timer(2, freq=1000) - ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=8000) - ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=16000) - -.. only:: port_pyboard - - .. method:: Timer.counter([value]) - - Get or set the timer counter. - -.. only:: port_pyboard - - .. method:: Timer.freq([value]) - - Get or set the frequency for the timer (changes prescaler and period if set). - -.. only:: port_pyboard - - .. method:: Timer.period([value]) - - Get or set the period of the timer. - - .. method:: Timer.prescaler([value]) - - Get or set the prescaler for the timer. - - .. method:: Timer.source_freq() - - Get the frequency of the source of the timer. - -class TimerChannel --- setup a channel for a timer -================================================== - -Timer channels are used to generate/capture a signal using a timer. - -TimerChannel objects are created using the Timer.channel() method. - -Methods -------- - -.. only:: port_pyboard - - .. method:: timerchannel.callback(fun) - - Set the function to be called when the timer channel triggers. - ``fun`` is passed 1 argument, the timer object. - If ``fun`` is ``None`` then the callback will be disabled. - -.. only:: port_pyboard - - .. method:: timerchannel.capture([value]) - - Get or set the capture value associated with a channel. - capture, compare, and pulse_width are all aliases for the same function. - capture is the logical name to use when the channel is in input capture mode. - - .. method:: timerchannel.compare([value]) - - Get or set the compare value associated with a channel. - capture, compare, and pulse_width are all aliases for the same function. - compare is the logical name to use when the channel is in output compare mode. - - .. method:: timerchannel.pulse_width([value]) - - Get or set the pulse width value associated with a channel. - capture, compare, and pulse_width are all aliases for the same function. - pulse_width is the logical name to use when the channel is in PWM mode. - - In edge aligned mode, a pulse_width of ``period + 1`` corresponds to a duty cycle of 100% - In center aligned mode, a pulse width of ``period`` corresponds to a duty cycle of 100% - - .. method:: timerchannel.pulse_width_percent([value]) - - Get or set the pulse width percentage associated with a channel. The value - is a number between 0 and 100 and sets the percentage of the timer period - for which the pulse is active. The value can be an integer or - floating-point number for more accuracy. For example, a value of 25 gives - a duty cycle of 25%. diff --git a/docs/library/pyb.UART.rst b/docs/library/pyb.UART.rst deleted file mode 100644 index 76f347ffa8..0000000000 --- a/docs/library/pyb.UART.rst +++ /dev/null @@ -1,245 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.UART: - -class UART -- duplex serial communication bus -============================================= - -UART implements the standard UART/USART duplex serial communications protocol. At -the physical level it consists of 2 lines: RX and TX. The unit of communication -is a character (not to be confused with a string character) which can be 8 or 9 -bits wide. - -UART objects can be created and initialised using:: - - from pyb import UART - - uart = UART(1, 9600) # init with given baudrate - uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters - -.. only:: port_pyboard - - Bits can be 7, 8 or 9. Parity can be None, 0 (even) or 1 (odd). Stop can be 1 or 2. - - *Note:* with parity=None, only 8 and 9 bits are supported. With parity enabled, - only 7 and 8 bits are supported. - -A UART object acts like a stream object and reading and writing is done -using the standard stream methods:: - - uart.read(10) # read 10 characters, returns a bytes object - uart.read() # read all available characters - uart.readline() # read a line - uart.readinto(buf) # read and store into the given buffer - uart.write('abc') # write the 3 characters - -.. only:: port_pyboard - - Individual characters can be read/written using:: - - uart.readchar() # read 1 character and returns it as an integer - uart.writechar(42) # write 1 character - - To check if there is anything to be read, use:: - - uart.any() # returns the number of characters waiting - - - *Note:* The stream functions ``read``, ``write``, etc. are new in MicroPython v1.3.4. - Earlier versions use ``uart.send`` and ``uart.recv``. - -Constructors ------------- - -.. only:: port_pyboard - - .. class:: pyb.UART(bus, ...) - - Construct a UART object on the given bus. ``bus`` can be 1-6, or 'XA', 'XB', 'YA', or 'YB'. - With no additional parameters, the UART object is created but not - initialised (it has the settings from the last initialisation of - the bus, if any). If extra arguments are given, the bus is initialised. - See ``init`` for parameters of initialisation. - - The physical pins of the UART busses are: - - - ``UART(4)`` is on ``XA``: ``(TX, RX) = (X1, X2) = (PA0, PA1)`` - - ``UART(1)`` is on ``XB``: ``(TX, RX) = (X9, X10) = (PB6, PB7)`` - - ``UART(6)`` is on ``YA``: ``(TX, RX) = (Y1, Y2) = (PC6, PC7)`` - - ``UART(3)`` is on ``YB``: ``(TX, RX) = (Y9, Y10) = (PB10, PB11)`` - - ``UART(2)`` is on: ``(TX, RX) = (X3, X4) = (PA2, PA3)`` - - The Pyboard Lite supports UART(1), UART(2) and UART(6) only. Pins are as above except: - - - ``UART(2)`` is on: ``(TX, RX) = (X1, X2) = (PA2, PA3)`` - -Methods -------- - -.. only:: port_pyboard - - .. method:: UART.init(baudrate, bits=8, parity=None, stop=1, \*, timeout=1000, flow=0, timeout_char=0, read_buf_len=64) - - Initialise the UART bus with the given parameters: - - - ``baudrate`` is the clock rate. - - ``bits`` is the number of bits per character, 7, 8 or 9. - - ``parity`` is the parity, ``None``, 0 (even) or 1 (odd). - - ``stop`` is the number of stop bits, 1 or 2. - - ``flow`` sets the flow control type. Can be 0, ``UART.RTS``, ``UART.CTS`` - or ``UART.RTS | UART.CTS``. - - ``timeout`` is the timeout in milliseconds to wait for writing/reading the first character. - - ``timeout_char`` is the timeout in milliseconds to wait between characters while writing or reading. - - ``read_buf_len`` is the character length of the read buffer (0 to disable). - - This method will raise an exception if the baudrate could not be set within - 5% of the desired value. The minimum baudrate is dictated by the frequency - of the bus that the UART is on; UART(1) and UART(6) are APB2, the rest are on - APB1. The default bus frequencies give a minimum baudrate of 1300 for - UART(1) and UART(6) and 650 for the others. Use :func:`pyb.freq ` - to reduce the bus frequencies to get lower baudrates. - - *Note:* with parity=None, only 8 and 9 bits are supported. With parity enabled, - only 7 and 8 bits are supported. - -.. method:: UART.deinit() - - Turn off the UART bus. - -.. only:: port_pyboard - - .. method:: UART.any() - - Returns the number of bytes waiting (may be 0). - -.. method:: UART.read([nbytes]) - - Read characters. If ``nbytes`` is specified then read at most that many bytes. - If ``nbytes`` are available in the buffer, returns immediately, otherwise returns - when sufficient characters arrive or the timeout elapses. - - If ``nbytes`` is not given then the method reads as much data as possible. It - returns after the timeout has elapsed. - - .. only:: port_pyboard - - *Note:* for 9 bit characters each character takes two bytes, ``nbytes`` must - be even, and the number of characters is ``nbytes/2``. - - Return value: a bytes object containing the bytes read in. Returns ``None`` - on timeout. - -.. method:: UART.readchar() - - Receive a single character on the bus. - - Return value: The character read, as an integer. Returns -1 on timeout. - -.. method:: UART.readinto(buf[, nbytes]) - - Read bytes into the ``buf``. If ``nbytes`` is specified then read at most - that many bytes. Otherwise, read at most ``len(buf)`` bytes. - - Return value: number of bytes read and stored into ``buf`` or ``None`` on - timeout. - -.. method:: UART.readline() - - Read a line, ending in a newline character. If such a line exists, return is - immediate. If the timeout elapses, all available data is returned regardless - of whether a newline exists. - - Return value: the line read or ``None`` on timeout if no data is available. - -.. method:: UART.write(buf) - - .. only:: port_pyboard - - Write the buffer of bytes to the bus. If characters are 7 or 8 bits wide - then each byte is one character. If characters are 9 bits wide then two - bytes are used for each character (little endian), and ``buf`` must contain - an even number of bytes. - - Return value: number of bytes written. If a timeout occurs and no bytes - were written returns ``None``. - -.. only:: port_pyboard - - .. method:: UART.writechar(char) - - Write a single character on the bus. ``char`` is an integer to write. - Return value: ``None``. See note below if CTS flow control is used. - -.. method:: UART.sendbreak() - - Send a break condition on the bus. This drives the bus low for a duration - of 13 bits. - Return value: ``None``. - -Constants ---------- - -.. only:: port_pyboard - - .. data:: UART.RTS - .. data:: UART.CTS - - to select the flow control type. - -Flow Control ------------- - -.. only:: port_pyboard - - On Pyboards V1 and V1.1 ``UART(2)`` and ``UART(3)`` support RTS/CTS hardware flow control - using the following pins: - - - ``UART(2)`` is on: ``(TX, RX, nRTS, nCTS) = (X3, X4, X2, X1) = (PA2, PA3, PA1, PA0)`` - - ``UART(3)`` is on :``(TX, RX, nRTS, nCTS) = (Y9, Y10, Y7, Y6) = (PB10, PB11, PB14, PB13)`` - - On the Pyboard Lite only ``UART(2)`` supports flow control on these pins: - - ``(TX, RX, nRTS, nCTS) = (X1, X2, X4, X3) = (PA2, PA3, PA1, PA0)`` - - In the following paragraphs the term "target" refers to the device connected to - the UART. - - When the UART's ``init()`` method is called with ``flow`` set to one or both of - ``UART.RTS`` and ``UART.CTS`` the relevant flow control pins are configured. - ``nRTS`` is an active low output, ``nCTS`` is an active low input with pullup - enabled. To achieve flow control the Pyboard's ``nCTS`` signal should be connected - to the target's ``nRTS`` and the Pyboard's ``nRTS`` to the target's ``nCTS``. - - CTS: target controls Pyboard transmitter - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - If CTS flow control is enabled the write behaviour is as follows: - - If the Pyboard's ``UART.write(buf)`` method is called, transmission will stall for - any periods when ``nCTS`` is ``False``. This will result in a timeout if the entire - buffer was not transmitted in the timeout period. The method returns the number of - bytes written, enabling the user to write the remainder of the data if required. In - the event of a timeout, a character will remain in the UART pending ``nCTS``. The - number of bytes composing this character will be included in the return value. - - If ``UART.writechar()`` is called when ``nCTS`` is ``False`` the method will time - out unless the target asserts ``nCTS`` in time. If it times out ``OSError 116`` - will be raised. The character will be transmitted as soon as the target asserts ``nCTS``. - - RTS: Pyboard controls target's transmitter - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - If RTS flow control is enabled, behaviour is as follows: - - If buffered input is used (``read_buf_len`` > 0), incoming characters are buffered. - If the buffer becomes full, the next character to arrive will cause ``nRTS`` to go - ``False``: the target should cease transmission. ``nRTS`` will go ``True`` when - characters are read from the buffer. - - Note that the ``any()`` method returns the number of bytes in the buffer. Assume a - buffer length of ``N`` bytes. If the buffer becomes full, and another character arrives, - ``nRTS`` will be set False, and ``any()`` will return the count ``N``. When - characters are read the additional character will be placed in the buffer and will - be included in the result of a subsequent ``any()`` call. - - If buffered input is not used (``read_buf_len`` == 0) the arrival of a character will - cause ``nRTS`` to go ``False`` until the character is read. diff --git a/docs/library/pyb.USB_HID.rst b/docs/library/pyb.USB_HID.rst deleted file mode 100644 index 7027044354..0000000000 --- a/docs/library/pyb.USB_HID.rst +++ /dev/null @@ -1,40 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.USB_HID: - -class USB_HID -- USB Human Interface Device (HID) -================================================= - -The USB_HID class allows creation of an object representing the USB -Human Interface Device (HID) interface. It can be used to emulate -a peripheral such as a mouse or keyboard. - -Before you can use this class, you need to use :meth:`pyb.usb_mode()` to set the USB mode to include the HID interface. - -Constructors ------------- - -.. class:: pyb.USB_HID() - - Create a new USB_HID object. - - -Methods -------- - -.. method:: USB_HID.recv(data, \*, timeout=5000) - - Receive data on the bus: - - - ``data`` can be an integer, which is the number of bytes to receive, - or a mutable buffer, which will be filled with received bytes. - - ``timeout`` is the timeout in milliseconds to wait for the receive. - - Return value: if ``data`` is an integer then a new buffer of the bytes received, - otherwise the number of bytes read into ``data`` is returned. - -.. method:: USB_HID.send(data) - - Send data over the USB HID interface: - - - ``data`` is the data to send (a tuple/list of integers, or a - bytearray). diff --git a/docs/library/pyb.USB_VCP.rst b/docs/library/pyb.USB_VCP.rst deleted file mode 100644 index 80cc40cdde..0000000000 --- a/docs/library/pyb.USB_VCP.rst +++ /dev/null @@ -1,103 +0,0 @@ -.. currentmodule:: pyb -.. _pyb.USB_VCP: - -class USB_VCP -- USB virtual comm port -====================================== - -The USB_VCP class allows creation of an object representing the USB -virtual comm port. It can be used to read and write data over USB to -the connected host. - - -Constructors ------------- - -.. class:: pyb.USB_VCP() - - Create a new USB_VCP object. - - -Methods -------- - -.. method:: USB_VCP.setinterrupt(chr) - - Set the character which interrupts running Python code. This is set - to 3 (CTRL-C) by default, and when a CTRL-C character is received over - the USB VCP port, a KeyboardInterrupt exception is raised. - - Set to -1 to disable this interrupt feature. This is useful when you - want to send raw bytes over the USB VCP port. - -.. method:: USB_VCP.isconnected() - - Return ``True`` if USB is connected as a serial device, else ``False``. - -.. method:: USB_VCP.any() - - Return ``True`` if any characters waiting, else ``False``. - -.. method:: USB_VCP.close() - - This method does nothing. It exists so the USB_VCP object can act as - a file. - -.. method:: USB_VCP.read([nbytes]) - - Read at most ``nbytes`` from the serial device and return them as a - bytes object. If ``nbytes`` is not specified then the method reads - all available bytes from the serial device. - USB_VCP stream implicitly works in non-blocking mode, - so if no pending data available, this method will return immediately - with ``None`` value. - -.. method:: USB_VCP.readinto(buf, [maxlen]) - - Read bytes from the serial device and store them into ``buf``, which - should be a buffer-like object. At most ``len(buf)`` bytes are read. - If ``maxlen`` is given and then at most ``min(maxlen, len(buf))`` bytes - are read. - - Returns the number of bytes read and stored into ``buf`` or ``None`` - if no pending data available. - -.. method:: USB_VCP.readline() - - Read a whole line from the serial device. - - Returns a bytes object containing the data, including the trailing - newline character or ``None`` if no pending data available. - -.. method:: USB_VCP.readlines() - - Read as much data as possible from the serial device, breaking it into - lines. - - Returns a list of bytes objects, each object being one of the lines. - Each line will include the newline character. - -.. method:: USB_VCP.write(buf) - - Write the bytes from ``buf`` to the serial device. - - Returns the number of bytes written. - -.. method:: USB_VCP.recv(data, \*, timeout=5000) - - Receive data on the bus: - - - ``data`` can be an integer, which is the number of bytes to receive, - or a mutable buffer, which will be filled with received bytes. - - ``timeout`` is the timeout in milliseconds to wait for the receive. - - Return value: if ``data`` is an integer then a new buffer of the bytes received, - otherwise the number of bytes read into ``data`` is returned. - -.. method:: USB_VCP.send(data, \*, timeout=5000) - - Send data over the USB VCP: - - - ``data`` is the data to send (an integer to send, or a buffer object). - - ``timeout`` is the timeout in milliseconds to wait for the send. - - Return value: number of bytes sent. diff --git a/docs/library/pyb.rst b/docs/library/pyb.rst deleted file mode 100644 index 7991601457..0000000000 --- a/docs/library/pyb.rst +++ /dev/null @@ -1,321 +0,0 @@ -:mod:`pyb` --- functions related to the board -============================================= - -.. module:: pyb - :synopsis: functions related to the board - -The ``pyb`` module contains specific functions related to the board. - -Time related functions ----------------------- - -.. function:: delay(ms) - - Delay for the given number of milliseconds. - -.. function:: udelay(us) - - Delay for the given number of microseconds. - -.. function:: millis() - - Returns the number of milliseconds since the board was last reset. - - The result is always a MicroPython smallint (31-bit signed number), so - after 2^30 milliseconds (about 12.4 days) this will start to return - negative numbers. - - Note that if :meth:`pyb.stop()` is issued the hardware counter supporting this - function will pause for the duration of the "sleeping" state. This - will affect the outcome of :meth:`pyb.elapsed_millis()`. - -.. function:: micros() - - Returns the number of microseconds since the board was last reset. - - The result is always a MicroPython smallint (31-bit signed number), so - after 2^30 microseconds (about 17.8 minutes) this will start to return - negative numbers. - - Note that if :meth:`pyb.stop()` is issued the hardware counter supporting this - function will pause for the duration of the "sleeping" state. This - will affect the outcome of :meth:`pyb.elapsed_micros()`. - -.. function:: elapsed_millis(start) - - Returns the number of milliseconds which have elapsed since ``start``. - - This function takes care of counter wrap, and always returns a positive - number. This means it can be used to measure periods up to about 12.4 days. - - Example:: - - start = pyb.millis() - while pyb.elapsed_millis(start) < 1000: - # Perform some operation - -.. function:: elapsed_micros(start) - - Returns the number of microseconds which have elapsed since ``start``. - - This function takes care of counter wrap, and always returns a positive - number. This means it can be used to measure periods up to about 17.8 minutes. - - Example:: - - start = pyb.micros() - while pyb.elapsed_micros(start) < 1000: - # Perform some operation - pass - -Reset related functions ------------------------ - -.. function:: hard_reset() - - Resets the pyboard in a manner similar to pushing the external RESET - button. - -.. function:: bootloader() - - Activate the bootloader without BOOT\* pins. - -.. function:: fault_debug(value) - - Enable or disable hard-fault debugging. A hard-fault is when there is a fatal - error in the underlying system, like an invalid memory access. - - If the *value* argument is ``False`` then the board will automatically reset if - there is a hard fault. - - If *value* is ``True`` then, when the board has a hard fault, it will print the - registers and the stack trace, and then cycle the LEDs indefinitely. - - The default value is disabled, i.e. to automatically reset. - -Interrupt related functions ---------------------------- - -.. function:: disable_irq() - - Disable interrupt requests. - Returns the previous IRQ state: ``False``/``True`` for disabled/enabled IRQs - respectively. This return value can be passed to enable_irq to restore - the IRQ to its original state. - -.. function:: enable_irq(state=True) - - Enable interrupt requests. - If ``state`` is ``True`` (the default value) then IRQs are enabled. - If ``state`` is ``False`` then IRQs are disabled. The most common use of - this function is to pass it the value returned by ``disable_irq`` to - exit a critical section. - -Power related functions ------------------------ - -.. only:: port_pyboard - - .. function:: freq([sysclk[, hclk[, pclk1[, pclk2]]]]) - - If given no arguments, returns a tuple of clock frequencies: - (sysclk, hclk, pclk1, pclk2). - These correspond to: - - - sysclk: frequency of the CPU - - hclk: frequency of the AHB bus, core memory and DMA - - pclk1: frequency of the APB1 bus - - pclk2: frequency of the APB2 bus - - If given any arguments then the function sets the frequency of the CPU, - and the busses if additional arguments are given. Frequencies are given in - Hz. Eg freq(120000000) sets sysclk (the CPU frequency) to 120MHz. Note that - not all values are supported and the largest supported frequency not greater - than the given value will be selected. - - Supported sysclk frequencies are (in MHz): 8, 16, 24, 30, 32, 36, 40, 42, 48, - 54, 56, 60, 64, 72, 84, 96, 108, 120, 144, 168. - - The maximum frequency of hclk is 168MHz, of pclk1 is 42MHz, and of pclk2 is - 84MHz. Be sure not to set frequencies above these values. - - The hclk, pclk1 and pclk2 frequencies are derived from the sysclk frequency - using a prescaler (divider). Supported prescalers for hclk are: 1, 2, 4, 8, - 16, 64, 128, 256, 512. Supported prescalers for pclk1 and pclk2 are: 1, 2, - 4, 8. A prescaler will be chosen to best match the requested frequency. - - A sysclk frequency of - 8MHz uses the HSE (external crystal) directly and 16MHz uses the HSI - (internal oscillator) directly. The higher frequencies use the HSE to - drive the PLL (phase locked loop), and then use the output of the PLL. - - Note that if you change the frequency while the USB is enabled then - the USB may become unreliable. It is best to change the frequency - in boot.py, before the USB peripheral is started. Also note that sysclk - frequencies below 36MHz do not allow the USB to function correctly. - - .. function:: wfi() - - Wait for an internal or external interrupt. - - This executes a ``wfi`` instruction which reduces power consumption - of the MCU until any interrupt occurs (be it internal or external), - at which point execution continues. Note that the system-tick interrupt - occurs once every millisecond (1000Hz) so this function will block for - at most 1ms. - - .. function:: stop() - - Put the pyboard in a "sleeping" state. - - This reduces power consumption to less than 500 uA. To wake from this - sleep state requires an external interrupt or a real-time-clock event. - Upon waking execution continues where it left off. - - See :meth:`rtc.wakeup` to configure a real-time-clock wakeup event. - - .. function:: standby() - - Put the pyboard into a "deep sleep" state. - - This reduces power consumption to less than 50 uA. To wake from this - sleep state requires a real-time-clock event, or an external interrupt - on X1 (PA0=WKUP) or X18 (PC13=TAMP1). - Upon waking the system undergoes a hard reset. - - See :meth:`rtc.wakeup` to configure a real-time-clock wakeup event. - -Miscellaneous functions ------------------------ - -.. only:: port_pyboard - - .. function:: have_cdc() - - Return True if USB is connected as a serial device, False otherwise. - - .. note:: This function is deprecated. Use pyb.USB_VCP().isconnected() instead. - - .. function:: hid((buttons, x, y, z)) - - Takes a 4-tuple (or list) and sends it to the USB host (the PC) to - signal a HID mouse-motion event. - - .. note:: This function is deprecated. Use :meth:`pyb.USB_HID.send()` instead. - - .. function:: info([dump_alloc_table]) - - Print out lots of information about the board. - -.. function:: main(filename) - - Set the filename of the main script to run after boot.py is finished. If - this function is not called then the default file main.py will be executed. - - It only makes sense to call this function from within boot.py. - -.. only:: port_pyboard - - .. function:: mount(device, mountpoint, \*, readonly=False, mkfs=False) - - Mount a block device and make it available as part of the filesystem. - ``device`` must be an object that provides the block protocol: - - - ``readblocks(self, blocknum, buf)`` - - ``writeblocks(self, blocknum, buf)`` (optional) - - ``count(self)`` - - ``sync(self)`` (optional) - - ``readblocks`` and ``writeblocks`` should copy data between ``buf`` and - the block device, starting from block number ``blocknum`` on the device. - ``buf`` will be a bytearray with length a multiple of 512. If - ``writeblocks`` is not defined then the device is mounted read-only. - The return value of these two functions is ignored. - - ``count`` should return the number of blocks available on the device. - ``sync``, if implemented, should sync the data on the device. - - The parameter ``mountpoint`` is the location in the root of the filesystem - to mount the device. It must begin with a forward-slash. - - If ``readonly`` is ``True``, then the device is mounted read-only, - otherwise it is mounted read-write. - - If ``mkfs`` is ``True``, then a new filesystem is created if one does not - already exist. - - To unmount a device, pass ``None`` as the device and the mount location - as ``mountpoint``. - -.. function:: repl_uart(uart) - - Get or set the UART object where the REPL is repeated on. - -.. only:: port_pyboard - - .. function:: rng() - - Return a 30-bit hardware generated random number. - -.. function:: sync() - - Sync all file systems. - -.. only:: port_pyboard - - .. function:: unique_id() - - Returns a string of 12 bytes (96 bits), which is the unique ID of the MCU. - -.. function:: usb_mode([modestr], vid=0xf055, pid=0x9801, hid=pyb.hid_mouse) - - If called with no arguments, return the current USB mode as a string. - - If called with ``modestr`` provided, attempts to set USB mode. - This can only be done when called from ``boot.py`` before - :meth:`pyb.main()` has been called. The following values of - ``modestr`` are understood: - - - ``None``: disables USB - - ``'VCP'``: enable with VCP (Virtual COM Port) interface - - ``'VCP+MSC'``: enable with VCP and MSC (mass storage device class) - - ``'VCP+HID'``: enable with VCP and HID (human interface device) - - For backwards compatibility, ``'CDC'`` is understood to mean - ``'VCP'`` (and similarly for ``'CDC+MSC'`` and ``'CDC+HID'``). - - The ``vid`` and ``pid`` parameters allow you to specify the VID - (vendor id) and PID (product id). - - If enabling HID mode, you may also specify the HID details by - passing the ``hid`` keyword parameter. It takes a tuple of - (subclass, protocol, max packet length, polling interval, report - descriptor). By default it will set appropriate values for a USB - mouse. There is also a ``pyb.hid_keyboard`` constant, which is an - appropriate tuple for a USB keyboard. - -Classes -------- - -.. only:: port_pyboard - - .. toctree:: - :maxdepth: 1 - - pyb.Accel.rst - pyb.ADC.rst - pyb.CAN.rst - pyb.DAC.rst - pyb.ExtInt.rst - pyb.I2C.rst - pyb.LCD.rst - pyb.LED.rst - pyb.Pin.rst - pyb.RTC.rst - pyb.Servo.rst - pyb.SPI.rst - pyb.Switch.rst - pyb.Timer.rst - pyb.UART.rst - pyb.USB_HID.rst - pyb.USB_VCP.rst diff --git a/docs/library/sys.rst b/docs/library/sys.rst index d49577306e..de2ec2dcd2 100644 --- a/docs/library/sys.rst +++ b/docs/library/sys.rst @@ -1,10 +1,12 @@ :mod:`sys` -- system specific functions ======================================= +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: sys :synopsis: system specific functions -|see_cpython_module| :mod:`python:sys`. +|see_cpython_module| :mod:`cpython:sys`. Functions --------- @@ -27,8 +29,7 @@ Functions ``traceback`` module in CPython. Unlike ``traceback.print_exception()``, this function takes just exception value instead of exception type, exception value, and traceback object; *file* argument should be - positional; further arguments are not supported. CPython-compatible - ``traceback`` module can be found in `micropython-lib`. + positional; further arguments are not supported. Constants --------- diff --git a/docs/library/ubinascii.rst b/docs/library/ubinascii.rst index 192d34514b..edf4a9fdf5 100644 --- a/docs/library/ubinascii.rst +++ b/docs/library/ubinascii.rst @@ -1,10 +1,12 @@ :mod:`ubinascii` -- binary/ASCII conversions ============================================ +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: ubinascii :synopsis: binary/ASCII conversions -|see_cpython_module| :mod:`python:binascii`. +|see_cpython_module| :mod:`cpython:binascii`. This module implements conversions between binary data and various encodings of it in ASCII form (in both directions). diff --git a/docs/library/ucollections.rst b/docs/library/ucollections.rst index 96de67acc4..396ba3c87d 100644 --- a/docs/library/ucollections.rst +++ b/docs/library/ucollections.rst @@ -1,10 +1,12 @@ :mod:`ucollections` -- collection and container types ===================================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: ucollections :synopsis: collection and container types -|see_cpython_module| :mod:`python:collections`. +|see_cpython_module| :mod:`cpython:collections`. This module implements advanced collection and container types to hold/accumulate various objects. diff --git a/docs/library/uctypes.rst b/docs/library/uctypes.rst index 2a9c4dd5c0..55de9a0a24 100644 --- a/docs/library/uctypes.rst +++ b/docs/library/uctypes.rst @@ -1,6 +1,8 @@ :mod:`uctypes` -- access binary data in a structured way ======================================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: uctypes :synopsis: access binary data in a structured way @@ -13,7 +15,7 @@ sub-fields. .. seealso:: - Module :mod:`ustruct` + Module :mod:`struct` Standard Python way to access binary data structures (doesn't scale well to large and complex structures). diff --git a/docs/library/uerrno.rst b/docs/library/uerrno.rst index 0cdcc84487..72f71f0aac 100644 --- a/docs/library/uerrno.rst +++ b/docs/library/uerrno.rst @@ -1,13 +1,14 @@ :mod:`uerrno` -- system error codes =================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: uerrno :synopsis: system error codes -|see_cpython_module| :mod:`python:errno`. +|see_cpython_module| :mod:`cpython:errno`. This module provides access to symbolic error codes for `OSError` exception. -A particular inventory of codes depends on `MicroPython port`. Constants --------- @@ -15,12 +16,11 @@ Constants .. data:: EEXIST, EAGAIN, etc. Error codes, based on ANSI C/POSIX standard. All error codes start with - "E". As mentioned above, inventory of the codes depends on - `MicroPython port`. Errors are usually accessible as ``exc.args[0]`` - where `exc` is an instance of `OSError`. Usage example:: + "E". Errors are usually accessible as ``exc.args[0]`` + where ``exc`` is an instance of `OSError`. Usage example:: try: - uos.mkdir("my_dir") + os.mkdir("my_dir") except OSError as exc: if exc.args[0] == uerrno.EEXIST: print("Directory already exists") diff --git a/docs/library/uhashlib.rst b/docs/library/uhashlib.rst index 50ed658cc1..0f20413f75 100644 --- a/docs/library/uhashlib.rst +++ b/docs/library/uhashlib.rst @@ -1,10 +1,12 @@ :mod:`uhashlib` -- hashing algorithms ===================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: uhashlib :synopsis: hashing algorithms -|see_cpython_module| :mod:`python:hashlib`. +|see_cpython_module| :mod:`cpython:hashlib`. This module implements binary data hashing algorithms. The exact inventory of available algorithms depends on a board. Among the algorithms which may diff --git a/docs/library/uheapq.rst b/docs/library/uheapq.rst index f822f1e7f3..67da5f7380 100644 --- a/docs/library/uheapq.rst +++ b/docs/library/uheapq.rst @@ -1,10 +1,12 @@ :mod:`uheapq` -- heap queue algorithm ===================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: uheapq :synopsis: heap queue algorithm -|see_cpython_module| :mod:`python:heapq`. +|see_cpython_module| :mod:`cpython:heapq`. This module implements the heap queue algorithm. diff --git a/docs/library/uio.rst b/docs/library/uio.rst index 7042a9e376..5ae8b9ecba 100644 --- a/docs/library/uio.rst +++ b/docs/library/uio.rst @@ -1,10 +1,12 @@ :mod:`uio` -- input/output streams ================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: uio :synopsis: input/output streams -|see_cpython_module| :mod:`python:io`. +|see_cpython_module| :mod:`cpython:io`. This module contains additional types of stream (file-like) objects and helper functions. @@ -81,7 +83,7 @@ Functions Open a file. Builtin ``open()`` function is aliased to this function. All ports (which provide access to file system) are required to support - `mode` parameter, but support for other arguments vary by port. + ``mode`` parameter, but support for other arguments vary by port. Classes ------- diff --git a/docs/library/ujson.rst b/docs/library/ujson.rst index 0932d0ab55..080ee2d036 100644 --- a/docs/library/ujson.rst +++ b/docs/library/ujson.rst @@ -1,10 +1,12 @@ :mod:`ujson` -- JSON encoding and decoding ========================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: ujson :synopsis: JSON encoding and decoding -|see_cpython_module| :mod:`python:json`. +|see_cpython_module| :mod:`cpython:json`. This modules allows to convert between Python objects and the JSON data format. diff --git a/docs/library/uos.rst b/docs/library/uos.rst deleted file mode 100644 index 43bf69cc0a..0000000000 --- a/docs/library/uos.rst +++ /dev/null @@ -1,110 +0,0 @@ -:mod:`uos` -- basic "operating system" services -=============================================== - -.. module:: uos - :synopsis: basic "operating system" services - -|see_cpython_module| :mod:`python:os`. - -The ``uos`` module contains functions for filesystem access and ``urandom`` -function. - -Functions ---------- - -.. function:: chdir(path) - - Change current directory. - -.. function:: getcwd() - - Get the current directory. - -.. function:: ilistdir([dir]) - - This function returns an iterator which then yields 3-tuples corresponding to - the entries in the directory that it is listing. With no argument it lists the - current directory, otherwise it lists the directory given by *dir*. - - The 3-tuples have the form *(name, type, inode)*: - - - *name* is a string (or bytes if *dir* is a bytes object) and is the name of - the entry; - - *type* is an integer that specifies the type of the entry, with 0x4000 for - directories and 0x8000 for regular files; - - *inode* is an integer corresponding to the inode of the file, and may be 0 - for filesystems that don't have such a notion. - -.. function:: listdir([dir]) - - With no argument, list the current directory. Otherwise list the given directory. - -.. function:: mkdir(path) - - Create a new directory. - -.. function:: remove(path) - - Remove a file. - -.. function:: rmdir(path) - - Remove a directory. - -.. function:: rename(old_path, new_path) - - Rename a file. - -.. function:: stat(path) - - Get the status of a file or directory. - -.. function:: statvfs(path) - - Get the status of a fileystem. - - Returns a tuple with the filesystem information in the following order: - - * ``f_bsize`` -- file system block size - * ``f_frsize`` -- fragment size - * ``f_blocks`` -- size of fs in f_frsize units - * ``f_bfree`` -- number of free blocks - * ``f_bavail`` -- number of free blocks for unpriviliged users - * ``f_files`` -- number of inodes - * ``f_ffree`` -- number of free inodes - * ``f_favail`` -- number of free inodes for unpriviliged users - * ``f_flag`` -- mount flags - * ``f_namemax`` -- maximum filename length - - Parameters related to inodes: ``f_files``, ``f_ffree``, ``f_avail`` - and the ``f_flags`` parameter may return ``0`` as they can be unavailable - in a port-specific implementation. - -.. function:: sync() - - Sync all filesystems. - -.. function:: urandom(n) - - Return a bytes object with n random bytes. Whenever possible, it is - generated by the hardware random number generator. - -.. function:: dupterm(stream_object, index=0) - - Duplicate or switch the MicroPython terminal (the REPL) on the given stream-like - object. The *stream_object* argument must implement the ``readinto()`` and - ``write()`` methods. The stream should be in non-blocking mode and - ``readinto()`` should return ``None`` if there is no data available for reading. - - After calling this function all terminal output is repeated on this stream, - and any input that is available on the stream is passed on to the terminal input. - - The *index* parameter should be a non-negative integer and specifies which - duplication slot is set. A given port may implement more than one slot (slot 0 - will always be available) and in that case terminal input and output is - duplicated on all the slots that are set. - - If ``None`` is passed as the *stream_object* then duplication is cancelled on - the slot given by *index*. - - The function returns the previous stream-like object in the given slot. diff --git a/docs/library/ure.rst b/docs/library/ure.rst index ebae1db5f1..c6457de9a8 100644 --- a/docs/library/ure.rst +++ b/docs/library/ure.rst @@ -1,10 +1,12 @@ :mod:`ure` -- simple regular expressions ======================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: ure :synopsis: regular expressions -|see_cpython_module| :mod:`python:re`. +|see_cpython_module| :mod:`cpython:re`. This module implements regular expression operations. Regular expression syntax supported is a subset of CPython ``re`` module (and actually is diff --git a/docs/library/uselect.rst b/docs/library/uselect.rst index beffce69ae..685f5b318b 100644 --- a/docs/library/uselect.rst +++ b/docs/library/uselect.rst @@ -1,10 +1,12 @@ :mod:`uselect` -- wait for events on a set of streams ======================================================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: uselect :synopsis: wait for events on a set of streams -|see_cpython_module| :mod:`python:select`. +|see_cpython_module| :mod:`cpython:select`. This module provides functions to efficiently wait for events on multiple streams (select streams which are ready for operations). @@ -69,7 +71,7 @@ Methods .. method:: poll.ipoll(timeout=-1, flags=0) Like :meth:`poll.poll`, but instead returns an iterator which yields - `callee-owned tuples`. This function provides efficient, allocation-free + ``callee-owned tuples``. This function provides efficient, allocation-free way to poll on streams. If *flags* is 1, one-shot behavior for events is employed: streams for diff --git a/docs/library/usocket.rst b/docs/library/usocket.rst index fab05b652b..b07ba44130 100644 --- a/docs/library/usocket.rst +++ b/docs/library/usocket.rst @@ -2,10 +2,12 @@ :mod:`usocket` -- socket module ******************************* +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: usocket :synopsis: socket module -|see_cpython_module| :mod:`python:socket`. +|see_cpython_module| :mod:`cpython:socket`. This module provides access to the BSD socket interface. @@ -36,11 +38,7 @@ power) and portable way to work with addresses. However, ``socket`` module (note the difference with native MicroPython ``usocket`` module described here) provides CPython-compatible way to specify -addresses using tuples, as described below. Note that depending on a -`MicroPython port`, ``socket`` module can be builtin or need to be -installed from `micropython-lib` (as in the case of `MicroPython Unix port`), -and some ports still accept only numeric addresses in the tuple format, -and require to use `getaddrinfo` function to resolve domain names. +addresses using tuples, as described below. Summing up: @@ -60,8 +58,7 @@ Tuple address format for ``socket`` module: and *port* is an integer port number in the range 1-65535. *flowinfo* must be 0. *scopeid* is the interface scope identifier for link-local addresses. Note the domain names are not accepted as *ipv6_address*, - they should be resolved first using `usocket.getaddrinfo()`. Availability - of IPv6 support depends on a `MicroPython port`. + they should be resolved first using `usocket.getaddrinfo()`. Functions --------- @@ -81,8 +78,8 @@ Functions .. function:: getaddrinfo(host, port) - Translate the host/port argument into a sequence of 5-tuples that contain all the - necessary arguments for creating a socket connected to that service. The list of + Translate the host/port argument into a sequence of 5-tuples that contain all the + necessary arguments for creating a socket connected to that service. The list of 5-tuples has following structure:: (family, type, proto, canonname, sockaddr) @@ -99,7 +96,7 @@ Functions of error in this function. MicroPython doesn't have ``socket.gaierror`` and raises OSError directly. Note that error numbers of `getaddrinfo()` form a separate namespace and may not match error numbers from - `uerrno` module. To distinguish `getaddrinfo()` errors, they are + :py:mod:`uerrno` module. To distinguish `getaddrinfo()` errors, they are represented by negative numbers, whereas standard system errors are positive numbers (error numbers are accessible using ``e.args[0]`` property from an exception object). The use of negative values is a provisional @@ -127,7 +124,7 @@ Constants .. data:: AF_INET AF_INET6 - Address family types. Availability depends on a particular `MicroPython port`. + Address family types. Availability depends on a particular ``MicroPython port``. .. data:: SOCK_STREAM SOCK_DGRAM @@ -137,7 +134,7 @@ Constants .. data:: IPPROTO_UDP IPPROTO_TCP - IP protocol numbers. Availability depends on a particular `MicroPython port`. + IP protocol numbers. Availability depends on a particular ``MicroPython port``. Note that you don't need to specify these in a call to `usocket.socket()`, because `SOCK_STREAM` socket type automatically selects `IPPROTO_TCP`, and `SOCK_DGRAM` - `IPPROTO_UDP`. Thus, the only real use of these constants @@ -146,12 +143,12 @@ Constants .. data:: usocket.SOL_* Socket option levels (an argument to `setsockopt()`). The exact - inventory depends on a `MicroPython port`. + inventory depends on a ``MicroPython port``. .. data:: usocket.SO_* Socket options (an argument to `setsockopt()`). The exact - inventory depends on a `MicroPython port`. + inventory depends on a ``MicroPython port``. Constants specific to WiPy: @@ -171,7 +168,7 @@ Methods on the socket object will fail. The remote end will receive EOF indication if supported by protocol. - Sockets are automatically closed when they are garbage-collected, but it is recommended + Sockets are automatically closed when they are garbage-collected, but it is recommended to `close()` them explicitly as soon you finished working with them. .. method:: socket.bind(address) @@ -245,7 +242,7 @@ Methods completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode. - Not every `MicroPython port` supports this method. A more portable and + Not every ``MicroPython port`` supports this method. A more portable and generic solution is to use `uselect.poll` object. This allows to wait on multiple objects at the same time (and not just on sockets, but on generic stream objects which support polling). Example:: diff --git a/docs/library/ussl.rst b/docs/library/ussl.rst index 3ec609f67b..34db3151d6 100644 --- a/docs/library/ussl.rst +++ b/docs/library/ussl.rst @@ -1,10 +1,12 @@ :mod:`ussl` -- SSL/TLS module ============================= +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: ussl :synopsis: TLS/SSL wrapper for socket objects -|see_cpython_module| :mod:`python:ssl`. +|see_cpython_module| :mod:`cpython:ssl`. This module provides access to Transport Layer Security (previously and widely known as “Secure Sockets Layer”) encryption and peer authentication @@ -18,13 +20,13 @@ Functions Takes a stream *sock* (usually usocket.socket instance of ``SOCK_STREAM`` type), and returns an instance of ssl.SSLSocket, which wraps the underlying stream in an SSL context. Returned object has the usual stream interface methods like - `read()`, `write()`, etc. In MicroPython, the returned object does not expose - socket interface and methods like `recv()`, `send()`. In particular, a + ``read()``, ``write()``, etc. In MicroPython, the returned object does not expose + socket interface and methods like ``recv()``, ``send()``. In particular, a server-side SSL socket should be created from a normal socket returned from `accept()` on a non-SSL listening server socket. Depending on the underlying module implementation in a particular - `MicroPython port`, some or all keyword arguments above may be not supported. + ``MicroPython port``, some or all keyword arguments above may be not supported. .. warning:: diff --git a/docs/library/ustruct.rst b/docs/library/ustruct.rst index 81915d0a8d..c378a94bbe 100644 --- a/docs/library/ustruct.rst +++ b/docs/library/ustruct.rst @@ -1,10 +1,12 @@ :mod:`ustruct` -- pack and unpack primitive data types ====================================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: ustruct :synopsis: pack and unpack primitive data types -|see_cpython_module| :mod:`python:struct`. +|see_cpython_module| :mod:`cpython:struct`. Supported size/byte order prefixes: ``@``, ``<``, ``>``, ``!``. diff --git a/docs/library/utime.rst b/docs/library/utime.rst deleted file mode 100644 index a39f5ee733..0000000000 --- a/docs/library/utime.rst +++ /dev/null @@ -1,229 +0,0 @@ -:mod:`utime` -- time related functions -====================================== - -.. module:: utime - :synopsis: time related functions - -|see_cpython_module| :mod:`python:time`. - -The ``utime`` module provides functions for getting the current time and date, -measuring time intervals, and for delays. - -**Time Epoch**: Unix port uses standard for POSIX systems epoch of -1970-01-01 00:00:00 UTC. However, embedded ports use epoch of -2000-01-01 00:00:00 UTC. - -**Maintaining actual calendar date/time**: This requires a -Real Time Clock (RTC). On systems with underlying OS (including some -RTOS), an RTC may be implicit. Setting and maintaining actual calendar -time is responsibility of OS/RTOS and is done outside of MicroPython, -it just uses OS API to query date/time. On baremetal ports however -system time depends on ``machine.RTC()`` object. The current calendar time -may be set using ``machine.RTC().datetime(tuple)`` function, and maintained -by following means: - -* By a backup battery (which may be an additional, optional component for - a particular board). -* Using networked time protocol (requires setup by a port/user). -* Set manually by a user on each power-up (many boards then maintain - RTC time across hard resets, though some may require setting it again - in such case). - -If actual calendar time is not maintained with a system/MicroPython RTC, -functions below which require reference to current absolute time may -behave not as expected. - -Functions ---------- - -.. function:: localtime([secs]) - - Convert a time expressed in seconds since the Epoch (see above) into an 8-tuple which - contains: (year, month, mday, hour, minute, second, weekday, yearday) - If secs is not provided or None, then the current time from the RTC is used. - - * year includes the century (for example 2014). - * month is 1-12 - * mday is 1-31 - * hour is 0-23 - * minute is 0-59 - * second is 0-59 - * weekday is 0-6 for Mon-Sun - * yearday is 1-366 - -.. function:: mktime() - - This is inverse function of localtime. It's argument is a full 8-tuple - which expresses a time as per localtime. It returns an integer which is - the number of seconds since Jan 1, 2000. - -.. function:: sleep(seconds) - - Sleep for the given number of seconds. Some boards may accept *seconds* as a - floating-point number to sleep for a fractional number of seconds. Note that - other boards may not accept a floating-point argument, for compatibility with - them use `sleep_ms()` and `sleep_us()` functions. - -.. function:: sleep_ms(ms) - - Delay for given number of milliseconds, should be positive or 0. - -.. function:: sleep_us(us) - - Delay for given number of microseconds, should be positive or 0. - -.. function:: ticks_ms() - - Returns an increasing millisecond counter with an arbitrary reference point, that - wraps around after some value. - - The wrap-around value is not explicitly exposed, but we will - refer to it as *TICKS_MAX* to simplify discussion. Period of the values is - *TICKS_PERIOD = TICKS_MAX + 1*. *TICKS_PERIOD* is guaranteed to be a power of - two, but otherwise may differ from port to port. The same period value is used - for all of `ticks_ms()`, `ticks_us()`, `ticks_cpu()` functions (for - simplicity). Thus, these functions will return a value in range [*0* .. - *TICKS_MAX*], inclusive, total *TICKS_PERIOD* values. Note that only - non-negative values are used. For the most part, you should treat values returned - by these functions as opaque. The only operations available for them are - `ticks_diff()` and `ticks_add()` functions described below. - - Note: Performing standard mathematical operations (+, -) or relational - operators (<, <=, >, >=) directly on these value will lead to invalid - result. Performing mathematical operations and then passing their results - as arguments to `ticks_diff()` or `ticks_add()` will also lead to - invalid results from the latter functions. - -.. function:: ticks_us() - - Just like `ticks_ms()` above, but in microseconds. - -.. function:: ticks_cpu() - - Similar to `ticks_ms()` and `ticks_us()`, but with the highest possible resolution - in the system. This is usually CPU clocks, and that's why the function is named that - way. But it doesn't have to be a CPU clock, some other timing source available in a - system (e.g. high-resolution timer) can be used instead. The exact timing unit - (resolution) of this function is not specified on ``utime`` module level, but - documentation for a specific port may provide more specific information. This - function is intended for very fine benchmarking or very tight real-time loops. - Avoid using it in portable code. - - Availability: Not every port implements this function. - - -.. function:: ticks_add(ticks, delta) - - Offset ticks value by a given number, which can be either positive or negative. - Given a *ticks* value, this function allows to calculate ticks value *delta* - ticks before or after it, following modular-arithmetic definition of tick values - (see `ticks_ms()` above). *ticks* parameter must be a direct result of call - to `ticks_ms()`, `ticks_us()`, or `ticks_cpu()` functions (or from previous - call to `ticks_add()`). However, *delta* can be an arbitrary integer number - or numeric expression. `ticks_add()` is useful for calculating deadlines for - events/tasks. (Note: you must use `ticks_diff()` function to work with - deadlines.) - - Examples:: - - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) - - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() - - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1)) - - -.. function:: ticks_diff(ticks1, ticks2) - - Measure ticks difference between values returned from `ticks_ms()`, `ticks_us()`, - or `ticks_cpu()` functions, as a signed value which may wrap around. - - The argument order is the same as for subtraction - operator, ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - However, values returned by `ticks_ms()`, etc. functions may wrap around, so - directly using subtraction on them will produce incorrect result. That is why - `ticks_diff()` is needed, it implements modular (or more specifically, ring) - arithmetics to produce correct result even for wrap-around values (as long as they not - too distant inbetween, see below). The function returns **signed** value in the range - [*-TICKS_PERIOD/2* .. *TICKS_PERIOD/2-1*] (that's a typical range definition for - two's-complement signed binary integers). If the result is negative, it means that - *ticks1* occurred earlier in time than *ticks2*. Otherwise, it means that - *ticks1* occurred after *ticks2*. This holds **only** if *ticks1* and *ticks2* - are apart from each other for no more than *TICKS_PERIOD/2-1* ticks. If that does - not hold, incorrect result will be returned. Specifically, if two tick values are - apart for *TICKS_PERIOD/2-1* ticks, that value will be returned by the function. - However, if *TICKS_PERIOD/2* of real-time ticks has passed between them, the - function will return *-TICKS_PERIOD/2* instead, i.e. result value will wrap around - to the negative range of possible values. - - Informal rationale of the constraints above: Suppose you are locked in a room with no - means to monitor passing of time except a standard 12-notch clock. Then if you look at - dial-plate now, and don't look again for another 13 hours (e.g., if you fall for a - long sleep), then once you finally look again, it may seem to you that only 1 hour - has passed. To avoid this mistake, just look at the clock regularly. Your application - should do the same. "Too long sleep" metaphor also maps directly to application - behavior: don't let your application run any single task for too long. Run tasks - in steps, and do time-keeping inbetween. - - `ticks_diff()` is designed to accommodate various usage patterns, among them: - - * Polling with timeout. In this case, the order of events is known, and you will deal - only with positive results of `ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - * Scheduling events. In this case, `ticks_diff()` result may be negative - if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(now, scheduled_time) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(now, scheduled_time)) - task.run() - elif ticks_diff(now, scheduled_time) == 0: - print("Right at time!") - task.run() - elif ticks_diff(now, scheduled_time) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=true) - - Note: Do not pass `time()` values to `ticks_diff()`, you should use - normal mathematical operations on them. But note that `time()` may (and will) - also overflow. This is known as https://en.wikipedia.org/wiki/Year_2038_problem . - - -.. function:: time() - - Returns the number of seconds, as an integer, since the Epoch, assuming that - underlying RTC is set and maintained as described above. If an RTC is not set, this - function returns number of seconds since a port-specific reference point in time (for - embedded boards without a battery-backed RTC, usually since power up or reset). If you - want to develop portable MicroPython application, you should not rely on this function - to provide higher than second precision. If you need higher precision, use - `ticks_ms()` and `ticks_us()` functions, if you need calendar time, - `localtime()` without an argument is a better choice. - - .. admonition:: Difference to CPython - :class: attention - - In CPython, this function returns number of - seconds since Unix epoch, 1970-01-01 00:00 UTC, as a floating-point, - usually having microsecond precision. With MicroPython, only Unix port - uses the same Epoch, and if floating-point precision allows, - returns sub-second precision. Embedded hardware usually doesn't have - floating-point precision to represent both long time ranges and subsecond - precision, so they use integer value with second precision. Some embedded - hardware also lacks battery-powered RTC, so returns number of seconds - since last power-up or from other relative, hardware-specific point - (e.g. reset). diff --git a/docs/library/uzlib.rst b/docs/library/uzlib.rst index fb1746fe8e..2a2d9668c4 100644 --- a/docs/library/uzlib.rst +++ b/docs/library/uzlib.rst @@ -1,10 +1,12 @@ :mod:`uzlib` -- zlib decompression ================================== +.. include:: ../templates/unsupported_in_circuitpython.inc + .. module:: uzlib :synopsis: zlib decompression -|see_cpython_module| :mod:`python:zlib`. +|see_cpython_module| :mod:`cpython:zlib`. This module allows to decompress binary data compressed with `DEFLATE algorithm `_ diff --git a/docs/library/wipy.rst b/docs/library/wipy.rst deleted file mode 100644 index cdece7b82b..0000000000 --- a/docs/library/wipy.rst +++ /dev/null @@ -1,17 +0,0 @@ -************************************* -:mod:`wipy` -- WiPy specific features -************************************* - -.. module:: wipy - :synopsis: WiPy specific features - -The ``wipy`` module contains functions to control specific features of the -WiPy, such as the heartbeat LED. - -Functions ---------- - -.. function:: heartbeat([enable]) - - Get or set the state (enabled or disabled) of the heartbeat LED. Accepts and - returns boolean values (``True`` or ``False``). diff --git a/docs/porting.rst b/docs/porting.rst index f46160b7d7..6bb5144588 100644 --- a/docs/porting.rst +++ b/docs/porting.rst @@ -45,7 +45,7 @@ these resources are compatible with the MIT License of the rest of the code! Step 2: Init -------------- Once your build is setup, the next step should be to get your clocks going as -you expect from the supervisor. The supervisor calls `port_init` to allow for +you expect from the supervisor. The supervisor calls ``port_init`` to allow for initialization at the beginning of main. This function also has the ability to request a safe mode state which prevents the supervisor from running user code while still allowing access to the REPL and other resources. diff --git a/docs/pyboard/general.rst b/docs/pyboard/general.rst deleted file mode 100644 index 97e9aabc0b..0000000000 --- a/docs/pyboard/general.rst +++ /dev/null @@ -1,80 +0,0 @@ -General information about the pyboard -===================================== - -.. contents:: - -Local filesystem and SD card ----------------------------- - -There is a small internal filesystem (a drive) on the pyboard, called ``/flash``, -which is stored within the microcontroller's flash memory. If a micro SD card -is inserted into the slot, it is available as ``/sd``. - -When the pyboard boots up, it needs to choose a filesystem to boot from. If -there is no SD card, then it uses the internal filesystem ``/flash`` as the boot -filesystem, otherwise, it uses the SD card ``/sd``. After the boot, the current -directory is set to one of the directories above. - -If needed, you can prevent the use of the SD card by creating an empty file -called ``/flash/SKIPSD``. If this file exists when the pyboard boots -up then the SD card will be skipped and the pyboard will always boot from the -internal filesystem (in this case the SD card won't be mounted but you can still -mount and use it later in your program using ``os.mount``). - -(Note that on older versions of the board, ``/flash`` is called ``0:/`` and ``/sd`` -is called ``1:/``). - -The boot filesystem is used for 2 things: it is the filesystem from which -the ``boot.py`` and ``main.py`` files are searched for, and it is the filesystem -which is made available on your PC over the USB cable. - -The filesystem will be available as a USB flash drive on your PC. You can -save files to the drive, and edit ``boot.py`` and ``main.py``. - -*Remember to eject (on Linux, unmount) the USB drive before you reset your -pyboard.* - -Boot modes ----------- - -If you power up normally, or press the reset button, the pyboard will boot -into standard mode: the ``boot.py`` file will be executed first, then the -USB will be configured, then ``main.py`` will run. - -You can override this boot sequence by holding down the user switch as -the board is booting up. Hold down user switch and press reset, and then -as you continue to hold the user switch, the LEDs will count in binary. -When the LEDs have reached the mode you want, let go of the user switch, -the LEDs for the selected mode will flash quickly, and the board will boot. - -The modes are: - -1. Green LED only, *standard boot*: run ``boot.py`` then ``main.py``. -2. Orange LED only, *safe boot*: don't run any scripts on boot-up. -3. Green and orange LED together, *filesystem reset*: resets the flash - filesystem to its factory state, then boots in safe mode. - -If your filesystem becomes corrupt, boot into mode 3 to fix it. -If resetting the filesystem while plugged into your compute doesn't work, -you can try doing the same procedure while the board is plugged into a USB -charger, or other USB power supply without data connection. - -Errors: flashing LEDs ---------------------- - -There are currently 2 kinds of errors that you might see: - -1. If the red and green LEDs flash alternatively, then a Python script - (eg ``main.py``) has an error. Use the REPL to debug it. -2. If all 4 LEDs cycle on and off slowly, then there was a hard fault. - This cannot be recovered from and you need to do a hard reset. - -Guide for using the pyboard with Windows ----------------------------------------- - -The following PDF guide gives information about using the pyboard with Windows, -including setting up the serial prompt and downloading new firmware using -DFU programming: -`PDF guide `__. - -.. include:: hardware/index.rst diff --git a/docs/pyboard/hardware/index.rst b/docs/pyboard/hardware/index.rst deleted file mode 100644 index 91fea24e7a..0000000000 --- a/docs/pyboard/hardware/index.rst +++ /dev/null @@ -1,30 +0,0 @@ -.. _hardware_index: - -The pyboard hardware --------------------- - -For the pyboard: - -* `PYBv1.0 schematics and layout `_ (2.4MiB PDF) -* `PYBv1.0 metric dimensions `_ (360KiB PDF) -* `PYBv1.0 imperial dimensions `_ (360KiB PDF) - -For the official skin modules: - -* `LCD32MKv1.0 schematics `_ (194KiB PDF) -* `AMPv1.0 schematics `_ (209KiB PDF) -* LCD160CRv1.0: see :mod:`lcd160cr` - -Datasheets for the components on the pyboard --------------------------------------------- - -* The microcontroller: `STM32F405RGT6 `_ (link to manufacturer's site) -* The accelerometer: `Freescale MMA7660 `_ (800kiB PDF) -* The LDO voltage regulator: `Microchip MCP1802 `_ (400kiB PDF) - -Datasheets for other components -------------------------------- - -* The LCD display on the LCD touch-sensor skin: `Newhaven Display NHD-C12832A1Z-FSW-FBW-3V3 `_ (460KiB PDF) -* The touch sensor chip on the LCD touch-sensor skin: `Freescale MPR121 `_ (280KiB PDF) -* The digital potentiometer on the audio skin: `Microchip MCP4541 `_ (2.7MiB PDF) diff --git a/docs/pyboard/index.rst b/docs/pyboard/index.rst deleted file mode 100644 index c05e5d47fe..0000000000 --- a/docs/pyboard/index.rst +++ /dev/null @@ -1,9 +0,0 @@ -PyBoard -======================================== - -.. toctree:: - - quickref.rst - general.rst - tutorial/index.rst - hardware/index.rst diff --git a/docs/pyboard/quickref.rst b/docs/pyboard/quickref.rst deleted file mode 100644 index 48798aad3e..0000000000 --- a/docs/pyboard/quickref.rst +++ /dev/null @@ -1,217 +0,0 @@ -.. _quickref: - -Quick reference for the pyboard -=============================== - -The below pinout is for PYBv1.0. You can also view pinouts for -other versions of the pyboard: -`PYBv1.1 `__ -or `PYBLITEv1.0-AC `__ -or `PYBLITEv1.0 `__. - -.. image:: http://micropython.org/resources/pybv10-pinout.jpg - :alt: PYBv1.0 pinout - :width: 700px - -General board control ---------------------- - -See :mod:`pyb`. :: - - import pyb - - pyb.repl_uart(pyb.UART(1, 9600)) # duplicate REPL on UART(1) - pyb.wfi() # pause CPU, waiting for interrupt - pyb.freq() # get CPU and bus frequencies - pyb.freq(60000000) # set CPU freq to 60MHz - pyb.stop() # stop CPU, waiting for external interrupt - -Delay and timing ----------------- - -Use the :mod:`time ` module:: - - import time - - time.sleep(1) # sleep for 1 second - time.sleep_ms(500) # sleep for 500 milliseconds - time.sleep_us(10) # sleep for 10 microseconds - start = time.ticks_ms() # get value of millisecond counter - delta = time.ticks_diff(time.ticks_ms(), start) # compute time difference - -Internal LEDs -------------- - -See :ref:`pyb.LED `. :: - - from pyb import LED - - led = LED(1) # 1=red, 2=green, 3=yellow, 4=blue - led.toggle() - led.on() - led.off() - - # LEDs 3 and 4 support PWM intensity (0-255) - LED(4).intensity() # get intensity - LED(4).intensity(128) # set intensity to half - -Internal switch ---------------- - -See :ref:`pyb.Switch `. :: - - from pyb import Switch - - sw = Switch() - sw.value() # returns True or False - sw.callback(lambda: pyb.LED(1).toggle()) - -Pins and GPIO -------------- - -See :ref:`pyb.Pin `. :: - - from pyb import Pin - - p_out = Pin('X1', Pin.OUT_PP) - p_out.high() - p_out.low() - - p_in = Pin('X2', Pin.IN, Pin.PULL_UP) - p_in.value() # get value, 0 or 1 - -Servo control -------------- - -See :ref:`pyb.Servo `. :: - - from pyb import Servo - - s1 = Servo(1) # servo on position 1 (X1, VIN, GND) - s1.angle(45) # move to 45 degrees - s1.angle(-60, 1500) # move to -60 degrees in 1500ms - s1.speed(50) # for continuous rotation servos - -External interrupts -------------------- - -See :ref:`pyb.ExtInt `. :: - - from pyb import Pin, ExtInt - - callback = lambda e: print("intr") - ext = ExtInt(Pin('Y1'), ExtInt.IRQ_RISING, Pin.PULL_NONE, callback) - -Timers ------- - -See :ref:`pyb.Timer `. :: - - from pyb import Timer - - tim = Timer(1, freq=1000) - tim.counter() # get counter value - tim.freq(0.5) # 0.5 Hz - tim.callback(lambda t: pyb.LED(1).toggle()) - -RTC (real time clock) ---------------------- - -See :ref:`pyb.RTC ` :: - - from pyb import RTC - - rtc = RTC() - rtc.datetime((2017, 8, 23, 1, 12, 48, 0, 0)) # set a specific date and time - rtc.datetime() # get date and time - -PWM (pulse width modulation) ----------------------------- - -See :ref:`pyb.Pin ` and :ref:`pyb.Timer `. :: - - from pyb import Pin, Timer - - p = Pin('X1') # X1 has TIM2, CH1 - tim = Timer(2, freq=1000) - ch = tim.channel(1, Timer.PWM, pin=p) - ch.pulse_width_percent(50) - -ADC (analog to digital conversion) ----------------------------------- - -See :ref:`pyb.Pin ` and :ref:`pyb.ADC `. :: - - from pyb import Pin, ADC - - adc = ADC(Pin('X19')) - adc.read() # read value, 0-4095 - -DAC (digital to analog conversion) ----------------------------------- - -See :ref:`pyb.Pin ` and :ref:`pyb.DAC `. :: - - from pyb import Pin, DAC - - dac = DAC(Pin('X5')) - dac.write(120) # output between 0 and 255 - -UART (serial bus) ------------------ - -See :ref:`pyb.UART `. :: - - from pyb import UART - - uart = UART(1, 9600) - uart.write('hello') - uart.read(5) # read up to 5 bytes - -SPI bus -------- - -See :ref:`pyb.SPI `. :: - - from pyb import SPI - - spi = SPI(1, SPI.MASTER, baudrate=200000, polarity=1, phase=0) - spi.send('hello') - spi.recv(5) # receive 5 bytes on the bus - spi.send_recv('hello') # send and receive 5 bytes - -I2C bus -------- - -See :ref:`pyb.I2C `. :: - - from pyb import I2C - - i2c = I2C(1, I2C.MASTER, baudrate=100000) - i2c.scan() # returns list of slave addresses - i2c.send('hello', 0x42) # send 5 bytes to slave with address 0x42 - i2c.recv(5, 0x42) # receive 5 bytes from slave - i2c.mem_read(2, 0x42, 0x10) # read 2 bytes from slave 0x42, slave memory 0x10 - i2c.mem_write('xy', 0x42, 0x10) # write 2 bytes to slave 0x42, slave memory 0x10 - -CAN bus (controller area network) ---------------------------------- - -See :ref:`pyb.CAN `. :: - - from pyb import CAN - - can = CAN(1, CAN.LOOPBACK) - can.setfilter(0, CAN.LIST16, 0, (123, 124, 125, 126)) - can.send('message!', 123) # send a message with id 123 - can.recv(0) # receive message on FIFO 0 - -Internal accelerometer ----------------------- - -See :ref:`pyb.Accel `. :: - - from pyb import Accel - - accel = Accel() - print(accel.x(), accel.y(), accel.z(), accel.tilt()) diff --git a/docs/pyboard/tutorial/accel.rst b/docs/pyboard/tutorial/accel.rst deleted file mode 100644 index 58170e74ff..0000000000 --- a/docs/pyboard/tutorial/accel.rst +++ /dev/null @@ -1,92 +0,0 @@ -The accelerometer -================= - -Here you will learn how to read the accelerometer and signal using LEDs states like tilt left and tilt right. - -Using the accelerometer ------------------------ - -The pyboard has an accelerometer (a tiny mass on a tiny spring) that can be used -to detect the angle of the board and motion. There is a different sensor for -each of the x, y, z directions. To get the value of the accelerometer, create a -pyb.Accel() object and then call the x() method. :: - - >>> accel = pyb.Accel() - >>> accel.x() - 7 - -This returns a signed integer with a value between around -30 and 30. Note that -the measurement is very noisy, this means that even if you keep the board -perfectly still there will be some variation in the number that you measure. -Because of this, you shouldn't use the exact value of the x() method but see if -it is in a certain range. - -We will start by using the accelerometer to turn on a light if it is not flat. :: - - accel = pyb.Accel() - light = pyb.LED(3) - SENSITIVITY = 3 - - while True: - x = accel.x() - if abs(x) > SENSITIVITY: - light.on() - else: - light.off() - - pyb.delay(100) - -We create Accel and LED objects, then get the value of the x direction of the -accelerometer. If the magnitude of x is bigger than a certain value ``SENSITIVITY``, -then the LED turns on, otherwise it turns off. The loop has a small ``pyb.delay()`` -otherwise the LED flashes annoyingly when the value of x is close to -``SENSITIVITY``. Try running this on the pyboard and tilt the board left and right -to make the LED turn on and off. - -**Exercise: Change the above script so that the blue LED gets brighter the more -you tilt the pyboard. HINT: You will need to rescale the values, intensity goes -from 0-255.** - -Making a spirit level ---------------------- - -The example above is only sensitive to the angle in the x direction but if we -use the ``y()`` value and more LEDs we can turn the pyboard into a spirit level. :: - - xlights = (pyb.LED(2), pyb.LED(3)) - ylights = (pyb.LED(1), pyb.LED(4)) - - accel = pyb.Accel() - SENSITIVITY = 3 - - while True: - x = accel.x() - if x > SENSITIVITY: - xlights[0].on() - xlights[1].off() - elif x < -SENSITIVITY: - xlights[1].on() - xlights[0].off() - else: - xlights[0].off() - xlights[1].off() - - y = accel.y() - if y > SENSITIVITY: - ylights[0].on() - ylights[1].off() - elif y < -SENSITIVITY: - ylights[1].on() - ylights[0].off() - else: - ylights[0].off() - ylights[1].off() - - pyb.delay(100) - -We start by creating a tuple of LED objects for the x and y directions. Tuples -are immutable objects in python which means they can't be modified once they are -created. We then proceed as before but turn on a different LED for positive and -negative x values. We then do the same for the y direction. This isn't -particularly sophisticated but it does the job. Run this on your pyboard and you -should see different LEDs turning on depending on how you tilt the board. diff --git a/docs/pyboard/tutorial/amp_skin.rst b/docs/pyboard/tutorial/amp_skin.rst deleted file mode 100644 index 697637f9d2..0000000000 --- a/docs/pyboard/tutorial/amp_skin.rst +++ /dev/null @@ -1,98 +0,0 @@ -The AMP audio skin -================== - -Soldering and using the AMP audio skin. - -.. image:: img/skin_amp_1.jpg - :alt: AMP skin - :width: 250px - -.. image:: img/skin_amp_2.jpg - :alt: AMP skin - :width: 250px - -The following video shows how to solder the headers, microphone and speaker onto the AMP skin. - -.. raw:: html - - - -For circuit schematics and datasheets for the components on the skin see :ref:`hardware_index`. - -Example code ------------- - -The AMP skin has a speaker which is connected to ``DAC(1)`` via a small -power amplifier. The volume of the amplifier is controlled by a digital -potentiometer, which is an I2C device with address 46 on the ``IC2(1)`` bus. - -To set the volume, define the following function:: - - import pyb - def volume(val): - pyb.I2C(1, pyb.I2C.MASTER).mem_write(val, 46, 0) - -Then you can do:: - - >>> volume(0) # minimum volume - >>> volume(127) # maximum volume - -To play a sound, use the ``write_timed`` method of the ``DAC`` object. -For example:: - - import math - from pyb import DAC - - # create a buffer containing a sine-wave - buf = bytearray(100) - for i in range(len(buf)): - buf[i] = 128 + int(127 * math.sin(2 * math.pi * i / len(buf))) - - # output the sine-wave at 400Hz - dac = DAC(1) - dac.write_timed(buf, 400 * len(buf), mode=DAC.CIRCULAR) - -You can also play WAV files using the Python ``wave`` module. You can get -the wave module `here `__ and you will also need -the chunk module available `here `__. Put these -on your pyboard (either on the flash or the SD card in the top-level directory). You will need an -8-bit WAV file to play, such as `this one `_, -or to convert any file you have with the command:: - - avconv -i original.wav -ar 22050 -codec pcm_u8 test.wav - -Then you can do:: - - >>> import wave - >>> from pyb import DAC - >>> dac = DAC(1) - >>> f = wave.open('test.wav') - >>> dac.write_timed(f.readframes(f.getnframes()), f.getframerate()) - -This should play the WAV file. Note that this will read the whole file into RAM -so it has to be small enough to fit in it. - -To play larger wave files you will have to use the micro-SD card to store it. -Also the file must be read and sent to the DAC in small chunks that will fit -the RAM limit of the microcontroller. Here is an example function that can -play 8-bit wave files with up to 16kHz sampling:: - - import wave - from pyb import DAC - from pyb import delay - dac = DAC(1) - - def play(filename): - f = wave.open(filename, 'r') - total_frames = f.getnframes() - framerate = f.getframerate() - - for position in range(0, total_frames, framerate): - f.setpos(position) - dac.write_timed(f.readframes(framerate), framerate) - delay(1000) - -This function reads one second worth of data and sends it to DAC. It then waits -one second and moves the file cursor to the new position to read the next second -of data in the next iteration of the for-loop. It plays one second of audio at -a time every one second. diff --git a/docs/pyboard/tutorial/assembler.rst b/docs/pyboard/tutorial/assembler.rst deleted file mode 100644 index 1fe2bc4b07..0000000000 --- a/docs/pyboard/tutorial/assembler.rst +++ /dev/null @@ -1,131 +0,0 @@ -.. _pyboard_tutorial_assembler: - -Inline assembler -================ - -Here you will learn how to write inline assembler in MicroPython. - -**Note**: this is an advanced tutorial, intended for those who already -know a bit about microcontrollers and assembly language. - -MicroPython includes an inline assembler. It allows you to write -assembly routines as a Python function, and you can call them as you would -a normal Python function. - -Returning a value ------------------ - -Inline assembler functions are denoted by a special function decorator. -Let's start with the simplest example:: - - @micropython.asm_thumb - def fun(): - movw(r0, 42) - -You can enter this in a script or at the REPL. This function takes no -arguments and returns the number 42. ``r0`` is a register, and the value -in this register when the function returns is the value that is returned. -MicroPython always interprets the ``r0`` as an integer, and converts it to an -integer object for the caller. - -If you run ``print(fun())`` you will see it print out 42. - -Accessing peripherals ---------------------- - -For something a bit more complicated, let's turn on an LED:: - - @micropython.asm_thumb - def led_on(): - movwt(r0, stm.GPIOA) - movw(r1, 1 << 13) - strh(r1, [r0, stm.GPIO_BSRRL]) - -This code uses a few new concepts: - - - ``stm`` is a module which provides a set of constants for easy - access to the registers of the pyboard's microcontroller. Try - running ``import stm`` and then ``help(stm)`` at the REPL. It will - give you a list of all the available constants. - - - ``stm.GPIOA`` is the address in memory of the GPIOA peripheral. - On the pyboard, the red LED is on port A, pin PA13. - - - ``movwt`` moves a 32-bit number into a register. It is a convenience - function that turns into 2 thumb instructions: ``movw`` followed by ``movt``. - The ``movt`` also shifts the immediate value right by 16 bits. - - - ``strh`` stores a half-word (16 bits). The instruction above stores - the lower 16-bits of ``r1`` into the memory location ``r0 + stm.GPIO_BSRRL``. - This has the effect of setting high all those pins on port A for which - the corresponding bit in ``r0`` is set. In our example above, the 13th - bit in ``r0`` is set, so PA13 is pulled high. This turns on the red LED. - -Accepting arguments -------------------- - -Inline assembler functions can accept up to 4 arguments. If they are -used, they must be named ``r0``, ``r1``, ``r2`` and ``r3`` to reflect the registers -and the calling conventions. - -Here is a function that adds its arguments:: - - @micropython.asm_thumb - def asm_add(r0, r1): - add(r0, r0, r1) - -This performs the computation ``r0 = r0 + r1``. Since the result is put -in ``r0``, that is what is returned. Try ``asm_add(1, 2)``, it should return -3. - -Loops ------ - -We can assign labels with ``label(my_label)``, and branch to them using -``b(my_label)``, or a conditional branch like ``bgt(my_label)``. - -The following example flashes the green LED. It flashes it ``r0`` times. :: - - @micropython.asm_thumb - def flash_led(r0): - # get the GPIOA address in r1 - movwt(r1, stm.GPIOA) - - # get the bit mask for PA14 (the pin LED #2 is on) - movw(r2, 1 << 14) - - b(loop_entry) - - label(loop1) - - # turn LED on - strh(r2, [r1, stm.GPIO_BSRRL]) - - # delay for a bit - movwt(r4, 5599900) - label(delay_on) - sub(r4, r4, 1) - cmp(r4, 0) - bgt(delay_on) - - # turn LED off - strh(r2, [r1, stm.GPIO_BSRRH]) - - # delay for a bit - movwt(r4, 5599900) - label(delay_off) - sub(r4, r4, 1) - cmp(r4, 0) - bgt(delay_off) - - # loop r0 times - sub(r0, r0, 1) - label(loop_entry) - cmp(r0, 0) - bgt(loop1) - -Further reading ---------------- - -For further information about supported instructions of the inline assembler, -see the :ref:`reference documentation `. diff --git a/docs/pyboard/tutorial/debounce.rst b/docs/pyboard/tutorial/debounce.rst deleted file mode 100644 index f730e1d340..0000000000 --- a/docs/pyboard/tutorial/debounce.rst +++ /dev/null @@ -1,37 +0,0 @@ -Debouncing a pin input -====================== - -A pin used as input from a switch or other mechanical device can have a lot -of noise on it, rapidly changing from low to high when the switch is first -pressed or released. This noise can be eliminated using a capacitor (a -debouncing circuit). It can also be eliminated using a simple function that -makes sure the value on the pin is stable. - -The following function does just this. It gets the current value of the given -pin, and then waits for the value to change. The new pin value must be stable -for a continuous 20ms for it to register the change. You can adjust this time -(to say 50ms) if you still have noise. :: - - import pyb - - def wait_pin_change(pin): - # wait for pin to change value - # it needs to be stable for a continuous 20ms - cur_value = pin.value() - active = 0 - while active < 20: - if pin.value() != cur_value: - active += 1 - else: - active = 0 - pyb.delay(1) - - -Use it something like this:: - - import pyb - - pin_x1 = pyb.Pin('X1', pyb.Pin.IN, pyb.Pin.PULL_DOWN) - while True: - wait_pin_change(pin_x1) - pyb.LED(4).toggle() diff --git a/docs/pyboard/tutorial/fading_led.rst b/docs/pyboard/tutorial/fading_led.rst deleted file mode 100644 index 0a4b5c5039..0000000000 --- a/docs/pyboard/tutorial/fading_led.rst +++ /dev/null @@ -1,89 +0,0 @@ -Fading LEDs -=========== - -In addition to turning LEDs on and off, it is also possible to control the brightness of an LED using `Pulse-Width Modulation (PWM) `_, a common technique for obtaining variable output from a digital pin. This allows us to fade an LED: - -.. image:: http://upload.wikimedia.org/wikipedia/commons/a/a9/Fade.gif - -Components ----------- - -You will need: - -- Standard 5 or 3 mm LED -- 100 Ohm resistor -- Wires -- `Breadboard `_ (optional, but makes things easier) - -Connecting Things Up --------------------- - -For this tutorial, we will use the ``X1`` pin. Connect one end of the resistor to ``X1``, and the other end to the **anode** of the LED, which is the longer leg. Connect the **cathode** of the LED to ground. - -.. image:: img/fading_leds_breadboard_fritzing.png - -Code ----- -By examining the :ref:`quickref`, we see that ``X1`` is connected to channel 1 of timer 5 (``TIM5 CH1``). Therefore we will first create a ``Timer`` object for timer 5, then create a ``TimerChannel`` object for channel 1:: - - from pyb import Timer - from time import sleep - - # timer 5 will be created with a frequency of 100 Hz - tim = pyb.Timer(5, freq=100) - tchannel = tim.channel(1, Timer.PWM, pin=pyb.Pin.board.X1, pulse_width=0) - -Brightness of the LED in PWM is controlled by controlling the pulse-width, that is the amount of time the LED is on every cycle. With a timer frequency of 100 Hz, each cycle takes 0.01 second, or 10 ms. - -To achieve the fading effect shown at the beginning of this tutorial, we want to set the pulse-width to a small value, then slowly increase the pulse-width to brighten the LED, and start over when we reach some maximum brightness:: - - # maximum and minimum pulse-width, which corresponds to maximum - # and minimum brightness - max_width = 200000 - min_width = 20000 - - # how much to change the pulse-width by each step - wstep = 1500 - cur_width = min_width - - while True: - tchannel.pulse_width(cur_width) - - # this determines how often we change the pulse-width. It is - # analogous to frames-per-second - sleep(0.01) - - cur_width += wstep - - if cur_width > max_width: - cur_width = min_width - -Breathing Effect ----------------- - -If we want to have a breathing effect, where the LED fades from dim to bright then bright to dim, then we simply need to reverse the sign of ``wstep`` when we reach maximum brightness, and reverse it again at minimum brightness. To do this we modify the ``while`` loop to be:: - - while True: - tchannel.pulse_width(cur_width) - - sleep(0.01) - - cur_width += wstep - - if cur_width > max_width: - cur_width = max_width - wstep *= -1 - elif cur_width < min_width: - cur_width = min_width - wstep *= -1 - -Advanced Exercise ------------------ - -You may have noticed that the LED brightness seems to fade slowly, but increases quickly. This is because our eyes interprets brightness logarithmically (`Weber's Law `_ -), while the LED's brightness changes linearly, that is by the same amount each time. How do you solve this problem? (Hint: what is the opposite of the logarithmic function?) - -Addendum --------- - -We could have also used the digital-to-analog converter (DAC) to achieve the same effect. The PWM method has the advantage that it drives the LED with the same current each time, but for different lengths of time. This allows better control over the brightness, because LEDs do not necessarily exhibit a linear relationship between the driving current and brightness. diff --git a/docs/pyboard/tutorial/img/fading_leds_breadboard_fritzing.png b/docs/pyboard/tutorial/img/fading_leds_breadboard_fritzing.png deleted file mode 100644 index a8eec4eb62..0000000000 Binary files a/docs/pyboard/tutorial/img/fading_leds_breadboard_fritzing.png and /dev/null differ diff --git a/docs/pyboard/tutorial/img/pyboard_servo.jpg b/docs/pyboard/tutorial/img/pyboard_servo.jpg deleted file mode 100644 index 0d64e46c42..0000000000 Binary files a/docs/pyboard/tutorial/img/pyboard_servo.jpg and /dev/null differ diff --git a/docs/pyboard/tutorial/img/pyboard_usb_micro.jpg b/docs/pyboard/tutorial/img/pyboard_usb_micro.jpg deleted file mode 100644 index bc1c2b8323..0000000000 Binary files a/docs/pyboard/tutorial/img/pyboard_usb_micro.jpg and /dev/null differ diff --git a/docs/pyboard/tutorial/img/skin_amp_1.jpg b/docs/pyboard/tutorial/img/skin_amp_1.jpg deleted file mode 100644 index df44460080..0000000000 Binary files a/docs/pyboard/tutorial/img/skin_amp_1.jpg and /dev/null differ diff --git a/docs/pyboard/tutorial/img/skin_amp_2.jpg b/docs/pyboard/tutorial/img/skin_amp_2.jpg deleted file mode 100644 index 7631b3b633..0000000000 Binary files a/docs/pyboard/tutorial/img/skin_amp_2.jpg and /dev/null differ diff --git a/docs/pyboard/tutorial/img/skin_lcd_1.jpg b/docs/pyboard/tutorial/img/skin_lcd_1.jpg deleted file mode 100644 index 1dda73ffd5..0000000000 Binary files a/docs/pyboard/tutorial/img/skin_lcd_1.jpg and /dev/null differ diff --git a/docs/pyboard/tutorial/img/skin_lcd_2.jpg b/docs/pyboard/tutorial/img/skin_lcd_2.jpg deleted file mode 100644 index 6e3e1033ef..0000000000 Binary files a/docs/pyboard/tutorial/img/skin_lcd_2.jpg and /dev/null differ diff --git a/docs/pyboard/tutorial/index.rst b/docs/pyboard/tutorial/index.rst deleted file mode 100644 index 1dc155f149..0000000000 --- a/docs/pyboard/tutorial/index.rst +++ /dev/null @@ -1,48 +0,0 @@ -.. _tutorial-index: - -MicroPython tutorial for the pyboard -==================================== - -This tutorial is intended to get you started with your pyboard. -All you need is a pyboard and a micro-USB cable to connect it to -your PC. If it is your first time, it is recommended to follow -the tutorial through in the order below. - -.. toctree:: - :maxdepth: 1 - :numbered: - - intro.rst - script.rst - repl.rst - leds.rst - switch.rst - accel.rst - reset.rst - usb_mouse.rst - timer.rst - assembler.rst - power_ctrl.rst - -Tutorials requiring extra components ------------------------------------- - -.. toctree:: - :maxdepth: 1 - :numbered: - - servo.rst - fading_led.rst - lcd_skin.rst - amp_skin.rst - lcd160cr_skin.rst - -Tips, tricks and useful things to know --------------------------------------- - -.. toctree:: - :maxdepth: 1 - :numbered: - - debounce.rst - pass_through.rst diff --git a/docs/pyboard/tutorial/intro.rst b/docs/pyboard/tutorial/intro.rst deleted file mode 100644 index 78343db59a..0000000000 --- a/docs/pyboard/tutorial/intro.rst +++ /dev/null @@ -1,54 +0,0 @@ -Introduction to the pyboard -=========================== - -To get the most out of your pyboard, there are a few basic things to -understand about how it works. - -Caring for your pyboard ------------------------ - -Because the pyboard does not have a housing it needs a bit of care: - - - Be gentle when plugging/unplugging the USB cable. Whilst the USB connector - is soldered through the board and is relatively strong, if it breaks off - it can be very difficult to fix. - - - Static electricity can shock the components on the pyboard and destroy them. - If you experience a lot of static electricity in your area (eg dry and cold - climates), take extra care not to shock the pyboard. If your pyboard came - in a black plastic box, then this box is the best way to store and carry the - pyboard as it is an anti-static box (it is made of a conductive plastic, with - conductive foam inside). - -As long as you take care of the hardware, you should be okay. It's almost -impossible to break the software on the pyboard, so feel free to play around -with writing code as much as you like. If the filesystem gets corrupt, see -below on how to reset it. In the worst case you might need to reflash the -MicroPython software, but that can be done over USB. - -Layout of the pyboard ---------------------- - -The micro USB connector is on the top right, the micro SD card slot on -the top left of the board. There are 4 LEDs between the SD slot and -USB connector. The colours are: red on the bottom, then green, orange, -and blue on the top. There are 2 switches: the right one is the reset -switch, the left is the user switch. - -Plugging in and powering on ---------------------------- - -The pyboard can be powered via USB. Connect it to your PC via a micro USB -cable. There is only one way that the cable will fit. Once connected, -the green LED on the board should flash quickly. - -Powering by an external power source ------------------------------------- - -The pyboard can be powered by a battery or other external power source. - -**Be sure to connect the positive lead of the power supply to VIN, and -ground to GND. There is no polarity protection on the pyboard so you -must be careful when connecting anything to VIN.** - -**The input voltage must be between 3.6V and 10V.** diff --git a/docs/pyboard/tutorial/lcd160cr_skin.rst b/docs/pyboard/tutorial/lcd160cr_skin.rst deleted file mode 100644 index fc9d635382..0000000000 --- a/docs/pyboard/tutorial/lcd160cr_skin.rst +++ /dev/null @@ -1,134 +0,0 @@ -The LCD160CR skin -================= - -This tutorial shows how to get started using the LCD160CR skin. - -.. image:: http://micropython.org/resources/LCD160CRv10-positions.jpg - :alt: LCD160CRv1.0 picture - :width: 800px - -For detailed documentation of the driver for the display see the -:mod:`lcd160cr` module. - -Plugging in the display ------------------------ - -The display can be plugged directly into a pyboard (all pyboard versions -are supported). You plug the display onto the top of the pyboard either -in the X or Y positions. The display should cover half of the pyboard. -See the picture above for how to achieve this; the left half of the picture -shows the X position, and the right half shows the Y position. - -Getting the driver ------------------- - -You can control the display directly using a power/enable pin and an I2C -bus, but it is much more convenient to use the driver provided by the -:mod:`lcd160cr` module. This driver is included in recent version of the -pyboard firmware (see `here `__). You -can also find the driver in the GitHub repository -`here `__, and to use this version you will need to copy the file to your -board, into a directory that is searched by import (usually the lib/ -directory). - -Once you have the driver installed you need to import it to use it:: - - import lcd160cr - -Testing the display -------------------- - -There is a test program which you can use to test the features of the display, -and which also serves as a basis to start creating your own code that uses the -LCD. This test program is included in recent versions of the pyboard firmware -and is also available on GitHub -`here `__. - -To run the test from the MicroPython prompt do:: - - >>> import lcd160cr_test - -It will then print some brief instructions. You will need to know which -position your display is connected to (X or Y) and then you can run (assuming -you have the display on position X):: - - >>> test_all('X') - -Drawing some graphics ---------------------- - -You must first create an LCD160CR object which will control the display. Do this -using:: - - >>> import lcd160cr - >>> lcd = lcd160cr.LCD160CR('X') - -This assumes your display is connected in the X position. If it's in the Y -position then use ``lcd = lcd160cr.LCD160CR('Y')`` instead. - -To erase the screen and draw a line, try:: - - >>> lcd.set_pen(lcd.rgb(255, 0, 0), lcd.rgb(64, 64, 128)) - >>> lcd.erase() - >>> lcd.line(10, 10, 50, 80) - -The next example draws random rectangles on the screen. You can copy-and-paste it -into the MicroPython prompt by first pressing "Ctrl-E" at the prompt, then "Ctrl-D" -once you have pasted the text. :: - - from random import randint - for i in range(1000): - fg = lcd.rgb(randint(128, 255), randint(128, 255), randint(128, 255)) - bg = lcd.rgb(randint(0, 128), randint(0, 128), randint(0, 128)) - lcd.set_pen(fg, bg) - lcd.rect(randint(0, lcd.w), randint(0, lcd.h), randint(10, 40), randint(10, 40)) - -Using the touch sensor ----------------------- - -The display includes a resistive touch sensor that can report the position (in -pixels) of a single force-based touch on the screen. To see if there is a touch -on the screen use:: - - >>> lcd.is_touched() - -This will return either ``False`` or ``True``. Run the above command while touching -the screen to see the result. - -To get the location of the touch you can use the method:: - - >>> lcd.get_touch() - -This will return a 3-tuple, with the first entry being 0 or 1 depending on whether -there is currently anything touching the screen (1 if there is), and the second and -third entries in the tuple being the x and y coordinates of the current (or most -recent) touch. - -Directing the MicroPython output to the display ------------------------------------------------ - -The display supports input from a UART and implements basic VT100 commands, which -means it can be used as a simple, general purpose terminal. Let's set up the -pyboard to redirect its output to the display. - -First you need to create a UART object:: - - >>> import pyb - >>> uart = pyb.UART('XA', 115200) - -This assumes your display is connected to position X. If it's on position Y then -use ``uart = pyb.UART('YA', 115200)`` instead. - -Now, connect the REPL output to this UART:: - - >>> pyb.repl_uart(uart) - -From now on anything you type at the MicroPython prompt, and any output you -receive, will appear on the display. - -No set-up commands are required for this mode to work and you can use the display -to monitor the output of any UART, not just from the pyboard. All that is needed -is for the display to have power, ground and the power/enable pin driven high. -Then any characters on the display's UART input will be printed to the screen. -You can adjust the UART baudrate from the default of 115200 using the -`set_uart_baudrate` method. diff --git a/docs/pyboard/tutorial/lcd_skin.rst b/docs/pyboard/tutorial/lcd_skin.rst deleted file mode 100644 index 288ac1bf08..0000000000 --- a/docs/pyboard/tutorial/lcd_skin.rst +++ /dev/null @@ -1,86 +0,0 @@ -The LCD and touch-sensor skin -============================= - -Soldering and using the LCD and touch-sensor skin. - -.. image:: img/skin_lcd_1.jpg - :alt: pyboard with LCD skin - :width: 250px - -.. image:: img/skin_lcd_2.jpg - :alt: pyboard with LCD skin - :width: 250px - -The following video shows how to solder the headers onto the LCD skin. -At the end of the video, it shows you how to correctly connect the LCD skin to the pyboard. - -.. raw:: html - - - -For circuit schematics and datasheets for the components on the skin see :ref:`hardware_index`. - -Using the LCD -------------- - -To get started using the LCD, try the following at the MicroPython prompt. -Make sure the LCD skin is attached to the pyboard as pictured at the top of this page. :: - - >>> import pyb - >>> lcd = pyb.LCD('X') - >>> lcd.light(True) - >>> lcd.write('Hello uPy!\n') - -You can make a simple animation using the code:: - - import pyb - lcd = pyb.LCD('X') - lcd.light(True) - for x in range(-80, 128): - lcd.fill(0) - lcd.text('Hello uPy!', x, 10, 1) - lcd.show() - pyb.delay(25) - -Using the touch sensor ----------------------- - -To read the touch-sensor data you need to use the I2C bus. The -MPR121 capacitive touch sensor has address 90. - -To get started, try:: - - >>> import pyb - >>> i2c = pyb.I2C(1, pyb.I2C.MASTER) - >>> i2c.mem_write(4, 90, 0x5e) - >>> touch = i2c.mem_read(1, 90, 0)[0] - -The first line above makes an I2C object, and the second line -enables the 4 touch sensors. The third line reads the touch -status and the ``touch`` variable holds the state of the 4 touch -buttons (A, B, X, Y). - -There is a simple driver `here `__ -which allows you to set the threshold and debounce parameters, and -easily read the touch status and electrode voltage levels. Copy -this script to your pyboard (either flash or SD card, in the top -directory or ``lib/`` directory) and then try:: - - >>> import pyb - >>> import mpr121 - >>> m = mpr121.MPR121(pyb.I2C(1, pyb.I2C.MASTER)) - >>> for i in range(100): - ... print(m.touch_status()) - ... pyb.delay(100) - ... - -This will continuously print out the touch status of all electrodes. -Try touching each one in turn. - -Note that if you put the LCD skin in the Y-position, then you need to -initialise the I2C bus using:: - - >>> m = mpr121.MPR121(pyb.I2C(2, pyb.I2C.MASTER)) - -There is also a demo which uses the LCD and the touch sensors together, -and can be found `here `__. diff --git a/docs/pyboard/tutorial/leds.rst b/docs/pyboard/tutorial/leds.rst deleted file mode 100644 index 6b05f5db05..0000000000 --- a/docs/pyboard/tutorial/leds.rst +++ /dev/null @@ -1,75 +0,0 @@ -Turning on LEDs and basic Python concepts -========================================= - -The easiest thing to do on the pyboard is to turn on the LEDs attached to the board. Connect the board, and log in as described in tutorial 1. We will start by turning and LED on in the interpreter, type the following :: - - >>> myled = pyb.LED(1) - >>> myled.on() - >>> myled.off() - -These commands turn the LED on and off. - -This is all very well but we would like this process to be automated. Open the file MAIN.PY on the pyboard in your favourite text editor. Write or paste the following lines into the file. If you are new to python, then make sure you get the indentation correct since this matters! :: - - led = pyb.LED(2) - while True: - led.toggle() - pyb.delay(1000) - -When you save, the red light on the pyboard should turn on for about a second. To run the script, do a soft reset (CTRL-D). The pyboard will then restart and you should see a green light continuously flashing on and off. Success, the first step on your path to building an army of evil robots! When you are bored of the annoying flashing light then press CTRL-C at your terminal to stop it running. - -So what does this code do? First we need some terminology. Python is an object-oriented language, almost everything in python is a *class* and when you create an instance of a class you get an *object*. Classes have *methods* associated to them. A method (also called a member function) is used to interact with or control the object. - -The first line of code creates an LED object which we have then called led. When we create the object, it takes a single parameter which must be between 1 and 4, corresponding to the 4 LEDs on the board. The pyb.LED class has three important member functions that we will use: on(), off() and toggle(). The other function that we use is pyb.delay() this simply waits for a given time in miliseconds. Once we have created the LED object, the statement while True: creates an infinite loop which toggles the led between on and off and waits for 1 second. - -**Exercise: Try changing the time between toggling the led and turning on a different LED.** - -**Exercise: Connect to the pyboard directly, create a pyb.LED object and turn it on using the on() method.** - -A Disco on your pyboard ------------------------ - -So far we have only used a single LED but the pyboard has 4 available. Let's start by creating an object for each LED so we can control each of them. We do that by creating a list of LEDS with a list comprehension. :: - - leds = [pyb.LED(i) for i in range(1,5)] - -If you call pyb.LED() with a number that isn't 1,2,3,4 you will get an error message. -Next we will set up an infinite loop that cycles through each of the LEDs turning them on and off. :: - - n = 0 - while True: - n = (n + 1) % 4 - leds[n].toggle() - pyb.delay(50) - -Here, n keeps track of the current LED and every time the loop is executed we cycle to the next n (the % sign is a modulus operator that keeps n between 0 and 3.) Then we access the nth LED and toggle it. If you run this you should see each of the LEDs turning on then all turning off again in sequence. - -One problem you might find is that if you stop the script and then start it again that the LEDs are stuck on from the previous run, ruining our carefully choreographed disco. We can fix this by turning all the LEDs off when we initialise the script and then using a try/finally block. When you press CTRL-C, MicroPython generates a VCPInterrupt exception. Exceptions normally mean something has gone wrong and you can use a try: command to "catch" an exception. In this case it is just the user interrupting the script, so we don't need to catch the error but just tell MicroPython what to do when we exit. The finally block does this, and we use it to make sure all the LEDs are off. The full code is:: - - leds = [pyb.LED(i) for i in range(1,5)] - for l in leds: - l.off() - - n = 0 - try: - while True: - n = (n + 1) % 4 - leds[n].toggle() - pyb.delay(50) - finally: - for l in leds: - l.off() - -The Special LEDs ----------------- - -The yellow and blue LEDs are special. As well as turning them on and off, you can control their intensity using the intensity() method. This takes a number between 0 and 255 that determines how bright it is. The following script makes the blue LED gradually brighter then turns it off again. :: - - led = pyb.LED(4) - intensity = 0 - while True: - intensity = (intensity + 1) % 255 - led.intensity(intensity) - pyb.delay(20) - -You can call intensity() on LEDs 1 and 2 but they can only be off or on. 0 sets them off and any other number up to 255 turns them on. diff --git a/docs/pyboard/tutorial/pass_through.rst b/docs/pyboard/tutorial/pass_through.rst deleted file mode 100644 index 012a907648..0000000000 --- a/docs/pyboard/tutorial/pass_through.rst +++ /dev/null @@ -1,18 +0,0 @@ -Making a UART - USB pass through -================================ - -It's as simple as:: - - import pyb - import select - - def pass_through(usb, uart): - usb.setinterrupt(-1) - while True: - select.select([usb, uart], [], []) - if usb.any(): - uart.write(usb.read(256)) - if uart.any(): - usb.write(uart.read(256)) - - pass_through(pyb.USB_VCP(), pyb.UART(1, 9600, timeout=0)) diff --git a/docs/pyboard/tutorial/power_ctrl.rst b/docs/pyboard/tutorial/power_ctrl.rst deleted file mode 100644 index 877b7cd7ee..0000000000 --- a/docs/pyboard/tutorial/power_ctrl.rst +++ /dev/null @@ -1,13 +0,0 @@ -Power control -============= - -:meth:`pyb.wfi` is used to reduce power consumption while waiting for an -event such as an interrupt. You would use it in the following situation:: - - while True: - do_some_processing() - pyb.wfi() - -Control the frequency using :meth:`pyb.freq`:: - - pyb.freq(30000000) # set CPU frequency to 30MHz diff --git a/docs/pyboard/tutorial/repl.rst b/docs/pyboard/tutorial/repl.rst deleted file mode 100644 index 646ecbc237..0000000000 --- a/docs/pyboard/tutorial/repl.rst +++ /dev/null @@ -1,110 +0,0 @@ -Getting a MicroPython REPL prompt -================================= - -REPL stands for Read Evaluate Print Loop, and is the name given to the -interactive MicroPython prompt that you can access on the pyboard. Using -the REPL is by far the easiest way to test out your code and run commands. -You can use the REPL in addition to writing scripts in ``main.py``. - -To use the REPL, you must connect to the serial USB device on the pyboard. -How you do this depends on your operating system. - -Windows -------- - -You need to install the pyboard driver to use the serial USB device. -The driver is on the pyboard's USB flash drive, and is called ``pybcdc.inf``. - -To install this driver you need to go to Device Manager -for your computer, find the pyboard in the list of devices (it should have -a warning sign next to it because it's not working yet), right click on -the pyboard device, select Properties, then Install Driver. You need to -then select the option to find the driver manually (don't use Windows auto update), -navigate to the pyboard's USB drive, and select that. It should then install. -After installing, go back to the Device Manager to find the installed pyboard, -and see which COM port it is (eg COM4). -More comprehensive instructions can be found in the -`Guide for pyboard on Windows (PDF) `_. -Please consult this guide if you are having problems installing the driver. - -You now need to run your terminal program. You can use HyperTerminal if you -have it installed, or download the free program PuTTY: -`putty.exe `_. -Using your serial program you must connect to the COM port that you found in the -previous step. With PuTTY, click on "Session" in the left-hand panel, then click -the "Serial" radio button on the right, then enter you COM port (eg COM4) in the -"Serial Line" box. Finally, click the "Open" button. - -Mac OS X --------- - -Open a terminal and run:: - - screen /dev/tty.usbmodem* - -When you are finished and want to exit screen, type CTRL-A CTRL-\\. - -Linux ------ - -Open a terminal and run:: - - screen /dev/ttyACM0 - -You can also try ``picocom`` or ``minicom`` instead of screen. You may have to -use ``/dev/ttyACM1`` or a higher number for ``ttyACM``. And, you may need to give -yourself the correct permissions to access this devices (eg group ``uucp`` or ``dialout``, -or use sudo). - -Using the REPL prompt ---------------------- - -Now let's try running some MicroPython code directly on the pyboard. - -With your serial program open (PuTTY, screen, picocom, etc) you may see a blank -screen with a flashing cursor. Press Enter and you should be presented with a -MicroPython prompt, i.e. ``>>>``. Let's make sure it is working with the obligatory test:: - - >>> print("hello pyboard!") - hello pyboard! - -In the above, you should not type in the ``>>>`` characters. They are there to -indicate that you should type the text after it at the prompt. In the end, once -you have entered the text ``print("hello pyboard!")`` and pressed Enter, the output -on your screen should look like it does above. - -If you already know some python you can now try some basic commands here. - -If any of this is not working you can try either a hard reset or a soft reset; -see below. - -Go ahead and try typing in some other commands. For example:: - - >>> pyb.LED(1).on() - >>> pyb.LED(2).on() - >>> 1 + 2 - 3 - >>> 1 / 2 - 0.5 - >>> 20 * 'py' - 'pypypypypypypypypypypypypypypypypypypypy' - -Resetting the board -------------------- - -If something goes wrong, you can reset the board in two ways. The first is to press CTRL-D -at the MicroPython prompt, which performs a soft reset. You will see a message something like :: - - >>> - PYB: sync filesystems - PYB: soft reboot - Micro Python v1.0 on 2014-05-03; PYBv1.0 with STM32F405RG - Type "help()" for more information. - >>> - -If that isn't working you can perform a hard reset (turn-it-off-and-on-again) by pressing the RST -switch (the small black button closest to the micro-USB socket on the board). This will end your -session, disconnecting whatever program (PuTTY, screen, etc) that you used to connect to the pyboard. - -If you are going to do a hard-reset, it's recommended to first close your serial program and eject/unmount -the pyboard drive. diff --git a/docs/pyboard/tutorial/reset.rst b/docs/pyboard/tutorial/reset.rst deleted file mode 100644 index 0cd5ac21c8..0000000000 --- a/docs/pyboard/tutorial/reset.rst +++ /dev/null @@ -1,60 +0,0 @@ -Safe mode and factory reset -=========================== - -If something goes wrong with your pyboard, don't panic! It is almost -impossible for you to break the pyboard by programming the wrong thing. - -The first thing to try is to enter safe mode: this temporarily skips -execution of ``boot.py`` and ``main.py`` and gives default USB settings. - -If you have problems with the filesystem you can do a factory reset, -which restores the filesystem to its original state. - -Safe mode ---------- - -To enter safe mode, do the following steps: - -1. Connect the pyboard to USB so it powers up. -2. Hold down the USR switch. -3. While still holding down USR, press and release the RST switch. -4. The LEDs will then cycle green to orange to green+orange and back again. -5. Keep holding down USR until *only the orange LED is lit*, and then let - go of the USR switch. -6. The orange LED should flash quickly 4 times, and then turn off. -7. You are now in safe mode. - -In safe mode, the ``boot.py`` and ``main.py`` files are not executed, and so -the pyboard boots up with default settings. This means you now have access -to the filesystem (the USB drive should appear), and you can edit ``boot.py`` -and ``main.py`` to fix any problems. - -Entering safe mode is temporary, and does not make any changes to the -files on the pyboard. - -Factory reset the filesystem ----------------------------- - -If you pyboard's filesystem gets corrupted (for example, you forgot to -eject/unmount it), or you have some code in ``boot.py`` or ``main.py`` which -you can't escape from, then you can reset the filesystem. - -Resetting the filesystem deletes all files on the internal pyboard storage -(not the SD card), and restores the files ``boot.py``, ``main.py``, ``README.txt`` -and ``pybcdc.inf`` back to their original state. - -To do a factory reset of the filesystem you follow a similar procedure as -you did to enter safe mode, but release USR on green+orange: - -1. Connect the pyboard to USB so it powers up. -2. Hold down the USR switch. -3. While still holding down USR, press and release the RST switch. -4. The LEDs will then cycle green to orange to green+orange and back again. -5. Keep holding down USR until *both the green and orange LEDs are lit*, and - then let go of the USR switch. -6. The green and orange LEDs should flash quickly 4 times. -7. The red LED will turn on (so red, green and orange are now on). -8. The pyboard is now resetting the filesystem (this takes a few seconds). -9. The LEDs all turn off. -10. You now have a reset filesystem, and are in safe mode. -11. Press and release the RST switch to boot normally. diff --git a/docs/pyboard/tutorial/script.rst b/docs/pyboard/tutorial/script.rst deleted file mode 100644 index 75dd324e3c..0000000000 --- a/docs/pyboard/tutorial/script.rst +++ /dev/null @@ -1,105 +0,0 @@ -Running your first script -========================= - -Let's jump right in and get a Python script running on the pyboard. After -all, that's what it's all about! - -Connecting your pyboard ------------------------ - -Connect your pyboard to your PC (Windows, Mac or Linux) with a micro USB cable. -There is only one way that the cable will connect, so you can't get it wrong. - -.. image:: img/pyboard_usb_micro.jpg - -When the pyboard is connected to your PC it will power on and enter the start up -process (the boot process). The green LED should light up for half a second or -less, and when it turns off it means the boot process has completed. - -Opening the pyboard USB drive ------------------------------ - -Your PC should now recognise the pyboard. It depends on the type of PC you -have as to what happens next: - - - **Windows**: Your pyboard will appear as a removable USB flash drive. - Windows may automatically pop-up a window, or you may need to go there - using Explorer. - - Windows will also see that the pyboard has a serial device, and it will - try to automatically configure this device. If it does, cancel the process. - We will get the serial device working in the next tutorial. - - - **Mac**: Your pyboard will appear on the desktop as a removable disc. - It will probably be called "NONAME". Click on it to open the pyboard folder. - - - **Linux**: Your pyboard will appear as a removable medium. On Ubuntu - it will mount automatically and pop-up a window with the pyboard folder. - On other Linux distributions, the pyboard may be mounted automatically, - or you may need to do it manually. At a terminal command line, type ``lsblk`` - to see a list of connected drives, and then ``mount /dev/sdb1`` (replace ``sdb1`` - with the appropriate device). You may need to be root to do this. - -Okay, so you should now have the pyboard connected as a USB flash drive, and -a window (or command line) should be showing the files on the pyboard drive. - -The drive you are looking at is known as ``/flash`` by the pyboard, and should contain -the following 4 files: - -* `boot.py `_ -- this script is executed when the pyboard boots up. It sets - up various configuration options for the pyboard. - -* `main.py `_ -- this is the main script that will contain your Python program. - It is executed after ``boot.py``. - -* `README.txt `_ -- this contains some very basic information about getting - started with the pyboard. - -* `pybcdc.inf `_ -- this is a Windows driver file to configure the serial USB - device. More about this in the next tutorial. - -Editing ``main.py`` -------------------- - -Now we are going to write our Python program, so open the ``main.py`` -file in a text editor. On Windows you can use notepad, or any other editor. -On Mac and Linux, use your favourite text editor. With the file open you will -see it contains 1 line:: - - # main.py -- put your code here! - -This line starts with a # character, which means that it is a *comment*. Such -lines will not do anything, and are there for you to write notes about your -program. - -Let's add 2 lines to this ``main.py`` file, to make it look like this:: - - # main.py -- put your code here! - import pyb - pyb.LED(4).on() - -The first line we wrote says that we want to use the ``pyb`` module. -This module contains all the functions and classes to control the features -of the pyboard. - -The second line that we wrote turns the blue LED on: it first gets the ``LED`` -class from the ``pyb`` module, creates LED number 4 (the blue LED), and then -turns it on. - -Resetting the pyboard ---------------------- - -To run this little script, you need to first save and close the ``main.py`` file, -and then eject (or unmount) the pyboard USB drive. Do this like you would a -normal USB flash drive. - -When the drive is safely ejected/unmounted you can get to the fun part: -press the RST switch on the pyboard to reset and run your script. The RST -switch is the small black button just below the USB connector on the board, -on the right edge. - -When you press RST the green LED will flash quickly, and then the blue -LED should turn on and stay on. - -Congratulations! You have written and run your very first MicroPython -program! diff --git a/docs/pyboard/tutorial/servo.rst b/docs/pyboard/tutorial/servo.rst deleted file mode 100644 index 83d1b0cc15..0000000000 --- a/docs/pyboard/tutorial/servo.rst +++ /dev/null @@ -1,146 +0,0 @@ -Controlling hobby servo motors -============================== - -There are 4 dedicated connection points on the pyboard for connecting up -hobby servo motors (see eg -[Wikipedia](http://en.wikipedia.org/wiki/Servo_%28radio_control%29)). -These motors have 3 wires: ground, power and signal. On the pyboard you -can connect them in the bottom right corner, with the signal pin on the -far right. Pins X1, X2, X3 and X4 are the 4 dedicated servo signal pins. - -.. image:: img/pyboard_servo.jpg - -In this picture there are male-male double adaptors to connect the servos -to the header pins on the pyboard. - -The ground wire on a servo is usually the darkest coloured one, either -black or dark brown. The power wire will most likely be red. - -The power pin for the servos (labelled VIN) is connected directly to the -input power source of the pyboard. When powered via USB, VIN is powered -through a diode by the 5V USB power line. Connect to USB, the pyboard can -power at least 4 small to medium sized servo motors. - -If using a battery to power the pyboard and run servo motors, make sure it -is not greater than 6V, since this is the maximum voltage most servo motors -can take. (Some motors take only up to 4.8V, so check what type you are -using.) - -Creating a Servo object ------------------------ - -Plug in a servo to position 1 (the one with pin X1) and create a servo object -using:: - - >>> servo1 = pyb.Servo(1) - -To change the angle of the servo use the ``angle`` method:: - - >>> servo1.angle(45) - >>> servo1.angle(-60) - -The angle here is measured in degrees, and ranges from about -90 to +90, -depending on the motor. Calling ``angle`` without parameters will return -the current angle:: - - >>> servo1.angle() - -60 - -Note that for some angles, the returned angle is not exactly the same as -the angle you set, due to rounding errors in setting the pulse width. - -You can pass a second parameter to the ``angle`` method, which specifies how -long to take (in milliseconds) to reach the desired angle. For example, to -take 1 second (1000 milliseconds) to go from the current position to 50 degrees, -use :: - - >>> servo1.angle(50, 1000) - -This command will return straight away and the servo will continue to move -to the desired angle, and stop when it gets there. You can use this feature -as a speed control, or to synchronise 2 or more servo motors. If we have -another servo motor (``servo2 = pyb.Servo(2)``) then we can do :: - - >>> servo1.angle(-45, 2000); servo2.angle(60, 2000) - -This will move the servos together, making them both take 2 seconds to -reach their final angles. - -Note: the semicolon between the 2 expressions above is used so that they -are executed one after the other when you press enter at the REPL prompt. -In a script you don't need to do this, you can just write them one line -after the other. - -Continuous rotation servos --------------------------- - -So far we have been using standard servos that move to a specific angle -and stay at that angle. These servo motors are useful to create joints -of a robot, or things like pan-tilt mechanisms. Internally, the motor -has a variable resistor (potentiometer) which measures the current angle -and applies power to the motor proportional to how far it is from the -desired angle. The desired angle is set by the width of a high-pulse on -the servo signal wire. A pulse width of 1500 microsecond corresponds -to the centre position (0 degrees). The pulses are sent at 50 Hz, ie -50 pulses per second. - -You can also get **continuous rotation** servo motors which turn -continuously clockwise or counterclockwise. The direction and speed of -rotation is set by the pulse width on the signal wire. A pulse width -of 1500 microseconds corresponds to a stopped motor. A pulse width -smaller or larger than this means rotate one way or the other, at a -given speed. - -On the pyboard, the servo object for a continuous rotation motor is -the same as before. In fact, using ``angle`` you can set the speed. But -to make it easier to understand what is intended, there is another method -called ``speed`` which sets the speed:: - - >>> servo1.speed(30) - -``speed`` has the same functionality as ``angle``: you can get the speed, -set it, and set it with a time to reach the final speed. :: - - >>> servo1.speed() - 30 - >>> servo1.speed(-20) - >>> servo1.speed(0, 2000) - -The final command above will set the motor to stop, but take 2 seconds -to do it. This is essentially a control over the acceleration of the -continuous servo. - -A servo speed of 100 (or -100) is considered maximum speed, but actually -you can go a bit faster than that, depending on the particular motor. - -The only difference between the ``angle`` and ``speed`` methods (apart from -the name) is the way the input numbers (angle or speed) are converted to -a pulse width. - -Calibration ------------ - -The conversion from angle or speed to pulse width is done by the servo -object using its calibration values. To get the current calibration, -use :: - - >>> servo1.calibration() - (640, 2420, 1500, 2470, 2200) - -There are 5 numbers here, which have meaning: - -1. Minimum pulse width; the smallest pulse width that the servo accepts. -2. Maximum pulse width; the largest pulse width that the servo accepts. -3. Centre pulse width; the pulse width that puts the servo at 0 degrees - or 0 speed. -4. The pulse width corresponding to 90 degrees. This sets the conversion - in the method ``angle`` of angle to pulse width. -5. The pulse width corresponding to a speed of 100. This sets the conversion - in the method ``speed`` of speed to pulse width. - -You can recalibrate the servo (change its default values) by using:: - - >>> servo1.calibration(700, 2400, 1510, 2500, 2000) - -Of course, you would change the above values to suit your particular -servo motor. diff --git a/docs/pyboard/tutorial/switch.rst b/docs/pyboard/tutorial/switch.rst deleted file mode 100644 index 91683fba45..0000000000 --- a/docs/pyboard/tutorial/switch.rst +++ /dev/null @@ -1,113 +0,0 @@ -The Switch, callbacks and interrupts -==================================== - -The pyboard has 2 small switches, labelled USR and RST. The RST switch -is a hard-reset switch, and if you press it then it restarts the pyboard -from scratch, equivalent to turning the power off then back on. - -The USR switch is for general use, and is controlled via a Switch object. -To make a switch object do:: - - >>> sw = pyb.Switch() - -Remember that you may need to type ``import pyb`` if you get an error that -the name ``pyb`` does not exist. - -With the switch object you can get its status:: - - >>> sw.value() - False - -This will print ``False`` if the switch is not held, or ``True`` if it is held. -Try holding the USR switch down while running the above command. - -There is also a shorthand notation to get the switch status, by "calling" the -switch object:: - - >>> sw() - False - -Switch callbacks ----------------- - -The switch is a very simple object, but it does have one advanced feature: -the ``sw.callback()`` function. The callback function sets up something to -run when the switch is pressed, and uses an interrupt. It's probably best -to start with an example before understanding how interrupts work. Try -running the following at the prompt:: - - >>> sw.callback(lambda:print('press!')) - -This tells the switch to print ``press!`` each time the switch is pressed -down. Go ahead and try it: press the USR switch and watch the output on -your PC. Note that this print will interrupt anything you are typing, and -is an example of an interrupt routine running asynchronously. - -As another example try:: - - >>> sw.callback(lambda:pyb.LED(1).toggle()) - -This will toggle the red LED each time the switch is pressed. And it will -even work while other code is running. - -To disable the switch callback, pass ``None`` to the callback function:: - - >>> sw.callback(None) - -You can pass any function (that takes zero arguments) to the switch callback. -Above we used the ``lambda`` feature of Python to create an anonymous function -on the fly. But we could equally do:: - - >>> def f(): - ... pyb.LED(1).toggle() - ... - >>> sw.callback(f) - -This creates a function called ``f`` and assigns it to the switch callback. -You can do things this way when your function is more complicated than a -``lambda`` will allow. - -Note that your callback functions must not allocate any memory (for example -they cannot create a tuple or list). Callback functions should be relatively -simple. If you need to make a list, make it beforehand and store it in a -global variable (or make it local and close over it). If you need to do -a long, complicated calculation, then use the callback to set a flag which -some other code then responds to. - -Technical details of interrupts -------------------------------- - -Let's step through the details of what is happening with the switch -callback. When you register a function with ``sw.callback()``, the switch -sets up an external interrupt trigger (falling edge) on the pin that the -switch is connected to. This means that the microcontroller will listen -on the pin for any changes, and the following will occur: - -1. When the switch is pressed a change occurs on the pin (the pin goes - from low to high), and the microcontroller registers this change. -2. The microcontroller finishes executing the current machine instruction, - stops execution, and saves its current state (pushes the registers on - the stack). This has the effect of pausing any code, for example your - running Python script. -3. The microcontroller starts executing the special interrupt handler - associated with the switch's external trigger. This interrupt handler - get the function that you registered with ``sw.callback()`` and executes - it. -4. Your callback function is executed until it finishes, returning control - to the switch interrupt handler. -5. The switch interrupt handler returns, and the microcontroller is - notified that the interrupt has been dealt with. -6. The microcontroller restores the state that it saved in step 2. -7. Execution continues of the code that was running at the beginning. Apart - from the pause, this code does not notice that it was interrupted. - -The above sequence of events gets a bit more complicated when multiple -interrupts occur at the same time. In that case, the interrupt with the -highest priority goes first, then the others in order of their priority. -The switch interrupt is set at the lowest priority. - -Further reading ---------------- - -For further information about using hardware interrupts see -:ref:`writing interrupt handlers `. diff --git a/docs/pyboard/tutorial/timer.rst b/docs/pyboard/tutorial/timer.rst deleted file mode 100644 index aedaaa13c5..0000000000 --- a/docs/pyboard/tutorial/timer.rst +++ /dev/null @@ -1,114 +0,0 @@ -The Timers -========== - -The pyboard has 14 timers which each consist of an independent counter -running at a user-defined frequency. They can be set up to run a function -at specific intervals. -The 14 timers are numbered 1 through 14, but 3 is reserved -for internal use, and 5 and 6 are used for servo and ADC/DAC control. -Avoid using these timers if possible. - -Let's create a timer object:: - - >>> tim = pyb.Timer(4) - -Now let's see what we just created:: - - >>> tim - Timer(4) - -The pyboard is telling us that ``tim`` is attached to timer number 4, but -it's not yet initialised. So let's initialise it to trigger at 10 Hz -(that's 10 times per second):: - - >>> tim.init(freq=10) - -Now that it's initialised, we can see some information about the timer:: - - >>> tim - Timer(4, prescaler=624, period=13439, mode=UP, div=1) - -The information means that this timer is set to run at the peripheral -clock speed divided by 624+1, and it will count from 0 up to 13439, at which -point it triggers an interrupt, and then starts counting again from 0. These -numbers are set to make the timer trigger at 10 Hz: the source frequency -of the timer is 84MHz (found by running ``tim.source_freq()``) so we -get 84MHz / 625 / 13440 = 10Hz. - -Timer counter -------------- - -So what can we do with our timer? The most basic thing is to get the -current value of its counter:: - - >>> tim.counter() - 21504 - -This counter will continuously change, and counts up. - -Timer callbacks ---------------- - -The next thing we can do is register a callback function for the timer to -execute when it triggers (see the [switch tutorial](tut-switch) for an -introduction to callback functions):: - - >>> tim.callback(lambda t:pyb.LED(1).toggle()) - -This should start the red LED flashing right away. It will be flashing -at 5 Hz (2 toggle's are needed for 1 flash, so toggling at 10 Hz makes -it flash at 5 Hz). You can change the frequency by re-initialising the -timer:: - - >>> tim.init(freq=20) - -You can disable the callback by passing it the value ``None``:: - - >>> tim.callback(None) - -The function that you pass to callback must take 1 argument, which is -the timer object that triggered. This allows you to control the timer -from within the callback function. - -We can create 2 timers and run them independently:: - - >>> tim4 = pyb.Timer(4, freq=10) - >>> tim7 = pyb.Timer(7, freq=20) - >>> tim4.callback(lambda t: pyb.LED(1).toggle()) - >>> tim7.callback(lambda t: pyb.LED(2).toggle()) - -Because the callbacks are proper hardware interrupts, we can continue -to use the pyboard for other things while these timers are running. - -Making a microsecond counter ----------------------------- - -You can use a timer to create a microsecond counter, which might be -useful when you are doing something which requires accurate timing. -We will use timer 2 for this, since timer 2 has a 32-bit counter (so -does timer 5, but if you use timer 5 then you can't use the Servo -driver at the same time). - -We set up timer 2 as follows:: - - >>> micros = pyb.Timer(2, prescaler=83, period=0x3fffffff) - -The prescaler is set at 83, which makes this timer count at 1 MHz. -This is because the CPU clock, running at 168 MHz, is divided by -2 and then by prescaler+1, giving a frequency of 168 MHz/2/(83+1)=1 MHz -for timer 2. The period is set to a large number so that the timer -can count up to a large number before wrapping back around to zero. -In this case it will take about 17 minutes before it cycles back to -zero. - -To use this timer, it's best to first reset it to 0:: - - >>> micros.counter(0) - -and then perform your timing:: - - >>> start_micros = micros.counter() - - ... do some stuff ... - - >>> end_micros = micros.counter() diff --git a/docs/pyboard/tutorial/usb_mouse.rst b/docs/pyboard/tutorial/usb_mouse.rst deleted file mode 100644 index 6f8831edb4..0000000000 --- a/docs/pyboard/tutorial/usb_mouse.rst +++ /dev/null @@ -1,131 +0,0 @@ -Making the pyboard act as a USB mouse -===================================== - -The pyboard is a USB device, and can configured to act as a mouse instead -of the default USB flash drive. - -To do this we must first edit the ``boot.py`` file to change the USB -configuration. If you have not yet touched your ``boot.py`` file then it -will look something like this:: - - # boot.py -- run on boot-up - # can run arbitrary Python, but best to keep it minimal - - import pyb - #pyb.main('main.py') # main script to run after this one - #pyb.usb_mode('VCP+MSC') # act as a serial and a storage device - #pyb.usb_mode('VCP+HID') # act as a serial device and a mouse - -To enable the mouse mode, uncomment the last line of the file, to -make it look like:: - - pyb.usb_mode('VCP+HID') # act as a serial device and a mouse - -If you already changed your ``boot.py`` file, then the minimum code it -needs to work is:: - - import pyb - pyb.usb_mode('VCP+HID') - -This tells the pyboard to configure itself as a VCP (Virtual COM Port, -ie serial port) and HID (human interface device, in our case a mouse) -USB device when it boots up. - -Eject/unmount the pyboard drive and reset it using the RST switch. -Your PC should now detect the pyboard as a mouse! - -Sending mouse events by hand ----------------------------- - -To get the py-mouse to do anything we need to send mouse events to the PC. -We will first do this manually using the REPL prompt. Connect to your -pyboard using your serial program and type the following:: - - >>> hid = pyb.USB_HID() - >>> hid.send((0, 10, 0, 0)) - -Your mouse should move 10 pixels to the right! In the command above you -are sending 4 pieces of information: button status, x, y and scroll. The -number 10 is telling the PC that the mouse moved 10 pixels in the x direction. - -Let's make the mouse oscillate left and right:: - - >>> import math - >>> def osc(n, d): - ... for i in range(n): - ... hid.send((0, int(20 * math.sin(i / 10)), 0, 0)) - ... pyb.delay(d) - ... - >>> osc(100, 50) - -The first argument to the function ``osc`` is the number of mouse events to send, -and the second argument is the delay (in milliseconds) between events. Try -playing around with different numbers. - -**Exercise: make the mouse go around in a circle.** - -Making a mouse with the accelerometer -------------------------------------- - -Now lets make the mouse move based on the angle of the pyboard, using the -accelerometer. The following code can be typed directly at the REPL prompt, -or put in the ``main.py`` file. Here, we'll put in in ``main.py`` because to do -that we will learn how to go into safe mode. - -At the moment the pyboard is acting as a serial USB device and an HID (a mouse). -So you cannot access the filesystem to edit your ``main.py`` file. - -You also can't edit your ``boot.py`` to get out of HID-mode and back to normal -mode with a USB drive... - -To get around this we need to go into *safe mode*. This was described in -the [safe mode tutorial](tut-reset), but we repeat the instructions here: - -1. Hold down the USR switch. -2. While still holding down USR, press and release the RST switch. -3. The LEDs will then cycle green to orange to green+orange and back again. -4. Keep holding down USR until *only the orange LED is lit*, and then let - go of the USR switch. -5. The orange LED should flash quickly 4 times, and then turn off. -6. You are now in safe mode. - -In safe mode, the ``boot.py`` and ``main.py`` files are not executed, and so -the pyboard boots up with default settings. This means you now have access -to the filesystem (the USB drive should appear), and you can edit ``main.py``. -(Leave ``boot.py`` as-is, because we still want to go back to HID-mode after -we finish editing ``main.py``.) - -In ``main.py`` put the following code:: - - import pyb - - switch = pyb.Switch() - accel = pyb.Accel() - hid = pyb.USB_HID() - - while not switch(): - hid.send((0, accel.x(), accel.y(), 0)) - pyb.delay(20) - -Save your file, eject/unmount your pyboard drive, and reset it using the RST -switch. It should now act as a mouse, and the angle of the board will move -the mouse around. Try it out, and see if you can make the mouse stand still! - -Press the USR switch to stop the mouse motion. - -You'll note that the y-axis is inverted. That's easy to fix: just put a -minus sign in front of the y-coordinate in the ``hid.send()`` line above. - -Restoring your pyboard to normal --------------------------------- - -If you leave your pyboard as-is, it'll behave as a mouse everytime you plug -it in. You probably want to change it back to normal. To do this you need -to first enter safe mode (see above), and then edit the ``boot.py`` file. -In the ``boot.py`` file, comment out (put a # in front of) the line with the -``VCP+HID`` setting, so it looks like:: - - #pyb.usb_mode('VCP+HID') # act as a serial device and a mouse - -Save your file, eject/unmount the drive, and reset the pyboard. It is now -back to normal operating mode. diff --git a/docs/pyboard_index.rst b/docs/pyboard_index.rst deleted file mode 100644 index 2255a75607..0000000000 --- a/docs/pyboard_index.rst +++ /dev/null @@ -1,12 +0,0 @@ -MicroPython documentation and references -======================================== - -.. toctree:: - - pyboard/quickref.rst - pyboard/general.rst - pyboard/tutorial/index.rst - library/index.rst - reference/index.rst - genrst/index.rst - license.rst diff --git a/docs/reference/asm_thumb2_arith.rst b/docs/reference/asm_thumb2_arith.rst deleted file mode 100644 index da4a688525..0000000000 --- a/docs/reference/asm_thumb2_arith.rst +++ /dev/null @@ -1,50 +0,0 @@ -Arithmetic instructions -======================= - -Document conventions --------------------- - -Notation: ``Rd, Rm, Rn`` denote ARM registers R0-R7. ``immN`` denotes an immediate -value having a width of N bits e.g. ``imm8``, ``imm3``. ``carry`` denotes -the carry condition flag, ``not(carry)`` denotes its complement. In the case of instructions -with more than one register argument, it is permissible for some to be identical. For example -the following will add the contents of R0 to itself, placing the result in R0: - -* add(r0, r0, r0) - -Arithmetic instructions affect the condition flags except where stated. - -Addition --------- - -* add(Rdn, imm8) ``Rdn = Rdn + imm8`` -* add(Rd, Rn, imm3) ``Rd = Rn + imm3`` -* add(Rd, Rn, Rm) ``Rd = Rn +Rm`` -* adc(Rd, Rn) ``Rd = Rd + Rn + carry`` - -Subtraction ------------ - -* sub(Rdn, imm8) ``Rdn = Rdn - imm8`` -* sub(Rd, Rn, imm3) ``Rd = Rn - imm3`` -* sub(Rd, Rn, Rm) ``Rd = Rn - Rm`` -* sbc(Rd, Rn) ``Rd = Rd - Rn - not(carry)`` - -Negation --------- - -* neg(Rd, Rn) ``Rd = -Rn`` - -Multiplication and division ---------------------------- - -* mul(Rd, Rn) ``Rd = Rd * Rn`` - -This produces a 32 bit result with overflow lost. The result may be treated as -signed or unsigned according to the definition of the operands. - -* sdiv(Rd, Rn, Rm) ``Rd = Rn / Rm`` -* udiv(Rd, Rn, Rm) ``Rd = Rn / Rm`` - -These functions perform signed and unsigned division respectively. Condition flags -are not affected. diff --git a/docs/reference/asm_thumb2_compare.rst b/docs/reference/asm_thumb2_compare.rst deleted file mode 100644 index 521af69da3..0000000000 --- a/docs/reference/asm_thumb2_compare.rst +++ /dev/null @@ -1,90 +0,0 @@ -Comparison instructions -======================= - -These perform an arithmetic or logical instruction on two arguments, discarding the result -but setting the condition flags. Typically these are used to test data values without changing -them prior to executing a conditional branch. - -Document conventions --------------------- - -Notation: ``Rd, Rm, Rn`` denote ARM registers R0-R7. ``imm8`` denotes an immediate -value having a width of 8 bits. - -The Application Program Status Register (APSR) ----------------------------------------------- - -This contains four bits which are tested by the conditional branch instructions. Typically a -conditional branch will test multiple bits, for example ``bge(LABEL)``. The meaning of -condition codes can depend on whether the operands of an arithmetic instruction are viewed as -signed or unsigned integers. Thus ``bhi(LABEL)`` assumes unsigned numbers were processed while -``bgt(LABEL)`` assumes signed operands. - -APSR Bits ---------- - -* Z (zero) - -This is set if the result of an operation is zero or the operands of a comparison are equal. - -* N (negative) - -Set if the result is negative. - -* C (carry) - -An addition sets the carry flag when the result overflows out of the MSB, for example adding -0x80000000 and 0x80000000. By the nature of two's complement arithmetic this behaviour is reversed -on subtraction, with a borrow indicated by the carry bit being clear. Thus 0x10 - 0x01 is executed -as 0x10 + 0xffffffff which will set the carry bit. - -* V (overflow) - -The overflow flag is set if the result, viewed as a two's compliment number, has the "wrong" sign -in relation to the operands. For example adding 1 to 0x7fffffff will set the overflow bit because -the result (0x8000000), viewed as a two's complement integer, is negative. Note that in this instance -the carry bit is not set. - -Comparison instructions ------------------------ - -These set the APSR (Application Program Status Register) N (negative), Z (zero), C (carry) and V -(overflow) flags. - -* cmp(Rn, imm8) ``Rn - imm8`` -* cmp(Rn, Rm) ``Rn - Rm`` -* cmn(Rn, Rm) ``Rn + Rm`` -* tst(Rn, Rm) ``Rn & Rm`` - -Conditional execution ---------------------- - -The ``it`` and ``ite`` instructions provide a means of conditionally executing from one to four subsequent -instructions without the need for a label. - -* it() If then - -Execute the next instruction if is true: - -:: - - cmp(r0, r1) - it(eq) - mov(r0, 100) # runs if r0 == r1 - # execution continues here - -* ite() If then else - -If is true, execute the next instruction, otherwise execute the -subsequent one. Thus: - -:: - - cmp(r0, r1) - ite(eq) - mov(r0, 100) # runs if r0 == r1 - mov(r0, 200) # runs if r0 != r1 - # execution continues here - -This may be extended to control the execution of upto four subsequent instructions: it[x[y[z]]] -where x,y,z=t/e; e.g. itt, itee, itete, ittte, itttt, iteee, etc. diff --git a/docs/reference/asm_thumb2_directives.rst b/docs/reference/asm_thumb2_directives.rst deleted file mode 100644 index 95acd7781f..0000000000 --- a/docs/reference/asm_thumb2_directives.rst +++ /dev/null @@ -1,36 +0,0 @@ -Assembler Directives -==================== - -Labels ------- - -* label(INNER1) - -This defines a label for use in a branch instruction. Thus elsewhere in the code a ``b(INNER1)`` -will cause execution to continue with the instruction after the label directive. - -Defining inline data --------------------- - -The following assembler directives facilitate embedding data in an assembler code block. - -* data(size, d0, d1 .. dn) - -The data directive creates n array of data values in memory. The first argument specifies the -size in bytes of the subsequent arguments. Hence the first statement below will cause the -assembler to put three bytes (with values 2, 3 and 4) into consecutive memory locations -while the second will cause it to emit two four byte words. - -:: - - data(1, 2, 3, 4) - data(4, 2, 100000) - -Data values longer than a single byte are stored in memory in little-endian format. - -* align(nBytes) - -Align the following instruction to an nBytes value. ARM Thumb-2 instructions must be two -byte aligned, hence it's advisable to issue ``align(2)`` after ``data`` directives and -prior to any subsequent code. This ensures that the code will run irrespective of the -size of the data array. diff --git a/docs/reference/asm_thumb2_float.rst b/docs/reference/asm_thumb2_float.rst deleted file mode 100644 index 4acb734eeb..0000000000 --- a/docs/reference/asm_thumb2_float.rst +++ /dev/null @@ -1,77 +0,0 @@ -Floating Point instructions -============================== - -These instructions support the use of the ARM floating point coprocessor -(on platforms such as the Pyboard which are equipped with one). The FPU -has 32 registers known as ``s0-s31`` each of which can hold a single -precision float. Data can be passed between the FPU registers and the -ARM core registers with the ``vmov`` instruction. - -Note that MicroPython doesn't support passing floats to -assembler functions, nor can you put a float into ``r0`` and expect a -reasonable result. There are two ways to overcome this. The first is to -use arrays, and the second is to pass and/or return integers and convert -to and from floats in code. - -Document conventions --------------------- - -Notation: ``Sd, Sm, Sn`` denote FPU registers, ``Rd, Rm, Rn`` denote ARM core -registers. The latter can be any ARM core register although registers -``R13-R15`` are unlikely to be appropriate in this context. - -Arithmetic ----------- - -* vadd(Sd, Sn, Sm) ``Sd = Sn + Sm`` -* vsub(Sd, Sn, Sm) ``Sd = Sn - Sm`` -* vneg(Sd, Sm) ``Sd = -Sm`` -* vmul(Sd, Sn, Sm) ``Sd = Sn * Sm`` -* vdiv(Sd, Sn, Sm) ``Sd = Sn / Sm`` -* vsqrt(Sd, Sm) ``Sd = sqrt(Sm)`` - -Registers may be identical: ``vmul(S0, S0, S0)`` will execute ``S0 = S0*S0`` - -Move between ARM core and FPU registers ---------------------------------------- - -* vmov(Sd, Rm) ``Sd = Rm`` -* vmov(Rd, Sm) ``Rd = Sm`` - -The FPU has a register known as FPSCR, similar to the ARM core's APSR, which stores condition -codes plus other data. The following instructions provide access to this. - -* vmrs(APSR\_nzcv, FPSCR) - -Move the floating-point N, Z, C, and V flags to the APSR N, Z, C, and V flags. - -This is done after an instruction such as an FPU -comparison to enable the condition codes to be tested by the assembler -code. The following is a more general form of the instruction. - -* vmrs(Rd, FPSCR) ``Rd = FPSCR`` - -Move between FPU register and memory ------------------------------------- - -* vldr(Sd, [Rn, offset]) ``Sd = [Rn + offset]`` -* vstr(Sd, [Rn, offset]) ``[Rn + offset] = Sd`` - -Where ``[Rn + offset]`` denotes the memory address obtained by adding Rn to the offset. This -is specified in bytes. Since each float value occupies a 32 bit word, when accessing arrays of -floats the offset must always be a multiple of four bytes. - -Data Comparison ---------------- - -* vcmp(Sd, Sm) - -Compare the values in Sd and Sm and set the FPU N, Z, -C, and V flags. This would normally be followed by ``vmrs(APSR_nzcv, FPSCR)`` -to enable the results to be tested. - -Convert between integer and float ---------------------------------- - -* vcvt\_f32\_s32(Sd, Sm) ``Sd = float(Sm)`` -* vcvt\_s32\_f32(Sd, Sm) ``Sd = int(Sm)`` diff --git a/docs/reference/asm_thumb2_hints_tips.rst b/docs/reference/asm_thumb2_hints_tips.rst deleted file mode 100644 index 062a3c8448..0000000000 --- a/docs/reference/asm_thumb2_hints_tips.rst +++ /dev/null @@ -1,244 +0,0 @@ -Hints and tips -============== - -The following are some examples of the use of the inline assembler and some -information on how to work around its limitations. In this document the term -"assembler function" refers to a function declared in Python with the -``@micropython.asm_thumb`` decorator, whereas "subroutine" refers to assembler -code called from within an assembler function. - -Code branches and subroutines ------------------------------ - -It is important to appreciate that labels are local to an assembler function. -There is currently no way for a subroutine defined in one function to be called -from another. - -To call a subroutine the instruction ``bl(LABEL)`` is issued. This transfers -control to the instruction following the ``label(LABEL)`` directive and stores -the return address in the link register (``lr`` or ``r14``). To return the -instruction ``bx(lr)`` is issued which causes execution to continue with -the instruction following the subroutine call. This mechanism implies that, if -a subroutine is to call another, it must save the link register prior to -the call and restore it before terminating. - -The following rather contrived example illustrates a function call. Note that -it's necessary at the start to branch around all subroutine calls: subroutines -end execution with ``bx(lr)`` while the outer function simply "drops off the end" -in the style of Python functions. - -:: - - @micropython.asm_thumb - def quad(r0): - b(START) - label(DOUBLE) - add(r0, r0, r0) - bx(lr) - label(START) - bl(DOUBLE) - bl(DOUBLE) - - print(quad(10)) - -The following code example demonstrates a nested (recursive) call: the classic -Fibonacci sequence. Here, prior to a recursive call, the link register is saved -along with other registers which the program logic requires to be preserved. - -:: - - @micropython.asm_thumb - def fib(r0): - b(START) - label(DOFIB) - push({r1, r2, lr}) - cmp(r0, 1) - ble(FIBDONE) - sub(r0, 1) - mov(r2, r0) # r2 = n -1 - bl(DOFIB) - mov(r1, r0) # r1 = fib(n -1) - sub(r0, r2, 1) - bl(DOFIB) # r0 = fib(n -2) - add(r0, r0, r1) - label(FIBDONE) - pop({r1, r2, lr}) - bx(lr) - label(START) - bl(DOFIB) - - for n in range(10): - print(fib(n)) - -Argument passing and return ---------------------------- - -The tutorial details the fact that assembler functions can support from zero to -three arguments, which must (if used) be named ``r0``, ``r1`` and ``r2``. When -the code executes the registers will be initialised to those values. - -The data types which can be passed in this way are integers and memory -addresses. With current firmware all possible 32 bit values may be passed and -returned. If the return value may have the most significant bit set a Python -type hint should be employed to enable MicroPython to determine whether the -value should be interpreted as a signed or unsigned integer: types are -``int`` or ``uint``. - -:: - - @micropython.asm_thumb - def uadd(r0, r1) -> uint: - add(r0, r0, r1) - -``hex(uadd(0x40000000,0x40000000))`` will return 0x80000000, demonstrating the -passing and return of integers where bits 30 and 31 differ. - -The limitations on the number of arguments and return values can be overcome by means -of the ``array`` module which enables any number of values of any type to be accessed. - -Multiple arguments -~~~~~~~~~~~~~~~~~~ - -If a Python array of integers is passed as an argument to an assembler -function, the function will receive the address of a contiguous set of integers. -Thus multiple arguments can be passed as elements of a single array. Similarly a -function can return multiple values by assigning them to array elements. -Assembler functions have no means of determining the length of an array: -this will need to be passed to the function. - -This use of arrays can be extended to enable more than three arrays to be used. -This is done using indirection: the ``uctypes`` module supports ``addressof()`` -which will return the address of an array passed as its argument. Thus you can -populate an integer array with the addresses of other arrays: - -:: - - from uctypes import addressof - @micropython.asm_thumb - def getindirect(r0): - ldr(r0, [r0, 0]) # Address of array loaded from passed array - ldr(r0, [r0, 4]) # Return element 1 of indirect array (24) - - def testindirect(): - a = array.array('i',[23, 24]) - b = array.array('i',[0,0]) - b[0] = addressof(a) - print(getindirect(b)) - -Non-integer data types -~~~~~~~~~~~~~~~~~~~~~~ - -These may be handled by means of arrays of the appropriate data type. For -example, single precision floating point data may be processed as follows. -This code example takes an array of floats and replaces its contents with -their squares. - -:: - - from array import array - - @micropython.asm_thumb - def square(r0, r1): - label(LOOP) - vldr(s0, [r0, 0]) - vmul(s0, s0, s0) - vstr(s0, [r0, 0]) - add(r0, 4) - sub(r1, 1) - bgt(LOOP) - - a = array('f', (x for x in range(10))) - square(a, len(a)) - print(a) - -The uctypes module supports the use of data structures beyond simple -arrays. It enables a Python data structure to be mapped onto a bytearray -instance which may then be passed to the assembler function. - -Named constants ---------------- - -Assembler code may be made more readable and maintainable by using named -constants rather than littering code with numbers. This may be achieved -thus: - -:: - - MYDATA = const(33) - - @micropython.asm_thumb - def foo(): - mov(r0, MYDATA) - -The const() construct causes MicroPython to replace the variable name -with its value at compile time. If constants are declared in an outer -Python scope they can be shared between multiple assembler functions and -with Python code. - -Assembler code as class methods -------------------------------- - -MicroPython passes the address of the object instance as the first argument -to class methods. This is normally of little use to an assembler function. -It can be avoided by declaring the function as a static method thus: - -:: - - class foo: - @staticmethod - @micropython.asm_thumb - def bar(r0): - add(r0, r0, r0) - -Use of unsupported instructions -------------------------------- - -These can be coded using the data statement as shown below. While -``push()`` and ``pop()`` are supported the example below illustrates the -principle. The necessary machine code may be found in the ARM v7-M -Architecture Reference Manual. Note that the first argument of data -calls such as - -:: - - data(2, 0xe92d, 0x0f00) # push r8,r9,r10,r11 - -indicates that each subsequent argument is a two byte quantity. - -Overcoming MicroPython's integer restriction --------------------------------------------- - -The Pyboard chip includes a CRC generator. Its use presents a problem in -MicroPython because the returned values cover the full gamut of 32 bit -quantities whereas small integers in MicroPython cannot have differing values -in bits 30 and 31. This limitation is overcome with the following code, which -uses assembler to put the result into an array and Python code to -coerce the result into an arbitrary precision unsigned integer. - -:: - - from array import array - import stm - - def enable_crc(): - stm.mem32[stm.RCC + stm.RCC_AHB1ENR] |= 0x1000 - - def reset_crc(): - stm.mem32[stm.CRC+stm.CRC_CR] = 1 - - @micropython.asm_thumb - def getval(r0, r1): - movwt(r3, stm.CRC + stm.CRC_DR) - str(r1, [r3, 0]) - ldr(r2, [r3, 0]) - str(r2, [r0, 0]) - - def getcrc(value): - a = array('i', [0]) - getval(a, value) - return a[0] & 0xffffffff # coerce to arbitrary precision - - enable_crc() - reset_crc() - for x in range(20): - print(hex(getcrc(0))) diff --git a/docs/reference/asm_thumb2_index.rst b/docs/reference/asm_thumb2_index.rst deleted file mode 100644 index f066e6acec..0000000000 --- a/docs/reference/asm_thumb2_index.rst +++ /dev/null @@ -1,73 +0,0 @@ -.. _asm_thumb2_index: - -Inline Assembler for Thumb2 architectures -========================================= - -This document assumes some familiarity with assembly language programming and should be read after studying -the :ref:`tutorial `. For a detailed description of the instruction set consult the -Architecture Reference Manual detailed below. -The inline assembler supports a subset of the ARM Thumb-2 instruction set described here. The syntax tries -to be as close as possible to that defined in the above ARM manual, converted to Python function calls. - -Instructions operate on 32 bit signed integer data except where stated otherwise. Most supported instructions -operate on registers ``R0-R7`` only: where ``R8-R15`` are supported this is stated. Registers ``R8-R12`` must be -restored to their initial value before return from a function. Registers ``R13-R15`` constitute the Link Register, -Stack Pointer and Program Counter respectively. - -Document conventions --------------------- - -Where possible the behaviour of each instruction is described in Python, for example - -* add(Rd, Rn, Rm) ``Rd = Rn + Rm`` - -This enables the effect of instructions to be demonstrated in Python. In certain case this is impossible -because Python doesn't support concepts such as indirection. The pseudocode employed in such cases is -described on the relevant page. - -Instruction Categories ----------------------- - -The following sections details the subset of the ARM Thumb-2 instruction set supported by MicroPython. - -.. toctree:: - :maxdepth: 1 - :numbered: - - asm_thumb2_mov.rst - asm_thumb2_ldr.rst - asm_thumb2_str.rst - asm_thumb2_logical_bit.rst - asm_thumb2_arith.rst - asm_thumb2_compare.rst - asm_thumb2_label_branch.rst - asm_thumb2_stack.rst - asm_thumb2_misc.rst - asm_thumb2_float.rst - asm_thumb2_directives.rst - -Usage examples --------------- - -These sections provide further code examples and hints on the use of the assembler. - -.. toctree:: - :maxdepth: 1 - :numbered: - - asm_thumb2_hints_tips.rst - -References ----------- - -- :ref:`Assembler Tutorial ` -- `Wiki hints and tips - `__ -- `uPy Inline Assembler source-code, - emitinlinethumb.c `__ -- `ARM Thumb2 Instruction Set Quick Reference - Card `__ -- `RM0090 Reference - Manual `__ -- ARM v7-M Architecture Reference Manual (Available on the - ARM site after a simple registration procedure. Also available on academic sites but beware of out of date versions.) diff --git a/docs/reference/asm_thumb2_label_branch.rst b/docs/reference/asm_thumb2_label_branch.rst deleted file mode 100644 index 8c85e55f0e..0000000000 --- a/docs/reference/asm_thumb2_label_branch.rst +++ /dev/null @@ -1,85 +0,0 @@ -Branch instructions -=================== - -These cause execution to jump to a target location usually specified by a label (see the ``label`` -assembler directive). Conditional branches and the ``it`` and ``ite`` instructions test -the Application Program Status Register (APSR) N (negative), Z (zero), C (carry) and V -(overflow) flags to determine whether the branch should be executed. - -Most of the exposed assembler instructions (including move operations) set the flags but -there are explicit comparison instructions to enable values to be tested. - -Further detail on the meaning of the condition flags is provided in the section -describing comparison functions. - -Document conventions --------------------- - -Notation: ``Rm`` denotes ARM registers R0-R15. ``LABEL`` denotes a label defined with the -``label()`` assembler directive. ```` indicates one of the following condition -specifiers: - -* eq Equal to (result was zero) -* ne Not equal -* cs Carry set -* cc Carry clear -* mi Minus (negative) -* pl Plus (positive) -* vs Overflow set -* vc Overflow clear -* hi > (unsigned comparison) -* ls <= (unsigned comparison) -* ge >= (signed comparison) -* lt < (signed comparison) -* gt > (signed comparison) -* le <= (signed comparison) - -Branch to label ---------------- - -* b(LABEL) Unconditional branch -* beq(LABEL) branch if equal -* bne(LABEL) branch if not equal -* bge(LABEL) branch if greater than or equal -* bgt(LABEL) branch if greater than -* blt(LABEL) branch if less than (<) (signed) -* ble(LABEL) branch if less than or equal to (<=) (signed) -* bcs(LABEL) branch if carry flag is set -* bcc(LABEL) branch if carry flag is clear -* bmi(LABEL) branch if negative -* bpl(LABEL) branch if positive -* bvs(LABEL) branch if overflow flag set -* bvc(LABEL) branch if overflow flag is clear -* bhi(LABEL) branch if higher (unsigned) -* bls(LABEL) branch if lower or equal (unsigned) - -Long branches -------------- - -The code produced by the branch instructions listed above uses a fixed bit width to specify the -branch destination, which is PC relative. Consequently in long programs where the -branch instruction is remote from its destination the assembler will produce a "branch not in -range" error. This can be overcome with the "wide" variants such as - -* beq\_w(LABEL) long branch if equal - -Wide branches use 4 bytes to encode the instruction (compared with 2 bytes for standard branch instructions). - -Subroutines (functions) ------------------------ - -When entering a subroutine the processor stores the return address in register r14, also -known as the link register (lr). Return to the instruction after the subroutine call is -performed by updating the program counter (r15 or pc) from the link register, This -process is handled by the following instructions. - -* bl(LABEL) - -Transfer execution to the instruction after ``LABEL`` storing the return address in -the link register (r14). - -* bx(Rm) Branch to address specified by Rm. - -Typically ``bx(lr)`` is issued to return from a subroutine. For nested subroutines the -link register of outer scopes must be saved (usually on the stack) before performing -inner subroutine calls. diff --git a/docs/reference/asm_thumb2_ldr.rst b/docs/reference/asm_thumb2_ldr.rst deleted file mode 100644 index 16b7729592..0000000000 --- a/docs/reference/asm_thumb2_ldr.rst +++ /dev/null @@ -1,23 +0,0 @@ -Load register from memory -========================= - -Document conventions --------------------- - -Notation: ``Rt, Rn`` denote ARM registers R0-R7 except where stated. ``immN`` represents an immediate -value having a width of N bits hence ``imm5`` is constrained to the range 0-31. ``[Rn + immN]`` is the contents -of the memory address obtained by adding Rn and the offset ``immN``. Offsets are measured in -bytes. These instructions affect the condition flags. - -Register Load -------------- - -* ldr(Rt, [Rn, imm7]) ``Rt = [Rn + imm7]`` Load a 32 bit word -* ldrb(Rt, [Rn, imm5]) ``Rt = [Rn + imm5]`` Load a byte -* ldrh(Rt, [Rn, imm6]) ``Rt = [Rn + imm6]`` Load a 16 bit half word - -Where a byte or half word is loaded, it is zero-extended to 32 bits. - -The specified immediate offsets are measured in bytes. Hence in the case of ``ldr`` the 7 bit value -enables 32 bit word aligned values to be accessed with a maximum offset of 31 words. In the case of ``ldrh`` the -6 bit value enables 16 bit half-word aligned values to be accessed with a maximum offset of 31 half-words. diff --git a/docs/reference/asm_thumb2_logical_bit.rst b/docs/reference/asm_thumb2_logical_bit.rst deleted file mode 100644 index 8c51feaf45..0000000000 --- a/docs/reference/asm_thumb2_logical_bit.rst +++ /dev/null @@ -1,53 +0,0 @@ -Logical & Bitwise instructions -============================== - -Document conventions --------------------- - -Notation: ``Rd, Rn`` denote ARM registers R0-R7 except in the case of the -special instructions where R0-R15 may be used. ``Rn`` denotes an ARM register -whose contents must lie in range ``a <= contents <= b``. In the case of instructions -with two register arguments, it is permissible for them to be identical. For example -the following will zero R0 (Python ``R0 ^= R0``) regardless of its initial contents. - -* eor(r0, r0) - -These instructions affect the condition flags except where stated. - -Logical instructions --------------------- - -* and\_(Rd, Rn) ``Rd &= Rn`` -* orr(Rd, Rn) ``Rd |= Rn`` -* eor(Rd, Rn) ``Rd ^= Rn`` -* mvn(Rd, Rn) ``Rd = Rn ^ 0xffffffff`` i.e. Rd = 1's complement of Rn -* bic(Rd, Rn) ``Rd &= ~Rn`` bit clear Rd using mask in Rn - -Note the use of "and\_" instead of "and", because "and" is a reserved keyword in Python. - -Shift and rotation instructions -------------------------------- - -* lsl(Rd, Rn<0-31>) ``Rd <<= Rn`` -* lsr(Rd, Rn<1-32>) ``Rd = (Rd & 0xffffffff) >> Rn`` Logical shift right -* asr(Rd, Rn<1-32>) ``Rd >>= Rn`` arithmetic shift right -* ror(Rd, Rn<1-31>) ``Rd = rotate_right(Rd, Rn)`` Rd is rotated right Rn bits. - -A rotation by (for example) three bits works as follows. If Rd initially -contains bits ``b31 b30..b0`` after rotation it will contain ``b2 b1 b0 b31 b30..b3`` - -Special instructions --------------------- - -Condition codes are unaffected by these instructions. - -* clz(Rd, Rn) ``Rd = count_leading_zeros(Rn)`` - -count_leading_zeros(Rn) returns the number of binary zero bits before the first binary one bit in Rn. - -* rbit(Rd, Rn) ``Rd = bit_reverse(Rn)`` - -bit_reverse(Rn) returns the bit-reversed contents of Rn. If Rn contains bits ``b31 b30..b0`` Rd will be set -to ``b0 b1 b2..b31`` - -Trailing zeros may be counted by performing a bit reverse prior to executing clz. diff --git a/docs/reference/asm_thumb2_misc.rst b/docs/reference/asm_thumb2_misc.rst deleted file mode 100644 index ca3f878cca..0000000000 --- a/docs/reference/asm_thumb2_misc.rst +++ /dev/null @@ -1,13 +0,0 @@ -Miscellaneous instructions -========================== - -* nop() ``pass`` no operation. -* wfi() Suspend execution in a low power state until an interrupt occurs. -* cpsid(flags) set the Priority Mask Register - disable interrupts. -* cpsie(flags) clear the Priority Mask Register - enable interrupts. -* mrs(Rd, special_reg) ``Rd = special_reg`` copy a special register to a general register. The special register - may be IPSR (Interrupt Status Register) or BASEPRI (Base Priority Register). The IPSR provides a means of determining - the exception number of an interrupt being processed. It contains zero if no interrupt is being processed. - -Currently the ``cpsie()`` and ``cpsid()`` functions are partially implemented. -They require but ignore the flags argument and serve as a means of enabling and disabling interrupts. diff --git a/docs/reference/asm_thumb2_mov.rst b/docs/reference/asm_thumb2_mov.rst deleted file mode 100644 index 900bf957b6..0000000000 --- a/docs/reference/asm_thumb2_mov.rst +++ /dev/null @@ -1,27 +0,0 @@ -Register move instructions -========================== - -Document conventions --------------------- - -Notation: ``Rd, Rn`` denote ARM registers R0-R15. ``immN`` denotes an immediate -value having a width of N bits. These instructions affect the condition flags. - -Register moves --------------- - -Where immediate values are used, these are zero-extended to 32 bits. Thus -``mov(R0, 0xff)`` will set R0 to 255. - -* mov(Rd, imm8) ``Rd = imm8`` -* mov(Rd, Rn) ``Rd = Rn`` -* movw(Rd, imm16) ``Rd = imm16`` -* movt(Rd, imm16) ``Rd = (Rd & 0xffff) | (imm16 << 16)`` - -movt writes an immediate value to the top halfword of the destination register. -It does not affect the contents of the bottom halfword. - -* movwt(Rd, imm32) ``Rd = imm32`` - -movwt is a pseudo-instruction: the MicroPython assembler emits a ``movw`` followed -by a ``movt`` to move a 32-bit value into Rd. diff --git a/docs/reference/asm_thumb2_stack.rst b/docs/reference/asm_thumb2_stack.rst deleted file mode 100644 index bffbab277c..0000000000 --- a/docs/reference/asm_thumb2_stack.rst +++ /dev/null @@ -1,20 +0,0 @@ -Stack push and pop -================== - -Document conventions --------------------- - -The ``push()`` and ``pop()`` instructions accept as their argument a register set containing -a subset, or possibly all, of the general-purpose registers R0-R12 and the link register (lr or R14). -As with any Python set the order in which the registers are specified is immaterial. Thus the -in the following example the pop() instruction would restore R1, R7 and R8 to their contents prior -to the push(): - -* push({r1, r8, r7}) Save three registers on the stack. -* pop({r7, r1, r8}) Restore them - -Stack operations ----------------- - -* push({regset}) Push a set of registers onto the stack -* pop({regset}) Restore a set of registers from the stack diff --git a/docs/reference/asm_thumb2_str.rst b/docs/reference/asm_thumb2_str.rst deleted file mode 100644 index 5a88b091bd..0000000000 --- a/docs/reference/asm_thumb2_str.rst +++ /dev/null @@ -1,21 +0,0 @@ -Store register to memory -======================== - -Document conventions --------------------- - -Notation: ``Rt, Rn`` denote ARM registers R0-R7 except where stated. ``immN`` represents an immediate -value having a width of N bits hence ``imm5`` is constrained to the range 0-31. ``[Rn + imm5]`` is the -contents of the memory address obtained by adding Rn and the offset ``imm5``. Offsets are measured in -bytes. These instructions do not affect the condition flags. - -Register Store --------------- - -* str(Rt, [Rn, imm7]) ``[Rn + imm7] = Rt`` Store a 32 bit word -* strb(Rt, [Rn, imm5]) ``[Rn + imm5] = Rt`` Store a byte (b0-b7) -* strh(Rt, [Rn, imm6]) ``[Rn + imm6] = Rt`` Store a 16 bit half word (b0-b15) - -The specified immediate offsets are measured in bytes. Hence in the case of ``str`` the 7 bit value -enables 32 bit word aligned values to be accessed with a maximum offset of 31 words. In the case of ``strh`` the -6 bit value enables 16 bit half-word aligned values to be accessed with a maximum offset of 31 half-words. diff --git a/docs/reference/constrained.rst b/docs/reference/constrained.rst deleted file mode 100644 index e7de459bc9..0000000000 --- a/docs/reference/constrained.rst +++ /dev/null @@ -1,456 +0,0 @@ -.. _constrained: - -MicroPython on Microcontrollers -=============================== - -MicroPython is designed to be capable of running on microcontrollers. These -have hardware limitations which may be unfamiliar to programmers more familiar -with conventional computers. In particular the amount of RAM and nonvolatile -"disk" (flash memory) storage is limited. This tutorial offers ways to make -the most of the limited resources. Because MicroPython runs on controllers -based on a variety of architectures, the methods presented are generic: in some -cases it will be necessary to obtain detailed information from platform specific -documentation. - -Flash Memory ------------- - -On the Pyboard the simple way to address the limited capacity is to fit a micro -SD card. In some cases this is impractical, either because the device does not -have an SD card slot or for reasons of cost or power consumption; hence the -on-chip flash must be used. The firmware including the MicroPython subsystem is -stored in the onboard flash. The remaining capacity is available for use. For -reasons connected with the physical architecture of the flash memory part of -this capacity may be inaccessible as a filesystem. In such cases this space may -be employed by incorporating user modules into a firmware build which is then -flashed to the device. - -There are two ways to achieve this: frozen modules and frozen bytecode. Frozen -modules store the Python source with the firmware. Frozen bytecode uses the -cross compiler to convert the source to bytecode which is then stored with the -firmware. In either case the module may be accessed with an import statement: - -.. code:: - - import mymodule - -The procedure for producing frozen modules and bytecode is platform dependent; -instructions for building the firmware can be found in the README files in the -relevant part of the source tree. - -In general terms the steps are as follows: - -* Clone the MicroPython `repository `_. -* Acquire the (platform specific) toolchain to build the firmware. -* Build the cross compiler. -* Place the modules to be frozen in a specified directory (dependent on whether - the module is to be frozen as source or as bytecode). -* Build the firmware. A specific command may be required to build frozen - code of either type - see the platform documentation. -* Flash the firmware to the device. - -RAM ---- - -When reducing RAM usage there are two phases to consider: compilation and -execution. In addition to memory consumption, there is also an issue known as -heap fragmentation. In general terms it is best to minimise the repeated -creation and destruction of objects. The reason for this is covered in the -section covering the `heap`_. - -Compilation Phase -~~~~~~~~~~~~~~~~~ - -When a module is imported, MicroPython compiles the code to bytecode which is -then executed by the MicroPython virtual machine (VM). The bytecode is stored -in RAM. The compiler itself requires RAM, but this becomes available for use -when the compilation has completed. - -If a number of modules have already been imported the situation can arise where -there is insufficient RAM to run the compiler. In this case the import -statement will produce a memory exception. - -If a module instantiates global objects on import it will consume RAM at the -time of import, which is then unavailable for the compiler to use on subsequent -imports. In general it is best to avoid code which runs on import; a better -approach is to have initialisation code which is run by the application after -all modules have been imported. This maximises the RAM available to the -compiler. - -If RAM is still insufficient to compile all modules one solution is to -precompile modules. MicroPython has a cross compiler capable of compiling Python -modules to bytecode (see the README in the mpy-cross directory). The resulting -bytecode file has a .mpy extension; it may be copied to the filesystem and -imported in the usual way. Alternatively some or all modules may be implemented -as frozen bytecode: on most platforms this saves even more RAM as the bytecode -is run directly from flash rather than being stored in RAM. - -Execution Phase -~~~~~~~~~~~~~~~ - -There are a number of coding techniques for reducing RAM usage. - -**Constants** - -MicroPython provides a ``const`` keyword which may be used as follows: - -.. code:: - - from micropython import const - ROWS = const(33) - _COLS = const(0x10) - a = ROWS - b = _COLS - -In both instances where the constant is assigned to a variable the compiler -will avoid coding a lookup to the name of the constant by substituting its -literal value. This saves bytecode and hence RAM. However the ``ROWS`` value -will occupy at least two machine words, one each for the key and value in the -globals dictionary. The presence in the dictionary is necessary because another -module might import or use it. This RAM can be saved by prepending the name -with an underscore as in ``_COLS``: this symbol is not visible outside the -module so will not occupy RAM. - -The argument to ``const()`` may be anything which, at compile time, evaluates -to an integer e.g. ``0x100`` or ``1 << 8``. It can even include other const -symbols that have already been defined, e.g. ``1 << BIT``. - -**Constant data structures** - -Where there is a substantial volume of constant data and the platform supports -execution from Flash, RAM may be saved as follows. The data should be located in -Python modules and frozen as bytecode. The data must be defined as `bytes` -objects. The compiler 'knows' that `bytes` objects are immutable and ensures -that the objects remain in flash memory rather than being copied to RAM. The -`ustruct` module can assist in converting between `bytes` types and other -Python built-in types. - -When considering the implications of frozen bytecode, note that in Python -strings, floats, bytes, integers and complex numbers are immutable. Accordingly -these will be frozen into flash. Thus, in the line - -.. code:: - - mystring = "The quick brown fox" - -the actual string "The quick brown fox" will reside in flash. At runtime a -reference to the string is assigned to the *variable* ``mystring``. The reference -occupies a single machine word. In principle a long integer could be used to -store constant data: - -.. code:: - - bar = 0xDEADBEEF0000DEADBEEF - -As in the string example, at runtime a reference to the arbitrarily large -integer is assigned to the variable ``bar``. That reference occupies a -single machine word. - -It might be expected that tuples of integers could be employed for the purpose -of storing constant data with minimal RAM use. With the current compiler this -is ineffective (the code works, but RAM is not saved). - -.. code:: - - foo = (1, 2, 3, 4, 5, 6, 100000) - -At runtime the tuple will be located in RAM. This may be subject to future -improvement. - -**Needless object creation** - -There are a number of situations where objects may unwittingly be created and -destroyed. This can reduce the usability of RAM through fragmentation. The -following sections discuss instances of this. - -**String concatenation** - -Consider the following code fragments which aim to produce constant strings: - -.. code:: - - var = "foo" + "bar" - var1 = "foo" "bar" - var2 = """\ - foo\ - bar""" - -Each produces the same outcome, however the first needlessly creates two string -objects at runtime, allocates more RAM for concatenation before producing the -third. The others perform the concatenation at compile time which is more -efficient, reducing fragmentation. - -Where strings must be dynamically created before being fed to a stream such as -a file it will save RAM if this is done in a piecemeal fashion. Rather than -creating a large string object, create a substring and feed it to the stream -before dealing with the next. - -The best way to create dynamic strings is by means of the string `format` -method: - -.. code:: - - var = "Temperature {:5.2f} Pressure {:06d}\n".format(temp, press) - -**Buffers** - -When accessing devices such as instances of UART, I2C and SPI interfaces, using -pre-allocated buffers avoids the creation of needless objects. Consider these -two loops: - -.. code:: - - while True: - var = spi.read(100) - # process data - - buf = bytearray(100) - while True: - spi.readinto(buf) - # process data in buf - -The first creates a buffer on each pass whereas the second re-uses a pre-allocated -buffer; this is both faster and more efficient in terms of memory fragmentation. - -**Bytes are smaller than ints** - -On most platforms an integer consumes four bytes. Consider the two calls to the -function ``foo()``: - -.. code:: - - def foo(bar): - for x in bar: - print(x) - foo((1, 2, 0xff)) - foo(b'\1\2\xff') - -In the first call a tuple of integers is created in RAM. The second efficiently -creates a `bytes` object consuming the minimum amount of RAM. If the module -were frozen as bytecode, the `bytes` object would reside in flash. - -**Strings Versus Bytes** - -Python3 introduced Unicode support. This introduced a distinction between a -string and an array of bytes. MicroPython ensures that Unicode strings take no -additional space so long as all characters in the string are ASCII (i.e. have -a value < 126). If values in the full 8-bit range are required `bytes` and -`bytearray` objects can be used to ensure that no additional space will be -required. Note that most string methods (e.g. :meth:`str.strip()`) apply also to `bytes` -instances so the process of eliminating Unicode can be painless. - -.. code:: - - s = 'the quick brown fox' # A string instance - b = b'the quick brown fox' # A bytes instance - -Where it is necessary to convert between strings and bytes the :meth:`str.encode` -and the :meth:`bytes.decode` methods can be used. Note that both strings and bytes -are immutable. Any operation which takes as input such an object and produces -another implies at least one RAM allocation to produce the result. In the -second line below a new bytes object is allocated. This would also occur if ``foo`` -were a string. - -.. code:: - - foo = b' empty whitespace' - foo = foo.lstrip() - -**Runtime compiler execution** - -The Python funcitons `eval` and `exec` invoke the compiler at runtime, which -requires significant amounts of RAM. Note that the `pickle` library from -`micropython-lib` employs `exec`. It may be more RAM efficient to use the -`ujson` library for object serialisation. - -**Storing strings in flash** - -Python strings are immutable hence have the potential to be stored in read only -memory. The compiler can place in flash strings defined in Python code. As with -frozen modules it is necessary to have a copy of the source tree on the PC and -the toolchain to build the firmware. The procedure will work even if the -modules have not been fully debugged, so long as they can be imported and run. - -After importing the modules, execute: - -.. code:: - - micropython.qstr_info(1) - -Then copy and paste all the Q(xxx) lines into a text editor. Check for and -remove lines which are obviously invalid. Open the file qstrdefsport.h which -will be found in ports/stm32 (or the equivalent directory for the architecture in -use). Copy and paste the corrected lines at the end of the file. Save the file, -rebuild and flash the firmware. The outcome can be checked by importing the -modules and again issuing: - -.. code:: - - micropython.qstr_info(1) - -The Q(xxx) lines should be gone. - -.. _heap: - -The Heap --------- - -When a running program instantiates an object the necessary RAM is allocated -from a fixed size pool known as the heap. When the object goes out of scope (in -other words becomes inaccessible to code) the redundant object is known as -"garbage". A process known as "garbage collection" (GC) reclaims that memory, -returning it to the free heap. This process runs automatically, however it can -be invoked directly by issuing `gc.collect()`. - -The discourse on this is somewhat involved. For a 'quick fix' issue the -following periodically: - -.. code:: - - gc.collect() - gc.threshold(gc.mem_free() // 4 + gc.mem_alloc()) - -Fragmentation -~~~~~~~~~~~~~ - -Say a program creates an object ``foo``, then an object ``bar``. Subsequently -``foo`` goes out of scope but ``bar`` remains. The RAM used by ``foo`` will be -reclaimed by GC. However if ``bar`` was allocated to a higher address, the -RAM reclaimed from ``foo`` will only be of use for objects no bigger than -``foo``. In a complex or long running program the heap can become fragmented: -despite there being a substantial amount of RAM available, there is insufficient -contiguous space to allocate a particular object, and the program fails with a -memory error. - -The techniques outlined above aim to minimise this. Where large permanent buffers -or other objects are required it is best to instantiate these early in the -process of program execution before fragmentation can occur. Further improvements -may be made by monitoring the state of the heap and by controlling GC; these are -outlined below. - -Reporting -~~~~~~~~~ - -A number of library functions are available to report on memory allocation and -to control GC. These are to be found in the `gc` and `micropython` modules. -The following example may be pasted at the REPL (``ctrl e`` to enter paste mode, -``ctrl d`` to run it). - -.. code:: - - import gc - import micropython - gc.collect() - micropython.mem_info() - print('-----------------------------') - print('Initial free: {} allocated: {}'.format(gc.mem_free(), gc.mem_alloc())) - def func(): - a = bytearray(10000) - gc.collect() - print('Func definition: {} allocated: {}'.format(gc.mem_free(), gc.mem_alloc())) - func() - print('Func run free: {} allocated: {}'.format(gc.mem_free(), gc.mem_alloc())) - gc.collect() - print('Garbage collect free: {} allocated: {}'.format(gc.mem_free(), gc.mem_alloc())) - print('-----------------------------') - micropython.mem_info(1) - -Methods employed above: - -* `gc.collect()` Force a garbage collection. See footnote. -* `micropython.mem_info()` Print a summary of RAM utilisation. -* `gc.mem_free()` Return the free heap size in bytes. -* `gc.mem_alloc()` Return the number of bytes currently allocated. -* ``micropython.mem_info(1)`` Print a table of heap utilisation (detailed below). - -The numbers produced are dependent on the platform, but it can be seen that -declaring the function uses a small amount of RAM in the form of bytecode -emitted by the compiler (the RAM used by the compiler has been reclaimed). -Running the function uses over 10KiB, but on return ``a`` is garbage because it -is out of scope and cannot be referenced. The final `gc.collect()` recovers -that memory. - -The final output produced by ``micropython.mem_info(1)`` will vary in detail but -may be interpreted as follows: - -====== ================= -Symbol Meaning -====== ================= - . free block - h head block - = tail block - m marked head block - T tuple - L list - D dict - F float - B byte code - M module -====== ================= - -Each letter represents a single block of memory, a block being 16 bytes. So each -line of the heap dump represents 0x400 bytes or 1KiB of RAM. - -Control of Garbage Collection -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -A GC can be demanded at any time by issuing `gc.collect()`. It is advantageous -to do this at intervals, firstly to pre-empt fragmentation and secondly for -performance. A GC can take several milliseconds but is quicker when there is -little work to do (about 1ms on the Pyboard). An explicit call can minimise that -delay while ensuring it occurs at points in the program when it is acceptable. - -Automatic GC is provoked under the following circumstances. When an attempt at -allocation fails, a GC is performed and the allocation re-tried. Only if this -fails is an exception raised. Secondly an automatic GC will be triggered if the -amount of free RAM falls below a threshold. This threshold can be adapted as -execution progresses: - -.. code:: - - gc.collect() - gc.threshold(gc.mem_free() // 4 + gc.mem_alloc()) - -This will provoke a GC when more than 25% of the currently free heap becomes -occupied. - -In general modules should instantiate data objects at runtime using constructors -or other initialisation functions. The reason is that if this occurs on -initialisation the compiler may be starved of RAM when subsequent modules are -imported. If modules do instantiate data on import then `gc.collect()` issued -after the import will ameliorate the problem. - -String Operations ------------------ - -MicroPython handles strings in an efficient manner and understanding this can -help in designing applications to run on microcontrollers. When a module -is compiled, strings which occur multiple times are stored once only, a process -known as string interning. In MicroPython an interned string is known as a ``qstr``. -In a module imported normally that single instance will be located in RAM, but -as described above, in modules frozen as bytecode it will be located in flash. - -String comparisons are also performed efficiently using hashing rather than -character by character. The penalty for using strings rather than integers may -hence be small both in terms of performance and RAM usage - a fact which may -come as a surprise to C programmers. - -Postscript ----------- - -MicroPython passes, returns and (by default) copies objects by reference. A -reference occupies a single machine word so these processes are efficient in -RAM usage and speed. - -Where variables are required whose size is neither a byte nor a machine word -there are standard libraries which can assist in storing these efficiently and -in performing conversions. See the `array`, `ustruct` and `uctypes` -modules. - -Footnote: gc.collect() return value -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -On Unix and Windows platforms the `gc.collect()` method returns an integer -which signifies the number of distinct memory regions that were reclaimed in the -collection (more precisely, the number of heads that were turned into frees). For -efficiency reasons bare metal ports do not return this value. diff --git a/docs/reference/glossary.rst b/docs/reference/glossary.rst deleted file mode 100644 index 4cd3d84cc5..0000000000 --- a/docs/reference/glossary.rst +++ /dev/null @@ -1,105 +0,0 @@ -Glossary -======== - -.. glossary:: - - baremetal - A system without (full-fledged) OS, like an :term:`MCU`. When - running on a baremetal system, MicroPython effectively becomes - its user-facing OS with a command interpreter (REPL). - - board - A PCB board. Oftentimes, the term is used to denote a particular - model of an :term:`MCU` system. Sometimes, it is used to actually - refer to :term:`MicroPython port` to a particular board (and then - may also refer to "boardless" ports like - :term:`Unix port `). - - CPython - CPython is the reference implementation of Python programming - language, and the most well-known one, which most of the people - run. It is however one of many implementations (among which - Jython, IronPython, PyPy, and many more, including MicroPython). - As there is no formal specification of the Python language, only - CPython documentation, it is not always easy to draw a line - between Python the language and CPython its particular - implementation. This however leaves more freedom for other - implementations. For example, MicroPython does a lot of things - differently than CPython, while still aspiring to be a Python - language implementation. - - GPIO - General-purpose input/output. The simplest means to control - electrical signals. With GPIO, user can configure hardware - signal pin to be either input or output, and set or get - its digital signal value (logical "0" or "1"). MicroPython - abstracts GPIO access using :class:`machine.Pin` and :class:`machine.Signal` - classes. - - GPIO port - A group of :term:`GPIO` pins, usually based on hardware - properties of these pins (e.g. controllable by the same - register). - - MCU - Microcontroller. Microcontrollers usually have much less resources - than a full-fledged computing system, but smaller, cheaper and - require much less power. MicroPython is designed to be small and - optimized enough to run on an average modern microcontroller. - - micropython-lib - MicroPython is (usually) distributed as a single executable/binary - file with just few builtin modules. There is no extensive standard - library comparable with :term:`CPython`. Instead, there is a related, but - separate project - `micropython-lib `_ - which provides implementations for many modules from CPython's - standard library. However, large subset of these modules require - POSIX-like environment (Linux, MacOS, Windows may be partially - supported), and thus would work or make sense only with - `MicroPython Unix port`. Some subset of modules is however usable - for `baremetal` ports too. - - Unlike monolithic :term:`CPython` stdlib, micropython-lib modules - are intended to be installed individually - either using manual - copying or using :term:`upip`. - - MicroPython port - MicroPython supports different :term:`boards `, RTOSes, - and OSes, and can be relatively easily adapted to new systems. - MicroPython with support for a particular system is called a - "port" to that system. Different ports may have widely different - functionality. This documentation is intended to be a reference - of the generic APIs available across different ports ("MicroPython - core"). Note that some ports may still omit some APIs described - here (e.g. due to resource constraints). Any such differences, - and port-specific extensions beyond MicroPython core functionality, - would be described in the separate port-specific documentation. - - MicroPython Unix port - Unix port is one of the major :term:`MicroPython ports `. - It is intended to run on POSIX-compatible operating systems, like - Linux, MacOS, FreeBSD, Solaris, etc. It also serves as the basis - of Windows port. The importance of Unix port lies in the fact - that while there are many different :term:`boards `, so - two random users unlikely have the same board, almost all modern - OSes have some level of POSIX compatibility, so Unix port serves - as a kind of "common ground" to which any user can have access. - So, Unix port is used for initial prototyping, different kinds - of testing, development of machine-independent features, etc. - All users of MicroPython, even those which are interested only - in running MicroPython on :term:`MCU` systems, are recommended - to be familiar with Unix (or Windows) port, as it is important - productivity helper and a part of normal MicroPython workflow. - - port - Either :term:`MicroPython port` or :term:`GPIO port`. If not clear - from context, it's recommended to use full specification like one - of the above. - - upip - (Literally, "micro pip"). A package manage for MicroPython, inspired - by :term:`CPython`'s pip, but much smaller and with reduced functionality. - upip runs both on :term:`Unix port ` and on - :term:`baremetal` ports (those which offer filesystem and networking - support). diff --git a/docs/reference/index.rst b/docs/reference/index.rst deleted file mode 100644 index 4d822d6fa6..0000000000 --- a/docs/reference/index.rst +++ /dev/null @@ -1,33 +0,0 @@ -The MicroPython language -======================== - -MicroPython aims to implement the Python 3.4 standard (with selected -features from later versions) with respect to language syntax, and most -of the features of MicroPython are identical to those described by the -"Language Reference" documentation at -`docs.python.org `_. - -The MicroPython standard library is described in the -:ref:`corresponding chapter `. The :ref:`cpython_diffs` -chapter describes differences between MicroPython and CPython (which -mostly concern standard library and types, but also some language-level -features). - -This chapter describes features and peculiarities of MicroPython -implementation and the best practices to use them. - -.. toctree:: - :maxdepth: 1 - - glossary.rst - repl.rst - isr_rules.rst - speed_python.rst - constrained.rst - -.. only:: port_pyboard - - .. toctree:: - :maxdepth: 1 - - asm_thumb2_index.rst diff --git a/docs/reference/isr_rules.rst b/docs/reference/isr_rules.rst deleted file mode 100644 index 2db261c09d..0000000000 --- a/docs/reference/isr_rules.rst +++ /dev/null @@ -1,353 +0,0 @@ -.. _isr_rules: - -Writing interrupt handlers -========================== - -On suitable hardware MicroPython offers the ability to write interrupt handlers in Python. Interrupt handlers -- also known as interrupt service routines (ISR's) - are defined as callback functions. These are executed -in response to an event such as a timer trigger or a voltage change on a pin. Such events can occur at any point -in the execution of the program code. This carries significant consequences, some specific to the MicroPython -language. Others are common to all systems capable of responding to real time events. This document covers -the language specific issues first, followed by a brief introduction to real time programming for those new to it. - -This introduction uses vague terms like "slow" or "as fast as possible". This is deliberate, as speeds are -application dependent. Acceptable durations for an ISR are dependent on the rate at which interrupts occur, -the nature of the main program, and the presence of other concurrent events. - -Tips and recommended practices ------------------------------- - -This summarises the points detailed below and lists the principal recommendations for interrupt handler code. - -* Keep the code as short and simple as possible. -* Avoid memory allocation: no appending to lists or insertion into dictionaries, no floating point. -* Consider using ``micropython.schedule`` to work around the above constraint. -* Where an ISR returns multiple bytes use a pre-allocated ``bytearray``. If multiple integers are to be - shared between an ISR and the main program consider an array (``array.array``). -* Where data is shared between the main program and an ISR, consider disabling interrupts prior to accessing - the data in the main program and re-enabling them immediately afterwards (see Critical Sections). -* Allocate an emergency exception buffer (see below). - - -MicroPython Issues ------------------- - -The emergency exception buffer -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If an error occurs in an ISR, MicroPython is unable to produce an error report unless a special buffer is created -for the purpose. Debugging is simplified if the following code is included in any program using interrupts. - -.. code:: python - - import micropython - micropython.alloc_emergency_exception_buf(100) - -Simplicity -~~~~~~~~~~ - -For a variety of reasons it is important to keep ISR code as short and simple as possible. It should do only what -has to be done immediately after the event which caused it: operations which can be deferred should be delegated -to the main program loop. Typically an ISR will deal with the hardware device which caused the interrupt, making -it ready for the next interrupt to occur. It will communicate with the main loop by updating shared data to indicate -that the interrupt has occurred, and it will return. An ISR should return control to the main loop as quickly -as possible. This is not a specific MicroPython issue so is covered in more detail :ref:`below `. - -Communication between an ISR and the main program -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Normally an ISR needs to communicate with the main program. The simplest means of doing this is via one or more -shared data objects, either declared as global or shared via a class (see below). There are various restrictions -and hazards around doing this, which are covered in more detail below. Integers, ``bytes`` and ``bytearray`` objects -are commonly used for this purpose along with arrays (from the array module) which can store various data types. - -The use of object methods as callbacks -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -MicroPython supports this powerful technique which enables an ISR to share instance variables with the underlying -code. It also enables a class implementing a device driver to support multiple device instances. The following -example causes two LED's to flash at different rates. - -.. code:: python - - import pyb, micropython - micropython.alloc_emergency_exception_buf(100) - class Foo(object): - def __init__(self, timer, led): - self.led = led - timer.callback(self.cb) - def cb(self, tim): - self.led.toggle() - - red = Foo(pyb.Timer(4, freq=1), pyb.LED(1)) - green = Foo(pyb.Timer(2, freq=0.8), pyb.LED(2)) - -In this example the ``red`` instance associates timer 4 with LED 1: when a timer 4 interrupt occurs ``red.cb()`` -is called causing LED 1 to change state. The ``green`` instance operates similarly: a timer 2 interrupt -results in the execution of ``green.cb()`` and toggles LED 2. The use of instance methods confers two -benefits. Firstly a single class enables code to be shared between multiple hardware instances. Secondly, as -a bound method the callback function's first argument is ``self``. This enables the callback to access instance -data and to save state between successive calls. For example, if the class above had a variable ``self.count`` -set to zero in the constructor, ``cb()`` could increment the counter. The ``red`` and ``green`` instances would -then maintain independent counts of the number of times each LED had changed state. - -Creation of Python objects -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -ISR's cannot create instances of Python objects. This is because MicroPython needs to allocate memory for the -object from a store of free memory block called the heap. This is not permitted in an interrupt handler because -heap allocation is not re-entrant. In other words the interrupt might occur when the main program is part way -through performing an allocation - to maintain the integrity of the heap the interpreter disallows memory -allocations in ISR code. - -A consequence of this is that ISR's can't use floating point arithmetic; this is because floats are Python objects. Similarly -an ISR can't append an item to a list. In practice it can be hard to determine exactly which code constructs will -attempt to perform memory allocation and provoke an error message: another reason for keeping ISR code short and simple. - -One way to avoid this issue is for the ISR to use pre-allocated buffers. For example a class constructor -creates a ``bytearray`` instance and a boolean flag. The ISR method assigns data to locations in the buffer and sets -the flag. The memory allocation occurs in the main program code when the object is instantiated rather than in the ISR. - -The MicroPython library I/O methods usually provide an option to use a pre-allocated buffer. For -example ``pyb.i2c.recv()`` can accept a mutable buffer as its first argument: this enables its use in an ISR. - -A means of creating an object without employing a class or globals is as follows: - -.. code:: python - - def set_volume(t, buf=bytearray(3)): - buf[0] = 0xa5 - buf[1] = t >> 4 - buf[2] = 0x5a - return buf - -The compiler instantiates the default ``buf`` argument when the function is -loaded for the first time (usually when the module it's in is imported). - -Use of Python objects -~~~~~~~~~~~~~~~~~~~~~ - -A further restriction on objects arises because of the way Python works. When an ``import`` statement is executed the -Python code is compiled to bytecode, with one line of code typically mapping to multiple bytecodes. When the code -runs the interpreter reads each bytecode and executes it as a series of machine code instructions. Given that an -interrupt can occur at any time between machine code instructions, the original line of Python code may be only -partially executed. Consequently a Python object such as a set, list or dictionary modified in the main loop -may lack internal consistency at the moment the interrupt occurs. - -A typical outcome is as follows. On rare occasions the ISR will run at the precise moment in time when the object -is partially updated. When the ISR tries to read the object, a crash results. Because such problems typically occur -on rare, random occasions they can be hard to diagnose. There are ways to circumvent this issue, described in -:ref:`Critical Sections ` below. - -It is important to be clear about what constitutes the modification of an object. An alteration to a built-in type -such as a dictionary is problematic. Altering the contents of an array or bytearray is not. This is because bytes -or words are written as a single machine code instruction which is not interruptible: in the parlance of real time -programming the write is atomic. A user defined object might instantiate an integer, array or bytearray. It is valid -for both the main loop and the ISR to alter the contents of these. - -MicroPython supports integers of arbitrary precision. Values between 2**30 -1 and -2**30 will be stored in -a single machine word. Larger values are stored as Python objects. Consequently changes to long integers cannot -be considered atomic. The use of long integers in ISR's is unsafe because memory allocation may be -attempted as the variable's value changes. - -Overcoming the float limitation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In general it is best to avoid using floats in ISR code: hardware devices normally handle integers and conversion -to floats is normally done in the main loop. However there are a few DSP algorithms which require floating point. -On platforms with hardware floating point (such as the Pyboard) the inline ARM Thumb assembler can be used to work -round this limitation. This is because the processor stores float values in a machine word; values can be shared -between the ISR and main program code via an array of floats. - -Using micropython.schedule -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This function enables an ISR to schedule a callback for execution "very soon". The callback is queued for -execution which will take place at a time when the heap is not locked. Hence it can create Python objects -and use floats. The callback is also guaranteed to run at a time when the main program has completed any -update of Python objects, so the callback will not encounter partially updated objects. - -Typical usage is to handle sensor hardware. The ISR acquires data from the hardware and enables it to -issue a further interrupt. It then schedules a callback to process the data. - -Scheduled callbacks should comply with the principles of interrupt handler design outlined below. This is to -avoid problems resulting from I/O activity and the modification of shared data which can arise in any code -which pre-empts the main program loop. - -Execution time needs to be considered in relation to the frequency with which interrupts can occur. If an -interrupt occurs while the previous callback is executing, a further instance of the callback will be queued -for execution; this will run after the current instance has completed. A sustained high interrupt repetition -rate therefore carries a risk of unconstrained queue growth and eventual failure with a ``RuntimeError``. - -Exceptions ----------- - -If an ISR raises an exception it will not propagate to the main loop. The interrupt will be disabled unless the -exception is handled by the ISR code. - -General Issues --------------- - -This is merely a brief introduction to the subject of real time programming. Beginners should note -that design errors in real time programs can lead to faults which are particularly hard to diagnose. This is because -they can occur rarely and at intervals which are essentially random. It is crucial to get the initial design right and -to anticipate issues before they arise. Both interrupt handlers and the main program need to be designed -with an appreciation of the following issues. - -.. _ISR: - -Interrupt Handler Design -~~~~~~~~~~~~~~~~~~~~~~~~ - -As mentioned above, ISR's should be designed to be as simple as possible. They should always return in a short, -predictable period of time. This is important because when the ISR is running, the main loop is not: inevitably -the main loop experiences pauses in its execution at random points in the code. Such pauses can be a source of hard -to diagnose bugs particularly if their duration is long or variable. In order to understand the implications of -ISR run time, a basic grasp of interrupt priorities is required. - -Interrupts are organised according to a priority scheme. ISR code may itself be interrupted by a higher priority -interrupt. This has implications if the two interrupts share data (see Critical Sections below). If such an interrupt -occurs it interposes a delay into the ISR code. If a lower priority interrupt occurs while the ISR is running, it -will be delayed until the ISR is complete: if the delay is too long, the lower priority interrupt may fail. A -further issue with slow ISR's is the case where a second interrupt of the same type occurs during its execution. -The second interrupt will be handled on termination of the first. However if the rate of incoming interrupts -consistently exceeds the capacity of the ISR to service them the outcome will not be a happy one. - -Consequently looping constructs should be avoided or minimised. I/O to devices other than to the interrupting device -should normally be avoided: I/O such as disk access, ``print`` statements and UART access is relatively slow, and -its duration may vary. A further issue here is that filesystem functions are not reentrant: using filesystem I/O -in an ISR and the main program would be hazardous. Crucially ISR code should not wait on an event. I/O is acceptable -if the code can be guaranteed to return in a predictable period, for example toggling a pin or LED. Accessing the -interrupting device via I2C or SPI may be necessary but the time taken for such accesses should be calculated or -measured and its impact on the application assessed. - -There is usually a need to share data between the ISR and the main loop. This may be done either through global -variables or via class or instance variables. Variables are typically integer or boolean types, or integer or byte -arrays (a pre-allocated integer array offers faster access than a list). Where multiple values are modified by -the ISR it is necessary to consider the case where the interrupt occurs at a time when the main program has -accessed some, but not all, of the values. This can lead to inconsistencies. - -Consider the following design. An ISR stores incoming data in a bytearray, then adds the number of bytes -received to an integer representing total bytes ready for processing. The main program reads the number of bytes, -processes the bytes, then clears down the number of bytes ready. This will work until an interrupt occurs just -after the main program has read the number of bytes. The ISR puts the added data into the buffer and updates -the number received, but the main program has already read the number, so processes the data originally received. -The newly arrived bytes are lost. - -There are various ways of avoiding this hazard, the simplest being to use a circular buffer. If it is not possible -to use a structure with inherent thread safety other ways are described below. - -Reentrancy -~~~~~~~~~~ - -A potential hazard may occur if a function or method is shared between the main program and one or more ISR's or -between multiple ISR's. The issue here is that the function may itself be interrupted and a further instance of -that function run. If this is to occur, the function must be designed to be reentrant. How this is done is an -advanced topic beyond the scope of this tutorial. - -.. _Critical: - -Critical Sections -~~~~~~~~~~~~~~~~~ - -An example of a critical section of code is one which accesses more than one variable which can be affected by an ISR. If -the interrupt happens to occur between accesses to the individual variables, their values will be inconsistent. This is -an instance of a hazard known as a race condition: the ISR and the main program loop race to alter the variables. To -avoid inconsistency a means must be employed to ensure that the ISR does not alter the values for the duration of -the critical section. One way to achieve this is to issue ``pyb.disable_irq()`` before the start of the section, and -``pyb.enable_irq()`` at the end. Here is an example of this approach: - -.. code:: python - - import pyb, micropython, array - micropython.alloc_emergency_exception_buf(100) - - class BoundsException(Exception): - pass - - ARRAYSIZE = const(20) - index = 0 - data = array.array('i', 0 for x in range(ARRAYSIZE)) - - def callback1(t): - global data, index - for x in range(5): - data[index] = pyb.rng() # simulate input - index += 1 - if index >= ARRAYSIZE: - raise BoundsException('Array bounds exceeded') - - tim4 = pyb.Timer(4, freq=100, callback=callback1) - - for loop in range(1000): - if index > 0: - irq_state = pyb.disable_irq() # Start of critical section - for x in range(index): - print(data[x]) - index = 0 - pyb.enable_irq(irq_state) # End of critical section - print('loop {}'.format(loop)) - pyb.delay(1) - - tim4.callback(None) - -A critical section can comprise a single line of code and a single variable. Consider the following code fragment. - -.. code:: python - - count = 0 - def cb(): # An interrupt callback - count +=1 - def main(): - # Code to set up the interrupt callback omitted - while True: - count += 1 - -This example illustrates a subtle source of bugs. The line ``count += 1`` in the main loop carries a specific race -condition hazard known as a read-modify-write. This is a classic cause of bugs in real time systems. In the main loop -MicroPython reads the value of ``t.counter``, adds 1 to it, and writes it back. On rare occasions the interrupt occurs -after the read and before the write. The interrupt modifies ``t.counter`` but its change is overwritten by the main -loop when the ISR returns. In a real system this could lead to rare, unpredictable failures. - -As mentioned above, care should be taken if an instance of a Python built in type is modified in the main code and -that instance is accessed in an ISR. The code performing the modification should be regarded as a critical -section to ensure that the instance is in a valid state when the ISR runs. - -Particular care needs to be taken if a dataset is shared between different ISR's. The hazard here is that the higher -priority interrupt may occur when the lower priority one has partially updated the shared data. Dealing with this -situation is an advanced topic beyond the scope of this introduction other than to note that mutex objects described -below can sometimes be used. - -Disabling interrupts for the duration of a critical section is the usual and simplest way to proceed, but it disables -all interrupts rather than merely the one with the potential to cause problems. It is generally undesirable to disable -an interrupt for long. In the case of timer interrupts it introduces variability to the time when a callback occurs. -In the case of device interrupts, it can lead to the device being serviced too late with possible loss of data or -overrun errors in the device hardware. Like ISR's, a critical section in the main code should have a short, predictable -duration. - -An approach to dealing with critical sections which radically reduces the time for which interrupts are disabled is to -use an object termed a mutex (name derived from the notion of mutual exclusion). The main program locks the mutex -before running the critical section and unlocks it at the end. The ISR tests whether the mutex is locked. If it is, -it avoids the critical section and returns. The design challenge is defining what the ISR should do in the event -that access to the critical variables is denied. A simple example of a mutex may be found -`here `_. Note that the mutex code does disable interrupts, -but only for the duration of eight machine instructions: the benefit of this approach is that other interrupts are -virtually unaffected. - -Interrupts and the REPL -~~~~~~~~~~~~~~~~~~~~~~~ - -Interrupt handlers, such as those associated with timers, can continue to run -after a program terminates. This may produce unexpected results where you might -have expected the object raising the callback to have gone out of scope. For -example on the Pyboard: - -.. code:: python - - def bar(): - foo = pyb.Timer(2, freq=4, callback=lambda t: print('.', end='')) - - bar() - -This continues to run until the timer is explicitly disabled or the board is -reset with ``ctrl D``. diff --git a/docs/reference/repl.rst b/docs/reference/repl.rst deleted file mode 100644 index 7a683ca220..0000000000 --- a/docs/reference/repl.rst +++ /dev/null @@ -1,211 +0,0 @@ -The MicroPython Interactive Interpreter Mode (aka REPL) -======================================================= - -This section covers some characteristics of the MicroPython Interactive -Interpreter Mode. A commonly used term for this is REPL (read-eval-print-loop) -which will be used to refer to this interactive prompt. - -Auto-indent ------------ - -When typing python statements which end in a colon (for example if, for, while) -then the prompt will change to three dots (...) and the cursor will be indented -by 4 spaces. When you press return, the next line will continue at the same -level of indentation for regular statements or an additional level of indentation -where appropriate. If you press the backspace key then it will undo one -level of indentation. - -If your cursor is all the way back at the beginning, pressing RETURN will then -execute the code that you've entered. The following shows what you'd see -after entering a for statement (the underscore shows where the cursor winds up): - - >>> for i in range(3): - ... _ - -If you then enter an if statement, an additional level of indentation will be -provided: - - >>> for i in range(30): - ... if i > 3: - ... _ - -Now enter ``break`` followed by RETURN and press BACKSPACE: - - >>> for i in range(30): - ... if i > 3: - ... break - ... _ - -Finally type ``print(i)``, press RETURN, press BACKSPACE and press RETURN again: - - >>> for i in range(30): - ... if i > 3: - ... break - ... print(i) - ... - 0 - 1 - 2 - 3 - >>> - -Auto-indent won't be applied if the previous two lines were all spaces. This -means that you can finish entering a compound statement by pressing RETURN -twice, and then a third press will finish and execute. - -Auto-completion ---------------- - -While typing a command at the REPL, if the line typed so far corresponds to -the beginning of the name of something, then pressing TAB will show -possible things that could be entered. For example type ``m`` and press TAB -and it should expand to ``machine``. Enter a dot ``.`` and press TAB again. You -should see something like: - - >>> machine. - __name__ info unique_id reset - bootloader freq rng idle - sleep deepsleep disable_irq enable_irq - Pin - -The word will be expanded as much as possible until multiple possibilities exist. -For example, type ``machine.Pin.AF3`` and press TAB and it will expand to -``machine.Pin.AF3_TIM``. Pressing TAB a second time will show the possible -expansions: - - >>> machine.Pin.AF3_TIM - AF3_TIM10 AF3_TIM11 AF3_TIM8 AF3_TIM9 - >>> machine.Pin.AF3_TIM - -Interrupting a running program ------------------------------- - -You can interrupt a running program by pressing Ctrl-C. This will raise a KeyboardInterrupt -which will bring you back to the REPL, providing your program doesn't intercept the -KeyboardInterrupt exception. - -For example: - - >>> for i in range(1000000): - ... print(i) - ... - 0 - 1 - 2 - 3 - ... - 6466 - 6467 - 6468 - Traceback (most recent call last): - File "", line 2, in - KeyboardInterrupt: - >>> - -Paste Mode ----------- - -If you want to paste some code into your terminal window, the auto-indent feature -will mess things up. For example, if you had the following python code: :: - - def foo(): - print('This is a test to show paste mode') - print('Here is a second line') - foo() - -and you try to paste this into the normal REPL, then you will see something like -this: - - >>> def foo(): - ... print('This is a test to show paste mode') - ... print('Here is a second line') - ... foo() - ... - Traceback (most recent call last): - File "", line 3 - IndentationError: unexpected indent - -If you press Ctrl-E, then you will enter paste mode, which essentially turns off -the auto-indent feature, and changes the prompt from ``>>>`` to ``===``. For example: - - >>> - paste mode; Ctrl-C to cancel, Ctrl-D to finish - === def foo(): - === print('This is a test to show paste mode') - === print('Here is a second line') - === foo() - === - This is a test to show paste mode - Here is a second line - >>> - -Paste Mode allows blank lines to be pasted. The pasted text is compiled as if -it were a file. Pressing Ctrl-D exits paste mode and initiates the compilation. - -Soft Reset ----------- - -A soft reset will reset the python interpreter, but tries not to reset the -method by which you're connected to the MicroPython board (USB-serial, or Wifi). - -You can perform a soft reset from the REPL by pressing Ctrl-D, or from your python -code by executing: :: - - raise SystemExit - -For example, if you reset your MicroPython board, and you execute a dir() -command, you'd see something like this: - - >>> dir() - ['__name__', 'pyb'] - -Now create some variables and repeat the dir() command: - - >>> i = 1 - >>> j = 23 - >>> x = 'abc' - >>> dir() - ['j', 'x', '__name__', 'pyb', 'i'] - >>> - -Now if you enter Ctrl-D, and repeat the dir() command, you'll see that your -variables no longer exist: - -.. code-block:: python - - PYB: sync filesystems - PYB: soft reboot - MicroPython v1.5-51-g6f70283-dirty on 2015-10-30; PYBv1.0 with STM32F405RG - Type "help()" for more information. - >>> dir() - ['__name__', 'pyb'] - >>> - -The special variable _ (underscore) ------------------------------------ - -When you use the REPL, you may perform computations and see the results. -MicroPython stores the results of the previous statement in the variable _ (underscore). -So you can use the underscore to save the result in a variable. For example: - - >>> 1 + 2 + 3 + 4 + 5 - 15 - >>> x = _ - >>> x - 15 - >>> - -Raw Mode --------- - -Raw mode is not something that a person would normally use. It is intended for -programmatic use. It essentially behaves like paste mode with echo turned off. - -Raw mode is entered using Ctrl-A. You then send your python code, followed by -a Ctrl-D. The Ctrl-D will be acknowledged by 'OK' and then the python code will -be compiled and executed. Any output (or errors) will be sent back. Entering -Ctrl-B will leave raw mode and return the the regular (aka friendly) REPL. - -The ``tools/pyboard.py`` program uses the raw REPL to execute python files on the -MicroPython board. - diff --git a/docs/reference/speed_python.rst b/docs/reference/speed_python.rst deleted file mode 100644 index 279a1bbcdc..0000000000 --- a/docs/reference/speed_python.rst +++ /dev/null @@ -1,342 +0,0 @@ -Maximising MicroPython Speed -============================ - -.. contents:: - -This tutorial describes ways of improving the performance of MicroPython code. -Optimisations involving other languages are covered elsewhere, namely the use -of modules written in C and the MicroPython inline assembler. - -The process of developing high performance code comprises the following stages -which should be performed in the order listed. - -* Design for speed. -* Code and debug. - -Optimisation steps: - -* Identify the slowest section of code. -* Improve the efficiency of the Python code. -* Use the native code emitter. -* Use the viper code emitter. -* Use hardware-specific optimisations. - -Designing for speed -------------------- - -Performance issues should be considered at the outset. This involves taking a view -on the sections of code which are most performance critical and devoting particular -attention to their design. The process of optimisation begins when the code has -been tested: if the design is correct at the outset optimisation will be -straightforward and may actually be unnecessary. - -Algorithms -~~~~~~~~~~ - -The most important aspect of designing any routine for performance is ensuring that -the best algorithm is employed. This is a topic for textbooks rather than for a -MicroPython guide but spectacular performance gains can sometimes be achieved -by adopting algorithms known for their efficiency. - -RAM Allocation -~~~~~~~~~~~~~~ - -To design efficient MicroPython code it is necessary to have an understanding of the -way the interpreter allocates RAM. When an object is created or grows in size -(for example where an item is appended to a list) the necessary RAM is allocated -from a block known as the heap. This takes a significant amount of time; -further it will on occasion trigger a process known as garbage collection which -can take several milliseconds. - -Consequently the performance of a function or method can be improved if an object is created -once only and not permitted to grow in size. This implies that the object persists -for the duration of its use: typically it will be instantiated in a class constructor -and used in various methods. - -This is covered in further detail :ref:`Controlling garbage collection ` below. - -Buffers -~~~~~~~ - -An example of the above is the common case where a buffer is required, such as one -used for communication with a device. A typical driver will create the buffer in the -constructor and use it in its I/O methods which will be called repeatedly. - -The MicroPython libraries typically provide support for pre-allocated buffers. For -example, objects which support stream interface (e.g., file or UART) provide `read()` -method which allocates new buffer for read data, but also a `readinto()` method -to read data into an existing buffer. - -Floating Point -~~~~~~~~~~~~~~ - -Some MicroPython ports allocate floating point numbers on heap. Some other ports -may lack dedicated floating-point coprocessor, and perform arithmetic operations -on them in "software" at considerably lower speed than on integers. Where -performance is important, use integer operations and restrict the use of floating -point to sections of the code where performance is not paramount. For example, -capture ADC readings as integers values to an array in one quick go, and only then -convert them to floating-point numbers for signal processing. - -Arrays -~~~~~~ - -Consider the use of the various types of array classes as an alternative to lists. -The `array` module supports various element types with 8-bit elements supported -by Python's built in `bytes` and `bytearray` classes. These data structures all store -elements in contiguous memory locations. Once again to avoid memory allocation in critical -code these should be pre-allocated and passed as arguments or as bound objects. - -When passing slices of objects such as `bytearray` instances, Python creates -a copy which involves allocation of the size proportional to the size of slice. -This can be alleviated using a `memoryview` object. `memoryview` itself -is allocated on heap, but is a small, fixed-size object, regardless of the size -of slice it points too. - -.. code:: python - - ba = bytearray(10000) # big array - func(ba[30:2000]) # a copy is passed, ~2K new allocation - mv = memoryview(ba) # small object is allocated - func(mv[30:2000]) # a pointer to memory is passed - -A `memoryview` can only be applied to objects supporting the buffer protocol - this -includes arrays but not lists. Small caveat is that while memoryview object is live, -it also keeps alive the original buffer object. So, a memoryview isn't a universal -panacea. For instance, in the example above, if you are done with 10K buffer and -just need those bytes 30:2000 from it, it may be better to make a slice, and let -the 10K buffer go (be ready for garbage collection), instead of making a -long-living memoryview and keeping 10K blocked for GC. - -Nonetheless, `memoryview` is indispensable for advanced preallocated buffer -management. `readinto()` method discussed above puts data at the beginning -of buffer and fills in entire buffer. What if you need to put data in the -middle of existing buffer? Just create a memoryview into the needed section -of buffer and pass it to `readinto()`. - -Identifying the slowest section of code ---------------------------------------- - -This is a process known as profiling and is covered in textbooks and -(for standard Python) supported by various software tools. For the type of -smaller embedded application likely to be running on MicroPython platforms -the slowest function or method can usually be established by judicious use -of the timing ``ticks`` group of functions documented in `utime`. -Code execution time can be measured in ms, us, or CPU cycles. - -The following enables any function or method to be timed by adding an -``@timed_function`` decorator: - -.. code:: python - - def timed_function(f, *args, **kwargs): - myname = str(f).split(' ')[1] - def new_func(*args, **kwargs): - t = utime.ticks_us() - result = f(*args, **kwargs) - delta = utime.ticks_diff(utime.ticks_us(), t) - print('Function {} Time = {:6.3f}ms'.format(myname, delta/1000)) - return result - return new_func - -MicroPython code improvements ------------------------------ - -The const() declaration -~~~~~~~~~~~~~~~~~~~~~~~ - -MicroPython provides a ``const()`` declaration. This works in a similar way -to ``#define`` in C in that when the code is compiled to bytecode the compiler -substitutes the numeric value for the identifier. This avoids a dictionary -lookup at runtime. The argument to ``const()`` may be anything which, at -compile time, evaluates to an integer e.g. ``0x100`` or ``1 << 8``. - -.. _Caching: - -Caching object references -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Where a function or method repeatedly accesses objects performance is improved -by caching the object in a local variable: - -.. code:: python - - class foo(object): - def __init__(self): - ba = bytearray(100) - def bar(self, obj_display): - ba_ref = self.ba - fb = obj_display.framebuffer - # iterative code using these two objects - -This avoids the need repeatedly to look up ``self.ba`` and ``obj_display.framebuffer`` -in the body of the method ``bar()``. - -.. _controlling_gc: - -Controlling garbage collection -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When memory allocation is required, MicroPython attempts to locate an adequately -sized block on the heap. This may fail, usually because the heap is cluttered -with objects which are no longer referenced by code. If a failure occurs, the -process known as garbage collection reclaims the memory used by these redundant -objects and the allocation is then tried again - a process which can take several -milliseconds. - -There may be benefits in pre-empting this by periodically issuing `gc.collect()`. -Firstly doing a collection before it is actually required is quicker - typically on the -order of 1ms if done frequently. Secondly you can determine the point in code -where this time is used rather than have a longer delay occur at random points, -possibly in a speed critical section. Finally performing collections regularly -can reduce fragmentation in the heap. Severe fragmentation can lead to -non-recoverable allocation failures. - -The Native code emitter ------------------------ - -This causes the MicroPython compiler to emit native CPU opcodes rather than -bytecode. It covers the bulk of the MicroPython functionality, so most functions will require -no adaptation (but see below). It is invoked by means of a function decorator: - -.. code:: python - - @micropython.native - def foo(self, arg): - buf = self.linebuf # Cached object - # code - -There are certain limitations in the current implementation of the native code emitter. - -* Context managers are not supported (the ``with`` statement). -* Generators are not supported. -* If ``raise`` is used an argument must be supplied. - -The trade-off for the improved performance (roughly twices as fast as bytecode) is an -increase in compiled code size. - -The Viper code emitter ----------------------- - -The optimisations discussed above involve standards-compliant Python code. The -Viper code emitter is not fully compliant. It supports special Viper native data types -in pursuit of performance. Integer processing is non-compliant because it uses machine -words: arithmetic on 32 bit hardware is performed modulo 2**32. - -Like the Native emitter Viper produces machine instructions but further optimisations -are performed, substantially increasing performance especially for integer arithmetic and -bit manipulations. It is invoked using a decorator: - -.. code:: python - - @micropython.viper - def foo(self, arg: int) -> int: - # code - -As the above fragment illustrates it is beneficial to use Python type hints to assist the Viper optimiser. -Type hints provide information on the data types of arguments and of the return value; these -are a standard Python language feature formally defined here `PEP0484 `_. -Viper supports its own set of types namely ``int``, ``uint`` (unsigned integer), ``ptr``, ``ptr8``, -``ptr16`` and ``ptr32``. The ``ptrX`` types are discussed below. Currently the ``uint`` type serves -a single purpose: as a type hint for a function return value. If such a function returns ``0xffffffff`` -Python will interpret the result as 2**32 -1 rather than as -1. - -In addition to the restrictions imposed by the native emitter the following constraints apply: - -* Functions may have up to four arguments. -* Default argument values are not permitted. -* Floating point may be used but is not optimised. - -Viper provides pointer types to assist the optimiser. These comprise - -* ``ptr`` Pointer to an object. -* ``ptr8`` Points to a byte. -* ``ptr16`` Points to a 16 bit half-word. -* ``ptr32`` Points to a 32 bit machine word. - -The concept of a pointer may be unfamiliar to Python programmers. It has similarities -to a Python `memoryview` object in that it provides direct access to data stored in memory. -Items are accessed using subscript notation, but slices are not supported: a pointer can return -a single item only. Its purpose is to provide fast random access to data stored in contiguous -memory locations - such as data stored in objects which support the buffer protocol, and -memory-mapped peripheral registers in a microcontroller. It should be noted that programming -using pointers is hazardous: bounds checking is not performed and the compiler does nothing to -prevent buffer overrun errors. - -Typical usage is to cache variables: - -.. code:: python - - @micropython.viper - def foo(self, arg: int) -> int: - buf = ptr8(self.linebuf) # self.linebuf is a bytearray or bytes object - for x in range(20, 30): - bar = buf[x] # Access a data item through the pointer - # code omitted - -In this instance the compiler "knows" that ``buf`` is the address of an array of bytes; -it can emit code to rapidly compute the address of ``buf[x]`` at runtime. Where casts are -used to convert objects to Viper native types these should be performed at the start of -the function rather than in critical timing loops as the cast operation can take several -microseconds. The rules for casting are as follows: - -* Casting operators are currently: ``int``, ``bool``, ``uint``, ``ptr``, ``ptr8``, ``ptr16`` and ``ptr32``. -* The result of a cast will be a native Viper variable. -* Arguments to a cast can be a Python object or a native Viper variable. -* If argument is a native Viper variable, then cast is a no-op (i.e. costs nothing at runtime) - that just changes the type (e.g. from ``uint`` to ``ptr8``) so that you can then store/load - using this pointer. -* If the argument is a Python object and the cast is ``int`` or ``uint``, then the Python object - must be of integral type and the value of that integral object is returned. -* The argument to a bool cast must be integral type (boolean or integer); when used as a return - type the viper function will return True or False objects. -* If the argument is a Python object and the cast is ``ptr``, ``ptr``, ``ptr16`` or ``ptr32``, - then the Python object must either have the buffer protocol with read-write capabilities - (in which case a pointer to the start of the buffer is returned) or it must be of integral - type (in which case the value of that integral object is returned). - -The following example illustrates the use of a ``ptr16`` cast to toggle pin X1 ``n`` times: - -.. code:: python - - BIT0 = const(1) - @micropython.viper - def toggle_n(n: int): - odr = ptr16(stm.GPIOA + stm.GPIO_ODR) - for _ in range(n): - odr[0] ^= BIT0 - -A detailed technical description of the three code emitters may be found -on Kickstarter here `Note 1 `_ -and here `Note 2 `_ - -Accessing hardware directly ---------------------------- - -.. note:: - - Code examples in this section are given for the Pyboard. The techniques - described however may be applied to other MicroPython ports too. - -This comes into the category of more advanced programming and involves some knowledge -of the target MCU. Consider the example of toggling an output pin on the Pyboard. The -standard approach would be to write - -.. code:: python - - mypin.value(mypin.value() ^ 1) # mypin was instantiated as an output pin - -This involves the overhead of two calls to the `Pin` instance's :meth:`~machine.Pin.value()` -method. This overhead can be eliminated by performing a read/write to the relevant bit -of the chip's GPIO port output data register (odr). To facilitate this the ``stm`` -module provides a set of constants providing the addresses of the relevant registers. -A fast toggle of pin ``P4`` (CPU pin ``A14``) - corresponding to the green LED - -can be performed as follows: - -.. code:: python - - import machine - import stm - - BIT14 = const(1 << 14) - machine.mem16[stm.GPIOA + stm.GPIO_ODR] ^= BIT14 diff --git a/docs/sphinx_selective_exclude/LICENSE b/docs/sphinx_selective_exclude/LICENSE deleted file mode 100644 index 0b47ced8a1..0000000000 --- a/docs/sphinx_selective_exclude/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2016 by the sphinx_selective_exclude authors. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -* Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/sphinx_selective_exclude/README.md b/docs/sphinx_selective_exclude/README.md deleted file mode 100644 index dab1407392..0000000000 --- a/docs/sphinx_selective_exclude/README.md +++ /dev/null @@ -1,138 +0,0 @@ -Sphinx eager ".. only::" directive and other selective rendition extensions -=========================================================================== - -Project home page: https://github.com/pfalcon/sphinx_selective_exclude - -The implementation of ".. only::" directive in Sphinx documentation -generation tool is known to violate principles of least user surprise -and user expectations in general. Instead of excluding content early -in the pipeline (pre-processor style), Sphinx defers exclusion until -output phase, and what's the worst, various stages processing ignore -"only" blocks and their exclusion status, so they may leak unexpected -information into ToC, indexes, etc. - -There's multiple issues submitted upstream on this matter: - -* https://github.com/sphinx-doc/sphinx/issues/2150 -* https://github.com/sphinx-doc/sphinx/issues/1717 -* https://github.com/sphinx-doc/sphinx/issues/1488 -* etc. - -They are largely ignored by Sphinx maintainers. - -This projects tries to rectify situation on users' side. It actually -changes the way Sphinx processes "only" directive, but does this -without forking the project, and instead is made as a standard -Sphinx extension, which a user may add to their documentation config. -Unlike normal extensions, extensions provided in this package -monkey-patch Sphinx core to work in a way expected by users. - -eager_only ----------- - -The core extension provided by the package is called `eager_only` and -is based on the idea by Andrea Cassioli (see bugreports above) to -process "only" directive as soon as possible during parsing phase. -This approach has some drawbacks, like producing warnings like -"WARNING: document isn't included in any toctree" if "only" is used -to shape up a toctree, or the fact that changing a documentation -builder (html/latex/etc.) will almost certainly require complete -rebuild of documentation. But these are relatively minor issues -comparing to completely broken way "only" works in upstream Sphinx. - -modindex_exclude ----------------- - -"only" directive allows for fine-grained conditional exclusion, but -sometimes you may want to exclude entire module(s) at once. Even if -you wrap an entire module description in "only" directive, like: - - .. only: option1 - .. module:: my_module - - ... - -You will still have an HTML page generated, albeit empty. It may also -go into indexes, so will be discoverable by users, leading to less -than ideal experience. `modindex_exclude` extension is design to -resolve this issue, by making sure that any reference of a module -is excluded from Python module index ("modindex"), as well as -general cross-reference index ("genindex"). In the latter case, -any symbol belong to a module will be excluded. Unlike `eager_only` -extension which appear to have issued with "latexpdf" builder, -`modindex_exclude` is useful for PDF, and allows to get cleaner -index for PDF, just the same as for HTML. - -search_auto_exclude -------------------- - -Even if you exclude some documents from toctree:: using only:: -directive, they will be indexed for full-text search, so user may -find them and get confused. This plugin follows very simple idea -that if you didn't include some documents in the toctree, then -you didn't want them to be accessible (e.g. for a particular -configuration), and so will make sure they aren't indexed either. - -This extension depends on `eager_only` and won't work without it. -Note that Sphinx will issue warnings, as usual, for any documents -not included in a toctree. This is considered a feature, and gives -you a chance to check that document exclusions are indeed right -for a particular configuration you build (and not that you forgot -to add something to a toctree). - -Summary -------- - -Based on the above, sphinx_selective_exclude offers extension to let -you: - -* Make "only::" directive work in an expected, intuitive manner, using - `eager_only` extension. -* However, if you apply only:: to toctree::, excluded documents will - still be available via full-text search, so you need to use - `search_auto_exclude` for that to work as expected. -* Similar to search, indexes may also require special treatment, hence - there's the `modindex_exclude` extension. - -Most likely, you will want to use all 3 extensions together - if you -really want build subsets of docimentation covering sufficiently different -configurations from a single doctree. However, if one of them is enough -to cover your usecase, that's OK to (and why they were separated into -3 extensions, to follow KISS and "least surprise" principles and to -not make people deal with things they aren't interested in). In this case, -however remember there're other extensions, if you later hit a usecase -when they're needed. - -Usage ------ - -To use these extensions, add https://github.com/pfalcon/sphinx_selective_exclude -as a git submodule to your project, in documentation folder (where -Sphinx conf.py is located). Alternatively, commit sphinx_selective_exclude -directory instead of making it a submodule (you will need to pick up -any project updates manually then). - -Add following lines to "extensions" settings in your conf.py (you -likely already have some standard Sphinx extensions enabled): - - extensions = [ - ... - 'sphinx_selective_exclude.eager_only', - 'sphinx_selective_exclude.search_auto_exclude', - 'sphinx_selective_exclude.modindex_exclude', - ] - -As discussed above, you may enable all extensions, or one by one. - -Please note that to make sure these extensions work well and avoid producing -output docs with artifacts, it is IMPERATIVE to remove cached doctree if -you rebuild documentation with another builder (i.e. with different output -format). Also, to stay on safe side, it's recommended to remove old doctree -anyway before generating production-ready documentation for publishing. To -do that, run something like: - - rm -rf _build/doctrees/ - -A typical artificat when not following these simple rules is that content -of some sections may be missing. If you face anything like that, just -remember what's written above and remove cached doctrees. diff --git a/docs/sphinx_selective_exclude/__init__.py b/docs/sphinx_selective_exclude/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/docs/sphinx_selective_exclude/eager_only.py b/docs/sphinx_selective_exclude/eager_only.py deleted file mode 100644 index 82766c2e64..0000000000 --- a/docs/sphinx_selective_exclude/eager_only.py +++ /dev/null @@ -1,45 +0,0 @@ -# -# This is a Sphinx documentation tool extension which makes .only:: -# directives be eagerly processed early in the parsing stage. This -# makes sure that content in .only:: blocks gets actually excluded -# as a typical user expects, instead of bits of information in -# these blocks leaking to documentation in various ways (e.g., -# indexes containing entries for functions which are actually in -# .only:: blocks and thus excluded from documentation, etc.) -# Note that with this extension, you may need to completely -# rebuild a doctree when switching builders (i.e. completely -# remove _build/doctree dir between generation of HTML vs PDF -# documentation). -# -# This extension works by monkey-patching Sphinx core, so potentially -# may not work with untested Sphinx versions. It tested to work with -# 1.2.2 and 1.4.2 -# -# Copyright (c) 2016 Paul Sokolovsky -# Based on idea by Andrea Cassioli: -# https://github.com/sphinx-doc/sphinx/issues/2150#issuecomment-171912290 -# Licensed under the terms of BSD license, see LICENSE file. -# -import sphinx -from docutils.parsers.rst import directives - - -class EagerOnly(sphinx.directives.other.Only): - - def run(self, *args): - # Evaluate the condition eagerly, and if false return no nodes right away - env = self.state.document.settings.env - env.app.builder.tags.add('TRUE') - #print(repr(self.arguments[0])) - if not env.app.builder.tags.eval_condition(self.arguments[0]): - return [] - - # Otherwise, do the usual processing - nodes = super(EagerOnly, self).run() - if len(nodes) == 1: - nodes[0]['expr'] = 'TRUE' - return nodes - - -def setup(app): - directives.register_directive('only', EagerOnly) diff --git a/docs/sphinx_selective_exclude/modindex_exclude.py b/docs/sphinx_selective_exclude/modindex_exclude.py deleted file mode 100644 index bf8db795e6..0000000000 --- a/docs/sphinx_selective_exclude/modindex_exclude.py +++ /dev/null @@ -1,75 +0,0 @@ -# -# This is a Sphinx documentation tool extension which allows to -# exclude some Python modules from the generated indexes. Modules -# are excluded both from "modindex" and "genindex" index tables -# (in the latter case, all members of a module are excluded). -# To control exclusion, set "modindex_exclude" variable in Sphinx -# conf.py to the list of modules to exclude. Note: these should be -# modules (as defined by py:module directive, not just raw filenames). -# This extension works by monkey-patching Sphinx core, so potentially -# may not work with untested Sphinx versions. It tested to work with -# 1.2.2 and 1.4.2 -# -# Copyright (c) 2016 Paul Sokolovsky -# Licensed under the terms of BSD license, see LICENSE file. -# -import sphinx - - -#org_PythonModuleIndex_generate = None -org_PyObject_add_target_and_index = None -org_PyModule_run = None - -EXCLUDES = {} - -# No longer used, PyModule_run() monkey-patch does all the job -def PythonModuleIndex_generate(self, docnames=None): - docnames = [] - excludes = self.domain.env.config['modindex_exclude'] - for modname, (docname, synopsis, platforms, deprecated) in self.domain.data['modules'].items(): - #print(docname) - if modname not in excludes: - docnames.append(docname) - - return org_PythonModuleIndex_generate(self, docnames) - - -def PyObject_add_target_and_index(self, name_cls, sig, signode): - if hasattr(self.env, "ref_context"): - # Sphinx 1.4 - ref_context = self.env.ref_context - else: - # Sphinx 1.2 - ref_context = self.env.temp_data - modname = self.options.get( - 'module', ref_context.get('py:module')) - #print("*", modname, name_cls) - if modname in self.env.config['modindex_exclude']: - return None - return org_PyObject_add_target_and_index(self, name_cls, sig, signode) - - -def PyModule_run(self): - env = self.state.document.settings.env - modname = self.arguments[0].strip() - excl = env.config['modindex_exclude'] - if modname in excl: - self.options['noindex'] = True - EXCLUDES.setdefault(modname, []).append(env.docname) - return org_PyModule_run(self) - - -def setup(app): - app.add_config_value('modindex_exclude', [], 'html') - -# global org_PythonModuleIndex_generate -# org_PythonModuleIndex_generate = sphinx.domains.python.PythonModuleIndex.generate -# sphinx.domains.python.PythonModuleIndex.generate = PythonModuleIndex_generate - - global org_PyObject_add_target_and_index - org_PyObject_add_target_and_index = sphinx.domains.python.PyObject.add_target_and_index - sphinx.domains.python.PyObject.add_target_and_index = PyObject_add_target_and_index - - global org_PyModule_run - org_PyModule_run = sphinx.domains.python.PyModule.run - sphinx.domains.python.PyModule.run = PyModule_run diff --git a/docs/sphinx_selective_exclude/search_auto_exclude.py b/docs/sphinx_selective_exclude/search_auto_exclude.py deleted file mode 100644 index b8b326dd2c..0000000000 --- a/docs/sphinx_selective_exclude/search_auto_exclude.py +++ /dev/null @@ -1,34 +0,0 @@ -# -# This is a Sphinx documentation tool extension which allows to -# automatically exclude from full-text search index document -# which are not referenced via toctree::. It's intended to be -# used with toctrees conditional on only:: directive, with the -# idea being that if you didn't include it in the ToC, you don't -# want the docs being findable by search either (for example, -# because these docs contain information not pertinent to a -# particular product configuration). -# -# This extension depends on "eager_only" extension and won't work -# without it. -# -# Copyright (c) 2016 Paul Sokolovsky -# Licensed under the terms of BSD license, see LICENSE file. -# -import sphinx - - -org_StandaloneHTMLBuilder_index_page = None - - -def StandaloneHTMLBuilder_index_page(self, pagename, doctree, title): - if pagename not in self.env.files_to_rebuild: - if pagename != self.env.config.master_doc and 'orphan' not in self.env.metadata[pagename]: - print("Excluding %s from full-text index because it's not referenced in ToC" % pagename) - return - return org_StandaloneHTMLBuilder_index_page(self, pagename, doctree, title) - - -def setup(app): - global org_StandaloneHTMLBuilder_index_page - org_StandaloneHTMLBuilder_index_page = sphinx.builders.html.StandaloneHTMLBuilder.index_page - sphinx.builders.html.StandaloneHTMLBuilder.index_page = StandaloneHTMLBuilder_index_page diff --git a/docs/supported_ports.rst b/docs/supported_ports.rst index 2a5b71a192..039ddea68b 100644 --- a/docs/supported_ports.rst +++ b/docs/supported_ports.rst @@ -1,11 +1,12 @@ Supported Ports ============================== -Adafruit's CircuitPython derivative currently has limited support with a focus on -the Atmel SAMD21 port and ESP8266 port. +Adafruit's CircuitPython currently has limited support with a focus on supporting the Atmel SAMD +and ESP8266. .. toctree:: :maxdepth: 2 - ../atmel-samd/README - esp8266/index.rst + ../ports/atmel-samd/README + ../ports/esp8266/README + ../ports/nrf/README diff --git a/docs/templates/layout.html b/docs/templates/layout.html deleted file mode 100644 index a6caa0bc5a..0000000000 --- a/docs/templates/layout.html +++ /dev/null @@ -1,6 +0,0 @@ -{% extends "!layout.html" %} -{% set css_files = css_files + ["_static/customstyle.css"] %} - -{# we change the master_doc variable so that links to the index - page are to index.html instead of _index.html #} -{% set master_doc = "index" %} diff --git a/docs/templates/replace.inc b/docs/templates/replace.inc index 319c53735f..2636045f6e 100644 --- a/docs/templates/replace.inc +++ b/docs/templates/replace.inc @@ -4,6 +4,6 @@ .. |see_cpython_module| replace:: - *This module implements a subset of the corresponding* `CPython` *module, - as described below. For more information, refer to the original - CPython documentation:* + *This module implements a subset of the corresponding* ``CPython`` *module, + as described below. For more information, refer to the original* + ``CPython`` *documentation:* diff --git a/docs/templates/topindex.html b/docs/templates/topindex.html deleted file mode 100644 index 76e5e18d72..0000000000 --- a/docs/templates/topindex.html +++ /dev/null @@ -1,112 +0,0 @@ -{% extends "defindex.html" %} -{% block body %} - -

MicroPython documentation

- -

- {{ _('Welcome! This is the documentation for MicroPython') }} - v{{ release|e }}{% if last_updated %}, {{ _('last updated') }} {{ last_updated|e }}{% endif %}. -

- -

- MicroPython runs on a variety of systems and each has their own specific - documentation. You are currently viewing the documentation for - {{ port_name }}. -

- - - -

Documentation for MicroPython and {{ port_name }}:

- - - - -
- {% if port in ("pyboard", "wipy", "esp8266") %} - - - - {% endif %} - - - - - -
- -

Indices and tables:

- - - -
- - - - - -
- -

External links:

- - - - -
- - - - -
- -{% endblock %} diff --git a/docs/templates/unsupported_in_circuitpython.inc b/docs/templates/unsupported_in_circuitpython.inc new file mode 100644 index 0000000000..18c9215a84 --- /dev/null +++ b/docs/templates/unsupported_in_circuitpython.inc @@ -0,0 +1,5 @@ +.. warning:: + + This module is inherited from MicroPython and may not work in CircuitPython + as documented or at all! If they do work, they may change at any time. It is + unsupported. diff --git a/docs/templates/versions.html b/docs/templates/versions.html deleted file mode 100644 index 198630dd77..0000000000 --- a/docs/templates/versions.html +++ /dev/null @@ -1,37 +0,0 @@ -
- - Ports and Versions - {{ port }} ({{ port_version }}) - - -
-
-
Ports
- {% for slug, url in all_ports %} -
{{ slug }}
- {% endfor %} -
-
-
Versions
- {% for slug, url in all_versions %} -
{{ slug }}
- {% endfor %} -
-
-
Downloads
- {% for type, url in downloads %} -
{{ type }}
- {% endfor %} -
-
-
-
External links
-
- micropython.org -
-
- GitHub -
-
-
-
diff --git a/docs/troubleshooting.rst b/docs/troubleshooting.rst index 1c7e87f61b..66bcc2764c 100644 --- a/docs/troubleshooting.rst +++ b/docs/troubleshooting.rst @@ -23,7 +23,7 @@ happen on Linux and Mac OSX but its less likely. such as Feather M0 Express, Metro M0 Express and Circuit Playground Express:** -#. Download the appropriate flash .erase uf2 from `here `_. +#. Download the appropriate flash .erase uf2 from `the Adafruit_SPIFlash repo `_. #. Double-click the reset button. #. Copy the appropriate .uf2 to the xxxBOOT drive. #. The on-board NeoPixel will turn blue, indicating the erase has started. @@ -32,7 +32,7 @@ such as Feather M0 Express, Metro M0 Express and Circuit Playground Express:** **For boards without SPI flash, such as Feather M0 Proto, Gemma M0 and, Trinket M0:** -#. Download the appropriate erase .uf2 from `here `_. +#. Download the appropriate erase .uf2 from `the Learn repo `_. #. Double-click the reset button. #. Copy the appropriate .uf2 to the xxxBOOT drive. #. The boot LED will start pulsing again, and the xxxBOOT drive will appear again. diff --git a/docs/unix_index.rst b/docs/unix_index.rst deleted file mode 100644 index 1bfeb0bdac..0000000000 --- a/docs/unix_index.rst +++ /dev/null @@ -1,9 +0,0 @@ -MicroPython documentation and references -======================================== - -.. toctree:: - - library/index.rst - reference/index.rst - genrst/index.rst - license.rst diff --git a/docs/unsupported_ports.rst b/docs/unsupported_ports.rst deleted file mode 100644 index e04537656b..0000000000 --- a/docs/unsupported_ports.rst +++ /dev/null @@ -1,14 +0,0 @@ -Unsupported Ports -============================== - -Adafruit's MicroPython derivative currently has limited support with a focus on -the Atmel SAMD21 port. The ports below still exist in the code to preserve -upstream compatibility but are not tested. Use at your own risk. - -We recommend using `upstream MicroPython `_ for the below ports. - -.. toctree:: - :maxdepth: 2 - - pyboard/index.rst - wipy/index.rst diff --git a/docs/wipy/general.rst b/docs/wipy/general.rst deleted file mode 100644 index f28edb4e4b..0000000000 --- a/docs/wipy/general.rst +++ /dev/null @@ -1,385 +0,0 @@ -General information about the WiPy -================================== - -No floating point support -------------------------- - -Due to space reasons, there's no floating point support, and no math module. This -means that floating point numbers cannot be used anywhere in the code, and that -all divisions must be performed using '//' instead of '/'. Example:: - - >>> r = 4 // 2 # this will work - >>> r = 4 / 2 # this WON'T - -Before applying power ---------------------- - -.. warning:: - - The GPIO pins of the WiPy are NOT 5V tolerant, connecting them to voltages higher - than 3.6V will cause irreparable damage to the board. ADC pins, when configured - in analog mode cannot withstand voltages above 1.8V. Keep these considerations in - mind when wiring your electronics. - -WLAN default behaviour ----------------------- - -When the WiPy boots with the default factory configuration starts in Access Point -mode with ``ssid`` that starts with: ``wipy-wlan`` and ``key: www.wipy.io``. -Connect to this network and the WiPy will be reachable at ``192.168.1.1``. In order -to gain access to the interactive prompt, open a telnet session to that IP address on -the default port (23). You will be asked for credentials: -``login: micro`` and ``password: python`` - -.. _wipy_telnet: - -Telnet REPL ------------ - -Linux stock telnet works like a charm (also on OSX), but other tools like putty -work quite well too. The default credentials are: **user:** ``micro``, **password:** ``python``. -See :ref:`network.server ` for info on how to change the defaults. -For instance, on a linux shell (when connected to the WiPy in AP mode):: - - $ telnet 192.168.1.1 - -.. _wipy_filesystem: - -Local file system and FTP access --------------------------------- - -There is a small internal file system (a drive) on the WiPy, called ``/flash``, -which is stored within the external serial flash memory. If a micro SD card -is hooked-up and mounted, it will be available as well. - -When the WiPy starts up, it always boots from the ``boot.py`` located in the -``/flash`` file system. On boot up, the current directory is ``/flash``. - -The file system is accessible via the native FTP server running in the WiPy. -Open your FTP client of choice and connect to: - -**url:** ``ftp://192.168.1.1``, **user:** ``micro``, **password:** ``python`` - -See :ref:`network.server ` for info on how to change the defaults. -The recommended clients are: Linux stock FTP (also in OSX), Filezilla and FireFTP. -For example, on a linux shell:: - - $ ftp 192.168.1.1 - -The FTP server on the WiPy doesn't support active mode, only passive, therefore, -if using the native unix ftp client, just after logging in do:: - - ftp> passive - -Besides that, the FTP server only supports one data connection at a time. Check out -the Filezilla settings section below for more info. - -FileZilla settings ------------------- -Do not use the quick connect button, instead, open the site manager and create a new -configuration. In the ``General`` tab make sure that encryption is set to: ``Only use -plain FTP (insecure)``. In the Transfer Settings tab limit the max number of connections -to one, otherwise FileZilla will try to open a second command connection when retrieving -and saving files, and for simplicity and to reduce code size, only one command and one -data connections are possible. Other FTP clients might behave in a similar way. - -.. _wipy_firmware_upgrade: - -Upgrading the firmware Over The Air ------------------------------------ - -OTA software updates can be performed through the FTP server. Upload the ``mcuimg.bin`` file -to: ``/flash/sys/mcuimg.bin`` it will take around 6s. You won't see the file being stored -inside ``/flash/sys/`` because it's actually saved bypassing the user file system, so it -ends up inside the internal **hidden** file system, but rest assured that it was successfully -transferred, and it has been signed with a MD5 checksum to verify its integrity. Now, reset -the WiPy by pressing the switch on the board, or by typing:: - - >>> import machine - >>> machine.reset() - -Software updates can be found in: https://github.com/wipy/wipy/releases (**Binaries.zip**). -It's always recommended to update to the latest software, but make sure to -read the **release notes** before. - -.. note:: - - The ``bootloader.bin`` found inside ``Binaries.zip`` is there only for reference, it's not - needed for the Over The Air update. - -In order to check your software version, do:: - - >>> import os - >>> os.uname().release - -If the version number is lower than the latest release found in -`the releases `_, go ahead and update your WiPy! - - -.. _wipy_boot_modes: - -Boot modes and safe boot ------------------------- - -If you power up normally, or press the reset button, the WiPy will boot -into standard mode; the ``boot.py`` file will be executed first, then -``main.py`` will run. - -You can override this boot sequence by pulling ``GP28`` **up** (connect -it to the 3v3 output pin) during reset. This procedure also allows going -back in time to old firmware versions. The WiPy can hold up to 3 different -firmware versions, which are: the factory firmware plus 2 user updates. - -After reset, if ``GP28`` is held high, the heartbeat LED will start flashing -slowly, if after 3 seconds the pin is still being held high, the LED will start -blinking a bit faster and the WiPy will select the previous user update to boot. -If the previous user update is the desired firmware image, ``GP28`` must be -released before 3 more seconds elapse. If 3 seconds later the pin is still high, -the factory firmware will be selected, the LED will flash quickly for 1.5 seconds -and the WiPy will proceed to boot. The firmware selection mechanism is as follows: - - -**Safe Boot Pin** ``GP28`` **released during:** - -+-------------------------+-------------------------+----------------------------+ -| 1st 3 secs window | 2nd 3 secs window | Final 1.5 secs window | -+=========================+=========================+============================+ -| | Safe boot, *latest* | | Safe boot, *previous* | | Safe boot, the *factory* | -| | firmware is selected | | user update selected | | firmware is selected | -+-------------------------+-------------------------+----------------------------+ - -On all of the above 3 scenarios, safe boot mode is entered, meaning that -the execution of both ``boot.py`` and ``main.py`` is skipped. This is -useful to recover from crash situations caused by the user scripts. The selection -made during safe boot is not persistent, therefore after the next normal reset -the latest firmware will run again. - -The heartbeat LED ------------------- - -By default the heartbeat LED flashes once every 4s to signal that the system is -alive. This can be overridden through the :mod:`wipy` module:: - - >>> import wipy - >>> wipy.heartbeat(False) - -There are currently 2 kinds of errors that you might see: - -1. If the heartbeat LED flashes quickly, then a Python script (eg ``main.py``) - has an error. Use the REPL to debug it. -2. If the heartbeat LED stays on, then there was a hard fault, you cannot - recover from this, the only way out is to press the reset switch. - -Details on sleep modes ----------------------- - -* ``machine.idle()``: Power consumption: ~12mA (in WLAN STA mode). Wake sources: - any hardware interrupt (including systick with period of 1ms), no special - configuration required. -* ``machine.sleep()``: 950uA (in WLAN STA mode). Wake sources are ``Pin``, ``RTC`` - and ``WLAN`` -* ``machine.deepsleep()``: ~350uA. Wake sources are ``Pin`` and ``RTC``. - -Additional details for machine.Pin ----------------------------------- - -On the WiPy board the pins are identified by their string id:: - - from machine import Pin - g = machine.Pin('GP9', mode=Pin.OUT, pull=None, drive=Pin.MED_POWER, alt=-1) - -You can also configure the Pin to generate interrupts. For instance:: - - from machine import Pin - - def pincb(pin): - print(pin.id()) - - pin_int = Pin('GP10', mode=Pin.IN, pull=Pin.PULL_DOWN) - pin_int.irq(trigger=Pin.IRQ_RISING, handler=pincb) - # the callback can be triggered manually - pin_int.irq()() - # to disable the callback - pin_int.irq().disable() - -Now every time a falling edge is seen on the gpio pin, the callback will be -executed. Caution: mechanical push buttons have "bounce" and pushing or -releasing a switch will often generate multiple edges. -See: http://www.eng.utah.edu/~cs5780/debouncing.pdf for a detailed -explanation, along with various techniques for debouncing. - -All pin objects go through the pin mapper to come up with one of the -gpio pins. - -For the ``drive`` parameter the strengths are: - - - ``Pin.LOW_POWER`` - 2mA drive capability. - - ``Pin.MED_POWER`` - 4mA drive capability. - - ``Pin.HIGH_POWER`` - 6mA drive capability. - -For the ``alt`` parameter please refer to the pinout and alternate functions -table at `_ -for the specific alternate functions that each pin supports. - -For interrupts, the ``priority`` can take values in the range 1-7. And the -``wake`` parameter has the following properties: - - - If ``wake_from=machine.Sleep.ACTIVE`` any pin can wake the board. - - If ``wake_from=machine.Sleep.SUSPENDED`` pins ``GP2``, ``GP4``, ``GP10``, - ``GP11``, GP17`` or ``GP24`` can wake the board. Note that only 1 - of this pins can be enabled as a wake source at the same time, so, only - the last enabled pin as a ``machine.Sleep.SUSPENDED`` wake source will have effect. - - If ``wake_from=machine.Sleep.SUSPENDED`` pins ``GP2``, ``GP4``, ``GP10``, - ``GP11``, ``GP17`` and ``GP24`` can wake the board. In this case all of the - 6 pins can be enabled as a ``machine.Sleep.HIBERNATE`` wake source at the same time. - -Additional Pin methods: - -.. method:: machine.Pin.alt_list() - - Returns a list of the alternate functions supported by the pin. List items are - a tuple of the form: ``('ALT_FUN_NAME', ALT_FUN_INDEX)`` - -Additional details for machine.I2C ----------------------------------- - -On the WiPy there is a single hardware I2C peripheral, identified by "0". By -default this is the peripheral that is used when constructing an I2C instance. -The default pins are GP23 for SCL and GP13 for SDA, and one can create the -default I2C peripheral simply by doing:: - - i2c = machine.I2C() - -The pins and frequency can be specified as:: - - i2c = machine.I2C(freq=400000, scl='GP23', sda='GP13') - -Only certain pins can be used as SCL/SDA. Please refer to the pinout for further -information. - -Known issues ------------- - -Incompatible way to create SSL sockets -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -SSL sockets need to be created the following way before wrapping them with. -``ssl.wrap_socket``:: - - import socket - import ssl - s = socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_SEC) - ss = ssl.wrap_socket(s) - -Certificates must be used in order to validate the other side of the connection, and also to -authenticate ourselves with the other end. Such certificates must be stored as files using the -FTP server, and they must be placed in specific paths with specific names. - -- The certificate to validate the other side goes in: **'/flash/cert/ca.pem'** -- The certificate to authenticate ourselves goes in: **'/flash/cert/cert.pem'** -- The key for our own certificate goes in: **'/flash/cert/private.key'** - -.. note:: - - When these files are stored, they are placed inside the internal **hidden** file system - (just like firmware updates), and therefore they are never visible. - -For instance to connect to the Blynk servers using certificates, take the file ``ca.pem`` located -in the `blynk examples folder `_. -and put it in '/flash/cert/'. Then do:: - - import socket - import ssl - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_SEC) - ss = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED, ca_certs='/flash/cert/ca.pem') - ss.connect(socket.getaddrinfo('cloud.blynk.cc', 8441)[0][-1]) - -Incompatibilities in uhashlib module -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Due to hardware implementation details of the WiPy, data must be buffered before being -digested, which would make it impossible to calculate the hash of big blocks of data that -do not fit in RAM. In this case, since most likely the total size of the data is known -in advance, the size can be passed to the constructor and hence the HASH hardware engine -of the WiPy can be properly initialized without needing buffering. If ``block_size`` is -to be given, an initial chunk of ``data`` must be passed as well. **When using this extension, -care must be taken to make sure that the length of all intermediate chunks (including the -initial one) is a multiple of 4 bytes.** The last chunk may be of any length. - -Example:: - - hash = uhashlib.sha1('abcd1234', 1001) # length of the initial piece is multiple of 4 bytes - hash.update('1234') # also multiple of 4 bytes - ... - hash.update('12345') # last chunk may be of any length - hash.digest() - -Unrelated function in machine module -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. function:: main(filename) - - Set the filename of the main script to run after boot.py is finished. If - this function is not called then the default file main.py will be executed. - - It only makes sense to call this function from within boot.py. - -Adhoc way to control telnet/FTP server via network module -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The ``Server`` class controls the behaviour and the configuration of the FTP and telnet -services running on the WiPy. Any changes performed using this class' methods will -affect both. - -Example:: - - import network - server = network.Server() - server.deinit() # disable the server - # enable the server again with new settings - server.init(login=('user', 'password'), timeout=600) - -.. class:: network.Server(id, ...) - - Create a server instance, see ``init`` for parameters of initialization. - -.. method:: server.init(\*, login=('micro', 'python'), timeout=300) - - Init (and effectively start the server). Optionally a new ``user``, ``password`` - and ``timeout`` (in seconds) can be passed. - -.. method:: server.deinit() - - Stop the server - -.. method:: server.timeout([timeout_in_seconds]) - - Get or set the server timeout. - -.. method:: server.isrunning() - - Returns ``True`` if the server is running, ``False`` otherwise. - -Adhoc VFS-like support -~~~~~~~~~~~~~~~~~~~~~~ - -WiPy doesn't implement full MicroPython VFS support, instead following -functions are defined in ``uos`` module: - -.. function:: mount(block_device, mount_point, \*, readonly=False) - - Mounts a block device (like an ``SD`` object) in the specified mount - point. Example:: - - os.mount(sd, '/sd') - -.. function:: unmount(path) - - Unmounts a previously mounted block device from the given path. - -.. function:: mkfs(block_device or path) - - Formats the specified path, must be either ``/flash`` or ``/sd``. - A block device can also be passed like an ``SD`` object before - being mounted. - diff --git a/docs/wipy/index.rst b/docs/wipy/index.rst deleted file mode 100644 index 9b355d4963..0000000000 --- a/docs/wipy/index.rst +++ /dev/null @@ -1,8 +0,0 @@ -WiPy -================================== - -.. toctree:: - - quickref.rst - general.rst - tutorial/index.rst diff --git a/docs/wipy/quickref.rst b/docs/wipy/quickref.rst deleted file mode 100644 index f60c81f5fe..0000000000 --- a/docs/wipy/quickref.rst +++ /dev/null @@ -1,218 +0,0 @@ -.. _quickref_: - -Quick reference for the WiPy -============================ - -.. image:: https://raw.githubusercontent.com/wipy/wipy/master/docs/PinOUT.png - :alt: WiPy pinout and alternate functions table - :width: 800px - -General board control (including sleep modes) ---------------------------------------------- - -See the :mod:`machine` module:: - - import machine - - help(machine) # display all members from the machine module - machine.freq() # get the CPU frequency - machine.unique_id() # return the 6-byte unique id of the board (the WiPy's MAC address) - - machine.idle() # average current decreases to (~12mA), any interrupts wake it up - machine.sleep() # everything except for WLAN is powered down (~950uA avg. current) - # wakes from Pin, RTC or WLAN - machine.deepsleep() # deepest sleep mode, MCU starts from reset. Wakes from Pin and RTC. - -Pins and GPIO -------------- - -See :ref:`machine.Pin `. :: - - from machine import Pin - - # initialize GP2 in gpio mode (alt=0) and make it an output - p_out = Pin('GP2', mode=Pin.OUT) - p_out.value(1) - p_out.value(0) - p_out.toggle() - p_out(True) - - # make GP1 an input with the pull-up enabled - p_in = Pin('GP1', mode=Pin.IN, pull=Pin.PULL_UP) - p_in() # get value, 0 or 1 - -Timers ------- - -See :ref:`machine.Timer ` and :ref:`machine.Pin `. -Timer ``id``'s take values from 0 to 3.:: - - from machine import Timer - from machine import Pin - - tim = Timer(0, mode=Timer.PERIODIC) - tim_a = tim.channel(Timer.A, freq=1000) - tim_a.freq(5) # 5 Hz - - p_out = Pin('GP2', mode=Pin.OUT) - tim_a.irq(trigger=Timer.TIMEOUT, handler=lambda t: p_out.toggle()) - -PWM (pulse width modulation) ----------------------------- - -See :ref:`machine.Pin ` and :ref:`machine.Timer `. :: - - from machine import Timer - - # timer 1 in PWM mode and width must be 16 buts - tim = Timer(1, mode=Timer.PWM, width=16) - - # enable channel A @1KHz with a 50.55% duty cycle - tim_a = tim.channel(Timer.A, freq=1000, duty_cycle=5055) - -ADC (analog to digital conversion) ----------------------------------- - -See :ref:`machine.ADC `. :: - - from machine import ADC - - adc = ADC() - apin = adc.channel(pin='GP3') - apin() # read value, 0-4095 - -UART (serial bus) ------------------ - -See :ref:`machine.UART `. :: - - from machine import UART - uart = UART(0, baudrate=9600) - uart.write('hello') - uart.read(5) # read up to 5 bytes - -SPI bus -------- - -See :ref:`machine.SPI `. :: - - from machine import SPI - - # configure the SPI master @ 2MHz - spi = SPI(0, SPI.MASTER, baudrate=200000, polarity=0, phase=0) - spi.write('hello') - spi.read(5) # receive 5 bytes on the bus - rbuf = bytearray(5) - spi.write_readinto('hello', rbuf) # send and receive 5 bytes - -I2C bus -------- - -See :ref:`machine.I2C `. :: - - from machine import I2C - # configure the I2C bus - i2c = I2C(baudrate=100000) - i2c.scan() # returns list of slave addresses - i2c.writeto(0x42, 'hello') # send 5 bytes to slave with address 0x42 - i2c.readfrom(0x42, 5) # receive 5 bytes from slave - i2c.readfrom_mem(0x42, 0x10, 2) # read 2 bytes from slave 0x42, slave memory 0x10 - i2c.writeto_mem(0x42, 0x10, 'xy') # write 2 bytes to slave 0x42, slave memory 0x10 - -Watchdog timer (WDT) --------------------- - -See :ref:`machine.WDT `. :: - - from machine import WDT - - # enable the WDT with a timeout of 5s (1s is the minimum) - wdt = WDT(timeout=5000) - wdt.feed() - -Real time clock (RTC) ---------------------- - -See :ref:`machine.RTC ` :: - - from machine import RTC - - rtc = RTC() # init with default time and date - rtc = RTC(datetime=(2015, 8, 29, 9, 0, 0, 0, None)) # init with a specific time and date - print(rtc.now()) - - def alarm_handler (rtc_o): - pass - # do some non blocking operations - # warning printing on an irq via telnet is not - # possible, only via UART - - # create a RTC alarm that expires after 5 seconds - rtc.alarm(time=5000, repeat=False) - - # enable RTC interrupts - rtc_i = rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler, wake=machine.SLEEP) - - # go into suspended mode waiting for the RTC alarm to expire and wake us up - machine.sleep() - -SD card -------- - -See :ref:`machine.SD `. :: - - from machine import SD - import os - - # clock pin, cmd pin, data0 pin - sd = SD(pins=('GP10', 'GP11', 'GP15')) - # or use default ones for the expansion board - sd = SD() - os.mount(sd, '/sd') - -WLAN (WiFi) ------------ - -See :ref:`network.WLAN ` and :mod:`machine`. :: - - import machine - from network import WLAN - - # configure the WLAN subsystem in station mode (the default is AP) - wlan = WLAN(mode=WLAN.STA) - # go for fixed IP settings - wlan.ifconfig(config=('192.168.0.107', '255.255.255.0', '192.168.0.1', '8.8.8.8')) - wlan.scan() # scan for available networks - wlan.connect(ssid='mynetwork', auth=(WLAN.WPA2, 'mynetworkkey')) - while not wlan.isconnected(): - pass - print(wlan.ifconfig()) - # enable wake on WLAN - wlan.irq(trigger=WLAN.ANY_EVENT, wake=machine.SLEEP) - # go to sleep - machine.sleep() - # now, connect to the FTP or the Telnet server and the WiPy will wake-up - -Telnet and FTP server ---------------------- - -See :ref:`network.Server ` :: - - from network import Server - - # init with new user, password and seconds timeout - server = Server(login=('user', 'password'), timeout=60) - server.timeout(300) # change the timeout - server.timeout() # get the timeout - server.isrunning() # check whether the server is running or not - -Heart beat LED --------------- - -See :mod:`wipy`. :: - - import wipy - - wipy.heartbeat(False) # disable the heartbeat LED - wipy.heartbeat(True) # enable the heartbeat LED - wipy.heartbeat() # get the heartbeat state diff --git a/docs/wipy/tutorial/blynk.rst b/docs/wipy/tutorial/blynk.rst deleted file mode 100644 index b5a2f24a47..0000000000 --- a/docs/wipy/tutorial/blynk.rst +++ /dev/null @@ -1,19 +0,0 @@ -Getting started with Blynk and the WiPy ---------------------------------------- - -Blynk is a platform with iOS and Android apps to control -Arduino, Raspberry Pi and the likes over the Internet. -You can easily build graphic interfaces for all your -projects by simply dragging and dropping widgets. - -There are several examples available that work out-of-the-box with -the WiPy. Before anything else, make sure that your WiPy is running -the latest software, check :ref:`OTA How-To ` for instructions. - -1. Get the `Blynk library `_ and put it in ``/flash/lib/`` via FTP. -2. Get the `Blynk examples `_, edit the network settings, and afterwards - upload them to ``/flash/lib/`` via FTP as well. -3. Follow the instructions on each example to setup the Blynk dashboard on your smartphone or tablet. -4. Give it a try, for instance:: - - >>> execfile('01_simple.py') diff --git a/docs/wipy/tutorial/index.rst b/docs/wipy/tutorial/index.rst deleted file mode 100644 index 816de27b5a..0000000000 --- a/docs/wipy/tutorial/index.rst +++ /dev/null @@ -1,18 +0,0 @@ -.. _wipy_tutorial_index: - -WiPy tutorials and examples -=========================== - -Before starting, make sure that you are running the latest firmware, -for instructions see :ref:`OTA How-To `. - -.. toctree:: - :maxdepth: 1 - :numbered: - - intro.rst - repl.rst - blynk.rst - wlan.rst - timer.rst - reset.rst diff --git a/docs/wipy/tutorial/intro.rst b/docs/wipy/tutorial/intro.rst deleted file mode 100644 index 3acc0510f1..0000000000 --- a/docs/wipy/tutorial/intro.rst +++ /dev/null @@ -1,64 +0,0 @@ -Introduction to the WiPy -======================== - -To get the most out of your WiPy, there are a few basic things to -understand about how it works. - -Caring for your WiPy and expansion board ----------------------------------------- - -Because the WiPy/expansion board does not have a housing it needs a bit of care: - - - Be gentle when plugging/unplugging the USB cable. Whilst the USB connector - is well soldered and is relatively strong, if it breaks off it can be very - difficult to fix. - - - Static electricity can shock the components on the WiPy and destroy them. - If you experience a lot of static electricity in your area (eg dry and cold - climates), take extra care not to shock the WiPy. If your WiPy came - in a ESD bag, then this bag is the best way to store and carry the - WiPy as it will protect it against static discharges. - -As long as you take care of the hardware, you should be okay. It's almost -impossible to break the software on the WiPy, so feel free to play around -with writing code as much as you like. If the filesystem gets corrupt, see -below on how to reset it. In the worst case you might need to do a safe boot, -which is explained in detail :ref:`here `. - -Plugging into the expansion board and powering on -------------------------------------------------- - -The expansion board can power the WiPy via USB. The WiPy comes with a sticker -on top of the RF shield that labels all pins, and this should match the label -numbers on the expansion board headers. When plugging it in, the WiPy antenna -will end up on top of the SD card connector of the expansion board. A video -showing how to do this can be found `here `_. - -Expansion board hardware guide ------------------------------- - -The document explaining the hardware details of the expansion board can be found -`here `_. - -Powering by an external power source ------------------------------------- - -The WiPy can be powered by a battery or other external power source. - -**Be sure to connect the positive lead of the power supply to VIN, and -ground to GND. There is no polarity protection on the WiPy so you -must be careful when connecting anything to VIN.** - -- When powering via ``VIN``: - - **The input voltage must be between 3.6V and 5.5V.** - -- When powering via ``3V3``: - - **The input voltage must be exactly 3V3, ripple free and from a supply capable - of sourcing at least 300mA of current** - -Performing firmware upgrades ----------------------------- - -For detailed instructions see :ref:`OTA How-To `. diff --git a/docs/wipy/tutorial/repl.rst b/docs/wipy/tutorial/repl.rst deleted file mode 100644 index e7b51f9c59..0000000000 --- a/docs/wipy/tutorial/repl.rst +++ /dev/null @@ -1,130 +0,0 @@ -Getting a MicroPython REPL prompt -================================= - -REPL stands for Read Evaluate Print Loop, and is the name given to the -interactive MicroPython prompt that you can access on the WiPy. Using -the REPL is by far the easiest way to test out your code and run commands. -You can use the REPL in addition to writing scripts in ``main.py``. - -.. _wipy_uart: - -To use the REPL, you must connect to the WiPy either via :ref:`telnet `, -or with a USB to serial converter wired to one of the two UARTs on the -WiPy. To enable REPL duplication on UART0 (the one accessible via the expansion board) -do:: - - >>> from machine import UART - >>> import os - >>> uart = UART(0, 115200) - >>> os.dupterm(uart) - -Place this piece of code inside your `boot.py` so that it's done automatically after -reset. - -Windows -------- - -First you need to install the FTDI drivers for the expansion board's USB to serial -converter. Then you need a terminal software. The best option is to download the -free program PuTTY: `putty.exe `_. - -**In order to get to the telnet REPL:** - -Using putty, select ``Telnet`` as connection type, leave the default port (23) -and enter the IP address of your WiPy (192.168.1.1 when in ``WLAN.AP`` mode), -then click open. - -**In order to get to the REPL UART:** - -Using your serial program you must connect to the COM port that you found in the -previous step. With PuTTY, click on "Session" in the left-hand panel, then click -the "Serial" radio button on the right, then enter you COM port (eg COM4) in the -"Serial Line" box. Finally, click the "Open" button. - -Mac OS X --------- - -Open a terminal and run:: - - $ telnet 192.168.1.1 - -or:: - - $ screen /dev/tty.usbmodem* 115200 - -When you are finished and want to exit ``screen``, type CTRL-A CTRL-\\. If your keyboard does not have a \\-key (i.e. you need an obscure combination for \\ like ALT-SHIFT-7) you can remap the ``quit`` command: - -- create ``~/.screenrc`` -- add ``bind q quit`` - -This will allow you to quit ``screen`` by hitting CTRL-A Q. - -Linux ------ - -Open a terminal and run:: - - $ telnet 192.168.1.1 - -or:: - - $ screen /dev/ttyUSB0 115200 - -You can also try ``picocom`` or ``minicom`` instead of screen. You may have to -use ``/dev/ttyUSB01`` or a higher number for ``ttyUSB``. And, you may need to give -yourself the correct permissions to access this devices (eg group ``uucp`` or ``dialout``, -or use sudo). - -Using the REPL prompt ---------------------- - -Now let's try running some MicroPython code directly on the WiPy. - -With your serial program open (PuTTY, screen, picocom, etc) you may see a blank -screen with a flashing cursor. Press Enter and you should be presented with a -MicroPython prompt, i.e. ``>>>``. Let's make sure it is working with the obligatory test:: - - >>> print("hello WiPy!") - hello WiPy! - -In the above, you should not type in the ``>>>`` characters. They are there to -indicate that you should type the text after it at the prompt. In the end, once -you have entered the text ``print("hello WiPy!")`` and pressed Enter, the output -on your screen should look like it does above. - -If you already know some Python you can now try some basic commands here. - -If any of this is not working you can try either a hard reset or a soft reset; -see below. - -Go ahead and try typing in some other commands. For example:: - - >>> from machine import Pin - >>> import wipy - >>> wipy.heartbeat(False) # disable the heartbeat - >>> led = Pin('GP25', mode=Pin.OUT) - >>> led(1) - >>> led(0) - >>> led.toggle() - >>> 1 + 2 - 3 - >>> 4 // 2 - 2 - >>> 20 * 'py' - 'pypypypypypypypypypypypypypypypypypypypy' - -Resetting the board -------------------- - -If something goes wrong, you can reset the board in two ways. The first is to press CTRL-D -at the MicroPython prompt, which performs a soft reset. You will see a message something like:: - - >>> - PYB: soft reboot - MicroPython v1.4.6-146-g1d8b5e5 on 2015-10-21; WiPy with CC3200 - Type "help()" for more information. - >>> - -If that isn't working you can perform a hard reset (turn-it-off-and-on-again) by pressing the -RST switch (the small black button next to the heartbeat LED). During telnet, this will end -your session, disconnecting whatever program that you used to connect to the WiPy. diff --git a/docs/wipy/tutorial/reset.rst b/docs/wipy/tutorial/reset.rst deleted file mode 100644 index ece28498b8..0000000000 --- a/docs/wipy/tutorial/reset.rst +++ /dev/null @@ -1,54 +0,0 @@ -Reset and boot modes -==================== - -There are soft resets and hard resets. - - - A soft reset simply clears the state of the MicroPython virtual machine, - but leaves hardware peripherals unaffected. To do a soft reset, simply press - **Ctrl+D** on the REPL, or within a script do:: - - import sys - sys.exit() - - - A hard reset is the same as performing a power cycle to the board. In order to - hard reset the WiPy, press the switch on the board or:: - - import machine - machine.reset() - -Safe boot ---------- - -If something goes wrong with your WiPy, don't panic! It is almost -impossible for you to break the WiPy by programming the wrong thing. - -The first thing to try is to boot in safe mode: this temporarily skips -execution of ``boot.py`` and ``main.py`` and gives default WLAN settings. - -If you have problems with the filesystem you can :ref:`format the internal flash -drive `. - -To boot in safe mode, follow the detailed instructions described :ref:`here `. - -In safe mode, the ``boot.py`` and ``main.py`` files are not executed, and so -the WiPy boots up with default settings. This means you now have access -to the filesystem, and you can edit ``boot.py`` and ``main.py`` to fix any problems. - -Entering safe mode is temporary, and does not make any changes to the -files on the WiPy. - -.. _wipy_factory_reset: - -Factory reset the filesystem ----------------------------- - -If you WiPy's filesystem gets corrupted (very unlikely, but possible), you -can format it very easily by doing:: - - >>> import os - >>> os.mkfs('/flash') - -Resetting the filesystem deletes all files on the internal WiPy storage -(not the SD card), and restores the files ``boot.py`` and ``main.py`` back -to their original state after the next reset. - diff --git a/docs/wipy/tutorial/timer.rst b/docs/wipy/tutorial/timer.rst deleted file mode 100644 index c87ac44959..0000000000 --- a/docs/wipy/tutorial/timer.rst +++ /dev/null @@ -1,70 +0,0 @@ -Hardware timers -=============== - -Timers can be used for a great variety of tasks, calling a function periodically, -counting events, and generating a PWM signal are among the most common use cases. -Each timer consists of two 16-bit channels and this channels can be tied together to -form one 32-bit timer. The operating mode needs to be configured per timer, but then -the period (or the frequency) can be independently configured on each channel. -By using the callback method, the timer event can call a Python function. - -Example usage to toggle an LED at a fixed frequency:: - - from machine import Timer - from machine import Pin - led = Pin('GP16', mode=Pin.OUT) # enable GP16 as output to drive the LED - tim = Timer(3) # create a timer object using timer 3 - tim.init(mode=Timer.PERIODIC) # initialize it in periodic mode - tim_ch = tim.channel(Timer.A, freq=5) # configure channel A at a frequency of 5Hz - tim_ch.irq(handler=lambda t:led.toggle(), trigger=Timer.TIMEOUT) # toggle a LED on every cycle of the timer - -Example using named function for the callback:: - - from machine import Timer - from machine import Pin - tim = Timer(1, mode=Timer.PERIODIC, width=32) - tim_a = tim.channel(Timer.A | Timer.B, freq=1) # 1 Hz frequency requires a 32 bit timer - - led = Pin('GP16', mode=Pin.OUT) # enable GP16 as output to drive the LED - - def tick(timer): # we will receive the timer object when being called - global led - led.toggle() # toggle the LED - - tim_a.irq(handler=tick, trigger=Timer.TIMEOUT) # create the interrupt - -Further examples:: - - from machine import Timer - tim1 = Timer(1, mode=Timer.ONE_SHOT) # initialize it in one shot mode - tim2 = Timer(2, mode=Timer.PWM) # initialize it in PWM mode - tim1_ch = tim1.channel(Timer.A, freq=10, polarity=Timer.POSITIVE) # start the event counter with a frequency of 10Hz and triggered by positive edges - tim2_ch = tim2.channel(Timer.B, freq=10000, duty_cycle=5000) # start the PWM on channel B with a 50% duty cycle - tim2_ch.freq(20) # set the frequency (can also get) - tim2_ch.duty_cycle(3010) # set the duty cycle to 30.1% (can also get) - tim2_ch.duty_cycle(3020, Timer.NEGATIVE) # set the duty cycle to 30.2% and change the polarity to negative - tim2_ch.period(2000000) # change the period to 2 seconds - - -Additional constants for Timer class ------------------------------------- - -.. data:: Timer.PWM - - PWM timer operating mode. - -.. data:: Timer.A -.. data:: Timer.B - - Selects the timer channel. Must be ORed (``Timer.A`` | ``Timer.B``) when - using a 32-bit timer. - -.. data:: Timer.POSITIVE -.. data:: Timer.NEGATIVE - - Timer channel polarity selection (only relevant in PWM mode). - -.. data:: Timer.TIMEOUT -.. data:: Timer.MATCH - - Timer channel IRQ triggers. diff --git a/docs/wipy/tutorial/wlan.rst b/docs/wipy/tutorial/wlan.rst deleted file mode 100644 index 434367cd93..0000000000 --- a/docs/wipy/tutorial/wlan.rst +++ /dev/null @@ -1,71 +0,0 @@ -WLAN step by step -================= - -The WLAN is a system feature of the WiPy, therefore it is always enabled -(even while in ``machine.SLEEP``), except when deepsleep mode is entered. - -In order to retrieve the current WLAN instance, do:: - - >>> from network import WLAN - >>> wlan = WLAN() # we call the constructor without params - -You can check the current mode (which is always ``WLAN.AP`` after power up):: - - >>> wlan.mode() - -.. warning:: - When you change the WLAN mode following the instructions below, your WLAN - connection to the WiPy will be broken. This means you will not be able - to run these commands interactively over the WLAN. - - There are two ways around this:: - 1. put this setup code into your :ref:`boot.py file` so that it gets executed automatically after reset. - 2. :ref:`duplicate the REPL on UART `, so that you can run commands via USB. - -Connecting to your home router ------------------------------- - -The WLAN network card always boots in ``WLAN.AP`` mode, so we must first configure -it as a station:: - - from network import WLAN - wlan = WLAN(mode=WLAN.STA) - - -Now you can proceed to scan for networks:: - - nets = wlan.scan() - for net in nets: - if net.ssid == 'mywifi': - print('Network found!') - wlan.connect(net.ssid, auth=(net.sec, 'mywifikey'), timeout=5000) - while not wlan.isconnected(): - machine.idle() # save power while waiting - print('WLAN connection succeeded!') - break - -Assigning a static IP address when booting ------------------------------------------- - -If you want your WiPy to connect to your home router after boot-up, and with a fixed -IP address so that you can access it via telnet or FTP, use the following script as /flash/boot.py:: - - import machine - from network import WLAN - wlan = WLAN() # get current object, without changing the mode - - if machine.reset_cause() != machine.SOFT_RESET: - wlan.init(WLAN.STA) - # configuration below MUST match your home router settings!! - wlan.ifconfig(config=('192.168.178.107', '255.255.255.0', '192.168.178.1', '8.8.8.8')) - - if not wlan.isconnected(): - # change the line below to match your network ssid, security and password - wlan.connect('mywifi', auth=(WLAN.WPA2, 'mywifikey'), timeout=5000) - while not wlan.isconnected(): - machine.idle() # save power while waiting - -.. note:: - - Notice how we check for the reset cause and the connection status, this is crucial in order - to be able to soft reset the WiPy during a telnet session without breaking the connection. diff --git a/docs/wipy_index.rst b/docs/wipy_index.rst deleted file mode 100644 index 15c04c0fba..0000000000 --- a/docs/wipy_index.rst +++ /dev/null @@ -1,12 +0,0 @@ -MicroPython documentation and references -======================================== - -.. toctree:: - - wipy/quickref.rst - wipy/general.rst - wipy/tutorial/index.rst - library/index.rst - reference/index.rst - genrst/index.rst - license.rst diff --git a/drivers/README.md b/drivers/README.md deleted file mode 100644 index 854acc50b6..0000000000 --- a/drivers/README.md +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains drivers for specific hardware. The drivers are -intended to work across multiple ports. diff --git a/drivers/cc3000/inc/cc3000_common.h b/drivers/cc3000/inc/cc3000_common.h deleted file mode 100644 index aa16242310..0000000000 --- a/drivers/cc3000/inc/cc3000_common.h +++ /dev/null @@ -1,365 +0,0 @@ -/***************************************************************************** -* -* cc3000_common.h - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ -#ifndef __CC3000_COMMON_H__ -#define __CC3000_COMMON_H__ - -#include "data_types.h" - -//****************************************************************************** -// Include files -//****************************************************************************** -#include -#include - -//***************************************************************************** -// Prefix exported names to avoid name clash -//***************************************************************************** -#define CC3000_EXPORT(name) cc3000_ ## name - -//***************************************************************************** -// -// If building with a C++ compiler, make all of the definitions in this header -// have a C binding. -// -//***************************************************************************** -#ifdef __cplusplus -extern "C" { -#endif - -extern int CC3000_EXPORT(errno); - -//***************************************************************************** -// ERROR CODES -//***************************************************************************** -#define ESUCCESS 0 -#define EFAIL -1 -#define EERROR EFAIL - -//***************************************************************************** -// COMMON DEFINES -//***************************************************************************** -#define ERROR_SOCKET_INACTIVE -57 - -#define WLAN_ENABLE (1) -#define WLAN_DISABLE (0) - -#define MAC_ADDR_LEN (6) - -#define SP_PORTION_SIZE (32) - -/*Defines for minimal and maximal RX buffer size. This size includes the spi - header and hci header. - The maximal buffer size derives from: - MTU + HCI header + SPI header + sendto() agrs size - The minimum buffer size derives from: - HCI header + SPI header + max args size - - This buffer is used for receiving events and data. - The packet can not be longer than MTU size and CC3000 does not support - fragmentation. Note that the same buffer is used for reception of the data - and events from CC3000. That is why the minimum is defined. - The calculation for the actual size of buffer for reception is: - Given the maximal data size MAX_DATA that is expected to be received by - application, the required buffer is: - Using recv() or recvfrom(): - - max(CC3000_MINIMAL_RX_SIZE, MAX_DATA + HEADERS_SIZE_DATA + fromlen - + ucArgsize + 1) - - Using gethostbyname() with minimal buffer size will limit the host name - returned to 99 bytes only. - The 1 is used for the overrun detection - - Buffer size increased to 130 following the add_profile() with WEP security - which requires TX buffer size of 130 bytes: - HEADERS_SIZE_EVNT + WLAN_ADD_PROFILE_WEP_PARAM_LEN + MAX SSID LEN + 4 * MAX KEY LEN = 130 - MAX SSID LEN = 32 - MAX SSID LEN = 13 (with add_profile only ascii key setting is supported, - therfore maximum key size is 13) -*/ - -#define CC3000_MINIMAL_RX_SIZE (130 + 1) -#define CC3000_MAXIMAL_RX_SIZE (1519 + 1) - -/*Defines for minimal and maximal TX buffer size. - This buffer is used for sending events and data. - The packet can not be longer than MTU size and CC3000 does not support - fragmentation. Note that the same buffer is used for transmission of the data - and commands. That is why the minimum is defined. - The calculation for the actual size of buffer for transmission is: - Given the maximal data size MAX_DATA, the required buffer is: - Using Sendto(): - - max(CC3000_MINIMAL_TX_SIZE, MAX_DATA + SPI_HEADER_SIZE - + SOCKET_SENDTO_PARAMS_LEN + SIMPLE_LINK_HCI_DATA_HEADER_SIZE + 1) - - Using Send(): - - max(CC3000_MINIMAL_TX_SIZE, MAX_DATA + SPI_HEADER_SIZE - + HCI_CMND_SEND_ARG_LENGTH + SIMPLE_LINK_HCI_DATA_HEADER_SIZE + 1) - - The 1 is used for the overrun detection */ - -#define CC3000_MINIMAL_TX_SIZE (130 + 1) -#define CC3000_MAXIMAL_TX_SIZE (1519 + 1) - -//TX and RX buffer sizes, allow to receive and transmit maximum data at length 8. -#ifdef CC3000_TINY_DRIVER -#define TINY_CC3000_MAXIMAL_RX_SIZE 44 -#define TINY_CC3000_MAXIMAL_TX_SIZE 59 -#endif - -/*In order to determine your preferred buffer size, - change CC3000_MAXIMAL_RX_SIZE and CC3000_MAXIMAL_TX_SIZE to a value between - the minimal and maximal specified above. - Note that the buffers are allocated by SPI. - In case you change the size of those buffers, you might need also to change - the linker file, since for example on MSP430 FRAM devices the buffers are - allocated in the FRAM section that is allocated manually and not by IDE. -*/ - -#ifndef CC3000_TINY_DRIVER - - #define CC3000_RX_BUFFER_SIZE (CC3000_MAXIMAL_RX_SIZE) - #define CC3000_TX_BUFFER_SIZE (CC3000_MAXIMAL_TX_SIZE) - -//if defined TINY DRIVER we use smaller RX and TX buffer in order to minimize RAM consumption -#else - #define CC3000_RX_BUFFER_SIZE (TINY_CC3000_MAXIMAL_RX_SIZE) - #define CC3000_TX_BUFFER_SIZE (TINY_CC3000_MAXIMAL_TX_SIZE) - -#endif - -//***************************************************************************** -// Compound Types -//***************************************************************************** -typedef INT32 time_t; -typedef UINT32 clock_t; -typedef INT32 suseconds_t; - -typedef struct cc3000_timeval cc3000_timeval; - -struct cc3000_timeval -{ - time_t tv_sec; /* seconds */ - suseconds_t tv_usec; /* microseconds */ -}; - -typedef CHAR *(*tFWPatches)(UINT32 *usLength); - -typedef CHAR *(*tDriverPatches)(UINT32 *usLength); - -typedef CHAR *(*tBootLoaderPatches)(UINT32 *usLength); - -typedef void (*tWlanCB)(INT32 event_type, CHAR * data, UINT8 length ); - -typedef INT32 (*tWlanReadInteruptPin)(void); - -typedef void (*tWlanInterruptEnable)(void); - -typedef void (*tWlanInterruptDisable)(void); - -typedef void (*tWriteWlanPin)(UINT8 val); - -typedef struct -{ - UINT16 usRxEventOpcode; - UINT16 usEventOrDataReceived; - UINT8 *pucReceivedData; - UINT8 *pucTxCommandBuffer; - - tFWPatches sFWPatches; - tDriverPatches sDriverPatches; - tBootLoaderPatches sBootLoaderPatches; - tWlanCB sWlanCB; - tWlanReadInteruptPin ReadWlanInterruptPin; - tWlanInterruptEnable WlanInterruptEnable; - tWlanInterruptDisable WlanInterruptDisable; - tWriteWlanPin WriteWlanPin; - - INT32 slTransmitDataError; - UINT16 usNumberOfFreeBuffers; - UINT16 usSlBufferLength; - UINT16 usBufferSize; - UINT16 usRxDataPending; - - UINT32 NumberOfSentPackets; - UINT32 NumberOfReleasedPackets; - - UINT8 InformHostOnTxComplete; -}sSimplLinkInformation; - -extern volatile sSimplLinkInformation tSLInformation; - - -//***************************************************************************** -// Prototypes for the APIs. -//***************************************************************************** - - - -//***************************************************************************** -// -//! SimpleLinkWaitEvent -//! -//! @param usOpcode command operation code -//! @param pRetParams command return parameters -//! -//! @return none -//! -//! @brief Wait for event, pass it to the hci_event_handler and -//! update the event opcode in a global variable. -// -//***************************************************************************** - -extern void SimpleLinkWaitEvent(UINT16 usOpcode, void *pRetParams); - -//***************************************************************************** -// -//! SimpleLinkWaitData -//! -//! @param pBuf data buffer -//! @param from from information -//! @param fromlen from information length -//! -//! @return none -//! -//! @brief Wait for data, pass it to the hci_event_handler -//! and update in a global variable that there is -//! data to read. -// -//***************************************************************************** - -extern void SimpleLinkWaitData(UINT8 *pBuf, UINT8 *from, UINT8 *fromlen); - -//***************************************************************************** -// -//! UINT32_TO_STREAM_f -//! -//! \param p pointer to the new stream -//! \param u32 pointer to the 32 bit -//! -//! \return pointer to the new stream -//! -//! \brief This function is used for copying 32 bit to stream -//! while converting to little endian format. -// -//***************************************************************************** - -extern UINT8* UINT32_TO_STREAM_f (UINT8 *p, UINT32 u32); - -//***************************************************************************** -// -//! UINT16_TO_STREAM_f -//! -//! \param p pointer to the new stream -//! \param u32 pointer to the 16 bit -//! -//! \return pointer to the new stream -//! -//! \brief This function is used for copying 16 bit to stream -//! while converting to little endian format. -// -//***************************************************************************** - -extern UINT8* UINT16_TO_STREAM_f (UINT8 *p, UINT16 u16); - -//***************************************************************************** -// -//! STREAM_TO_UINT16_f -//! -//! \param p pointer to the stream -//! \param offset offset in the stream -//! -//! \return pointer to the new 16 bit -//! -//! \brief This function is used for copying received stream to -//! 16 bit in little endian format. -// -//***************************************************************************** - -extern UINT16 STREAM_TO_UINT16_f(CHAR* p, UINT16 offset); - -//***************************************************************************** -// -//! STREAM_TO_UINT32_f -//! -//! \param p pointer to the stream -//! \param offset offset in the stream -//! -//! \return pointer to the new 32 bit -//! -//! \brief This function is used for copying received stream to -//! 32 bit in little endian format. -// -//***************************************************************************** - -extern UINT32 STREAM_TO_UINT32_f(CHAR* p, UINT16 offset); - - -//***************************************************************************** -// COMMON MACROs -//***************************************************************************** - - -//This macro is used for copying 8 bit to stream while converting to little endian format. -#define UINT8_TO_STREAM(_p, _val) {*(_p)++ = (_val);} -//This macro is used for copying 16 bit to stream while converting to little endian format. -#define UINT16_TO_STREAM(_p, _u16) (UINT16_TO_STREAM_f(_p, _u16)) -//This macro is used for copying 32 bit to stream while converting to little endian format. -#define UINT32_TO_STREAM(_p, _u32) (UINT32_TO_STREAM_f(_p, _u32)) -//This macro is used for copying a specified value length bits (l) to stream while converting to little endian format. -#define ARRAY_TO_STREAM(p, a, l) {register INT16 _i; for (_i = 0; _i < l; _i++) *(p)++ = ((UINT8 *) a)[_i];} -//This macro is used for copying received stream to 8 bit in little endian format. -#define STREAM_TO_UINT8(_p, _offset, _u8) {_u8 = (UINT8)(*(_p + _offset));} -//This macro is used for copying received stream to 16 bit in little endian format. -#define STREAM_TO_UINT16(_p, _offset, _u16) {_u16 = STREAM_TO_UINT16_f(_p, _offset);} -//This macro is used for copying received stream to 32 bit in little endian format. -#define STREAM_TO_UINT32(_p, _offset, _u32) {_u32 = STREAM_TO_UINT32_f(_p, _offset);} -#define STREAM_TO_STREAM(p, a, l) {register INT16 _i; for (_i = 0; _i < l; _i++) *(a)++= ((UINT8 *) p)[_i];} - - - - -//***************************************************************************** -// -// Mark the end of the C bindings section for C++ compilers. -// -//***************************************************************************** -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif // __CC3000_COMMON_H__ diff --git a/drivers/cc3000/inc/ccspi.h b/drivers/cc3000/inc/ccspi.h deleted file mode 100644 index 8fa3ecd10c..0000000000 --- a/drivers/cc3000/inc/ccspi.h +++ /dev/null @@ -1,84 +0,0 @@ -/***************************************************************************** -* -* spi.h - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ - - -#ifndef __CC3000_SPI_H__ -#define __CC3000_SPI_H__ - -//***************************************************************************** -// -// If building with a C++ compiler, make all of the definitions in this header -// have a C binding. -// -//***************************************************************************** -#ifdef __cplusplus -extern "C" { -#endif - -typedef void (*gcSpiHandleRx)(void *p); -typedef void (*gcSpiHandleTx)(void); -extern unsigned char wlan_tx_buffer[]; - -//***************************************************************************** -// -// Prototypes for the APIs. -// -//***************************************************************************** - -// the arguments must be of type pin_obj_t* and SPI_HandleTypeDef* -extern void SpiInit(void *spi, const void *pin_cs, const void *pin_en, const void *pin_irq); - -extern void SpiOpen(gcSpiHandleRx pfRxHandler); -extern void SpiClose(void); -extern void SpiPauseSpi(void); -extern void SpiResumeSpi(void); -extern long SpiWrite(unsigned char *pUserBuffer, unsigned short usLength); -extern void SpiConfigureHwMapping(void); -extern void SpiCleanGPIOISR(void); -extern void SSIConfigure(unsigned long ulSSIFreq, unsigned long bForceGpioConfiguration, unsigned long uiReconfigureSysClock); -extern int init_spi(void); -extern long ReadWlanInterruptPin(void); -extern void WriteWlanPin(unsigned char val); -//***************************************************************************** -// -// Mark the end of the C bindings section for C++ compilers. -// -//***************************************************************************** -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif - diff --git a/drivers/cc3000/inc/data_types.h b/drivers/cc3000/inc/data_types.h deleted file mode 100644 index 0520a9202f..0000000000 --- a/drivers/cc3000/inc/data_types.h +++ /dev/null @@ -1,107 +0,0 @@ -/***************************************************************************** -* -* data_types.h - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ -#ifndef __CC3000_DATA_TYPES__ -#define __CC3000_DATA_TYPES__ - -//***************************************************************************** -// -// If building with a C++ compiler, make all of the definitions in this header -// have a C binding. -// -//***************************************************************************** -#ifdef __cplusplus -extern "C" { -#endif - - -#ifndef NULL -#define NULL (0) -#endif - -#ifndef FALSE -#define FALSE (0) -#endif - -#ifndef TRUE -#define TRUE (!FALSE) -#endif - -#ifndef OK -#define OK (0) -#endif - -#ifndef _INT8 -#define _INT8 -typedef signed char INT8; -#endif - -#ifndef _UINT8 -#define _UINT8 -typedef unsigned char UINT8; -#endif - -#ifndef _INT16 -#define _INT16 -typedef signed short INT16; -#endif - -#ifndef _UINT16 -#define _UINT16 -typedef unsigned short UINT16; -#endif - -#ifndef _BOOLEAN -#define _BOOLEAN -typedef unsigned char BOOLEAN; -#endif - -#ifndef _INT32 -#define _INT32 -typedef signed long INT32; -#endif - -#ifndef _UINT32 -#define _UINT32 -typedef unsigned long UINT32; -#endif - -typedef int INT; -typedef char CHAR; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __CC3000_DATA_TYPES__ */ diff --git a/drivers/cc3000/inc/evnt_handler.h b/drivers/cc3000/inc/evnt_handler.h deleted file mode 100644 index d05a442f05..0000000000 --- a/drivers/cc3000/inc/evnt_handler.h +++ /dev/null @@ -1,166 +0,0 @@ -/***************************************************************************** -* -* evnt_handler.h - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ -#ifndef __CC3000_EVENT_HANDLER_H__ -#define __CC3000_EVENT_HANDLER_H__ -#include "hci.h" -#include "socket.h" - -//***************************************************************************** -// -// If building with a C++ compiler, make all of the definitions in this header -// have a C binding. -// -//***************************************************************************** -#ifdef __cplusplus -extern "C" { -#endif - -//***************************************************************************** -// -// Prototypes for the APIs. -// -//***************************************************************************** - -//***************************************************************************** -// -//! hci_event_handler -//! -//! @param pRetParams incoming data buffer -//! @param from from information (in case of data received) -//! @param fromlen from information length (in case of data received) -//! -//! @return none -//! -//! @brief Parse the incoming events packets and issues corresponding -//! event handler from global array of handlers pointers -// -//***************************************************************************** -extern UINT8 *hci_event_handler(void *pRetParams, UINT8 *from, UINT8 *fromlen); - -//***************************************************************************** -// -//! hci_unsol_event_handler -//! -//! @param event_hdr event header -//! -//! @return 1 if event supported and handled -//! 0 if event is not supported -//! -//! @brief Handle unsolicited events -// -//***************************************************************************** -extern INT32 hci_unsol_event_handler(CHAR *event_hdr); - -//***************************************************************************** -// -//! hci_unsolicited_event_handler -//! -//! @param None -//! -//! @return ESUCCESS if successful, EFAIL if an error occurred -//! -//! @brief Parse the incoming unsolicited event packets and issues -//! corresponding event handler. -// -//***************************************************************************** -extern INT32 hci_unsolicited_event_handler(void); - -#define M_BSD_RESP_PARAMS_OFFSET(hci_event_hdr)((CHAR *)(hci_event_hdr) + HCI_EVENT_HEADER_SIZE) - -#define SOCKET_STATUS_ACTIVE 0 -#define SOCKET_STATUS_INACTIVE 1 -/* Init socket_active_status = 'all ones': init all sockets with SOCKET_STATUS_INACTIVE. - Will be changed by 'set_socket_active_status' upon 'connect' and 'accept' calls */ -#define SOCKET_STATUS_INIT_VAL 0xFFFF -#define M_IS_VALID_SD(sd) ((0 <= (sd)) && ((sd) <= 7)) -#define M_IS_VALID_STATUS(status) (((status) == SOCKET_STATUS_ACTIVE)||((status) == SOCKET_STATUS_INACTIVE)) - -extern UINT32 socket_active_status; - -extern void set_socket_active_status(INT32 Sd, INT32 Status); -extern INT32 get_socket_active_status(INT32 Sd); - -typedef struct _bsd_accept_return_t -{ - INT32 iSocketDescriptor; - INT32 iStatus; - sockaddr tSocketAddress; - -} tBsdReturnParams; - - -typedef struct _bsd_read_return_t -{ - INT32 iSocketDescriptor; - INT32 iNumberOfBytes; - UINT32 uiFlags; -} tBsdReadReturnParams; - -#define BSD_RECV_FROM_FROMLEN_OFFSET (4) -#define BSD_RECV_FROM_FROM_OFFSET (16) - - -typedef struct _bsd_select_return_t -{ - INT32 iStatus; - UINT32 uiRdfd; - UINT32 uiWrfd; - UINT32 uiExfd; -} tBsdSelectRecvParams; - - -typedef struct _bsd_getsockopt_return_t -{ - UINT8 ucOptValue[4]; - CHAR iStatus; -} tBsdGetSockOptReturnParams; - -typedef struct _bsd_gethostbyname_return_t -{ - INT32 retVal; - INT32 outputAddress; -} tBsdGethostbynameParams; - -//***************************************************************************** -// -// Mark the end of the C bindings section for C++ compilers. -// -//***************************************************************************** -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif // __CC3000_EVENT_HANDLER_H__ - diff --git a/drivers/cc3000/inc/hci.h b/drivers/cc3000/inc/hci.h deleted file mode 100644 index f12b00e918..0000000000 --- a/drivers/cc3000/inc/hci.h +++ /dev/null @@ -1,330 +0,0 @@ -/***************************************************************************** -* -* hci.h - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ -#ifndef __CC3000_HCI_H__ -#define __CC3000_HCI_H__ - -#include "cc3000_common.h" - -//***************************************************************************** -// -// If building with a C++ compiler, make all of the definitions in this header -// have a C binding. -// -//***************************************************************************** -#ifdef __cplusplus -extern "C" { -#endif - - -#define SPI_HEADER_SIZE (5) -#define SIMPLE_LINK_HCI_CMND_HEADER_SIZE (4) -#define HEADERS_SIZE_CMD (SPI_HEADER_SIZE + SIMPLE_LINK_HCI_CMND_HEADER_SIZE) -#define SIMPLE_LINK_HCI_DATA_CMND_HEADER_SIZE (5) -#define SIMPLE_LINK_HCI_DATA_HEADER_SIZE (5) -#define SIMPLE_LINK_HCI_PATCH_HEADER_SIZE (2) - - -//***************************************************************************** -// -// Values that can be used as HCI Commands and HCI Packet header defines -// -//***************************************************************************** -#define HCI_TYPE_CMND 0x1 -#define HCI_TYPE_DATA 0x2 -#define HCI_TYPE_PATCH 0x3 -#define HCI_TYPE_EVNT 0x4 - - -#define HCI_EVENT_PATCHES_DRV_REQ (1) -#define HCI_EVENT_PATCHES_FW_REQ (2) -#define HCI_EVENT_PATCHES_BOOTLOAD_REQ (3) - - -#define HCI_CMND_WLAN_BASE (0x0000) -#define HCI_CMND_WLAN_CONNECT 0x0001 -#define HCI_CMND_WLAN_DISCONNECT 0x0002 -#define HCI_CMND_WLAN_IOCTL_SET_SCANPARAM 0x0003 -#define HCI_CMND_WLAN_IOCTL_SET_CONNECTION_POLICY 0x0004 -#define HCI_CMND_WLAN_IOCTL_ADD_PROFILE 0x0005 -#define HCI_CMND_WLAN_IOCTL_DEL_PROFILE 0x0006 -#define HCI_CMND_WLAN_IOCTL_GET_SCAN_RESULTS 0x0007 -#define HCI_CMND_EVENT_MASK 0x0008 -#define HCI_CMND_WLAN_IOCTL_STATUSGET 0x0009 -#define HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_START 0x000A -#define HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_STOP 0x000B -#define HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_SET_PREFIX 0x000C -#define HCI_CMND_WLAN_CONFIGURE_PATCH 0x000D - - -#define HCI_CMND_SOCKET_BASE 0x1000 -#define HCI_CMND_SOCKET 0x1001 -#define HCI_CMND_BIND 0x1002 -#define HCI_CMND_RECV 0x1004 -#define HCI_CMND_ACCEPT 0x1005 -#define HCI_CMND_LISTEN 0x1006 -#define HCI_CMND_CONNECT 0x1007 -#define HCI_CMND_BSD_SELECT 0x1008 -#define HCI_CMND_SETSOCKOPT 0x1009 -#define HCI_CMND_GETSOCKOPT 0x100A -#define HCI_CMND_CLOSE_SOCKET 0x100B -#define HCI_CMND_RECVFROM 0x100D -#define HCI_CMND_GETHOSTNAME 0x1010 -#define HCI_CMND_MDNS_ADVERTISE 0x1011 -#define HCI_CMND_GETMSSVALUE 0x1012 - - -#define HCI_DATA_BASE 0x80 - -#define HCI_CMND_SEND (0x01 + HCI_DATA_BASE) -#define HCI_CMND_SENDTO (0x03 + HCI_DATA_BASE) -#define HCI_DATA_BSD_RECVFROM (0x04 + HCI_DATA_BASE) -#define HCI_DATA_BSD_RECV (0x05 + HCI_DATA_BASE) - - -#define HCI_CMND_NVMEM_CBASE (0x0200) - - -#define HCI_CMND_NVMEM_CREATE_ENTRY (0x0203) -#define HCI_CMND_NVMEM_SWAP_ENTRY (0x0205) -#define HCI_CMND_NVMEM_READ (0x0201) -#define HCI_CMND_NVMEM_WRITE (0x0090) -#define HCI_CMND_NVMEM_WRITE_PATCH (0x0204) -#define HCI_CMND_READ_SP_VERSION (0x0207) - -#define HCI_CMND_READ_BUFFER_SIZE 0x400B -#define HCI_CMND_SIMPLE_LINK_START 0x4000 - -#define HCI_CMND_NETAPP_BASE 0x2000 - -#define HCI_NETAPP_DHCP (0x0001 + HCI_CMND_NETAPP_BASE) -#define HCI_NETAPP_PING_SEND (0x0002 + HCI_CMND_NETAPP_BASE) -#define HCI_NETAPP_PING_REPORT (0x0003 + HCI_CMND_NETAPP_BASE) -#define HCI_NETAPP_PING_STOP (0x0004 + HCI_CMND_NETAPP_BASE) -#define HCI_NETAPP_IPCONFIG (0x0005 + HCI_CMND_NETAPP_BASE) -#define HCI_NETAPP_ARP_FLUSH (0x0006 + HCI_CMND_NETAPP_BASE) -#define HCI_NETAPP_SET_DEBUG_LEVEL (0x0008 + HCI_CMND_NETAPP_BASE) -#define HCI_NETAPP_SET_TIMERS (0x0009 + HCI_CMND_NETAPP_BASE) - - - - - - -//***************************************************************************** -// -// Values that can be used as HCI Events defines -// -//***************************************************************************** -#define HCI_EVNT_WLAN_BASE 0x0000 -#define HCI_EVNT_WLAN_CONNECT 0x0001 -#define HCI_EVNT_WLAN_DISCONNECT \ - 0x0002 -#define HCI_EVNT_WLAN_IOCTL_ADD_PROFILE \ - 0x0005 - - -#define HCI_EVNT_SOCKET HCI_CMND_SOCKET -#define HCI_EVNT_BIND HCI_CMND_BIND -#define HCI_EVNT_RECV HCI_CMND_RECV -#define HCI_EVNT_ACCEPT HCI_CMND_ACCEPT -#define HCI_EVNT_LISTEN HCI_CMND_LISTEN -#define HCI_EVNT_CONNECT HCI_CMND_CONNECT -#define HCI_EVNT_SELECT HCI_CMND_BSD_SELECT -#define HCI_EVNT_CLOSE_SOCKET HCI_CMND_CLOSE_SOCKET -#define HCI_EVNT_RECVFROM HCI_CMND_RECVFROM -#define HCI_EVNT_SETSOCKOPT HCI_CMND_SETSOCKOPT -#define HCI_EVNT_GETSOCKOPT HCI_CMND_GETSOCKOPT -#define HCI_EVNT_BSD_GETHOSTBYNAME HCI_CMND_GETHOSTNAME -#define HCI_EVNT_MDNS_ADVERTISE HCI_CMND_MDNS_ADVERTISE -#define HCI_EVNT_GETMSSVALUE HCI_CMND_GETMSSVALUE - -#define HCI_EVNT_SEND 0x1003 -#define HCI_EVNT_WRITE 0x100E -#define HCI_EVNT_SENDTO 0x100F - -#define HCI_EVNT_PATCHES_REQ 0x1000 - -#define HCI_EVNT_UNSOL_BASE 0x4000 - -#define HCI_EVNT_WLAN_UNSOL_BASE (0x8000) - -#define HCI_EVNT_WLAN_UNSOL_CONNECT (0x0001 + HCI_EVNT_WLAN_UNSOL_BASE) -#define HCI_EVNT_WLAN_UNSOL_DISCONNECT (0x0002 + HCI_EVNT_WLAN_UNSOL_BASE) -#define HCI_EVNT_WLAN_UNSOL_INIT (0x0004 + HCI_EVNT_WLAN_UNSOL_BASE) -#define HCI_EVNT_WLAN_TX_COMPLETE (0x0008 + HCI_EVNT_WLAN_UNSOL_BASE) -#define HCI_EVNT_WLAN_UNSOL_DHCP (0x0010 + HCI_EVNT_WLAN_UNSOL_BASE) -#define HCI_EVNT_WLAN_ASYNC_PING_REPORT (0x0040 + HCI_EVNT_WLAN_UNSOL_BASE) -#define HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE (0x0080 + HCI_EVNT_WLAN_UNSOL_BASE) -#define HCI_EVNT_WLAN_KEEPALIVE (0x0200 + HCI_EVNT_WLAN_UNSOL_BASE) -#define HCI_EVNT_BSD_TCP_CLOSE_WAIT (0x0800 + HCI_EVNT_WLAN_UNSOL_BASE) - -#define HCI_EVNT_DATA_UNSOL_FREE_BUFF \ - 0x4100 - -#define HCI_EVNT_NVMEM_CREATE_ENTRY \ - HCI_CMND_NVMEM_CREATE_ENTRY -#define HCI_EVNT_NVMEM_SWAP_ENTRY HCI_CMND_NVMEM_SWAP_ENTRY - -#define HCI_EVNT_NVMEM_READ HCI_CMND_NVMEM_READ -#define HCI_EVNT_NVMEM_WRITE (0x0202) - -#define HCI_EVNT_READ_SP_VERSION \ - HCI_CMND_READ_SP_VERSION - -#define HCI_EVNT_INPROGRESS 0xFFFF - - -#define HCI_DATA_RECVFROM 0x84 -#define HCI_DATA_RECV 0x85 -#define HCI_DATA_NVMEM 0x91 - -#define HCI_EVENT_CC3000_CAN_SHUT_DOWN 0x99 - -//***************************************************************************** -// -// Prototypes for the structures for APIs. -// -//***************************************************************************** - -#define HCI_DATA_HEADER_SIZE (5) -#define HCI_EVENT_HEADER_SIZE (5) -#define HCI_DATA_CMD_HEADER_SIZE (5) -#define HCI_PATCH_HEADER_SIZE (6) - -#define HCI_PACKET_TYPE_OFFSET (0) -#define HCI_PACKET_ARGSIZE_OFFSET (2) -#define HCI_PACKET_LENGTH_OFFSET (3) - - -#define HCI_EVENT_OPCODE_OFFSET (1) -#define HCI_EVENT_LENGTH_OFFSET (3) -#define HCI_EVENT_STATUS_OFFSET (4) -#define HCI_DATA_LENGTH_OFFSET (3) - - - - -//***************************************************************************** -// -// Prototypes for the APIs. -// -//***************************************************************************** - -//***************************************************************************** -// -//! hci_command_send -//! -//! @param usOpcode command operation code -//! @param pucBuff pointer to the command's arguments buffer -//! @param ucArgsLength length of the arguments -//! -//! @return none -//! -//! @brief Initiate an HCI command. -// -//***************************************************************************** -extern UINT16 hci_command_send(UINT16 usOpcode, - UINT8 *ucArgs, - UINT8 ucArgsLength); - - -//***************************************************************************** -// -//! hci_data_send -//! -//! @param usOpcode command operation code -//! @param ucArgs pointer to the command's arguments buffer -//! @param usArgsLength length of the arguments -//! @param ucTail pointer to the data buffer -//! @param usTailLength buffer length -//! -//! @return none -//! -//! @brief Initiate an HCI data write operation -// -//***************************************************************************** -extern INT32 hci_data_send(UINT8 ucOpcode, - UINT8 *ucArgs, - UINT16 usArgsLength, - UINT16 usDataLength, - const UINT8 *ucTail, - UINT16 usTailLength); - - -//***************************************************************************** -// -//! hci_data_command_send -//! -//! @param usOpcode command operation code -//! @param pucBuff pointer to the data buffer -//! @param ucArgsLength arguments length -//! @param ucDataLength data length -//! -//! @return none -//! -//! @brief Prepare HCI header and initiate an HCI data write operation -// -//***************************************************************************** -extern void hci_data_command_send(UINT16 usOpcode, UINT8 *pucBuff, - UINT8 ucArgsLength, UINT16 ucDataLength); - -//***************************************************************************** -// -//! hci_patch_send -//! -//! @param usOpcode command operation code -//! @param pucBuff pointer to the command's arguments buffer -//! @param patch pointer to patch content buffer -//! @param usDataLength data length -//! -//! @return none -//! -//! @brief Prepare HCI header and initiate an HCI patch write operation -// -//***************************************************************************** -extern void hci_patch_send(UINT8 ucOpcode, UINT8 *pucBuff, CHAR *patch, UINT16 usDataLength); - - - -//***************************************************************************** -// -// Mark the end of the C bindings section for C++ compilers. -// -//***************************************************************************** -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif // __CC3000_HCI_H__ diff --git a/drivers/cc3000/inc/host_driver_version.h b/drivers/cc3000/inc/host_driver_version.h deleted file mode 100644 index a28d21f1be..0000000000 --- a/drivers/cc3000/inc/host_driver_version.h +++ /dev/null @@ -1,40 +0,0 @@ -/***************************************************************************** -* -* host_driver_version.h - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ -#ifndef __CC3000_HOST_DRIVER_VERSION_H__ -#define __CC3000_HOST_DRIVER_VERSION_H__ - -#define DRIVER_VERSION_NUMBER 15 - -#endif // __CC3000_HOST_DRIVER_VERSION_H__ diff --git a/drivers/cc3000/inc/inet_ntop.h b/drivers/cc3000/inc/inet_ntop.h deleted file mode 100644 index fa70806206..0000000000 --- a/drivers/cc3000/inc/inet_ntop.h +++ /dev/null @@ -1,4 +0,0 @@ -#ifndef __INET_NTOP_H -#define __INET_NTOP_H -char *inet_ntop(int af, const void *addr, char *buf, size_t size); -#endif /* __INET_NTOP_H */ diff --git a/drivers/cc3000/inc/inet_pton.h b/drivers/cc3000/inc/inet_pton.h deleted file mode 100644 index 0896d5d29f..0000000000 --- a/drivers/cc3000/inc/inet_pton.h +++ /dev/null @@ -1,4 +0,0 @@ -#ifndef __INET_PTON_H -#define __INET_PTON_H -int inet_pton(int, const char *, void *); -#endif /* __INET_PTON_H */ diff --git a/drivers/cc3000/inc/netapp.h b/drivers/cc3000/inc/netapp.h deleted file mode 100644 index 1e4f265896..0000000000 --- a/drivers/cc3000/inc/netapp.h +++ /dev/null @@ -1,343 +0,0 @@ -/***************************************************************************** -* -* netapp.h - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ -#ifndef __CC3000_NETAPP_H__ -#define __CC3000_NETAPP_H__ - -#include "data_types.h" - -//***************************************************************************** -// -// If building with a C++ compiler, make all of the definitions in this header -// have a C binding. -// -//***************************************************************************** -#ifdef __cplusplus -extern "C" { -#endif - -//***************************************************************************** -// -//! \addtogroup netapp_api -//! @{ -// -//***************************************************************************** - -typedef struct _netapp_dhcp_ret_args_t -{ - UINT8 aucIP[4]; - UINT8 aucSubnetMask[4]; - UINT8 aucDefaultGateway[4]; - UINT8 aucDHCPServer[4]; - UINT8 aucDNSServer[4]; -}tNetappDhcpParams; - -typedef struct _netapp_ipconfig_ret_args_t -{ - UINT8 aucIP[4]; - UINT8 aucSubnetMask[4]; - UINT8 aucDefaultGateway[4]; - UINT8 aucDHCPServer[4]; - UINT8 aucDNSServer[4]; - UINT8 uaMacAddr[6]; - UINT8 uaSSID[32]; -}tNetappIpconfigRetArgs; - - -/*Ping send report parameters*/ -typedef struct _netapp_pingreport_args -{ - UINT32 packets_sent; - UINT32 packets_received; - UINT32 min_round_time; - UINT32 max_round_time; - UINT32 avg_round_time; -} netapp_pingreport_args_t; - - -//***************************************************************************** -// -//! netapp_config_mac_adrress -//! -//! @param mac device mac address, 6 bytes. Saved: yes -//! -//! @return return on success 0, otherwise error. -//! -//! @brief Configure device MAC address and store it in NVMEM. -//! The value of the MAC address configured through the API will -//! be stored in CC3000 non volatile memory, thus preserved -//! over resets. -// -//***************************************************************************** -extern INT32 netapp_config_mac_adrress( UINT8 *mac ); - -//***************************************************************************** -// -//! netapp_dhcp -//! -//! @param aucIP device mac address, 6 bytes. Saved: yes -//! @param aucSubnetMask device mac address, 6 bytes. Saved: yes -//! @param aucDefaultGateway device mac address, 6 bytes. Saved: yes -//! @param aucDNSServer device mac address, 6 bytes. Saved: yes -//! -//! @return return on success 0, otherwise error. -//! -//! @brief netapp_dhcp is used to configure the network interface, -//! static or dynamic (DHCP).\n In order to activate DHCP mode, -//! aucIP, aucSubnetMask, aucDefaultGateway must be 0. -//! The default mode of CC3000 is DHCP mode. -//! Note that the configuration is saved in non volatile memory -//! and thus preserved over resets. -//! -//! @note If the mode is altered a reset of CC3000 device is required -//! in order to apply changes.\nAlso note that asynchronous event -//! of DHCP_EVENT, which is generated when an IP address is -//! allocated either by the DHCP server or due to static -//! allocation is generated only upon a connection to the -//! AP was established. -//! -//***************************************************************************** -extern INT32 netapp_dhcp(UINT32 *aucIP, UINT32 *aucSubnetMask,UINT32 *aucDefaultGateway, UINT32 *aucDNSServer); - - - -//***************************************************************************** -// -//! netapp_timeout_values -//! -//! @param aucDHCP DHCP lease time request, also impact -//! the DHCP renew timeout. Range: [0-0xffffffff] seconds, -//! 0 or 0xffffffff == infinity lease timeout. -//! Resolution:10 seconds. Influence: only after -//! reconnecting to the AP. -//! Minimal bound value: MIN_TIMER_VAL_SECONDS - 10 seconds. -//! The parameter is saved into the CC3000 NVMEM. -//! The default value on CC3000 is 14400 seconds. -//! -//! @param aucARP ARP refresh timeout, if ARP entry is not updated by -//! incoming packet, the ARP entry will be deleted by -//! the end of the timeout. -//! Range: [0-0xffffffff] seconds, 0 == infinity ARP timeout -//! Resolution: 10 seconds. Influence: on runtime. -//! Minimal bound value: MIN_TIMER_VAL_SECONDS - 10 seconds -//! The parameter is saved into the CC3000 NVMEM. -//! The default value on CC3000 is 3600 seconds. -//! -//! @param aucKeepalive Keepalive event sent by the end of keepalive timeout -//! Range: [0-0xffffffff] seconds, 0 == infinity timeout -//! Resolution: 10 seconds. -//! Influence: on runtime. -//! Minimal bound value: MIN_TIMER_VAL_SECONDS - 10 sec -//! The parameter is saved into the CC3000 NVMEM. -//! The default value on CC3000 is 10 seconds. -//! -//! @param aucInactivity Socket inactivity timeout, socket timeout is -//! refreshed by incoming or outgoing packet, by the -//! end of the socket timeout the socket will be closed -//! Range: [0-0xffffffff] sec, 0 == infinity timeout. -//! Resolution: 10 seconds. Influence: on runtime. -//! Minimal bound value: MIN_TIMER_VAL_SECONDS - 10 sec -//! The parameter is saved into the CC3000 NVMEM. -//! The default value on CC3000 is 60 seconds. -//! -//! @return return on success 0, otherwise error. -//! -//! @brief Set new timeout values. Function set new timeout values for: -//! DHCP lease timeout, ARP refresh timeout, keepalive event -//! timeout and socket inactivity timeout -//! -//! @note If a parameter set to non zero value which is less than 10s, -//! it will be set automatically to 10s. -//! -//***************************************************************************** -#ifndef CC3000_TINY_DRIVER -extern INT32 netapp_timeout_values(UINT32 *aucDHCP, UINT32 *aucARP, UINT32 *aucKeepalive, UINT32 *aucInactivity); -#endif - -//***************************************************************************** -// -//! netapp_ping_send -//! -//! @param ip destination IP address -//! @param pingAttempts number of echo requests to send -//! @param pingSize send buffer size which may be up to 1400 bytes -//! @param pingTimeout Time to wait for a response,in milliseconds. -//! -//! @return return on success 0, otherwise error. -//! -//! @brief send ICMP ECHO_REQUEST to network hosts -//! -//! @note If an operation finished successfully asynchronous ping report -//! event will be generated. The report structure is as defined -//! by structure netapp_pingreport_args_t. -//! -//! @warning Calling this function while a previous Ping Requests are in -//! progress will stop the previous ping request. -//***************************************************************************** - - #ifndef CC3000_TINY_DRIVER -extern INT32 netapp_ping_send(UINT32 *ip, UINT32 ulPingAttempts, UINT32 ulPingSize, UINT32 ulPingTimeout); -#endif - -//***************************************************************************** -// -//! netapp_ping_stop -//! -//! @param none -//! -//! @return On success, zero is returned. On error, -1 is returned. -//! -//! @brief Stop any ping request. -//! -//! -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -extern INT32 netapp_ping_stop(); -#endif -//***************************************************************************** -// -//! netapp_ping_report -//! -//! @param none -//! -//! @return none -//! -//! @brief Request for ping status. This API triggers the CC3000 to send -//! asynchronous events: HCI_EVNT_WLAN_ASYNC_PING_REPORT. -//! This event will carry the report structure: -//! netapp_pingreport_args_t. This structure is filled in with ping -//! results up till point of triggering API. -//! netapp_pingreport_args_t:\n packets_sent - echo sent, -//! packets_received - echo reply, min_round_time - minimum -//! round time, max_round_time - max round time, -//! avg_round_time - average round time -//! -//! @note When a ping operation is not active, the returned structure -//! fields are 0. -//! -//***************************************************************************** -#ifndef CC3000_TINY_DRIVER -extern void netapp_ping_report(); -#endif - - -//***************************************************************************** -// -//! netapp_ipconfig -//! -//! @param[out] ipconfig This argument is a pointer to a -//! tNetappIpconfigRetArgs structure. This structure is -//! filled in with the network interface configuration. -//! tNetappIpconfigRetArgs:\n aucIP - ip address, -//! aucSubnetMask - mask, aucDefaultGateway - default -//! gateway address, aucDHCPServer - dhcp server address -//! aucDNSServer - dns server address, uaMacAddr - mac -//! address, uaSSID - connected AP ssid -//! -//! @return none -//! -//! @brief Obtain the CC3000 Network interface information. -//! Note that the information is available only after the WLAN -//! connection was established. Calling this function before -//! associated, will cause non-defined values to be returned. -//! -//! @note The function is useful for figuring out the IP Configuration of -//! the device when DHCP is used and for figuring out the SSID of -//! the Wireless network the device is associated with. -//! -//***************************************************************************** - -extern void netapp_ipconfig( tNetappIpconfigRetArgs * ipconfig ); - - -//***************************************************************************** -// -//! netapp_arp_flush -//! -//! @param none -//! -//! @return none -//! -//! @brief Flushes ARP table -//! -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -extern INT32 netapp_arp_flush(); -#endif - - -//***************************************************************************** -// -//! netapp_set_debug_level -//! -//! @param[in] level debug level. Bitwise [0-8], -//! 0(disable)or 1(enable).\n Bitwise map: 0 - Critical -//! message, 1 information message, 2 - core messages, 3 - -//! HCI messages, 4 - Network stack messages, 5 - wlan -//! messages, 6 - wlan driver messages, 7 - epprom messages, -//! 8 - general messages. Default: 0x13f. Saved: no -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Debug messages sent via the UART debug channel, this function -//! enable/disable the debug level -//! -//***************************************************************************** - - -#ifndef CC3000_TINY_DRIVER -INT32 netapp_set_debug_level(UINT32 ulLevel); -#endif -//***************************************************************************** -// -// Close the Doxygen group. -//! @} -// -//***************************************************************************** - - - -//***************************************************************************** -// -// Mark the end of the C bindings section for C++ compilers. -// -//***************************************************************************** -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif // __CC3000_NETAPP_H__ - diff --git a/drivers/cc3000/inc/nvmem.h b/drivers/cc3000/inc/nvmem.h deleted file mode 100644 index b99a2e7b9e..0000000000 --- a/drivers/cc3000/inc/nvmem.h +++ /dev/null @@ -1,248 +0,0 @@ -/***************************************************************************** -* -* nvmem.h - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ -#ifndef __CC3000_NVRAM_H__ -#define __CC3000_NVRAM_H__ - -#include "cc3000_common.h" - - -//***************************************************************************** -// -// If building with a C++ compiler, make all of the definitions in this header -// have a C binding. -// -//***************************************************************************** -#ifdef __cplusplus -extern "C" { -#endif - - -//***************************************************************************** -// -//! \addtogroup nvmem_api -//! @{ -// -//***************************************************************************** - -/**************************************************************************** -** -** Definitions for File IDs -** -****************************************************************************/ -/* NVMEM file ID - system files*/ -#define NVMEM_NVS_FILEID (0) -#define NVMEM_NVS_SHADOW_FILEID (1) -#define NVMEM_WLAN_CONFIG_FILEID (2) -#define NVMEM_WLAN_CONFIG_SHADOW_FILEID (3) -#define NVMEM_WLAN_DRIVER_SP_FILEID (4) -#define NVMEM_WLAN_FW_SP_FILEID (5) -#define NVMEM_MAC_FILEID (6) -#define NVMEM_FRONTEND_VARS_FILEID (7) -#define NVMEM_IP_CONFIG_FILEID (8) -#define NVMEM_IP_CONFIG_SHADOW_FILEID (9) -#define NVMEM_BOOTLOADER_SP_FILEID (10) -#define NVMEM_RM_FILEID (11) - -/* NVMEM file ID - user files*/ -#define NVMEM_AES128_KEY_FILEID (12) -#define NVMEM_SHARED_MEM_FILEID (13) - -/* max entry in order to invalid nvmem */ -#define NVMEM_MAX_ENTRY (16) - - -//***************************************************************************** -// -//! nvmem_read -//! -//! @param ulFileId nvmem file id:\n -//! NVMEM_NVS_FILEID, NVMEM_NVS_SHADOW_FILEID, -//! NVMEM_WLAN_CONFIG_FILEID, NVMEM_WLAN_CONFIG_SHADOW_FILEID, -//! NVMEM_WLAN_DRIVER_SP_FILEID, NVMEM_WLAN_FW_SP_FILEID, -//! NVMEM_MAC_FILEID, NVMEM_FRONTEND_VARS_FILEID, -//! NVMEM_IP_CONFIG_FILEID, NVMEM_IP_CONFIG_SHADOW_FILEID, -//! NVMEM_BOOTLOADER_SP_FILEID, NVMEM_RM_FILEID, -//! and user files 12-15. -//! @param ulLength number of bytes to read -//! @param ulOffset ulOffset in file from where to read -//! @param buff output buffer pointer -//! -//! @return on success 0, error otherwise. -//! -//! @brief Reads data from the file referred by the ulFileId parameter. -//! Reads data from file ulOffset till length. Err if the file can't -//! be used, is invalid, or if the read is out of bounds. -//! -//***************************************************************************** - -extern INT32 nvmem_read(UINT32 file_id, UINT32 length, UINT32 offset, UINT8 *buff); - -//***************************************************************************** -// -//! nvmem_write -//! -//! @param ulFileId nvmem file id:\n -//! NVMEM_WLAN_DRIVER_SP_FILEID, NVMEM_WLAN_FW_SP_FILEID, -//! NVMEM_MAC_FILEID, NVMEM_BOOTLOADER_SP_FILEID, -//! and user files 12-15. -//! @param ulLength number of bytes to write -//! @param ulEntryOffset offset in file to start write operation from -//! @param buff data to write -//! -//! @return on success 0, error otherwise. -//! -//! @brief Write data to nvmem. -//! writes data to file referred by the ulFileId parameter. -//! Writes data to file ulOffset till ulLength.The file id will be -//! marked invalid till the write is done. The file entry doesn't -//! need to be valid - only allocated. -//! -//***************************************************************************** - -extern INT32 nvmem_write(UINT32 ulFileId, UINT32 ulLength, UINT32 ulEntryOffset, UINT8 *buff); - - -//***************************************************************************** -// -//! nvmem_set_mac_address -//! -//! @param mac mac address to be set -//! -//! @return on success 0, error otherwise. -//! -//! @brief Write MAC address to EEPROM. -//! mac address as appears over the air (OUI first) -//! -//***************************************************************************** -extern UINT8 nvmem_set_mac_address(UINT8 *mac); - - -//***************************************************************************** -// -//! nvmem_get_mac_address -//! -//! @param[out] mac mac address -//! -//! @return on success 0, error otherwise. -//! -//! @brief Read MAC address from EEPROM. -//! mac address as appears over the air (OUI first) -//! -//***************************************************************************** -extern UINT8 nvmem_get_mac_address(UINT8 *mac); - - -//***************************************************************************** -// -//! nvmem_write_patch -//! -//! @param ulFileId nvmem file id:\n -//! NVMEM_WLAN_DRIVER_SP_FILEID, NVMEM_WLAN_FW_SP_FILEID, -//! @param spLength number of bytes to write -//! @param spData SP data to write -//! -//! @return on success 0, error otherwise. -//! -//! @brief program a patch to a specific file ID. -//! The SP data is assumed to be organized in 2-dimensional. -//! Each line is SP_PORTION_SIZE bytes long. Actual programming is -//! applied in SP_PORTION_SIZE bytes portions. -//! -//***************************************************************************** -extern UINT8 nvmem_write_patch(UINT32 ulFileId, UINT32 spLength, const UINT8 *spData); - - -//***************************************************************************** -// -//! nvmem_read_sp_version -//! -//! @param[out] patchVer first number indicates package ID and the second -//! number indicates package build number -//! -//! @return on success 0, error otherwise. -//! -//! @brief Read patch version. read package version (WiFi FW patch, -//! driver-supplicant-NS patch, bootloader patch) -//! -//***************************************************************************** -#ifndef CC3000_TINY_DRIVER -extern UINT8 nvmem_read_sp_version(UINT8* patchVer); -#endif - -//***************************************************************************** -// -//! nvmem_create_entry -//! -//! @param ulFileId nvmem file Id:\n -//! * NVMEM_AES128_KEY_FILEID: 12 -//! * NVMEM_SHARED_MEM_FILEID: 13 -//! * and fileIDs 14 and 15 -//! @param ulNewLen entry ulLength -//! -//! @return on success 0, error otherwise. -//! -//! @brief Create new file entry and allocate space on the NVMEM. -//! Applies only to user files. -//! Modify the size of file. -//! If the entry is unallocated - allocate it to size -//! ulNewLen (marked invalid). -//! If it is allocated then deallocate it first. -//! To just mark the file as invalid without resizing - -//! set ulNewLen=0. -//! -//***************************************************************************** -extern INT32 nvmem_create_entry(UINT32 file_id, UINT32 newlen); - - -//***************************************************************************** -// -// Mark the end of the C bindings section for C++ compilers. -// -//***************************************************************************** - - -//***************************************************************************** -// -// Close the Doxygen group. -//! @} -// -//***************************************************************************** - - -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif // __CC3000_NVRAM_H__ diff --git a/drivers/cc3000/inc/patch_prog.h b/drivers/cc3000/inc/patch_prog.h deleted file mode 100644 index 0a141a0cb5..0000000000 --- a/drivers/cc3000/inc/patch_prog.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef __CC3000_PATCH_PROG_H__ -#define __CC3000_PATCH_PROG_H__ -extern unsigned short fw_length; -extern const unsigned char fw_patch[]; - -extern unsigned short drv_length; -extern const unsigned char wlan_drv_patch[]; -extern const unsigned char cRMdefaultParams[128]; - -void patch_prog_start(); -#endif //__CC3000_PATCH_PROG_H__ diff --git a/drivers/cc3000/inc/security.h b/drivers/cc3000/inc/security.h deleted file mode 100644 index cd1baf5541..0000000000 --- a/drivers/cc3000/inc/security.h +++ /dev/null @@ -1,130 +0,0 @@ -/***************************************************************************** -* -* security.h - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ -#ifndef __CC3000_SECURITY__ -#define __CC3000_SECURITY__ - -#include "nvmem.h" - -//***************************************************************************** -// -// If building with a C++ compiler, make all of the definitions in this header -// have a C binding. -// -//***************************************************************************** -#ifdef __cplusplus -extern "C" { -#endif - - -#define AES128_KEY_SIZE 16 - -#ifndef CC3000_UNENCRYPTED_SMART_CONFIG - - -//***************************************************************************** -// -//! aes_encrypt -//! -//! @param[in] key AES128 key of size 16 bytes -//! @param[in\out] state 16 bytes of plain text and cipher text -//! -//! @return none -//! -//! @brief AES128 encryption: -//! Given AES128 key and 16 bytes plain text, cipher text of 16 bytes -//! is computed. The AES implementation is in mode ECB (Electronic -//! Code Book). -//! -//! -//***************************************************************************** -extern void aes_encrypt(UINT8 *state, UINT8 *key); - -//***************************************************************************** -// -//! aes_decrypt -//! -//! @param[in] key AES128 key of size 16 bytes -//! @param[in\out] state 16 bytes of cipher text and plain text -//! -//! @return none -//! -//! @brief AES128 decryption: -//! Given AES128 key and 16 bytes cipher text, plain text of 16 bytes -//! is computed The AES implementation is in mode ECB -//! (Electronic Code Book). -//! -//! -//***************************************************************************** -extern void aes_decrypt(UINT8 *state, UINT8 *key); - - -//***************************************************************************** -// -//! aes_read_key -//! -//! @param[out] key AES128 key of size 16 bytes -//! -//! @return on success 0, error otherwise. -//! -//! @brief Reads AES128 key from EEPROM -//! Reads the AES128 key from fileID #12 in EEPROM -//! returns an error if the key does not exist. -//! -//! -//***************************************************************************** -extern INT32 aes_read_key(UINT8 *key); - -//***************************************************************************** -// -//! aes_write_key -//! -//! @param[out] key AES128 key of size 16 bytes -//! -//! @return on success 0, error otherwise. -//! -//! @brief writes AES128 key from EEPROM -//! Writes the AES128 key to fileID #12 in EEPROM -//! -//! -//***************************************************************************** -extern INT32 aes_write_key(UINT8 *key); - -#endif //CC3000_UNENCRYPTED_SMART_CONFIG - -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif diff --git a/drivers/cc3000/inc/socket.h b/drivers/cc3000/inc/socket.h deleted file mode 100644 index 96c814bf77..0000000000 --- a/drivers/cc3000/inc/socket.h +++ /dev/null @@ -1,676 +0,0 @@ -/***************************************************************************** -* -* socket.h - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ -#ifndef __CC3000_SOCKET_H__ -#define __CC3000_SOCKET_H__ - -#include "cc3000_common.h" - -//***************************************************************************** -// -//! \addtogroup socket_api -//! @{ -// -//***************************************************************************** - - -//***************************************************************************** -// -// If building with a C++ compiler, make all of the definitions in this header -// have a C binding. -// -//***************************************************************************** -#ifdef __cplusplus -extern "C" { -#endif - -#define HOSTNAME_MAX_LENGTH (230) // 230 bytes + header shouldn't exceed 8 bit value - -//--------- Address Families -------- - -#define AF_INET 2 -#define AF_INET6 23 - -//------------ Socket Types ------------ - -#define SOCK_STREAM 1 -#define SOCK_DGRAM 2 -#define SOCK_RAW 3 // Raw sockets allow new IPv4 protocols to be implemented in user space. A raw socket receives or sends the raw datagram not including link level headers -#define SOCK_RDM 4 -#define SOCK_SEQPACKET 5 - -//----------- Socket Protocol ---------- - -#define IPPROTO_IP 0 // dummy for IP -#define IPPROTO_ICMP 1 // control message protocol -#define IPPROTO_IPV4 IPPROTO_IP // IP inside IP -#define IPPROTO_TCP 6 // tcp -#define IPPROTO_UDP 17 // user datagram protocol -#define IPPROTO_IPV6 41 // IPv6 in IPv6 -#define IPPROTO_NONE 59 // No next header -#define IPPROTO_RAW 255 // raw IP packet -#define IPPROTO_MAX 256 - -//----------- Socket retunr codes ----------- - -#define SOC_ERROR (-1) // error -#define SOC_IN_PROGRESS (-2) // socket in progress - -//----------- Socket Options ----------- -#define SOL_SOCKET 0xffff // socket level -#define SOCKOPT_RECV_NONBLOCK 0 // recv non block mode, set SOCK_ON or SOCK_OFF (default block mode) -#define SOCKOPT_RECV_TIMEOUT 1 // optname to configure recv and recvfromtimeout -#define SOCKOPT_ACCEPT_NONBLOCK 2 // accept non block mode, set SOCK_ON or SOCK_OFF (default block mode) -#define SOCK_ON 0 // socket non-blocking mode is enabled -#define SOCK_OFF 1 // socket blocking mode is enabled - -#define MAX_PACKET_SIZE 1500 -#define MAX_LISTEN_QUEUE 4 - -#define IOCTL_SOCKET_EVENTMASK - -#define ENOBUFS 55 // No buffer space available - -#define __FD_SETSIZE 32 - -#define ASIC_ADDR_LEN 8 - -#define NO_QUERY_RECIVED -3 - - -typedef struct _in_addr_t -{ - UINT32 s_addr; // load with inet_aton() -} in_addr; - -typedef struct _sockaddr_t -{ - UINT16 sa_family; - UINT8 sa_data[14]; -} sockaddr; - -typedef struct _sockaddr_in_t -{ - INT16 sin_family; // e.g. AF_INET - UINT16 sin_port; // e.g. htons(3490) - in_addr sin_addr; // see struct in_addr, below - CHAR sin_zero[8]; // zero this if you want to -} sockaddr_in; - -typedef UINT32 socklen_t; - -// The fd_set member is required to be an array of INT32s. -typedef INT32 __fd_mask; - -// It's easier to assume 8-bit bytes than to get CHAR_BIT. -#define __NFDBITS (8 * sizeof (__fd_mask)) -#define __FDELT(d) ((d) / __NFDBITS) -#define __FDMASK(d) ((__fd_mask) 1 << ((d) % __NFDBITS)) - -// fd_set for select and pselect. -typedef struct -{ - __fd_mask fds_bits[__FD_SETSIZE / __NFDBITS]; -#define __FDS_BITS(set) ((set)->fds_bits) -} fd_set; - -// We don't use `memset' because this would require a prototype and -// the array isn't too big. -#define __FD_ZERO(set) \ - do { \ - UINT16 __i; \ - fd_set *__arr = (set); \ - for (__i = 0; __i < sizeof (fd_set) / sizeof (__fd_mask); ++__i) \ - __FDS_BITS (__arr)[__i] = 0; \ - } while (0) -#define __FD_SET(d, set) (__FDS_BITS (set)[__FDELT (d)] |= __FDMASK (d)) -#define __FD_CLR(d, set) (__FDS_BITS (set)[__FDELT (d)] &= ~__FDMASK (d)) -#define __FD_ISSET(d, set) (__FDS_BITS (set)[__FDELT (d)] & __FDMASK (d)) - -// Access macros for 'fd_set'. -#define FD_SET(fd, fdsetp) __FD_SET (fd, fdsetp) -#define FD_CLR(fd, fdsetp) __FD_CLR (fd, fdsetp) -#define FD_ISSET(fd, fdsetp) __FD_ISSET (fd, fdsetp) -#define FD_ZERO(fdsetp) __FD_ZERO (fdsetp) - -//Use in case of Big Endian only - -#define htonl(A) ((((UINT32)(A) & 0xff000000) >> 24) | \ - (((UINT32)(A) & 0x00ff0000) >> 8) | \ - (((UINT32)(A) & 0x0000ff00) << 8) | \ - (((UINT32)(A) & 0x000000ff) << 24)) - -#define ntohl htonl - -//Use in case of Big Endian only -#define htons(A) ((((UINT32)(A) & 0xff00) >> 8) | \ - (((UINT32)(A) & 0x00ff) << 8)) - - -#define ntohs htons - -// mDNS port - 5353 mDNS multicast address - 224.0.0.251 -#define SET_mDNS_ADD(sockaddr) sockaddr.sa_data[0] = 0x14; \ - sockaddr.sa_data[1] = 0xe9; \ - sockaddr.sa_data[2] = 0xe0; \ - sockaddr.sa_data[3] = 0x0; \ - sockaddr.sa_data[4] = 0x0; \ - sockaddr.sa_data[5] = 0xfb; - - -//***************************************************************************** -// -// Prototypes for the APIs. -// -//***************************************************************************** - -//***************************************************************************** -// -//! socket -//! -//! @param domain selects the protocol family which will be used for -//! communication. On this version only AF_INET is supported -//! @param type specifies the communication semantics. On this version -//! only SOCK_STREAM, SOCK_DGRAM, SOCK_RAW are supported -//! @param protocol specifies a particular protocol to be used with the -//! socket IPPROTO_TCP, IPPROTO_UDP or IPPROTO_RAW are -//! supported. -//! -//! @return On success, socket handle that is used for consequent socket -//! operations. On error, -1 is returned. -//! -//! @brief create an endpoint for communication -//! The socket function creates a socket that is bound to a specific -//! transport service provider. This function is called by the -//! application layer to obtain a socket handle. -// -//***************************************************************************** -extern INT16 CC3000_EXPORT(socket)(INT32 domain, INT32 type, INT32 protocol); - -//***************************************************************************** -// -//! closesocket -//! -//! @param sd socket handle. -//! -//! @return On success, zero is returned. On error, -1 is returned. -//! -//! @brief The socket function closes a created socket. -// -//***************************************************************************** -extern INT32 CC3000_EXPORT(closesocket)(INT32 sd); - -//***************************************************************************** -// -//! accept -//! -//! @param[in] sd socket descriptor (handle) -//! @param[out] addr the argument addr is a pointer to a sockaddr structure -//! This structure is filled in with the address of the -//! peer socket, as known to the communications layer. -//! determined. The exact format of the address returned -//! addr is by the socket's address sockaddr. -//! On this version only AF_INET is supported. -//! This argument returns in network order. -//! @param[out] addrlen the addrlen argument is a value-result argument: -//! it should initially contain the size of the structure -//! pointed to by addr. -//! -//! @return For socket in blocking mode: -//! On success, socket handle. on failure negative -//! For socket in non-blocking mode: -//! - On connection establishment, socket handle -//! - On connection pending, SOC_IN_PROGRESS (-2) -//! - On failure, SOC_ERROR (-1) -//! -//! @brief accept a connection on a socket: -//! This function is used with connection-based socket types -//! (SOCK_STREAM). It extracts the first connection request on the -//! queue of pending connections, creates a new connected socket, and -//! returns a new file descriptor referring to that socket. -//! The newly created socket is not in the listening state. -//! The original socket sd is unaffected by this call. -//! The argument sd is a socket that has been created with socket(), -//! bound to a local address with bind(), and is listening for -//! connections after a listen(). The argument addr is a pointer -//! to a sockaddr structure. This structure is filled in with the -//! address of the peer socket, as known to the communications layer. -//! The exact format of the address returned addr is determined by the -//! socket's address family. The addrlen argument is a value-result -//! argument: it should initially contain the size of the structure -//! pointed to by addr, on return it will contain the actual -//! length (in bytes) of the address returned. -//! -//! @sa socket ; bind ; listen -// -//***************************************************************************** -extern INT32 CC3000_EXPORT(accept)(INT32 sd, sockaddr *addr, socklen_t *addrlen); - -//***************************************************************************** -// -//! bind -//! -//! @param[in] sd socket descriptor (handle) -//! @param[out] addr specifies the destination address. On this version -//! only AF_INET is supported. -//! @param[out] addrlen contains the size of the structure pointed to by addr. -//! -//! @return On success, zero is returned. On error, -1 is returned. -//! -//! @brief assign a name to a socket -//! This function gives the socket the local address addr. -//! addr is addrlen bytes long. Traditionally, this is called when a -//! socket is created with socket, it exists in a name space (address -//! family) but has no name assigned. -//! It is necessary to assign a local address before a SOCK_STREAM -//! socket may receive connections. -//! -//! @sa socket ; accept ; listen -// -//***************************************************************************** -extern INT32 CC3000_EXPORT(bind)(INT32 sd, const sockaddr *addr, INT32 addrlen); - -//***************************************************************************** -// -//! listen -//! -//! @param[in] sd socket descriptor (handle) -//! @param[in] backlog specifies the listen queue depth. On this version -//! backlog is not supported. -//! @return On success, zero is returned. On error, -1 is returned. -//! -//! @brief listen for connections on a socket -//! The willingness to accept incoming connections and a queue -//! limit for incoming connections are specified with listen(), -//! and then the connections are accepted with accept. -//! The listen() call applies only to sockets of type SOCK_STREAM -//! The backlog parameter defines the maximum length the queue of -//! pending connections may grow to. -//! -//! @sa socket ; accept ; bind -//! -//! @note On this version, backlog is not supported -// -//***************************************************************************** -extern INT32 CC3000_EXPORT(listen)(INT32 sd, INT32 backlog); - -//***************************************************************************** -// -//! gethostbyname -//! -//! @param[in] hostname host name -//! @param[in] usNameLen name length -//! @param[out] out_ip_addr This parameter is filled in with host IP address. -//! In case that host name is not resolved, -//! out_ip_addr is zero. -//! @return On success, positive is returned. On error, negative is returned -//! -//! @brief Get host IP by name. Obtain the IP Address of machine on network, -//! by its name. -//! -//! @note On this version, only blocking mode is supported. Also note that -//! the function requires DNS server to be configured prior to its usage. -// -//***************************************************************************** -#ifndef CC3000_TINY_DRIVER -extern INT16 CC3000_EXPORT(gethostbyname)(CHAR * hostname, UINT16 usNameLen, UINT32* out_ip_addr); -#endif - - -//***************************************************************************** -// -//! connect -//! -//! @param[in] sd socket descriptor (handle) -//! @param[in] addr specifies the destination addr. On this version -//! only AF_INET is supported. -//! @param[out] addrlen contains the size of the structure pointed to by addr -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief initiate a connection on a socket -//! Function connects the socket referred to by the socket descriptor -//! sd, to the address specified by addr. The addrlen argument -//! specifies the size of addr. The format of the address in addr is -//! determined by the address space of the socket. If it is of type -//! SOCK_DGRAM, this call specifies the peer with which the socket is -//! to be associated; this address is that to which datagrams are to be -//! sent, and the only address from which datagrams are to be received. -//! If the socket is of type SOCK_STREAM, this call attempts to make a -//! connection to another socket. The other socket is specified by -//! address, which is an address in the communications space of the -//! socket. Note that the function implements only blocking behavior -//! thus the caller will be waiting either for the connection -//! establishment or for the connection establishment failure. -//! -//! @sa socket -// -//***************************************************************************** -extern INT32 CC3000_EXPORT(connect)(INT32 sd, const sockaddr *addr, INT32 addrlen); - -//***************************************************************************** -// -//! select -//! -//! @param[in] nfds the highest-numbered file descriptor in any of the -//! three sets, plus 1. -//! @param[out] writesds socket descriptors list for write monitoring -//! @param[out] readsds socket descriptors list for read monitoring -//! @param[out] exceptsds socket descriptors list for exception monitoring -//! @param[in] timeout is an upper bound on the amount of time elapsed -//! before select() returns. Null means infinity -//! timeout. The minimum timeout is 5 milliseconds, -//! less than 5 milliseconds will be set -//! automatically to 5 milliseconds. -//! @return On success, select() returns the number of file descriptors -//! contained in the three returned descriptor sets (that is, the -//! total number of bits that are set in readfds, writefds, -//! exceptfds) which may be zero if the timeout expires before -//! anything interesting happens. -//! On error, -1 is returned. -//! *readsds - return the sockets on which Read request will -//! return without delay with valid data. -//! *writesds - return the sockets on which Write request -//! will return without delay. -//! *exceptsds - return the sockets which closed recently. -//! -//! @brief Monitor socket activity -//! Select allow a program to monitor multiple file descriptors, -//! waiting until one or more of the file descriptors become -//! "ready" for some class of I/O operation -//! -//! @Note If the timeout value set to less than 5ms it will automatically set -//! to 5ms to prevent overload of the system -//! -//! @sa socket -// -//***************************************************************************** -extern INT16 CC3000_EXPORT(select)(INT32 nfds, fd_set *readsds, fd_set *writesds, - fd_set *exceptsds, struct cc3000_timeval *timeout); - -//***************************************************************************** -// -//! setsockopt -//! -//! @param[in] sd socket handle -//! @param[in] level defines the protocol level for this option -//! @param[in] optname defines the option name to Interrogate -//! @param[in] optval specifies a value for the option -//! @param[in] optlen specifies the length of the option value -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief set socket options -//! This function manipulate the options associated with a socket. -//! Options may exist at multiple protocol levels; they are always -//! present at the uppermost socket level. -//! When manipulating socket options the level at which the option -//! resides and the name of the option must be specified. -//! To manipulate options at the socket level, level is specified as -//! SOL_SOCKET. To manipulate options at any other level the protocol -//! number of the appropriate protocol controlling the option is -//! supplied. For example, to indicate that an option is to be -//! interpreted by the TCP protocol, level should be set to the -//! protocol number of TCP; -//! The parameters optval and optlen are used to access optval - -//! use for setsockopt(). For getsockopt() they identify a buffer -//! in which the value for the requested option(s) are to -//! be returned. For getsockopt(), optlen is a value-result -//! parameter, initially containing the size of the buffer -//! pointed to by option_value, and modified on return to -//! indicate the actual size of the value returned. If no option -//! value is to be supplied or returned, option_value may be NULL. -//! -//! @Note On this version the following two socket options are enabled: -//! The only protocol level supported in this version -//! is SOL_SOCKET (level). -//! 1. SOCKOPT_RECV_TIMEOUT (optname) -//! SOCKOPT_RECV_TIMEOUT configures recv and recvfrom timeout -//! in milliseconds. -//! In that case optval should be pointer to UINT32. -//! 2. SOCKOPT_NONBLOCK (optname). sets the socket non-blocking mode on -//! or off. -//! In that case optval should be SOCK_ON or SOCK_OFF (optval). -//! -//! @sa getsockopt -// -//***************************************************************************** -#ifndef CC3000_TINY_DRIVER -extern INT16 CC3000_EXPORT(setsockopt)(INT32 sd, INT32 level, INT32 optname, const void *optval, - socklen_t optlen); -#endif -//***************************************************************************** -// -//! getsockopt -//! -//! @param[in] sd socket handle -//! @param[in] level defines the protocol level for this option -//! @param[in] optname defines the option name to Interrogate -//! @param[out] optval specifies a value for the option -//! @param[out] optlen specifies the length of the option value -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief set socket options -//! This function manipulate the options associated with a socket. -//! Options may exist at multiple protocol levels; they are always -//! present at the uppermost socket level. -//! When manipulating socket options the level at which the option -//! resides and the name of the option must be specified. -//! To manipulate options at the socket level, level is specified as -//! SOL_SOCKET. To manipulate options at any other level the protocol -//! number of the appropriate protocol controlling the option is -//! supplied. For example, to indicate that an option is to be -//! interpreted by the TCP protocol, level should be set to the -//! protocol number of TCP; -//! The parameters optval and optlen are used to access optval - -//! use for setsockopt(). For getsockopt() they identify a buffer -//! in which the value for the requested option(s) are to -//! be returned. For getsockopt(), optlen is a value-result -//! parameter, initially containing the size of the buffer -//! pointed to by option_value, and modified on return to -//! indicate the actual size of the value returned. If no option -//! value is to be supplied or returned, option_value may be NULL. -//! -//! @Note On this version the following two socket options are enabled: -//! The only protocol level supported in this version -//! is SOL_SOCKET (level). -//! 1. SOCKOPT_RECV_TIMEOUT (optname) -//! SOCKOPT_RECV_TIMEOUT configures recv and recvfrom timeout -//! in milliseconds. -//! In that case optval should be pointer to UINT32. -//! 2. SOCKOPT_NONBLOCK (optname). sets the socket non-blocking mode on -//! or off. -//! In that case optval should be SOCK_ON or SOCK_OFF (optval). -//! -//! @sa setsockopt -// -//***************************************************************************** -extern INT16 CC3000_EXPORT(getsockopt)(INT32 sd, INT32 level, INT32 optname, void *optval, - socklen_t *optlen); - -//***************************************************************************** -// -//! recv -//! -//! @param[in] sd socket handle -//! @param[out] buf Points to the buffer where the message should be stored -//! @param[in] len Specifies the length in bytes of the buffer pointed to -//! by the buffer argument. -//! @param[in] flags Specifies the type of message reception. -//! On this version, this parameter is not supported. -//! -//! @return Return the number of bytes received, or -1 if an error -//! occurred -//! -//! @brief function receives a message from a connection-mode socket -//! -//! @sa recvfrom -//! -//! @Note On this version, only blocking mode is supported. -// -//***************************************************************************** -extern INT16 CC3000_EXPORT(recv)(INT32 sd, void *buf, INT32 len, INT32 flags); - -//***************************************************************************** -// -//! recvfrom -//! -//! @param[in] sd socket handle -//! @param[out] buf Points to the buffer where the message should be stored -//! @param[in] len Specifies the length in bytes of the buffer pointed to -//! by the buffer argument. -//! @param[in] flags Specifies the type of message reception. -//! On this version, this parameter is not supported. -//! @param[in] from pointer to an address structure indicating the source -//! address: sockaddr. On this version only AF_INET is -//! supported. -//! @param[in] fromlen source address structure size -//! -//! @return Return the number of bytes received, or -1 if an error -//! occurred -//! -//! @brief read data from socket -//! function receives a message from a connection-mode or -//! connectionless-mode socket. Note that raw sockets are not -//! supported. -//! -//! @sa recv -//! -//! @Note On this version, only blocking mode is supported. -// -//***************************************************************************** -extern INT16 CC3000_EXPORT(recvfrom)(INT32 sd, void *buf, INT32 len, INT32 flags, sockaddr *from, - socklen_t *fromlen); - -//***************************************************************************** -// -//! send -//! -//! @param sd socket handle -//! @param buf Points to a buffer containing the message to be sent -//! @param len message size in bytes -//! @param flags On this version, this parameter is not supported -//! -//! @return Return the number of bytes transmitted, or -1 if an -//! error occurred -//! -//! @brief Write data to TCP socket -//! This function is used to transmit a message to another -//! socket. -//! -//! @Note On this version, only blocking mode is supported. -//! -//! @sa sendto -// -//***************************************************************************** - -extern INT16 CC3000_EXPORT(send)(INT32 sd, const void *buf, INT32 len, INT32 flags); - -//***************************************************************************** -// -//! sendto -//! -//! @param sd socket handle -//! @param buf Points to a buffer containing the message to be sent -//! @param len message size in bytes -//! @param flags On this version, this parameter is not supported -//! @param to pointer to an address structure indicating the destination -//! address: sockaddr. On this version only AF_INET is -//! supported. -//! @param tolen destination address structure size -//! -//! @return Return the number of bytes transmitted, or -1 if an -//! error occurred -//! -//! @brief Write data to TCP socket -//! This function is used to transmit a message to another -//! socket. -//! -//! @Note On this version, only blocking mode is supported. -//! -//! @sa send -// -//***************************************************************************** - -extern INT16 CC3000_EXPORT(sendto)(INT32 sd, const void *buf, INT32 len, INT32 flags, - const sockaddr *to, socklen_t tolen); - -//***************************************************************************** -// -//! mdnsAdvertiser -//! -//! @param[in] mdnsEnabled flag to enable/disable the mDNS feature -//! @param[in] deviceServiceName Service name as part of the published -//! canonical domain name -//! @param[in] deviceServiceNameLength Length of the service name - up to 32 chars -//! -//! -//! @return On success, zero is returned, return SOC_ERROR if socket was not -//! opened successfully, or if an error occurred. -//! -//! @brief Set CC3000 in mDNS advertiser mode in order to advertise itself. -// -//***************************************************************************** -extern INT16 CC3000_EXPORT(mdnsAdvertiser)(UINT16 mdnsEnabled, CHAR * deviceServiceName, UINT16 deviceServiceNameLength); - - -//***************************************************************************** -// -//! getmssvalue -//! -//! @param[in] sd socket descriptor -//! -//! @return On success, returns the MSS value of a TCP connection -//! -//! @brief Returns the MSS value of a TCP connection according to the socket descriptor -// -//***************************************************************************** -extern UINT16 CC3000_EXPORT(getmssvalue) (INT32 sd); - -//***************************************************************************** -// -// Close the Doxygen group. -//! @} -// -//***************************************************************************** - - -//***************************************************************************** -// -// Mark the end of the C bindings section for C++ compilers. -// -//***************************************************************************** -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif // __SOCKET_H__ diff --git a/drivers/cc3000/inc/wlan.h b/drivers/cc3000/inc/wlan.h deleted file mode 100644 index 48d195b32a..0000000000 --- a/drivers/cc3000/inc/wlan.h +++ /dev/null @@ -1,518 +0,0 @@ -/***************************************************************************** -* -* wlan.h - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ -#ifndef __CC3000_WLAN_H__ -#define __CC3000_WLAN_H__ - -#include "cc3000_common.h" - -//***************************************************************************** -// -// If building with a C++ compiler, make all of the definitions in this header -// have a C binding. -// -//***************************************************************************** -#ifdef __cplusplus -extern "C" { -#endif - -#define WLAN_SEC_UNSEC (0) -#define WLAN_SEC_WEP (1) -#define WLAN_SEC_WPA (2) -#define WLAN_SEC_WPA2 (3) -//***************************************************************************** -// -//! \addtogroup wlan_api -//! @{ -// -//***************************************************************************** - - -//***************************************************************************** -// -//! wlan_init -//! -//! @param sWlanCB Asynchronous events callback. -//! 0 no event call back. -//! -call back parameters: -//! 1) event_type: HCI_EVNT_WLAN_UNSOL_CONNECT connect event, -//! HCI_EVNT_WLAN_UNSOL_DISCONNECT disconnect event, -//! HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE config done, -//! HCI_EVNT_WLAN_UNSOL_DHCP dhcp report, -//! HCI_EVNT_WLAN_ASYNC_PING_REPORT ping report OR -//! HCI_EVNT_WLAN_KEEPALIVE keepalive. -//! 2) data: pointer to extra data that received by the event -//! (NULL no data). -//! 3) length: data length. -//! -Events with extra data: -//! HCI_EVNT_WLAN_UNSOL_DHCP: 4 bytes IP, 4 bytes Mask, -//! 4 bytes default gateway, 4 bytes DHCP server and 4 bytes -//! for DNS server. -//! HCI_EVNT_WLAN_ASYNC_PING_REPORT: 4 bytes Packets sent, -//! 4 bytes Packets received, 4 bytes Min round time, -//! 4 bytes Max round time and 4 bytes for Avg round time. -//! -//! @param sFWPatches 0 no patch or pointer to FW patches -//! @param sDriverPatches 0 no patch or pointer to driver patches -//! @param sBootLoaderPatches 0 no patch or pointer to bootloader patches -//! @param sReadWlanInterruptPin init callback. the callback read wlan -//! interrupt status. -//! @param sWlanInterruptEnable init callback. the callback enable wlan -//! interrupt. -//! @param sWlanInterruptDisable init callback. the callback disable wlan -//! interrupt. -//! @param sWriteWlanPin init callback. the callback write value -//! to device pin. -//! -//! @return none -//! -//! @sa wlan_set_event_mask , wlan_start , wlan_stop -//! -//! @brief Initialize wlan driver -//! -//! @warning This function must be called before ANY other wlan driver function -// -//***************************************************************************** -extern void wlan_init( tWlanCB sWlanCB, - tFWPatches sFWPatches, - tDriverPatches sDriverPatches, - tBootLoaderPatches sBootLoaderPatches, - tWlanReadInteruptPin sReadWlanInterruptPin, - tWlanInterruptEnable sWlanInterruptEnable, - tWlanInterruptDisable sWlanInterruptDisable, - tWriteWlanPin sWriteWlanPin); - - - -//***************************************************************************** -// -//! wlan_start -//! -//! @param usPatchesAvailableAtHost - flag to indicate if patches available -//! from host or from EEPROM. Due to the -//! fact the patches are burn to the EEPROM -//! using the patch programmer utility, the -//! patches will be available from the EEPROM -//! and not from the host. -//! -//! @return none -//! -//! @brief Start WLAN device. This function asserts the enable pin of -//! the device (WLAN_EN), starting the HW initialization process. -//! The function blocked until device Initialization is completed. -//! Function also configure patches (FW, driver or bootloader) -//! and calls appropriate device callbacks. -//! -//! @Note Prior calling the function wlan_init shall be called. -//! @Warning This function must be called after wlan_init and before any -//! other wlan API -//! @sa wlan_init , wlan_stop -//! -// -//***************************************************************************** -extern int wlan_start(UINT16 usPatchesAvailableAtHost); - -//***************************************************************************** -// -//! wlan_stop -//! -//! @param none -//! -//! @return none -//! -//! @brief Stop WLAN device by putting it into reset state. -//! -//! @sa wlan_start -// -//***************************************************************************** -extern void wlan_stop(void); - -//***************************************************************************** -// -//! wlan_connect -//! -//! @param sec_type security options: -//! WLAN_SEC_UNSEC, -//! WLAN_SEC_WEP (ASCII support only), -//! WLAN_SEC_WPA or WLAN_SEC_WPA2 -//! @param ssid up to 32 bytes and is ASCII SSID of the AP -//! @param ssid_len length of the SSID -//! @param bssid 6 bytes specified the AP bssid -//! @param key up to 32 bytes specified the AP security key -//! @param key_len key length -//! -//! @return On success, zero is returned. On error, negative is returned. -//! Note that even though a zero is returned on success to trigger -//! connection operation, it does not mean that CCC3000 is already -//! connected. An asynchronous "Connected" event is generated when -//! actual association process finishes and CC3000 is connected to -//! the AP. If DHCP is set, An asynchronous "DHCP" event is -//! generated when DHCP process is finish. -//! -//! -//! @brief Connect to AP -//! @warning Please Note that when connection to AP configured with security -//! type WEP, please confirm that the key is set as ASCII and not -//! as HEX. -//! @sa wlan_disconnect -// -//***************************************************************************** -#ifndef CC3000_TINY_DRIVER -extern INT32 wlan_connect(UINT32 ulSecType, CHAR *ssid, INT32 ssid_len, - UINT8 *bssid, UINT8 *key, INT32 key_len); -#else -extern INT32 wlan_connect(CHAR *ssid, INT32 ssid_len); - -#endif - -//***************************************************************************** -// -//! wlan_disconnect -//! -//! @return 0 disconnected done, other CC3000 already disconnected -//! -//! @brief Disconnect connection from AP. -//! -//! @sa wlan_connect -// -//***************************************************************************** - -extern INT32 wlan_disconnect(void); - -//***************************************************************************** -// -//! wlan_add_profile -//! -//! @param ulSecType WLAN_SEC_UNSEC,WLAN_SEC_WEP,WLAN_SEC_WPA,WLAN_SEC_WPA2 -//! @param ucSsid ssid SSID up to 32 bytes -//! @param ulSsidLen ssid length -//! @param ucBssid bssid 6 bytes -//! @param ulPriority ulPriority profile priority. Lowest priority:0. -//! @param ulPairwiseCipher_Or_TxKeyLen key length for WEP security -//! @param ulGroupCipher_TxKeyIndex key index -//! @param ulKeyMgmt KEY management -//! @param ucPf_OrKey security key -//! @param ulPassPhraseLen security key length for WPA\WPA2 -//! -//! @return On success, index (1-7) of the stored profile is returned. -//! On error, -1 is returned. -//! -//! @brief When auto start is enabled, the device connects to -//! station from the profiles table. Up to 7 profiles are supported. -//! If several profiles configured the device choose the highest -//! priority profile, within each priority group, device will choose -//! profile based on security policy, signal strength, etc -//! parameters. All the profiles are stored in CC3000 NVMEM. -//! -//! @sa wlan_ioctl_del_profile -// -//***************************************************************************** - -extern INT32 wlan_add_profile(UINT32 ulSecType, UINT8* ucSsid, - UINT32 ulSsidLen, - UINT8 *ucBssid, - UINT32 ulPriority, - UINT32 ulPairwiseCipher_Or_Key, - UINT32 ulGroupCipher_TxKeyLen, - UINT32 ulKeyMgmt, - UINT8* ucPf_OrKey, - UINT32 ulPassPhraseLen); - - - -//***************************************************************************** -// -//! wlan_ioctl_del_profile -//! -//! @param index number of profile to delete -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Delete WLAN profile -//! -//! @Note In order to delete all stored profile, set index to 255. -//! -//! @sa wlan_add_profile -// -//***************************************************************************** -extern INT32 wlan_ioctl_del_profile(UINT32 ulIndex); - -//***************************************************************************** -// -//! wlan_set_event_mask -//! -//! @param mask mask option: -//! HCI_EVNT_WLAN_UNSOL_CONNECT connect event -//! HCI_EVNT_WLAN_UNSOL_DISCONNECT disconnect event -//! HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE smart config done -//! HCI_EVNT_WLAN_UNSOL_INIT init done -//! HCI_EVNT_WLAN_UNSOL_DHCP dhcp event report -//! HCI_EVNT_WLAN_ASYNC_PING_REPORT ping report -//! HCI_EVNT_WLAN_KEEPALIVE keepalive -//! HCI_EVNT_WLAN_TX_COMPLETE - disable information on end of transmission -//! Saved: no. -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Mask event according to bit mask. In case that event is -//! masked (1), the device will not send the masked event to host. -// -//***************************************************************************** -extern INT32 wlan_set_event_mask(UINT32 ulMask); - -//***************************************************************************** -// -//! wlan_ioctl_statusget -//! -//! @param none -//! -//! @return WLAN_STATUS_DISCONNECTED, WLAN_STATUS_SCANING, -//! STATUS_CONNECTING or WLAN_STATUS_CONNECTED -//! -//! @brief get wlan status: disconnected, scanning, connecting or connected -// -//***************************************************************************** -extern INT32 wlan_ioctl_statusget(void); - - -//***************************************************************************** -// -//! wlan_ioctl_set_connection_policy -//! -//! @param should_connect_to_open_ap enable(1), disable(0) connect to any -//! available AP. This parameter corresponds to the configuration of -//! item # 3 in the brief description. -//! @param should_use_fast_connect enable(1), disable(0). if enabled, tries -//! to connect to the last connected AP. This parameter corresponds -//! to the configuration of item # 1 in the brief description. -//! @param auto_start enable(1), disable(0) auto connect -//! after reset and periodically reconnect if needed. This -//! configuration configures option 2 in the above description. -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief When auto is enabled, the device tries to connect according -//! the following policy: -//! 1) If fast connect is enabled and last connection is valid, -//! the device will try to connect to it without the scanning -//! procedure (fast). The last connection will be marked as -//! invalid, due to adding/removing profile. -//! 2) If profile exists, the device will try to connect it -//! (Up to seven profiles). -//! 3) If fast and profiles are not found, and open mode is -//! enabled, the device will try to connect to any AP. -//! * Note that the policy settings are stored in the CC3000 NVMEM. -//! -//! @sa wlan_add_profile , wlan_ioctl_del_profile -// -//***************************************************************************** -extern INT32 wlan_ioctl_set_connection_policy( - UINT32 should_connect_to_open_ap, - UINT32 should_use_fast_connect, - UINT32 ulUseProfiles); - -//***************************************************************************** -// -//! wlan_ioctl_get_scan_results -//! -//! @param[in] scan_timeout parameter not supported -//! @param[out] ucResults scan result (_wlan_full_scan_results_args_t) -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Gets entry from scan result table. -//! The scan results are returned one by one, and each entry -//! represents a single AP found in the area. The following is a -//! format of the scan result: -//! - 4 Bytes: number of networks found -//! - 4 Bytes: The status of the scan: 0 - aged results, -//! 1 - results valid, 2 - no results -//! - 42 bytes: Result entry, where the bytes are arranged as follows: -//! -//! - 1 bit isValid - is result valid or not -//! - 7 bits rssi - RSSI value; -//! - 2 bits: securityMode - security mode of the AP: -//! 0 - Open, 1 - WEP, 2 WPA, 3 WPA2 -//! - 6 bits: SSID name length -//! - 2 bytes: the time at which the entry has entered into -//! scans result table -//! - 32 bytes: SSID name -//! - 6 bytes: BSSID -//! -//! @Note scan_timeout, is not supported on this version. -//! -//! @sa wlan_ioctl_set_scan_params -// -//***************************************************************************** - - -extern INT32 wlan_ioctl_get_scan_results(UINT32 ulScanTimeout, - UINT8 *ucResults); - -//***************************************************************************** -// -//! wlan_ioctl_set_scan_params -//! -//! @param uiEnable - start/stop application scan: -//! 1 = start scan with default interval value of 10 min. -//! in order to set a different scan interval value apply the value -//! in milliseconds. minimum 1 second. 0=stop). Wlan reset -//! (wlan_stop() wlan_start()) is needed when changing scan interval -//! value. Saved: No -//! @param uiMinDwellTime minimum dwell time value to be used for each -//! channel, in milliseconds. Saved: yes -//! Recommended Value: 100 (Default: 20) -//! @param uiMaxDwellTime maximum dwell time value to be used for each -//! channel, in milliseconds. Saved: yes -//! Recommended Value: 100 (Default: 30) -//! @param uiNumOfProbeRequests max probe request between dwell time. -//! Saved: yes. Recommended Value: 5 (Default:2) -//! @param uiChannelMask bitwise, up to 13 channels (0x1fff). -//! Saved: yes. Default: 0x7ff -//! @param uiRSSIThreshold RSSI threshold. Saved: yes (Default: -80) -//! @param uiSNRThreshold NSR threshold. Saved: yes (Default: 0) -//! @param uiDefaultTxPower probe Tx power. Saved: yes (Default: 205) -//! @param aiIntervalList pointer to array with 16 entries (16 channels) -//! each entry (UINT32) holds timeout between periodic scan -//! (connection scan) - in milliseconds. Saved: yes. Default 2000ms. -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief start and stop scan procedure. Set scan parameters. -//! -//! @Note uiDefaultTxPower, is not supported on this version. -//! -//! @sa wlan_ioctl_get_scan_results -// -//***************************************************************************** -extern INT32 wlan_ioctl_set_scan_params(UINT32 uiEnable, UINT32 - uiMinDwellTime,UINT32 uiMaxDwellTime, - UINT32 uiNumOfProbeRequests, - UINT32 uiChannelMask, - INT32 iRSSIThreshold,UINT32 uiSNRThreshold, - UINT32 uiDefaultTxPower, - UINT32 *aiIntervalList); - - -//***************************************************************************** -// -//! wlan_smart_config_start -//! -//! @param algoEncryptedFlag indicates whether the information is encrypted -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Start to acquire device profile. The device acquire its own -//! profile, if profile message is found. The acquired AP information -//! is stored in CC3000 EEPROM only in case AES128 encryption is used. -//! In case AES128 encryption is not used, a profile is created by -//! CC3000 internally. -//! -//! @Note An asynchronous event - Smart Config Done will be generated as soon -//! as the process finishes successfully. -//! -//! @sa wlan_smart_config_set_prefix , wlan_smart_config_stop -// -//***************************************************************************** -extern INT32 wlan_smart_config_start(UINT32 algoEncryptedFlag); - - -//***************************************************************************** -// -//! wlan_smart_config_stop -//! -//! @param algoEncryptedFlag indicates whether the information is encrypted -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Stop the acquire profile procedure -//! -//! @sa wlan_smart_config_start , wlan_smart_config_set_prefix -// -//***************************************************************************** -extern INT32 wlan_smart_config_stop(void); - -//***************************************************************************** -// -//! wlan_smart_config_set_prefix -//! -//! @param newPrefix 3 bytes identify the SSID prefix for the Smart Config. -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Configure station ssid prefix. The prefix is used internally -//! in CC3000. It should always be TTT. -//! -//! @Note The prefix is stored in CC3000 NVMEM -//! -//! @sa wlan_smart_config_start , wlan_smart_config_stop -// -//***************************************************************************** -extern INT32 wlan_smart_config_set_prefix(CHAR* cNewPrefix); - -//***************************************************************************** -// -//! wlan_smart_config_process -//! -//! @param none -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief process the acquired data and store it as a profile. The acquired -//! AP information is stored in CC3000 EEPROM encrypted. -//! The encrypted data is decrypted and stored as a profile. -//! behavior is as defined by connection policy. -// -//***************************************************************************** -extern INT32 wlan_smart_config_process(void); - -//***************************************************************************** -// -// Close the Doxygen group. -//! @} -// -//***************************************************************************** - - - -//***************************************************************************** -// -// Mark the end of the C bindings section for C++ compilers. -// -//***************************************************************************** -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif // __CC3000_WLAN_H__ diff --git a/drivers/cc3000/src/cc3000_common.c b/drivers/cc3000/src/cc3000_common.c deleted file mode 100644 index b4c87848cf..0000000000 --- a/drivers/cc3000/src/cc3000_common.c +++ /dev/null @@ -1,164 +0,0 @@ -/***************************************************************************** -* -* cc3000_common.c.c - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ -//***************************************************************************** -// -//! \addtogroup common_api -//! @{ -// -//***************************************************************************** -/****************************************************************************** -* -* Include files -* -*****************************************************************************/ - -#include "cc3000_common.h" -#include "socket.h" -#include "wlan.h" -#include "evnt_handler.h" - -//***************************************************************************** -// -//! __error__ -//! -//! @param pcFilename - file name, where error occurred -//! @param ulLine - line number, where error occurred -//! -//! @return none -//! -//! @brief stub function for ASSERT macro -// -//***************************************************************************** -void __error__(CHAR *pcFilename, UINT32 ulLine) -{ - //TODO full up function -} - - - -//***************************************************************************** -// -//! UINT32_TO_STREAM_f -//! -//! @param p pointer to the new stream -//! @param u32 pointer to the 32 bit -//! -//! @return pointer to the new stream -//! -//! @brief This function is used for copying 32 bit to stream -//! while converting to little endian format. -// -//***************************************************************************** - -UINT8* UINT32_TO_STREAM_f (UINT8 *p, UINT32 u32) -{ - *(p)++ = (UINT8)(u32); - *(p)++ = (UINT8)((u32) >> 8); - *(p)++ = (UINT8)((u32) >> 16); - *(p)++ = (UINT8)((u32) >> 24); - return p; -} - -//***************************************************************************** -// -//! UINT16_TO_STREAM_f -//! -//! @param p pointer to the new stream -//! @param u32 pointer to the 16 bit -//! -//! @return pointer to the new stream -//! -//! @brief This function is used for copying 16 bit to stream -//! while converting to little endian format. -// -//***************************************************************************** - -UINT8* UINT16_TO_STREAM_f (UINT8 *p, UINT16 u16) -{ - *(p)++ = (UINT8)(u16); - *(p)++ = (UINT8)((u16) >> 8); - return p; -} - -//***************************************************************************** -// -//! STREAM_TO_UINT16_f -//! -//! @param p pointer to the stream -//! @param offset offset in the stream -//! -//! @return pointer to the new 16 bit -//! -//! @brief This function is used for copying received stream to -//! 16 bit in little endian format. -// -//***************************************************************************** - -UINT16 STREAM_TO_UINT16_f(CHAR* p, UINT16 offset) -{ - return (UINT16)((UINT16)((UINT16) - (*(p + offset + 1)) << 8) + (UINT16)(*(p + offset))); -} - -//***************************************************************************** -// -//! STREAM_TO_UINT32_f -//! -//! @param p pointer to the stream -//! @param offset offset in the stream -//! -//! @return pointer to the new 32 bit -//! -//! @brief This function is used for copying received stream to -//! 32 bit in little endian format. -// -//***************************************************************************** - -UINT32 STREAM_TO_UINT32_f(CHAR* p, UINT16 offset) -{ - return (UINT32)((UINT32)((UINT32) - (*(p + offset + 3)) << 24) + (UINT32)((UINT32) - (*(p + offset + 2)) << 16) + (UINT32)((UINT32) - (*(p + offset + 1)) << 8) + (UINT32)(*(p + offset))); -} - - - -//***************************************************************************** -// -// Close the Doxygen group. -//! @} -// -//***************************************************************************** diff --git a/drivers/cc3000/src/ccspi.c b/drivers/cc3000/src/ccspi.c deleted file mode 100644 index 820be809b3..0000000000 --- a/drivers/cc3000/src/ccspi.c +++ /dev/null @@ -1,454 +0,0 @@ -/***************************************************************************** - * - * spi.c - CC3000 Host Driver Implementation. - * Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - *****************************************************************************/ - -#include - -#include "py/runtime.h" -#include "pin.h" -#include "led.h" -#include "extint.h" -#include "spi.h" -#include "ccspi.h" -#include "evnt_handler.h" - -#if 0 // print debugging info -#include -#define DEBUG_printf(args...) printf(args) -#else // don't print debugging info -#define DEBUG_printf(args...) (void)0 -#endif - -// these need to be set to valid values before anything in this file will work -STATIC SPI_HandleTypeDef *SPI_HANDLE = NULL; -STATIC const pin_obj_t *PIN_CS = NULL; -STATIC const pin_obj_t *PIN_EN = NULL; -STATIC const pin_obj_t *PIN_IRQ = NULL; - -#define CS_LOW() HAL_GPIO_WritePin(PIN_CS->gpio, PIN_CS->pin_mask, GPIO_PIN_RESET) -#define CS_HIGH() HAL_GPIO_WritePin(PIN_CS->gpio, PIN_CS->pin_mask, GPIO_PIN_SET) - -#define READ 3 -#define WRITE 1 - -#define HI(value) (((value) & 0xFF00) >> 8) -#define LO(value) ((value) & 0x00FF) - -#define SPI_TIMEOUT (1000) -#define HEADERS_SIZE_EVNT (SPI_HEADER_SIZE + 5) - -/* SPI bus states */ -#define eSPI_STATE_POWERUP (0) -#define eSPI_STATE_INITIALIZED (1) -#define eSPI_STATE_IDLE (2) -#define eSPI_STATE_WRITE_IRQ (3) -#define eSPI_STATE_WRITE_FIRST_PORTION (4) -#define eSPI_STATE_WRITE_EOT (5) -#define eSPI_STATE_READ_IRQ (6) -#define eSPI_STATE_READ_FIRST_PORTION (7) -#define eSPI_STATE_READ_EOT (8) - -// The magic number that resides at the end of the TX/RX buffer (1 byte after the allocated size) -// for the purpose of detection of the overrun. The location of the memory where the magic number -// resides shall never be written. In case it is written - the overrun occured and either recevie function -// or send function will stuck forever. -#define CC3000_BUFFER_MAGIC_NUMBER (0xDE) - -typedef struct { - gcSpiHandleRx SPIRxHandler; - unsigned short usTxPacketLength; - unsigned short usRxPacketLength; - unsigned long ulSpiState; - unsigned char *pTxPacket; - unsigned char *pRxPacket; -} tSpiInformation; -STATIC tSpiInformation sSpiInformation; - -STATIC char spi_buffer[CC3000_RX_BUFFER_SIZE]; -unsigned char wlan_tx_buffer[CC3000_TX_BUFFER_SIZE]; - -STATIC const mp_obj_fun_builtin_fixed_t irq_callback_obj; - -// set the pins to use to communicate with the CC3000 -// the arguments must be of type pin_obj_t* and SPI_HandleTypeDef* -void SpiInit(void *spi, const void *pin_cs, const void *pin_en, const void *pin_irq) { - SPI_HANDLE = spi; - PIN_CS = pin_cs; - PIN_EN = pin_en; - PIN_IRQ = pin_irq; -} - -void SpiClose(void) -{ - if (sSpiInformation.pRxPacket) { - sSpiInformation.pRxPacket = 0; - } - - tSLInformation.WlanInterruptDisable(); - - //HAL_SPI_DeInit(SPI_HANDLE); -} - -void SpiOpen(gcSpiHandleRx pfRxHandler) -{ - DEBUG_printf("SpiOpen\n"); - - /* initialize SPI state */ - sSpiInformation.ulSpiState = eSPI_STATE_POWERUP; - sSpiInformation.SPIRxHandler = pfRxHandler; - sSpiInformation.usTxPacketLength = 0; - sSpiInformation.pTxPacket = NULL; - sSpiInformation.pRxPacket = (unsigned char *)spi_buffer; - sSpiInformation.usRxPacketLength = 0; - spi_buffer[CC3000_RX_BUFFER_SIZE - 1] = CC3000_BUFFER_MAGIC_NUMBER; - wlan_tx_buffer[CC3000_TX_BUFFER_SIZE - 1] = CC3000_BUFFER_MAGIC_NUMBER; - - /* SPI configuration */ - SPI_HANDLE->Init.Mode = SPI_MODE_MASTER; - SPI_HANDLE->Init.Direction = SPI_DIRECTION_2LINES; - SPI_HANDLE->Init.DataSize = SPI_DATASIZE_8BIT; - SPI_HANDLE->Init.CLKPolarity = SPI_POLARITY_LOW; - SPI_HANDLE->Init.CLKPhase = SPI_PHASE_2EDGE; - SPI_HANDLE->Init.NSS = SPI_NSS_SOFT; - SPI_HANDLE->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8; - SPI_HANDLE->Init.FirstBit = SPI_FIRSTBIT_MSB; - SPI_HANDLE->Init.TIMode = SPI_TIMODE_DISABLED; - SPI_HANDLE->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLED; - SPI_HANDLE->Init.CRCPolynomial = 7; - spi_init(SPI_HANDLE, false); - - // configure wlan CS and EN pins - GPIO_InitTypeDef GPIO_InitStructure; - GPIO_InitStructure.Speed = GPIO_SPEED_FAST; - GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP; - GPIO_InitStructure.Pull = GPIO_NOPULL; - GPIO_InitStructure.Alternate = 0; - - GPIO_InitStructure.Pin = PIN_CS->pin_mask; - HAL_GPIO_Init(PIN_CS->gpio, &GPIO_InitStructure); - - GPIO_InitStructure.Pin = PIN_EN->pin_mask; - HAL_GPIO_Init(PIN_EN->gpio, &GPIO_InitStructure); - - HAL_GPIO_WritePin(PIN_CS->gpio, PIN_CS->pin_mask, GPIO_PIN_SET); - HAL_GPIO_WritePin(PIN_EN->gpio, PIN_EN->pin_mask, GPIO_PIN_RESET); - - /* do a dummy read, this ensures SCLK is low before - actual communications start, it might be required */ - CS_LOW(); - uint8_t buf[1]; - HAL_SPI_Receive(SPI_HANDLE, buf, sizeof(buf), SPI_TIMEOUT); - CS_HIGH(); - - // register EXTI - extint_register((mp_obj_t)PIN_IRQ, GPIO_MODE_IT_FALLING, GPIO_PULLUP, (mp_obj_t)&irq_callback_obj, true); - extint_enable(PIN_IRQ->pin); - - DEBUG_printf("SpiOpen finished; IRQ.pin=%d IRQ_LINE=%d\n", PIN_IRQ->pin, PIN_IRQ->pin); -} - -long ReadWlanInterruptPin(void) -{ - return HAL_GPIO_ReadPin(PIN_IRQ->gpio, PIN_IRQ->pin_mask); -} - -void WriteWlanPin(unsigned char val) -{ - HAL_GPIO_WritePin(PIN_EN->gpio, PIN_EN->pin_mask, - (WLAN_ENABLE)? GPIO_PIN_SET:GPIO_PIN_RESET); -} - -STATIC void SpiWriteDataSynchronous(unsigned char *data, unsigned short size) -{ - DEBUG_printf("SpiWriteDataSynchronous(data=%p [%x %x %x %x], size=%u)\n", data, data[0], data[1], data[2], data[3], size); - __disable_irq(); - if (HAL_SPI_TransmitReceive(SPI_HANDLE, data, data, size, SPI_TIMEOUT) != HAL_OK) { - //BREAK(); - } - __enable_irq(); - DEBUG_printf(" - rx data = [%x %x %x %x]\n", data[0], data[1], data[2], data[3]); -} - -STATIC void SpiReadDataSynchronous(unsigned char *data, unsigned short size) -{ - memset(data, READ, size); - __disable_irq(); - if (HAL_SPI_TransmitReceive(SPI_HANDLE, data, data, size, SPI_TIMEOUT) != HAL_OK) { - //BREAK(); - } - __enable_irq(); -} - -STATIC void __delay_cycles(volatile int x) -{ - x *= 6; // for 168 MHz CPU - while (x--); -} - -STATIC long SpiFirstWrite(unsigned char *ucBuf, unsigned short usLength) -{ - DEBUG_printf("SpiFirstWrite %lu\n", sSpiInformation.ulSpiState); - - CS_LOW(); - - // Assuming we are running on 24 MHz ~50 micro delay is 1200 cycles; - __delay_cycles(1200); - - // SPI writes first 4 bytes of data - SpiWriteDataSynchronous(ucBuf, 4); - - __delay_cycles(1200); - - SpiWriteDataSynchronous(ucBuf + 4, usLength - 4); - - // From this point on - operate in a regular way - sSpiInformation.ulSpiState = eSPI_STATE_IDLE; - - CS_HIGH(); - - return(0); -} - -long SpiWrite(unsigned char *pUserBuffer, unsigned short usLength) -{ - DEBUG_printf("SpiWrite %lu\n", sSpiInformation.ulSpiState); - - unsigned char ucPad = 0; - - // Figure out the total length of the packet in order to figure out if there - // is padding or not - if(!(usLength & 0x0001)) { - ucPad++; - } - - pUserBuffer[0] = WRITE; - pUserBuffer[1] = HI(usLength + ucPad); - pUserBuffer[2] = LO(usLength + ucPad); - pUserBuffer[3] = 0; - pUserBuffer[4] = 0; - - usLength += (SPI_HEADER_SIZE + ucPad); - - // The magic number that resides at the end of the TX/RX buffer (1 byte after the allocated size) - // for the purpose of detection of the overrun. If the magic number is overriten - buffer overrun - // occurred - and we will stuck here forever! - if (wlan_tx_buffer[CC3000_TX_BUFFER_SIZE - 1] != CC3000_BUFFER_MAGIC_NUMBER) { - while (1); - } - - if (sSpiInformation.ulSpiState == eSPI_STATE_POWERUP) { - while (sSpiInformation.ulSpiState != eSPI_STATE_INITIALIZED); - } - - if (sSpiInformation.ulSpiState == eSPI_STATE_INITIALIZED) { - // This is time for first TX/RX transactions over SPI: - // the IRQ is down - so need to send read buffer size command - SpiFirstWrite(pUserBuffer, usLength); - } else { - // - // We need to prevent here race that can occur in case 2 back to back packets are sent to the - // device, so the state will move to IDLE and once again to not IDLE due to IRQ - // - tSLInformation.WlanInterruptDisable(); - - while (sSpiInformation.ulSpiState != eSPI_STATE_IDLE); - - sSpiInformation.ulSpiState = eSPI_STATE_WRITE_IRQ; - sSpiInformation.pTxPacket = pUserBuffer; - sSpiInformation.usTxPacketLength = usLength; - - // Assert the CS line and wait till SSI IRQ line is active and then initialize write operation - CS_LOW(); - - // Re-enable IRQ - if it was not disabled - this is not a problem... - tSLInformation.WlanInterruptEnable(); - - // check for a missing interrupt between the CS assertion and enabling back the interrupts - if (tSLInformation.ReadWlanInterruptPin() == 0) { - SpiWriteDataSynchronous(sSpiInformation.pTxPacket, sSpiInformation.usTxPacketLength); - - sSpiInformation.ulSpiState = eSPI_STATE_IDLE; - - CS_HIGH(); - } - } - - // Due to the fact that we are currently implementing a blocking situation - // here we will wait till end of transaction - while (eSPI_STATE_IDLE != sSpiInformation.ulSpiState); - - return(0); -} - -#if 0 -unused -STATIC void SpiReadPacket(void) -{ - int length; - - /* read SPI header */ - SpiReadDataSynchronous(sSpiInformation.pRxPacket, SPI_HEADER_SIZE); - - /* parse data length */ - STREAM_TO_UINT8(sSpiInformation.pRxPacket, SPI_HEADER_SIZE-1, length); - - /* read the remainder of the packet */ - SpiReadDataSynchronous(sSpiInformation.pRxPacket + SPI_HEADER_SIZE, length); - - sSpiInformation.ulSpiState = eSPI_STATE_READ_EOT; -} -#endif - -STATIC void SpiReadHeader(void) -{ - SpiReadDataSynchronous(sSpiInformation.pRxPacket, 10); -} - -STATIC void SpiTriggerRxProcessing(void) -{ - SpiPauseSpi(); - CS_HIGH(); - - // The magic number that resides at the end of the TX/RX buffer (1 byte after the allocated size) - // for the purpose of detection of the overrun. If the magic number is overriten - buffer overrun - // occurred - and we will stuck here forever! - if (sSpiInformation.pRxPacket[CC3000_RX_BUFFER_SIZE - 1] != CC3000_BUFFER_MAGIC_NUMBER) { - while (1); - } - - sSpiInformation.ulSpiState = eSPI_STATE_IDLE; - sSpiInformation.SPIRxHandler(sSpiInformation.pRxPacket + SPI_HEADER_SIZE); -} - - -STATIC long SpiReadDataCont(void) -{ - long data_to_recv=0; - unsigned char *evnt_buff, type; - - //determine what type of packet we have - evnt_buff = sSpiInformation.pRxPacket; - STREAM_TO_UINT8((char *)(evnt_buff + SPI_HEADER_SIZE), HCI_PACKET_TYPE_OFFSET, type); - - switch (type) { - case HCI_TYPE_DATA:{ - // We need to read the rest of data.. - STREAM_TO_UINT16((char *)(evnt_buff + SPI_HEADER_SIZE), - HCI_DATA_LENGTH_OFFSET, data_to_recv); - if (!((HEADERS_SIZE_EVNT + data_to_recv) & 1)) { - data_to_recv++; - } - - if (data_to_recv) { - SpiReadDataSynchronous(evnt_buff + 10, data_to_recv); - } - break; - } - case HCI_TYPE_EVNT: { - // Calculate the rest length of the data - STREAM_TO_UINT8((char *)(evnt_buff + SPI_HEADER_SIZE), - HCI_EVENT_LENGTH_OFFSET, data_to_recv); - data_to_recv -= 1; - - // Add padding byte if needed - if ((HEADERS_SIZE_EVNT + data_to_recv) & 1) { - data_to_recv++; - } - - if (data_to_recv) { - SpiReadDataSynchronous(evnt_buff + 10, data_to_recv); - } - - sSpiInformation.ulSpiState = eSPI_STATE_READ_EOT; - break; - } - } - - return 0; -} - -STATIC void SSIContReadOperation(void) -{ - // The header was read - continue with the payload read - if (!SpiReadDataCont()) { - /* All the data was read - finalize handling by switching - to the task and calling from task Event Handler */ - SpiTriggerRxProcessing(); - } -} - -STATIC mp_obj_t irq_callback(mp_obj_t line) { - DEBUG_printf("<< IRQ; state=%lu >>\n", sSpiInformation.ulSpiState); - switch (sSpiInformation.ulSpiState) { - case eSPI_STATE_POWERUP: - /* This means IRQ line was low call a callback of HCI Layer to inform on event */ - DEBUG_printf(" - POWERUP\n"); - sSpiInformation.ulSpiState = eSPI_STATE_INITIALIZED; - break; - case eSPI_STATE_IDLE: - DEBUG_printf(" - IDLE\n"); - sSpiInformation.ulSpiState = eSPI_STATE_READ_IRQ; - - /* IRQ line goes down - we are start reception */ - CS_LOW(); - - // Wait for TX/RX Compete which will come as DMA interrupt - SpiReadHeader(); - - sSpiInformation.ulSpiState = eSPI_STATE_READ_EOT; - - SSIContReadOperation(); - break; - case eSPI_STATE_WRITE_IRQ: - DEBUG_printf(" - WRITE IRQ\n"); - SpiWriteDataSynchronous(sSpiInformation.pTxPacket, sSpiInformation.usTxPacketLength); - - sSpiInformation.ulSpiState = eSPI_STATE_IDLE; - - CS_HIGH(); - break; - } - return mp_const_none; -} - -STATIC MP_DEFINE_CONST_FUN_OBJ_1(irq_callback_obj, irq_callback); - -void SpiPauseSpi(void) { - DEBUG_printf("SpiPauseSpi\n"); - extint_disable(PIN_IRQ->pin); -} - -void SpiResumeSpi(void) { - DEBUG_printf("SpiResumeSpi\n"); - extint_enable(PIN_IRQ->pin); -} diff --git a/drivers/cc3000/src/evnt_handler.c b/drivers/cc3000/src/evnt_handler.c deleted file mode 100644 index 80f34e469b..0000000000 --- a/drivers/cc3000/src/evnt_handler.c +++ /dev/null @@ -1,849 +0,0 @@ -/***************************************************************************** -* -* evnt_handler.c - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ -//***************************************************************************** -// -//! \addtogroup evnt_handler_api -//! @{ -// -//****************************************************************************** - -//****************************************************************************** -// INCLUDE FILES -//****************************************************************************** - -#include "cc3000_common.h" -#include "string.h" -#include "hci.h" -#include "evnt_handler.h" -#include "wlan.h" -#include "socket.h" -#include "netapp.h" -#include "ccspi.h" - - - -//***************************************************************************** -// COMMON DEFINES -//***************************************************************************** - -#define FLOW_CONTROL_EVENT_HANDLE_OFFSET (0) -#define FLOW_CONTROL_EVENT_BLOCK_MODE_OFFSET (1) -#define FLOW_CONTROL_EVENT_FREE_BUFFS_OFFSET (2) -#define FLOW_CONTROL_EVENT_SIZE (4) - -#define BSD_RSP_PARAMS_SOCKET_OFFSET (0) -#define BSD_RSP_PARAMS_STATUS_OFFSET (4) - -#define GET_HOST_BY_NAME_RETVAL_OFFSET (0) -#define GET_HOST_BY_NAME_ADDR_OFFSET (4) - -#define ACCEPT_SD_OFFSET (0) -#define ACCEPT_RETURN_STATUS_OFFSET (4) -#define ACCEPT_ADDRESS__OFFSET (8) - -#define SL_RECEIVE_SD_OFFSET (0) -#define SL_RECEIVE_NUM_BYTES_OFFSET (4) -#define SL_RECEIVE__FLAGS__OFFSET (8) - - -#define SELECT_STATUS_OFFSET (0) -#define SELECT_READFD_OFFSET (4) -#define SELECT_WRITEFD_OFFSET (8) -#define SELECT_EXFD_OFFSET (12) - - -#define NETAPP_IPCONFIG_IP_OFFSET (0) -#define NETAPP_IPCONFIG_SUBNET_OFFSET (4) -#define NETAPP_IPCONFIG_GW_OFFSET (8) -#define NETAPP_IPCONFIG_DHCP_OFFSET (12) -#define NETAPP_IPCONFIG_DNS_OFFSET (16) -#define NETAPP_IPCONFIG_MAC_OFFSET (20) -#define NETAPP_IPCONFIG_SSID_OFFSET (26) - -#define NETAPP_IPCONFIG_IP_LENGTH (4) -#define NETAPP_IPCONFIG_MAC_LENGTH (6) -#define NETAPP_IPCONFIG_SSID_LENGTH (32) - - -#define NETAPP_PING_PACKETS_SENT_OFFSET (0) -#define NETAPP_PING_PACKETS_RCVD_OFFSET (4) -#define NETAPP_PING_MIN_RTT_OFFSET (8) -#define NETAPP_PING_MAX_RTT_OFFSET (12) -#define NETAPP_PING_AVG_RTT_OFFSET (16) - -#define GET_SCAN_RESULTS_TABlE_COUNT_OFFSET (0) -#define GET_SCAN_RESULTS_SCANRESULT_STATUS_OFFSET (4) -#define GET_SCAN_RESULTS_ISVALID_TO_SSIDLEN_OFFSET (8) -#define GET_SCAN_RESULTS_FRAME_TIME_OFFSET (10) -#define GET_SCAN_RESULTS_SSID_MAC_LENGTH (38) - -#define GET_MSS_VAL_RETVAL_OFFSET (0) - -//***************************************************************************** -// GLOBAL VARAIABLES -//***************************************************************************** - -UINT32 socket_active_status = SOCKET_STATUS_INIT_VAL; - - -//***************************************************************************** -// Prototypes for the static functions -//***************************************************************************** - -static INT32 hci_event_unsol_flowcontrol_handler(CHAR *pEvent); - -static void update_socket_active_status(CHAR *resp_params); - - -//***************************************************************************** -// -//! hci_unsol_handle_patch_request -//! -//! @param event_hdr event header -//! -//! @return none -//! -//! @brief Handle unsolicited event from type patch request -// -//***************************************************************************** -void hci_unsol_handle_patch_request(CHAR *event_hdr) -{ - CHAR *params = (CHAR *)(event_hdr) + HCI_EVENT_HEADER_SIZE; - UINT32 ucLength = 0; - CHAR *patch; - - switch (*params) - { - case HCI_EVENT_PATCHES_DRV_REQ: - - if (tSLInformation.sDriverPatches) - { - patch = tSLInformation.sDriverPatches(&ucLength); - - if (patch) - { - hci_patch_send(HCI_EVENT_PATCHES_DRV_REQ, - tSLInformation.pucTxCommandBuffer, patch, ucLength); - return; - } - } - - // Send 0 length Patches response event - hci_patch_send(HCI_EVENT_PATCHES_DRV_REQ, - tSLInformation.pucTxCommandBuffer, 0, 0); - break; - - case HCI_EVENT_PATCHES_FW_REQ: - - if (tSLInformation.sFWPatches) - { - patch = tSLInformation.sFWPatches(&ucLength); - - // Build and send a patch - if (patch) - { - hci_patch_send(HCI_EVENT_PATCHES_FW_REQ, - tSLInformation.pucTxCommandBuffer, patch, ucLength); - return; - } - } - - // Send 0 length Patches response event - hci_patch_send(HCI_EVENT_PATCHES_FW_REQ, - tSLInformation.pucTxCommandBuffer, 0, 0); - break; - - case HCI_EVENT_PATCHES_BOOTLOAD_REQ: - - if (tSLInformation.sBootLoaderPatches) - { - patch = tSLInformation.sBootLoaderPatches(&ucLength); - - if (patch) - { - hci_patch_send(HCI_EVENT_PATCHES_BOOTLOAD_REQ, - tSLInformation.pucTxCommandBuffer, patch, ucLength); - return; - } - } - - // Send 0 length Patches response event - hci_patch_send(HCI_EVENT_PATCHES_BOOTLOAD_REQ, - tSLInformation.pucTxCommandBuffer, 0, 0); - break; - } -} - - - -//***************************************************************************** -// -//! hci_event_handler -//! -//! @param pRetParams incoming data buffer -//! @param from from information (in case of data received) -//! @param fromlen from information length (in case of data received) -//! -//! @return none -//! -//! @brief Parse the incoming events packets and issues corresponding -//! event handler from global array of handlers pointers -// -//***************************************************************************** - - -UINT8 * hci_event_handler(void *pRetParams, UINT8 *from, UINT8 *fromlen) -{ - UINT8 *pucReceivedData, ucArgsize; - UINT16 usLength; - UINT8 *pucReceivedParams; - UINT16 usReceivedEventOpcode = 0; - UINT32 retValue32; - UINT8 * RecvParams; - UINT8 *RetParams; - - - while (1) - { - if (tSLInformation.usEventOrDataReceived != 0) - { - pucReceivedData = (tSLInformation.pucReceivedData); - - if (*pucReceivedData == HCI_TYPE_EVNT) - { - // Event Received - STREAM_TO_UINT16((CHAR *)pucReceivedData, HCI_EVENT_OPCODE_OFFSET, - usReceivedEventOpcode); - pucReceivedParams = pucReceivedData + HCI_EVENT_HEADER_SIZE; - RecvParams = pucReceivedParams; - RetParams = pRetParams; - - // In case unsolicited event received - here the handling finished - if (hci_unsol_event_handler((CHAR *)pucReceivedData) == 0) - { - STREAM_TO_UINT8(pucReceivedData, HCI_DATA_LENGTH_OFFSET, usLength); - - switch(usReceivedEventOpcode) - { - case HCI_CMND_READ_BUFFER_SIZE: - { - STREAM_TO_UINT8((CHAR *)pucReceivedParams, 0, - tSLInformation.usNumberOfFreeBuffers); - STREAM_TO_UINT16((CHAR *)pucReceivedParams, 1, - tSLInformation.usSlBufferLength); - } - break; - - case HCI_CMND_WLAN_CONFIGURE_PATCH: - case HCI_NETAPP_DHCP: - case HCI_NETAPP_PING_SEND: - case HCI_NETAPP_PING_STOP: - case HCI_NETAPP_ARP_FLUSH: - case HCI_NETAPP_SET_DEBUG_LEVEL: - case HCI_NETAPP_SET_TIMERS: - case HCI_EVNT_NVMEM_READ: - case HCI_EVNT_NVMEM_CREATE_ENTRY: - case HCI_CMND_NVMEM_WRITE_PATCH: - case HCI_NETAPP_PING_REPORT: - case HCI_EVNT_MDNS_ADVERTISE: - - STREAM_TO_UINT8(pucReceivedData, HCI_EVENT_STATUS_OFFSET - ,*(UINT8 *)pRetParams); - break; - - case HCI_CMND_SETSOCKOPT: - case HCI_CMND_WLAN_CONNECT: - case HCI_CMND_WLAN_IOCTL_STATUSGET: - case HCI_EVNT_WLAN_IOCTL_ADD_PROFILE: - case HCI_CMND_WLAN_IOCTL_DEL_PROFILE: - case HCI_CMND_WLAN_IOCTL_SET_CONNECTION_POLICY: - case HCI_CMND_WLAN_IOCTL_SET_SCANPARAM: - case HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_START: - case HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_STOP: - case HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_SET_PREFIX: - case HCI_CMND_EVENT_MASK: - case HCI_EVNT_WLAN_DISCONNECT: - case HCI_EVNT_SOCKET: - case HCI_EVNT_BIND: - case HCI_CMND_LISTEN: - case HCI_EVNT_CLOSE_SOCKET: - case HCI_EVNT_CONNECT: - case HCI_EVNT_NVMEM_WRITE: - - STREAM_TO_UINT32((CHAR *)pucReceivedParams,0 - ,*(UINT32 *)pRetParams); - break; - - case HCI_EVNT_READ_SP_VERSION: - - STREAM_TO_UINT8(pucReceivedData, HCI_EVENT_STATUS_OFFSET - ,*(UINT8 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 1; - STREAM_TO_UINT32((CHAR *)pucReceivedParams, 0, retValue32); - UINT32_TO_STREAM((UINT8 *)pRetParams, retValue32); - break; - - case HCI_EVNT_BSD_GETHOSTBYNAME: - - STREAM_TO_UINT32((CHAR *)pucReceivedParams - ,GET_HOST_BY_NAME_RETVAL_OFFSET,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 4; - STREAM_TO_UINT32((CHAR *)pucReceivedParams - ,GET_HOST_BY_NAME_ADDR_OFFSET,*(UINT32 *)pRetParams); - break; - - case HCI_EVNT_GETMSSVALUE: - - STREAM_TO_UINT16((CHAR *)pucReceivedParams - ,GET_MSS_VAL_RETVAL_OFFSET,*(UINT16 *)pRetParams); - - break; - - case HCI_EVNT_ACCEPT: - { - STREAM_TO_UINT32((CHAR *)pucReceivedParams,ACCEPT_SD_OFFSET - ,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 4; - STREAM_TO_UINT32((CHAR *)pucReceivedParams - ,ACCEPT_RETURN_STATUS_OFFSET,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 4; - - //This argument returns in network order - memcpy((UINT8 *)pRetParams, - pucReceivedParams + ACCEPT_ADDRESS__OFFSET, sizeof(sockaddr)); - break; - } - - case HCI_EVNT_RECV: - case HCI_EVNT_RECVFROM: - { - STREAM_TO_UINT32((CHAR *)pucReceivedParams,SL_RECEIVE_SD_OFFSET ,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 4; - STREAM_TO_UINT32((CHAR *)pucReceivedParams,SL_RECEIVE_NUM_BYTES_OFFSET,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 4; - STREAM_TO_UINT32((CHAR *)pucReceivedParams,SL_RECEIVE__FLAGS__OFFSET,*(UINT32 *)pRetParams); - - if(((tBsdReadReturnParams *)pRetParams)->iNumberOfBytes == ERROR_SOCKET_INACTIVE) - { - set_socket_active_status(((tBsdReadReturnParams *)pRetParams)->iSocketDescriptor,SOCKET_STATUS_INACTIVE); - } - break; - } - - case HCI_EVNT_SEND: - case HCI_EVNT_SENDTO: - { - STREAM_TO_UINT32((CHAR *)pucReceivedParams,SL_RECEIVE_SD_OFFSET ,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 4; - STREAM_TO_UINT32((CHAR *)pucReceivedParams,SL_RECEIVE_NUM_BYTES_OFFSET,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 4; - - break; - } - - case HCI_EVNT_SELECT: - { - STREAM_TO_UINT32((CHAR *)pucReceivedParams,SELECT_STATUS_OFFSET,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 4; - STREAM_TO_UINT32((CHAR *)pucReceivedParams,SELECT_READFD_OFFSET,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 4; - STREAM_TO_UINT32((CHAR *)pucReceivedParams,SELECT_WRITEFD_OFFSET,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 4; - STREAM_TO_UINT32((CHAR *)pucReceivedParams,SELECT_EXFD_OFFSET,*(UINT32 *)pRetParams); - break; - } - - case HCI_CMND_GETSOCKOPT: - - STREAM_TO_UINT8(pucReceivedData, HCI_EVENT_STATUS_OFFSET,((tBsdGetSockOptReturnParams *)pRetParams)->iStatus); - //This argument returns in network order - memcpy((UINT8 *)pRetParams, pucReceivedParams, 4); - break; - - case HCI_CMND_WLAN_IOCTL_GET_SCAN_RESULTS: - - STREAM_TO_UINT32((CHAR *)pucReceivedParams,GET_SCAN_RESULTS_TABlE_COUNT_OFFSET,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 4; - STREAM_TO_UINT32((CHAR *)pucReceivedParams,GET_SCAN_RESULTS_SCANRESULT_STATUS_OFFSET,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 4; - STREAM_TO_UINT16((CHAR *)pucReceivedParams,GET_SCAN_RESULTS_ISVALID_TO_SSIDLEN_OFFSET,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 2; - STREAM_TO_UINT16((CHAR *)pucReceivedParams,GET_SCAN_RESULTS_FRAME_TIME_OFFSET,*(UINT32 *)pRetParams); - pRetParams = ((CHAR *)pRetParams) + 2; - memcpy((UINT8 *)pRetParams, (CHAR *)(pucReceivedParams + GET_SCAN_RESULTS_FRAME_TIME_OFFSET + 2), GET_SCAN_RESULTS_SSID_MAC_LENGTH); - break; - - case HCI_CMND_SIMPLE_LINK_START: - break; - - case HCI_NETAPP_IPCONFIG: - - //Read IP address - STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_IP_LENGTH); - RecvParams += 4; - - //Read subnet - STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_IP_LENGTH); - RecvParams += 4; - - //Read default GW - STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_IP_LENGTH); - RecvParams += 4; - - //Read DHCP server - STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_IP_LENGTH); - RecvParams += 4; - - //Read DNS server - STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_IP_LENGTH); - RecvParams += 4; - - //Read Mac address - STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_MAC_LENGTH); - RecvParams += 6; - - //Read SSID - STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_SSID_LENGTH); - - } - } - - if (usReceivedEventOpcode == tSLInformation.usRxEventOpcode) - { - tSLInformation.usRxEventOpcode = 0; - } - } - else - { - pucReceivedParams = pucReceivedData; - STREAM_TO_UINT8((CHAR *)pucReceivedData, HCI_PACKET_ARGSIZE_OFFSET, ucArgsize); - - STREAM_TO_UINT16((CHAR *)pucReceivedData, HCI_PACKET_LENGTH_OFFSET, usLength); - - // Data received: note that the only case where from and from length - // are not null is in recv from, so fill the args accordingly - if (from) - { - STREAM_TO_UINT32((CHAR *)(pucReceivedData + HCI_DATA_HEADER_SIZE), BSD_RECV_FROM_FROMLEN_OFFSET, *(UINT32 *)fromlen); - memcpy(from, (pucReceivedData + HCI_DATA_HEADER_SIZE + BSD_RECV_FROM_FROM_OFFSET) ,*fromlen); - } - - memcpy(pRetParams, pucReceivedParams + HCI_DATA_HEADER_SIZE + ucArgsize, - usLength - ucArgsize); - - tSLInformation.usRxDataPending = 0; - } - - tSLInformation.usEventOrDataReceived = 0; - - SpiResumeSpi(); - - // Since we are going to TX - we need to handle this event after the - // ResumeSPi since we need interrupts - if ((*pucReceivedData == HCI_TYPE_EVNT) && - (usReceivedEventOpcode == HCI_EVNT_PATCHES_REQ)) - { - hci_unsol_handle_patch_request((CHAR *)pucReceivedData); - } - - if ((tSLInformation.usRxEventOpcode == 0) && (tSLInformation.usRxDataPending == 0)) - { - return NULL; - } - } - } - -} - -//***************************************************************************** -// -//! hci_unsol_event_handler -//! -//! @param event_hdr event header -//! -//! @return 1 if event supported and handled -//! 0 if event is not supported -//! -//! @brief Handle unsolicited events -// -//***************************************************************************** -INT32 hci_unsol_event_handler(CHAR *event_hdr) -{ - CHAR * data = NULL; - INT32 event_type; - UINT32 NumberOfReleasedPackets; - UINT32 NumberOfSentPackets; - - STREAM_TO_UINT16(event_hdr, HCI_EVENT_OPCODE_OFFSET,event_type); - - if (event_type & HCI_EVNT_UNSOL_BASE) - { - switch(event_type) - { - - case HCI_EVNT_DATA_UNSOL_FREE_BUFF: - { - hci_event_unsol_flowcontrol_handler(event_hdr); - - NumberOfReleasedPackets = tSLInformation.NumberOfReleasedPackets; - NumberOfSentPackets = tSLInformation.NumberOfSentPackets; - - if (NumberOfReleasedPackets == NumberOfSentPackets) - { - if (tSLInformation.InformHostOnTxComplete) - { - tSLInformation.sWlanCB(HCI_EVENT_CC3000_CAN_SHUT_DOWN, NULL, 0); - } - } - return 1; - - } - } - } - - if(event_type & HCI_EVNT_WLAN_UNSOL_BASE) - { - switch(event_type) - { - case HCI_EVNT_WLAN_KEEPALIVE: - case HCI_EVNT_WLAN_UNSOL_CONNECT: - case HCI_EVNT_WLAN_UNSOL_DISCONNECT: - case HCI_EVNT_WLAN_UNSOL_INIT: - case HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE: - - if( tSLInformation.sWlanCB ) - { - tSLInformation.sWlanCB(event_type, 0, 0); - } - break; - - case HCI_EVNT_WLAN_UNSOL_DHCP: - { - UINT8 params[NETAPP_IPCONFIG_MAC_OFFSET + 1]; // extra byte is for the status - UINT8 *recParams = params; - - data = (CHAR*)(event_hdr) + HCI_EVENT_HEADER_SIZE; - - //Read IP address - STREAM_TO_STREAM(data,recParams,NETAPP_IPCONFIG_IP_LENGTH); - data += 4; - //Read subnet - STREAM_TO_STREAM(data,recParams,NETAPP_IPCONFIG_IP_LENGTH); - data += 4; - //Read default GW - STREAM_TO_STREAM(data,recParams,NETAPP_IPCONFIG_IP_LENGTH); - data += 4; - //Read DHCP server - STREAM_TO_STREAM(data,recParams,NETAPP_IPCONFIG_IP_LENGTH); - data += 4; - //Read DNS server - STREAM_TO_STREAM(data,recParams,NETAPP_IPCONFIG_IP_LENGTH); - // read the status - STREAM_TO_UINT8(event_hdr, HCI_EVENT_STATUS_OFFSET, *recParams); - - - if( tSLInformation.sWlanCB ) - { - tSLInformation.sWlanCB(event_type, (CHAR *)params, sizeof(params)); - } - } - break; - - case HCI_EVNT_WLAN_ASYNC_PING_REPORT: - { - netapp_pingreport_args_t params; - data = (CHAR*)(event_hdr) + HCI_EVENT_HEADER_SIZE; - STREAM_TO_UINT32(data, NETAPP_PING_PACKETS_SENT_OFFSET, params.packets_sent); - STREAM_TO_UINT32(data, NETAPP_PING_PACKETS_RCVD_OFFSET, params.packets_received); - STREAM_TO_UINT32(data, NETAPP_PING_MIN_RTT_OFFSET, params.min_round_time); - STREAM_TO_UINT32(data, NETAPP_PING_MAX_RTT_OFFSET, params.max_round_time); - STREAM_TO_UINT32(data, NETAPP_PING_AVG_RTT_OFFSET, params.avg_round_time); - - if( tSLInformation.sWlanCB ) - { - tSLInformation.sWlanCB(event_type, (CHAR *)¶ms, sizeof(params)); - } - } - break; - case HCI_EVNT_BSD_TCP_CLOSE_WAIT: - { - data = (CHAR *)(event_hdr) + HCI_EVENT_HEADER_SIZE; - if( tSLInformation.sWlanCB ) - { - //data[0] represents the socket id, for which FIN was received by remote. - //Upon receiving this event, the user can close the socket, or else the - //socket will be closded after inacvitity timeout (by default 60 seconds) - tSLInformation.sWlanCB(event_type, data, 1); - } - } - break; - - //'default' case which means "event not supported" - default: - return (0); - } - return(1); - } - - if ((event_type == HCI_EVNT_SEND) || (event_type == HCI_EVNT_SENDTO) - || (event_type == HCI_EVNT_WRITE)) - { - CHAR *pArg; - INT32 status; - - pArg = M_BSD_RESP_PARAMS_OFFSET(event_hdr); - STREAM_TO_UINT32(pArg, BSD_RSP_PARAMS_STATUS_OFFSET,status); - - if (ERROR_SOCKET_INACTIVE == status) - { - // The only synchronous event that can come from SL device in form of - // command complete is "Command Complete" on data sent, in case SL device - // was unable to transmit - STREAM_TO_UINT8(event_hdr, HCI_EVENT_STATUS_OFFSET, tSLInformation.slTransmitDataError); - update_socket_active_status(M_BSD_RESP_PARAMS_OFFSET(event_hdr)); - - return (1); - } - else - return (0); - } - - //handle a case where unsolicited event arrived, but was not handled by any of the cases above - if ((event_type != tSLInformation.usRxEventOpcode) && (event_type != HCI_EVNT_PATCHES_REQ)) - { - return(1); - } - - return(0); -} - -//***************************************************************************** -// -//! hci_unsolicited_event_handler -//! -//! @param None -//! -//! @return ESUCCESS if successful, EFAIL if an error occurred -//! -//! @brief Parse the incoming unsolicited event packets and issues -//! corresponding event handler. -// -//***************************************************************************** -INT32 hci_unsolicited_event_handler(void) -{ - UINT32 res = 0; - UINT8 *pucReceivedData; - - if (tSLInformation.usEventOrDataReceived != 0) - { - pucReceivedData = (tSLInformation.pucReceivedData); - - if (*pucReceivedData == HCI_TYPE_EVNT) - { - - // In case unsolicited event received - here the handling finished - if (hci_unsol_event_handler((CHAR *)pucReceivedData) == 1) - { - - // There was an unsolicited event received - we can release the buffer - // and clean the event received - tSLInformation.usEventOrDataReceived = 0; - - res = 1; - SpiResumeSpi(); - } - } - } - - return res; -} - -//***************************************************************************** -// -//! set_socket_active_status -//! -//! @param Sd -//! @param Status -//! @return none -//! -//! @brief Check if the socket ID and status are valid and set -//! accordingly the global socket status -// -//***************************************************************************** -void set_socket_active_status(INT32 Sd, INT32 Status) -{ - if(M_IS_VALID_SD(Sd) && M_IS_VALID_STATUS(Status)) - { - socket_active_status &= ~(1 << Sd); /* clean socket's mask */ - socket_active_status |= (Status << Sd); /* set new socket's mask */ - } -} - - -//***************************************************************************** -// -//! hci_event_unsol_flowcontrol_handler -//! -//! @param pEvent pointer to the string contains parameters for IPERF -//! @return ESUCCESS if successful, EFAIL if an error occurred -//! -//! @brief Called in case unsolicited event from type -//! HCI_EVNT_DATA_UNSOL_FREE_BUFF has received. -//! Keep track on the number of packets transmitted and update the -//! number of free buffer in the SL device. -// -//***************************************************************************** -INT32 hci_event_unsol_flowcontrol_handler(CHAR *pEvent) -{ - - INT32 temp, value; - UINT16 i; - UINT16 pusNumberOfHandles=0; - CHAR *pReadPayload; - - STREAM_TO_UINT16((CHAR *)pEvent,HCI_EVENT_HEADER_SIZE,pusNumberOfHandles); - pReadPayload = ((CHAR *)pEvent + - HCI_EVENT_HEADER_SIZE + sizeof(pusNumberOfHandles)); - temp = 0; - - for(i = 0; i < pusNumberOfHandles ; i++) - { - STREAM_TO_UINT16(pReadPayload, FLOW_CONTROL_EVENT_FREE_BUFFS_OFFSET, value); - temp += value; - pReadPayload += FLOW_CONTROL_EVENT_SIZE; - } - - tSLInformation.usNumberOfFreeBuffers += temp; - tSLInformation.NumberOfReleasedPackets += temp; - - return(ESUCCESS); -} - -//***************************************************************************** -// -//! get_socket_active_status -//! -//! @param Sd Socket IS -//! @return Current status of the socket. -//! -//! @brief Retrieve socket status -// -//***************************************************************************** - -INT32 get_socket_active_status(INT32 Sd) -{ - if(M_IS_VALID_SD(Sd)) - { - return (socket_active_status & (1 << Sd)) ? SOCKET_STATUS_INACTIVE : SOCKET_STATUS_ACTIVE; - } - return SOCKET_STATUS_INACTIVE; -} - -//***************************************************************************** -// -//! update_socket_active_status -//! -//! @param resp_params Socket IS -//! @return Current status of the socket. -//! -//! @brief Retrieve socket status -// -//***************************************************************************** -void update_socket_active_status(CHAR *resp_params) -{ - INT32 status, sd; - - STREAM_TO_UINT32(resp_params, BSD_RSP_PARAMS_SOCKET_OFFSET,sd); - STREAM_TO_UINT32(resp_params, BSD_RSP_PARAMS_STATUS_OFFSET,status); - - if(ERROR_SOCKET_INACTIVE == status) - { - set_socket_active_status(sd, SOCKET_STATUS_INACTIVE); - } -} - - -//***************************************************************************** -// -//! SimpleLinkWaitEvent -//! -//! @param usOpcode command operation code -//! @param pRetParams command return parameters -//! -//! @return none -//! -//! @brief Wait for event, pass it to the hci_event_handler and -//! update the event opcode in a global variable. -// -//***************************************************************************** - -void SimpleLinkWaitEvent(UINT16 usOpcode, void *pRetParams) -{ - // In the blocking implementation the control to caller will be returned only - // after the end of current transaction - tSLInformation.usRxEventOpcode = usOpcode; - hci_event_handler(pRetParams, 0, 0); -} - -//***************************************************************************** -// -//! SimpleLinkWaitData -//! -//! @param pBuf data buffer -//! @param from from information -//! @param fromlen from information length -//! -//! @return none -//! -//! @brief Wait for data, pass it to the hci_event_handler -//! and update in a global variable that there is -//! data to read. -// -//***************************************************************************** - -void SimpleLinkWaitData(UINT8 *pBuf, UINT8 *from, UINT8 *fromlen) -{ - // In the blocking implementation the control to caller will be returned only - // after the end of current transaction, i.e. only after data will be received - tSLInformation.usRxDataPending = 1; - hci_event_handler(pBuf, from, fromlen); -} - -//***************************************************************************** -// -// Close the Doxygen group. -//! @} -// -//***************************************************************************** diff --git a/drivers/cc3000/src/hci.c b/drivers/cc3000/src/hci.c deleted file mode 100644 index 4391692b8b..0000000000 --- a/drivers/cc3000/src/hci.c +++ /dev/null @@ -1,225 +0,0 @@ -/***************************************************************************** -* -* hci.c - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ - -//***************************************************************************** -// -//! \addtogroup hci_app -//! @{ -// -//***************************************************************************** - -#include -#include "cc3000_common.h" -#include "hci.h" -#include "ccspi.h" -#include "evnt_handler.h" -#include "wlan.h" - -#define SL_PATCH_PORTION_SIZE (1000) - - -//***************************************************************************** -// -//! hci_command_send -//! -//! @param usOpcode command operation code -//! @param pucBuff pointer to the command's arguments buffer -//! @param ucArgsLength length of the arguments -//! -//! @return none -//! -//! @brief Initiate an HCI command. -// -//***************************************************************************** -UINT16 hci_command_send(UINT16 usOpcode, UINT8 *pucBuff, UINT8 ucArgsLength) -{ - UINT8 *stream; - - stream = (pucBuff + SPI_HEADER_SIZE); - - UINT8_TO_STREAM(stream, HCI_TYPE_CMND); - stream = UINT16_TO_STREAM(stream, usOpcode); - UINT8_TO_STREAM(stream, ucArgsLength); - - //Update the opcode of the event we will be waiting for - SpiWrite(pucBuff, ucArgsLength + SIMPLE_LINK_HCI_CMND_HEADER_SIZE); - - return(0); -} - -//***************************************************************************** -// -//! hci_data_send -//! -//! @param usOpcode command operation code -//! @param ucArgs pointer to the command's arguments buffer -//! @param usArgsLength length of the arguments -//! @param ucTail pointer to the data buffer -//! @param usTailLength buffer length -//! -//! @return none -//! -//! @brief Initiate an HCI data write operation -// -//***************************************************************************** -INT32 hci_data_send(UINT8 ucOpcode, - UINT8 *ucArgs, - UINT16 usArgsLength, - UINT16 usDataLength, - const UINT8 *ucTail, - UINT16 usTailLength) -{ - UINT8 *stream; - - stream = ((ucArgs) + SPI_HEADER_SIZE); - - UINT8_TO_STREAM(stream, HCI_TYPE_DATA); - UINT8_TO_STREAM(stream, ucOpcode); - UINT8_TO_STREAM(stream, usArgsLength); - stream = UINT16_TO_STREAM(stream, usArgsLength + usDataLength + usTailLength); - - // Send the packet over the SPI - SpiWrite(ucArgs, SIMPLE_LINK_HCI_DATA_HEADER_SIZE + usArgsLength + usDataLength + usTailLength); - - return(ESUCCESS); -} - - -//***************************************************************************** -// -//! hci_data_command_send -//! -//! @param usOpcode command operation code -//! @param pucBuff pointer to the data buffer -//! @param ucArgsLength arguments length -//! @param ucDataLength data length -//! -//! @return none -//! -//! @brief Prepeare HCI header and initiate an HCI data write operation -// -//***************************************************************************** -void hci_data_command_send(UINT16 usOpcode, UINT8 *pucBuff, UINT8 ucArgsLength,UINT16 ucDataLength) -{ - UINT8 *stream = (pucBuff + SPI_HEADER_SIZE); - - UINT8_TO_STREAM(stream, HCI_TYPE_DATA); - UINT8_TO_STREAM(stream, usOpcode); - UINT8_TO_STREAM(stream, ucArgsLength); - stream = UINT16_TO_STREAM(stream, ucArgsLength + ucDataLength); - - // Send the command over SPI on data channel - SpiWrite(pucBuff, ucArgsLength + ucDataLength + SIMPLE_LINK_HCI_DATA_CMND_HEADER_SIZE); - - return; -} - -//***************************************************************************** -// -//! hci_patch_send -//! -//! @param usOpcode command operation code -//! @param pucBuff pointer to the command's arguments buffer -//! @param patch pointer to patch content buffer -//! @param usDataLength data length -//! -//! @return none -//! -//! @brief Prepeare HCI header and initiate an HCI patch write operation -// -//***************************************************************************** -void hci_patch_send(UINT8 ucOpcode, UINT8 *pucBuff, CHAR *patch, UINT16 usDataLength) -{ - UINT8 *data_ptr = (pucBuff + SPI_HEADER_SIZE); - UINT16 usTransLength; - UINT8 *stream = (pucBuff + SPI_HEADER_SIZE); - - UINT8_TO_STREAM(stream, HCI_TYPE_PATCH); - UINT8_TO_STREAM(stream, ucOpcode); - stream = UINT16_TO_STREAM(stream, usDataLength + SIMPLE_LINK_HCI_PATCH_HEADER_SIZE); - - if (usDataLength <= SL_PATCH_PORTION_SIZE) - { - UINT16_TO_STREAM(stream, usDataLength); - stream = UINT16_TO_STREAM(stream, usDataLength); - memcpy((pucBuff + SPI_HEADER_SIZE) + HCI_PATCH_HEADER_SIZE, patch, usDataLength); - - // Update the opcode of the event we will be waiting for - SpiWrite(pucBuff, usDataLength + HCI_PATCH_HEADER_SIZE); - } - else - { - - usTransLength = (usDataLength/SL_PATCH_PORTION_SIZE); - UINT16_TO_STREAM(stream, usDataLength + SIMPLE_LINK_HCI_PATCH_HEADER_SIZE + usTransLength*SIMPLE_LINK_HCI_PATCH_HEADER_SIZE); - stream = UINT16_TO_STREAM(stream, SL_PATCH_PORTION_SIZE); - memcpy(pucBuff + SPI_HEADER_SIZE + HCI_PATCH_HEADER_SIZE, patch, SL_PATCH_PORTION_SIZE); - usDataLength -= SL_PATCH_PORTION_SIZE; - patch += SL_PATCH_PORTION_SIZE; - - // Update the opcode of the event we will be waiting for - SpiWrite(pucBuff, SL_PATCH_PORTION_SIZE + HCI_PATCH_HEADER_SIZE); - - while (usDataLength) - { - if (usDataLength <= SL_PATCH_PORTION_SIZE) - { - usTransLength = usDataLength; - usDataLength = 0; - - } - else - { - usTransLength = SL_PATCH_PORTION_SIZE; - usDataLength -= usTransLength; - } - - *(UINT16 *)data_ptr = usTransLength; - memcpy(data_ptr + SIMPLE_LINK_HCI_PATCH_HEADER_SIZE, patch, usTransLength); - patch += usTransLength; - - // Update the opcode of the event we will be waiting for - SpiWrite((UINT8 *)data_ptr, usTransLength + sizeof(usTransLength)); - } - } -} - -//***************************************************************************** -// -// Close the Doxygen group. -//! @} -// -// -//***************************************************************************** diff --git a/drivers/cc3000/src/inet_ntop.c b/drivers/cc3000/src/inet_ntop.c deleted file mode 100644 index 83242efa00..0000000000 --- a/drivers/cc3000/src/inet_ntop.c +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (C) 1996-2001 Internet Software Consortium. - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM - * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL - * INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, - * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING - * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, - * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION - * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include -#include "cc3000_common.h" -#include "socket.h" -#include "inet_ntop.h" - -// We can't include stdio.h because it defines _types_fd_set, but we -// need to use the CC3000 version of this type. So we must provide -// our own declaration of snprintf. Grrr. -int snprintf(char *str, size_t size, const char *fmt, ...); - -#define IN6ADDRSZ 16 -#define INADDRSZ 4 -#define INT16SZ 2 - -#define ENOSPC (28) -#define EAFNOSUPPORT (106) -#define SET_ERRNO(err) (CC3000_EXPORT(errno)=-err) - -/* - * Format an IPv4 address, more or less like inet_ntoa(). - * - * Returns `dst' (as a const) - * Note: - * - uses no statics - * - takes a unsigned char* not an in_addr as input - */ -static char *inet_ntop4 (const unsigned char *src, char *dst, size_t size) -{ - size_t len; - char tmp[sizeof "255.255.255.255"]; - - tmp[0] = '\0'; - (void)snprintf(tmp, sizeof(tmp), "%d.%d.%d.%d", - ((int)((unsigned char)src[3])) & 0xff, - ((int)((unsigned char)src[2])) & 0xff, - ((int)((unsigned char)src[1])) & 0xff, - ((int)((unsigned char)src[0])) & 0xff); - - len = strlen(tmp); - if(len == 0 || len >= size) - { - SET_ERRNO(ENOSPC); - return (NULL); - } - strcpy(dst, tmp); - return dst; -} - -#ifdef ENABLE_IPV6 -/* - * Convert IPv6 binary address into presentation (printable) format. - */ -static char *inet_ntop6 (const unsigned char *src, char *dst, size_t size) -{ - /* - * Note that int32_t and int16_t need only be "at least" large enough - * to contain a value of the specified size. On some systems, like - * Crays, there is no such thing as an integer variable with 16 bits. - * Keep this in mind if you think this function should have been coded - * to use pointer overlays. All the world's not a VAX. - */ - char tmp[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")]; - char *tp; - struct { - long base; - long len; - } best, cur; - unsigned long words[IN6ADDRSZ / INT16SZ]; - int i; - - /* Preprocess: - * Copy the input (bytewise) array into a wordwise array. - * Find the longest run of 0x00's in src[] for :: shorthanding. - */ - memset(words, '\0', sizeof(words)); - for (i = 0; i < IN6ADDRSZ; i++) - words[i/2] |= (src[i] << ((1 - (i % 2)) << 3)); - - best.base = -1; - cur.base = -1; - best.len = 0; - cur.len = 0; - - for (i = 0; i < (IN6ADDRSZ / INT16SZ); i++) - { - if(words[i] == 0) - { - if(cur.base == -1) - cur.base = i, cur.len = 1; - else - cur.len++; - } - else if(cur.base != -1) - { - if(best.base == -1 || cur.len > best.len) - best = cur; - cur.base = -1; - } - } - if((cur.base != -1) && (best.base == -1 || cur.len > best.len)) - best = cur; - if(best.base != -1 && best.len < 2) - best.base = -1; - - /* Format the result. - */ - tp = tmp; - for (i = 0; i < (IN6ADDRSZ / INT16SZ); i++) - { - /* Are we inside the best run of 0x00's? - */ - if(best.base != -1 && i >= best.base && i < (best.base + best.len)) - { - if(i == best.base) - *tp++ = ':'; - continue; - } - - /* Are we following an initial run of 0x00s or any real hex? - */ - if(i != 0) - *tp++ = ':'; - - /* Is this address an encapsulated IPv4? - */ - if(i == 6 && best.base == 0 && - (best.len == 6 || (best.len == 5 && words[5] == 0xffff))) - { - if(!inet_ntop4(src+12, tp, sizeof(tmp) - (tp - tmp))) - { - SET_ERRNO(ENOSPC); - return (NULL); - } - tp += strlen(tp); - break; - } - tp += snprintf(tp, 5, "%lx", words[i]); - } - - /* Was it a trailing run of 0x00's? - */ - if(best.base != -1 && (best.base + best.len) == (IN6ADDRSZ / INT16SZ)) - *tp++ = ':'; - *tp++ = '\0'; - - /* Check for overflow, copy, and we're done. - */ - if((size_t)(tp - tmp) > size) - { - SET_ERRNO(ENOSPC); - return (NULL); - } - strcpy(dst, tmp); - return dst; -} -#endif /* ENABLE_IPV6 */ - -/* - * Convert a network format address to presentation format. - * - * Returns pointer to presentation format address (`buf'). - * Returns NULL on error and errno set with the specific - * error, EAFNOSUPPORT or ENOSPC. - * - * On Windows we store the error in the thread errno, not - * in the winsock error code. This is to avoid loosing the - * actual last winsock error. So use macro ERRNO to fetch the - * errno this funtion sets when returning NULL, not SOCKERRNO. - */ -char *inet_ntop(int af, const void *src, char *buf, size_t size) -{ - switch (af) { - case AF_INET: - return inet_ntop4((const unsigned char*)src, buf, size); -#ifdef ENABLE_IPV6 - case AF_INET6: - return inet_ntop6((const unsigned char*)src, buf, size); -#endif - default: - SET_ERRNO(EAFNOSUPPORT); - return NULL; - } -} diff --git a/drivers/cc3000/src/inet_pton.c b/drivers/cc3000/src/inet_pton.c deleted file mode 100644 index 5f5ae5f9d7..0000000000 --- a/drivers/cc3000/src/inet_pton.c +++ /dev/null @@ -1,216 +0,0 @@ -/* This is from the BIND 4.9.4 release, modified to compile by itself */ - -/* Copyright (c) 1996 by Internet Software Consortium. - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS - * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE - * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR - * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS - * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS - * SOFTWARE. - */ - -#include -#include "cc3000_common.h" -#include "socket.h" -#include "inet_pton.h" - -#define IN6ADDRSZ 16 -#define INADDRSZ 4 -#define INT16SZ 2 - -static int inet_pton4(const char *src, unsigned char *dst); -#ifdef ENABLE_IPV6 -static int inet_pton6(const char *src, unsigned char *dst); -#endif - -#define EAFNOSUPPORT (106) -#define SET_ERRNO(err) (CC3000_EXPORT(errno)=-err) - -/* int - * inet_pton(af, src, dst) - * convert from presentation format (which usually means ASCII printable) - * to network format (which is usually some kind of binary format). - * return: - * 1 if the address was valid for the specified address family - * 0 if the address wasn't valid (`dst' is untouched in this case) - * -1 if some other error occurred (`dst' is untouched in this case, too) - * notice: - * On Windows we store the error in the thread errno, not - * in the winsock error code. This is to avoid loosing the - * actual last winsock error. So use macro ERRNO to fetch the - * errno this funtion sets when returning (-1), not SOCKERRNO. - * author: - * Paul Vixie, 1996. - */ -int inet_pton(int af, const char *src, void *dst) -{ - switch (af) { - case AF_INET: - return (inet_pton4(src, (unsigned char *)dst)); -#ifdef ENABLE_IPV6 - case AF_INET6: - return (inet_pton6(src, (unsigned char *)dst)); -#endif - default: - SET_ERRNO(EAFNOSUPPORT); - return (-1); - } - /* NOTREACHED */ -} - -/* int - * inet_pton4(src, dst) - * like inet_aton() but without all the hexadecimal and shorthand. - * return: - * 1 if `src' is a valid dotted quad, else 0. - * notice: - * does not touch `dst' unless it's returning 1. - * author: - * Paul Vixie, 1996. - */ -static int inet_pton4(const char *src, unsigned char *dst) -{ - static const char digits[] = "0123456789"; - int saw_digit, octets, ch; - unsigned char tmp[INADDRSZ], *tp; - - saw_digit = 0; - octets = 0; - tp = tmp; - *tp = 0; - while((ch = *src++) != '\0') { - const char *pch; - - if((pch = strchr(digits, ch)) != NULL) { - unsigned int val = *tp * 10 + (unsigned int)(pch - digits); - - if(saw_digit && *tp == 0) - return (0); - if(val > 255) - return (0); - *tp = (unsigned char)val; - if(! saw_digit) { - if(++octets > 4) - return (0); - saw_digit = 1; - } - } - else if(ch == '.' && saw_digit) { - if(octets == 4) - return (0); - *++tp = 0; - saw_digit = 0; - } - else - return (0); - } - if(octets < 4) - return (0); - memcpy(dst, tmp, INADDRSZ); - return (1); -} - -#ifdef ENABLE_IPV6 -/* int - * inet_pton6(src, dst) - * convert presentation level address to network order binary form. - * return: - * 1 if `src' is a valid [RFC1884 2.2] address, else 0. - * notice: - * (1) does not touch `dst' unless it's returning 1. - * (2) :: in a full address is silently ignored. - * credit: - * inspired by Mark Andrews. - * author: - * Paul Vixie, 1996. - */ -static int inet_pton6(const char *src, unsigned char *dst) -{ - static const char xdigits_l[] = "0123456789abcdef", - xdigits_u[] = "0123456789ABCDEF"; - unsigned char tmp[IN6ADDRSZ], *tp, *endp, *colonp; - const char *xdigits, *curtok; - int ch, saw_xdigit; - unsigned int val; - - memset((tp = tmp), 0, IN6ADDRSZ); - endp = tp + IN6ADDRSZ; - colonp = NULL; - /* Leading :: requires some special handling. */ - if(*src == ':') - if(*++src != ':') - return (0); - curtok = src; - saw_xdigit = 0; - val = 0; - while((ch = *src++) != '\0') { - const char *pch; - - if((pch = strchr((xdigits = xdigits_l), ch)) == NULL) - pch = strchr((xdigits = xdigits_u), ch); - if(pch != NULL) { - val <<= 4; - val |= (pch - xdigits); - if(++saw_xdigit > 4) - return (0); - continue; - } - if(ch == ':') { - curtok = src; - if(!saw_xdigit) { - if(colonp) - return (0); - colonp = tp; - continue; - } - if(tp + INT16SZ > endp) - return (0); - *tp++ = (unsigned char) (val >> 8) & 0xff; - *tp++ = (unsigned char) val & 0xff; - saw_xdigit = 0; - val = 0; - continue; - } - if(ch == '.' && ((tp + INADDRSZ) <= endp) && - inet_pton4(curtok, tp) > 0) { - tp += INADDRSZ; - saw_xdigit = 0; - break; /* '\0' was seen by inet_pton4(). */ - } - return (0); - } - if(saw_xdigit) { - if(tp + INT16SZ > endp) - return (0); - *tp++ = (unsigned char) (val >> 8) & 0xff; - *tp++ = (unsigned char) val & 0xff; - } - if(colonp != NULL) { - /* - * Since some memmove()'s erroneously fail to handle - * overlapping regions, we'll do the shift by hand. - */ - const long n = tp - colonp; - long i; - - if(tp == endp) - return (0); - for (i = 1; i <= n; i++) { - endp[- i] = colonp[n - i]; - colonp[n - i] = 0; - } - tp = endp; - } - if(tp != endp) - return (0); - memcpy(dst, tmp, IN6ADDRSZ); - return (1); -} -#endif /* ENABLE_IPV6 */ diff --git a/drivers/cc3000/src/netapp.c b/drivers/cc3000/src/netapp.c deleted file mode 100644 index a6f60feda0..0000000000 --- a/drivers/cc3000/src/netapp.c +++ /dev/null @@ -1,459 +0,0 @@ -/***************************************************************************** -* -* netapp.c - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ - -#include -#include "netapp.h" -#include "hci.h" -#include "socket.h" -#include "evnt_handler.h" -#include "nvmem.h" - -#define MIN_TIMER_VAL_SECONDS 10 -#define MIN_TIMER_SET(t) if ((0 != t) && (t < MIN_TIMER_VAL_SECONDS)) \ - { \ - t = MIN_TIMER_VAL_SECONDS; \ - } - - -#define NETAPP_DHCP_PARAMS_LEN (20) -#define NETAPP_SET_TIMER_PARAMS_LEN (20) -#define NETAPP_SET_DEBUG_LEVEL_PARAMS_LEN (4) -#define NETAPP_PING_SEND_PARAMS_LEN (16) - - -//***************************************************************************** -// -//! netapp_config_mac_adrress -//! -//! @param mac device mac address, 6 bytes. Saved: yes -//! -//! @return return on success 0, otherwise error. -//! -//! @brief Configure device MAC address and store it in NVMEM. -//! The value of the MAC address configured through the API will -//! be stored in CC3000 non volatile memory, thus preserved -//! over resets. -// -//***************************************************************************** -INT32 netapp_config_mac_adrress(UINT8 * mac) -{ - return nvmem_set_mac_address(mac); -} - -//***************************************************************************** -// -//! netapp_dhcp -//! -//! @param aucIP device mac address, 6 bytes. Saved: yes -//! @param aucSubnetMask device mac address, 6 bytes. Saved: yes -//! @param aucDefaultGateway device mac address, 6 bytes. Saved: yes -//! @param aucDNSServer device mac address, 6 bytes. Saved: yes -//! -//! @return return on success 0, otherwise error. -//! -//! @brief netapp_dhcp is used to configure the network interface, -//! static or dynamic (DHCP).\n In order to activate DHCP mode, -//! aucIP, aucSubnetMask, aucDefaultGateway must be 0. -//! The default mode of CC3000 is DHCP mode. -//! Note that the configuration is saved in non volatile memory -//! and thus preserved over resets. -//! -//! @note If the mode is altered a reset of CC3000 device is required -//! in order to apply changes.\nAlso note that asynchronous event -//! of DHCP_EVENT, which is generated when an IP address is -//! allocated either by the DHCP server or due to static -//! allocation is generated only upon a connection to the -//! AP was established. -//! -//***************************************************************************** -INT32 netapp_dhcp(UINT32 *aucIP, UINT32 *aucSubnetMask,UINT32 *aucDefaultGateway, UINT32 *aucDNSServer) -{ - INT8 scRet; - UINT8 *ptr; - UINT8 *args; - - scRet = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in temporary command buffer - ARRAY_TO_STREAM(args,aucIP,4); - ARRAY_TO_STREAM(args,aucSubnetMask,4); - ARRAY_TO_STREAM(args,aucDefaultGateway,4); - args = UINT32_TO_STREAM(args, 0); - ARRAY_TO_STREAM(args,aucDNSServer,4); - - // Initiate a HCI command - hci_command_send(HCI_NETAPP_DHCP, ptr, NETAPP_DHCP_PARAMS_LEN); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_NETAPP_DHCP, &scRet); - - return(scRet); -} - - -//***************************************************************************** -// -//! netapp_timeout_values -//! -//! @param aucDHCP DHCP lease time request, also impact -//! the DHCP renew timeout. Range: [0-0xffffffff] seconds, -//! 0 or 0xffffffff == infinity lease timeout. -//! Resolution:10 seconds. Influence: only after -//! reconnecting to the AP. -//! Minimal bound value: MIN_TIMER_VAL_SECONDS - 10 seconds. -//! The parameter is saved into the CC3000 NVMEM. -//! The default value on CC3000 is 14400 seconds. -//! -//! @param aucARP ARP refresh timeout, if ARP entry is not updated by -//! incoming packet, the ARP entry will be deleted by -//! the end of the timeout. -//! Range: [0-0xffffffff] seconds, 0 == infinity ARP timeout -//! Resolution: 10 seconds. Influence: on runtime. -//! Minimal bound value: MIN_TIMER_VAL_SECONDS - 10 seconds -//! The parameter is saved into the CC3000 NVMEM. -//! The default value on CC3000 is 3600 seconds. -//! -//! @param aucKeepalive Keepalive event sent by the end of keepalive timeout -//! Range: [0-0xffffffff] seconds, 0 == infinity timeout -//! Resolution: 10 seconds. -//! Influence: on runtime. -//! Minimal bound value: MIN_TIMER_VAL_SECONDS - 10 sec -//! The parameter is saved into the CC3000 NVMEM. -//! The default value on CC3000 is 10 seconds. -//! -//! @param aucInactivity Socket inactivity timeout, socket timeout is -//! refreshed by incoming or outgoing packet, by the -//! end of the socket timeout the socket will be closed -//! Range: [0-0xffffffff] sec, 0 == infinity timeout. -//! Resolution: 10 seconds. Influence: on runtime. -//! Minimal bound value: MIN_TIMER_VAL_SECONDS - 10 sec -//! The parameter is saved into the CC3000 NVMEM. -//! The default value on CC3000 is 60 seconds. -//! -//! @return return on success 0, otherwise error. -//! -//! @brief Set new timeout values. Function set new timeout values for: -//! DHCP lease timeout, ARP refresh timeout, keepalive event -//! timeout and socket inactivity timeout -//! -//! @note If a parameter set to non zero value which is less than 10s, -//! it will be set automatically to 10s. -//! -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -INT32 netapp_timeout_values(UINT32 *aucDHCP, UINT32 *aucARP,UINT32 *aucKeepalive, UINT32 *aucInactivity) -{ - INT8 scRet; - UINT8 *ptr; - UINT8 *args; - - scRet = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Set minimal values of timers - MIN_TIMER_SET(*aucDHCP) - MIN_TIMER_SET(*aucARP) - MIN_TIMER_SET(*aucKeepalive) - MIN_TIMER_SET(*aucInactivity) - - // Fill in temporary command buffer - args = UINT32_TO_STREAM(args, *aucDHCP); - args = UINT32_TO_STREAM(args, *aucARP); - args = UINT32_TO_STREAM(args, *aucKeepalive); - args = UINT32_TO_STREAM(args, *aucInactivity); - - // Initiate a HCI command - hci_command_send(HCI_NETAPP_SET_TIMERS, ptr, NETAPP_SET_TIMER_PARAMS_LEN); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_NETAPP_SET_TIMERS, &scRet); - - return(scRet); -} -#endif - - -//***************************************************************************** -// -//! netapp_ping_send -//! -//! @param ip destination IP address -//! @param pingAttempts number of echo requests to send -//! @param pingSize send buffer size which may be up to 1400 bytes -//! @param pingTimeout Time to wait for a response,in milliseconds. -//! -//! @return return on success 0, otherwise error. -//! -//! @brief send ICMP ECHO_REQUEST to network hosts -//! -//! @note If an operation finished successfully asynchronous ping report -//! event will be generated. The report structure is as defined -//! by structure netapp_pingreport_args_t. -//! -//! @warning Calling this function while a previous Ping Requests are in -//! progress will stop the previous ping request. -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -INT32 - netapp_ping_send(UINT32 *ip, UINT32 ulPingAttempts, UINT32 ulPingSize, UINT32 ulPingTimeout) -{ - INT8 scRet; - UINT8 *ptr, *args; - - scRet = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in temporary command buffer - args = UINT32_TO_STREAM(args, *ip); - args = UINT32_TO_STREAM(args, ulPingAttempts); - args = UINT32_TO_STREAM(args, ulPingSize); - args = UINT32_TO_STREAM(args, ulPingTimeout); - - // Initiate a HCI command - hci_command_send(HCI_NETAPP_PING_SEND, ptr, NETAPP_PING_SEND_PARAMS_LEN); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_NETAPP_PING_SEND, &scRet); - - return(scRet); -} -#endif - -//***************************************************************************** -// -//! netapp_ping_report -//! -//! @param none -//! -//! @return none -//! -//! @brief Request for ping status. This API triggers the CC3000 to send -//! asynchronous events: HCI_EVNT_WLAN_ASYNC_PING_REPORT. -//! This event will carry the report structure: -//! netapp_pingreport_args_t. This structure is filled in with ping -//! results up till point of triggering API. -//! netapp_pingreport_args_t:\n packets_sent - echo sent, -//! packets_received - echo reply, min_round_time - minimum -//! round time, max_round_time - max round time, -//! avg_round_time - average round time -//! -//! @note When a ping operation is not active, the returned structure -//! fields are 0. -//! -//***************************************************************************** - - -#ifndef CC3000_TINY_DRIVER -void netapp_ping_report() -{ - UINT8 *ptr; - ptr = tSLInformation.pucTxCommandBuffer; - INT8 scRet; - - scRet = EFAIL; - - // Initiate a HCI command - hci_command_send(HCI_NETAPP_PING_REPORT, ptr, 0); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_NETAPP_PING_REPORT, &scRet); -} -#endif - -//***************************************************************************** -// -//! netapp_ping_stop -//! -//! @param none -//! -//! @return On success, zero is returned. On error, -1 is returned. -//! -//! @brief Stop any ping request. -//! -//! -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -INT32 netapp_ping_stop() -{ - INT8 scRet; - UINT8 *ptr; - - scRet = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - - // Initiate a HCI command - hci_command_send(HCI_NETAPP_PING_STOP, ptr, 0); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_NETAPP_PING_STOP, &scRet); - - return(scRet); -} -#endif - -//***************************************************************************** -// -//! netapp_ipconfig -//! -//! @param[out] ipconfig This argument is a pointer to a -//! tNetappIpconfigRetArgs structure. This structure is -//! filled in with the network interface configuration. -//! tNetappIpconfigRetArgs:\n aucIP - ip address, -//! aucSubnetMask - mask, aucDefaultGateway - default -//! gateway address, aucDHCPServer - dhcp server address -//! aucDNSServer - dns server address, uaMacAddr - mac -//! address, uaSSID - connected AP ssid -//! -//! @return none -//! -//! @brief Obtain the CC3000 Network interface information. -//! Note that the information is available only after the WLAN -//! connection was established. Calling this function before -//! associated, will cause non-defined values to be returned. -//! -//! @note The function is useful for figuring out the IP Configuration of -//! the device when DHCP is used and for figuring out the SSID of -//! the Wireless network the device is associated with. -//! -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -void netapp_ipconfig( tNetappIpconfigRetArgs * ipconfig ) -{ - UINT8 *ptr; - - ptr = tSLInformation.pucTxCommandBuffer; - - // Initiate a HCI command - hci_command_send(HCI_NETAPP_IPCONFIG, ptr, 0); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_NETAPP_IPCONFIG, ipconfig ); - -} -#else -void netapp_ipconfig( tNetappIpconfigRetArgs * ipconfig ) -{ - -} -#endif - -//***************************************************************************** -// -//! netapp_arp_flush -//! -//! @param none -//! -//! @return none -//! -//! @brief Flushes ARP table -//! -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -INT32 netapp_arp_flush(void) -{ - INT8 scRet; - UINT8 *ptr; - - scRet = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - - // Initiate a HCI command - hci_command_send(HCI_NETAPP_ARP_FLUSH, ptr, 0); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_NETAPP_ARP_FLUSH, &scRet); - - return(scRet); -} -#endif - -//***************************************************************************** -// -//! netapp_set_debug_level -//! -//! @param[in] level debug level. Bitwise [0-8], -//! 0(disable)or 1(enable).\n Bitwise map: 0 - Critical -//! message, 1 information message, 2 - core messages, 3 - -//! HCI messages, 4 - Network stack messages, 5 - wlan -//! messages, 6 - wlan driver messages, 7 - epprom messages, -//! 8 - general messages. Default: 0x13f. Saved: no -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Debug messages sent via the UART debug channel, this function -//! enable/disable the debug level -//! -//***************************************************************************** - - -#ifndef CC3000_TINY_DRIVER -INT32 netapp_set_debug_level(UINT32 ulLevel) -{ - INT8 scRet; - UINT8 *ptr, *args; - - scRet = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // - // Fill in temporary command buffer - // - args = UINT32_TO_STREAM(args, ulLevel); - - - // - // Initiate a HCI command - // - hci_command_send(HCI_NETAPP_SET_DEBUG_LEVEL, ptr, NETAPP_SET_DEBUG_LEVEL_PARAMS_LEN); - - // - // Wait for command complete event - // - SimpleLinkWaitEvent(HCI_NETAPP_SET_DEBUG_LEVEL, &scRet); - - return(scRet); - -} -#endif diff --git a/drivers/cc3000/src/nvmem.c b/drivers/cc3000/src/nvmem.c deleted file mode 100644 index c6e170a746..0000000000 --- a/drivers/cc3000/src/nvmem.c +++ /dev/null @@ -1,334 +0,0 @@ -/***************************************************************************** -* -* nvmem.c - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ - -//***************************************************************************** -// -//! \addtogroup nvmem_api -//! @{ -// -//***************************************************************************** - -#include -#include "nvmem.h" -#include "hci.h" -#include "socket.h" -#include "evnt_handler.h" - -//***************************************************************************** -// -// Prototypes for the structures for APIs. -// -//***************************************************************************** - -#define NVMEM_READ_PARAMS_LEN (12) -#define NVMEM_CREATE_PARAMS_LEN (8) -#define NVMEM_WRITE_PARAMS_LEN (16) - -//***************************************************************************** -// -//! nvmem_read -//! -//! @param ulFileId nvmem file id:\n -//! NVMEM_NVS_FILEID, NVMEM_NVS_SHADOW_FILEID, -//! NVMEM_WLAN_CONFIG_FILEID, NVMEM_WLAN_CONFIG_SHADOW_FILEID, -//! NVMEM_WLAN_DRIVER_SP_FILEID, NVMEM_WLAN_FW_SP_FILEID, -//! NVMEM_MAC_FILEID, NVMEM_FRONTEND_VARS_FILEID, -//! NVMEM_IP_CONFIG_FILEID, NVMEM_IP_CONFIG_SHADOW_FILEID, -//! NVMEM_BOOTLOADER_SP_FILEID, NVMEM_RM_FILEID, -//! and user files 12-15. -//! @param ulLength number of bytes to read -//! @param ulOffset ulOffset in file from where to read -//! @param buff output buffer pointer -//! -//! @return on success 0, error otherwise. -//! -//! @brief Reads data from the file referred by the ulFileId parameter. -//! Reads data from file ulOffset till length. Err if the file can't -//! be used, is invalid, or if the read is out of bounds. -//! -//***************************************************************************** - -INT32 nvmem_read(UINT32 ulFileId, UINT32 ulLength, UINT32 ulOffset, UINT8 *buff) -{ - UINT8 ucStatus = 0xFF; - UINT8 *ptr; - UINT8 *args; - - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in HCI packet structure - args = UINT32_TO_STREAM(args, ulFileId); - args = UINT32_TO_STREAM(args, ulLength); - args = UINT32_TO_STREAM(args, ulOffset); - - // Initiate a HCI command - hci_command_send(HCI_CMND_NVMEM_READ, ptr, NVMEM_READ_PARAMS_LEN); - SimpleLinkWaitEvent(HCI_CMND_NVMEM_READ, &ucStatus); - - // In case there is data - read it - even if an error code is returned - // Note: It is the user responsibility to ignore the data in case of an error code - - // Wait for the data in a synchronous way. Here we assume that the buffer is - // big enough to store also parameters of nvmem - - SimpleLinkWaitData(buff, 0, 0); - - return(ucStatus); -} - -//***************************************************************************** -// -//! nvmem_write -//! -//! @param ulFileId nvmem file id:\n -//! NVMEM_WLAN_DRIVER_SP_FILEID, NVMEM_WLAN_FW_SP_FILEID, -//! NVMEM_MAC_FILEID, NVMEM_BOOTLOADER_SP_FILEID, -//! and user files 12-15. -//! @param ulLength number of bytes to write -//! @param ulEntryOffset offset in file to start write operation from -//! @param buff data to write -//! -//! @return on success 0, error otherwise. -//! -//! @brief Write data to nvmem. -//! writes data to file referred by the ulFileId parameter. -//! Writes data to file ulOffset till ulLength.The file id will be -//! marked invalid till the write is done. The file entry doesn't -//! need to be valid - only allocated. -//! -//***************************************************************************** - -INT32 nvmem_write(UINT32 ulFileId, UINT32 ulLength, UINT32 ulEntryOffset, UINT8 *buff) -{ - INT32 iRes; - UINT8 *ptr; - UINT8 *args; - - iRes = EFAIL; - - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + SPI_HEADER_SIZE + HCI_DATA_CMD_HEADER_SIZE); - - // Fill in HCI packet structure - args = UINT32_TO_STREAM(args, ulFileId); - args = UINT32_TO_STREAM(args, 12); - args = UINT32_TO_STREAM(args, ulLength); - args = UINT32_TO_STREAM(args, ulEntryOffset); - - memcpy((ptr + SPI_HEADER_SIZE + HCI_DATA_CMD_HEADER_SIZE + - NVMEM_WRITE_PARAMS_LEN),buff,ulLength); - - // Initiate a HCI command but it will come on data channel - hci_data_command_send(HCI_CMND_NVMEM_WRITE, ptr, NVMEM_WRITE_PARAMS_LEN, - ulLength); - - SimpleLinkWaitEvent(HCI_EVNT_NVMEM_WRITE, &iRes); - - return(iRes); -} - - -//***************************************************************************** -// -//! nvmem_set_mac_address -//! -//! @param mac mac address to be set -//! -//! @return on success 0, error otherwise. -//! -//! @brief Write MAC address to EEPROM. -//! mac address as appears over the air (OUI first) -//! -//***************************************************************************** - -UINT8 nvmem_set_mac_address(UINT8 *mac) -{ - return nvmem_write(NVMEM_MAC_FILEID, MAC_ADDR_LEN, 0, mac); -} - -//***************************************************************************** -// -//! nvmem_get_mac_address -//! -//! @param[out] mac mac address -//! -//! @return on success 0, error otherwise. -//! -//! @brief Read MAC address from EEPROM. -//! mac address as appears over the air (OUI first) -//! -//***************************************************************************** - -UINT8 nvmem_get_mac_address(UINT8 *mac) -{ - return nvmem_read(NVMEM_MAC_FILEID, MAC_ADDR_LEN, 0, mac); -} - -//***************************************************************************** -// -//! nvmem_write_patch -//! -//! @param ulFileId nvmem file id:\n -//! NVMEM_WLAN_DRIVER_SP_FILEID, NVMEM_WLAN_FW_SP_FILEID, -//! @param spLength number of bytes to write -//! @param spData SP data to write -//! -//! @return on success 0, error otherwise. -//! -//! @brief program a patch to a specific file ID. -//! The SP data is assumed to be organized in 2-dimensional. -//! Each line is SP_PORTION_SIZE bytes long. Actual programming is -//! applied in SP_PORTION_SIZE bytes portions. -//! -//***************************************************************************** - -UINT8 nvmem_write_patch(UINT32 ulFileId, UINT32 spLength, const UINT8 *spData) -{ - UINT8 status = 0; - UINT16 offset = 0; - UINT8* spDataPtr = (UINT8*)spData; - - while ((status == 0) && (spLength >= SP_PORTION_SIZE)) - { - status = nvmem_write(ulFileId, SP_PORTION_SIZE, offset, spDataPtr); - offset += SP_PORTION_SIZE; - spLength -= SP_PORTION_SIZE; - spDataPtr += SP_PORTION_SIZE; - } - - if (status !=0) - { - // NVMEM error occurred - return status; - } - - if (spLength != 0) - { - // if reached here, a reminder is left - status = nvmem_write(ulFileId, spLength, offset, spDataPtr); - } - - return status; -} - -//***************************************************************************** -// -//! nvmem_read_sp_version -//! -//! @param[out] patchVer first number indicates package ID and the second -//! number indicates package build number -//! -//! @return on success 0, error otherwise. -//! -//! @brief Read patch version. read package version (WiFi FW patch, -//! driver-supplicant-NS patch, bootloader patch) -//! -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -UINT8 nvmem_read_sp_version(UINT8* patchVer) -{ - UINT8 *ptr; - // 1st byte is the status and the rest is the SP version - UINT8 retBuf[5]; - - ptr = tSLInformation.pucTxCommandBuffer; - - // Initiate a HCI command, no args are required - hci_command_send(HCI_CMND_READ_SP_VERSION, ptr, 0); - SimpleLinkWaitEvent(HCI_CMND_READ_SP_VERSION, retBuf); - - // package ID - *patchVer = retBuf[3]; - // package build number - *(patchVer+1) = retBuf[4]; - - return(retBuf[0]); -} -#endif - -//***************************************************************************** -// -//! nvmem_create_entry -//! -//! @param ulFileId nvmem file Id:\n -//! * NVMEM_AES128_KEY_FILEID: 12 -//! * NVMEM_SHARED_MEM_FILEID: 13 -//! * and fileIDs 14 and 15 -//! @param ulNewLen entry ulLength -//! -//! @return on success 0, error otherwise. -//! -//! @brief Create new file entry and allocate space on the NVMEM. -//! Applies only to user files. -//! Modify the size of file. -//! If the entry is unallocated - allocate it to size -//! ulNewLen (marked invalid). -//! If it is allocated then deallocate it first. -//! To just mark the file as invalid without resizing - -//! set ulNewLen=0. -//! -//***************************************************************************** - -INT32 nvmem_create_entry(UINT32 ulFileId, UINT32 ulNewLen) -{ - UINT8 *ptr; - UINT8 *args; - UINT8 retval; - - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in HCI packet structure - args = UINT32_TO_STREAM(args, ulFileId); - args = UINT32_TO_STREAM(args, ulNewLen); - - // Initiate a HCI command - hci_command_send(HCI_CMND_NVMEM_CREATE_ENTRY,ptr, NVMEM_CREATE_PARAMS_LEN); - - SimpleLinkWaitEvent(HCI_CMND_NVMEM_CREATE_ENTRY, &retval); - - return(retval); -} - - - -//***************************************************************************** -// -// Close the Doxygen group. -//! @} -// -//***************************************************************************** diff --git a/drivers/cc3000/src/patch.c b/drivers/cc3000/src/patch.c deleted file mode 100644 index 227be3c9f2..0000000000 --- a/drivers/cc3000/src/patch.c +++ /dev/null @@ -1,117 +0,0 @@ -/***************************************************************************** - * - * {PatchProgrammer_DR_Patch.c} - * - * Burn Patches to EEPROM - * - * Copyright (C) 2013 Texas Instruments Incorporated - http://www.ti.com/ - * ALL RIGHTS RESERVED - * - *****************************************************************************/ -// -// Service Pack version P1.13.7.15.28 - Driver patches -// This file contains the CC3K driver and firmware patches -// From CC3000-FRAM-PATCH V:1.13.7 15-MAY-2014 - -unsigned short fw_length = 5700; -unsigned short drv_length = 8024; - -const unsigned char wlan_drv_patch[8024] = { 0x00, 0x01, 0x00, 0x00, 0x50, 0x1F, 0x00, 0x00, 0xF0, 0x03, 0x18, 0x00, 0xE4, 0x62, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 , -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x7A, 0x63, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 , -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x10, 0x64, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x20, 0x0C, 0x49, 0x08, 0x60, 0x0C, 0x48, 0x19, 0x30, 0xF7, 0x46, 0x30, 0xB5, 0x05, 0x1C, 0xAC, 0x69, 0x68, 0x68, 0x5F, 0x30, 0x09, 0xD1, 0x60, 0x6B, 0x0C, 0x38, 0x01, 0x21, 0x8E, 0x46, 0x06, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x00, 0x20, 0x60, 0x63, 0xAC, 0x69, 0x6C, 0x60, 0x04, 0x48, 0x5B, 0x30, 0x30, 0xBD, 0x40, 0x3B, 0x08, 0x00, 0x49, 0xD0, 0x01, 0x00, 0x09, 0xEA, 0x02, 0x00, 0x91, 0xE1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 , -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xA6, 0x64, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 , -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x3C, 0x65, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xB5, 0x85, 0xB0, 0x05, 0x1C, 0xA8, 0x88, 0x00, 0x90, 0x28, 0x89, 0x01, 0x90, 0xE9, 0x68, 0x02, 0x91, 0x28, 0x7C, 0x03, 0x90, 0x2A, 0x6A, 0x00, 0x20, 0x17, 0x56, 0x68, 0x60, 0x00, 0x29, 0x4C, 0xD0, 0x00, 0x2F, 0x4A, 0xDC , -0xCA, 0x49, 0x0C, 0x1C, 0x08, 0x26, 0x04, 0x90, 0x21, 0x88, 0x00, 0x98, 0x81, 0x42, 0x0C, 0xD1, 0x62, 0x88, 0x01, 0x98, 0x82, 0x42, 0x08, 0xD1, 0x46, 0x20, 0x02, 0x5D, 0x03, 0x98, 0x82, 0x42, 0x03, 0xD1, 0x0E, 0x20, 0x00, 0x57, 0xB8, 0x42, 0x0A, 0xD0, 0x46, 0x20, 0x00, 0x5D, 0x11, 0x28, 0x22, 0xD1, 0x00, 0x98, 0x81, 0x42, 0x1F, 0xD1, 0x0E, 0x20, 0x00, 0x57, 0xFF, 0xFF, 0xD2, 0x65, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0xB8, 0x42, 0x1B, 0xD1, 0x04, 0x20, 0x02, 0x1C, 0x02, 0x98, 0xB9, 0x49, 0x01, 0x23, 0x9E, 0x46, 0xEC, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x00, 0x28, 0x17, 0xD0, 0x20, 0x1D, 0x02, 0x99, 0x04, 0x22, 0x01, 0x23, 0x9E, 0x46, 0xE7, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x00, 0x28, 0x0D, 0xD0, 0x46, 0x20, 0x00, 0x5D, 0x11, 0x28, 0x09, 0xD0, 0xA0, 0x6D, 0x00, 0x28, 0x06, 0xD0, 0xAC, 0x34, 0x04, 0x98, 0x01, 0x30, 0x04, 0x90, 0x01, 0x3E, 0xC1, 0xD1, 0x07, 0xE0, 0x04, 0x98, 0x00, 0x06, 0x00, 0x0E , -0xAC, 0x21, 0x41, 0x43, 0xA6, 0x48, 0x40, 0x18, 0x68, 0x60, 0xA6, 0x48, 0xAD, 0x30, 0x05, 0xB0, 0xF0, 0xBD, 0x00, 0xB5, 0xC2, 0x68, 0x90, 0x69, 0x02, 0x21, 0x01, 0x23, 0x9E, 0x46, 0xA2, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0xA2, 0x48, 0x61, 0x30, 0x00, 0xBD, 0x01, 0x79, 0x0B, 0x29, 0x03, 0xD0, 0x89, 0x00, 0x9F, 0x4A, 0x51, 0x5A, 0x01, 0xE0, 0x01, 0x21, 0x49, 0x02, 0x41, 0x60, 0x9D, 0x48, 0x0D, 0x30, 0xF7, 0x46, 0x01, 0x1C, 0xFF, 0xFF, 0x68, 0x66, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x9C, 0x48, 0x02, 0x68, 0x9C, 0x48, 0x01, 0x2A, 0x01, 0xD1, 0x25, 0x30, 0xF7, 0x46, 0x9B, 0x4A, 0x12, 0x68, 0x4A, 0x60, 0x19, 0x30, 0xF7, 0x46, 0x00, 0x21, 0x41, 0x60, 0x99, 0x48, 0x98, 0x49, 0x08, 0x18, 0xF7, 0x46, 0x00, 0x21, 0x41, 0x60, 0x97, 0x48, 0xE7, 0x49, 0x08, 0x18, 0xF7, 0x46, 0xFF, 0xB5, 0x46, 0x69, 0x40, 0x68, 0x01, 0x90, 0x94, 0x49, 0x0A, 0x7C, 0x9A, 0x4F, 0x01, 0x2A, 0x63, 0xD0, 0x09, 0x7C, 0x03, 0x29 , -0x60, 0xD0, 0x91, 0x4A, 0x92, 0x4B, 0x00, 0x21, 0x02, 0x91, 0x59, 0x56, 0x24, 0x23, 0x59, 0x43, 0x53, 0x18, 0x03, 0x93, 0x01, 0x28, 0x17, 0xD1, 0x8A, 0x18, 0x04, 0x23, 0x6C, 0x46, 0x8C, 0x49, 0x15, 0x79, 0x08, 0x78, 0xC0, 0x43, 0x28, 0x43, 0x20, 0x70, 0x01, 0x32, 0x01, 0x31, 0x01, 0x34, 0x01, 0x3B, 0xF5, 0xD1, 0x31, 0x1D, 0x68, 0x46, 0x04, 0x22, 0x01, 0x23, 0x9E, 0x46, 0xA9, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x00, 0x28, 0x40, 0xD0, 0x35, 0x1D, 0x82, 0x48, 0x00, 0x78, 0xFF, 0x28, 0xFF, 0xFF, 0xFE, 0x66, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x11, 0xD0, 0x00, 0x28, 0x0F, 0xD0, 0x03, 0x98, 0x01, 0x1D, 0x28, 0x1C, 0x01, 0x24, 0xA6, 0x46, 0x7E, 0x4A, 0xFE, 0x44, 0x10, 0x47, 0x00, 0x28, 0x05, 0xD1, 0x7A, 0x48, 0xA6, 0x46, 0x7B, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x05, 0xE0, 0x28, 0x1C, 0x01, 0x21, 0x8E, 0x46, 0x78, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x01, 0x99, 0x01, 0x29, 0x01, 0xD1, 0x00, 0x28, 0x1E, 0xD1 , -0x01, 0x99, 0x5F, 0x31, 0x01, 0xD0, 0x00, 0x28, 0x0F, 0xD1, 0xA8, 0x20, 0x81, 0x5D, 0x00, 0x29, 0x08, 0xD0, 0x49, 0x1E, 0x81, 0x55, 0x80, 0x5D, 0x00, 0x28, 0x09, 0xD1, 0x38, 0x1C, 0xFF, 0x30, 0x08, 0x30, 0x11, 0xE0, 0x03, 0x21, 0x02, 0x91, 0x00, 0xE0, 0xA8, 0x20, 0x02, 0x99, 0x81, 0x55, 0x38, 0x1C, 0xFF, 0x30, 0x16, 0x30, 0x07, 0xE0, 0x01, 0x98, 0x01, 0x28, 0x02, 0xD1, 0x38, 0x1C, 0xA3, 0x30, 0x01, 0xE0, 0x38, 0x1C, 0x9F, 0x30, 0x00, 0x90, 0xFF, 0xBD, 0x00, 0xB5, 0x02, 0x1C, 0x10, 0x6A, 0xD1, 0x69, 0x52, 0x69, 0xC3, 0x69, 0x5A, 0x60, 0xFF, 0xFF, 0x94, 0x67, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x01, 0x22, 0x96, 0x46, 0x5E, 0x4A, 0xFE, 0x44, 0x10, 0x47, 0x5E, 0x48, 0xFF, 0x30, 0x6E, 0x30, 0x00, 0xBD, 0x10, 0xB5, 0x0A, 0x1C, 0x41, 0x69, 0x00, 0x6A, 0x93, 0x69, 0xDB, 0x69, 0x58, 0x60, 0x90, 0x69, 0x01, 0x24, 0xA6, 0x46, 0x56, 0x4A, 0xFE, 0x44, 0x10, 0x47, 0xA6, 0x46, 0x56, 0x48, 0xFE, 0x44 , -0x00, 0x47, 0x55, 0x48, 0xFF, 0x30, 0xB6, 0x30, 0x10, 0xBD, 0x70, 0xB5, 0x05, 0x1C, 0x6E, 0x69, 0x53, 0x48, 0x02, 0x68, 0x5C, 0x21, 0x88, 0x5D, 0x04, 0x28, 0x15, 0xD1, 0x07, 0x20, 0x88, 0x55, 0x10, 0x0B, 0x11, 0xD2, 0x01, 0x24, 0xA6, 0x46, 0x4E, 0x48, 0xFE, 0x44, 0x00, 0x47, 0x00, 0x28, 0x0A, 0xD0, 0x47, 0x21, 0x89, 0x57, 0xC1, 0x60, 0x11, 0x21, 0xC9, 0x02, 0x00, 0x22, 0x04, 0x23, 0xA6, 0x46, 0xE8, 0x4C, 0xFE, 0x44, 0x20, 0x47, 0x01, 0x20, 0x68, 0x60, 0x43, 0x48, 0xED, 0x49, 0x08, 0x18, 0x70, 0xBD, 0x70, 0xB5, 0x05, 0x1C, 0xAE, 0x69, 0x9C, 0x20, 0x80, 0x19, 0x4B, 0x21, 0x89, 0x00, 0x01, 0x24, 0xFF, 0xFF, 0x2A, 0x68, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0xA6, 0x46, 0xE8, 0x4A, 0xFE, 0x44, 0x10, 0x47, 0x5C, 0x21, 0x88, 0x5D, 0x07, 0x28, 0x01, 0xD1, 0x09, 0x20, 0x00, 0xE0, 0x05, 0x20, 0xAA, 0x69, 0x88, 0x54, 0x30, 0x1C, 0xA6, 0x46, 0xE9, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x68, 0x60, 0xE8, 0x48 , -0x4D, 0x30, 0x70, 0xBD, 0xF0, 0xB5, 0x41, 0x68, 0x82, 0x68, 0x88, 0x23, 0x5E, 0x18, 0x37, 0x88, 0x0B, 0x6F, 0x00, 0x2B, 0x01, 0xD1, 0x00, 0x2F, 0x10, 0xD1, 0x06, 0x2F, 0x02, 0xDD, 0x00, 0x21, 0xC9, 0x43, 0x07, 0xE0, 0x33, 0x88, 0x9B, 0x00, 0xC9, 0x18, 0x0A, 0x67, 0x31, 0x88, 0x01, 0x31, 0x31, 0x80, 0x01, 0x21, 0x81, 0x60, 0xE1, 0x48, 0x1D, 0x30, 0xF0, 0xBD, 0x0B, 0x1C, 0x01, 0x24, 0x5D, 0x6F, 0x1D, 0x67, 0x04, 0x33, 0x01, 0x34, 0x06, 0x2C, 0xE1, 0xDA, 0xF8, 0xE7, 0x00, 0xB5, 0x00, 0x21, 0xC1, 0x60, 0xE9, 0x48, 0x01, 0x68, 0x10, 0x31, 0xE6, 0x48, 0x20, 0x22, 0x01, 0x23, 0x9E, 0x46, 0xE7, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0xE5, 0x48, 0xFB, 0x30, 0x00, 0xBD, 0xFF, 0xFF, 0xC0, 0x68, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x14, 0x0D, 0x1B, 0x00, 0x54, 0x19, 0x1B, 0x00, 0x91, 0x1A, 0x01, 0x00, 0x4B, 0xAD, 0x03, 0x00, 0x61, 0x4E, 0x01, 0x00, 0x06, 0x32, 0x08, 0x00, 0x1F, 0x0B, 0x02, 0x00, 0x54, 0x3F , -0x08, 0x00, 0x45, 0xC1, 0x00, 0x00, 0x84, 0x3C, 0x08, 0x00, 0x1B, 0x02, 0x00, 0x00, 0xED, 0x17, 0x00, 0x00, 0xF3, 0xC1, 0x01, 0x00, 0x34, 0x19, 0x1B, 0x00, 0x08, 0x19, 0x1B, 0x00, 0xA6, 0x44, 0x08, 0x00, 0x1C, 0x17, 0x1B, 0x00, 0x18, 0x17, 0x1B, 0x00, 0xCB, 0x67, 0x03, 0x00, 0x0D, 0x47, 0x02, 0x00, 0x39, 0x42, 0x03, 0x00, 0xBD, 0xE7, 0x02, 0x00, 0xB1, 0x40, 0x03, 0x00, 0xB9, 0xEA, 0x01, 0x00, 0x45, 0xDA, 0x00, 0x00, 0x24, 0x41, 0x08, 0x00, 0x71, 0xC0, 0x02, 0x00, 0xF0, 0xB5, 0x88, 0xB0, 0x06, 0x91, 0x07, 0x90, 0x86, 0x69, 0xF0, 0x1C, 0xD9, 0xA1, 0x04, 0x22, 0x01, 0x24, 0xA6, 0x46, 0x14, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x00, 0x28, 0x32, 0xD1, 0xF2, 0x79, 0xD7, 0x48, 0x02, 0x70, 0x35, 0x7A, 0x77, 0x7A, 0x78, 0x1B, 0xFF, 0xFF, 0x56, 0x69, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x43, 0x1C, 0x93, 0x42, 0x1D, 0xD0, 0x16, 0x2A, 0x0C, 0xDB, 0x00, 0x2D, 0x0A, 0xD1, 0xD6, 0x48, 0x04, 0x70, 0x0A, 0x20 , -0x81, 0x19, 0xD0, 0x48, 0x1A, 0x1C, 0xA6, 0x46, 0xB8, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x74, 0xE0, 0xD2, 0x48, 0x04, 0x70, 0xCC, 0x48, 0x40, 0x19, 0x0A, 0x21, 0x89, 0x19, 0x7A, 0x1B, 0x52, 0x1C, 0xA6, 0x46, 0xB1, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x67, 0xE0, 0x8F, 0xC6, 0x03, 0x00, 0xC9, 0x48, 0x04, 0x70, 0xC9, 0x48, 0x04, 0x70, 0x0A, 0x20, 0x81, 0x19, 0xC2, 0x48, 0xA6, 0x46, 0xAA, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x59, 0xE0, 0xF0, 0x1C, 0x03, 0x21, 0x0A, 0x1C, 0xBC, 0xA1, 0xA6, 0x46, 0xC6, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x00, 0x28, 0x4F, 0xD1, 0xF1, 0x79, 0xBB, 0x48, 0x01, 0x70, 0xBB, 0x4D, 0xB2, 0x79, 0x2A, 0x70, 0x03, 0x20, 0x17, 0x49, 0xF4, 0x31, 0xA6, 0x46, 0xB8, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x28, 0x78, 0x00, 0x28, 0x0B, 0xD1, 0xFF, 0xE7, 0xB8, 0x49, 0x0C, 0x70, 0xB8, 0x49, 0xFF, 0xFF, 0xEC, 0x69, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x0C, 0x70, 0x03, 0x20, 0x0F, 0x49, 0xF5, 0x31, 0xA6, 0x46 , -0xB6, 0x4A, 0xFE, 0x44, 0x10, 0x47, 0x20, 0x1C, 0xF2, 0x79, 0x35, 0x7A, 0x77, 0x7A, 0x79, 0x1B, 0x4B, 0x1C, 0x93, 0x42, 0x20, 0xD0, 0xA9, 0x49, 0x09, 0x78, 0x16, 0x29, 0x0F, 0xDB, 0x00, 0x2D, 0x0D, 0xD1, 0xAB, 0x49, 0x08, 0x70, 0x0A, 0x20, 0x81, 0x19, 0xE9, 0x48, 0x1A, 0x1C, 0xA6, 0x46, 0x8B, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x1A, 0xE0, 0xC0, 0x46, 0xC7, 0x04, 0x00, 0x00, 0xA5, 0x49, 0x08, 0x70, 0xE3, 0x48, 0x40, 0x19, 0x0A, 0x21, 0x89, 0x19, 0x7A, 0x1B, 0x52, 0x1C, 0xA6, 0x46, 0x83, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x0A, 0xE0, 0x9E, 0x49, 0x08, 0x70, 0x9E, 0x49, 0x08, 0x70, 0x0A, 0x20, 0x81, 0x19, 0xDB, 0x48, 0xA6, 0x46, 0x7D, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x96, 0x48, 0x00, 0x78, 0x00, 0x28, 0x0A, 0xD0, 0x95, 0x48, 0x00, 0x78, 0x00, 0x28, 0x06, 0xD0, 0x94, 0x48, 0x00, 0x78, 0x00, 0x28, 0x02, 0xD0, 0x93, 0x48, 0x00, 0x78, 0x00, 0x28, 0xFF, 0xFF, 0x82, 0x6A, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00 , -0x00, 0xD1, 0x8C, 0xE0, 0x03, 0x20, 0x17, 0x21, 0x89, 0x01, 0xA6, 0x46, 0x90, 0x4A, 0xFE, 0x44, 0x10, 0x47, 0x87, 0x48, 0x01, 0x78, 0x87, 0x48, 0x07, 0x78, 0x84, 0x4E, 0x83, 0x4D, 0xE0, 0x48, 0x00, 0x68, 0x00, 0x28, 0x2E, 0xD1, 0x07, 0x98, 0x41, 0x61, 0x06, 0x62, 0xC6, 0x48, 0x06, 0x9A, 0x10, 0x64, 0x02, 0x2F, 0x01, 0xD0, 0x03, 0x2F, 0x01, 0xD1, 0x03, 0x22, 0x00, 0xE0, 0x3A, 0x1C, 0x06, 0x9B, 0xDA, 0x63, 0x2A, 0x78, 0x9A, 0x63, 0x01, 0x2F, 0x03, 0xD1, 0x05, 0x29, 0x04, 0xD0, 0x0D, 0x29, 0x02, 0xD0, 0xEC, 0x48, 0xDB, 0x30, 0x64, 0xE0, 0x00, 0x25, 0x00, 0x95, 0x01, 0x91, 0x02, 0x96, 0x03, 0x95, 0x04, 0x90, 0x2B, 0x1C, 0x20, 0x1C, 0x01, 0x1C, 0x8E, 0x46, 0xE6, 0x4E, 0xFE, 0x44, 0x30, 0x47, 0xE6, 0x48, 0x04, 0x60, 0x28, 0x1C, 0xA6, 0x46, 0xE5, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x4C, 0xE0, 0x0D, 0x27, 0x00, 0x20, 0x39, 0x1C, 0x05, 0xAA, 0xA6, 0x46, 0xE3, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x68, 0x46 , -0xFF, 0xFF, 0x18, 0x6B, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x80, 0x8A, 0x40, 0x08, 0x05, 0xD2, 0x38, 0x1C, 0x50, 0x21, 0xA6, 0x46, 0xDC, 0x4A, 0xFE, 0x44, 0x10, 0x47, 0x38, 0x1C, 0x21, 0x1C, 0x0B, 0x1C, 0x29, 0x1C, 0x00, 0x22, 0xA6, 0x46, 0xD9, 0x4F, 0xFE, 0x44, 0x38, 0x47, 0x2B, 0x78, 0x0D, 0x20, 0x31, 0x1C, 0x22, 0x1C, 0xA6, 0x46, 0xD5, 0x4E, 0xFE, 0x44, 0x30, 0x47, 0x28, 0x78, 0x01, 0x30, 0x02, 0x1C, 0x0D, 0x20, 0x57, 0x49, 0x23, 0x1C, 0xA6, 0x46, 0xD0, 0x4E, 0xFE, 0x44, 0x30, 0x47, 0x55, 0x4E, 0x28, 0x78, 0x02, 0x30, 0x02, 0x1C, 0x0D, 0x20, 0x31, 0x1C, 0x23, 0x1C, 0xA6, 0x46, 0xCA, 0x4F, 0xFE, 0x44, 0x38, 0x47, 0x30, 0x78, 0x00, 0x28, 0x0A, 0xD0, 0x28, 0x78, 0x03, 0x30, 0x02, 0x1C, 0x4C, 0x48, 0x03, 0x78, 0x0D, 0x20, 0x8F, 0x49, 0xA6, 0x46, 0xC3, 0x4D, 0xFE, 0x44, 0x28, 0x47, 0xBF, 0x48, 0x04, 0x60, 0x00, 0x20, 0xA6, 0x46, 0xBE, 0x49, 0xFE, 0x44, 0x08, 0x47, 0xB9, 0x48, 0xEC, 0x49 , -0x08, 0x18, 0x08, 0xB0, 0xF0, 0xBD, 0xC0, 0x46, 0x7B, 0xC0, 0xFF, 0xFF, 0xAE, 0x6B, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x1C, 0xE9, 0x48, 0x02, 0x68, 0xE9, 0x48, 0x00, 0x2A, 0x04, 0xD0, 0x00, 0x22, 0x0A, 0x62, 0x8A, 0x61, 0x1D, 0x30, 0xF7, 0x46, 0xD7, 0x30, 0xF7, 0x46, 0xC0, 0x46, 0x9F, 0x03, 0x00, 0x00, 0x7D, 0xB8, 0x03, 0x00, 0x01, 0x1C, 0xE2, 0x48, 0x02, 0x68, 0xE2, 0x48, 0x00, 0x2A, 0x02, 0xD0, 0xFF, 0x30, 0xB4, 0x30, 0xF7, 0x46, 0x00, 0x22, 0xCA, 0x61, 0x8A, 0x61, 0x4F, 0x30, 0xF7, 0x46, 0xC9, 0x21, 0x01, 0x00, 0x91, 0xE1, 0x00, 0x00, 0xDB, 0x48, 0x01, 0x68, 0x8A, 0x69, 0x01, 0x20, 0xC0, 0x03, 0x10, 0x43, 0x88, 0x61, 0x00, 0x20, 0x08, 0x61, 0xD8, 0x48, 0x23, 0x30, 0xF7, 0x46, 0x89, 0x17, 0x02, 0x00, 0x70, 0xB5, 0x05, 0x1C, 0xD5, 0x4E, 0x29, 0x6A, 0xEA, 0x69, 0x30, 0x1C, 0x01, 0x24, 0xA6, 0x46, 0x0B, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x68, 0x69, 0xA6, 0x46, 0xD1, 0x49 , -0xFE, 0x44, 0x08, 0x47, 0xA8, 0x69, 0x06, 0x30, 0xA8, 0x60, 0xCF, 0x48, 0x00, 0x68, 0x68, 0x60, 0xEE, 0x60, 0xCE, 0x48, 0xFF, 0xFF, 0x44, 0x6C, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x6D, 0x30, 0x70, 0xBD, 0x46, 0x17, 0x1B, 0x00, 0x30, 0x3F, 0x08, 0x00, 0x41, 0xEB, 0x00, 0x00, 0x09, 0xB4, 0x03, 0x00, 0x30, 0xB5, 0xEE, 0x48, 0x01, 0x6D, 0x80, 0x6C, 0x08, 0x43, 0x18, 0xD0, 0xEC, 0x49, 0x08, 0x1C, 0x07, 0x22, 0xFF, 0x23, 0x09, 0x33, 0x1B, 0x58, 0x00, 0x2B, 0x04, 0xD0, 0xFF, 0x30, 0x1D, 0x30, 0x01, 0x3A, 0xF6, 0xD1, 0x0B, 0xE0, 0x02, 0x20, 0xF0, 0x4A, 0xF1, 0x4B, 0x01, 0x24, 0xA6, 0x46, 0xF0, 0x4D, 0xFE, 0x44, 0x28, 0x47, 0xA6, 0x46, 0xEF, 0x48, 0xFE, 0x44, 0x00, 0x47, 0xEF, 0x48, 0xFF, 0x30, 0x5C, 0x30, 0x30, 0xBD, 0xC0, 0x46, 0x53, 0x53, 0x49, 0x44, 0x00, 0xC0, 0x46, 0xC0, 0x4B, 0x45, 0x59, 0x00, 0xEE, 0x62, 0x08, 0x00, 0xF0, 0x62, 0x08, 0x00, 0xEC, 0x62, 0x08, 0x00, 0xED, 0x62, 0x08, 0x00 , -0xE7, 0x7E, 0x03, 0x00, 0xE8, 0x62, 0x08, 0x00, 0xE9, 0x62, 0x08, 0x00, 0xEA, 0x62, 0x08, 0x00, 0xEB, 0x62, 0x08, 0x00, 0xDD, 0x7E, 0x03, 0x00, 0x8F, 0xC6, 0x03, 0x00, 0xF0, 0xB5, 0xFF, 0xFF, 0xDA, 0x6C, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x87, 0xB0, 0x00, 0x91, 0x01, 0x90, 0x6B, 0x48, 0x01, 0x68, 0xCC, 0x4A, 0x14, 0x1C, 0x02, 0x94, 0x07, 0x26, 0x00, 0x25, 0x03, 0x95, 0x04, 0x94, 0x05, 0x95, 0xDF, 0x48, 0x00, 0x68, 0x08, 0x43, 0x27, 0xD0, 0xE0, 0x68, 0x03, 0x99, 0x88, 0x42, 0x0A, 0xDD, 0x03, 0x90, 0x40, 0x1C, 0x00, 0x99, 0x88, 0x60, 0xC2, 0x49, 0xFF, 0x20, 0x1D, 0x30, 0x68, 0x43, 0x0C, 0x18, 0xE0, 0x68, 0x04, 0x91, 0x02, 0x99, 0xC9, 0x68, 0x88, 0x42, 0x10, 0xDB, 0x88, 0x42, 0x10, 0xD1, 0x02, 0x98, 0x01, 0x27, 0xBE, 0x46, 0xCE, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x06, 0x90, 0x20, 0x1C, 0xBE, 0x46, 0xCB, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x06, 0x99, 0x88, 0x42, 0x01, 0xDA, 0x05, 0x95, 0x02, 0x94 , -0x51, 0x48, 0x01, 0x68, 0xFF, 0x27, 0x09, 0x37, 0x38, 0x59, 0x00, 0x28, 0x06, 0xD0, 0xC7, 0x48, 0x00, 0x68, 0x07, 0x2E, 0x00, 0xD1, 0x2E, 0x1C, 0x08, 0x43, 0x04, 0xD0, 0xFF, 0x34, 0x1D, 0x34, 0x01, 0x35, 0x07, 0x2D, 0xC2, 0xDB, 0x07, 0x2E, 0xFF, 0xFF, 0x70, 0x6D, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x0A, 0xD1, 0xC0, 0x48, 0x00, 0x68, 0x08, 0x43, 0x06, 0xD0, 0x05, 0x9E, 0x30, 0x1C, 0x01, 0x21, 0x8E, 0x46, 0xBA, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x01, 0x98, 0x47, 0x61, 0x00, 0x21, 0x81, 0x61, 0xFF, 0x22, 0x1D, 0x32, 0x72, 0x43, 0x04, 0x99, 0x89, 0x18, 0xC1, 0x61, 0x06, 0x62, 0xB4, 0x48, 0x39, 0x30, 0x07, 0xB0, 0xF0, 0xBD, 0x10, 0xB5, 0x04, 0x1C, 0x00, 0x20, 0x01, 0x21, 0x8E, 0x46, 0xB1, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x40, 0x1E, 0x00, 0xD5, 0x00, 0x20, 0x60, 0x60, 0xE0, 0x61, 0xAE, 0x48, 0x21, 0x30, 0x10, 0xBD, 0xC0, 0x46, 0x10, 0x63, 0x08, 0x00, 0x70, 0xB5, 0x04, 0x1C, 0xE5, 0x69, 0x66, 0x69 , -0x00, 0x20, 0x01, 0x21, 0x8E, 0x46, 0xA7, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x60, 0x60, 0xAB, 0x19, 0xA6, 0x4A, 0xA5, 0x49, 0x93, 0x42, 0x02, 0xD3, 0x9A, 0x1A, 0x82, 0x42, 0x02, 0xD9, 0x08, 0x1C, 0x99, 0x30, 0x70, 0xBD, 0x08, 0x1C, 0xAB, 0x30, 0x70, 0xBD, 0x08, 0x6B, 0x41, 0x7D, 0x02, 0x88, 0x92, 0x00, 0xFF, 0xFF, 0x06, 0x6E, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x51, 0x1A, 0x3C, 0x39, 0xFF, 0x22, 0x5F, 0x32, 0x91, 0x42, 0x03, 0xD9, 0x65, 0x21, 0x01, 0x80, 0x02, 0x21, 0x81, 0x73, 0x9B, 0x48, 0x99, 0x49, 0x08, 0x18, 0xF7, 0x46, 0xC0, 0x46, 0x30, 0x63, 0x08, 0x00, 0xF8, 0xB5, 0x40, 0x68, 0x24, 0x21, 0x41, 0x43, 0x97, 0x48, 0x45, 0x18, 0x28, 0x1D, 0x0C, 0x21, 0x49, 0x19, 0x04, 0x22, 0x01, 0x23, 0x9E, 0x46, 0x94, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x91, 0x4C, 0x00, 0x28, 0x1B, 0xD0, 0x2B, 0x1C, 0x04, 0x22, 0x6E, 0x46, 0x91, 0x49, 0x1F, 0x7B, 0x08, 0x78, 0xC0, 0x43, 0x38, 0x43, 0x30, 0x70, 0x01, 0x33 , -0x01, 0x31, 0x01, 0x36, 0x01, 0x3A, 0xF5, 0xD1, 0x0C, 0x20, 0x41, 0x19, 0x68, 0x46, 0x04, 0x22, 0x01, 0x23, 0x9E, 0x46, 0x87, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x00, 0x28, 0x02, 0xD0, 0x20, 0x1C, 0x4A, 0x30, 0xF8, 0xBD, 0x20, 0x1C, 0xF8, 0xBD, 0xB1, 0xBD, 0x00, 0x00, 0x15, 0x95, 0x00, 0x00, 0x58, 0x3F, 0x08, 0x00, 0xF3, 0xF8, 0x00, 0x00, 0xE9, 0x09, 0x02, 0x00, 0xFF, 0xFF, 0x9C, 0x6E, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x2B, 0x09, 0x02, 0x00, 0xDD, 0x0A, 0x02, 0x00, 0xF8, 0xB5, 0x05, 0x1C, 0xAA, 0x69, 0x7D, 0x49, 0x00, 0x20, 0x08, 0x56, 0x24, 0x21, 0x41, 0x43, 0x76, 0x48, 0x43, 0x18, 0x04, 0x24, 0x6E, 0x46, 0x76, 0x49, 0x1F, 0x79, 0x08, 0x78, 0xC0, 0x43, 0x38, 0x43, 0x30, 0x70, 0x01, 0x33, 0x01, 0x31, 0x01, 0x36, 0x01, 0x3C, 0xF5, 0xD1, 0x11, 0x1D, 0x68, 0x46, 0x04, 0x22, 0x01, 0x24, 0xA6, 0x46, 0x6D, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x01, 0x1C, 0x6D, 0x48, 0x04, 0xD0, 0x6E, 0x49, 0x09, 0x78 , -0x69, 0x60, 0x45, 0x30, 0xF8, 0xBD, 0xEC, 0x61, 0xAF, 0x30, 0xF8, 0xBD, 0x70, 0xB5, 0xC5, 0x68, 0x81, 0x68, 0x0A, 0x89, 0x6D, 0x4E, 0x00, 0x2A, 0x22, 0xD0, 0x01, 0x24, 0xC2, 0x6D, 0xA2, 0x18, 0xC2, 0x65, 0x08, 0x89, 0x0D, 0x28, 0x1B, 0xD1, 0x68, 0x6B, 0x21, 0x1C, 0xA6, 0x46, 0x63, 0x4A, 0xFE, 0x44, 0x10, 0x47, 0x22, 0x1C, 0x28, 0x1C, 0x00, 0x21, 0xA6, 0x46, 0x60, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x2C, 0x60, 0xE9, 0x6B, 0xFF, 0xFF, 0x32, 0x6F, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x28, 0x1C, 0xA6, 0x46, 0x5E, 0x4A, 0xFE, 0x44, 0x10, 0x47, 0x28, 0x1C, 0xA6, 0x46, 0x5C, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x30, 0x1C, 0x3D, 0x30, 0x70, 0xBD, 0x30, 0x1C, 0x23, 0x30, 0x70, 0xBD, 0xC0, 0x46, 0xB1, 0x02, 0x00, 0x00, 0x74, 0x3F, 0x08, 0x00, 0x19, 0xC6, 0x00, 0x00, 0x5C, 0x3F, 0x08, 0x00, 0x1D, 0xC2, 0x00, 0x00, 0x68, 0x44, 0x08, 0x00, 0x43, 0x12, 0x03, 0x00, 0x34, 0x63, 0x08, 0x00, 0x2F, 0x7A, 0x02, 0x00 , -0xB4, 0x36, 0x08, 0x00, 0x8F, 0xF4, 0x01, 0x00, 0xF0, 0xB5, 0x05, 0x1C, 0xAB, 0x69, 0xEC, 0x69, 0x60, 0x68, 0x00, 0x68, 0x2A, 0x30, 0x01, 0x78, 0x0A, 0x06, 0x41, 0x78, 0x09, 0x04, 0x8A, 0x18, 0x81, 0x78, 0x09, 0x02, 0x8A, 0x18, 0xC1, 0x78, 0x8A, 0x18, 0x8E, 0x26, 0xF1, 0x5A, 0x09, 0x0A, 0x01, 0x70, 0xF0, 0x5C, 0x61, 0x68, 0x09, 0x68, 0x2B, 0x26, 0x70, 0x54, 0x8C, 0x20, 0xC0, 0x18, 0x61, 0x68, 0x0E, 0x68, 0x01, 0x88, 0x09, 0x0A, 0x2C, 0x27, 0xB9, 0x55, 0x61, 0x68, 0x09, 0x68, 0xFF, 0xFF, 0xC8, 0x6F, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x2D, 0x26, 0x00, 0x78, 0x70, 0x54, 0x60, 0x68, 0x01, 0x68, 0x32, 0x31, 0x08, 0x78, 0x00, 0x02, 0x49, 0x78, 0x08, 0x18, 0x00, 0x04, 0x00, 0x0C, 0x8C, 0x21, 0xCB, 0x58, 0x35, 0x49, 0x41, 0x40, 0x08, 0x04, 0x00, 0x0C, 0xC0, 0x18, 0x80, 0x1A, 0x01, 0x21, 0x8E, 0x46, 0x32, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x61, 0x68, 0x0A, 0x68, 0x32, 0x23, 0x01, 0x0A, 0x99, 0x54 , -0x61, 0x68, 0x09, 0x68, 0x33, 0x22, 0x50, 0x54, 0x60, 0x68, 0x68, 0x60, 0x2C, 0x48, 0xF0, 0xBD, 0x00, 0x00, 0x1B, 0x00, 0x34, 0x04, 0x1B, 0x00, 0x02, 0x6A, 0x8B, 0x69, 0xDB, 0x69, 0x1B, 0x68, 0x83, 0x60, 0x88, 0x69, 0xC0, 0x69, 0x41, 0x68, 0x8A, 0x42, 0x00, 0xDA, 0x42, 0x60, 0x25, 0x48, 0x79, 0x30, 0xF7, 0x46, 0x24, 0x48, 0x57, 0x30, 0xF7, 0x46, 0x24, 0x48, 0x91, 0x30, 0xF7, 0x46, 0x32, 0x04, 0x00, 0x00, 0xC4, 0x07, 0x00, 0x00, 0x15, 0x09, 0x02, 0x00, 0xC5, 0x93, 0x00, 0x00, 0x0D, 0x91, 0x00, 0x00, 0x40, 0x1E, 0x80, 0x00, 0x1E, 0x4B, 0xFF, 0xFF, 0x5E, 0x70, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x19, 0x50, 0x1C, 0x49, 0x0A, 0x50, 0xF7, 0x46, 0xC0, 0x46, 0xBD, 0xB5, 0x00, 0x00, 0x95, 0x92, 0x00, 0x00, 0xFD, 0x93, 0x00, 0x00, 0x54, 0x3F, 0x08, 0x00, 0x29, 0x4F, 0x03, 0x00, 0xDF, 0xE8, 0x02, 0x00, 0x36, 0x89, 0x41, 0x00, 0x81, 0x06, 0x00, 0x00, 0xB1, 0x78, 0x00, 0x00, 0x94, 0xEC, 0x01, 0x00 , -0x08, 0x19, 0x1B, 0x00, 0x8F, 0xC6, 0x03, 0x00, 0x1C, 0x17, 0x1B, 0x00, 0x67, 0x66, 0x03, 0x00, 0xA6, 0x44, 0x08, 0x00, 0x18, 0x17, 0x1B, 0x00, 0xA7, 0x2F, 0x02, 0x00, 0x91, 0x44, 0x03, 0x00, 0x91, 0x63, 0x03, 0x00, 0x5B, 0x44, 0x03, 0x00, 0xE7, 0x44, 0x03, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x61, 0xA2, 0x03, 0x00, 0x6A, 0x1E, 0x01, 0x00, 0x45, 0xDA, 0x00, 0x00, 0xD7, 0xE8, 0x01, 0x00, 0xE9, 0x78, 0x02, 0x00, 0x04, 0xF3, 0x1A, 0x00, 0x80, 0x7B, 0x08, 0x00, 0xFC, 0xB5, 0x04, 0x1C, 0xA5, 0x69, 0x60, 0x6A, 0x01, 0x90, 0x20, 0x69, 0x00, 0x28, 0x35, 0xD4, 0x08, 0x28, 0x33, 0xDA, 0xE1, 0x69, 0x09, 0x68, 0xFF, 0xFF, 0xF4, 0x70, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x10, 0x29, 0x2F, 0xD1, 0xAC, 0x21, 0x41, 0x43, 0x9E, 0x4A, 0x51, 0x5C, 0x49, 0x08, 0x27, 0xD3, 0x00, 0x06, 0x00, 0x16, 0xA2, 0x68, 0x69, 0x46, 0x01, 0x23, 0x9E, 0x46, 0x9A, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x06, 0x1C, 0x39, 0x30, 0x1F, 0xD0 , -0x00, 0x2E, 0x1D, 0xD0, 0x00, 0x98, 0x07, 0x68, 0x00, 0x99, 0x0C, 0x39, 0x01, 0x98, 0x01, 0x60, 0x28, 0x1D, 0x10, 0x21, 0x79, 0x1A, 0x04, 0x22, 0x01, 0x23, 0x9E, 0x46, 0x91, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x02, 0x22, 0x2A, 0x80, 0xA8, 0x1C, 0x08, 0x21, 0x79, 0x1A, 0x01, 0x23, 0x9E, 0x46, 0x8C, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x03, 0xE0, 0x38, 0x20, 0x00, 0xE0, 0x00, 0x20, 0xC6, 0x43, 0x26, 0x60, 0x89, 0x48, 0x7C, 0x30, 0x20, 0x62, 0xFC, 0xBD, 0x30, 0xB5, 0x05, 0x1C, 0x28, 0x69, 0xA9, 0x69, 0x90, 0x29, 0x1D, 0xD1, 0x69, 0x69, 0x09, 0x78, 0x04, 0x29, 0x19, 0xD0, 0x05, 0x29, 0x17, 0xD0, 0x0A, 0x29, 0x15, 0xD0, 0x06, 0x29, 0x13, 0xD0, 0x0C, 0x29, 0x01, 0xDB, 0xFF, 0xFF, 0x8A, 0x71, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x10, 0x29, 0x0F, 0xD1, 0x01, 0x24, 0xA6, 0x46, 0x7D, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x7C, 0x48, 0x7D, 0x49, 0x00, 0x22, 0xA6, 0x46, 0x7C, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x7C, 0x48 , -0xFF, 0x30, 0x5F, 0x30, 0x28, 0x62, 0x30, 0xBD, 0xF0, 0xB5, 0x89, 0xB0, 0x05, 0x90, 0x41, 0x69, 0x02, 0x69, 0x75, 0x48, 0x79, 0x4E, 0x82, 0x42, 0x3A, 0xD0, 0x04, 0x30, 0x82, 0x42, 0x25, 0xD0, 0x74, 0x4D, 0xAA, 0x42, 0x00, 0xD0, 0xCC, 0xE0, 0x08, 0x68, 0x06, 0x1C, 0x0C, 0x22, 0x8F, 0x1A, 0x4A, 0x68, 0x89, 0x18, 0x09, 0x1D, 0x10, 0x22, 0x01, 0x24, 0xA6, 0x46, 0x6E, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x01, 0x1C, 0x09, 0xD1, 0xAC, 0x22, 0x72, 0x43, 0xCB, 0x48, 0x80, 0x18, 0x46, 0x22, 0x12, 0x5C, 0x11, 0x2A, 0x01, 0xD1, 0x44, 0x22, 0x14, 0x54, 0x28, 0x1C, 0x3A, 0x1C, 0xA6, 0x46, 0x62, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x69, 0x48, 0xEC, 0x30, 0xAB, 0xE0, 0x08, 0x68, 0xC0, 0x00, 0x30, 0x18, 0x8A, 0x68, 0x02, 0x2A, 0x02, 0xD0, 0xFF, 0xFF, 0x20, 0x72, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0xE7, 0x20, 0x80, 0x00, 0xA2, 0xE0, 0xCA, 0x68, 0x89, 0x18, 0x09, 0x7B, 0x41, 0x60, 0x80, 0x21, 0x01, 0x60, 0x3B, 0x20 , -0x00, 0x01, 0x99, 0xE0, 0x08, 0x68, 0x06, 0x90, 0xC0, 0x00, 0x34, 0x58, 0x10, 0x20, 0x04, 0x90, 0x01, 0x25, 0xAE, 0x46, 0x57, 0x48, 0xFE, 0x44, 0x00, 0x47, 0x07, 0x90, 0x00, 0x28, 0x00, 0xD1, 0x89, 0xE0, 0x0C, 0x21, 0x07, 0x98, 0x0F, 0x18, 0xB0, 0x49, 0xAC, 0x20, 0x06, 0x9A, 0x50, 0x43, 0x08, 0x18, 0x48, 0x22, 0x13, 0x5C, 0x5B, 0x06, 0x5B, 0x0E, 0x13, 0x54, 0x06, 0x9A, 0xD2, 0x00, 0xB6, 0x18, 0x71, 0x68, 0x00, 0x29, 0x47, 0xD1, 0x00, 0x2C, 0x01, 0xDD, 0x08, 0x2C, 0x21, 0xDB, 0x00, 0x22, 0x69, 0x46, 0x0A, 0x70, 0x01, 0x92, 0x0A, 0x81, 0x8A, 0x72, 0xCD, 0x72, 0x0D, 0x73, 0x4D, 0x73, 0x01, 0x88, 0x44, 0x48, 0x06, 0x23, 0xAE, 0x46, 0x44, 0x4C, 0xFE, 0x44, 0x20, 0x47, 0x04, 0x1C, 0x02, 0xDC, 0x00, 0x20, 0xC0, 0x43, 0x36, 0xE0, 0x34, 0x60, 0xAC, 0x20, 0x60, 0x43, 0x9A, 0x49, 0xFF, 0xFF, 0xB6, 0x72, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x09, 0x18, 0x5C, 0x22, 0x28, 0x1C, 0x50, 0x54, 0x48, 0x20 , -0x42, 0x5C, 0x52, 0x06, 0x52, 0x0E, 0x42, 0x54, 0xAC, 0x20, 0x60, 0x43, 0x94, 0x49, 0x08, 0x18, 0x5C, 0x21, 0x09, 0x5C, 0x49, 0x1E, 0x02, 0x29, 0x16, 0xD9, 0x03, 0x39, 0x08, 0xD0, 0x00, 0x20, 0x30, 0x56, 0xAE, 0x46, 0xEA, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x80, 0x20, 0x30, 0x60, 0xDB, 0xE7, 0x08, 0x94, 0x80, 0x21, 0x31, 0x60, 0x48, 0x22, 0x13, 0x5C, 0x19, 0x43, 0x11, 0x54, 0xAE, 0x46, 0xE4, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x0A, 0xE0, 0x01, 0x20, 0xCE, 0xE7, 0x06, 0x98, 0x39, 0x1C, 0x04, 0xAA, 0xAE, 0x46, 0xE0, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x04, 0x1C, 0x08, 0x90, 0x06, 0x98, 0x38, 0x60, 0x08, 0x98, 0x78, 0x60, 0x00, 0x28, 0x15, 0xD0, 0xAC, 0x20, 0x60, 0x43, 0x7C, 0x49, 0x09, 0x18, 0x48, 0x88, 0x02, 0x04, 0x02, 0x20, 0x10, 0x43, 0xB8, 0x60, 0x48, 0x68, 0x02, 0x0E, 0x01, 0x02, 0x09, 0x0E, 0x09, 0x02, 0x11, 0x43, 0x02, 0x04, 0x12, 0x0E, 0xFF, 0xFF, 0x4C, 0x73, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00 , -0x12, 0x04, 0x0A, 0x43, 0x00, 0x06, 0x10, 0x43, 0xF8, 0x60, 0x07, 0x98, 0x0D, 0x49, 0x00, 0x22, 0x10, 0x23, 0xAE, 0x46, 0xCE, 0x4C, 0xFE, 0x44, 0x20, 0x47, 0x13, 0x48, 0x00, 0xE0, 0x16, 0x20, 0xCC, 0x49, 0x09, 0x18, 0x05, 0x98, 0x01, 0x62, 0x09, 0xB0, 0xF0, 0xBD, 0x5D, 0x0D, 0x1B, 0x00, 0x81, 0xE7, 0x02, 0x00, 0x09, 0xB4, 0x03, 0x00, 0x27, 0x1A, 0x02, 0x00, 0x2F, 0x7A, 0x02, 0x00, 0x02, 0x02, 0x00, 0x00, 0x05, 0x10, 0x00, 0x00, 0xCF, 0xF6, 0x00, 0x00, 0xD5, 0xF4, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x91, 0x19, 0x02, 0x00, 0x50, 0x65, 0x08, 0x00, 0x71, 0xC0, 0x02, 0x00, 0x50, 0x19, 0x1B, 0x00, 0x29, 0x16, 0x01, 0x00, 0x2A, 0x03, 0x00, 0x00, 0xF0, 0xB5, 0x8B, 0xB0, 0x07, 0x90, 0x05, 0x69, 0x47, 0x69, 0x0C, 0x20, 0x38, 0x1A, 0x08, 0x90, 0xB6, 0x49, 0x8D, 0x42, 0x16, 0xD1, 0x78, 0x68, 0x0F, 0x30, 0x00, 0x11, 0x00, 0x01, 0x78, 0x60, 0x38, 0x68, 0x0B, 0x28, 0x0E, 0xD8, 0x00, 0x23, 0x68, 0x46 , -0xFF, 0xFF, 0xE2, 0x73, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x03, 0x70, 0x08, 0x98, 0x05, 0x22, 0x01, 0x24, 0xA6, 0x46, 0xAE, 0x4C, 0xFE, 0x44, 0x20, 0x47, 0xAE, 0x48, 0xFF, 0x30, 0x95, 0x30, 0x07, 0x99, 0x08, 0x62, 0xAC, 0x48, 0x85, 0x42, 0x23, 0xD1, 0xAC, 0x48, 0x02, 0x78, 0x6C, 0x46, 0x22, 0x72, 0x43, 0x78, 0x63, 0x72, 0x81, 0x78, 0xA1, 0x72, 0xC0, 0x78, 0xE0, 0x72, 0x00, 0x91, 0x01, 0x90, 0x03, 0x20, 0xA6, 0x49, 0x01, 0x39, 0x01, 0x26, 0xB6, 0x46, 0xF3, 0x4E, 0xFE, 0x44, 0x30, 0x47, 0x04, 0x20, 0x20, 0x70, 0x08, 0x98, 0x9F, 0x49, 0x00, 0x22, 0x02, 0xAB, 0x01, 0x24, 0xA6, 0x46, 0x9B, 0x4C, 0xFE, 0x44, 0x20, 0x47, 0x9A, 0x48, 0xFF, 0x30, 0x95, 0x30, 0x07, 0x99, 0x08, 0x62, 0xEB, 0x49, 0x8D, 0x42, 0x14, 0xD1, 0x02, 0x22, 0x68, 0x46, 0x02, 0x70, 0x3A, 0x68, 0xAC, 0x20, 0x42, 0x43, 0x30, 0x48, 0x68, 0x30, 0x83, 0x18, 0x08, 0x98, 0x00, 0x22, 0x01, 0x24, 0xA6, 0x46, 0x8F, 0x4C, 0xFE, 0x44 , -0x20, 0x47, 0x8E, 0x48, 0xFF, 0x30, 0x95, 0x30, 0x07, 0x99, 0xFF, 0xFF, 0x78, 0x74, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x08, 0x62, 0xEF, 0x48, 0x85, 0x42, 0x00, 0xD0, 0x04, 0xE1, 0x03, 0x20, 0x8C, 0x49, 0x01, 0x22, 0x96, 0x46, 0xEC, 0x4A, 0xFE, 0x44, 0x10, 0x47, 0x86, 0x48, 0xFF, 0x30, 0x95, 0x30, 0x09, 0x90, 0x38, 0x68, 0xEA, 0x4D, 0x00, 0x28, 0x00, 0xD1, 0xE2, 0xE0, 0x01, 0x24, 0xA6, 0x46, 0xE6, 0x48, 0xFE, 0x44, 0x00, 0x47, 0x00, 0x28, 0x00, 0xD1, 0xD6, 0xE0, 0xE4, 0x48, 0x02, 0x68, 0x03, 0x20, 0x7F, 0x49, 0x01, 0x31, 0xA6, 0x46, 0xE2, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0xDF, 0x48, 0x00, 0x68, 0x00, 0x28, 0x5A, 0xD1, 0xDF, 0x4D, 0x2E, 0x20, 0x41, 0x19, 0xB8, 0x68, 0x03, 0x30, 0x08, 0x70, 0x38, 0x7A, 0x48, 0x70, 0x2E, 0x1C, 0x30, 0x36, 0xB8, 0x68, 0x28, 0x18, 0x30, 0x30, 0xDA, 0x49, 0x0A, 0x68, 0x30, 0x3A, 0x31, 0x1C, 0xA6, 0x46, 0xD8, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x78, 0x68, 0x38, 0x18 , -0x01, 0x1D, 0xBA, 0x68, 0x30, 0x1C, 0xA6, 0x46, 0xD9, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0xB8, 0x68, 0x41, 0x19, 0x97, 0x22, 0xFF, 0xFF, 0x0E, 0x75, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x09, 0x30, 0x50, 0x54, 0xB8, 0x68, 0x46, 0x19, 0x9E, 0x36, 0x30, 0x70, 0x01, 0x36, 0xB8, 0x68, 0x01, 0xE0, 0x14, 0x0D, 0x1B, 0x00, 0x30, 0x18, 0xCA, 0x49, 0x0A, 0x68, 0x9E, 0x3A, 0x31, 0x1C, 0xA6, 0x46, 0xC8, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x78, 0x68, 0x38, 0x18, 0x01, 0x1D, 0xBA, 0x68, 0x30, 0x1C, 0xA6, 0x46, 0xC9, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0xB8, 0x68, 0x40, 0x00, 0xC0, 0x49, 0x09, 0x68, 0x08, 0x18, 0x28, 0x18, 0xC0, 0x49, 0x0A, 0x79, 0x02, 0x70, 0x4A, 0x79, 0x42, 0x70, 0x8A, 0x79, 0x82, 0x70, 0xC9, 0x79, 0xC1, 0x70, 0x04, 0x30, 0x0F, 0x21, 0x41, 0x1A, 0x0A, 0x78, 0xBB, 0x68, 0x9A, 0x18, 0x0A, 0x70, 0x40, 0x1B, 0x00, 0x04, 0x00, 0x0C, 0xB5, 0x49, 0x08, 0x60, 0xB1, 0x48, 0x04, 0x60, 0x02, 0x20, 0x01, 0x1C , -0x11, 0x22, 0xA6, 0x46, 0xB4, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x06, 0x1C, 0x63, 0xD4, 0x03, 0x20, 0xA6, 0x46, 0xB1, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x0A, 0x90, 0x00, 0x25, 0x01, 0x1C, 0xFF, 0xFF, 0xA4, 0x75, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x8D, 0x42, 0x50, 0xD0, 0x29, 0x1C, 0x2B, 0x22, 0xA6, 0x46, 0xAD, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x0C, 0x20, 0x0A, 0x99, 0x40, 0x18, 0xAC, 0x22, 0x72, 0x43, 0xAB, 0x49, 0x8F, 0x18, 0x78, 0x63, 0x29, 0x1C, 0x18, 0x22, 0xA6, 0x46, 0xA6, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x9F, 0x48, 0x02, 0x68, 0x79, 0x6B, 0x4A, 0x60, 0x0A, 0x98, 0xAC, 0x30, 0x08, 0x60, 0x08, 0x68, 0x9A, 0x49, 0xA6, 0x46, 0xA0, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x29, 0x1C, 0x03, 0xA8, 0x10, 0x22, 0xA6, 0x46, 0x9C, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0xE0, 0x21, 0x68, 0x46, 0x01, 0x74, 0x45, 0x74, 0x85, 0x74, 0xFB, 0x21, 0xC1, 0x74, 0xEE, 0x49, 0xC1, 0x81, 0x02, 0x21, 0x81, 0x81, 0x79, 0x6B, 0xCA, 0x68 , -0x01, 0x20, 0xC0, 0x03, 0x10, 0x43, 0xC8, 0x60, 0x48, 0x68, 0x00, 0x90, 0x2A, 0x1C, 0x30, 0x1C, 0x0A, 0x9D, 0x29, 0x1C, 0x03, 0xAB, 0xA6, 0x46, 0xE6, 0x4F, 0xFE, 0x44, 0x38, 0x47, 0x07, 0x1C, 0x30, 0x06, 0x00, 0x16, 0xA6, 0x46, 0xEF, 0x49, 0xFF, 0xFF, 0x3A, 0x76, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0xFE, 0x44, 0x08, 0x47, 0x28, 0x1C, 0xA6, 0x46, 0xEE, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x11, 0xE0, 0x30, 0x06, 0x00, 0x16, 0xA6, 0x46, 0xE9, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x01, 0x20, 0xC7, 0x43, 0x08, 0xE0, 0x07, 0x1C, 0x06, 0xE0, 0x00, 0x20, 0x00, 0x21, 0xCF, 0x43, 0x01, 0xE0, 0x00, 0x20, 0x07, 0x1C, 0x28, 0x60, 0x00, 0x23, 0x68, 0x46, 0x03, 0x70, 0x3A, 0x06, 0x12, 0x0E, 0x08, 0x98, 0x6F, 0x49, 0x01, 0x24, 0xA6, 0x46, 0x09, 0x4C, 0xFE, 0x44, 0x20, 0x47, 0x07, 0x98, 0x09, 0x99, 0x01, 0x62, 0x0B, 0xB0, 0xF0, 0xBD, 0xC1, 0x18, 0x01, 0x00, 0xF1, 0x1B, 0x01, 0x00, 0xF3, 0x1C, 0x02, 0x00, 0x7B, 0xC0 , -0x02, 0x00, 0x91, 0xF0, 0x00, 0x00, 0x03, 0x02, 0x00, 0x00, 0xA3, 0xC0, 0x02, 0x00, 0xA9, 0xE9, 0x00, 0x00, 0x07, 0x02, 0x00, 0x00, 0xE4, 0x62, 0x08, 0x00, 0xAC, 0x05, 0x00, 0x00, 0xFE, 0xB5, 0x07, 0x1C, 0x7D, 0x69, 0xBE, 0x69, 0x0C, 0x20, 0x30, 0x1A, 0x01, 0x90, 0xDF, 0x4C, 0x0A, 0x2D, 0x13, 0xD1, 0xFF, 0xFF, 0xD0, 0x76, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x30, 0x68, 0xDB, 0x49, 0x08, 0x60, 0x01, 0x20, 0x86, 0x46, 0xDA, 0x48, 0xFE, 0x44, 0x00, 0x47, 0x0A, 0x20, 0x00, 0x21, 0x01, 0x9A, 0x01, 0x23, 0x9E, 0x46, 0xE6, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0xF5, 0x20, 0x80, 0x00, 0x00, 0x19, 0x38, 0x62, 0x03, 0x2D, 0x79, 0xD1, 0xF5, 0x20, 0x80, 0x00, 0x00, 0x19, 0x02, 0x90, 0x70, 0x68, 0x00, 0x28, 0x0C, 0xD1, 0x00, 0x21, 0xCF, 0x48, 0x01, 0x60, 0xCF, 0x48, 0x00, 0x68, 0x00, 0x28, 0x61, 0xD0, 0x01, 0x21, 0x8E, 0x46, 0xCD, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x5B, 0xE0, 0xCC, 0x48, 0xB1, 0x68, 0x01, 0x60 , -0xF1, 0x68, 0x41, 0x60, 0x31, 0x69, 0x81, 0x60, 0x71, 0x69, 0xC1, 0x60, 0xB1, 0x69, 0xC1, 0x63, 0xF1, 0x69, 0x01, 0x64, 0x31, 0x6A, 0xC1, 0x64, 0x01, 0x24, 0xA6, 0x46, 0xC5, 0x48, 0xFE, 0x44, 0x00, 0x47, 0xA6, 0x46, 0xC4, 0x48, 0xFE, 0x44, 0x00, 0x47, 0x70, 0x68, 0x7D, 0x25, 0xED, 0x00, 0xA8, 0x42, 0x21, 0xD8, 0x01, 0x28, 0x18, 0xD0, 0x02, 0x28, 0x05, 0xD0, 0xFF, 0xFF, 0x66, 0x77, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x28, 0x1C, 0xA6, 0x46, 0xBE, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x1C, 0xE0, 0xB9, 0x48, 0x00, 0x23, 0x19, 0x1C, 0x59, 0x43, 0x3E, 0x22, 0x4A, 0x43, 0x82, 0x83, 0x02, 0x30, 0x01, 0x33, 0x10, 0x2B, 0xF6, 0xDB, 0xA6, 0x46, 0xB4, 0x48, 0xFE, 0x44, 0x00, 0x47, 0xB5, 0x48, 0x0D, 0xE0, 0xB5, 0x4D, 0x28, 0x1C, 0xA6, 0x46, 0xB2, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x04, 0xE0, 0xA6, 0x46, 0xAF, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x75, 0x68, 0xAE, 0x48, 0x05, 0x60, 0x05, 0x1C, 0xA7, 0x4E, 0x30, 0x68 , -0x00, 0x28, 0x06, 0xD1, 0xAD, 0x48, 0x00, 0x68, 0xA6, 0x46, 0xAC, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x30, 0x60, 0x00, 0x94, 0x2B, 0x68, 0xAA, 0x49, 0xAB, 0x4A, 0xA6, 0x46, 0xAB, 0x4D, 0xFE, 0x44, 0x28, 0x47, 0x9C, 0x48, 0x04, 0x60, 0x03, 0x20, 0x00, 0x21, 0x01, 0x9A, 0x01, 0x23, 0x9E, 0x46, 0xA7, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x02, 0x98, 0x38, 0x62, 0xFE, 0xBD, 0xC0, 0x46, 0x13, 0x7F, 0x03, 0x00, 0x12, 0x10, 0x00, 0x00, 0xFF, 0xFF, 0xFC, 0x77, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x30, 0xB5, 0x05, 0x1C, 0x00, 0x20, 0x01, 0x24, 0xA6, 0x46, 0xA0, 0x49, 0xFE, 0x44, 0x08, 0x47, 0xA6, 0x46, 0x9F, 0x49, 0xFE, 0x44, 0x08, 0x47, 0xA6, 0x46, 0x9E, 0x48, 0xFE, 0x44, 0x00, 0x47, 0x7D, 0x21, 0xC9, 0x00, 0xA6, 0x46, 0x9E, 0x4A, 0xFE, 0x44, 0x10, 0x47, 0x9B, 0x49, 0x08, 0x18, 0x99, 0x49, 0x08, 0x80, 0x9B, 0x48, 0x0A, 0x30, 0x28, 0x62, 0x30, 0xBD, 0x11, 0x10, 0x00, 0x00, 0xDD, 0x7E, 0x03, 0x00, 0xB9, 0x90 , -0x00, 0x00, 0x6C, 0x64, 0x08, 0x00, 0xE7, 0x7E, 0x03, 0x00, 0x74, 0x64, 0x08, 0x00, 0x70, 0x64, 0x08, 0x00, 0x6D, 0xC6, 0x03, 0x00, 0x08, 0x19, 0x1B, 0x00, 0x11, 0x18, 0x02, 0x00, 0xD1, 0x78, 0x02, 0x00, 0xC9, 0xBA, 0x03, 0x00, 0x09, 0xB4, 0x03, 0x00, 0x14, 0x0D, 0x1B, 0x00, 0xFE, 0xB5, 0x02, 0x90, 0x45, 0x69, 0x68, 0x46, 0x01, 0x21, 0x8E, 0x46, 0x89, 0x49, 0xFE, 0x44, 0x08, 0x47, 0x89, 0x48, 0x04, 0x1C, 0x68, 0x68, 0x01, 0x69, 0x4A, 0x78, 0x00, 0x27, 0x3E, 0x1C, 0x20, 0x88, 0xFF, 0xFF, 0x92, 0x78, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x40, 0x08, 0x22, 0xD3, 0x20, 0x1D, 0x89, 0x1C, 0x01, 0x23, 0x9E, 0x46, 0x83, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x00, 0x28, 0x07, 0xD1, 0x68, 0x68, 0x00, 0x69, 0x40, 0x78, 0x21, 0x88, 0x09, 0x04, 0x89, 0x16, 0x81, 0x42, 0x3D, 0xD0, 0x02, 0x20, 0x00, 0x5F, 0x00, 0x99, 0x08, 0x1A, 0x00, 0x04, 0x00, 0x14, 0x3C, 0x28, 0x03, 0xDD, 0x20, 0x88, 0x40, 0x10, 0x40, 0x00 , -0x20, 0x80, 0x78, 0x1C, 0x07, 0x06, 0x3F, 0x0E, 0x68, 0x68, 0x01, 0x69, 0x4A, 0x78, 0x2A, 0x34, 0x01, 0x36, 0x14, 0x2E, 0xD5, 0xDB, 0x00, 0x2A, 0x02, 0xD1, 0xAB, 0x20, 0x40, 0x00, 0x50, 0xE0, 0x00, 0x9B, 0x6D, 0x48, 0x14, 0x21, 0x00, 0x22, 0x04, 0x88, 0x64, 0x08, 0x03, 0xD3, 0x2A, 0x30, 0x01, 0x32, 0x01, 0x39, 0xF8, 0xD1, 0x12, 0x06, 0x12, 0x0E, 0x14, 0x2F, 0x16, 0xD1, 0x66, 0x48, 0x00, 0x88, 0x00, 0x06, 0x44, 0x16, 0x64, 0x49, 0x00, 0x22, 0x01, 0x20, 0x4E, 0x8D, 0x36, 0x06, 0x76, 0x16, 0xA6, 0x42, 0x02, 0xDD, 0x34, 0x1C, 0x02, 0x06, 0xFF, 0xFF, 0x28, 0x79, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0x12, 0x0E, 0x2A, 0x31, 0x01, 0x30, 0x14, 0x28, 0xF3, 0xDB, 0x02, 0xE0, 0x32, 0x06, 0x12, 0x0E, 0x00, 0x9B, 0x2A, 0x20, 0x42, 0x43, 0x5A, 0x48, 0x11, 0x18, 0x0C, 0x88, 0x01, 0x20, 0x20, 0x43, 0x00, 0x04, 0x00, 0x0C, 0x08, 0x80, 0xFE, 0x24, 0xA0, 0x43, 0x14, 0x24, 0x64, 0x57, 0x64, 0x06, 0x24, 0x0E , -0x04, 0x43, 0x52, 0x48, 0x14, 0x52, 0x14, 0x18, 0x63, 0x80, 0x08, 0x88, 0x80, 0x05, 0x82, 0x0D, 0x68, 0x68, 0x00, 0x69, 0x40, 0x78, 0x80, 0x02, 0x10, 0x43, 0x08, 0x80, 0x68, 0x68, 0x02, 0x69, 0x20, 0x1D, 0x91, 0x1C, 0x52, 0x78, 0x01, 0x23, 0x9E, 0x46, 0x4B, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x02, 0x98, 0x04, 0x61, 0xFE, 0x20, 0x47, 0x49, 0x09, 0x18, 0x02, 0x98, 0x01, 0x62, 0xFE, 0xBD, 0x82, 0x69, 0x41, 0x69, 0x03, 0x69, 0x02, 0x2B, 0x0A, 0xD1, 0x01, 0x2A, 0x01, 0xD1, 0x00, 0x29, 0x05, 0xD0, 0x02, 0x2A, 0x04, 0xD1, 0x00, 0x29, 0x02, 0xD1, 0x11, 0x21, 0x00, 0xE0, 0x06, 0x21, 0x41, 0x61, 0xF7, 0x46, 0xFF, 0xFF, 0xBE, 0x79, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0xC0, 0x46, 0x14, 0xE9, 0x00, 0x00, 0xC9, 0x18, 0x02, 0x00, 0x30, 0xB5, 0x05, 0x1C, 0x3A, 0x48, 0x00, 0x78, 0x00, 0x28, 0x04, 0xD0, 0x01, 0x20, 0x86, 0x46, 0x38, 0x48, 0xFE, 0x44, 0x00, 0x47, 0x01, 0x24, 0xA6, 0x46, 0x37, 0x48, 0xFE, 0x44 , -0x00, 0x47, 0xA6, 0x46, 0x36, 0x48, 0xFE, 0x44, 0x00, 0x47, 0x35, 0x48, 0x0E, 0x30, 0x28, 0x62, 0x30, 0xBD, 0x49, 0x19, 0x01, 0x00, 0x2F, 0x7A, 0x02, 0x00, 0x18, 0xB5, 0x43, 0x69, 0x81, 0x69, 0x31, 0x48, 0x81, 0x29, 0x00, 0xD1, 0x0B, 0x38, 0x00, 0x21, 0x00, 0x91, 0x1A, 0x68, 0x9B, 0x68, 0x01, 0x24, 0xA6, 0x46, 0x2D, 0x4C, 0xFE, 0x44, 0x20, 0x47, 0x18, 0xBD, 0x18, 0xB5, 0x40, 0x69, 0x00, 0x21, 0x00, 0x91, 0x02, 0x68, 0x83, 0x68, 0x27, 0x48, 0x01, 0x30, 0x01, 0x24, 0xA6, 0x46, 0x26, 0x4C, 0xFE, 0x44, 0x20, 0x47, 0x18, 0xBD, 0xC0, 0x46, 0x30, 0x63, 0x08, 0x00, 0x19, 0x9E, 0x00, 0x00, 0xB9, 0xEC, 0x00, 0x00, 0x74, 0x3F, 0x08, 0x00, 0x80, 0x3F, 0x08, 0x00, 0xFF, 0xFF, 0x54, 0x7A, 0x08, 0x00, 0x96, 0x00, 0x00, 0x00, 0xB7, 0x5D, 0x03, 0x00, 0x00, 0x00, 0x1B, 0x00, 0xD3, 0x8E, 0x00, 0x00, 0xF7, 0xC6, 0x00, 0x00, 0xE5, 0x90, 0x00, 0x00, 0x68, 0x64, 0x08, 0x00, 0xC0, 0x27, 0x09, 0x00, 0xA0, 0x3B , -0x08, 0x00, 0x3D, 0x5D, 0x03, 0x00, 0x19, 0xC6, 0x00, 0x00, 0xE8, 0x3A, 0x08, 0x00, 0x81, 0x5D, 0x03, 0x00, 0xCF, 0xF6, 0x00, 0x00, 0x4B, 0x4F, 0x03, 0x00, 0x6B, 0xC0, 0x03, 0x00, 0x95, 0x1E, 0x01, 0x00, 0xDA, 0x40, 0x08, 0x00, 0xDC, 0x05, 0x00, 0x00, 0x55, 0xAA, 0x03, 0x00, 0x0D, 0x91, 0x00, 0x00, 0xD7, 0x56, 0x03, 0x00, 0x08, 0x51, 0x08, 0x00, 0x8F, 0xC6, 0x03, 0x00, 0x65, 0xB8, 0x00, 0x00, 0x09, 0xB4, 0x03, 0x00, 0x84, 0x17, 0x1B, 0x00, 0xB5, 0x86, 0x01, 0x00, 0x3D, 0x47, 0x02, 0x00, 0x73, 0x49, 0x02, 0x00, 0x5F, 0x90, 0x00, 0x00, 0x0E, 0x10, 0x00, 0x00, 0xF7, 0xF6, 0x00, 0x00, 0xFF, 0xB5, 0x68, 0x46, 0xFF, 0xF7, 0x76, 0xFF, 0xFF, 0xBD, 0xFF, 0xB5, 0x68, 0x46, 0xFF, 0xF7, 0x5A, 0xFF, 0xFF, 0xBD, 0xFF, 0xB5, 0xFF, 0xFF, 0xEA, 0x7A, 0x08, 0x00, 0x58, 0x00, 0x00, 0x00, 0x68, 0x46, 0xFF, 0xF7, 0x99, 0xFF, 0xFF, 0xBD, 0xFF, 0xB5, 0x68, 0x46, 0xFF, 0xF7, 0x83, 0xFF, 0xFF, 0xBD, 0xFF, 0xB5 , -0x68, 0x46, 0xFF, 0xF7, 0xB6, 0xFE, 0xFF, 0xBD, 0xFF, 0xB5, 0x68, 0x46, 0xFF, 0xF7, 0x55, 0xFC, 0xFF, 0xBD, 0xFF, 0xB5, 0x68, 0x46, 0xFF, 0xF7, 0x27, 0xFB, 0xFF, 0xBD, 0xFF, 0xB5, 0x68, 0x46, 0xFF, 0xF7, 0xDD, 0xFA, 0xFF, 0xBD, 0xFF, 0xB5, 0x68, 0x46, 0xFF, 0xF7, 0x68, 0xFE, 0xFF, 0xBD, 0xFF, 0xB5, 0x68, 0x46, 0xFF, 0xF7, 0x3D, 0xFB, 0xFF, 0xBD, 0xFF, 0xB5, 0x68, 0x46, 0xFF, 0xF7, 0xBE, 0xFD, 0xFF, 0xBD, 0x78, 0x7B, 0x08, 0x00, 0x88, 0x00, 0x00, 0x00, 0x00, 0xB5, 0xF8, 0xF0, 0x43, 0xFA, 0x00, 0xBD, 0x35, 0x66, 0x08, 0x00, 0x67, 0x66, 0x08, 0x00, 0x71, 0x65, 0x08, 0x00, 0x4D, 0x66, 0x08, 0x00, 0x25, 0x64, 0x08, 0x00, 0x81, 0x66, 0x08, 0x00, 0x8D, 0x66, 0x08, 0x00, 0x99, 0x66, 0x08, 0x00, 0x87, 0x67, 0x08, 0x00, 0xA7, 0x67, 0x08, 0x00, 0xD1, 0x67, 0x08, 0x00, 0x1B, 0x68, 0x08, 0x00, 0x57, 0x68, 0x08, 0x00, 0x2D, 0x69, 0x08, 0x00, 0xB1, 0x6B, 0x08, 0x00, 0xD5, 0x6B, 0x08, 0x00, 0xF9, 0x6B , -0x08, 0x00, 0x15, 0x6C, 0x08, 0x00, 0xA1, 0x68, 0x08, 0x00, 0x59, 0x6C, 0x08, 0x00, 0xA7, 0x6D, 0x08, 0x00, 0xFF, 0x6D, 0x08, 0x00, 0x29, 0x6E, 0x08, 0x00, 0xF9, 0x6E, 0x08, 0x00, 0xD9, 0x6C, 0x08, 0x00, 0xA5, 0x6E, 0x08, 0x00, 0xCD, 0x6D, 0x08, 0x00, 0x81, 0x6F, 0x08, 0x00, 0x1D, 0x70, 0x08, 0x00, 0x31, 0x64, 0x08, 0x00, 0x39, 0x70, 0x08, 0x00, 0x3F, 0x70, 0x08, 0x00, 0x04, 0xF3, 0x1A, 0x00, 0x80, 0x00, 0x00, 0x00, 0xB2, 0x4E, 0x01, 0x00, 0x5A, 0xC1, 0x00, 0x00, 0x96, 0x1A, 0x01, 0x00, 0x22, 0x0B, 0x02, 0x00, 0x60, 0xD0, 0x01, 0x00, 0x06, 0x1A, 0x00, 0x00, 0xB8, 0xC6, 0x01, 0x00, 0xD8, 0x42, 0x03, 0x00, 0x16, 0x42, 0x03, 0x00, 0xEE, 0xDB, 0x00, 0x00, 0x62, 0xDC, 0x00, 0x00, 0xC8, 0xE1, 0x00, 0x00, 0x8A, 0x17, 0x02, 0x00, 0x38, 0xBE, 0x00, 0x00, 0x26, 0xC6, 0x00, 0x00, 0x56, 0xC2, 0x00, 0x00, 0x62, 0x12, 0x03, 0x00, 0xE4, 0xF4, 0x01, 0x00, 0x3A, 0xEC, 0x00, 0x00, 0x5E, 0x92, 0x00, 0x00 , -0xFE, 0xE8, 0x02, 0x00, 0x18, 0x7F, 0x00, 0x00, 0x64, 0xEC, 0x01, 0x00, 0xFE, 0x44, 0x03, 0x00, 0x1C, 0x94, 0x00, 0x00, 0xA8, 0x66, 0x03, 0x00, 0x74, 0xE9, 0x02, 0x00, 0x68, 0x1E, 0x01, 0x00, 0xBC, 0xDA, 0x00, 0x00, 0xEA, 0xE1, 0x00, 0x00, 0x24, 0xE9, 0x01, 0x00, 0x70, 0x79, 0x02, 0x00, 0x00, 0x00, 0x18, 0x00, 0x96, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x1C, 0xF0, 0xB5, 0x88, 0xB0, 0xCA, 0x4C, 0x03, 0x20, 0x22, 0x78, 0x63, 0x78, 0xCA, 0x4E, 0x31, 0x1C, 0x01, 0x39, 0x01, 0x25, 0xAE, 0x46, 0xC7, 0x4F, 0xFE, 0x44, 0x38, 0x47, 0xA2, 0x78, 0xE3, 0x78, 0x03, 0x20, 0x31, 0x1C, 0xAE, 0x46, 0xC3, 0x4F, 0xFE, 0x44, 0x38, 0x47, 0x03, 0x20, 0x31, 0x1C, 0x01, 0x31, 0xAE, 0x46, 0xC1, 0x4A, 0xFE, 0x44, 0x10, 0x47, 0xC1, 0x48, 0x21, 0x78, 0x01, 0x70, 0x61, 0x78, 0x41, 0x70, 0xE1, 0x78, 0xC1, 0x70, 0xA1, 0x78, 0x81, 0x70, 0xBF, 0x48, 0x04, 0x1C, 0x33, 0x3C, 0x20, 0x1C, 0x00, 0x21, 0xDC, 0x22, 0xAE, 0x46 , -0xBA, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x84, 0x20, 0xA0, 0x70, 0x05, 0x27, 0xE7, 0x71, 0x0C, 0x26, 0x26, 0x73, 0x0D, 0x20, 0x00, 0x19, 0x98, 0xA1, 0x32, 0x1C, 0xAE, 0x46, 0xB4, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x04, 0x20, 0x60, 0x76, 0x1A, 0x20, 0x00, 0x19, 0x97, 0xA1, 0x06, 0x91, 0x04, 0x22, 0xAE, 0x46, 0xAE, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0xFF, 0xFF, 0x96, 0x00, 0x18, 0x00, 0x96, 0x00, 0x00, 0x00, 0xA7, 0x77, 0x1F, 0x34, 0x95, 0xA1, 0x07, 0x91, 0x20, 0x1C, 0x3A, 0x1C, 0xAE, 0x46, 0xA9, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0xE6, 0x71, 0x28, 0x1C, 0x60, 0x72, 0x11, 0x20, 0x20, 0x73, 0x94, 0x20, 0x60, 0x73, 0xC0, 0x25, 0x65, 0x74, 0xA6, 0x74, 0x09, 0x22, 0xE2, 0x74, 0xA3, 0x4C, 0x20, 0x1C, 0x8C, 0xA1, 0x01, 0x23, 0x9E, 0x46, 0x9F, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x07, 0x22, 0x62, 0x72, 0x9E, 0x4C, 0x0A, 0x34, 0x20, 0x1C, 0x89, 0xA1, 0x01, 0x23, 0x9E, 0x46, 0x9A, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x04, 0x20 , -0xE0, 0x71, 0x98, 0x4C, 0x12, 0x34, 0x20, 0x1C, 0x06, 0x99, 0x04, 0x22, 0x01, 0x23, 0x9E, 0x46, 0x94, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x27, 0x71, 0x93, 0x4C, 0x17, 0x34, 0x20, 0x1C, 0x07, 0x99, 0x3A, 0x1C, 0x01, 0x23, 0x9E, 0x46, 0x8E, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0xE6, 0x71, 0x01, 0x20, 0x60, 0x72, 0x11, 0x20, 0x20, 0x73, 0x94, 0x20, 0x60, 0x73, 0x02, 0x20, 0xE0, 0x73, 0x25, 0x74, 0x66, 0x74, 0xFF, 0xFF, 0x2C, 0x01, 0x18, 0x00, 0x96, 0x00, 0x00, 0x00, 0xA5, 0x74, 0x2F, 0x27, 0xE7, 0x74, 0x10, 0x20, 0x60, 0x75, 0x80, 0x26, 0xA6, 0x75, 0x01, 0x20, 0xE0, 0x75, 0x11, 0x20, 0xA0, 0x76, 0x94, 0x20, 0xE0, 0x76, 0x24, 0x20, 0x60, 0x77, 0x0A, 0x22, 0xA2, 0x77, 0x80, 0x4C, 0x36, 0x34, 0x20, 0x1C, 0x6D, 0xA1, 0x01, 0x23, 0x9E, 0x46, 0x7C, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x18, 0x22, 0xA2, 0x72, 0x7A, 0x4C, 0x41, 0x34, 0x20, 0x1C, 0x6B, 0xA1, 0x01, 0x23, 0x9E, 0x46, 0x76, 0x4B, 0xFE, 0x44, 0x18, 0x47 , -0x25, 0x76, 0x67, 0x76, 0x21, 0x20, 0xE0, 0x76, 0x26, 0x77, 0x01, 0x20, 0x60, 0x77, 0x72, 0x48, 0x61, 0x30, 0x11, 0x21, 0x01, 0x70, 0x94, 0x21, 0x41, 0x70, 0x04, 0x21, 0x01, 0x72, 0xD2, 0x21, 0x41, 0x72, 0xC5, 0x72, 0x1E, 0x21, 0x01, 0x73, 0x45, 0x73, 0x9E, 0x21, 0x81, 0x73, 0x01, 0x21, 0x01, 0x74, 0x46, 0x74, 0x81, 0x74, 0x11, 0x21, 0x41, 0x75, 0x94, 0x21, 0x81, 0x75, 0x04, 0x21, 0x01, 0x76, 0xAD, 0x20, 0x66, 0x49, 0x08, 0x60, 0x00, 0x24, 0x0F, 0x25, 0xFF, 0xFF, 0xC2, 0x01, 0x18, 0x00, 0x96, 0x00, 0x00, 0x00, 0x29, 0x06, 0x09, 0x0E, 0x00, 0x20, 0x6A, 0x46, 0x01, 0x23, 0x9E, 0x46, 0x62, 0x4B, 0xFE, 0x44, 0x18, 0x47, 0x6B, 0x46, 0x18, 0x88, 0x40, 0x08, 0x0E, 0xD3, 0xA0, 0x00, 0x0F, 0x21, 0xCA, 0x43, 0x69, 0x46, 0x0E, 0x88, 0x16, 0x40, 0x01, 0xAF, 0x3E, 0x52, 0x49, 0x88, 0x11, 0x40, 0x68, 0x44, 0xC1, 0x80, 0x60, 0x1C, 0x04, 0x04, 0x24, 0x0C, 0x01, 0x3D, 0x0B, 0x2D, 0xE0, 0xDA, 0x60, 0x1E , -0x00, 0x04, 0x00, 0x0C, 0x1D, 0xD0, 0x86, 0x46, 0x01, 0x1C, 0x01, 0xAD, 0x01, 0x22, 0xAE, 0x88, 0x90, 0x00, 0xC7, 0x5A, 0xB7, 0x42, 0x0A, 0xDA, 0xBC, 0x46, 0x07, 0x1C, 0x6F, 0x44, 0x7F, 0x88, 0x68, 0x44, 0x06, 0x80, 0xEE, 0x88, 0x46, 0x80, 0x60, 0x46, 0xA8, 0x80, 0xEF, 0x80, 0x04, 0x35, 0x50, 0x1C, 0x02, 0x04, 0x12, 0x0C, 0x01, 0x39, 0xE9, 0xD1, 0x70, 0x46, 0x01, 0x38, 0x86, 0x46, 0xE2, 0xD1, 0x99, 0x88, 0x68, 0x46, 0xC0, 0x88, 0x40, 0x18, 0x00, 0x04, 0x00, 0x0C, 0x42, 0x4B, 0x18, 0x80, 0x42, 0x49, 0x08, 0x1A, 0xFF, 0xFF, 0x58, 0x02, 0x18, 0x00, 0x96, 0x00, 0x00, 0x00, 0x58, 0x80, 0x02, 0x2C, 0x1E, 0xDB, 0x65, 0x1E, 0x01, 0xAA, 0x01, 0x20, 0x01, 0x1C, 0x8C, 0x00, 0x6B, 0x46, 0xE6, 0x5A, 0x93, 0x88, 0xD4, 0x88, 0xE7, 0x18, 0xB7, 0x42, 0x0C, 0xDA, 0x06, 0x24, 0x44, 0x43, 0x38, 0x4B, 0x1B, 0x19, 0x1F, 0x80, 0x1C, 0x88, 0x34, 0x1B, 0x5C, 0x80, 0x01, 0x24, 0x1C, 0x71, 0x40, 0x1C, 0x00, 0x04 , -0x00, 0x0C, 0x04, 0x32, 0x49, 0x1C, 0x09, 0x06, 0x09, 0x0E, 0x01, 0x3D, 0xE4, 0xD1, 0x00, 0x24, 0x31, 0x48, 0x04, 0x70, 0x31, 0x48, 0x04, 0x70, 0x31, 0x48, 0x04, 0x70, 0x31, 0x48, 0x04, 0x70, 0x01, 0x20, 0x86, 0x46, 0x30, 0x48, 0xFE, 0x44, 0x00, 0x47, 0x2F, 0x49, 0x22, 0x1C, 0x08, 0x68, 0x00, 0x28, 0x02, 0xD0, 0x01, 0x20, 0x90, 0x40, 0x04, 0x43, 0x04, 0x31, 0x01, 0x32, 0x20, 0x2A, 0xF5, 0xD3, 0x2A, 0x48, 0x04, 0x60, 0x08, 0xB0, 0xF0, 0xBD, 0x5F, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x2D, 0x69, 0x6E, 0x66, 0x6F, 0x00, 0xC0, 0x46, 0xC0, 0x5F, 0x75, 0x64, 0x70, 0x00, 0xC0, 0xFF, 0xFF, 0xEE, 0x02, 0x18, 0x00, 0x96, 0x00, 0x00, 0x00, 0x46, 0xC0, 0x6C, 0x6F, 0x63, 0x61, 0x6C, 0x00, 0xC0, 0x46, 0x5F, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x00, 0xC0, 0x46, 0x5F, 0x64, 0x6E, 0x73, 0x2D, 0x73, 0x64, 0x00, 0x64, 0x65, 0x76, 0x3D, 0x43, 0x43, 0x33, 0x30, 0x30, 0x30, 0x00, 0xC0, 0x76, 0x65 , -0x6E, 0x64, 0x6F, 0x72, 0x3D, 0x54, 0x65, 0x78, 0x61, 0x73, 0x2D, 0x49, 0x6E, 0x73, 0x74, 0x72, 0x75, 0x6D, 0x65, 0x6E, 0x74, 0x73, 0x00, 0xC0, 0x46, 0xC0, 0x00, 0x00, 0x18, 0x00, 0xF3, 0x7E, 0x03, 0x00, 0xC6, 0x05, 0x00, 0x00, 0xDD, 0x7E, 0x03, 0x00, 0xE4, 0x62, 0x08, 0x00, 0xC9, 0xBA, 0x03, 0x00, 0x09, 0xB4, 0x03, 0x00, 0xA7, 0x64, 0x08, 0x00, 0x70, 0x64, 0x08, 0x00, 0xDD, 0x0A, 0x02, 0x00, 0x48, 0x32, 0x08, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xE8, 0x62, 0x08, 0x00, 0xE9, 0x62, 0x08, 0x00, 0xEA, 0x62, 0x08, 0x00, 0xEB, 0x62, 0x08, 0x00, 0x81, 0x03, 0x18, 0x00, 0x80, 0x7B, 0x08, 0x00, 0x84, 0xF3, 0x1A, 0x00, 0x0D, 0x49, 0x0E, 0x48, 0xFF, 0xFF, 0x84, 0x03, 0x18, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x88, 0x67, 0x0E, 0x48, 0x88, 0x64, 0x0E, 0x48, 0x48, 0x64, 0x0E, 0x48, 0xC8, 0x64, 0x0E, 0x48, 0x08, 0x65, 0x11, 0x48, 0x02, 0x1C, 0x04, 0x32, 0x0C, 0x4B, 0x13, 0x60, 0x0C, 0x4B, 0x93, 0x62, 0x0C, 0x4A , -0x8A, 0x66, 0x0D, 0x49, 0x01, 0x60, 0x0D, 0x48, 0x0E, 0x49, 0x01, 0x60, 0x0E, 0x49, 0x41, 0x60, 0xF7, 0x46, 0x1C, 0x21, 0x08, 0x00, 0x1B, 0x7B, 0x08, 0x00, 0x11, 0x7B, 0x08, 0x00, 0x07, 0x7B, 0x08, 0x00, 0x39, 0x7B, 0x08, 0x00, 0x2F, 0x7B, 0x08, 0x00, 0x25, 0x7B, 0x08, 0x00, 0xFD, 0x7A, 0x08, 0x00, 0xDF, 0x7A, 0x08, 0x00, 0x50, 0x23, 0x08, 0x00, 0xD5, 0x7A, 0x08, 0x00, 0x58, 0x26, 0x08, 0x00, 0xF3, 0x7A, 0x08, 0x00, 0xE9, 0x7A, 0x08, 0x00 }; - - -const unsigned char cRMdefaultParams[128] = { 0x03, 0x00, 0x01, 0x01, 0x14, 0x14, 0x00, 0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x27, 0x23, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x23, 0x23, 0x23, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x01, 0x77, 0x80, 0x1D, 0x1F, 0x22, 0x26, 0x28, 0x29, 0x1A, 0x1F, 0x22, 0x24, 0x26, 0x28, 0x16, 0x1D, 0x1E, 0x20, 0x24, 0x25, 0x1E, 0x2D, 0x01, 0x02, 0x02, 0x02, 0x02, 0x00, 0x15, 0x15, 0x15, 0x11, 0x15, 0x15, 0x0E, 0x00}; - -// -//Service Pack version P1.13.7.15.15 - FW patches -// -const unsigned char fw_patch[5700] = { 0x00, 0x01, 0x00, 0x00, 0x3C, 0x16, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x14, 0x03, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x68, 0x46, 0x25, 0xF0, 0x95, 0xFB, 0xE0, 0x6B, 0xD0, 0x03, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x25, 0xF0, 0x38, 0xFB, 0x2C, 0x04, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x25, 0xF0, 0x0A, 0xFB, 0x04, 0x15, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xB8, 0xF1, 0x90, 0x0F, 0xA4, 0x16, 0x00, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x66, 0xE0, 0x04, 0xA8, 0x35, 0x1D, 0x21, 0xF0, 0x99, 0xFC, 0x68, 0x46, 0x23, 0xF0, 0x28, 0xFB, 0x9A, 0xF8, 0x00, 0x00, 0x01, 0x28, 0x07, 0xD1, 0x28, 0x46, 0x05, 0xF0, 0xC3, 0xFE, 0x01, 0x46, 0x01, 0xAA, 0x00, 0x20, 0x21, 0xF0, 0x50, 0xF9, 0x28, 0x46, 0x05, 0xF0, 0xBB, 0xFE, 0x01, 0xA9, 0x21, 0xF0, 0x2A, 0xFA, 0xE9, 0x79, 0x4F, 0xEA, 0xE0, 0x00, 0x40, 0xB2, 0x11, 0xB1, 0x00, 0xF1, 0x06, 0x00, 0x40, 0xB2, 0xA8, 0x71, 0x1F, 0x38, 0x40, 0x00, 0xE8, 0x71, 0x30, 0x46 , -0x01, 0xF0, 0x0D, 0xFF, 0x10, 0xF1, 0x00, 0x09, 0x4F, 0xF0, 0x00, 0x01, 0x09, 0xD0, 0x28, 0x68, 0x40, 0x0C, 0x09, 0xD3, 0xE8, 0x68, 0xC0, 0x0B, 0x03, 0xD2, 0x48, 0x46, 0xFF, 0xF7, 0xDD, 0xFE, 0x01, 0x21, 0x28, 0x68, 0x40, 0x0C, 0x0A, 0xD2, 0x38, 0x68, 0x40, 0x1C, 0x38, 0x60, 0x20, 0x68, 0x6F, 0xF3, 0x0F, 0x00, 0x20, 0x60, 0x22, 0x68, 0x38, 0x68, 0x10, 0x43, 0x20, 0x60, 0xE8, 0x68, 0xC0, 0x0B, 0x0F, 0xD3, 0xD8, 0xF8, 0x00, 0x00, 0x00, 0xF1, 0x01, 0x00, 0xC8, 0xF8, 0x00, 0x00, 0x20, 0x68, 0x6F, 0xF3, 0x1F, 0x40, 0x20, 0x60, 0xD8, 0xF8, 0x00, 0x20, 0x20, 0x68, 0x40, 0xEA, 0x02, 0x40, 0x20, 0x60, 0x49, 0xB9, 0xB9, 0xF1, 0x00, 0x0F, 0x03, 0xD1, 0x30, 0x46, 0x07, 0xF0, 0xBE, 0xF9, 0x02, 0xE0, 0x48, 0x46, 0x07, 0xF0, 0x06, 0xFA, 0x6C, 0x17, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x68, 0x46, 0x0E, 0xF0, 0x85, 0xFB, 0x00, 0x9E, 0x00, 0x2E, 0x96, 0xD1, 0x05, 0xB0, 0xBD, 0xE8, 0xF0, 0x87, 0xC0, 0x46 , -0x9C, 0x20, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x23, 0xF0, 0x2A, 0xFE, 0x74, 0x47, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0B, 0x21, 0x21, 0xF0, 0x41, 0xFA, 0x20, 0x68, 0x18, 0x4B, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x21, 0xF0, 0x1C, 0xF9, 0x0A, 0xE0, 0x20, 0x68, 0x00, 0x68, 0x0C, 0x21, 0x40, 0xF0, 0x20, 0x00, 0x21, 0xF0, 0x14, 0xF9, 0x10, 0x57, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0xA8, 0x20, 0xF0, 0x97, 0xF9, 0x01, 0x98, 0x5C, 0x57, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x02, 0xA8, 0x20, 0xF0, 0x71, 0xF9, 0x03, 0x98, 0x00, 0x58, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0xF0, 0x20, 0xF9, 0x1C, 0x58, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0xF0, 0x12, 0xF9, 0x54, 0x58, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, 0xA8, 0x20, 0xF0, 0xF5, 0xF8, 0x04, 0xAB, 0x04, 0x62, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x20, 0x79, 0x1F, 0xF0, 0x1B, 0xFD, 0x69, 0xE0, 0x60, 0x93, 0x00, 0x00, 0x40, 0x00 , -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0xA6, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x78, 0x1B, 0xF0, 0x39, 0xFB, 0x28, 0x46, 0x90, 0xA8, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x78, 0x1B, 0xF0, 0x69, 0xF9, 0x1E, 0x48, 0x34, 0xAD, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x09, 0x68, 0xFF, 0x29, 0x98, 0xAD, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x10, 0xD4, 0x21, 0xD4, 0xB2, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, 0xD0, 0x1A, 0xF0, 0x47, 0xFC, 0x20, 0x98, 0xAC, 0xC5, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x78, 0x19, 0xF0 , -0xDB, 0xFA, 0x09, 0x49, 0x28, 0xC6, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x19, 0xF0, 0x9E, 0xFA, 0xDC, 0xD3, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0xB5, 0x18, 0xF0, 0xAB, 0xFC, 0x00, 0xF0, 0x03, 0xF8, 0x00, 0xBD, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xDF, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x17, 0xF0, 0xA8, 0xFD, 0xCC, 0xEB, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x38, 0x78, 0x17, 0xF0, 0x77, 0xF8, 0x38, 0x78, 0x16, 0xF0, 0xF0, 0xFF, 0xA8, 0xF7, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0E, 0x49, 0x09, 0x68, 0x23, 0x22, 0x41, 0x61, 0xC8, 0xF7, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x31, 0x2E, 0x31, 0x39, 0x2E, 0x33, 0x31, 0x34, 0x5F, 0x4E, 0x65, 0x77, 0x5F, 0x43, 0x43, 0x41, 0x5F, 0x61, 0x6C, 0x67, 0x6F, 0x72, 0x69, 0x74, 0x68, 0x6D, 0x00, 0xC0, 0x74, 0x56, 0x30, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4C, 0xF9, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x02, 0xA8, 0x16, 0xF0, 0x79, 0xF8 , -0x12, 0xE0, 0x38, 0xFA, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0xA8, 0x16, 0xF0, 0x03, 0xF8, 0x32, 0x20, 0x94, 0xFB, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x0C, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x05, 0xA8, 0x14, 0xF0, 0x05, 0xFF, 0x01, 0xF0, 0x10, 0x1B, 0x01, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 , -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x1E, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x13, 0xF0, 0x46, 0xBF, 0x18, 0x30, 0x01, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x30, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x12, 0xF0, 0xD8, 0xFC, 0x9C, 0x31, 0x01, 0x00, 0x08, 0x00 , -0x00, 0x00, 0x68, 0x46, 0x12, 0xF0, 0x51, 0xFC, 0xFE, 0xF7, 0xF0, 0x35, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x68, 0x46, 0x12, 0xF0, 0x27, 0xFA, 0xFE, 0xF7, 0xF0, 0x3D, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x05, 0xA9, 0x11, 0xF0, 0x27, 0xFE, 0x20, 0x6F, 0xD0, 0x62, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0xB8, 0xFB, 0x80, 0x7E, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0xDF, 0xF8, 0x58, 0x82, 0xE0, 0x7E, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00, 0x0D, 0xF0, 0x6A, 0xFE, 0x0B, 0xF0, 0x9A, 0xF9, 0x03, 0x20, 0xA8, 0xF5, 0x88, 0x71, 0x08, 0x60, 0xF2, 0xF7, 0x16, 0xF9, 0x7A, 0x48, 0x6B, 0x49, 0x9C, 0x7F, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x70, 0x51, 0x4D, 0xC4, 0x7F, 0x01, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x40, 0x49, 0x00, 0xF1, 0x52, 0x00, 0x3A, 0x4A, 0xA8, 0x81, 0x28, 0x83, 0xE8, 0x83, 0xE8, 0x84, 0xA8, 0x85, 0x2A, 0x60, 0x39, 0x48, 0x41, 0xF2, 0x11, 0x12, 0x2A, 0x85, 0x18, 0x90, 0x19, 0x91 , -0x39, 0x49, 0x1A, 0x91, 0x39, 0x49, 0x1B, 0x91, 0x39, 0x49, 0x20, 0x46, 0xDF, 0xF8, 0xC4, 0x90, 0x1C, 0x91, 0x38, 0x49, 0xDF, 0xF8, 0xC0, 0xB0, 0x31, 0x4E, 0x1D, 0x91, 0x48, 0x80, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x0D, 0xF0, 0x7C, 0xFA, 0xB4, 0x80, 0x01, 0x00, 0x34, 0x00, 0x00, 0x00, 0x34, 0x12, 0x66, 0x09, 0x84, 0x6B, 0x00, 0x20, 0x94, 0x70, 0x00, 0x20, 0xB4, 0x70, 0x00, 0x20, 0xC4, 0x78, 0x00, 0x20, 0x50, 0x7A, 0x00, 0x20, 0xFE, 0xFF, 0x03, 0x00, 0xA4, 0x70, 0x00, 0x20, 0xB0, 0x70, 0x00, 0x20, 0xB8, 0x70, 0x00, 0x20, 0x60, 0x55, 0x30, 0x80, 0x3C, 0x5C, 0x00, 0x20, 0x04, 0x74, 0x00, 0x20, 0xB8, 0xE4, 0x01, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x20, 0x78, 0x07, 0xF0, 0x01, 0xFC, 0x20, 0x78, 0x07, 0xF0, 0x7A, 0xFB, 0x04, 0x4D, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x2D, 0xE9, 0xF0, 0x4F, 0xAD, 0xF1, 0x8C, 0x0D, 0x04, 0x68, 0x0F, 0x30, 0x03, 0x94, 0xFE, 0xF7, 0xDB, 0xFA, 0x04, 0xF1, 0x14, 0x00 , -0x04, 0x90, 0x21, 0x7D, 0x00, 0x20, 0x21, 0xF0, 0x73, 0x01, 0x88, 0x29, 0x08, 0xBF, 0x01, 0x20, 0x05, 0x90, 0x03, 0x98, 0x00, 0x1D, 0x06, 0x90, 0x5D, 0x48, 0x00, 0x68, 0x01, 0x28, 0x40, 0xF0, 0xFA, 0x83, 0x5B, 0x4D, 0x5C, 0x48, 0xDF, 0xF8, 0x70, 0x91, 0x29, 0x68, 0xDF, 0xF8, 0x70, 0x81, 0xDF, 0xF8, 0x74, 0xA1, 0x88, 0x42, 0x21, 0xD1, 0x10, 0x22, 0x00, 0x21, 0x48, 0x46, 0x4F, 0x46, 0xFB, 0xF7, 0xB7, 0xFE, 0x10, 0x22, 0x00, 0x21, 0x40, 0x46, 0xFB, 0xF7, 0xB2, 0xFE, 0x54, 0x49, 0x08, 0x68, 0x40, 0xF4, 0x80, 0x10, 0x08, 0x60, 0x01, 0x20, 0x51, 0x46, 0x08, 0x60, 0x00, 0x21, 0x29, 0x60, 0x39, 0x78, 0x46, 0x46, 0x00, 0x91, 0x31, 0x78, 0x41, 0xF2, 0x11, 0x13, 0x04, 0x22, 0x01, 0x91, 0x07, 0x21, 0x02, 0x90, 0x03, 0x20, 0xF3, 0xF7, 0x41, 0xFC, 0x51, 0x46, 0x07, 0x91, 0x08, 0x68, 0x56, 0x49, 0xDF, 0xF8, 0x5C, 0xB1, 0x01, 0x28, 0x08, 0x91, 0x56, 0x49, 0xDF, 0xF8, 0x48, 0xA1, 0x09, 0x91, 0x55, 0x49 , -0x0A, 0x91, 0x44, 0x49, 0x0B, 0x91, 0x44, 0x49, 0x0C, 0x91, 0x44, 0x49, 0x0D, 0x91, 0x44, 0x49, 0x0E, 0x91, 0x44, 0x49, 0x0F, 0x91, 0x44, 0x49, 0x10, 0x91, 0x44, 0x49, 0xCC, 0x4D, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x11, 0x91, 0x44, 0x49, 0x12, 0x91, 0x44, 0x49, 0x13, 0x91, 0x44, 0x49, 0x14, 0x91, 0x44, 0x49, 0x15, 0x91, 0x44, 0x49, 0x16, 0x91, 0x9F, 0x49, 0x17, 0x91, 0x9F, 0x49, 0x18, 0x91, 0x9F, 0x49, 0x19, 0x91, 0x9F, 0x49, 0x1A, 0x91, 0x9F, 0x49, 0x1B, 0x91, 0x9F, 0x49, 0x1C, 0x91, 0x9F, 0x49, 0x1D, 0x91, 0x9F, 0x49, 0x1E, 0x91, 0x9F, 0x49, 0x1F, 0x91, 0x40, 0xF0, 0x00, 0x81, 0x04, 0x98, 0x40, 0x78, 0x00, 0xF0, 0x03, 0x01, 0x01, 0x29, 0x40, 0xF0, 0xF9, 0x80, 0x04, 0x99, 0x09, 0x78, 0x01, 0xF0, 0x0C, 0x01, 0x08, 0x29, 0x40, 0xF0, 0xF2, 0x80, 0x06, 0x99, 0x09, 0x88, 0xA1, 0xF1, 0x3C, 0x01, 0x0E, 0xB2, 0x05, 0x99, 0x11, 0xB1, 0xA6, 0xF1, 0x02, 0x06, 0x36, 0xB2, 0xC0, 0x09, 0x4F, 0xF0 , -0x00, 0x07, 0x15, 0xD3, 0x08, 0x3E, 0x36, 0xB2, 0x03, 0x2E, 0x10, 0xD0, 0x17, 0x2E, 0x0E, 0xD0, 0x08, 0x3E, 0x36, 0xB2, 0x03, 0x2E, 0x08, 0xD0, 0x17, 0x2E, 0x06, 0xD0, 0x36, 0x1F, 0x36, 0xB2, 0x03, 0x2E, 0x14, 0xBF, 0x17, 0x2E, 0x02, 0x27, 0x02, 0xE0, 0x03, 0x27, 0x00, 0xE0, 0x01, 0x27, 0x03, 0x2E, 0x18, 0xBF, 0x17, 0x2E, 0x04, 0x9A, 0x40, 0xF0, 0xC8, 0x80, 0x0A, 0x32, 0x12, 0xF8, 0x01, 0x1B, 0x05, 0x24, 0x12, 0xF8, 0x01, 0x3B, 0x4B, 0x40, 0x64, 0x1E, 0xD9, 0xB2, 0xF9, 0xD1, 0x81, 0xEA, 0x21, 0x11, 0x03, 0x2E, 0x94, 0x4E, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x01, 0xF0, 0x0F, 0x01, 0x48, 0x46, 0x35, 0xD0, 0x43, 0x46, 0xCA, 0x5C, 0x52, 0x1C, 0xCA, 0x54, 0x0C, 0x18, 0x33, 0xE0, 0x50, 0x57, 0x02, 0x00, 0x04, 0x74, 0x00, 0x20, 0x34, 0x12, 0x66, 0x09, 0x60, 0x57, 0x02, 0x00, 0x70, 0x57, 0x02, 0x00, 0xC8, 0x48, 0x30, 0x80, 0x4C, 0x57, 0x02, 0x00, 0x88, 0x57, 0x02, 0x00, 0x80, 0x57, 0x02, 0x00 , -0x18, 0x58, 0x02, 0x00, 0x20, 0x58, 0x02, 0x00, 0x28, 0x58, 0x02, 0x00, 0x30, 0x58, 0x02, 0x00, 0x38, 0x58, 0x02, 0x00, 0x40, 0x58, 0x02, 0x00, 0xE4, 0x58, 0x02, 0x00, 0xE2, 0x58, 0x02, 0x00, 0x14, 0x58, 0x02, 0x00, 0xEF, 0x58, 0x02, 0x00, 0xE0, 0x58, 0x02, 0x00, 0xEE, 0x58, 0x02, 0x00, 0x5C, 0x57, 0x02, 0x00, 0xE6, 0x58, 0x02, 0x00, 0xE8, 0x58, 0x02, 0x00, 0x0C, 0x18, 0x20, 0x78, 0x40, 0x1C, 0x20, 0x70, 0x20, 0x78, 0x43, 0x46, 0x03, 0xEB, 0x01, 0x08, 0x0A, 0x28, 0x76, 0xDB, 0x98, 0xF8, 0x00, 0x00, 0x0A, 0x28, 0x72, 0xDB, 0x94, 0x48, 0x00, 0x25, 0x01, 0x60, 0x04, 0x98, 0x00, 0xF1, 0x0A, 0x09, 0x40, 0x78, 0x41, 0x08, 0x24, 0xBF, 0x04, 0x99, 0x09, 0x1D, 0x04, 0xD2, 0x80, 0x08, 0x2E, 0xBF, 0x49, 0x46, 0x04, 0x99, 0x10, 0x31, 0x0B, 0x98, 0x06, 0x22, 0xFA, 0xF7, 0xB9, 0xFC, 0x0C, 0x98, 0x06, 0x22, 0x49, 0x46, 0xFA, 0xF7, 0xB4, 0xFC, 0x9B, 0x48, 0x9A, 0x49, 0x5C, 0x4F, 0x02, 0x00, 0xC8, 0x00 , -0x00, 0x00, 0x00, 0x78, 0x08, 0x22, 0x08, 0x60, 0x58, 0x46, 0x07, 0x60, 0x0D, 0x98, 0x29, 0x46, 0xFB, 0xF7, 0xAF, 0xFD, 0x08, 0x22, 0x0E, 0x98, 0x29, 0x46, 0xFB, 0xF7, 0xAA, 0xFD, 0x08, 0x22, 0x0F, 0x98, 0x29, 0x46, 0xFB, 0xF7, 0xA5, 0xFD, 0x08, 0x22, 0x10, 0x98, 0x29, 0x46, 0xFB, 0xF7, 0xA0, 0xFD, 0x08, 0x22, 0x11, 0x98, 0x29, 0x46, 0xFB, 0xF7, 0x9B, 0xFD, 0x08, 0x22, 0x12, 0x98, 0x29, 0x46, 0xFB, 0xF7, 0x96, 0xFD, 0x07, 0x99, 0x02, 0x20, 0x08, 0x60, 0x13, 0x99, 0x28, 0x46, 0x08, 0x80, 0x08, 0x99, 0x08, 0x70, 0x14, 0x99, 0x08, 0x70, 0x15, 0x99, 0x08, 0x60, 0x16, 0x99, 0x08, 0x70, 0x17, 0x99, 0x08, 0x60, 0x18, 0x99, 0x08, 0x60, 0x19, 0x99, 0x08, 0x60, 0x09, 0x99, 0x08, 0x80, 0x0A, 0x99, 0x08, 0x80, 0x1A, 0x99, 0x08, 0x80, 0x7D, 0x49, 0x0D, 0x60, 0x1B, 0x99, 0x08, 0x70, 0x1C, 0x99, 0x08, 0x70, 0x1D, 0x99, 0x08, 0x70, 0x1E, 0x99, 0x08, 0x80, 0x1F, 0x99, 0x08, 0x80, 0x51, 0x46, 0x08, 0x80 , -0x20, 0x78, 0x00, 0x96, 0x04, 0x22, 0x01, 0x90, 0x98, 0xF8, 0x00, 0x00, 0x41, 0xF2, 0x14, 0x13, 0x07, 0x21, 0x02, 0x90, 0x03, 0x20, 0xF3, 0xF7, 0x07, 0xFB, 0x07, 0x98, 0xA2, 0x49, 0x00, 0x68, 0x20, 0x91, 0xA2, 0x49, 0x05, 0x28, 0x21, 0x91, 0x9E, 0x49, 0x22, 0x91, 0x40, 0xF0, 0x37, 0x82, 0x04, 0x98, 0x40, 0x78, 0x24, 0x50, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x41, 0x08, 0x24, 0xBF, 0x04, 0x99, 0x09, 0x1D, 0x05, 0xD2, 0x80, 0x08, 0x27, 0xBF, 0x04, 0x99, 0x0A, 0x31, 0x04, 0x99, 0x10, 0x31, 0x0B, 0x98, 0xF8, 0xF7, 0x2D, 0xFC, 0x01, 0x28, 0x04, 0x98, 0x40, 0xF0, 0x23, 0x82, 0x40, 0x78, 0x00, 0xF0, 0x03, 0x00, 0x03, 0x28, 0x18, 0xD0, 0x02, 0x28, 0x07, 0xBF, 0x04, 0x99, 0x10, 0x31, 0x04, 0x99, 0x0A, 0x31, 0x13, 0xE0, 0x48, 0x58, 0x02, 0x00, 0x4C, 0x58, 0x02, 0x00, 0x50, 0x58, 0x02, 0x00, 0xF0, 0x58, 0x02, 0x00, 0xF2, 0x58, 0x02, 0x00, 0xF3, 0x58, 0x02, 0x00, 0xF4, 0x58, 0x02, 0x00, 0xEA, 0x58 , -0x02, 0x00, 0xEC, 0x58, 0x02, 0x00, 0x04, 0x99, 0x18, 0x31, 0x0C, 0x98, 0xF8, 0xF7, 0x06, 0xFC, 0x04, 0x99, 0x01, 0x28, 0x40, 0xF0, 0xFC, 0x81, 0x49, 0x78, 0x01, 0xF0, 0x03, 0x01, 0x01, 0x29, 0x40, 0xF0, 0xF6, 0x81, 0x59, 0x46, 0x09, 0x68, 0x04, 0x9A, 0x8E, 0x46, 0x51, 0x46, 0xD2, 0x8A, 0x0B, 0x88, 0x12, 0x11, 0x93, 0x42, 0x00, 0xF0, 0x37, 0x82, 0x0A, 0x80, 0x06, 0x99, 0x09, 0x88, 0x3C, 0x39, 0x0B, 0xB2, 0x71, 0x46, 0x49, 0x1E, 0x09, 0xD0, 0x49, 0x1E, 0x04, 0xD0, 0x49, 0x1E, 0x08, 0xD1, 0xA3, 0xF1, 0x10, 0x03, 0x04, 0xE0, 0xA3, 0xF1, 0x14, 0x03, 0x01, 0xE0, 0xA3, 0xF1, 0x08, 0x03, 0x1B, 0xB2, 0x05, 0x98, 0x10, 0xB1, 0xA3, 0xF1, 0x02, 0x03, 0x1B, 0xB2, 0xEC, 0x50, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x00, 0x2B, 0x00, 0xF1, 0xCE, 0x81, 0x16, 0x98, 0x40, 0xF2, 0x77, 0x51, 0x99, 0x42, 0x0B, 0x90, 0x14, 0x98, 0x05, 0x90, 0x00, 0xF0, 0xA3, 0x81, 0x08, 0x46, 0x00, 0xF1, 0x3C, 0x00, 0x98, 0x42 , -0x05, 0x9A, 0x00, 0xF0, 0x9A, 0x81, 0xDF, 0xF8, 0x48, 0x82, 0x14, 0x78, 0x0B, 0x9A, 0xBB, 0x2C, 0x12, 0x78, 0x0C, 0x92, 0x63, 0xD1, 0xDD, 0xF8, 0x68, 0xC0, 0xBC, 0xF9, 0x00, 0x20, 0x91, 0x42, 0x18, 0xBF, 0x90, 0x42, 0x5B, 0xD1, 0x1C, 0x2B, 0x4F, 0xF0, 0x00, 0x00, 0xC0, 0xF2, 0x82, 0x81, 0x3D, 0x2B, 0x13, 0x9D, 0x80, 0xF2, 0x7E, 0x81, 0xA3, 0xF1, 0x1C, 0x01, 0x09, 0xB2, 0x29, 0x80, 0x1E, 0x9A, 0xDD, 0xF8, 0x30, 0x90, 0xB2, 0xF9, 0x00, 0x60, 0xB9, 0xF1, 0x01, 0x0F, 0x15, 0xD1, 0xDD, 0xF8, 0x24, 0x90, 0x03, 0x2E, 0x0D, 0xDA, 0xB9, 0xF9, 0x00, 0x70, 0xB9, 0x42, 0x07, 0xD0, 0x01, 0x26, 0x16, 0x80, 0x4A, 0x46, 0x0E, 0x46, 0x03, 0xE0, 0xC0, 0x46, 0x90, 0x57, 0x02, 0x00, 0x76, 0x1C, 0x16, 0x80, 0x1B, 0x9A, 0x16, 0x78, 0x1D, 0x9A, 0x16, 0x70, 0x0C, 0x9A, 0x1F, 0x9E, 0x02, 0x2A, 0x28, 0xD1, 0xB6, 0xF9, 0x00, 0x20, 0xBE, 0xF1, 0x00, 0x0F, 0x1A, 0xD0, 0x03, 0x2A, 0x35, 0x46, 0x0B, 0xDA, 0x0A, 0x9E , -0xB6, 0xF9, 0x00, 0x70, 0xB9, 0x42, 0x04, 0xD0, 0x01, 0x22, 0x2A, 0x80, 0x0A, 0x46, 0x35, 0x46, 0x00, 0xE0, 0xB4, 0x51, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x52, 0x1C, 0x2A, 0x80, 0x1C, 0x99, 0x0A, 0x78, 0x1D, 0x99, 0x0A, 0x70, 0x0F, 0xE0, 0xC0, 0x46, 0x58, 0x57, 0x02, 0x00, 0xA6, 0x64, 0x00, 0x20, 0x54, 0x57, 0x02, 0x00, 0x28, 0x80, 0x05, 0x99, 0x08, 0x70, 0x08, 0x9A, 0x11, 0x78, 0x41, 0xF0, 0x04, 0x01, 0x11, 0x70, 0x04, 0x46, 0x45, 0x46, 0xAC, 0xF8, 0x00, 0x00, 0x28, 0x70, 0xCC, 0x2C, 0x09, 0x9A, 0x40, 0xF0, 0x00, 0x81, 0xDD, 0xF8, 0x7C, 0xC0, 0x0A, 0x99, 0x1E, 0x9F, 0x45, 0x46, 0xB1, 0xF9, 0x00, 0x60, 0xB2, 0xF9, 0x00, 0x90, 0x28, 0x78, 0xCD, 0xF8, 0x50, 0xC0, 0x16, 0x91, 0x0A, 0x97, 0x13, 0x92, 0x09, 0x95, 0x0C, 0x99, 0x01, 0x29, 0x05, 0xD1, 0x05, 0x9A, 0xB0, 0xEB, 0x49, 0x0F, 0x01, 0xD1, 0x00, 0x21, 0x11, 0x70, 0x0C, 0x99, 0x02, 0x29, 0x05, 0xD1, 0x05, 0x9A, 0xB0, 0xEB, 0x46, 0x0F , -0x01, 0xD1, 0x00, 0x21, 0x11, 0x70, 0xB3, 0xF5, 0x14, 0x7F, 0x40, 0xF3, 0xBA, 0x80, 0x40, 0xF2, 0x51, 0x31, 0x99, 0x42, 0x08, 0x99, 0x40, 0xF3, 0xB4, 0x80, 0x09, 0x78, 0x06, 0x29, 0x00, 0xF0, 0xB0, 0x80, 0xA3, 0xF2, 0x51, 0x21, 0x0B, 0xB2, 0x4F, 0xEA, 0xE3, 0x01, 0x03, 0xEB, 0x11, 0x71, 0x4F, 0xEA, 0x21, 0x11, 0xCA, 0xB2, 0x4F, 0xEA, 0xE3, 0x01, 0x03, 0xEB, 0x11, 0x71, 0x15, 0x9D, 0x21, 0xF0, 0x0F, 0x01, 0xA3, 0xEB, 0x01, 0x03, 0x1D, 0x99, 0x2E, 0x68, 0x7C, 0x52, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x91, 0xF8, 0x00, 0xE0, 0x5F, 0xFA, 0x83, 0xF8, 0x60, 0xB1, 0x31, 0x18, 0x11, 0xF8, 0x01, 0x1C, 0x51, 0x40, 0xCB, 0xB2, 0x07, 0xE0, 0xC0, 0x46, 0x58, 0x58, 0x02, 0x00, 0x54, 0x58, 0x02, 0x00, 0xDC, 0x58, 0x02, 0x00, 0x13, 0x46, 0x19, 0x99, 0xDD, 0xF8, 0x6C, 0xA0, 0xDD, 0xF8, 0x70, 0xB0, 0xD1, 0xF8, 0x00, 0xC0, 0x00, 0xF0, 0x0F, 0x01, 0x99, 0x42, 0x22, 0xD0, 0x0A, 0x9B, 0x86, 0x45, 0x9A, 0xF8 , -0x00, 0x10, 0xB3, 0xF9, 0x00, 0x30, 0x9B, 0xF8, 0x00, 0x50, 0x15, 0xDD, 0x37, 0x5C, 0x44, 0x1C, 0x82, 0xEA, 0x07, 0x0C, 0x04, 0xF0, 0x0F, 0x07, 0x67, 0x45, 0x0B, 0xD0, 0xA6, 0x45, 0x06, 0x44, 0x0A, 0xDD, 0x76, 0x78, 0x72, 0x40, 0x86, 0x1C, 0x06, 0xF0, 0x0F, 0x06, 0x96, 0x42, 0x03, 0xD1, 0xC0, 0x1C, 0x4D, 0xE0, 0x80, 0x1C, 0x4B, 0xE0, 0x05, 0x9E, 0x00, 0x22, 0x32, 0x70, 0x4A, 0xE0, 0x00, 0xF0, 0x1F, 0x01, 0x01, 0x22, 0x8A, 0x40, 0x17, 0x99, 0xC4, 0x10, 0x0B, 0x68, 0x24, 0xF0, 0x03, 0x01, 0x5C, 0xF8, 0x01, 0x70, 0x3A, 0x42, 0x32, 0xD1, 0x5F, 0x58, 0x3A, 0x42, 0x06, 0x44, 0x1F, 0xD0, 0x18, 0x9B, 0x37, 0x78, 0x1B, 0x68, 0xB8, 0x45, 0x04, 0xD1, 0x58, 0x58, 0x02, 0x42, 0x19, 0xD0, 0x63, 0x46, 0x15, 0xE0, 0xA1, 0x10, 0x8C, 0x00, 0x19, 0x59, 0x91, 0x43, 0x19, 0x51, 0x00, 0x90, 0x30, 0x78, 0x01, 0x90, 0x44, 0x53, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x03, 0x20, 0x06, 0x21, 0x02, 0x46, 0x4D, 0xF6 , -0x80, 0x53, 0xF3, 0xF7, 0x63, 0xF9, 0x09, 0x99, 0x28, 0x68, 0x0E, 0x78, 0x36, 0x18, 0x06, 0xE0, 0xE3, 0x58, 0x02, 0x00, 0xA0, 0x10, 0x81, 0x00, 0x58, 0x58, 0x02, 0x43, 0x5A, 0x50, 0x86, 0xF8, 0x00, 0x80, 0x0B, 0x98, 0x00, 0x78, 0x0C, 0x90, 0x13, 0x98, 0xB0, 0xF9, 0x00, 0x90, 0x09, 0x98, 0x00, 0x78, 0x0A, 0x9A, 0x40, 0x1C, 0x9B, 0xF8, 0x00, 0x50, 0x9A, 0xF8, 0x00, 0x10, 0xB2, 0xF9, 0x00, 0x30, 0x09, 0x9A, 0xC0, 0xB2, 0x10, 0x70, 0x0C, 0x9A, 0x01, 0x2A, 0x03, 0xD1, 0x88, 0x42, 0xC8, 0xBF, 0x8A, 0xF8, 0x00, 0x00, 0x0C, 0x99, 0x02, 0x29, 0x07, 0xD1, 0xA8, 0x42, 0xC8, 0xBF, 0x8B, 0xF8, 0x00, 0x00, 0x02, 0xE0, 0x0A, 0x98, 0xB0, 0xF9, 0x00, 0x30, 0xB9, 0xF1, 0x00, 0x0F, 0x06, 0xDD, 0x03, 0x2B, 0x04, 0xD1, 0x11, 0x98, 0x01, 0x22, 0x49, 0x46, 0x00, 0xF0, 0x72, 0xFB, 0x16, 0x98, 0xB0, 0xF9, 0x00, 0x10, 0x14, 0x98, 0x00, 0x29, 0xB0, 0xF9, 0x00, 0x00, 0x05, 0xDD, 0x03, 0x28, 0x03, 0xD1, 0x12, 0x98 , -0x02, 0x22, 0x00, 0xF0, 0x64, 0xFB, 0x05, 0x98, 0x04, 0x78, 0x0B, 0x98, 0x00, 0x78, 0x0C, 0x90, 0x08, 0x98, 0xBB, 0x2C, 0x01, 0x78, 0x02, 0xD0, 0xAA, 0x2C, 0x2F, 0xD0, 0x31, 0xE0, 0x0C, 0x98, 0x01, 0x28, 0x0B, 0xD1, 0x0D, 0x98, 0x17, 0x9A, 0x10, 0x60, 0x0C, 0x54, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x0F, 0x98, 0x18, 0x9A, 0x10, 0x60, 0x19, 0x9A, 0x11, 0x98, 0x10, 0x60, 0x47, 0x4A, 0x15, 0x98, 0x02, 0x60, 0x0C, 0x98, 0x02, 0x28, 0x0B, 0xD1, 0x0E, 0x98, 0x17, 0x9A, 0x10, 0x60, 0x10, 0x98, 0x18, 0x9A, 0x10, 0x60, 0x19, 0x9A, 0x12, 0x98, 0x10, 0x60, 0x41, 0x4A, 0x15, 0x98, 0x02, 0x60, 0xCC, 0x20, 0x0F, 0xE0, 0x08, 0x99, 0x09, 0x78, 0x0C, 0xE0, 0x02, 0x20, 0x00, 0xE0, 0x01, 0x20, 0x0B, 0x99, 0x08, 0x70, 0x1A, 0x99, 0x0B, 0x80, 0x13, 0x99, 0x00, 0x20, 0x08, 0x80, 0x08, 0x98, 0x01, 0x78, 0xBB, 0x20, 0x05, 0x9A, 0x10, 0x70, 0x06, 0x29, 0x07, 0x99, 0x11, 0xD1, 0x06, 0x20, 0x08, 0x60, 0x20, 0x98 , -0x00, 0x25, 0x05, 0x70, 0x21, 0x98, 0x29, 0x46, 0x04, 0x22, 0xFB, 0xF7, 0x27, 0xFB, 0x01, 0x20, 0x00, 0xF0, 0x3A, 0xFA, 0x02, 0x20, 0x00, 0xF0, 0x37, 0xFA, 0x22, 0x98, 0x05, 0x60, 0x07, 0x98, 0x04, 0x99, 0x00, 0x68, 0x07, 0x28, 0x44, 0xD1, 0x09, 0x78, 0x03, 0x9C, 0x80, 0x29, 0x40, 0xD1, 0x38, 0x34, 0x21, 0x78, 0x64, 0x1C, 0x22, 0x46, 0x00, 0x29, 0x3A, 0xD1, 0x20, 0x98, 0x90, 0xF8, 0x00, 0xA0, 0x22, 0x98, 0x05, 0x90, 0xD0, 0xF8, 0x00, 0x90, 0x51, 0x46, 0x48, 0x46, 0xFD, 0xF7, 0x79, 0xF9, 0x5F, 0xFA, 0x80, 0xF8, 0x21, 0x9F, 0x15, 0x78, 0x51, 0x46, 0x48, 0x46, 0x17, 0xF8, 0x08, 0x30, 0xFD, 0xF7, 0xD4, 0x54, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x6F, 0xF9, 0x1E, 0x46, 0x1B, 0x1D, 0xC0, 0xB2, 0x38, 0x5C, 0x00, 0x1D, 0xA8, 0x42, 0x28, 0x46, 0x07, 0xDD, 0x80, 0x18, 0x82, 0x1C, 0x10, 0x78, 0x2D, 0x18, 0xAD, 0x1C, 0xAD, 0xB2, 0xAB, 0x42, 0xF7, 0xDC, 0x04, 0xF8, 0x01, 0x6B, 0x11, 0x49, 0x32, 0x46 , -0x20, 0x46, 0x01, 0xEB, 0x48, 0x11, 0xFA, 0xF7, 0xDC, 0xF9, 0xAD, 0x1B, 0xFF, 0x20, 0x34, 0x19, 0xAD, 0x1E, 0x04, 0xF8, 0x01, 0x0B, 0x25, 0x70, 0x05, 0x98, 0x01, 0x68, 0x49, 0x1C, 0x01, 0x60, 0x07, 0x98, 0x00, 0x68, 0x07, 0x28, 0x04, 0xD0, 0x06, 0x99, 0x08, 0x68, 0x20, 0xF4, 0x80, 0x30, 0x08, 0x60, 0x23, 0xB0, 0xBD, 0xE8, 0xF0, 0x8F, 0xC0, 0x46, 0x94, 0x57, 0x02, 0x00, 0xD4, 0x57, 0x02, 0x00, 0x5C, 0x58, 0x02, 0x00, 0x6E, 0x48, 0x2D, 0xE9, 0xF0, 0x47, 0x6E, 0x4D, 0x82, 0x89, 0x4A, 0xF6, 0x55, 0x21, 0xAD, 0xF5, 0xFE, 0x7D, 0x91, 0x42, 0x4F, 0xF0, 0x00, 0x01, 0xAD, 0xF1, 0x38, 0x0D, 0x12, 0xD1, 0x29, 0x60, 0x68, 0x4A, 0x11, 0x70, 0x41, 0xF2, 0x10, 0x41, 0x81, 0x81, 0x4F, 0xF6, 0xFF, 0x70, 0x66, 0x49, 0x08, 0x60, 0x28, 0x68, 0x00, 0x90, 0x02, 0x22, 0x05, 0x21, 0x03, 0x20, 0x41, 0xF2, 0x34, 0x23, 0xF3, 0xF7, 0x48, 0xF8, 0x29, 0x68, 0x61, 0x4C, 0x01, 0x29, 0x20, 0x68, 0x40, 0xF0, 0xAF, 0x80 , -0x5F, 0x4D, 0x02, 0x28, 0x29, 0x68, 0x23, 0xD1, 0x9C, 0x55, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x5E, 0x48, 0x00, 0x68, 0x5F, 0x4A, 0x12, 0x5C, 0x00, 0x92, 0x01, 0x91, 0x5E, 0x49, 0x09, 0x68, 0x02, 0x91, 0x5B, 0x49, 0x0B, 0x5C, 0x03, 0x20, 0x07, 0x21, 0x04, 0x22, 0xF3, 0xF7, 0x2E, 0xF8, 0x5B, 0x49, 0x4A, 0x79, 0x59, 0x48, 0x00, 0x92, 0x02, 0x79, 0x01, 0x92, 0x40, 0x79, 0x04, 0x22, 0x02, 0x90, 0x03, 0x20, 0x0B, 0x79, 0x07, 0x21, 0xF3, 0xF7, 0x20, 0xF8, 0x03, 0x20, 0x20, 0x60, 0xEC, 0xF7, 0x1A, 0xFF, 0x20, 0x68, 0x29, 0x68, 0x04, 0x28, 0x15, 0xD1, 0x0D, 0x20, 0x8D, 0xF8, 0x10, 0x00, 0x00, 0x25, 0x8D, 0xF8, 0x14, 0x50, 0x8D, 0xF8, 0x15, 0x10, 0x28, 0x46, 0x63, 0x21, 0x00, 0xF0, 0xAA, 0xFB, 0x63, 0x21, 0x28, 0x46, 0x00, 0xF0, 0xFA, 0xFA, 0x03, 0xA9, 0x04, 0xA8, 0xE0, 0xF7, 0xCA, 0xFC, 0x05, 0x20, 0x20, 0x60, 0x46, 0x4D, 0x05, 0x28, 0x29, 0x68, 0x01, 0xF1, 0x01, 0x01, 0x29, 0x60, 0x1D, 0xD1 , -0x44, 0x4A, 0x8A, 0x42, 0x1A, 0xD1, 0x43, 0x48, 0x01, 0x68, 0x00, 0x91, 0x40, 0x68, 0x01, 0x90, 0x03, 0x20, 0x02, 0x46, 0x06, 0x21, 0x41, 0x4E, 0x33, 0x46, 0x22, 0x3B, 0xF2, 0xF7, 0xEB, 0xFF, 0x3E, 0x48, 0x01, 0x68, 0x00, 0x91, 0x40, 0x68, 0x33, 0x46, 0x06, 0x21, 0x01, 0x90, 0x03, 0x20, 0x02, 0x46, 0xF2, 0xF7, 0xE0, 0xFF, 0x00, 0x20, 0x28, 0x60, 0x20, 0x68, 0x06, 0x28, 0x47, 0xD1, 0x4F, 0xF0, 0x64, 0x56, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x07, 0x0A, 0xC4, 0xF8, 0x00, 0xA0, 0x03, 0x20, 0x48, 0xF2, 0x70, 0x53, 0x01, 0x22, 0x04, 0x21, 0xF2, 0xF7, 0xD0, 0xFF, 0xDF, 0xF8, 0xCC, 0x80, 0x31, 0x4F, 0x48, 0xF2, 0x70, 0x59, 0x01, 0x25, 0x49, 0xEA, 0x05, 0x03, 0x01, 0x22, 0x04, 0x21, 0x03, 0x20, 0xF2, 0xF7, 0xC3, 0xFF, 0x00, 0x24, 0x17, 0xF8, 0x02, 0x0F, 0x20, 0xE0, 0x69, 0x01, 0x04, 0xEB, 0x08, 0x02, 0x88, 0x18, 0xC6, 0x1C, 0x43, 0x78, 0x00, 0x93, 0x80, 0x78, 0x01, 0x90, 0x30, 0x78, 0x02, 0x90 , -0x53, 0x5C, 0x51, 0x46, 0x04, 0x22, 0x03, 0x20, 0xF2, 0xF7, 0xAE, 0xFF, 0x38, 0x78, 0x01, 0x1B, 0xB1, 0xF1, 0xFF, 0x3F, 0x08, 0xD1, 0xF0, 0x78, 0x00, 0x90, 0xB3, 0x78, 0x03, 0x20, 0x02, 0x22, 0x05, 0x21, 0xF2, 0xF7, 0xA1, 0xFF, 0x38, 0x78, 0x24, 0x1D, 0xE4, 0xB2, 0xA0, 0x42, 0xDC, 0xDC, 0xAD, 0x1C, 0xED, 0xB2, 0x04, 0x2D, 0xCD, 0xDB, 0x63, 0x21, 0x4F, 0xF4, 0x05, 0x70, 0xF1, 0xF7, 0xA3, 0xFC, 0xE1, 0xF7, 0x85, 0xFD, 0x7F, 0xB0, 0x0E, 0xB0, 0xBD, 0xE8, 0xF0, 0x87, 0xC0, 0x46, 0x04, 0x74, 0x00, 0x20, 0x50, 0x57, 0x02, 0x00, 0x6C, 0x5D, 0x02, 0x00, 0x40, 0x00, 0x3D, 0x80, 0x4C, 0x57, 0x02, 0x00, 0x58, 0x57, 0x02, 0x00, 0x90, 0x57, 0x02, 0x00, 0x60, 0x57, 0x02, 0x00, 0x70, 0x57, 0x02, 0x00, 0x5C, 0x57, 0x02, 0x00, 0x80, 0x57, 0x02, 0x00, 0x2C, 0x57, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x88, 0x57, 0x02, 0x00, 0x54, 0x57, 0x02, 0x00, 0xFF, 0xFF, 0x03, 0x00, 0x38, 0x58, 0x02, 0x00, 0x40, 0x58 , -0x02, 0x00, 0x66, 0x55, 0xDD, 0xEE, 0xDB, 0x58, 0x02, 0x00, 0x5C, 0x58, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 , -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF4, 0x57, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 , -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBC, 0x58, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 , -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2D, 0xE9, 0xFE, 0x4F, 0x4A, 0x4A, 0x49, 0x4D, 0x00, 0x90, 0xB2, 0xF9, 0x00, 0x20, 0x43, 0xA3, 0x29, 0x78, 0x01, 0x93, 0x43, 0xA3, 0x01, 0x28, 0x02, 0x93, 0x47, 0x4E, 0xDF, 0xF8, 0x1C, 0x81, 0xDF, 0xF8, 0x1C, 0x91, 0x1E, 0xD0, 0x43, 0x48, 0x04, 0x78, 0x48, 0x01, 0x87, 0x19, 0x30, 0x18, 0x01, 0x99, 0x06, 0x22, 0xF9, 0xF7, 0xC8, 0xFF, 0x40, 0x46, 0x01, 0x78, 0x00, 0x68, 0x07, 0xF1, 0x06, 0x07, 0x07, 0xF8, 0x01, 0x1B, 0x07, 0xF8, 0x01, 0x4B, 0x4F, 0xF0, 0x00, 0x01, 0x07, 0xF8, 0x01, 0x1B, 0x20, 0xB9, 0x39, 0x70, 0x28, 0x78, 0x4E, 0x46, 0x0A, 0x21, 0x58, 0xE0, 0xDF, 0xF8, 0xE4, 0xB0, 0x0F, 0xE0, 0xD4, 0xB2, 0x48, 0x01, 0x87, 0x19, 0x30, 0x18, 0x02, 0x99, 0x07, 0x22, 0xF9, 0xF7, 0xAA, 0xFF, 0xFF, 0x1D, 0x00, 0x20, 0xDF, 0xF8, 0xCC, 0xB0, 0x07, 0xF8, 0x01, 0x4B, 0x07, 0xF8, 0x01, 0x0B, 0x16, 0x2C, 0xB2, 0x46, 0xAE, 0xBF, 0x14, 0x20, 0x84, 0x59 , -0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x60, 0x1E, 0xC0, 0xB2, 0x38, 0x70, 0x4E, 0x46, 0x7F, 0x1C, 0x40, 0x1C, 0xC2, 0xB2, 0x28, 0x78, 0x5B, 0x46, 0x00, 0x21, 0x32, 0x54, 0x38, 0x46, 0x00, 0xF0, 0xBC, 0xF9, 0x28, 0x78, 0x16, 0x2C, 0x31, 0x5C, 0x01, 0xF1, 0x0A, 0x01, 0x31, 0x54, 0x00, 0xF1, 0x01, 0x00, 0xC0, 0xB2, 0x28, 0x70, 0x2B, 0xDB, 0x00, 0x99, 0x0A, 0xEB, 0x40, 0x10, 0x07, 0x46, 0x01, 0x29, 0xA4, 0xF1, 0x01, 0x09, 0x09, 0xD0, 0x01, 0x99, 0x06, 0x22, 0xF9, 0xF7, 0x79, 0xFF, 0x40, 0x46, 0x00, 0x78, 0xBF, 0x1D, 0x07, 0xF8, 0x01, 0x0B, 0x04, 0xE0, 0x02, 0x99, 0x07, 0x22, 0xF9, 0xF7, 0x6F, 0xFF, 0xFF, 0x1D, 0x07, 0xF8, 0x01, 0x4B, 0x15, 0x3C, 0x15, 0x21, 0x28, 0x78, 0xE2, 0xB2, 0x5B, 0x46, 0x07, 0xF8, 0x01, 0x1B, 0x32, 0x54, 0x07, 0xF8, 0x01, 0x9B, 0x38, 0x46, 0x00, 0xF0, 0x8B, 0xF9, 0x28, 0x78, 0x31, 0x5C, 0x0A, 0x31, 0x31, 0x54, 0x40, 0x1C, 0x28, 0x70, 0xBD, 0xE8, 0xFE, 0x8F, 0xC0, 0x46 , -0x54, 0x54, 0x54, 0x4B, 0x45, 0x59, 0x00, 0xC0, 0x54, 0x54, 0x54, 0x53, 0x53, 0x49, 0x44, 0x00, 0x54, 0x58, 0x02, 0x00, 0xE6, 0x58, 0x02, 0x00, 0xE8, 0x58, 0x02, 0x00, 0x5C, 0x58, 0x02, 0x00, 0x5C, 0x57, 0x02, 0x00, 0xDC, 0x58, 0x02, 0x00, 0xD4, 0x57, 0x02, 0x00, 0x94, 0x57, 0x02, 0x00, 0xFF, 0xB5, 0x0C, 0x46, 0x06, 0x46, 0xF7, 0xF7, 0x4C, 0x5A, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0xE3, 0xFE, 0x15, 0x49, 0x15, 0x4A, 0x0D, 0x68, 0x01, 0xA9, 0x92, 0xE8, 0x8C, 0x00, 0x81, 0xE8, 0x8C, 0x00, 0xF7, 0xF7, 0xFD, 0xFE, 0x01, 0x98, 0x11, 0x49, 0x28, 0x1A, 0x03, 0x9D, 0x25, 0x60, 0x02, 0x9A, 0x80, 0x18, 0x82, 0x42, 0x30, 0x60, 0x0E, 0xD8, 0x08, 0x46, 0x00, 0x68, 0x22, 0x68, 0x82, 0x42, 0x0E, 0xD2, 0x68, 0x46, 0xE8, 0xF7, 0xB9, 0xFF, 0x9D, 0xF8, 0x00, 0x00, 0x05, 0xF1, 0x01, 0x05, 0x30, 0xB9, 0x03, 0x95, 0x03, 0xE0, 0x25, 0x68, 0x6D, 0x1C, 0x25, 0x60, 0x0C, 0x46, 0x25, 0x60, 0x00, 0x20, 0x00, 0x90 , -0xFF, 0xBD, 0x60, 0x55, 0x30, 0x80, 0x24, 0x5D, 0x00, 0x20, 0x6C, 0x5D, 0x02, 0x00, 0x70, 0xB5, 0x4D, 0x00, 0x20, 0x2D, 0x4F, 0xF0, 0x00, 0x01, 0x0C, 0x46, 0x4F, 0xEA, 0x55, 0x13, 0x09, 0xD3, 0x50, 0xF8, 0x21, 0x60, 0xB6, 0xF1, 0xFF, 0x3F, 0x04, 0xD1, 0x49, 0x1C, 0xC9, 0xB2, 0x20, 0x3D, 0x5B, 0x1E, 0xF5, 0xD1, 0x4D, 0xB1, 0x20, 0x2D, 0x09, 0xD2, 0x01, 0x23, 0xAB, 0x40, 0x5B, 0x1E, 0x50, 0xF8, 0x21, 0x00, 0x18, 0x40, 0x83, 0x42, 0x01, 0xD1, 0x4F, 0xF0, 0x01, 0x04, 0x07, 0x48, 0x03, 0x78, 0x2C, 0xB9, 0x01, 0x21, 0x91, 0x40, 0xC9, 0x43, 0xC9, 0xB2, 0x0B, 0x40, 0x03, 0xE0, 0x01, 0x21, 0x91, 0x40, 0xC9, 0xB2, 0x0B, 0x43, 0x03, 0x70, 0x70, 0xBD, 0xC0, 0x46, 0xEE, 0x58, 0x02, 0x00, 0x14, 0x5B, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x7E, 0xB5, 0x05, 0x46, 0x95, 0xF8, 0x36, 0x20, 0x0E, 0x46, 0x0F, 0x49, 0x07, 0x2A, 0x12, 0xBF, 0x08, 0x68, 0x01, 0x20, 0x08, 0x60, 0x0D, 0x4C, 0x00, 0x92, 0x21, 0x68 , -0x41, 0xF2, 0x12, 0x13, 0x04, 0x22, 0x01, 0x91, 0x07, 0x21, 0x02, 0x90, 0x03, 0x20, 0xF2, 0xF7, 0x6B, 0xFD, 0x31, 0x46, 0x28, 0x46, 0xE7, 0xF7, 0x21, 0xFC, 0x21, 0x68, 0x00, 0x22, 0x05, 0x29, 0x02, 0xD1, 0x04, 0x49, 0x08, 0x31, 0x0A, 0x60, 0x7E, 0xBD, 0xC0, 0x46, 0x50, 0x57, 0x02, 0x00, 0x4C, 0x57, 0x02, 0x00, 0x00, 0x7C, 0x00, 0x20, 0x0E, 0x49, 0x09, 0x68, 0x49, 0x08, 0x15, 0xD2, 0x0D, 0x49, 0x09, 0x78, 0x91, 0xB1, 0x44, 0xF2, 0xE9, 0x21, 0x68, 0xB9, 0x0B, 0x48, 0x01, 0x78, 0x07, 0x48, 0x01, 0x29, 0x03, 0xD1, 0x0A, 0x49, 0x09, 0x78, 0x0E, 0x29, 0x02, 0xD0, 0x44, 0xF2, 0xDE, 0x21, 0x41, 0x60, 0x01, 0x21, 0x00, 0xE0, 0x06, 0x48, 0x01, 0x60, 0x70, 0x47, 0xC0, 0x46, 0x00, 0x97, 0x3C, 0x80, 0x10, 0x0C, 0x30, 0x80, 0xDD, 0x6A, 0x00, 0x20, 0xE0, 0x7C, 0x00, 0x20, 0xA6, 0x64, 0x00, 0x20, 0x04, 0x97, 0x3C, 0x80, 0x00, 0xB5, 0xAD, 0xF1, 0x18, 0x0D, 0x4F, 0xF0, 0x09, 0x00, 0x00, 0x90, 0x4F, 0xF4 , -0x0C, 0x60, 0x03, 0x90, 0x4F, 0xF0, 0x00, 0x00, 0x01, 0x90, 0x02, 0x90, 0x08, 0x48, 0x08, 0x49, 0x05, 0x90, 0x08, 0x68, 0x20, 0xB9, 0xDC, 0x5B, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0x68, 0x46, 0x03, 0x22, 0xED, 0xF7, 0x3A, 0xFA, 0x03, 0xE0, 0x68, 0x46, 0x03, 0x22, 0xED, 0xF7, 0xC1, 0xFC, 0x06, 0xB0, 0x00, 0xBD, 0xC0, 0x46, 0x81, 0x5C, 0x02, 0x00, 0xDC, 0x7C, 0x00, 0x20, 0x1C, 0xB5, 0x0F, 0x4C, 0x22, 0x68, 0x01, 0x2A, 0x15, 0xD1, 0x0C, 0x48, 0x00, 0x68, 0x07, 0x28, 0x14, 0xBF, 0x40, 0x20, 0x4F, 0xF4, 0x05, 0x70, 0x63, 0x21, 0xF1, 0xF7, 0x0F, 0xFA, 0x20, 0x68, 0x00, 0x90, 0x43, 0xF2, 0x33, 0x33, 0x06, 0x21, 0x40, 0x20, 0x01, 0x90, 0x03, 0x20, 0x02, 0x46, 0xF2, 0xF7, 0xF4, 0xFC, 0x1C, 0xBD, 0xF1, 0xF7, 0x01, 0xFA, 0x1C, 0xBD, 0x4C, 0x57, 0x02, 0x00, 0x50, 0x57, 0x02, 0x00, 0x1E, 0xB5, 0x04, 0x46, 0x0A, 0x49, 0x00, 0x20, 0x0A, 0x4A, 0x08, 0x60, 0x0A, 0x49, 0x00, 0x90, 0x01, 0x90, 0x11, 0x60 , -0x09, 0x4A, 0x45, 0xF2, 0x55, 0x53, 0x02, 0x91, 0x10, 0x60, 0x07, 0x21, 0x04, 0x22, 0x03, 0x20, 0xF2, 0xF7, 0xD8, 0xFC, 0x20, 0x46, 0xE7, 0xF7, 0x59, 0xFD, 0x1E, 0xBD, 0x50, 0x57, 0x02, 0x00, 0x04, 0x74, 0x00, 0x20, 0x34, 0x12, 0x66, 0x09, 0x4C, 0x57, 0x02, 0x00, 0x00, 0xB5, 0x0B, 0x49, 0x00, 0x20, 0x08, 0x60, 0xE0, 0x20, 0xF7, 0xF7, 0xAA, 0xFD, 0x09, 0x49, 0x09, 0x78, 0x49, 0xB1, 0x08, 0x49, 0x0A, 0x78, 0x08, 0x49, 0x00, 0x2A, 0x06, 0xBF, 0x01, 0x22, 0x09, 0x1F, 0x44, 0xF2, 0xA4, 0x5C, 0x02, 0x00, 0xC8, 0x00, 0x00, 0x00, 0xE9, 0x22, 0x0A, 0x60, 0xF7, 0xF7, 0xA1, 0xFD, 0x00, 0xBD, 0xC0, 0x46, 0xDC, 0x7C, 0x00, 0x20, 0xDD, 0x6A, 0x00, 0x20, 0xA7, 0x64, 0x00, 0x20, 0x04, 0x97, 0x3C, 0x80, 0x50, 0xB9, 0x09, 0x48, 0x00, 0x78, 0x01, 0x28, 0x06, 0xD1, 0x08, 0x48, 0x00, 0x78, 0x0E, 0x28, 0x08, 0xBF, 0x44, 0xF2, 0xCB, 0x20, 0x01, 0xD0, 0x44, 0xF2, 0xDE, 0x20, 0x04, 0x49, 0x08, 0x60, 0x01, 0x20 , -0x41, 0xF8, 0x04, 0x0C, 0x70, 0x47, 0xE0, 0x7C, 0x00, 0x20, 0xA6, 0x64, 0x00, 0x20, 0x04, 0x97, 0x3C, 0x80, 0x30, 0xB5, 0x0D, 0x46, 0x84, 0x69, 0xDC, 0xF7, 0x97, 0xFB, 0x24, 0x1D, 0x01, 0x28, 0x04, 0xEB, 0x45, 0x01, 0x06, 0xD1, 0x89, 0x8E, 0x04, 0xEB, 0x85, 0x04, 0x11, 0xB9, 0x21, 0x69, 0x01, 0xB9, 0x00, 0x20, 0x30, 0xBD, 0x30, 0xB5, 0x05, 0x46, 0x5A, 0xB1, 0x03, 0xEB, 0x41, 0x03, 0x1C, 0x78, 0x59, 0x78, 0x41, 0xEA, 0x04, 0x11, 0x52, 0x1E, 0x03, 0xF1, 0x02, 0x03, 0x05, 0xF8, 0x01, 0x1B, 0xF5, 0xD1, 0x30, 0xBD, 0x00, 0xB5, 0x00, 0x20, 0xE7, 0xF7, 0xD6, 0xFE, 0x03, 0x48, 0x01, 0x68, 0x03, 0x29, 0x04, 0xBF, 0x04, 0x21, 0x01, 0x60, 0x00, 0xBD, 0xC0, 0x46, 0x4C, 0x57, 0x02, 0x00, 0x03, 0x4A, 0x12, 0x68, 0x01, 0x2A, 0x04, 0xBF, 0x02, 0x48, 0x63, 0x21, 0xF1, 0xF7, 0x76, 0xB9, 0x50, 0x57, 0x02, 0x00, 0x02, 0x20, 0x01, 0x00, 0x6C, 0x5D, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; diff --git a/drivers/cc3000/src/patch_prog.c b/drivers/cc3000/src/patch_prog.c deleted file mode 100644 index fd128928fb..0000000000 --- a/drivers/cc3000/src/patch_prog.c +++ /dev/null @@ -1,414 +0,0 @@ -#include -#include -#include "cc3000_common.h" -#include "nvmem.h" -#include "ccspi.h" -#include "hci.h" -#include "wlan.h" -#include "patch_prog.h" -#define BIT0 0x1 -#define BIT1 0x2 -#define BIT2 0x4 -#define BIT3 0x8 -#define BIT4 0x10 -#define BIT5 0x20 -#define BIT6 0x40 -#define BIT7 0x80 - -static unsigned char ucStatus_Dr; -static unsigned char ucStatus_FW; -static unsigned char return_status = 0xFF; - -static signed char mac_status = -1; -static unsigned char counter = 0; - -// Array to store RM parameters from EEPROM. -static unsigned char cRMParamsFromEeprom[128]; -// Array to store MAC address from EEPROM. -static unsigned char cMacFromEeprom[MAC_ADDR_LEN]; -// Smart Config Prefix -static const char aucCC3000_prefix[] = {'T', 'T', 'T'}; - -static void systick_sleep(unsigned long ms) { - extern void HAL_Delay(volatile uint32_t Delay); - HAL_Delay(ms); -} - -// 2 dim array to store address and length of new FAT -static const unsigned short aFATEntries[2][NVMEM_RM_FILEID + 1] = -/* address */ {{0x50, 0x1f0, 0x390, 0x1390, 0x2390, 0x4390, 0x6390, 0x63a0, 0x63b0, 0x63f0, 0x6430, 0x6830}, -/* length */ {0x1a0, 0x1a0, 0x1000, 0x1000, 0x2000, 0x2000, 0x10, 0x10, 0x40, 0x40, 0x400, 0x200}}; -/* 0. NVS */ -/* 1. NVS Shadow */ -/* 2. Wireless Conf */ -/* 3. Wireless Conf Shadow */ -/* 4. BT (WLAN driver) Patches */ -/* 5. WiLink (Firmware) Patches */ -/* 6. MAC addr */ -/* 7. Frontend Vars */ -/* 8. IP config */ -/* 9. IP config Shadow */ -/* 10. Bootloader Patches */ -/* 11. Radio Module params */ -/* 12. AES128 for smart config */ -/* 13. user file */ -/* 14. user file */ -/* 15. user file */ - -//***************************************************************************** -// -//! sendDriverPatch -//! -//! \param pointer to the length -//! -//! \return none -//! -//! \brief The function returns a pointer to the driver patch: -//! since there is no patch yet - it returns 0 -// -//***************************************************************************** - -static char *sendDriverPatch(unsigned long *Length) -{ - *Length = 0; - return NULL; -} - - -//***************************************************************************** -// -//! sendBootLoaderPatch -//! -//! \param pointer to the length -//! -//! \return none -//! -//! \brief The function returns a pointer to the boot loader patch: -//! since there is no patch yet - it returns 0 -// -//***************************************************************************** - -static char *sendBootLoaderPatch(unsigned long *Length) -{ - *Length = 0; - return NULL; -} - -//***************************************************************************** -// -//! sendWLFWPatch -//! -//! \param pointer to the length -//! -//! \return none -//! -//! \brief The function returns a pointer to the FW patch: -//! since there is no patch yet - it returns 0 -// -//***************************************************************************** - -static char *sendWLFWPatch(unsigned long *Length) -{ - *Length = 0; - return NULL; -} - -//***************************************************************************** -// -//! CC3000_UsynchCallback -//! -//! \param Event type -//! -//! \return none -//! -//! \brief The function handles asynchronous events that come from CC3000 -//! device and operates a LED4 to have an on-board indication -// -//***************************************************************************** - -static void CC3000_UsynchCallback(long lEventType, char * data, unsigned char length) -{ - -} - -//***************************************************************************** -// -//! initDriver -//! -//! \param[in] cRequestPatch 0 to load with EEPROM patches -//! and 1 to load with no patches -//! -//! \return none -//! -//! \brief The function initializes a CC3000 device -//! and triggers it to start operation -// -//***************************************************************************** -static int initDriver(unsigned short cRequestPatch) -{ - // WLAN On API Implementation - wlan_init(CC3000_UsynchCallback, sendWLFWPatch, sendDriverPatch, sendBootLoaderPatch, - ReadWlanInterruptPin, SpiResumeSpi, SpiPauseSpi, WriteWlanPin); - - // Trigger a WLAN device - wlan_start(cRequestPatch); - wlan_smart_config_set_prefix((char*)aucCC3000_prefix); - wlan_ioctl_set_connection_policy(0, 0, 0); - wlan_ioctl_del_profile(255); - - // Mask out all non-required events from CC3000 - wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE| - HCI_EVNT_WLAN_UNSOL_INIT| - HCI_EVNT_WLAN_ASYNC_PING_REPORT); - - //unsolicicted_events_timer_init(); - systick_sleep(100); - return(0); -} - - -//***************************************************************************** -// -//! fat_read_content -//! -//! \param[out] is_allocated array of is_allocated in FAT table:\n -//! an allocated entry implies the address and length of the -//! file are valid. -//! 0: not allocated; 1: allocated. -//! \param[out] is_valid array of is_valid in FAT table:\n -//! a valid entry implies the content of the file is relevant. -//! 0: not valid; 1: valid. -//! \param[out] write_protected array of write_protected in FAT table:\n -//! a write protected entry implies it is not possible to write -//! into this entry. -//! 0: not protected; 1: protected. -//! \param[out] file_address array of file address in FAT table:\n -//! this is the absolute address of the file in the EEPROM. -//! \param[out] file_length array of file length in FAT table:\n -//! this is the upper limit of the file size in the EEPROM. -//! -//! \return on succes 0, error otherwise -//! -//! \brief parse the FAT table from eeprom -// -//***************************************************************************** -static unsigned char __attribute__ ((unused)) -fat_read_content(unsigned char *is_allocated, unsigned char *is_valid, - unsigned char *write_protected, unsigned short *file_address, unsigned short *file_length) -{ - unsigned short index; - unsigned char ucStatus; - unsigned char fatTable[48]; - unsigned char* fatTablePtr = fatTable; - - // - // Read in 6 parts to work with tiny driver - // - for (index = 0; index < 6; index++) - { - ucStatus = nvmem_read(16, 8, 4 + 8*index, fatTablePtr); - fatTablePtr += 8; - } - - fatTablePtr = fatTable; - - for (index = 0; index <= NVMEM_RM_FILEID; index++) - { - *is_allocated++ = (*fatTablePtr) & BIT0; - *is_valid++ = ((*fatTablePtr) & BIT1) >> 1; - *write_protected++ = ((*fatTablePtr) & BIT2) >> 2; - *file_address++ = ((*(fatTablePtr+1)<<8) | (*fatTablePtr)) & (BIT4|BIT5|BIT6|BIT7); - *file_length++ = ((*(fatTablePtr+3)<<8) | (*(fatTablePtr+2))) & (BIT4|BIT5|BIT6|BIT7); - - // - // Move to next file ID - // - fatTablePtr += 4; - } - - return ucStatus; -} - -//***************************************************************************** -// -//! fat_write_content -//! -//! \param[in] file_address array of file address in FAT table:\n -//! this is the absolute address of the file in the EEPROM. -//! \param[in] file_length array of file length in FAT table:\n -//! this is the upper limit of the file size in the EEPROM. -//! -//! \return on succes 0, error otherwise -//! -//! \brief parse the FAT table from eeprom -// -//***************************************************************************** -static unsigned char fat_write_content(unsigned short const *file_address, - unsigned short const *file_length) -{ - unsigned short index = 0; - unsigned char ucStatus; - unsigned char fatTable[48]; - unsigned char* fatTablePtr = fatTable; - - // - // First, write the magic number. - // - ucStatus = nvmem_write(16, 2, 0, (unsigned char*)"LS"); - - for (; index <= NVMEM_RM_FILEID; index++) - { - // - // Write address low char and mark as allocated. - // - *fatTablePtr++ = (unsigned char)(file_address[index] & 0xff) | BIT0; - - // - // Write address high char. - // - *fatTablePtr++ = (unsigned char)((file_address[index]>>8) & 0xff); - - // - // Write length low char. - // - *fatTablePtr++ = (unsigned char)(file_length[index] & 0xff); - - // - // Write length high char. - // - *fatTablePtr++ = (unsigned char)((file_length[index]>>8) & 0xff); - } - - // - // Second, write the FAT. - // Write in two parts to work with tiny driver. - // - ucStatus = nvmem_write(16, 24, 4, fatTable); - ucStatus = nvmem_write(16, 24, 24+4, &fatTable[24]); - - // - // Third, we want to erase any user files. - // - memset(fatTable, 0, sizeof(fatTable)); - ucStatus = nvmem_write(16, 16, 52, fatTable); - - return ucStatus; -} - -void patch_prog_start() -{ - unsigned short index; - unsigned char *pRMParams; - - printf("Initializing module...\n"); - - // Init module and request to load with no patches. - // This is in order to overwrite restrictions to - // write to specific places in EEPROM. - initDriver(1); - - // Read MAC address. - mac_status = nvmem_get_mac_address(cMacFromEeprom); - - return_status = 1; - - printf("Reading RM parameters...\n"); - while ((return_status) && (counter < 3)) { - // Read RM parameters. - // Read in 16 parts to work with tiny driver. - return_status = 0; - pRMParams = cRMParamsFromEeprom; - for (index = 0; index < 16; index++) { - return_status |= nvmem_read(NVMEM_RM_FILEID, 8, 8*index, pRMParams); - pRMParams += 8; - } - counter++; - } - - // If RM file is not valid, load the default one. - if (counter == 3) { - printf("RM is not valid, loading default one...\n"); - pRMParams = (unsigned char *)cRMdefaultParams; - } else { - printf("RM is valid.\n"); - pRMParams = cRMParamsFromEeprom; - } - - return_status = 1; - - printf("Writing new FAT\n"); - while (return_status) { - // Write new FAT. - return_status = fat_write_content(aFATEntries[0], aFATEntries[1]); - } - - return_status = 1; - - printf("Writing RM parameters...\n"); - while (return_status) { - // Write RM parameters. - // Write in 4 parts to work with tiny driver. - return_status = 0; - - for (index = 0; index < 4; index++) { - return_status |= nvmem_write(NVMEM_RM_FILEID, - 32, - 32*index, - (pRMParams + 32*index)); - } - } - - return_status = 1; - - // Write back the MAC address, only if exists. - if (mac_status == 0) { - // Zero out MCAST bit if set. - cMacFromEeprom[0] &= 0xfe; - printf("Writing back MAC address..\n"); - while (return_status) { - return_status = nvmem_set_mac_address(cMacFromEeprom); - } - } - - // Update driver - ucStatus_Dr = 1; - printf("Updating driver patch...\n"); - while (ucStatus_Dr) { - // Writing driver patch to EEPRROM - PROTABLE CODE - // Note that the array itself is changing between the - // different Service Packs. - ucStatus_Dr = nvmem_write_patch(NVMEM_WLAN_DRIVER_SP_FILEID, - drv_length, - wlan_drv_patch); - } - - // Update firmware - ucStatus_FW = 1; - printf("Updating firmware patch...\n"); - while (ucStatus_FW) { - // Writing FW patch to EEPRROM - PROTABLE CODE - // Note that the array itself is changing between the - // different Service Packs. - ucStatus_FW = nvmem_write_patch(NVMEM_WLAN_FW_SP_FILEID, - fw_length, - fw_patch); - } - - printf("Update complete, resetting module\n"\ - "If this doesn't work, reset manually...\n"); - - wlan_stop(); - systick_sleep(500); - - // Re-Init module and request to load with patches. - initDriver(0); - - // If MAC does not exist, it is recommended - // that the user will write a valid mac address. - if (mac_status != 0) { - printf("MAC address is not valid, please write a new one\n"); - } - - // Patch update done - printf("All done, call wlan.patch_version()\n"); -} diff --git a/drivers/cc3000/src/security.c b/drivers/cc3000/src/security.c deleted file mode 100644 index 62b4f88134..0000000000 --- a/drivers/cc3000/src/security.c +++ /dev/null @@ -1,530 +0,0 @@ -/***************************************************************************** -* -* security.c - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ - -//***************************************************************************** -// -//! \addtogroup security_api -//! @{ -// -//***************************************************************************** - -#include "security.h" - -#ifndef CC3000_UNENCRYPTED_SMART_CONFIG -// foreward sbox -const UINT8 sbox[256] = { -//0 1 2 3 4 5 6 7 8 9 A B C D E F -0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, //0 -0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, //1 -0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, //2 -0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, //3 -0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, //4 -0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, //5 -0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, //6 -0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, //7 -0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, //8 -0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, //9 -0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, //A -0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, //B -0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, //C -0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, //D -0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, //E -0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; //F -// inverse sbox -const UINT8 rsbox[256] = -{ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb -, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb -, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e -, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 -, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92 -, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 -, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06 -, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b -, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73 -, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e -, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b -, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4 -, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f -, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef -, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 -, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }; -// round constant -const UINT8 Rcon[11] = { - 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36}; - - -UINT8 expandedKey[176]; - -//***************************************************************************** -// -//! expandKey -//! -//! @param key AES128 key - 16 bytes -//! @param expandedKey expanded AES128 key -//! -//! @return none -//! -//! @brief expend a 16 bytes key for AES128 implementation -//! -//***************************************************************************** - -void expandKey(UINT8 *expandedKey, UINT8 *key) -{ - UINT16 ii, buf1; - for (ii=0;ii<16;ii++) - expandedKey[ii] = key[ii]; - for (ii=1;ii<11;ii++){ - buf1 = expandedKey[ii*16 - 4]; - expandedKey[ii*16 + 0] = sbox[expandedKey[ii*16 - 3]]^expandedKey[(ii-1)*16 + 0]^Rcon[ii]; - expandedKey[ii*16 + 1] = sbox[expandedKey[ii*16 - 2]]^expandedKey[(ii-1)*16 + 1]; - expandedKey[ii*16 + 2] = sbox[expandedKey[ii*16 - 1]]^expandedKey[(ii-1)*16 + 2]; - expandedKey[ii*16 + 3] = sbox[buf1 ]^expandedKey[(ii-1)*16 + 3]; - expandedKey[ii*16 + 4] = expandedKey[(ii-1)*16 + 4]^expandedKey[ii*16 + 0]; - expandedKey[ii*16 + 5] = expandedKey[(ii-1)*16 + 5]^expandedKey[ii*16 + 1]; - expandedKey[ii*16 + 6] = expandedKey[(ii-1)*16 + 6]^expandedKey[ii*16 + 2]; - expandedKey[ii*16 + 7] = expandedKey[(ii-1)*16 + 7]^expandedKey[ii*16 + 3]; - expandedKey[ii*16 + 8] = expandedKey[(ii-1)*16 + 8]^expandedKey[ii*16 + 4]; - expandedKey[ii*16 + 9] = expandedKey[(ii-1)*16 + 9]^expandedKey[ii*16 + 5]; - expandedKey[ii*16 +10] = expandedKey[(ii-1)*16 +10]^expandedKey[ii*16 + 6]; - expandedKey[ii*16 +11] = expandedKey[(ii-1)*16 +11]^expandedKey[ii*16 + 7]; - expandedKey[ii*16 +12] = expandedKey[(ii-1)*16 +12]^expandedKey[ii*16 + 8]; - expandedKey[ii*16 +13] = expandedKey[(ii-1)*16 +13]^expandedKey[ii*16 + 9]; - expandedKey[ii*16 +14] = expandedKey[(ii-1)*16 +14]^expandedKey[ii*16 +10]; - expandedKey[ii*16 +15] = expandedKey[(ii-1)*16 +15]^expandedKey[ii*16 +11]; - } - -} - -//***************************************************************************** -// -//! galois_mul2 -//! -//! @param value argument to multiply -//! -//! @return multiplied argument -//! -//! @brief multiply by 2 in the galois field -//! -//***************************************************************************** - -UINT8 galois_mul2(UINT8 value) -{ - if (value>>7) - { - value = value << 1; - return (value^0x1b); - } else - return value<<1; -} - -//***************************************************************************** -// -//! aes_encr -//! -//! @param[in] expandedKey expanded AES128 key -//! @param[in/out] state 16 bytes of plain text and cipher text -//! -//! @return none -//! -//! @brief internal implementation of AES128 encryption. -//! straight forward aes encryption implementation -//! first the group of operations -//! - addRoundKey -//! - subbytes -//! - shiftrows -//! - mixcolums -//! is executed 9 times, after this addroundkey to finish the 9th -//! round, after that the 10th round without mixcolums -//! no further subfunctions to save cycles for function calls -//! no structuring with "for (....)" to save cycles. -//! -//! -//***************************************************************************** - -void aes_encr(UINT8 *state, UINT8 *expandedKey) -{ - UINT8 buf1, buf2, buf3, round; - - for (round = 0; round < 9; round ++){ - // addroundkey, sbox and shiftrows - // row 0 - state[ 0] = sbox[(state[ 0] ^ expandedKey[(round*16) ])]; - state[ 4] = sbox[(state[ 4] ^ expandedKey[(round*16) + 4])]; - state[ 8] = sbox[(state[ 8] ^ expandedKey[(round*16) + 8])]; - state[12] = sbox[(state[12] ^ expandedKey[(round*16) + 12])]; - // row 1 - buf1 = state[1] ^ expandedKey[(round*16) + 1]; - state[ 1] = sbox[(state[ 5] ^ expandedKey[(round*16) + 5])]; - state[ 5] = sbox[(state[ 9] ^ expandedKey[(round*16) + 9])]; - state[ 9] = sbox[(state[13] ^ expandedKey[(round*16) + 13])]; - state[13] = sbox[buf1]; - // row 2 - buf1 = state[2] ^ expandedKey[(round*16) + 2]; - buf2 = state[6] ^ expandedKey[(round*16) + 6]; - state[ 2] = sbox[(state[10] ^ expandedKey[(round*16) + 10])]; - state[ 6] = sbox[(state[14] ^ expandedKey[(round*16) + 14])]; - state[10] = sbox[buf1]; - state[14] = sbox[buf2]; - // row 3 - buf1 = state[15] ^ expandedKey[(round*16) + 15]; - state[15] = sbox[(state[11] ^ expandedKey[(round*16) + 11])]; - state[11] = sbox[(state[ 7] ^ expandedKey[(round*16) + 7])]; - state[ 7] = sbox[(state[ 3] ^ expandedKey[(round*16) + 3])]; - state[ 3] = sbox[buf1]; - - // mixcolums ////////// - // col1 - buf1 = state[0] ^ state[1] ^ state[2] ^ state[3]; - buf2 = state[0]; - buf3 = state[0]^state[1]; buf3=galois_mul2(buf3); state[0] = state[0] ^ buf3 ^ buf1; - buf3 = state[1]^state[2]; buf3=galois_mul2(buf3); state[1] = state[1] ^ buf3 ^ buf1; - buf3 = state[2]^state[3]; buf3=galois_mul2(buf3); state[2] = state[2] ^ buf3 ^ buf1; - buf3 = state[3]^buf2; buf3=galois_mul2(buf3); state[3] = state[3] ^ buf3 ^ buf1; - // col2 - buf1 = state[4] ^ state[5] ^ state[6] ^ state[7]; - buf2 = state[4]; - buf3 = state[4]^state[5]; buf3=galois_mul2(buf3); state[4] = state[4] ^ buf3 ^ buf1; - buf3 = state[5]^state[6]; buf3=galois_mul2(buf3); state[5] = state[5] ^ buf3 ^ buf1; - buf3 = state[6]^state[7]; buf3=galois_mul2(buf3); state[6] = state[6] ^ buf3 ^ buf1; - buf3 = state[7]^buf2; buf3=galois_mul2(buf3); state[7] = state[7] ^ buf3 ^ buf1; - // col3 - buf1 = state[8] ^ state[9] ^ state[10] ^ state[11]; - buf2 = state[8]; - buf3 = state[8]^state[9]; buf3=galois_mul2(buf3); state[8] = state[8] ^ buf3 ^ buf1; - buf3 = state[9]^state[10]; buf3=galois_mul2(buf3); state[9] = state[9] ^ buf3 ^ buf1; - buf3 = state[10]^state[11]; buf3=galois_mul2(buf3); state[10] = state[10] ^ buf3 ^ buf1; - buf3 = state[11]^buf2; buf3=galois_mul2(buf3); state[11] = state[11] ^ buf3 ^ buf1; - // col4 - buf1 = state[12] ^ state[13] ^ state[14] ^ state[15]; - buf2 = state[12]; - buf3 = state[12]^state[13]; buf3=galois_mul2(buf3); state[12] = state[12] ^ buf3 ^ buf1; - buf3 = state[13]^state[14]; buf3=galois_mul2(buf3); state[13] = state[13] ^ buf3 ^ buf1; - buf3 = state[14]^state[15]; buf3=galois_mul2(buf3); state[14] = state[14] ^ buf3 ^ buf1; - buf3 = state[15]^buf2; buf3=galois_mul2(buf3); state[15] = state[15] ^ buf3 ^ buf1; - - } - // 10th round without mixcols - state[ 0] = sbox[(state[ 0] ^ expandedKey[(round*16) ])]; - state[ 4] = sbox[(state[ 4] ^ expandedKey[(round*16) + 4])]; - state[ 8] = sbox[(state[ 8] ^ expandedKey[(round*16) + 8])]; - state[12] = sbox[(state[12] ^ expandedKey[(round*16) + 12])]; - // row 1 - buf1 = state[1] ^ expandedKey[(round*16) + 1]; - state[ 1] = sbox[(state[ 5] ^ expandedKey[(round*16) + 5])]; - state[ 5] = sbox[(state[ 9] ^ expandedKey[(round*16) + 9])]; - state[ 9] = sbox[(state[13] ^ expandedKey[(round*16) + 13])]; - state[13] = sbox[buf1]; - // row 2 - buf1 = state[2] ^ expandedKey[(round*16) + 2]; - buf2 = state[6] ^ expandedKey[(round*16) + 6]; - state[ 2] = sbox[(state[10] ^ expandedKey[(round*16) + 10])]; - state[ 6] = sbox[(state[14] ^ expandedKey[(round*16) + 14])]; - state[10] = sbox[buf1]; - state[14] = sbox[buf2]; - // row 3 - buf1 = state[15] ^ expandedKey[(round*16) + 15]; - state[15] = sbox[(state[11] ^ expandedKey[(round*16) + 11])]; - state[11] = sbox[(state[ 7] ^ expandedKey[(round*16) + 7])]; - state[ 7] = sbox[(state[ 3] ^ expandedKey[(round*16) + 3])]; - state[ 3] = sbox[buf1]; - // last addroundkey - state[ 0]^=expandedKey[160]; - state[ 1]^=expandedKey[161]; - state[ 2]^=expandedKey[162]; - state[ 3]^=expandedKey[163]; - state[ 4]^=expandedKey[164]; - state[ 5]^=expandedKey[165]; - state[ 6]^=expandedKey[166]; - state[ 7]^=expandedKey[167]; - state[ 8]^=expandedKey[168]; - state[ 9]^=expandedKey[169]; - state[10]^=expandedKey[170]; - state[11]^=expandedKey[171]; - state[12]^=expandedKey[172]; - state[13]^=expandedKey[173]; - state[14]^=expandedKey[174]; - state[15]^=expandedKey[175]; -} - -//***************************************************************************** -// -//! aes_decr -//! -//! @param[in] expandedKey expanded AES128 key -//! @param[in\out] state 16 bytes of cipher text and plain text -//! -//! @return none -//! -//! @brief internal implementation of AES128 decryption. -//! straight forward aes decryption implementation -//! the order of substeps is the exact reverse of decryption -//! inverse functions: -//! - addRoundKey is its own inverse -//! - rsbox is inverse of sbox -//! - rightshift instead of leftshift -//! - invMixColumns = barreto + mixColumns -//! no further subfunctions to save cycles for function calls -//! no structuring with "for (....)" to save cycles -//! -//***************************************************************************** - -void aes_decr(UINT8 *state, UINT8 *expandedKey) -{ - UINT8 buf1, buf2, buf3; - INT8 round; - round = 9; - - // initial addroundkey - state[ 0]^=expandedKey[160]; - state[ 1]^=expandedKey[161]; - state[ 2]^=expandedKey[162]; - state[ 3]^=expandedKey[163]; - state[ 4]^=expandedKey[164]; - state[ 5]^=expandedKey[165]; - state[ 6]^=expandedKey[166]; - state[ 7]^=expandedKey[167]; - state[ 8]^=expandedKey[168]; - state[ 9]^=expandedKey[169]; - state[10]^=expandedKey[170]; - state[11]^=expandedKey[171]; - state[12]^=expandedKey[172]; - state[13]^=expandedKey[173]; - state[14]^=expandedKey[174]; - state[15]^=expandedKey[175]; - - // 10th round without mixcols - state[ 0] = rsbox[state[ 0]] ^ expandedKey[(round*16) ]; - state[ 4] = rsbox[state[ 4]] ^ expandedKey[(round*16) + 4]; - state[ 8] = rsbox[state[ 8]] ^ expandedKey[(round*16) + 8]; - state[12] = rsbox[state[12]] ^ expandedKey[(round*16) + 12]; - // row 1 - buf1 = rsbox[state[13]] ^ expandedKey[(round*16) + 1]; - state[13] = rsbox[state[ 9]] ^ expandedKey[(round*16) + 13]; - state[ 9] = rsbox[state[ 5]] ^ expandedKey[(round*16) + 9]; - state[ 5] = rsbox[state[ 1]] ^ expandedKey[(round*16) + 5]; - state[ 1] = buf1; - // row 2 - buf1 = rsbox[state[ 2]] ^ expandedKey[(round*16) + 10]; - buf2 = rsbox[state[ 6]] ^ expandedKey[(round*16) + 14]; - state[ 2] = rsbox[state[10]] ^ expandedKey[(round*16) + 2]; - state[ 6] = rsbox[state[14]] ^ expandedKey[(round*16) + 6]; - state[10] = buf1; - state[14] = buf2; - // row 3 - buf1 = rsbox[state[ 3]] ^ expandedKey[(round*16) + 15]; - state[ 3] = rsbox[state[ 7]] ^ expandedKey[(round*16) + 3]; - state[ 7] = rsbox[state[11]] ^ expandedKey[(round*16) + 7]; - state[11] = rsbox[state[15]] ^ expandedKey[(round*16) + 11]; - state[15] = buf1; - - for (round = 8; round >= 0; round--){ - // barreto - //col1 - buf1 = galois_mul2(galois_mul2(state[0]^state[2])); - buf2 = galois_mul2(galois_mul2(state[1]^state[3])); - state[0] ^= buf1; state[1] ^= buf2; state[2] ^= buf1; state[3] ^= buf2; - //col2 - buf1 = galois_mul2(galois_mul2(state[4]^state[6])); - buf2 = galois_mul2(galois_mul2(state[5]^state[7])); - state[4] ^= buf1; state[5] ^= buf2; state[6] ^= buf1; state[7] ^= buf2; - //col3 - buf1 = galois_mul2(galois_mul2(state[8]^state[10])); - buf2 = galois_mul2(galois_mul2(state[9]^state[11])); - state[8] ^= buf1; state[9] ^= buf2; state[10] ^= buf1; state[11] ^= buf2; - //col4 - buf1 = galois_mul2(galois_mul2(state[12]^state[14])); - buf2 = galois_mul2(galois_mul2(state[13]^state[15])); - state[12] ^= buf1; state[13] ^= buf2; state[14] ^= buf1; state[15] ^= buf2; - // mixcolums ////////// - // col1 - buf1 = state[0] ^ state[1] ^ state[2] ^ state[3]; - buf2 = state[0]; - buf3 = state[0]^state[1]; buf3=galois_mul2(buf3); state[0] = state[0] ^ buf3 ^ buf1; - buf3 = state[1]^state[2]; buf3=galois_mul2(buf3); state[1] = state[1] ^ buf3 ^ buf1; - buf3 = state[2]^state[3]; buf3=galois_mul2(buf3); state[2] = state[2] ^ buf3 ^ buf1; - buf3 = state[3]^buf2; buf3=galois_mul2(buf3); state[3] = state[3] ^ buf3 ^ buf1; - // col2 - buf1 = state[4] ^ state[5] ^ state[6] ^ state[7]; - buf2 = state[4]; - buf3 = state[4]^state[5]; buf3=galois_mul2(buf3); state[4] = state[4] ^ buf3 ^ buf1; - buf3 = state[5]^state[6]; buf3=galois_mul2(buf3); state[5] = state[5] ^ buf3 ^ buf1; - buf3 = state[6]^state[7]; buf3=galois_mul2(buf3); state[6] = state[6] ^ buf3 ^ buf1; - buf3 = state[7]^buf2; buf3=galois_mul2(buf3); state[7] = state[7] ^ buf3 ^ buf1; - // col3 - buf1 = state[8] ^ state[9] ^ state[10] ^ state[11]; - buf2 = state[8]; - buf3 = state[8]^state[9]; buf3=galois_mul2(buf3); state[8] = state[8] ^ buf3 ^ buf1; - buf3 = state[9]^state[10]; buf3=galois_mul2(buf3); state[9] = state[9] ^ buf3 ^ buf1; - buf3 = state[10]^state[11]; buf3=galois_mul2(buf3); state[10] = state[10] ^ buf3 ^ buf1; - buf3 = state[11]^buf2; buf3=galois_mul2(buf3); state[11] = state[11] ^ buf3 ^ buf1; - // col4 - buf1 = state[12] ^ state[13] ^ state[14] ^ state[15]; - buf2 = state[12]; - buf3 = state[12]^state[13]; buf3=galois_mul2(buf3); state[12] = state[12] ^ buf3 ^ buf1; - buf3 = state[13]^state[14]; buf3=galois_mul2(buf3); state[13] = state[13] ^ buf3 ^ buf1; - buf3 = state[14]^state[15]; buf3=galois_mul2(buf3); state[14] = state[14] ^ buf3 ^ buf1; - buf3 = state[15]^buf2; buf3=galois_mul2(buf3); state[15] = state[15] ^ buf3 ^ buf1; - - // addroundkey, rsbox and shiftrows - // row 0 - state[ 0] = rsbox[state[ 0]] ^ expandedKey[(round*16) ]; - state[ 4] = rsbox[state[ 4]] ^ expandedKey[(round*16) + 4]; - state[ 8] = rsbox[state[ 8]] ^ expandedKey[(round*16) + 8]; - state[12] = rsbox[state[12]] ^ expandedKey[(round*16) + 12]; - // row 1 - buf1 = rsbox[state[13]] ^ expandedKey[(round*16) + 1]; - state[13] = rsbox[state[ 9]] ^ expandedKey[(round*16) + 13]; - state[ 9] = rsbox[state[ 5]] ^ expandedKey[(round*16) + 9]; - state[ 5] = rsbox[state[ 1]] ^ expandedKey[(round*16) + 5]; - state[ 1] = buf1; - // row 2 - buf1 = rsbox[state[ 2]] ^ expandedKey[(round*16) + 10]; - buf2 = rsbox[state[ 6]] ^ expandedKey[(round*16) + 14]; - state[ 2] = rsbox[state[10]] ^ expandedKey[(round*16) + 2]; - state[ 6] = rsbox[state[14]] ^ expandedKey[(round*16) + 6]; - state[10] = buf1; - state[14] = buf2; - // row 3 - buf1 = rsbox[state[ 3]] ^ expandedKey[(round*16) + 15]; - state[ 3] = rsbox[state[ 7]] ^ expandedKey[(round*16) + 3]; - state[ 7] = rsbox[state[11]] ^ expandedKey[(round*16) + 7]; - state[11] = rsbox[state[15]] ^ expandedKey[(round*16) + 11]; - state[15] = buf1; - } - -} - -//***************************************************************************** -// -//! aes_encrypt -//! -//! @param[in] key AES128 key of size 16 bytes -//! @param[in\out] state 16 bytes of plain text and cipher text -//! -//! @return none -//! -//! @brief AES128 encryption: -//! Given AES128 key and 16 bytes plain text, cipher text of 16 bytes -//! is computed. The AES implementation is in mode ECB (Electronic -//! Code Book). -//! -//! -//***************************************************************************** - -void aes_encrypt(UINT8 *state, UINT8 *key) -{ - // expand the key into 176 bytes - expandKey(expandedKey, key); - aes_encr(state, expandedKey); -} - -//***************************************************************************** -// -//! aes_decrypt -//! -//! @param[in] key AES128 key of size 16 bytes -//! @param[in\out] state 16 bytes of cipher text and plain text -//! -//! @return none -//! -//! @brief AES128 decryption: -//! Given AES128 key and 16 bytes cipher text, plain text of 16 bytes -//! is computed The AES implementation is in mode ECB -//! (Electronic Code Book). -//! -//! -//***************************************************************************** - -void aes_decrypt(UINT8 *state, UINT8 *key) -{ - expandKey(expandedKey, key); // expand the key into 176 bytes - aes_decr(state, expandedKey); -} - -//***************************************************************************** -// -//! aes_read_key -//! -//! @param[out] key AES128 key of size 16 bytes -//! -//! @return on success 0, error otherwise. -//! -//! @brief Reads AES128 key from EEPROM -//! Reads the AES128 key from fileID #12 in EEPROM -//! returns an error if the key does not exist. -//! -//! -//***************************************************************************** - -INT32 aes_read_key(UINT8 *key) -{ - INT32 returnValue; - - returnValue = nvmem_read(NVMEM_AES128_KEY_FILEID, AES128_KEY_SIZE, 0, key); - - return returnValue; -} - -//***************************************************************************** -// -//! aes_write_key -//! -//! @param[out] key AES128 key of size 16 bytes -//! -//! @return on success 0, error otherwise. -//! -//! @brief writes AES128 key from EEPROM -//! Writes the AES128 key to fileID #12 in EEPROM -//! -//! -//***************************************************************************** - -INT32 aes_write_key(UINT8 *key) -{ - INT32 returnValue; - - returnValue = nvmem_write(NVMEM_AES128_KEY_FILEID, AES128_KEY_SIZE, 0, key); - - return returnValue; -} - -#endif //CC3000_UNENCRYPTED_SMART_CONFIG - -//***************************************************************************** -// -// Close the Doxygen group. -//! @} -// -//***************************************************************************** diff --git a/drivers/cc3000/src/socket.c b/drivers/cc3000/src/socket.c deleted file mode 100644 index ddd7e56e80..0000000000 --- a/drivers/cc3000/src/socket.c +++ /dev/null @@ -1,1182 +0,0 @@ -/***************************************************************************** -* -* socket.c - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ - -//***************************************************************************** -// -//! \addtogroup socket_api -//! @{ -// -//***************************************************************************** - -#include -#include -#include "hci.h" -#include "socket.h" -#include "evnt_handler.h" -#include "netapp.h" - - - -//Enable this flag if and only if you must comply with BSD socket -//close() function -#ifdef _API_USE_BSD_CLOSE -#define close(sd) closesocket(sd) -#endif - -//Enable this flag if and only if you must comply with BSD socket read() and -//write() functions -#ifdef _API_USE_BSD_READ_WRITE -#define read(sd, buf, len, flags) recv(sd, buf, len, flags) -#define write(sd, buf, len, flags) send(sd, buf, len, flags) -#endif - -#define SOCKET_OPEN_PARAMS_LEN (12) -#define SOCKET_CLOSE_PARAMS_LEN (4) -#define SOCKET_ACCEPT_PARAMS_LEN (4) -#define SOCKET_BIND_PARAMS_LEN (20) -#define SOCKET_LISTEN_PARAMS_LEN (8) -#define SOCKET_GET_HOST_BY_NAME_PARAMS_LEN (9) -#define SOCKET_CONNECT_PARAMS_LEN (20) -#define SOCKET_SELECT_PARAMS_LEN (44) -#define SOCKET_SET_SOCK_OPT_PARAMS_LEN (20) -#define SOCKET_GET_SOCK_OPT_PARAMS_LEN (12) -#define SOCKET_RECV_FROM_PARAMS_LEN (12) -#define SOCKET_SENDTO_PARAMS_LEN (24) -#define SOCKET_MDNS_ADVERTISE_PARAMS_LEN (12) -#define SOCKET_GET_MSS_VALUE_PARAMS_LEN (4) - -// The legnth of arguments for the SEND command: sd + buff_offset + len + flags, -// while size of each parameter is 32 bit - so the total length is 16 bytes; - -#define HCI_CMND_SEND_ARG_LENGTH (16) - - -#define SELECT_TIMEOUT_MIN_MICRO_SECONDS 5000 - -#define HEADERS_SIZE_DATA (SPI_HEADER_SIZE + 5) - -#define SIMPLE_LINK_HCI_CMND_TRANSPORT_HEADER_SIZE (SPI_HEADER_SIZE + SIMPLE_LINK_HCI_CMND_HEADER_SIZE) - -#define MDNS_DEVICE_SERVICE_MAX_LENGTH (32) - - -//***************************************************************************** -// -//! HostFlowControlConsumeBuff -//! -//! @param sd socket descriptor -//! -//! @return 0 in case there are buffers available, -//! -1 in case of bad socket -//! -2 if there are no free buffers present (only when -//! SEND_NON_BLOCKING is enabled) -//! -//! @brief if SEND_NON_BLOCKING not define - block until have free buffer -//! becomes available, else return immediately with correct status -//! regarding the buffers available. -// -//***************************************************************************** -static INT16 HostFlowControlConsumeBuff(INT16 sd) -{ -#ifndef SEND_NON_BLOCKING - /* wait in busy loop */ - do - { - // In case last transmission failed then we will return the last failure - // reason here. - // Note that the buffer will not be allocated in this case - if (tSLInformation.slTransmitDataError != 0) - { - CC3000_EXPORT(errno) = tSLInformation.slTransmitDataError; - tSLInformation.slTransmitDataError = 0; - return CC3000_EXPORT(errno); - } - - if(SOCKET_STATUS_ACTIVE != get_socket_active_status(sd)) - return -1; - } while(0 == tSLInformation.usNumberOfFreeBuffers); - - tSLInformation.usNumberOfFreeBuffers--; - - return 0; -#else - - // In case last transmission failed then we will return the last failure - // reason here. - // Note that the buffer will not be allocated in this case - if (tSLInformation.slTransmitDataError != 0) - { - CC3000_EXPORT(errno) = tSLInformation.slTransmitDataError; - tSLInformation.slTransmitDataError = 0; - return CC3000_EXPORT(errno); - } - if(SOCKET_STATUS_ACTIVE != get_socket_active_status(sd)) - return -1; - - //If there are no available buffers, return -2. It is recommended to use - // select or receive to see if there is any buffer occupied with received data - // If so, call receive() to release the buffer. - if(0 == tSLInformation.usNumberOfFreeBuffers) - { - return -2; - } - else - { - tSLInformation.usNumberOfFreeBuffers--; - return 0; - } -#endif -} - -//***************************************************************************** -// -//! socket -//! -//! @param domain selects the protocol family which will be used for -//! communication. On this version only AF_INET is supported -//! @param type specifies the communication semantics. On this version -//! only SOCK_STREAM, SOCK_DGRAM, SOCK_RAW are supported -//! @param protocol specifies a particular protocol to be used with the -//! socket IPPROTO_TCP, IPPROTO_UDP or IPPROTO_RAW are -//! supported. -//! -//! @return On success, socket handle that is used for consequent socket -//! operations. On error, -1 is returned. -//! -//! @brief create an endpoint for communication -//! The socket function creates a socket that is bound to a specific -//! transport service provider. This function is called by the -//! application layer to obtain a socket handle. -// -//***************************************************************************** - -INT16 CC3000_EXPORT(socket)(INT32 domain, INT32 type, INT32 protocol) -{ - INT32 ret; - UINT8 *ptr, *args; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in HCI packet structure - args = UINT32_TO_STREAM(args, domain); - args = UINT32_TO_STREAM(args, type); - args = UINT32_TO_STREAM(args, protocol); - - // Initiate a HCI command - hci_command_send(HCI_CMND_SOCKET, ptr, SOCKET_OPEN_PARAMS_LEN); - - // Since we are in blocking state - wait for event complete - SimpleLinkWaitEvent(HCI_CMND_SOCKET, &ret); - - // Process the event - CC3000_EXPORT(errno) = ret; - - set_socket_active_status(ret, SOCKET_STATUS_ACTIVE); - - return(ret); -} - -//***************************************************************************** -// -//! closesocket -//! -//! @param sd socket handle. -//! -//! @return On success, zero is returned. On error, -1 is returned. -//! -//! @brief The socket function closes a created socket. -// -//***************************************************************************** - -INT32 CC3000_EXPORT(closesocket)(INT32 sd) -{ - INT32 ret; - UINT8 *ptr, *args; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in HCI packet structure - args = UINT32_TO_STREAM(args, sd); - - // Initiate a HCI command - hci_command_send(HCI_CMND_CLOSE_SOCKET, - ptr, SOCKET_CLOSE_PARAMS_LEN); - - // Since we are in blocking state - wait for event complete - SimpleLinkWaitEvent(HCI_CMND_CLOSE_SOCKET, &ret); - CC3000_EXPORT(errno) = ret; - - // since 'close' call may result in either OK (and then it closed) or error - // mark this socket as invalid - set_socket_active_status(sd, SOCKET_STATUS_INACTIVE); - - return(ret); -} - -//***************************************************************************** -// -//! accept -//! -//! @param[in] sd socket descriptor (handle) -//! @param[out] addr the argument addr is a pointer to a sockaddr structure -//! This structure is filled in with the address of the -//! peer socket, as known to the communications layer. -//! determined. The exact format of the address returned -//! addr is by the socket's address sockaddr. -//! On this version only AF_INET is supported. -//! This argument returns in network order. -//! @param[out] addrlen the addrlen argument is a value-result argument: -//! it should initially contain the size of the structure -//! pointed to by addr. -//! -//! @return For socket in blocking mode: -//! On success, socket handle. on failure negative -//! For socket in non-blocking mode: -//! - On connection establishment, socket handle -//! - On connection pending, SOC_IN_PROGRESS (-2) -//! - On failure, SOC_ERROR (-1) -//! -//! @brief accept a connection on a socket: -//! This function is used with connection-based socket types -//! (SOCK_STREAM). It extracts the first connection request on the -//! queue of pending connections, creates a new connected socket, and -//! returns a new file descriptor referring to that socket. -//! The newly created socket is not in the listening state. -//! The original socket sd is unaffected by this call. -//! The argument sd is a socket that has been created with socket(), -//! bound to a local address with bind(), and is listening for -//! connections after a listen(). The argument addr is a pointer -//! to a sockaddr structure. This structure is filled in with the -//! address of the peer socket, as known to the communications layer. -//! The exact format of the address returned addr is determined by the -//! socket's address family. The addrlen argument is a value-result -//! argument: it should initially contain the size of the structure -//! pointed to by addr, on return it will contain the actual -//! length (in bytes) of the address returned. -//! -//! @sa socket ; bind ; listen -// -//***************************************************************************** - -INT32 CC3000_EXPORT(accept)(INT32 sd, sockaddr *addr, socklen_t *addrlen) -{ - INT32 ret; - UINT8 *ptr, *args; - tBsdReturnParams tAcceptReturnArguments; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in temporary command buffer - args = UINT32_TO_STREAM(args, sd); - - // Initiate a HCI command - hci_command_send(HCI_CMND_ACCEPT, - ptr, SOCKET_ACCEPT_PARAMS_LEN); - - // Since we are in blocking state - wait for event complete - SimpleLinkWaitEvent(HCI_CMND_ACCEPT, &tAcceptReturnArguments); - - - // need specify return parameters!!! - memcpy(addr, &tAcceptReturnArguments.tSocketAddress, ASIC_ADDR_LEN); - *addrlen = ASIC_ADDR_LEN; - CC3000_EXPORT(errno) = tAcceptReturnArguments.iStatus; - ret = CC3000_EXPORT(errno); - - // if succeeded, iStatus = new socket descriptor. otherwise - error number - if(M_IS_VALID_SD(ret)) - { - set_socket_active_status(ret, SOCKET_STATUS_ACTIVE); - } - else - { - set_socket_active_status(sd, SOCKET_STATUS_INACTIVE); - } - - return(ret); -} - -//***************************************************************************** -// -//! bind -//! -//! @param[in] sd socket descriptor (handle) -//! @param[out] addr specifies the destination address. On this version -//! only AF_INET is supported. -//! @param[out] addrlen contains the size of the structure pointed to by addr. -//! -//! @return On success, zero is returned. On error, -1 is returned. -//! -//! @brief assign a name to a socket -//! This function gives the socket the local address addr. -//! addr is addrlen bytes long. Traditionally, this is called when a -//! socket is created with socket, it exists in a name space (address -//! family) but has no name assigned. -//! It is necessary to assign a local address before a SOCK_STREAM -//! socket may receive connections. -//! -//! @sa socket ; accept ; listen -// -//***************************************************************************** - -INT32 CC3000_EXPORT(bind)(INT32 sd, const sockaddr *addr, INT32 addrlen) -{ - INT32 ret; - UINT8 *ptr, *args; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - addrlen = ASIC_ADDR_LEN; - - // Fill in temporary command buffer - args = UINT32_TO_STREAM(args, sd); - args = UINT32_TO_STREAM(args, 0x00000008); - args = UINT32_TO_STREAM(args, addrlen); - ARRAY_TO_STREAM(args, ((UINT8 *)addr), addrlen); - - // Initiate a HCI command - hci_command_send(HCI_CMND_BIND, - ptr, SOCKET_BIND_PARAMS_LEN); - - // Since we are in blocking state - wait for event complete - SimpleLinkWaitEvent(HCI_CMND_BIND, &ret); - - CC3000_EXPORT(errno) = ret; - - return(ret); -} - -//***************************************************************************** -// -//! listen -//! -//! @param[in] sd socket descriptor (handle) -//! @param[in] backlog specifies the listen queue depth. On this version -//! backlog is not supported. -//! @return On success, zero is returned. On error, -1 is returned. -//! -//! @brief listen for connections on a socket -//! The willingness to accept incoming connections and a queue -//! limit for incoming connections are specified with listen(), -//! and then the connections are accepted with accept. -//! The listen() call applies only to sockets of type SOCK_STREAM -//! The backlog parameter defines the maximum length the queue of -//! pending connections may grow to. -//! -//! @sa socket ; accept ; bind -//! -//! @note On this version, backlog is not supported -// -//***************************************************************************** - -INT32 CC3000_EXPORT(listen)(INT32 sd, INT32 backlog) -{ - INT32 ret; - UINT8 *ptr, *args; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in temporary command buffer - args = UINT32_TO_STREAM(args, sd); - args = UINT32_TO_STREAM(args, backlog); - - // Initiate a HCI command - hci_command_send(HCI_CMND_LISTEN, - ptr, SOCKET_LISTEN_PARAMS_LEN); - - // Since we are in blocking state - wait for event complete - SimpleLinkWaitEvent(HCI_CMND_LISTEN, &ret); - CC3000_EXPORT(errno) = ret; - - return(ret); -} - -//***************************************************************************** -// -//! gethostbyname -//! -//! @param[in] hostname host name -//! @param[in] usNameLen name length -//! @param[out] out_ip_addr This parameter is filled in with host IP address. -//! In case that host name is not resolved, -//! out_ip_addr is zero. -//! @return On success, positive is returned. On error, negative is returned -//! -//! @brief Get host IP by name. Obtain the IP Address of machine on network, -//! by its name. -//! -//! @note On this version, only blocking mode is supported. Also note that -//! the function requires DNS server to be configured prior to its usage. -// -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -INT16 CC3000_EXPORT(gethostbyname)(CHAR * hostname, UINT16 usNameLen, - UINT32* out_ip_addr) -{ - tBsdGethostbynameParams ret; - UINT8 *ptr, *args; - - CC3000_EXPORT(errno) = EFAIL; - - if (usNameLen > HOSTNAME_MAX_LENGTH) - { - return CC3000_EXPORT(errno); - } - - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + SIMPLE_LINK_HCI_CMND_TRANSPORT_HEADER_SIZE); - - // Fill in HCI packet structure - args = UINT32_TO_STREAM(args, 8); - args = UINT32_TO_STREAM(args, usNameLen); - ARRAY_TO_STREAM(args, hostname, usNameLen); - - // Initiate a HCI command - hci_command_send(HCI_CMND_GETHOSTNAME, ptr, SOCKET_GET_HOST_BY_NAME_PARAMS_LEN - + usNameLen - 1); - - // Since we are in blocking state - wait for event complete - SimpleLinkWaitEvent(HCI_EVNT_BSD_GETHOSTBYNAME, &ret); - - CC3000_EXPORT(errno) = ret.retVal; - - (*((INT32*)out_ip_addr)) = ret.outputAddress; - - return CC3000_EXPORT(errno); - -} -#endif - -//***************************************************************************** -// -//! connect -//! -//! @param[in] sd socket descriptor (handle) -//! @param[in] addr specifies the destination addr. On this version -//! only AF_INET is supported. -//! @param[out] addrlen contains the size of the structure pointed to by addr -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief initiate a connection on a socket -//! Function connects the socket referred to by the socket descriptor -//! sd, to the address specified by addr. The addrlen argument -//! specifies the size of addr. The format of the address in addr is -//! determined by the address space of the socket. If it is of type -//! SOCK_DGRAM, this call specifies the peer with which the socket is -//! to be associated; this address is that to which datagrams are to be -//! sent, and the only address from which datagrams are to be received. -//! If the socket is of type SOCK_STREAM, this call attempts to make a -//! connection to another socket. The other socket is specified by -//! address, which is an address in the communications space of the -//! socket. Note that the function implements only blocking behavior -//! thus the caller will be waiting either for the connection -//! establishment or for the connection establishment failure. -//! -//! @sa socket -// -//***************************************************************************** - -INT32 CC3000_EXPORT(connect)(INT32 sd, const sockaddr *addr, INT32 addrlen) -{ - INT32 ret; - UINT8 *ptr, *args; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + SIMPLE_LINK_HCI_CMND_TRANSPORT_HEADER_SIZE); - addrlen = 8; - - // Fill in temporary command buffer - args = UINT32_TO_STREAM(args, sd); - args = UINT32_TO_STREAM(args, 0x00000008); - args = UINT32_TO_STREAM(args, addrlen); - ARRAY_TO_STREAM(args, ((UINT8 *)addr), addrlen); - - // Initiate a HCI command - hci_command_send(HCI_CMND_CONNECT, - ptr, SOCKET_CONNECT_PARAMS_LEN); - - // Since we are in blocking state - wait for event complete - SimpleLinkWaitEvent(HCI_CMND_CONNECT, &ret); - - CC3000_EXPORT(errno) = ret; - - return((INT32)ret); -} - - -//***************************************************************************** -// -//! select -//! -//! @param[in] nfds the highest-numbered file descriptor in any of the -//! three sets, plus 1. -//! @param[out] writesds socket descriptors list for write monitoring -//! @param[out] readsds socket descriptors list for read monitoring -//! @param[out] exceptsds socket descriptors list for exception monitoring -//! @param[in] timeout is an upper bound on the amount of time elapsed -//! before select() returns. Null means infinity -//! timeout. The minimum timeout is 5 milliseconds, -//! less than 5 milliseconds will be set -//! automatically to 5 milliseconds. -//! @return On success, select() returns the number of file descriptors -//! contained in the three returned descriptor sets (that is, the -//! total number of bits that are set in readfds, writefds, -//! exceptfds) which may be zero if the timeout expires before -//! anything interesting happens. -//! On error, -1 is returned. -//! *readsds - return the sockets on which Read request will -//! return without delay with valid data. -//! *writesds - return the sockets on which Write request -//! will return without delay. -//! *exceptsds - return the sockets which closed recently. -//! -//! @brief Monitor socket activity -//! Select allow a program to monitor multiple file descriptors, -//! waiting until one or more of the file descriptors become -//! "ready" for some class of I/O operation -//! -//! @Note If the timeout value set to less than 5ms it will automatically set -//! to 5ms to prevent overload of the system -//! -//! @sa socket -// -//***************************************************************************** - -INT16 CC3000_EXPORT(select)(INT32 nfds, fd_set *readsds, fd_set *writesds, fd_set *exceptsds, -struct cc3000_timeval *timeout) -{ - UINT8 *ptr, *args; - tBsdSelectRecvParams tParams; - UINT32 is_blocking; - - if( timeout == NULL) - { - is_blocking = 1; /* blocking , infinity timeout */ - } - else - { - is_blocking = 0; /* no blocking, timeout */ - } - - // Fill in HCI packet structure - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in temporary command buffer - args = UINT32_TO_STREAM(args, nfds); - args = UINT32_TO_STREAM(args, 0x00000014); - args = UINT32_TO_STREAM(args, 0x00000014); - args = UINT32_TO_STREAM(args, 0x00000014); - args = UINT32_TO_STREAM(args, 0x00000014); - args = UINT32_TO_STREAM(args, is_blocking); - args = UINT32_TO_STREAM(args, ((readsds) ? *(UINT32*)readsds : 0)); - args = UINT32_TO_STREAM(args, ((writesds) ? *(UINT32*)writesds : 0)); - args = UINT32_TO_STREAM(args, ((exceptsds) ? *(UINT32*)exceptsds : 0)); - - if (timeout) - { - if ( 0 == timeout->tv_sec && timeout->tv_usec < - SELECT_TIMEOUT_MIN_MICRO_SECONDS) - { - timeout->tv_usec = SELECT_TIMEOUT_MIN_MICRO_SECONDS; - } - args = UINT32_TO_STREAM(args, timeout->tv_sec); - args = UINT32_TO_STREAM(args, timeout->tv_usec); - } - - // Initiate a HCI command - hci_command_send(HCI_CMND_BSD_SELECT, ptr, SOCKET_SELECT_PARAMS_LEN); - - // Since we are in blocking state - wait for event complete - SimpleLinkWaitEvent(HCI_EVNT_SELECT, &tParams); - - // Update actually read FD - if (tParams.iStatus >= 0) - { - if (readsds) - { - memcpy(readsds, &tParams.uiRdfd, sizeof(tParams.uiRdfd)); - } - - if (writesds) - { - memcpy(writesds, &tParams.uiWrfd, sizeof(tParams.uiWrfd)); - } - - if (exceptsds) - { - memcpy(exceptsds, &tParams.uiExfd, sizeof(tParams.uiExfd)); - } - - return(tParams.iStatus); - - } - else - { - CC3000_EXPORT(errno) = tParams.iStatus; - return(-1); - } -} - -//***************************************************************************** -// -//! setsockopt -//! -//! @param[in] sd socket handle -//! @param[in] level defines the protocol level for this option -//! @param[in] optname defines the option name to Interrogate -//! @param[in] optval specifies a value for the option -//! @param[in] optlen specifies the length of the option value -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief set socket options -//! This function manipulate the options associated with a socket. -//! Options may exist at multiple protocol levels; they are always -//! present at the uppermost socket level. -//! When manipulating socket options the level at which the option -//! resides and the name of the option must be specified. -//! To manipulate options at the socket level, level is specified as -//! SOL_SOCKET. To manipulate options at any other level the protocol -//! number of the appropriate protocol controlling the option is -//! supplied. For example, to indicate that an option is to be -//! interpreted by the TCP protocol, level should be set to the -//! protocol number of TCP; -//! The parameters optval and optlen are used to access optval - -//! use for setsockopt(). For getsockopt() they identify a buffer -//! in which the value for the requested option(s) are to -//! be returned. For getsockopt(), optlen is a value-result -//! parameter, initially containing the size of the buffer -//! pointed to by option_value, and modified on return to -//! indicate the actual size of the value returned. If no option -//! value is to be supplied or returned, option_value may be NULL. -//! -//! @Note On this version the following two socket options are enabled: -//! The only protocol level supported in this version -//! is SOL_SOCKET (level). -//! 1. SOCKOPT_RECV_TIMEOUT (optname) -//! SOCKOPT_RECV_TIMEOUT configures recv and recvfrom timeout -//! in milliseconds. -//! In that case optval should be pointer to UINT32. -//! 2. SOCKOPT_NONBLOCK (optname). sets the socket non-blocking mode on -//! or off. -//! In that case optval should be SOCK_ON or SOCK_OFF (optval). -//! -//! @sa getsockopt -// -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -INT16 CC3000_EXPORT(setsockopt)(INT32 sd, INT32 level, INT32 optname, const void *optval, - socklen_t optlen) -{ - INT32 ret; - UINT8 *ptr, *args; - - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in temporary command buffer - args = UINT32_TO_STREAM(args, sd); - args = UINT32_TO_STREAM(args, level); - args = UINT32_TO_STREAM(args, optname); - args = UINT32_TO_STREAM(args, 0x00000008); - args = UINT32_TO_STREAM(args, optlen); - ARRAY_TO_STREAM(args, ((UINT8 *)optval), optlen); - - // Initiate a HCI command - hci_command_send(HCI_CMND_SETSOCKOPT, - ptr, SOCKET_SET_SOCK_OPT_PARAMS_LEN + optlen); - - // Since we are in blocking state - wait for event complete - SimpleLinkWaitEvent(HCI_CMND_SETSOCKOPT, &ret); - - if (ret >= 0) - { - return (0); - } - else - { - CC3000_EXPORT(errno) = ret; - return ret; - } -} -#endif - -//***************************************************************************** -// -//! getsockopt -//! -//! @param[in] sd socket handle -//! @param[in] level defines the protocol level for this option -//! @param[in] optname defines the option name to Interrogate -//! @param[out] optval specifies a value for the option -//! @param[out] optlen specifies the length of the option value -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief set socket options -//! This function manipulate the options associated with a socket. -//! Options may exist at multiple protocol levels; they are always -//! present at the uppermost socket level. -//! When manipulating socket options the level at which the option -//! resides and the name of the option must be specified. -//! To manipulate options at the socket level, level is specified as -//! SOL_SOCKET. To manipulate options at any other level the protocol -//! number of the appropriate protocol controlling the option is -//! supplied. For example, to indicate that an option is to be -//! interpreted by the TCP protocol, level should be set to the -//! protocol number of TCP; -//! The parameters optval and optlen are used to access optval - -//! use for setsockopt(). For getsockopt() they identify a buffer -//! in which the value for the requested option(s) are to -//! be returned. For getsockopt(), optlen is a value-result -//! parameter, initially containing the size of the buffer -//! pointed to by option_value, and modified on return to -//! indicate the actual size of the value returned. If no option -//! value is to be supplied or returned, option_value may be NULL. -//! -//! @Note On this version the following two socket options are enabled: -//! The only protocol level supported in this version -//! is SOL_SOCKET (level). -//! 1. SOCKOPT_RECV_TIMEOUT (optname) -//! SOCKOPT_RECV_TIMEOUT configures recv and recvfrom timeout -//! in milliseconds. -//! In that case optval should be pointer to UINT32. -//! 2. SOCKOPT_NONBLOCK (optname). sets the socket non-blocking mode on -//! or off. -//! In that case optval should be SOCK_ON or SOCK_OFF (optval). -//! -//! @sa setsockopt -// -//***************************************************************************** - -INT16 CC3000_EXPORT(getsockopt) (INT32 sd, INT32 level, INT32 optname, void *optval, socklen_t *optlen) -{ - UINT8 *ptr, *args; - tBsdGetSockOptReturnParams tRetParams; - - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in temporary command buffer - args = UINT32_TO_STREAM(args, sd); - args = UINT32_TO_STREAM(args, level); - args = UINT32_TO_STREAM(args, optname); - - // Initiate a HCI command - hci_command_send(HCI_CMND_GETSOCKOPT, - ptr, SOCKET_GET_SOCK_OPT_PARAMS_LEN); - - // Since we are in blocking state - wait for event complete - SimpleLinkWaitEvent(HCI_CMND_GETSOCKOPT, &tRetParams); - - if (((INT8)tRetParams.iStatus) >= 0) - { - *optlen = 4; - memcpy(optval, tRetParams.ucOptValue, 4); - return (0); - } - else - { - CC3000_EXPORT(errno) = tRetParams.iStatus; - return CC3000_EXPORT(errno); - } -} - -//***************************************************************************** -// -//! simple_link_recv -//! -//! @param sd socket handle -//! @param buf read buffer -//! @param len buffer length -//! @param flags indicates blocking or non-blocking operation -//! @param from pointer to an address structure indicating source address -//! @param fromlen source address structure size -//! -//! @return Return the number of bytes received, or -1 if an error -//! occurred -//! -//! @brief Read data from socket -//! Return the length of the message on successful completion. -//! If a message is too long to fit in the supplied buffer, -//! excess bytes may be discarded depending on the type of -//! socket the message is received from -// -//***************************************************************************** -static INT16 simple_link_recv(INT32 sd, void *buf, INT32 len, INT32 flags, sockaddr *from, - socklen_t *fromlen, INT32 opcode) -{ - UINT8 *ptr, *args; - tBsdReadReturnParams tSocketReadEvent; - - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in HCI packet structure - args = UINT32_TO_STREAM(args, sd); - args = UINT32_TO_STREAM(args, len); - args = UINT32_TO_STREAM(args, flags); - - // Generate the read command, and wait for the - hci_command_send(opcode, ptr, SOCKET_RECV_FROM_PARAMS_LEN); - - // Since we are in blocking state - wait for event complete - SimpleLinkWaitEvent(opcode, &tSocketReadEvent); - - // In case the number of bytes is more then zero - read data - if (tSocketReadEvent.iNumberOfBytes > 0) - { - // Wait for the data in a synchronous way. Here we assume that the bug is - // big enough to store also parameters of receive from too.... - SimpleLinkWaitData(buf, (UINT8 *)from, (UINT8 *)fromlen); - } - - CC3000_EXPORT(errno) = tSocketReadEvent.iNumberOfBytes; - - return(tSocketReadEvent.iNumberOfBytes); -} - -//***************************************************************************** -// -//! recv -//! -//! @param[in] sd socket handle -//! @param[out] buf Points to the buffer where the message should be stored -//! @param[in] len Specifies the length in bytes of the buffer pointed to -//! by the buffer argument. -//! @param[in] flags Specifies the type of message reception. -//! On this version, this parameter is not supported. -//! -//! @return Return the number of bytes received, or -1 if an error -//! occurred -//! -//! @brief function receives a message from a connection-mode socket -//! -//! @sa recvfrom -//! -//! @Note On this version, only blocking mode is supported. -// -//***************************************************************************** - -INT16 CC3000_EXPORT(recv)(INT32 sd, void *buf, INT32 len, INT32 flags) -{ - return(simple_link_recv(sd, buf, len, flags, NULL, NULL, HCI_CMND_RECV)); -} - -//***************************************************************************** -// -//! recvfrom -//! -//! @param[in] sd socket handle -//! @param[out] buf Points to the buffer where the message should be stored -//! @param[in] len Specifies the length in bytes of the buffer pointed to -//! by the buffer argument. -//! @param[in] flags Specifies the type of message reception. -//! On this version, this parameter is not supported. -//! @param[in] from pointer to an address structure indicating the source -//! address: sockaddr. On this version only AF_INET is -//! supported. -//! @param[in] fromlen source address tructure size -//! -//! @return Return the number of bytes received, or -1 if an error -//! occurred -//! -//! @brief read data from socket -//! function receives a message from a connection-mode or -//! connectionless-mode socket. Note that raw sockets are not -//! supported. -//! -//! @sa recv -//! -//! @Note On this version, only blocking mode is supported. -// -//***************************************************************************** -INT16 CC3000_EXPORT(recvfrom)(INT32 sd, void *buf, INT32 len, INT32 flags, sockaddr *from, - socklen_t *fromlen) -{ - return(simple_link_recv(sd, buf, len, flags, from, fromlen, - HCI_CMND_RECVFROM)); -} - -//***************************************************************************** -// -//! simple_link_send -//! -//! @param sd socket handle -//! @param buf write buffer -//! @param len buffer length -//! @param flags On this version, this parameter is not supported -//! @param to pointer to an address structure indicating destination -//! address -//! @param tolen destination address structure size -//! -//! @return Return the number of bytes transmitted, or -1 if an error -//! occurred, or -2 in case there are no free buffers available -//! (only when SEND_NON_BLOCKING is enabled) -//! -//! @brief This function is used to transmit a message to another -//! socket -// -//***************************************************************************** -static INT16 simple_link_send(INT32 sd, const void *buf, INT32 len, INT32 flags, - const sockaddr *to, INT32 tolen, INT32 opcode) -{ - UINT8 uArgSize=0, addrlen; - UINT8 *ptr, *pDataPtr=0, *args; - UINT32 addr_offset=0; - INT16 res; - tBsdReadReturnParams tSocketSendEvent; - - // Check the bsd_arguments - if (0 != (res = HostFlowControlConsumeBuff(sd))) - { - return res; - } - - //Update the number of sent packets - tSLInformation.NumberOfSentPackets++; - - // Allocate a buffer and construct a packet and send it over spi - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_DATA); - - // Update the offset of data and parameters according to the command - switch(opcode) - { - case HCI_CMND_SENDTO: - { - addr_offset = len + sizeof(len) + sizeof(len); - addrlen = 8; - uArgSize = SOCKET_SENDTO_PARAMS_LEN; - pDataPtr = ptr + HEADERS_SIZE_DATA + SOCKET_SENDTO_PARAMS_LEN; - break; - } - - case HCI_CMND_SEND: - { - tolen = 0; - to = NULL; - uArgSize = HCI_CMND_SEND_ARG_LENGTH; - pDataPtr = ptr + HEADERS_SIZE_DATA + HCI_CMND_SEND_ARG_LENGTH; - break; - } - - default: - { - break; - } - } - - // Fill in temporary command buffer - args = UINT32_TO_STREAM(args, sd); - args = UINT32_TO_STREAM(args, uArgSize - sizeof(sd)); - args = UINT32_TO_STREAM(args, len); - args = UINT32_TO_STREAM(args, flags); - - if (opcode == HCI_CMND_SENDTO) - { - args = UINT32_TO_STREAM(args, addr_offset); - args = UINT32_TO_STREAM(args, addrlen); - } - - // Copy the data received from user into the TX Buffer - ARRAY_TO_STREAM(pDataPtr, ((UINT8 *)buf), len); - - // In case we are using SendTo, copy the to parameters - if (opcode == HCI_CMND_SENDTO) - { - ARRAY_TO_STREAM(pDataPtr, ((UINT8 *)to), tolen); - } - - // Initiate a HCI command - hci_data_send(opcode, ptr, uArgSize, len,(UINT8*)to, tolen); - - if (opcode == HCI_CMND_SENDTO) - SimpleLinkWaitEvent(HCI_EVNT_SENDTO, &tSocketSendEvent); - else - SimpleLinkWaitEvent(HCI_EVNT_SEND, &tSocketSendEvent); - - return (len); -} - - -//***************************************************************************** -// -//! send -//! -//! @param sd socket handle -//! @param buf Points to a buffer containing the message to be sent -//! @param len message size in bytes -//! @param flags On this version, this parameter is not supported -//! -//! @return Return the number of bytes transmitted, or -1 if an -//! error occurred -//! -//! @brief Write data to TCP socket -//! This function is used to transmit a message to another -//! socket. -//! -//! @Note On this version, only blocking mode is supported. -//! -//! @sa sendto -// -//***************************************************************************** - -INT16 CC3000_EXPORT(send)(INT32 sd, const void *buf, INT32 len, INT32 flags) -{ - return(simple_link_send(sd, buf, len, flags, NULL, 0, HCI_CMND_SEND)); -} - -//***************************************************************************** -// -//! sendto -//! -//! @param sd socket handle -//! @param buf Points to a buffer containing the message to be sent -//! @param len message size in bytes -//! @param flags On this version, this parameter is not supported -//! @param to pointer to an address structure indicating the destination -//! address: sockaddr. On this version only AF_INET is -//! supported. -//! @param tolen destination address structure size -//! -//! @return Return the number of bytes transmitted, or -1 if an -//! error occurred -//! -//! @brief Write data to TCP socket -//! This function is used to transmit a message to another -//! socket. -//! -//! @Note On this version, only blocking mode is supported. -//! -//! @sa send -// -//***************************************************************************** - -INT16 CC3000_EXPORT(sendto)(INT32 sd, const void *buf, INT32 len, INT32 flags, const sockaddr *to, - socklen_t tolen) -{ - return(simple_link_send(sd, buf, len, flags, to, tolen, HCI_CMND_SENDTO)); -} - -//***************************************************************************** -// -//! mdnsAdvertiser -//! -//! @param[in] mdnsEnabled flag to enable/disable the mDNS feature -//! @param[in] deviceServiceName Service name as part of the published -//! canonical domain name -//! @param[in] deviceServiceNameLength Length of the service name - up to 32 chars -//! -//! -//! @return On success, zero is returned, return SOC_ERROR if socket was not -//! opened successfully, or if an error occurred. -//! -//! @brief Set CC3000 in mDNS advertiser mode in order to advertise itself. -// -//***************************************************************************** - -INT16 CC3000_EXPORT(mdnsAdvertiser)(UINT16 mdnsEnabled, CHAR * deviceServiceName, UINT16 deviceServiceNameLength) -{ - INT8 ret; - UINT8 *pTxBuffer, *pArgs; - - if (deviceServiceNameLength > MDNS_DEVICE_SERVICE_MAX_LENGTH) - { - return EFAIL; - } - - pTxBuffer = tSLInformation.pucTxCommandBuffer; - pArgs = (pTxBuffer + SIMPLE_LINK_HCI_CMND_TRANSPORT_HEADER_SIZE); - - // Fill in HCI packet structure - pArgs = UINT32_TO_STREAM(pArgs, mdnsEnabled); - pArgs = UINT32_TO_STREAM(pArgs, 8); - pArgs = UINT32_TO_STREAM(pArgs, deviceServiceNameLength); - ARRAY_TO_STREAM(pArgs, deviceServiceName, deviceServiceNameLength); - - // Initiate a HCI command - hci_command_send(HCI_CMND_MDNS_ADVERTISE, pTxBuffer, SOCKET_MDNS_ADVERTISE_PARAMS_LEN + deviceServiceNameLength); - - // Since we are in blocking state - wait for event complete - SimpleLinkWaitEvent(HCI_EVNT_MDNS_ADVERTISE, &ret); - - return ret; - -} - - -//***************************************************************************** -// -//! getmssvalue -//! -//! @param[in] sd socket descriptor -//! -//! @return On success, returns the MSS value of a TCP connection -//! -//! @brief Returns the MSS value of a TCP connection according to the socket descriptor -// -//***************************************************************************** -UINT16 CC3000_EXPORT(getmssvalue) (INT32 sd) -{ - UINT8 *ptr, *args; - UINT16 ret; - - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in temporary command buffer - args = UINT32_TO_STREAM(args, sd); - - // Initiate a HCI command - hci_command_send(HCI_CMND_GETMSSVALUE, ptr, SOCKET_GET_MSS_VALUE_PARAMS_LEN); - - // Since we are in blocking state - wait for event complete - SimpleLinkWaitEvent(HCI_EVNT_GETMSSVALUE, &ret); - - return ret; -} diff --git a/drivers/cc3000/src/wlan.c b/drivers/cc3000/src/wlan.c deleted file mode 100644 index 6385937778..0000000000 --- a/drivers/cc3000/src/wlan.c +++ /dev/null @@ -1,1252 +0,0 @@ -/***************************************************************************** -* -* wlan.c - CC3000 Host Driver Implementation. -* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*****************************************************************************/ - -//***************************************************************************** -// -//! \addtogroup wlan_api -//! @{ -// -//***************************************************************************** - -#include -#include "wlan.h" -#include "hci.h" -#include "ccspi.h" -#include "socket.h" -#include "nvmem.h" -#include "security.h" -#include "evnt_handler.h" - - -volatile sSimplLinkInformation tSLInformation; - -#define SMART_CONFIG_PROFILE_SIZE 67 // 67 = 32 (max ssid) + 32 (max key) + 1 (SSID length) + 1 (security type) + 1 (key length) - -#ifndef CC3000_UNENCRYPTED_SMART_CONFIG -UINT8 key[AES128_KEY_SIZE]; -UINT8 profileArray[SMART_CONFIG_PROFILE_SIZE]; -#endif //CC3000_UNENCRYPTED_SMART_CONFIG - -/* patches type */ -#define PATCHES_HOST_TYPE_WLAN_DRIVER 0x01 -#define PATCHES_HOST_TYPE_WLAN_FW 0x02 -#define PATCHES_HOST_TYPE_BOOTLOADER 0x03 - -#define SL_SET_SCAN_PARAMS_INTERVAL_LIST_SIZE (16) -#define SL_SIMPLE_CONFIG_PREFIX_LENGTH (3) -#define ETH_ALEN (6) -#define MAXIMAL_SSID_LENGTH (32) - -#define SL_PATCHES_REQUEST_DEFAULT (0) -#define SL_PATCHES_REQUEST_FORCE_HOST (1) -#define SL_PATCHES_REQUEST_FORCE_NONE (2) - - -#define WLAN_SEC_UNSEC (0) -#define WLAN_SEC_WEP (1) -#define WLAN_SEC_WPA (2) -#define WLAN_SEC_WPA2 (3) - - -#define WLAN_SL_INIT_START_PARAMS_LEN (1) -#define WLAN_PATCH_PARAMS_LENGTH (8) -#define WLAN_SET_CONNECTION_POLICY_PARAMS_LEN (12) -#define WLAN_DEL_PROFILE_PARAMS_LEN (4) -#define WLAN_SET_MASK_PARAMS_LEN (4) -#define WLAN_SET_SCAN_PARAMS_LEN (100) -#define WLAN_GET_SCAN_RESULTS_PARAMS_LEN (4) -#define WLAN_ADD_PROFILE_NOSEC_PARAM_LEN (24) -#define WLAN_ADD_PROFILE_WEP_PARAM_LEN (36) -#define WLAN_ADD_PROFILE_WPA_PARAM_LEN (44) -#define WLAN_CONNECT_PARAM_LEN (29) -#define WLAN_SMART_CONFIG_START_PARAMS_LEN (4) - - - - -//***************************************************************************** -// -//! SimpleLink_Init_Start -//! -//! @param usPatchesAvailableAtHost flag to indicate if patches available -//! from host or from EEPROM. Due to the -//! fact the patches are burn to the EEPROM -//! using the patch programmer utility, the -//! patches will be available from the EEPROM -//! and not from the host. -//! -//! @return none -//! -//! @brief Send HCI_CMND_SIMPLE_LINK_START to CC3000 -// -//***************************************************************************** -static void SimpleLink_Init_Start(UINT16 usPatchesAvailableAtHost) -{ - UINT8 *ptr; - UINT8 *args; - - ptr = tSLInformation.pucTxCommandBuffer; - args = (UINT8 *)(ptr + HEADERS_SIZE_CMD); - - UINT8_TO_STREAM(args, ((usPatchesAvailableAtHost) ? SL_PATCHES_REQUEST_FORCE_NONE : SL_PATCHES_REQUEST_DEFAULT)); - - // IRQ Line asserted - send HCI_CMND_SIMPLE_LINK_START to CC3000 - hci_command_send(HCI_CMND_SIMPLE_LINK_START, ptr, WLAN_SL_INIT_START_PARAMS_LEN); - - SimpleLinkWaitEvent(HCI_CMND_SIMPLE_LINK_START, 0); -} - - - -//***************************************************************************** -// -//! wlan_init -//! -//! @param sWlanCB Asynchronous events callback. -//! 0 no event call back. -//! -call back parameters: -//! 1) event_type: HCI_EVNT_WLAN_UNSOL_CONNECT connect event, -//! HCI_EVNT_WLAN_UNSOL_DISCONNECT disconnect event, -//! HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE config done, -//! HCI_EVNT_WLAN_UNSOL_DHCP dhcp report, -//! HCI_EVNT_WLAN_ASYNC_PING_REPORT ping report OR -//! HCI_EVNT_WLAN_KEEPALIVE keepalive. -//! 2) data: pointer to extra data that received by the event -//! (NULL no data). -//! 3) length: data length. -//! -Events with extra data: -//! HCI_EVNT_WLAN_UNSOL_DHCP: 4 bytes IP, 4 bytes Mask, -//! 4 bytes default gateway, 4 bytes DHCP server and 4 bytes -//! for DNS server. -//! HCI_EVNT_WLAN_ASYNC_PING_REPORT: 4 bytes Packets sent, -//! 4 bytes Packets received, 4 bytes Min round time, -//! 4 bytes Max round time and 4 bytes for Avg round time. -//! -//! @param sFWPatches 0 no patch or pointer to FW patches -//! @param sDriverPatches 0 no patch or pointer to driver patches -//! @param sBootLoaderPatches 0 no patch or pointer to bootloader patches -//! @param sReadWlanInterruptPin init callback. the callback read wlan -//! interrupt status. -//! @param sWlanInterruptEnable init callback. the callback enable wlan -//! interrupt. -//! @param sWlanInterruptDisable init callback. the callback disable wlan -//! interrupt. -//! @param sWriteWlanPin init callback. the callback write value -//! to device pin. -//! -//! @return none -//! -//! @sa wlan_set_event_mask , wlan_start , wlan_stop -//! -//! @brief Initialize wlan driver -//! -//! @warning This function must be called before ANY other wlan driver function -// -//***************************************************************************** - -void wlan_init( tWlanCB sWlanCB, - tFWPatches sFWPatches, - tDriverPatches sDriverPatches, - tBootLoaderPatches sBootLoaderPatches, - tWlanReadInteruptPin sReadWlanInterruptPin, - tWlanInterruptEnable sWlanInterruptEnable, - tWlanInterruptDisable sWlanInterruptDisable, - tWriteWlanPin sWriteWlanPin) -{ - - tSLInformation.sFWPatches = sFWPatches; - tSLInformation.sDriverPatches = sDriverPatches; - tSLInformation.sBootLoaderPatches = sBootLoaderPatches; - - // init io callback - tSLInformation.ReadWlanInterruptPin = sReadWlanInterruptPin; - tSLInformation.WlanInterruptEnable = sWlanInterruptEnable; - tSLInformation.WlanInterruptDisable = sWlanInterruptDisable; - tSLInformation.WriteWlanPin = sWriteWlanPin; - - //init asynchronous events callback - tSLInformation.sWlanCB= sWlanCB; - - // By default TX Complete events are routed to host too - tSLInformation.InformHostOnTxComplete = 1; -} - -//***************************************************************************** -// -//! SpiReceiveHandler -//! -//! @param pvBuffer - pointer to the received data buffer -//! The function triggers Received event/data processing -//! -//! @param Pointer to the received data -//! @return none -//! -//! @brief The function triggers Received event/data processing. It is -//! called from the SPI library to receive the data -// -//***************************************************************************** -void SpiReceiveHandler(void *pvBuffer) -{ - tSLInformation.usEventOrDataReceived = 1; - tSLInformation.pucReceivedData = (UINT8 *)pvBuffer; - - hci_unsolicited_event_handler(); -} - - -//***************************************************************************** -// -//! wlan_start -//! -//! @param usPatchesAvailableAtHost - flag to indicate if patches available -//! from host or from EEPROM. Due to the -//! fact the patches are burn to the EEPROM -//! using the patch programmer utility, the -//! patches will be available from the EEPROM -//! and not from the host. -//! -//! @return none -//! -//! @brief Start WLAN device. This function asserts the enable pin of -//! the device (WLAN_EN), starting the HW initialization process. -//! The function blocked until device Initialization is completed. -//! Function also configure patches (FW, driver or bootloader) -//! and calls appropriate device callbacks. -//! -//! @Note Prior calling the function wlan_init shall be called. -//! @Warning This function must be called after wlan_init and before any -//! other wlan API -//! @sa wlan_init , wlan_stop -//! -// -//***************************************************************************** -#define TIMEOUT (500000) - -int wlan_start(UINT16 usPatchesAvailableAtHost) -{ - - UINT32 ulSpiIRQState; - UINT32 wlan_timeout; - - tSLInformation.NumberOfSentPackets = 0; - tSLInformation.NumberOfReleasedPackets = 0; - tSLInformation.usRxEventOpcode = 0; - tSLInformation.usNumberOfFreeBuffers = 0; - tSLInformation.usSlBufferLength = 0; - tSLInformation.usBufferSize = 0; - tSLInformation.usRxDataPending = 0; - tSLInformation.slTransmitDataError = 0; - tSLInformation.usEventOrDataReceived = 0; - tSLInformation.pucReceivedData = 0; - - // Allocate the memory for the RX/TX data transactions - tSLInformation.pucTxCommandBuffer = (UINT8 *)wlan_tx_buffer; - - // init spi - SpiOpen(SpiReceiveHandler); - - // Check the IRQ line - ulSpiIRQState = tSLInformation.ReadWlanInterruptPin(); - - // Chip enable: toggle WLAN EN line - tSLInformation.WriteWlanPin( WLAN_ENABLE ); - - wlan_timeout = TIMEOUT; - if (ulSpiIRQState) { - // wait till the IRQ line goes low - while(tSLInformation.ReadWlanInterruptPin() != 0 && --wlan_timeout) - { - } - } - else - { - // wait till the IRQ line goes high and than low - while(tSLInformation.ReadWlanInterruptPin() == 0 && --wlan_timeout) - { - } - - if (wlan_timeout == 0) { - return -1; - } - - wlan_timeout = TIMEOUT; - while(tSLInformation.ReadWlanInterruptPin() != 0 && --wlan_timeout) - { - } - } - - if (wlan_timeout ==0) { - return -1; - } - - SimpleLink_Init_Start(usPatchesAvailableAtHost); - - // Read Buffer's size and finish - hci_command_send(HCI_CMND_READ_BUFFER_SIZE, tSLInformation.pucTxCommandBuffer, 0); - SimpleLinkWaitEvent(HCI_CMND_READ_BUFFER_SIZE, 0); - - return 0; -} - - -//***************************************************************************** -// -//! wlan_stop -//! -//! @param none -//! -//! @return none -//! -//! @brief Stop WLAN device by putting it into reset state. -//! -//! @sa wlan_start -// -//***************************************************************************** - -void wlan_stop(void) -{ - // Chip disable - tSLInformation.WriteWlanPin( WLAN_DISABLE ); - - // Wait till IRQ line goes high... - while(tSLInformation.ReadWlanInterruptPin() == 0) - { - } - - // Free the used by WLAN Driver memory - if (tSLInformation.pucTxCommandBuffer) - { - tSLInformation.pucTxCommandBuffer = 0; - } - - SpiClose(); -} - - -//***************************************************************************** -// -//! wlan_connect -//! -//! @param sec_type security options: -//! WLAN_SEC_UNSEC, -//! WLAN_SEC_WEP (ASCII support only), -//! WLAN_SEC_WPA or WLAN_SEC_WPA2 -//! @param ssid up to 32 bytes and is ASCII SSID of the AP -//! @param ssid_len length of the SSID -//! @param bssid 6 bytes specified the AP bssid -//! @param key up to 32 bytes specified the AP security key -//! @param key_len key length -//! -//! @return On success, zero is returned. On error, negative is returned. -//! Note that even though a zero is returned on success to trigger -//! connection operation, it does not mean that CCC3000 is already -//! connected. An asynchronous "Connected" event is generated when -//! actual association process finishes and CC3000 is connected to -//! the AP. If DHCP is set, An asynchronous "DHCP" event is -//! generated when DHCP process is finish. -//! -//! -//! @brief Connect to AP -//! @warning Please Note that when connection to AP configured with security -//! type WEP, please confirm that the key is set as ASCII and not -//! as HEX. -//! @sa wlan_disconnect -// -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -INT32 wlan_connect(UINT32 ulSecType, CHAR *ssid, INT32 ssid_len, - UINT8 *bssid, UINT8 *key, INT32 key_len) -{ - INT32 ret; - UINT8 *ptr; - UINT8 *args; - UINT8 bssid_zero[] = {0, 0, 0, 0, 0, 0}; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in command buffer - args = UINT32_TO_STREAM(args, 0x0000001c); - args = UINT32_TO_STREAM(args, ssid_len); - args = UINT32_TO_STREAM(args, ulSecType); - args = UINT32_TO_STREAM(args, 0x00000010 + ssid_len); - args = UINT32_TO_STREAM(args, key_len); - args = UINT16_TO_STREAM(args, 0); - - // padding shall be zeroed - if(bssid) - { - ARRAY_TO_STREAM(args, bssid, ETH_ALEN); - } - else - { - ARRAY_TO_STREAM(args, bssid_zero, ETH_ALEN); - } - - ARRAY_TO_STREAM(args, ssid, ssid_len); - - if(key_len && key) - { - ARRAY_TO_STREAM(args, key, key_len); - } - - // Initiate a HCI command - hci_command_send(HCI_CMND_WLAN_CONNECT, ptr, WLAN_CONNECT_PARAM_LEN + - ssid_len + key_len - 1); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_CMND_WLAN_CONNECT, &ret); - CC3000_EXPORT(errno) = ret; - - return(ret); -} -#else -INT32 wlan_connect(CHAR *ssid, INT32 ssid_len) -{ - INT32 ret; - UINT8 *ptr; - UINT8 *args; - UINT8 bssid_zero[] = {0, 0, 0, 0, 0, 0}; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in command buffer - args = UINT32_TO_STREAM(args, 0x0000001c); - args = UINT32_TO_STREAM(args, ssid_len); - args = UINT32_TO_STREAM(args, 0); - args = UINT32_TO_STREAM(args, 0x00000010 + ssid_len); - args = UINT32_TO_STREAM(args, 0); - args = UINT16_TO_STREAM(args, 0); - - // padding shall be zeroed - ARRAY_TO_STREAM(args, bssid_zero, ETH_ALEN); - ARRAY_TO_STREAM(args, ssid, ssid_len); - - // Initiate a HCI command - hci_command_send(HCI_CMND_WLAN_CONNECT, ptr, WLAN_CONNECT_PARAM_LEN + - ssid_len - 1); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_CMND_WLAN_CONNECT, &ret); - CC3000_EXPORT(errno) = ret; - - return(ret); -} -#endif - -//***************************************************************************** -// -//! wlan_disconnect -//! -//! @return 0 disconnected done, other CC3000 already disconnected -//! -//! @brief Disconnect connection from AP. -//! -//! @sa wlan_connect -// -//***************************************************************************** - -INT32 wlan_disconnect() -{ - INT32 ret; - UINT8 *ptr; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - - hci_command_send(HCI_CMND_WLAN_DISCONNECT, ptr, 0); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_CMND_WLAN_DISCONNECT, &ret); - CC3000_EXPORT(errno) = ret; - - return(ret); -} - -//***************************************************************************** -// -//! wlan_ioctl_set_connection_policy -//! -//! @param should_connect_to_open_ap enable(1), disable(0) connect to any -//! available AP. This parameter corresponds to the configuration of -//! item # 3 in the brief description. -//! @param should_use_fast_connect enable(1), disable(0). if enabled, tries -//! to connect to the last connected AP. This parameter corresponds -//! to the configuration of item # 1 in the brief description. -//! @param auto_start enable(1), disable(0) auto connect -//! after reset and periodically reconnect if needed. This -//! configuration configures option 2 in the above description. -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief When auto is enabled, the device tries to connect according -//! the following policy: -//! 1) If fast connect is enabled and last connection is valid, -//! the device will try to connect to it without the scanning -//! procedure (fast). The last connection will be marked as -//! invalid, due to adding/removing profile. -//! 2) If profile exists, the device will try to connect it -//! (Up to seven profiles). -//! 3) If fast and profiles are not found, and open mode is -//! enabled, the device will try to connect to any AP. -//! * Note that the policy settings are stored in the CC3000 NVMEM. -//! -//! @sa wlan_add_profile , wlan_ioctl_del_profile -// -//***************************************************************************** - -INT32 wlan_ioctl_set_connection_policy(UINT32 should_connect_to_open_ap, - UINT32 ulShouldUseFastConnect, - UINT32 ulUseProfiles) -{ - INT32 ret; - UINT8 *ptr; - UINT8 *args; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (UINT8 *)(ptr + HEADERS_SIZE_CMD); - - // Fill in HCI packet structure - args = UINT32_TO_STREAM(args, should_connect_to_open_ap); - args = UINT32_TO_STREAM(args, ulShouldUseFastConnect); - args = UINT32_TO_STREAM(args, ulUseProfiles); - - // Initiate a HCI command - hci_command_send(HCI_CMND_WLAN_IOCTL_SET_CONNECTION_POLICY, - ptr, WLAN_SET_CONNECTION_POLICY_PARAMS_LEN); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_CMND_WLAN_IOCTL_SET_CONNECTION_POLICY, &ret); - - return(ret); -} - -//***************************************************************************** -// -//! wlan_add_profile -//! -//! @param ulSecType WLAN_SEC_UNSEC,WLAN_SEC_WEP,WLAN_SEC_WPA,WLAN_SEC_WPA2 -//! @param ucSsid ssid SSID up to 32 bytes -//! @param ulSsidLen ssid length -//! @param ucBssid bssid 6 bytes -//! @param ulPriority ulPriority profile priority. Lowest priority:0. -//! Important Note: Smartconfig process (in unencrypted mode) -//! stores the profile internally with priority 1, so changing -//! priorities when adding new profiles should be done with extra care -//! @param ulPairwiseCipher_Or_TxKeyLen key length for WEP security -//! @param ulGroupCipher_TxKeyIndex key index -//! @param ulKeyMgmt KEY management -//! @param ucPf_OrKey security key -//! @param ulPassPhraseLen security key length for WPA\WPA2 -//! -//! @return On success, index (1-7) of the stored profile is returned. -//! On error, -1 is returned. -//! -//! @brief When auto start is enabled, the device connects to -//! station from the profiles table. Up to 7 profiles are supported. -//! If several profiles configured the device choose the highest -//! priority profile, within each priority group, device will choose -//! profile based on security policy, signal strength, etc -//! parameters. All the profiles are stored in CC3000 NVMEM. -//! -//! @sa wlan_ioctl_del_profile -// -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -INT32 wlan_add_profile(UINT32 ulSecType, - UINT8* ucSsid, - UINT32 ulSsidLen, - UINT8 *ucBssid, - UINT32 ulPriority, - UINT32 ulPairwiseCipher_Or_TxKeyLen, - UINT32 ulGroupCipher_TxKeyIndex, - UINT32 ulKeyMgmt, - UINT8* ucPf_OrKey, - UINT32 ulPassPhraseLen) -{ - UINT16 arg_len=0; - INT32 ret; - UINT8 *ptr; - INT32 i = 0; - UINT8 *args; - UINT8 bssid_zero[] = {0, 0, 0, 0, 0, 0}; - - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - args = UINT32_TO_STREAM(args, ulSecType); - - // Setup arguments in accordance with the security type - switch (ulSecType) - { - //OPEN - case WLAN_SEC_UNSEC: - { - args = UINT32_TO_STREAM(args, 0x00000014); - args = UINT32_TO_STREAM(args, ulSsidLen); - args = UINT16_TO_STREAM(args, 0); - if(ucBssid) - { - ARRAY_TO_STREAM(args, ucBssid, ETH_ALEN); - } - else - { - ARRAY_TO_STREAM(args, bssid_zero, ETH_ALEN); - } - args = UINT32_TO_STREAM(args, ulPriority); - ARRAY_TO_STREAM(args, ucSsid, ulSsidLen); - - arg_len = WLAN_ADD_PROFILE_NOSEC_PARAM_LEN + ulSsidLen; - } - break; - - //WEP - case WLAN_SEC_WEP: - { - args = UINT32_TO_STREAM(args, 0x00000020); - args = UINT32_TO_STREAM(args, ulSsidLen); - args = UINT16_TO_STREAM(args, 0); - if(ucBssid) - { - ARRAY_TO_STREAM(args, ucBssid, ETH_ALEN); - } - else - { - ARRAY_TO_STREAM(args, bssid_zero, ETH_ALEN); - } - args = UINT32_TO_STREAM(args, ulPriority); - args = UINT32_TO_STREAM(args, 0x0000000C + ulSsidLen); - args = UINT32_TO_STREAM(args, ulPairwiseCipher_Or_TxKeyLen); - args = UINT32_TO_STREAM(args, ulGroupCipher_TxKeyIndex); - ARRAY_TO_STREAM(args, ucSsid, ulSsidLen); - - for(i = 0; i < 4; i++) - { - UINT8 *p = &ucPf_OrKey[i * ulPairwiseCipher_Or_TxKeyLen]; - - ARRAY_TO_STREAM(args, p, ulPairwiseCipher_Or_TxKeyLen); - } - - arg_len = WLAN_ADD_PROFILE_WEP_PARAM_LEN + ulSsidLen + - ulPairwiseCipher_Or_TxKeyLen * 4; - - } - break; - - //WPA - //WPA2 - case WLAN_SEC_WPA: - case WLAN_SEC_WPA2: - { - args = UINT32_TO_STREAM(args, 0x00000028); - args = UINT32_TO_STREAM(args, ulSsidLen); - args = UINT16_TO_STREAM(args, 0); - if(ucBssid) - { - ARRAY_TO_STREAM(args, ucBssid, ETH_ALEN); - } - else - { - ARRAY_TO_STREAM(args, bssid_zero, ETH_ALEN); - } - args = UINT32_TO_STREAM(args, ulPriority); - args = UINT32_TO_STREAM(args, ulPairwiseCipher_Or_TxKeyLen); - args = UINT32_TO_STREAM(args, ulGroupCipher_TxKeyIndex); - args = UINT32_TO_STREAM(args, ulKeyMgmt); - args = UINT32_TO_STREAM(args, 0x00000008 + ulSsidLen); - args = UINT32_TO_STREAM(args, ulPassPhraseLen); - ARRAY_TO_STREAM(args, ucSsid, ulSsidLen); - ARRAY_TO_STREAM(args, ucPf_OrKey, ulPassPhraseLen); - - arg_len = WLAN_ADD_PROFILE_WPA_PARAM_LEN + ulSsidLen + ulPassPhraseLen; - } - - break; - } - - // Initiate a HCI command - hci_command_send(HCI_CMND_WLAN_IOCTL_ADD_PROFILE, - ptr, arg_len); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_CMND_WLAN_IOCTL_ADD_PROFILE, &ret); - - return(ret); -} -#else -INT32 wlan_add_profile(UINT32 ulSecType, - UINT8* ucSsid, - UINT32 ulSsidLen, - UINT8 *ucBssid, - UINT32 ulPriority, - UINT32 ulPairwiseCipher_Or_TxKeyLen, - UINT32 ulGroupCipher_TxKeyIndex, - UINT32 ulKeyMgmt, - UINT8* ucPf_OrKey, - UINT32 ulPassPhraseLen) -{ - return -1; -} -#endif - -//***************************************************************************** -// -//! wlan_ioctl_del_profile -//! -//! @param index number of profile to delete -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Delete WLAN profile -//! -//! @Note In order to delete all stored profile, set index to 255. -//! -//! @sa wlan_add_profile -// -//***************************************************************************** - -INT32 wlan_ioctl_del_profile(UINT32 ulIndex) -{ - INT32 ret; - UINT8 *ptr; - UINT8 *args; - - ptr = tSLInformation.pucTxCommandBuffer; - args = (UINT8 *)(ptr + HEADERS_SIZE_CMD); - - // Fill in HCI packet structure - args = UINT32_TO_STREAM(args, ulIndex); - ret = EFAIL; - - // Initiate a HCI command - hci_command_send(HCI_CMND_WLAN_IOCTL_DEL_PROFILE, - ptr, WLAN_DEL_PROFILE_PARAMS_LEN); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_CMND_WLAN_IOCTL_DEL_PROFILE, &ret); - - return(ret); -} - -//***************************************************************************** -// -//! wlan_ioctl_get_scan_results -//! -//! @param[in] scan_timeout parameter not supported -//! @param[out] ucResults scan results (_wlan_full_scan_results_args_t) -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Gets entry from scan result table. -//! The scan results are returned one by one, and each entry -//! represents a single AP found in the area. The following is a -//! format of the scan result: -//! - 4 Bytes: number of networks found -//! - 4 Bytes: The status of the scan: 0 - aged results, -//! 1 - results valid, 2 - no results -//! - 42 bytes: Result entry, where the bytes are arranged as follows: -//! -//! - 1 bit isValid - is result valid or not -//! - 7 bits rssi - RSSI value; -//! - 2 bits: securityMode - security mode of the AP: -//! 0 - Open, 1 - WEP, 2 WPA, 3 WPA2 -//! - 6 bits: SSID name length -//! - 2 bytes: the time at which the entry has entered into -//! scans result table -//! - 32 bytes: SSID name -//! - 6 bytes: BSSID -//! -//! @Note scan_timeout, is not supported on this version. -//! -//! @sa wlan_ioctl_set_scan_params -// -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -INT32 wlan_ioctl_get_scan_results(UINT32 ulScanTimeout, - UINT8 *ucResults) -{ - UINT8 *ptr; - UINT8 *args; - - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in temporary command buffer - args = UINT32_TO_STREAM(args, ulScanTimeout); - - // Initiate a HCI command - hci_command_send(HCI_CMND_WLAN_IOCTL_GET_SCAN_RESULTS, - ptr, WLAN_GET_SCAN_RESULTS_PARAMS_LEN); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_CMND_WLAN_IOCTL_GET_SCAN_RESULTS, ucResults); - - return(0); -} -#endif - -//***************************************************************************** -// -//! wlan_ioctl_set_scan_params -//! -//! @param uiEnable - start/stop application scan: -//! 1 = start scan with default interval value of 10 min. -//! in order to set a different scan interval value apply the value -//! in milliseconds. minimum 1 second. 0=stop). Wlan reset -//! (wlan_stop() wlan_start()) is needed when changing scan interval -//! value. Saved: No -//! @param uiMinDwellTime minimum dwell time value to be used for each -//! channel, in milliseconds. Saved: yes -//! Recommended Value: 100 (Default: 20) -//! @param uiMaxDwellTime maximum dwell time value to be used for each -//! channel, in milliseconds. Saved: yes -//! Recommended Value: 100 (Default: 30) -//! @param uiNumOfProbeRequests max probe request between dwell time. -//! Saved: yes. Recommended Value: 5 (Default:2) -//! @param uiChannelMask bitwise, up to 13 channels (0x1fff). -//! Saved: yes. Default: 0x7ff -//! @param uiRSSIThreshold RSSI threshold. Saved: yes (Default: -80) -//! @param uiSNRThreshold NSR threshold. Saved: yes (Default: 0) -//! @param uiDefaultTxPower probe Tx power. Saved: yes (Default: 205) -//! @param aiIntervalList pointer to array with 16 entries (16 channels) -//! each entry (UINT32) holds timeout between periodic scan -//! (connection scan) - in millisecond. Saved: yes. Default 2000ms. -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief start and stop scan procedure. Set scan parameters. -//! -//! @Note uiDefaultTxPower, is not supported on this version. -//! -//! @sa wlan_ioctl_get_scan_results -// -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -INT32 wlan_ioctl_set_scan_params(UINT32 uiEnable, UINT32 uiMinDwellTime, - UINT32 uiMaxDwellTime, - UINT32 uiNumOfProbeRequests, - UINT32 uiChannelMask,INT32 iRSSIThreshold, - UINT32 uiSNRThreshold, - UINT32 uiDefaultTxPower, - UINT32 *aiIntervalList) -{ - UINT32 uiRes; - UINT8 *ptr; - UINT8 *args; - - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - // Fill in temporary command buffer - args = UINT32_TO_STREAM(args, 36); - args = UINT32_TO_STREAM(args, uiEnable); - args = UINT32_TO_STREAM(args, uiMinDwellTime); - args = UINT32_TO_STREAM(args, uiMaxDwellTime); - args = UINT32_TO_STREAM(args, uiNumOfProbeRequests); - args = UINT32_TO_STREAM(args, uiChannelMask); - args = UINT32_TO_STREAM(args, iRSSIThreshold); - args = UINT32_TO_STREAM(args, uiSNRThreshold); - args = UINT32_TO_STREAM(args, uiDefaultTxPower); - ARRAY_TO_STREAM(args, aiIntervalList, sizeof(UINT32) * - SL_SET_SCAN_PARAMS_INTERVAL_LIST_SIZE); - - // Initiate a HCI command - hci_command_send(HCI_CMND_WLAN_IOCTL_SET_SCANPARAM, - ptr, WLAN_SET_SCAN_PARAMS_LEN); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_CMND_WLAN_IOCTL_SET_SCANPARAM, &uiRes); - - return(uiRes); -} -#endif - -//***************************************************************************** -// -//! wlan_set_event_mask -//! -//! @param mask mask option: -//! HCI_EVNT_WLAN_UNSOL_CONNECT connect event -//! HCI_EVNT_WLAN_UNSOL_DISCONNECT disconnect event -//! HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE smart config done -//! HCI_EVNT_WLAN_UNSOL_INIT init done -//! HCI_EVNT_WLAN_UNSOL_DHCP dhcp event report -//! HCI_EVNT_WLAN_ASYNC_PING_REPORT ping report -//! HCI_EVNT_WLAN_KEEPALIVE keepalive -//! HCI_EVNT_WLAN_TX_COMPLETE - disable information on end of transmission -//! Saved: no. -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Mask event according to bit mask. In case that event is -//! masked (1), the device will not send the masked event to host. -// -//***************************************************************************** - -INT32 wlan_set_event_mask(UINT32 ulMask) -{ - INT32 ret; - UINT8 *ptr; - UINT8 *args; - - - if ((ulMask & HCI_EVNT_WLAN_TX_COMPLETE) == HCI_EVNT_WLAN_TX_COMPLETE) - { - tSLInformation.InformHostOnTxComplete = 0; - - // Since an event is a virtual event - i.e. it is not coming from CC3000 - // there is no need to send anything to the device if it was an only event - if (ulMask == HCI_EVNT_WLAN_TX_COMPLETE) - { - return 0; - } - - ulMask &= ~HCI_EVNT_WLAN_TX_COMPLETE; - ulMask |= HCI_EVNT_WLAN_UNSOL_BASE; - } - else - { - tSLInformation.InformHostOnTxComplete = 1; - } - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (UINT8 *)(ptr + HEADERS_SIZE_CMD); - - // Fill in HCI packet structure - args = UINT32_TO_STREAM(args, ulMask); - - // Initiate a HCI command - hci_command_send(HCI_CMND_EVENT_MASK, - ptr, WLAN_SET_MASK_PARAMS_LEN); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_CMND_EVENT_MASK, &ret); - - return(ret); -} - -//***************************************************************************** -// -//! wlan_ioctl_statusget -//! -//! @param none -//! -//! @return WLAN_STATUS_DISCONNECTED, WLAN_STATUS_SCANING, -//! STATUS_CONNECTING or WLAN_STATUS_CONNECTED -//! -//! @brief get wlan status: disconnected, scanning, connecting or connected -// -//***************************************************************************** - -#ifndef CC3000_TINY_DRIVER -INT32 wlan_ioctl_statusget(void) -{ - INT32 ret; - UINT8 *ptr; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - - hci_command_send(HCI_CMND_WLAN_IOCTL_STATUSGET, - ptr, 0); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_CMND_WLAN_IOCTL_STATUSGET, &ret); - - return(ret); -} -#endif - -//***************************************************************************** -// -//! wlan_smart_config_start -//! -//! @param algoEncryptedFlag indicates whether the information is encrypted -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Start to acquire device profile. The device acquire its own -//! profile, if profile message is found. The acquired AP information -//! is stored in CC3000 EEPROM only in case AES128 encryption is used. -//! In case AES128 encryption is not used, a profile is created by -//! CC3000 internally. -//! -//! @Note An asynchronous event - Smart Config Done will be generated as soon -//! as the process finishes successfully. -//! -//! @sa wlan_smart_config_set_prefix , wlan_smart_config_stop -// -//***************************************************************************** - -INT32 wlan_smart_config_start(UINT32 algoEncryptedFlag) -{ - INT32 ret; - UINT8 *ptr; - UINT8 *args; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (UINT8 *)(ptr + HEADERS_SIZE_CMD); - - // Fill in HCI packet structure - args = UINT32_TO_STREAM(args, algoEncryptedFlag); - ret = EFAIL; - - hci_command_send(HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_START, ptr, - WLAN_SMART_CONFIG_START_PARAMS_LEN); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_START, &ret); - - return(ret); -} - -//***************************************************************************** -// -//! wlan_smart_config_stop -//! -//! @param algoEncryptedFlag indicates whether the information is encrypted -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Stop the acquire profile procedure -//! -//! @sa wlan_smart_config_start , wlan_smart_config_set_prefix -// -//***************************************************************************** - -INT32 wlan_smart_config_stop(void) -{ - INT32 ret; - UINT8 *ptr; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - - hci_command_send(HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_STOP, ptr, 0); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_STOP, &ret); - - return(ret); -} - -//***************************************************************************** -// -//! wlan_smart_config_set_prefix -//! -//! @param newPrefix 3 bytes identify the SSID prefix for the Smart Config. -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief Configure station ssid prefix. The prefix is used internally -//! in CC3000. It should always be TTT. -//! -//! @Note The prefix is stored in CC3000 NVMEM -//! -//! @sa wlan_smart_config_start , wlan_smart_config_stop -// -//***************************************************************************** - -INT32 wlan_smart_config_set_prefix(CHAR* cNewPrefix) -{ - INT32 ret; - UINT8 *ptr; - UINT8 *args; - - ret = EFAIL; - ptr = tSLInformation.pucTxCommandBuffer; - args = (ptr + HEADERS_SIZE_CMD); - - if (cNewPrefix == NULL) - return ret; - else // with the new Smart Config, prefix must be TTT - { - *cNewPrefix = 'T'; - *(cNewPrefix + 1) = 'T'; - *(cNewPrefix + 2) = 'T'; - } - - ARRAY_TO_STREAM(args, cNewPrefix, SL_SIMPLE_CONFIG_PREFIX_LENGTH); - - hci_command_send(HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_SET_PREFIX, ptr, - SL_SIMPLE_CONFIG_PREFIX_LENGTH); - - // Wait for command complete event - SimpleLinkWaitEvent(HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_SET_PREFIX, &ret); - - return(ret); -} - -//***************************************************************************** -// -//! wlan_smart_config_process -//! -//! @param none -//! -//! @return On success, zero is returned. On error, -1 is returned -//! -//! @brief process the acquired data and store it as a profile. The acquired -//! AP information is stored in CC3000 EEPROM encrypted. -//! The encrypted data is decrypted and stored as a profile. -//! behavior is as defined by connection policy. -// -//***************************************************************************** - - -#ifndef CC3000_UNENCRYPTED_SMART_CONFIG -INT32 wlan_smart_config_process() -{ - INT32 returnValue; - UINT32 ssidLen, keyLen; - UINT8 *decKeyPtr; - UINT8 *ssidPtr; - - // read the key from EEPROM - fileID 12 - returnValue = aes_read_key(key); - - if (returnValue != 0) - return returnValue; - - // read the received data from fileID #13 and parse it according to the followings: - // 1) SSID LEN - not encrypted - // 2) SSID - not encrypted - // 3) KEY LEN - not encrypted. always 32 bytes long - // 4) Security type - not encrypted - // 5) KEY - encrypted together with true key length as the first byte in KEY - // to elaborate, there are two corner cases: - // 1) the KEY is 32 bytes long. In this case, the first byte does not represent KEY length - // 2) the KEY is 31 bytes long. In this case, the first byte represent KEY length and equals 31 - returnValue = nvmem_read(NVMEM_SHARED_MEM_FILEID, SMART_CONFIG_PROFILE_SIZE, 0, profileArray); - - if (returnValue != 0) - return returnValue; - - ssidPtr = &profileArray[1]; - - ssidLen = profileArray[0]; - - decKeyPtr = &profileArray[profileArray[0] + 3]; - - aes_decrypt(decKeyPtr, key); - if (profileArray[profileArray[0] + 1] > 16) - aes_decrypt((UINT8 *)(decKeyPtr + 16), key); - - if (*(UINT8 *)(decKeyPtr +31) != 0) - { - if (*decKeyPtr == 31) - { - keyLen = 31; - decKeyPtr++; - } - else - { - keyLen = 32; - } - } - else - { - keyLen = *decKeyPtr; - decKeyPtr++; - } - - // add a profile - switch (profileArray[profileArray[0] + 2]) - { - case WLAN_SEC_UNSEC://None - { - returnValue = wlan_add_profile(profileArray[profileArray[0] + 2], // security type - ssidPtr, // SSID - ssidLen, // SSID length - NULL, // BSSID - 1, // Priority - 0, 0, 0, 0, 0); - - break; - } - - case WLAN_SEC_WEP://WEP - { - returnValue = wlan_add_profile(profileArray[profileArray[0] + 2], // security type - ssidPtr, // SSID - ssidLen, // SSID length - NULL, // BSSID - 1, // Priority - keyLen, // KEY length - 0, // KEY index - 0, - decKeyPtr, // KEY - 0); - - break; - } - - case WLAN_SEC_WPA://WPA - case WLAN_SEC_WPA2://WPA2 - { - returnValue = wlan_add_profile(WLAN_SEC_WPA2, // security type - ssidPtr, - ssidLen, - NULL, // BSSID - 1, // Priority - 0x18, // PairwiseCipher - 0x1e, // GroupCipher - 2, // KEY management - decKeyPtr, // KEY - keyLen); // KEY length - - break; - } - } - - return returnValue; -} -#endif //CC3000_UNENCRYPTED_SMART_CONFIG - -//***************************************************************************** -// -// Close the Doxygen group. -//! @} -// -//***************************************************************************** diff --git a/drivers/cc3100/inc/device.h b/drivers/cc3100/inc/device.h deleted file mode 100644 index 169736da21..0000000000 --- a/drivers/cc3100/inc/device.h +++ /dev/null @@ -1,656 +0,0 @@ -/* - * device.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" - -#ifndef __DEVICE_H__ -#define __DEVICE_H__ - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -/*! - - \addtogroup device - @{ - -*/ - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ - - -/* SL internal Error codes */ - -/* Receive this error in case there are no resources to issue the command - If possible, increase the number of MAX_CUNCURENT_ACTIONS (result in memory increase) - If not, try again later */ -#define SL_POOL_IS_EMPTY (-2000) - -/* Receive this error in case a given length for RX buffer was too small. - Receive payload was bigger than the given buffer size. Therefore, payload is cut according to receive size - Recommend to increase buffer size */ -#define SL_ESMALLBUF (-2001) - -/* Receive this error in case zero length is supplied to a "get" API - Recommend to supply length according to requested information (view options defines for help) */ -#define SL_EZEROLEN (-2002) - -/* User supplied invalid parameter */ -#define SL_INVALPARAM (-2003) - - -/* Failed to open interface */ -#define SL_BAD_INTERFACE (-2004) - -/* End of SL internal Error codes */ - - - -/*****************************************************************************/ -/* Errors returned from the general error async event */ -/*****************************************************************************/ - -/* Send types */ -typedef enum -{ - SL_ERR_SENDER_HEALTH_MON, - SL_ERR_SENDER_CLI_UART, - SL_ERR_SENDER_SUPPLICANT, - SL_ERR_SENDER_NETWORK_STACK, - SL_ERR_SENDER_WLAN_DRV_IF, - SL_ERR_SENDER_WILINK, - SL_ERR_SENDER_INIT_APP, - SL_ERR_SENDER_NETX, - SL_ERR_SENDER_HOST_APD, - SL_ERR_SENDER_MDNS, - SL_ERR_SENDER_HTTP_SERVER, - SL_ERR_SENDER_DHCP_SERVER, - SL_ERR_SENDER_DHCP_CLIENT, - SL_ERR_DISPATCHER, - SL_ERR_NUM_SENDER_LAST=0xFF -}SlErrorSender_e; - - -/* Error codes */ -#define SL_ERROR_STATIC_ADDR_SUBNET_ERROR (-60) /* network stack error*/ -#define SL_ERROR_ILLEGAL_CHANNEL (-61) /* supplicant error */ -#define SL_ERROR_SUPPLICANT_ERROR (-72) /* init error code */ -#define SL_ERROR_HOSTAPD_INIT_FAIL (-73) /* init error code */ -#define SL_ERROR_HOSTAPD_INIT_IF_FAIL (-74) /* init error code */ -#define SL_ERROR_WLAN_DRV_INIT_FAIL (-75) /* init error code */ -#define SL_ERROR_WLAN_DRV_START_FAIL (-76) /* wlan start error */ -#define SL_ERROR_FS_FILE_TABLE_LOAD_FAILED (-77) /* init file system failed */ -#define SL_ERROR_PREFERRED_NETWORKS_FILE_LOAD_FAILED (-78) /* init file system failed */ -#define SL_ERROR_HOSTAPD_BSSID_VALIDATION_ERROR (-79) /* Ap configurations BSSID error */ -#define SL_ERROR_HOSTAPD_FAILED_TO_SETUP_INTERFACE (-80) /* Ap configurations interface error */ -#define SL_ERROR_MDNS_ENABLE_FAIL (-81) /* mDNS enable failed */ -#define SL_ERROR_HTTP_SERVER_ENABLE_FAILED (-82) /* HTTP server enable failed */ -#define SL_ERROR_DHCP_SERVER_ENABLE_FAILED (-83) /* DHCP server enable failed */ -#define SL_ERROR_PREFERRED_NETWORK_LIST_FULL (-93) /* supplicant error */ -#define SL_ERROR_PREFERRED_NETWORKS_FILE_WRITE_FAILED (-94) /* supplicant error */ -#define SL_ERROR_DHCP_CLIENT_RENEW_FAILED (-100) /* DHCP client error */ -/* WLAN Connection management status */ -#define SL_ERROR_CON_MGMT_STATUS_UNSPECIFIED (-102) -#define SL_ERROR_CON_MGMT_STATUS_AUTH_REJECT (-103) -#define SL_ERROR_CON_MGMT_STATUS_ASSOC_REJECT (-104) -#define SL_ERROR_CON_MGMT_STATUS_SECURITY_FAILURE (-105) -#define SL_ERROR_CON_MGMT_STATUS_AP_DEAUTHENTICATE (-106) -#define SL_ERROR_CON_MGMT_STATUS_AP_DISASSOCIATE (-107) -#define SL_ERROR_CON_MGMT_STATUS_ROAMING_TRIGGER (-108) -#define SL_ERROR_CON_MGMT_STATUS_DISCONNECT_DURING_CONNECT (-109) -#define SL_ERROR_CON_MGMT_STATUS_SG_RESELECT (-110) -#define SL_ERROR_CON_MGMT_STATUS_ROC_FAILURE (-111) -#define SL_ERROR_CON_MGMT_STATUS_MIC_FAILURE (-112) -/* end of WLAN connection management error statuses */ -#define SL_ERROR_WAKELOCK_ERROR_PREFIX (-115) /* Wake lock expired */ -#define SL_ERROR_LENGTH_ERROR_PREFIX (-116) /* Uart header length error */ -#define SL_ERROR_MDNS_CREATE_FAIL (-121) /* mDNS create failed */ -#define SL_ERROR_GENERAL_ERROR (-127) - - - -#define SL_DEVICE_GENERAL_CONFIGURATION (1) -#define SL_DEVICE_GENERAL_CONFIGURATION_DATE_TIME (11) -#define SL_DEVICE_GENERAL_VERSION (12) -#define SL_DEVICE_STATUS (2) - -/* - Declare the different event group classifications - The SimpleLink device send asynchronous events. Each event has a group - classification according to its nature. -*/ -/* SL_EVENT_CLASS_WLAN connection user events */ -#define SL_WLAN_CONNECT_EVENT (1) -#define SL_WLAN_DISCONNECT_EVENT (2) -/* WLAN Smart Config user events */ -#define SL_WLAN_SMART_CONFIG_COMPLETE_EVENT (3) -#define SL_WLAN_SMART_CONFIG_STOP_EVENT (4) -/* WLAN AP user events */ -#define SL_WLAN_STA_CONNECTED_EVENT (5) -#define SL_WLAN_STA_DISCONNECTED_EVENT (6) -/* WLAN P2P user events */ -#define SL_WLAN_P2P_DEV_FOUND_EVENT (7) -#define SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT (8) -#define SL_WLAN_CONNECTION_FAILED_EVENT (9) -/* SL_EVENT_CLASS_DEVICE user events */ -#define SL_DEVICE_FATAL_ERROR_EVENT (1) -#define SL_DEVICE_ABORT_ERROR_EVENT (2) - -/* SL_EVENT_CLASS_BSD user events */ -#define SL_SOCKET_TX_FAILED_EVENT (1) -#define SL_SOCKET_ASYNC_EVENT (2) -/* SL_EVENT_CLASS_NETAPP user events */ -#define SL_NETAPP_IPV4_IPACQUIRED_EVENT (1) -#define SL_NETAPP_IPV6_IPACQUIRED_EVENT (2) -#define SL_NETAPP_IP_LEASED_EVENT (3) -#define SL_NETAPP_IP_RELEASED_EVENT (4) - -/* Server Events */ -#define SL_NETAPP_HTTPGETTOKENVALUE_EVENT (1) -#define SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT (2) - - -/* - Declare the different event group classifications for sl_DevGet - for getting status indications - */ - -/* Events list to mask/unmask*/ -#define SL_EVENT_CLASS_GLOBAL (0) -#define SL_EVENT_CLASS_DEVICE (1) -#define SL_EVENT_CLASS_WLAN (2) -#define SL_EVENT_CLASS_BSD (3) -#define SL_EVENT_CLASS_NETAPP (4) -#define SL_EVENT_CLASS_NETCFG (5) -#define SL_EVENT_CLASS_FS (6) - - -/****************** DEVICE CLASS status ****************/ -#define EVENT_DROPPED_DEVICE_ASYNC_GENERAL_ERROR (0x00000001L) -#define STATUS_DEVICE_SMART_CONFIG_ACTIVE (0x80000000L) - -/****************** WLAN CLASS status ****************/ -#define EVENT_DROPPED_WLAN_WLANASYNCONNECTEDRESPONSE (0x00000001L) -#define EVENT_DROPPED_WLAN_WLANASYNCDISCONNECTEDRESPONSE (0x00000002L) -#define EVENT_DROPPED_WLAN_STA_CONNECTED (0x00000004L) -#define EVENT_DROPPED_WLAN_STA_DISCONNECTED (0x00000008L) -#define STATUS_WLAN_STA_CONNECTED (0x80000000L) - -/****************** NETAPP CLASS status ****************/ -#define EVENT_DROPPED_NETAPP_IPACQUIRED (0x00000001L) -#define EVENT_DROPPED_NETAPP_IPACQUIRED_V6 (0x00000002L) -#define EVENT_DROPPED_NETAPP_IP_LEASED (0x00000004L) -#define EVENT_DROPPED_NETAPP_IP_RELEASED (0x00000008L) - -/****************** BSD CLASS status ****************/ -#define EVENT_DROPPED_SOCKET_TXFAILEDASYNCRESPONSE (0x00000001L) - -/****************** FS CLASS ****************/ - - - -/*****************************************************************************/ -/* Structure/Enum declarations */ -/*****************************************************************************/ - -#define ROLE_UNKNOWN_ERR (-1) - -#ifdef SL_IF_TYPE_UART -typedef struct -{ - _u32 BaudRate; - _u8 FlowControlEnable; - _u8 CommPort; -} SlUartIfParams_t; -#endif - -typedef struct -{ - _u32 ChipId; - _u32 FwVersion[4]; - _u8 PhyVersion[4]; -}_SlPartialVersion; - -typedef struct -{ - _SlPartialVersion ChipFwAndPhyVersion; - _u32 NwpVersion[4]; - _u16 RomVersion; - _u16 Padding; -}SlVersionFull; - - -typedef struct -{ - _u32 AbortType; - _u32 AbortData; -}sl_DeviceReportAbort; - - -typedef struct -{ - _i8 status; - SlErrorSender_e sender; -}sl_DeviceReport; - -typedef union -{ - sl_DeviceReport deviceEvent; - sl_DeviceReportAbort deviceReport; -} _SlDeviceEventData_u; - -typedef struct -{ - _u32 Event; - _SlDeviceEventData_u EventData; -} SlDeviceEvent_t; - -typedef struct -{ - /* time */ - _u32 sl_tm_sec; - _u32 sl_tm_min; - _u32 sl_tm_hour; - /* date */ - _u32 sl_tm_day; /* 1-31 */ - _u32 sl_tm_mon; /* 1-12 */ - _u32 sl_tm_year; /* YYYY 4 digits */ - _u32 sl_tm_week_day; /* not required */ - _u32 sl_tm_year_day; /* not required */ - _u32 reserved[3]; -}SlDateTime_t; - - -/******************************************************************************/ -/* Type declarations */ -/******************************************************************************/ -typedef void (*P_INIT_CALLBACK)(_u32 Status); - -/*****************************************************************************/ -/* Function prototypes */ -/*****************************************************************************/ - -/*! - \brief Start the SimpleLink device - - This function initialize the communication interface, set the enable pin - of the device, and call to the init complete callback. - - \param[in] pIfHdl Opened Interface Object. In case the interface - must be opened outside the SimpleLink Driver, the - user might give the handler to be used in \n - any access of the communication interface with the - device (UART/SPI). \n - The SimpleLink driver will open an interface port - only if this parameter is null! \n - \param[in] pDevName The name of the device to open. Could be used when - the pIfHdl is null, to transfer information to the - open interface function \n - This pointer could be used to pass additional information to - sl_IfOpen in case it is required (e.g. UART com port name) - \param[in] pInitCallBack Pointer to function that would be called - on completion of the initialization process.\n - If this parameter is NULL the function is - blocked until the device initialization - is completed, otherwise the function returns - immediately. - - \return Returns the current active role (STA/AP/P2P) or an error code: - - ROLE_STA, ROLE_AP, ROLE_P2P in case of success, - otherwise in failure one of the following is return: - - ROLE_STA_ERR (Failure to load MAC/PHY in STA role) - - ROLE_AP_ERR (Failure to load MAC/PHY in AP role) - - ROLE_P2P_ERR (Failure to load MAC/PHY in P2P role) - - - \sa sl_Stop - - \note belongs to \ref basic_api - - \warning This function must be called before any other SimpleLink API is used, or after sl_Stop is called for reinit the device - \par Example: - \code - An example for open interface without callback routine. The interface name and handler are - handled by the sl_IfOpen routine: - - if( sl_Start(NULL, NULL, NULL) < 0 ) - { - LOG("Error opening interface to device\n"); - } - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_Start) -_i16 sl_Start(const void* pIfHdl, _i8* pDevName, const P_INIT_CALLBACK pInitCallBack); -#endif - -/*! - \brief Stop the SimpleLink device - - This function clears the enable pin of the device, closes the communication \n - interface and invokes the stop complete callback - - \param[in] timeout Stop timeout in msec. Should be used to give the device time to finish \n - any transmission/reception that is not completed when the function was called. \n - Additional options: - - 0 Enter to hibernate immediately \n - - 0xFFFF Host waits for device's response before \n - hibernating, without timeout protection \n - - 0 < Timeout[msec] < 0xFFFF Host waits for device's response before \n - hibernating, with a defined timeout protection \n - This timeout defines the max time to wait. The NWP \n - response can be sent earlier than this timeout. - - \return On success, zero is returned. On error, -1 is returned - - \sa sl_Start - - \note This API will shutdown the device and invoke the "i/f close" function regardless \n - if it was opened implicitly or explicitly. \n - It is up to the platform interface library to properly handle interface close \n - routine \n - belongs to \ref basic_api \n - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_Stop) -_i16 sl_Stop(const _u16 timeout); -#endif - - -/*! - \brief Internal function for setting device configurations - - \return On success, zero is returned. On error, -1 is - returned - - \param[in] DeviceSetId configuration id - \param[in] Option configurations option - \param[in] ConfigLen configurations len - \param[in] pValues configurations values - - \sa - \note - \warning - \par Examples: - \code - Setting device time and date example: - - SlDateTime_t dateTime= {0}; - dateTime.sl_tm_day = (_u32)23; // Day of month (DD format) range 1-31 - dateTime.sl_tm_mon = (_u32)6; // Month (MM format) in the range of 1-12 - dateTime.sl_tm_year = (_u32)2014; // Year (YYYY format) - dateTime.sl_tm_hour = (_u32)17; // Hours in the range of 0-23 - dateTime.sl_tm_min = (_u32)55; // Minutes in the range of 0-59 - dateTime.sl_tm_sec = (_u32)22; // Seconds in the range of 0-59 - sl_DevSet(SL_DEVICE_GENERAL_CONFIGURATION, - SL_DEVICE_GENERAL_CONFIGURATION_DATE_TIME, - sizeof(SlDateTime_t), - (_u8 *)(&dateTime)); - - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_DevSet) -_i32 sl_DevSet(const _u8 DeviceSetId ,const _u8 Option,const _u8 ConfigLen,const _u8 *pValues); -#endif - -/*! - \brief Internal function for getting device configurations - \return On success, zero is returned. On error, -1 is - returned - \param[in] DeviceGetId configuration id - example SL_DEVICE_STATUS - \param[out] pOption Get configurations option, example for get status options - - SL_EVENT_CLASS_GLOBAL - - SL_EVENT_CLASS_DEVICE - - SL_EVENT_CLASS_WLAN - - SL_EVENT_CLASS_BSD - - SL_EVENT_CLASS_NETAPP - - SL_EVENT_CLASS_NETCFG - - SL_EVENT_CLASS_FS - \param[out] pConfigLen The length of the allocated memory as input, when the - function complete, the value of this parameter would be - the len that actually read from the device.\n - If the device return length that is longer from the input - value, the function will cut the end of the returned structure - and will return SL_ESMALLBUF - \param[out] pValues Get configurations values - \sa - \note - \warning - \par Examples: - \code - Example for getting WLAN class status: - _u32 statusWlan; - _u8 pConfigOpt; - _u8 pConfigLen; - pConfigOpt = SL_EVENT_CLASS_WLAN; - pConfigLen = sizeof(_u32); - sl_DevGet(SL_DEVICE_STATUS,&pConfigOpt,&pConfigLen,(_u8 *)(&statusWlan)); - Example for getting version: - SlVersionFull ver; - pConfigLen = sizeof(ver); - pConfigOpt = SL_DEVICE_GENERAL_VERSION; - sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION,&pConfigOpt,&pConfigLen,(_u8 *)(&ver)); - printf("CHIP %d\nMAC 31.%d.%d.%d.%d\nPHY %d.%d.%d.%d\nNWP %d.%d.%d.%d\nROM %d\nHOST %d.%d.%d.%d\n", - ver.ChipFwAndPhyVersion.ChipId, - ver.ChipFwAndPhyVersion.FwVersion[0],ver.ChipFwAndPhyVersion.FwVersion[1], - ver.ChipFwAndPhyVersion.FwVersion[2],ver.ChipFwAndPhyVersion.FwVersion[3], - ver.ChipFwAndPhyVersion.PhyVersion[0],ver.ChipFwAndPhyVersion.PhyVersion[1], - ver.ChipFwAndPhyVersion.PhyVersion[2],ver.ChipFwAndPhyVersion.PhyVersion[3], - ver.NwpVersion[0],ver.NwpVersion[1],ver.NwpVersion[2],ver.NwpVersion[3], - ver.RomVersion, - SL_MAJOR_VERSION_NUM,SL_MINOR_VERSION_NUM,SL_VERSION_NUM,SL_SUB_VERSION_NUM); - - \endcode - \code - Getting Device time and date example: - - SlDateTime_t dateTime = {0}; - _i8 configLen = sizeof(SlDateTime_t); - _i8 configOpt = SL_DEVICE_GENERAL_CONFIGURATION_DATE_TIME; - sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION,&configOpt, &configLen,(_u8 *)(&dateTime)); - - printf("Day %d,Mon %d,Year %d,Hour %,Min %d,Sec %d\n",dateTime.sl_tm_day,dateTime.sl_tm_mon,dateTime.sl_tm_year - dateTime.sl_tm_hour,dateTime.sl_tm_min,dateTime.sl_tm_sec); - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_DevGet) -_i32 sl_DevGet(const _u8 DeviceGetId,_u8 *pOption,_u8 *pConfigLen, _u8 *pValues); -#endif - - -/*! - \brief Set asynchronous event mask - - Mask asynchronous events from the device. Masked events do not - generate asynchronous messages from the device. - By default - all events are active - - \param[in] EventClass The classification groups that the - mask is referred to. Need to be one of - the following: - - SL_EVENT_CLASS_GLOBAL - - SL_EVENT_CLASS_DEVICE - - SL_EVENT_CLASS_WLAN - - SL_EVENT_CLASS_BSD - - SL_EVENT_CLASS_NETAPP - - SL_EVENT_CLASS_NETCFG - - SL_EVENT_CLASS_FS - - - \param[in] Mask Event Mask bitmap. Valid mask are (per group): - - SL_EVENT_CLASS_WLAN user events - - SL_WLAN_CONNECT_EVENT - - SL_WLAN_DISCONNECT_EVENT - - SL_EVENT_CLASS_DEVICE user events - - SL_DEVICE_FATAL_ERROR_EVENT - - SL_EVENT_CLASS_BSD user events - - SL_SOCKET_TX_FAILED_EVENT - - SL_SOCKET_ASYNC_EVENT - - SL_EVENT_CLASS_NETAPP user events - - SL_NETAPP_IPV4_IPACQUIRED_EVENT - - SL_NETAPP_IPV6_IPACQUIRED_EVENT - - \return On success, zero is returned. On error, -1 is returned - - \sa sl_EventMaskGet - - \note belongs to \ref ext_api - - \warning - \par Example: - \code - - An example of masking connection/disconnection async events from WLAN class: - sl_EventMaskSet(SL_EVENT_CLASS_WLAN, (SL_WLAN_CONNECT_EVENT | SL_WLAN_DISCONNECT_EVENT) ); - - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_EventMaskSet) -_i16 sl_EventMaskSet(const _u8 EventClass ,const _u32 Mask); -#endif - -/*! - \brief Get current event mask of the device - - return the events bit mask from the device. In case that event is - masked, the device is not sending this event. - - \param[in] EventClass The classification groups that the - mask is referred to. Need to be one of - the following: - - SL_EVENT_CLASS_GLOBAL - - SL_EVENT_CLASS_DEVICE - - SL_EVENT_CLASS_WLAN - - SL_EVENT_CLASS_BSD - - SL_EVENT_CLASS_NETAPP - - SL_EVENT_CLASS_NETCFG - - SL_EVENT_CLASS_FS - - \param[out] pMask Pointer to Mask bitmap where the - value should be stored. Bitmasks are the same as in \ref sl_EventMaskSet - - \return On success, zero is returned. On error, -1 is returned - - \sa sl_EventMaskSet - - \note belongs to \ref ext_api - - \warning - \par Example: - \code - - An example of getting an event mask for WLAN class - _u32 maskWlan; - sl_StatusGet(SL_EVENT_CLASS_WLAN,&maskWlan); - - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_EventMaskGet) -_i16 sl_EventMaskGet(const _u8 EventClass,_u32 *pMask); -#endif - - -/*! - \brief the simple link task entry - - \Param - This function must be called from the main loop or from dedicated thread in - the following cases: - - Non-Os Platform - should be called from the mail loop - - Multi Threaded Platform when the user does not implement the external spawn functions - - should be called from dedicated thread allocated to the simplelink driver. - In this mode the function never return. - - \return None - - \sa sl_Stop - - \note belongs to \ref basic_api - - \warning This function must be called from a thread that is start running before - any call to other simple link API -*/ -#if _SL_INCLUDE_FUNC(sl_Task) -void sl_Task(void); -#endif - - -/*! - \brief Setting the internal uart mode - - \param[in] pUartParams Pointer to the uart configuration parameter set: - baudrate - up to 711 Kbps - flow control - enable/disable - comm port - the comm port number - - \return On success zero is returned, otherwise - Failed. - - \sa sl_Stop - - \note belongs to \ref basic_api - - \warning This function must consider the host uart capability -*/ -#ifdef SL_IF_TYPE_UART -#if _SL_INCLUDE_FUNC(sl_UartSetMode) -_i16 sl_UartSetMode(const SlUartIfParams_t* pUartParams); -#endif -#endif - -/*! - - Close the Doxygen group. - @} - - */ - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __DEVICE_H__ */ - - diff --git a/drivers/cc3100/inc/driver.h b/drivers/cc3100/inc/driver.h deleted file mode 100644 index 4ef484dfb5..0000000000 --- a/drivers/cc3100/inc/driver.h +++ /dev/null @@ -1,247 +0,0 @@ -/* - * driver.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - -#ifndef __DRIVER_INT_H__ -#define __DRIVER_INT_H__ - - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ - -#ifndef CPU_FREQ_IN_MHZ - #define CPU_FREQ_IN_MHZ (200) -#endif -#define USEC_DELAY (50) - -/*****************************************************************************/ -/* Structure/Enum declarations */ -/*****************************************************************************/ - -typedef struct -{ - _SlOpcode_t Opcode; - _SlArgSize_t TxDescLen; - _SlArgSize_t RxDescLen; -}_SlCmdCtrl_t; - -typedef struct -{ - _u16 TxPayloadLen; - _i16 RxPayloadLen; - _i16 ActualRxPayloadLen; - _u8 *pTxPayload; - _u8 *pRxPayload; -}_SlCmdExt_t; - - -typedef struct _SlArgsData_t -{ - _u8 *pArgs; - _u8 *pData; -} _SlArgsData_t; - - -typedef struct _SlPoolObj_t -{ - _SlSyncObj_t SyncObj; - _u8 *pRespArgs; - _u8 ActionID; - _u8 AdditionalData; /* use for socketID and one bit which indicate supprt IPV6 or not (1=support, 0 otherwise) */ - _u8 NextIndex; - -} _SlPoolObj_t; - - -typedef enum -{ - SOCKET_0, - SOCKET_1, - SOCKET_2, - SOCKET_3, - SOCKET_4, - SOCKET_5, - SOCKET_6, - SOCKET_7, - MAX_SOCKET_ENUM_IDX, -#ifndef SL_TINY_EXT - ACCEPT_ID = MAX_SOCKET_ENUM_IDX, - CONNECT_ID, -#else - CONNECT_ID = MAX_SOCKET_ENUM_IDX, -#endif -#ifndef SL_TINY_EXT - SELECT_ID, -#endif - GETHOSYBYNAME_ID, -#ifndef SL_TINY_EXT - GETHOSYBYSERVICE_ID, - PING_ID, -#endif - START_STOP_ID, - RECV_ID -}_SlActionID_e; - -typedef struct _SlActionLookup_t -{ - _u8 ActionID; - _u16 ActionAsyncOpcode; - _SlSpawnEntryFunc_t AsyncEventHandler; - -} _SlActionLookup_t; - - -typedef struct -{ - _u8 TxPoolCnt; - _SlLockObj_t TxLockObj; - _SlSyncObj_t TxSyncObj; -}_SlFlowContCB_t; - -typedef enum -{ - RECV_RESP_CLASS, - CMD_RESP_CLASS, - ASYNC_EVT_CLASS, - DUMMY_MSG_CLASS -}_SlRxMsgClass_e; - -typedef struct -{ - _u8 *pAsyncBuf; /* place to write pointer to buffer with CmdResp's Header + Arguments */ - _u8 ActionIndex; - _SlSpawnEntryFunc_t AsyncEvtHandler; /* place to write pointer to AsyncEvent handler (calc-ed by Opcode) */ - _SlRxMsgClass_e RxMsgClass; /* type of Rx message */ -} AsyncExt_t; - -typedef _u8 _SlSd_t; - -typedef struct -{ - _SlCmdCtrl_t *pCmdCtrl; - _u8 *pTxRxDescBuff; - _SlCmdExt_t *pCmdExt; - AsyncExt_t AsyncExt; -}_SlFunctionParams_t; - - -typedef struct -{ - _SlFd_t FD; - _SlLockObj_t GlobalLockObj; - _SlCommandHeader_t TempProtocolHeader; - P_INIT_CALLBACK pInitCallback; - - _SlPoolObj_t ObjPool[MAX_CONCURRENT_ACTIONS]; - _u8 FreePoolIdx; - _u8 PendingPoolIdx; - _u8 ActivePoolIdx; - _u32 ActiveActionsBitmap; - _SlLockObj_t ProtectionLockObj; - - _SlSyncObj_t CmdSyncObj; - _u8 IsCmdRespWaited; - _SlFlowContCB_t FlowContCB; - _u8 TxSeqNum; - _u8 RxDoneCnt; - _u8 SocketNonBlocking; - _u8 SocketTXFailure; - /* for stack reduction the parameters are globals */ - _SlFunctionParams_t FunctionParams; - - _u8 ActionIndex; -}_SlDriverCb_t; - -extern _volatile _u8 RxIrqCnt; - -extern _SlDriverCb_t* g_pCB; -extern P_SL_DEV_PING_CALLBACK pPingCallBackFunc; - -/*****************************************************************************/ -/* Function prototypes */ -/*****************************************************************************/ -extern void _SlDrvDriverCBInit(void); -extern void _SlDrvDriverCBDeinit(void); -extern void _SlDrvRxIrqHandler(void *pValue); -extern _SlReturnVal_t _SlDrvCmdOp(_SlCmdCtrl_t *pCmdCtrl , void* pTxRxDescBuff , _SlCmdExt_t* pCmdExt); -extern _SlReturnVal_t _SlDrvCmdSend(_SlCmdCtrl_t *pCmdCtrl , void* pTxRxDescBuff , _SlCmdExt_t* pCmdExt); -extern _SlReturnVal_t _SlDrvDataReadOp(_SlSd_t Sd, _SlCmdCtrl_t *pCmdCtrl , void* pTxRxDescBuff , _SlCmdExt_t* pCmdExt); -extern _SlReturnVal_t _SlDrvDataWriteOp(_SlSd_t Sd, _SlCmdCtrl_t *pCmdCtrl , void* pTxRxDescBuff , _SlCmdExt_t* pCmdExt); -extern void _sl_HandleAsync_InitComplete(void *pVoidBuf); -extern void _sl_HandleAsync_Connect(void *pVoidBuf); - - -#ifndef SL_TINY_EXT -extern _i16 _SlDrvBasicCmd(_SlOpcode_t Opcode); -extern void _sl_HandleAsync_Accept(void *pVoidBuf); -extern void _sl_HandleAsync_DnsGetHostByService(void *pVoidBuf); -extern void _sl_HandleAsync_Select(void *pVoidBuf); -#endif - - -extern void _sl_HandleAsync_DnsGetHostByName(void *pVoidBuf); -extern void _sl_HandleAsync_DnsGetHostByAddr(void *pVoidBuf); -extern void _sl_HandleAsync_PingResponse(void *pVoidBuf); -extern void _SlDrvNetAppEventHandler(void* pArgs); -extern void _SlDrvDeviceEventHandler(void* pArgs); -extern void _sl_HandleAsync_Stop(void *pVoidBuf); -extern _u8 _SlDrvWaitForPoolObj(_u8 ActionID, _u8 SocketID); -extern void _SlDrvReleasePoolObj(_u8 pObj); -extern _u16 _SlDrvAlignSize(_u16 msgLen); -extern _u8 _SlDrvProtectAsyncRespSetting(_u8 *pAsyncRsp, _u8 ActionID, _u8 SocketID); - - -extern void _SlDrvSyncObjWaitForever(_SlSyncObj_t *pSyncObj); -extern void _SlDrvSyncObjSignal(_SlSyncObj_t *pSyncObj); -extern void _SlDrvObjLock(_SlLockObj_t *pLockObj, _SlTime_t Timeout); -extern void _SlDrvObjLockWaitForever(_SlLockObj_t *pLockObj); -extern void _SlDrvProtectionObjLockWaitForever(); -extern void _SlDrvObjUnLock(_SlLockObj_t *pLockObj); -extern void _SlDrvProtectionObjUnLock(); - -extern void _SlDrvMemZero(void* Addr, _u16 size); -extern void _SlDrvResetCmdExt(_SlCmdExt_t* pCmdExt); - - - -#define _SL_PROTOCOL_ALIGN_SIZE(msgLen) (((msgLen)+3) & (~3)) -#define _SL_IS_PROTOCOL_ALIGNED_SIZE(msgLen) (!((msgLen) & 3)) - - -#define _SL_PROTOCOL_CALC_LEN(pCmdCtrl,pCmdExt) ((pCmdExt) ? \ - (_SL_PROTOCOL_ALIGN_SIZE(pCmdCtrl->TxDescLen) + _SL_PROTOCOL_ALIGN_SIZE(pCmdExt->TxPayloadLen)) : \ - (_SL_PROTOCOL_ALIGN_SIZE(pCmdCtrl->TxDescLen))) -#endif /* __DRIVER_INT_H__ */ diff --git a/drivers/cc3100/inc/flowcont.h b/drivers/cc3100/inc/flowcont.h deleted file mode 100644 index 3dcc130d83..0000000000 --- a/drivers/cc3100/inc/flowcont.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * flowcont.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - -#ifndef __FLOWCONT_H__ -#define __FLOWCONT_H__ - - -#ifdef __cplusplus -extern "C" { -#endif - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ -#define FLOW_CONT_MIN 1 - -/*****************************************************************************/ -/* Function prototypes */ -/*****************************************************************************/ -extern void _SlDrvFlowContInit(void); -extern void _SlDrvFlowContDeinit(void); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __FLOWCONT_H__ */ - diff --git a/drivers/cc3100/inc/fs.h b/drivers/cc3100/inc/fs.h deleted file mode 100644 index 078feafff6..0000000000 --- a/drivers/cc3100/inc/fs.h +++ /dev/null @@ -1,382 +0,0 @@ -/* - * fs.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ - -#include "simplelink.h" - -#ifndef __FS_H__ -#define __FS_H__ - - - -#ifdef __cplusplus -extern "C" { -#endif - -/*! - - \addtogroup FileSystem - @{ - -*/ - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ - -/* FS error codes */ -#define SL_FS_OK (0) -#define SL_FS_ERR_EMPTY_SFLASH (-67) -#define SL_FS_ERR_FILE_IS_NOT_SECURE_AND_SIGN (-66) -#define SL_FS_ERASING_FLASH (-65) -#define SL_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY (-64) -#define SL_FS_WRONG_SIGNATURE (-63) -#define SL_FS_WRONG_SIGNATURE_OR_CERTIFIC_NAME_LENGTH (-62) -#define SL_FS_NOT_16_ALIGNED (-61) -#define SL_FS_CERT_CHAIN_ERROR (-60) -#define SL_FS_FILE_NAME_EXIST (-59) -#define SL_FS_SECURITY_BUF_ALREADY_ALLOC (-58) -#define SL_FS_SECURE_FILE_MUST_BE_COMMIT (-57) -#define SL_FS_ERR_INCORRECT_OFFSET_ALIGNMENT (-56) -#define SL_FS_ERR_FAILED_READ_NVMEM_HEADER (-55) -#define SL_FS_WRONG_FILE_NAME (-54) -#define SL_FS_FILE_SYSTEM_IS_LOCKED (-53) -#define SL_FS_SECURITY_ALLERT (-52) -#define SL_FS_FILE_UNVALID_FILE_SIZE (-51) -#define SL_FS_ERR_TOKEN_IS_NOT_VALID (-50) -#define SL_FS_NO_DEVICE_IS_LOADED (-49) -#define SL_FS_DATA_ADDRESS_SHOUD_BE_IN_DATA_RAM (-48) -#define SL_FS_DATA_IS_NOT_ALIGNED (-47) -#define SL_FS_ERR_OVERLAP_DETECTION_THRESHHOLD (-46) -#define SL_FS_FILE_HAS_RESERVED_NV_INDEX (-45) -#define SL_FS_ERR_MAX_FS_FILES_IS_LARGER (-44) -#define SL_FS_ERR_MAX_FS_FILES_IS_SMALLER (-43) -#define SL_FS_FILE_MAX_SIZE_EXCEEDED (-42) -#define SL_FS_INVALID_BUFFER_FOR_READ (-41) -#define SL_FS_INVALID_BUFFER_FOR_WRITE (-40) -#define SL_FS_ERR_FILE_IMAGE_IS_CORRUPTED (-39) -#define SL_FS_ERR_SIZE_OF_FILE_EXT_EXCEEDED (-38) -#define SL_FS_WARNING_FILE_NAME_NOT_KEPT (-37) -#define SL_FS_ERR_DEVICE_IS_NOT_FORMATTED (-36) -#define SL_FS_ERR_FAILED_WRITE_NVMEM_HEADER (-35) -#define SL_FS_ERR_NO_AVAILABLE_NV_INDEX (-34) -#define SL_FS_ERR_FAILED_TO_ALLOCATE_MEM (-33) -#define SL_FS_ERR_FAILED_TO_READ_INTEGRITY_HEADER_2 (-32) -#define SL_FS_ERR_FAILED_TO_READ_INTEGRITY_HEADER_1 (-31) -#define SL_FS_ERR_NO_AVAILABLE_BLOCKS (-30) -#define SL_FS_ERR_FILE_MAX_SIZE_BIGGER_THAN_EXISTING_FILE (-29) -#define SL_FS_ERR_FILE_EXISTS_ON_DIFFERENT_DEVICE_ID (-28) -#define SL_FS_ERR_INVALID_ACCESS_TYPE (-27) -#define SL_FS_ERR_FILE_ALREADY_EXISTS (-26) -#define SL_FS_ERR_PROGRAM (-25) -#define SL_FS_ERR_NO_ENTRIES_AVAILABLE (-24) -#define SL_FS_ERR_FILE_ACCESS_IS_DIFFERENT (-23) -#define SL_FS_ERR_BAD_FILE_MODE (-22) -#define SL_FS_ERR_FAILED_READ_NVFILE (-21) -#define SL_FS_ERR_FAILED_INIT_STORAGE (-20) -#define SL_FS_ERR_CONTINUE_WRITE_MUST_BE_MOD_4 (-19) -#define SL_FS_ERR_FAILED_LOAD_FILE (-18) -#define SL_FS_ERR_INVALID_HANDLE (-17) -#define SL_FS_ERR_FAILED_TO_WRITE (-16) -#define SL_FS_ERR_OFFSET_OUT_OF_RANGE (-15) -#define SL_FS_ERR_ALLOC (-14) -#define SL_FS_ERR_READ_DATA_LENGTH (-13) -#define SL_FS_ERR_INVALID_FILE_ID (-12) -#define SL_FS_ERR_FILE_NOT_EXISTS (-11) -#define SL_FS_ERR_EMPTY_ERROR (-10) -#define SL_FS_ERR_INVALID_ARGS (-9) -#define SL_FS_ERR_FAILED_TO_CREATE_FILE (-8) -#define SL_FS_ERR_FS_ALREADY_LOADED (-7) -#define SL_FS_ERR_UNKNOWN (-6) -#define SL_FS_ERR_FAILED_TO_CREATE_LOCK_OBJ (-5) -#define SL_FS_ERR_DEVICE_NOT_LOADED (-4) -#define SL_FS_ERR_INVALID_MAGIC_NUM (-3) -#define SL_FS_ERR_FAILED_TO_READ (-2) -#define SL_FS_ERR_NOT_SUPPORTED (-1) -/* end of error codes */ - -#define _FS_MODE_ACCESS_RESERVED_OFFSET (24) -#define _FS_MODE_ACCESS_RESERVED_MASK (0xFF) -#define _FS_MODE_ACCESS_FLAGS_OFFSET (16) -#define _FS_MODE_ACCESS_FLAGS_MASK (0xFF) -#define _FS_MODE_ACCESS_OFFSET (12) -#define _FS_MODE_ACCESS_MASK (0xF) -#define _FS_MODE_OPEN_SIZE_GRAN_OFFSET (8) -#define _FS_MODE_OPEN_SIZE_GRAN_MASK (0xF) -#define _FS_MODE_OPEN_SIZE_OFFSET (0) -#define _FS_MODE_OPEN_SIZE_MASK (0xFF) -#define MAX_MODE_SIZE (0xFF) -#define _FS_MODE(Access, SizeGran, Size,Flags) (_u32)(((_u32)((Access) & _FS_MODE_ACCESS_MASK)<<_FS_MODE_ACCESS_OFFSET) | \ - ((_u32)((SizeGran) & _FS_MODE_OPEN_SIZE_GRAN_MASK)<<_FS_MODE_OPEN_SIZE_GRAN_OFFSET) | \ - ((_u32)((Size) & _FS_MODE_OPEN_SIZE_MASK)<<_FS_MODE_OPEN_SIZE_OFFSET) | \ - ((_u32)((Flags) & _FS_MODE_ACCESS_FLAGS_MASK)<<_FS_MODE_ACCESS_FLAGS_OFFSET)) - - -/* sl_FsOpen options */ -/* Open for Read */ -#define FS_MODE_OPEN_READ _FS_MODE(_FS_MODE_OPEN_READ,0,0,0) -/* Open for Write (in case file exist) */ -#define FS_MODE_OPEN_WRITE _FS_MODE(_FS_MODE_OPEN_WRITE,0,0,0) -/* Open for Creating a new file */ -#define FS_MODE_OPEN_CREATE(maxSizeInBytes,accessModeFlags) _sl_GetCreateFsMode(maxSizeInBytes,accessModeFlags) - -/*****************************************************************************/ -/* Structure/Enum declarations */ -/*****************************************************************************/ -typedef struct -{ - _u16 flags; - _u32 FileLen; - _u32 AllocatedLen; - _u32 Token[4]; -}SlFsFileInfo_t; - -typedef enum -{ - _FS_MODE_OPEN_READ = 0, - _FS_MODE_OPEN_WRITE, - _FS_MODE_OPEN_CREATE, - _FS_MODE_OPEN_WRITE_CREATE_IF_NOT_EXIST -}SlFsFileOpenAccessType_e; - -typedef enum -{ - _FS_FILE_OPEN_FLAG_COMMIT = 0x1, /* MIRROR - for fail safe */ - _FS_FILE_OPEN_FLAG_SECURE = 0x2, /* SECURE */ - _FS_FILE_OPEN_FLAG_NO_SIGNATURE_TEST = 0x4, /* Relevant to secure file only */ - _FS_FILE_OPEN_FLAG_STATIC = 0x8, /* Relevant to secure file only */ - _FS_FILE_OPEN_FLAG_VENDOR = 0x10, /* Relevant to secure file only */ - _FS_FILE_PUBLIC_WRITE= 0x20, /* Relevant to secure file only, the file can be opened for write without Token */ - _FS_FILE_PUBLIC_READ = 0x40 /* Relevant to secure file only, the file can be opened for read without Token */ -}SlFileOpenFlags_e; - -typedef enum -{ - _FS_MODE_SIZE_GRAN_256B = 0, /* MAX_SIZE = 64K */ - _FS_MODE_SIZE_GRAN_1KB, /* MAX_SIZE = 256K */ - _FS_MODE_SIZE_GRAN_4KB, /* MAX_SZIE = 1M */ - _FS_MODE_SIZE_GRAN_16KB, /* MAX_SIZE = 4M */ - _FS_MODE_SIZE_GRAN_64KB, /* MAX_SIZE = 16M */ - _FS_MAX_MODE_SIZE_GRAN -}_SlFsFileOpenMaxSizeGran_e; - -/*****************************************************************************/ -/* Internal Function prototypes */ -/*****************************************************************************/ -_u32 _sl_GetCreateFsMode(_u32 maxSizeInBytes,_u32 accessFlags); - -/*****************************************************************************/ -/* Function prototypes */ -/*****************************************************************************/ - -/*! - \brief open file for read or write from/to storage device - - \param[in] pFileName File Name buffer pointer - \param[in] AccessModeAndMaxSize Options: As described below - \param[in] pToken Reserved for future use. Use NULL for this field - \param[out] pFileHandle Pointing on the file and used for read and write commands to the file - - AccessModeAndMaxSize possible input \n - FS_MODE_OPEN_READ - Read a file \n - FS_MODE_OPEN_WRITE - Open for write for an existing file \n - FS_MODE_OPEN_CREATE(maxSizeInBytes,accessModeFlags) - Open for creating a new file. Max file size is defined in bytes. \n - For optimal FS size, use max size in 4K-512 bytes steps (e.g. 3584,7680,117760) \n - Several access modes bits can be combined together from SlFileOpenFlags_e enum - - \return On success, zero is returned. On error, an error code is returned - - \sa sl_FsRead sl_FsWrite sl_FsClose - \note belongs to \ref basic_api - \warning - \par Example: - \code - char* DeviceFileName = "MyFile.txt"; - unsigned long MaxSize = 63 * 1024; //62.5K is max file size - long DeviceFileHandle = -1; - long RetVal; //negative retval is an error - unsigned long Offset = 0; - unsigned char InputBuffer[100]; - - // Create a file and write data. The file in this example is secured, without signature and with a fail safe commit - RetVal = sl_FsOpen((unsigned char *)DeviceFileName, - FS_MODE_OPEN_CREATE(MaxSize , _FS_FILE_OPEN_FLAG_NO_SIGNATURE_TEST | _FS_FILE_OPEN_FLAG_COMMIT ), - NULL, &DeviceFileHandle); - - Offset = 0; - //Preferred in secure file that the Offset and the length will be aligned to 16 bytes. - RetVal = sl_FsWrite( DeviceFileHandle, Offset, (unsigned char *)"HelloWorld", strlen("HelloWorld")); - - RetVal = sl_FsClose(DeviceFileHandle, NULL, NULL , 0); - - // open the same file for read, using the Token we got from the creation procedure above - RetVal = sl_FsOpen((unsigned char *)DeviceFileName, - FS_MODE_OPEN_READ, - NULL, &DeviceFileHandle); - - Offset = 0; - RetVal = sl_FsRead( DeviceFileHandle, Offset, (unsigned char *)InputBuffer, strlen("HelloWorld")); - - RetVal = sl_FsClose(DeviceFileHandle, NULL, NULL , 0); - - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_FsOpen) -_i32 sl_FsOpen(const _u8 *pFileName,const _u32 AccessModeAndMaxSize,_u32 *pToken,_i32 *pFileHandle); -#endif - -/*! - \brief close file in storage device - - \param[in] FileHdl Pointer to the file (assigned from sl_FsOpen) - \param[in] pCeritificateFileName Reserved for future use. Use NULL. - \param[in] pSignature Reserved for future use. Use NULL. - \param[in] SignatureLen Reserved for future use. Use 0. - - - \return On success, zero is returned. On error, an error code is returned - - \sa sl_FsRead sl_FsWrite sl_FsOpen - \note Call the fs_Close with signature = 'A' signature len = 1 for activating an abort action - \warning - \par Example: - \code - sl_FsClose(FileHandle,0,0,0); - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_FsClose) -_i16 sl_FsClose(const _i32 FileHdl,const _u8* pCeritificateFileName,const _u8* pSignature,const _u32 SignatureLen); -#endif - -/*! - \brief Read block of data from a file in storage device - - \param[in] FileHdl Pointer to the file (assigned from sl_FsOpen) - \param[in] Offset Offset to specific read block - \param[out] pData Pointer for the received data - \param[in] Len Length of the received data - - \return On success, returns the number of read bytes. On error, negative number is returned - - \sa sl_FsClose sl_FsWrite sl_FsOpen - \note belongs to \ref basic_api - \warning - \par Example: - \code - Status = sl_FsRead(FileHandle, 0, &readBuff[0], readSize); - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_FsRead) -_i32 sl_FsRead(const _i32 FileHdl,_u32 Offset ,_u8* pData,_u32 Len); -#endif - -/*! - \brief write block of data to a file in storage device - - \param[in] FileHdl Pointer to the file (assigned from sl_FsOpen) - \param[in] Offset Offset to specific block to be written - \param[in] pData Pointer the transmitted data to the storage device - \param[in] Len Length of the transmitted data - - \return On success, returns the number of written bytes. On error, an error code is returned - - \sa - \note belongs to \ref basic_api - \warning - \par Example: - \code - Status = sl_FsWrite(FileHandle, 0, &buff[0], readSize); - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_FsWrite) -_i32 sl_FsWrite(const _i32 FileHdl,_u32 Offset,_u8* pData,_u32 Len); -#endif - -/*! - \brief get info on a file - - \param[in] pFileName File name - \param[in] Token Reserved for future use. Use 0 - \param[out] pFsFileInfo Returns the File's Information: flags,file size, allocated size and Tokens - - \return On success, zero is returned. On error, an error code is returned - - \sa sl_FsOpen - \note belongs to \ref basic_api - \warning - \par Example: - \code - Status = sl_FsGetInfo("FileName.html",0,&FsFileInfo); - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_FsGetInfo) -_i16 sl_FsGetInfo(const _u8 *pFileName,const _u32 Token,SlFsFileInfo_t* pFsFileInfo); -#endif - -/*! - \brief Delete specific file from a storage or all files from a storage (format) - - \param[in] pFileName File Name - \param[in] Token Reserved for future use. Use 0 - \return On success, zero is returned. On error, an error code is returned - - \sa - \note belongs to \ref basic_api - \warning - \par Example: - \code - Status = sl_FsDel("FileName.html",0); - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_FsDel) -_i16 sl_FsDel(const _u8 *pFileName,const _u32 Token); -#endif -/*! - - Close the Doxygen group. - @} - - */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __FS_H__ */ - diff --git a/drivers/cc3100/inc/netapp.h b/drivers/cc3100/inc/netapp.h deleted file mode 100644 index a968e7d0ba..0000000000 --- a/drivers/cc3100/inc/netapp.h +++ /dev/null @@ -1,884 +0,0 @@ -/* - * netapp.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ - -#include "simplelink.h" - -#ifndef __NETAPP_H__ -#define __NETAPP_H__ - - - - -#ifdef __cplusplus -extern "C" { -#endif - -/*! - - \addtogroup netapp - @{ - -*/ - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ - -/*ERROR code*/ -#define SL_ERROR_NETAPP_RX_BUFFER_LENGTH_ERROR (-230) - -/* Http Server interface */ -#define MAX_INPUT_STRING (64) /* because of WPA */ - -#define MAX_AUTH_NAME_LEN (20) -#define MAX_AUTH_PASSWORD_LEN (20) -#define MAX_AUTH_REALM_LEN (20) - -#define MAX_DEVICE_URN_LEN (15+1) -#define MAX_DOMAIN_NAME_LEN (24+1) - -#define MAX_ACTION_LEN (30) -/* Important: in case the max len is changed, make sure the struct sl_NetAppHttpServerSendToken_t in protocol.h is padded correctly! */ -#define MAX_TOKEN_NAME_LEN (20) -#define MAX_TOKEN_VALUE_LEN MAX_INPUT_STRING - -#define NETAPP_MAX_SERVICE_TEXT_SIZE (256) -#define NETAPP_MAX_SERVICE_NAME_SIZE (60) -#define NETAPP_MAX_SERVICE_HOST_NAME_SIZE (64) - - -/* Server Responses */ -#define SL_NETAPP_RESPONSE_NONE (0) -#define SL_NETAPP_HTTPSETTOKENVALUE (1) - -#define SL_NETAPP_FAMILY_MASK (0x80) - -/* mDNS types */ -#define SL_NET_APP_MASK_IPP_TYPE_OF_SERVICE (0x00000001) -#define SL_NET_APP_MASK_DEVICE_INFO_TYPE_OF_SERVICE (0x00000002) -#define SL_NET_APP_MASK_HTTP_TYPE_OF_SERVICE (0x00000004) -#define SL_NET_APP_MASK_HTTPS_TYPE_OF_SERVICE (0x00000008) -#define SL_NET_APP_MASK_WORKSATION_TYPE_OF_SERVICE (0x00000010) -#define SL_NET_APP_MASK_GUID_TYPE_OF_SERVICE (0x00000020) -#define SL_NET_APP_MASK_H323_TYPE_OF_SERVICE (0x00000040) -#define SL_NET_APP_MASK_NTP_TYPE_OF_SERVICE (0x00000080) -#define SL_NET_APP_MASK_OBJECITVE_TYPE_OF_SERVICE (0x00000100) -#define SL_NET_APP_MASK_RDP_TYPE_OF_SERVICE (0x00000200) -#define SL_NET_APP_MASK_REMOTE_TYPE_OF_SERVICE (0x00000400) -#define SL_NET_APP_MASK_RTSP_TYPE_OF_SERVICE (0x00000800) -#define SL_NET_APP_MASK_SIP_TYPE_OF_SERVICE (0x00001000) -#define SL_NET_APP_MASK_SMB_TYPE_OF_SERVICE (0x00002000) -#define SL_NET_APP_MASK_SOAP_TYPE_OF_SERVICE (0x00004000) -#define SL_NET_APP_MASK_SSH_TYPE_OF_SERVICE (0x00008000) -#define SL_NET_APP_MASK_TELNET_TYPE_OF_SERVICE (0x00010000) -#define SL_NET_APP_MASK_TFTP_TYPE_OF_SERVICE (0x00020000) -#define SL_NET_APP_MASK_XMPP_CLIENT_TYPE_OF_SERVICE (0x00040000) -#define SL_NET_APP_MASK_RAOP_TYPE_OF_SERVICE (0x00080000) -#define SL_NET_APP_MASK_ALL_TYPE_OF_SERVICE (0xFFFFFFFF) - -/********************************************************************************************************/ -/* sl_NetAppDnsGetHostByName error codes */ - -#define SL_NET_APP_DNS_QUERY_NO_RESPONSE (-159) /* DNS query failed, no response */ -#define SL_NET_APP_DNS_NO_SERVER (-161) /* No DNS server was specified */ -#define SL_NET_APP_DNS_PARAM_ERROR (-162) /* mDNS parameters error */ -#define SL_NET_APP_DNS_QUERY_FAILED (-163) /* DNS query failed; no DNS server sent an 'answer' */ -#define SL_NET_APP_DNS_INTERNAL_1 (-164) -#define SL_NET_APP_DNS_INTERNAL_2 (-165) -#define SL_NET_APP_DNS_MALFORMED_PACKET (-166) /* Improperly formed or corrupted DNS packet received */ -#define SL_NET_APP_DNS_INTERNAL_3 (-167) -#define SL_NET_APP_DNS_INTERNAL_4 (-168) -#define SL_NET_APP_DNS_INTERNAL_5 (-169) -#define SL_NET_APP_DNS_INTERNAL_6 (-170) -#define SL_NET_APP_DNS_INTERNAL_7 (-171) -#define SL_NET_APP_DNS_INTERNAL_8 (-172) -#define SL_NET_APP_DNS_INTERNAL_9 (-173) -#define SL_NET_APP_DNS_MISMATCHED_RESPONSE (-174) /* Server response type does not match the query request*/ -#define SL_NET_APP_DNS_INTERNAL_10 (-175) -#define SL_NET_APP_DNS_INTERNAL_11 (-176) -#define SL_NET_APP_DNS_NO_ANSWER (-177) /* No response for one-shot query */ -#define SL_NET_APP_DNS_NO_KNOWN_ANSWER (-178) /* No known answer for query */ -#define SL_NET_APP_DNS_NAME_MISMATCH (-179) /* Illegal service name according to the RFC */ -#define SL_NET_APP_DNS_NOT_STARTED (-180) /* mDNS is not running */ -#define SL_NET_APP_DNS_HOST_NAME_ERROR (-181) /* Host name error. Host name format is not allowed according to RFC 1033,1034,1035, 6763 */ -#define SL_NET_APP_DNS_NO_MORE_ENTRIES (-182) /* No more entries be found. */ - -#define SL_NET_APP_DNS_MAX_SERVICES_ERROR (-200) /* Maximum advertise services are already configured */ -#define SL_NET_APP_DNS_IDENTICAL_SERVICES_ERROR (-201) /* Trying to register a service that is already exists */ -#define SL_NET_APP_DNS_NOT_EXISTED_SERVICE_ERROR (-203) /* Trying to delete service that does not existed */ -#define SL_NET_APP_DNS_ERROR_SERVICE_NAME_ERROR (-204) /* Illegal service name according to the RFC */ -#define SL_NET_APP_DNS_RX_PACKET_ALLOCATION_ERROR (-205) /* Retry request */ -#define SL_NET_APP_DNS_BUFFER_SIZE_ERROR (-206) /* List size buffer is bigger than internally allowed in the NWP */ -#define SL_NET_APP_DNS_NET_APP_SET_ERROR (-207) /* Illegal length of one of the mDNS Set functions */ -#define SL_NET_APP_DNS_GET_SERVICE_LIST_FLAG_ERROR (-208) -#define SL_NET_APP_DNS_NO_CONFIGURATION_ERROR (-209) - -/* Set Dev name error codes (NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN) */ -#define SL_ERROR_DEVICE_NAME_LEN_ERR (-117) -#define SL_ERROR_DEVICE_NAME_INVALID (-118) -/* Set domain name error codes (NETAPP_SET_GET_DEV_CONF_OPT_DOMAIN_NAME) */ -#define SL_ERROR_DOMAIN_NAME_LEN_ERR (-119) -#define SL_ERROR_DOMAIN_NAME_INVALID (-120) - -/********************************************************************************************************/ - -/* NetApp application IDs */ -#define SL_NET_APP_HTTP_SERVER_ID (1) -#define SL_NET_APP_DHCP_SERVER_ID (2) -#define SL_NET_APP_MDNS_ID (4) -#define SL_NET_APP_DNS_SERVER_ID (8) -#define SL_NET_APP_DEVICE_CONFIG_ID (16) -/* NetApp application set/get options */ -#define NETAPP_SET_DHCP_SRV_BASIC_OPT (0) -/* HTTP server set/get options */ -#define NETAPP_SET_GET_HTTP_OPT_PORT_NUMBER (0) -#define NETAPP_SET_GET_HTTP_OPT_AUTH_CHECK (1) -#define NETAPP_SET_GET_HTTP_OPT_AUTH_NAME (2) -#define NETAPP_SET_GET_HTTP_OPT_AUTH_PASSWORD (3) -#define NETAPP_SET_GET_HTTP_OPT_AUTH_REALM (4) -#define NETAPP_SET_GET_HTTP_OPT_ROM_PAGES_ACCESS (5) - -#define NETAPP_SET_GET_MDNS_CONT_QUERY_OPT (1) -#define NETAPP_SET_GET_MDNS_QEVETN_MASK_OPT (2) -#define NETAPP_SET_GET_MDNS_TIMING_PARAMS_OPT (3) - -/* DNS server set/get options */ -#define NETAPP_SET_GET_DNS_OPT_DOMAIN_NAME (0) - -/* Device Config set/get options */ -#define NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN (0) -#define NETAPP_SET_GET_DEV_CONF_OPT_DOMAIN_NAME (1) - - -/*****************************************************************************/ -/* Structure/Enum declarations */ -/*****************************************************************************/ - -typedef struct -{ - _u32 PacketsSent; - _u32 PacketsReceived; - _u16 MinRoundTime; - _u16 MaxRoundTime; - _u16 AvgRoundTime; - _u32 TestTime; -}SlPingReport_t; - -typedef struct -{ - _u32 PingIntervalTime; /* delay between pings, in milliseconds */ - _u16 PingSize; /* ping packet size in bytes */ - _u16 PingRequestTimeout; /* timeout time for every ping in milliseconds */ - _u32 TotalNumberOfAttempts; /* max number of ping requests. 0 - forever */ - _u32 Flags; /* flag - 0 report only when finished, 1 - return response for every ping, 2 - stop after 1 successful ping. */ - _u32 Ip; /* IPv4 address or IPv6 first 4 bytes */ - _u32 Ip1OrPaadding; - _u32 Ip2OrPaadding; - _u32 Ip3OrPaadding; -}SlPingStartCommand_t; - -typedef struct _slHttpServerString_t -{ - _u8 len; - _u8 *data; -} slHttpServerString_t; - -typedef struct _slHttpServerData_t -{ - _u8 value_len; - _u8 name_len; - _u8 *token_value; - _u8 *token_name; -} slHttpServerData_t; - -typedef struct _slHttpServerPostData_t -{ - slHttpServerString_t action; - slHttpServerString_t token_name; - slHttpServerString_t token_value; -}slHttpServerPostData_t; - -typedef union -{ - slHttpServerString_t httpTokenName; /* SL_NETAPP_HTTPGETTOKENVALUE */ - slHttpServerPostData_t httpPostData; /* SL_NETAPP_HTTPPOSTTOKENVALUE */ -} SlHttpServerEventData_u; - -typedef union -{ - slHttpServerString_t token_value; -} SlHttpServerResponsedata_u; - -typedef struct -{ - _u32 Event; - SlHttpServerEventData_u EventData; -}SlHttpServerEvent_t; - -typedef struct -{ - _u32 Response; - SlHttpServerResponsedata_u ResponseData; -}SlHttpServerResponse_t; - - -typedef struct -{ - _u32 lease_time; - _u32 ipv4_addr_start; - _u32 ipv4_addr_last; -}SlNetAppDhcpServerBasicOpt_t; - -/*mDNS parameters*/ -typedef enum -{ - SL_NET_APP_FULL_SERVICE_WITH_TEXT_IPV4_TYPE = 1, - SL_NET_APP_FULL_SERVICE_IPV4_TYPE, - SL_NET_APP_SHORT_SERVICE_IPV4_TYPE - -} SlNetAppGetServiceListType_e; - -typedef struct -{ - _u32 service_ipv4; - _u16 service_port; - _u16 Reserved; -}SlNetAppGetShortServiceIpv4List_t; - -typedef struct -{ - _u32 service_ipv4; - _u16 service_port; - _u16 Reserved; - _u8 service_name[NETAPP_MAX_SERVICE_NAME_SIZE]; - _u8 service_host[NETAPP_MAX_SERVICE_HOST_NAME_SIZE]; -}SlNetAppGetFullServiceIpv4List_t; - -typedef struct -{ - _u32 service_ipv4; - _u16 service_port; - _u16 Reserved; - _u8 service_name[NETAPP_MAX_SERVICE_NAME_SIZE]; - _u8 service_host[NETAPP_MAX_SERVICE_HOST_NAME_SIZE]; - _u8 service_text[NETAPP_MAX_SERVICE_TEXT_SIZE]; -}SlNetAppGetFullServiceWithTextIpv4List_t; - -typedef struct -{ - /*The below parameters are used to configure the advertise times and interval - For example: - If: - Period is set to T - Repetitions are set to P - Telescopic factor is K=2 - The transmission shall be: - advertise P times - wait T - advertise P times - wait 4 * T - advertise P time - wait 16 * T ... (till max time reached / configuration changed / query issued) - */ - _u32 t; /* Number of ticks for the initial period. Default is 100 ticks for 1 second. */ - _u32 p; /* Number of repetitions. Default value is 1 */ - _u32 k; /* Telescopic factor. Default value is 2. */ - _u32 RetransInterval;/* Announcing retransmission interval */ - _u32 Maxinterval; /* Announcing max period interval */ - _u32 max_time; /* Announcing max time */ -}SlNetAppServiceAdvertiseTimingParameters_t; - -/*****************************************************************************/ -/* Types declarations */ -/*****************************************************************************/ -typedef void (*P_SL_DEV_PING_CALLBACK)(SlPingReport_t*); - -/*****************************************************************************/ -/* Function prototypes */ -/*****************************************************************************/ - - -/*! - \brief Starts a network application - - Gets and starts network application for the current WLAN mode - - \param[in] AppBitMap application bitmap, could be one or combination of the following: \n - - SL_NET_APP_HTTP_SERVER_ID - - SL_NET_APP_DHCP_SERVER_ID - - SL_NET_APP_MDNS_ID - - \return On error, negative number is returned - - \sa Stop one or more the above started applications using sl_NetAppStop - \note This command activates the application for the current WLAN mode (AP or STA) - \warning - \par Example: - \code - For example: Starting internal HTTP server + DHCP server: - sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID | SL_NET_APP_DHCP_SERVER_ID) - - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_NetAppStart) -_i16 sl_NetAppStart(const _u32 AppBitMap); -#endif -/*! - \brief Stops a network application - - Gets and stops network application for the current WLAN mode - - \param[in] AppBitMap application id, could be one of the following: \n - - SL_NET_APP_HTTP_SERVER_ID - - SL_NET_APP_DHCP_SERVER_ID - - SL_NET_APP_MDNS_ID - - \return On error, negative number is returned - - \sa - \note This command disables the application for the current active WLAN mode (AP or STA) - \warning - \par Example: - \code - - For example: Stopping internal HTTP server: - sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); - - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_NetAppStop) -_i16 sl_NetAppStop(const _u32 AppBitMap); -#endif - -/*! - \brief Get host IP by name - - Obtain the IP Address of machine on network, by machine name. - - \param[in] hostname host name - \param[in] usNameLen name length - \param[out] out_ip_addr This parameter is filled in with - host IP address. In case that host name is not - resolved, out_ip_addr is zero. - \param[in] family protocol family - - \return On success, 0 is returned. - On error, negative is returned - SL_POOL_IS_EMPTY may be return in case there are no resources in the system - In this case try again later or increase MAX_CONCURRENT_ACTIONS - Possible DNS error codes: - - SL_NET_APP_DNS_QUERY_NO_RESPONSE - - SL_NET_APP_DNS_NO_SERVER - - SL_NET_APP_DNS_QUERY_FAILED - - SL_NET_APP_DNS_MALFORMED_PACKET - - SL_NET_APP_DNS_MISMATCHED_RESPONSE - - \sa - \note Only one sl_NetAppDnsGetHostByName can be handled at a time. - Calling this API while the same command is called from another thread, may result - in one of the two scenarios: - 1. The command will wait (internal) until the previous command finish, and then be executed. - 2. There are not enough resources and POOL_IS_EMPTY error will return. - In this case, MAX_CONCURRENT_ACTIONS can be increased (result in memory increase) or try - again later to issue the command. - \warning - In case an IP address in a string format is set as input, without any prefix (e.g. "1.2.3.4") the device will not - try to access the DNS and it will return the input address on the 'out_ip_addr' field - \par Example: - \code - _u32 DestinationIP; - sl_NetAppDnsGetHostByName("www.google.com", strlen("www.google.com"), &DestinationIP,SL_AF_INET); - - Addr.sin_family = SL_AF_INET; - Addr.sin_port = sl_Htons(80); - Addr.sin_addr.s_addr = sl_Htonl(DestinationIP); - AddrSize = sizeof(SlSockAddrIn_t); - SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_NetAppDnsGetHostByName) -_i16 sl_NetAppDnsGetHostByName(_i8 * hostname,const _u16 usNameLen, _u32* out_ip_addr,const _u8 family ); -#endif - -/*! - \brief Return service attributes like IP address, port and text according to service name - \par - The user sets a service name Full/Part (see example below), and should get: - - IP of service - - The port of service - - The text of service - - Hence it can make a connection to the specific service and use it. - It is similar to get host by name method. - It is done by a single shot query with PTR type on the service name. - The command that is sent is from constant parameters and variables parameters. - - \param[in] pService Service name can be full or partial. \n - Example for full service name: - 1. PC1._ipp._tcp.local - 2. PC2_server._ftp._tcp.local \n - . - Example for partial service name: - 1. _ipp._tcp.local - 2. _ftp._tcp.local - - \param[in] ServiceLen The length of the service name (in_pService). - \param[in] Family IPv4 or IPv6 (SL_AF_INET , SL_AF_INET6). - \param[out] pAddr Contains the IP address of the service. - \param[out] pPort Contains the port of the service. - \param[out] pTextLen Has 2 options. One as Input field and the other one as output: - - Input: \n - Contains the max length of the text that the user wants to get.\n - It means that if the text len of service is bigger that its value than - the text is cut to inout_TextLen value. - - Output: \n - Contain the length of the text that is returned. Can be full text or part of the text (see above). - - \param[out] pOut_pText Contains the text of the service full or partial - - \return On success, zero is returned - SL_POOL_IS_EMPTY may be return in case there are no resources in the system - In this case try again later or increase MAX_CONCURRENT_ACTIONS - In case No service is found error SL_NET_APP_DNS_NO_ANSWER will be returned - - \note The returns attributes belongs to the first service found. - There may be other services with the same service name that will response to the query. - The results of these responses are saved in the peer cache of the Device and should be read by another API. - - Only one sl_NetAppDnsGetHostByService can be handled at a time. - Calling this API while the same command is called from another thread, may result - in one of the two scenarios: - 1. The command will wait (internal) until the previous command finish, and then be executed. - 2. There are not enough resources and SL_POOL_IS_EMPTY error will return. - In this case, MAX_CONCURRENT_ACTIONS can be increased (result in memory increase) or try - again later to issue the command. - - \warning Text length can be 120 bytes only -*/ -#if _SL_INCLUDE_FUNC(sl_NetAppDnsGetHostByService) -_i32 sl_NetAppDnsGetHostByService(_i8 *pServiceName, /* string containing all (or only part): name + subtype + service */ - const _u8 ServiceLen, - const _u8 Family, /* 4-IPv4 , 16-IPv6 */ - _u32 pAddr[], - _u32 *pPort, - _u16 *pTextLen, /* in: max len , out: actual len */ - _i8 *pText - ); - -#endif - -/*! - \brief Get service List - Insert into out pBuffer a list of peer's services that are the NWP. - The list is in a form of service struct. The user should chose the type - of the service struct like: - - Full service parameters with text. - - Full service parameters. - - Short service parameters (port and IP only) especially for tiny hosts. - - The different types of struct are made to give the - Possibility to save memory in the host - - - The user also chose how many max services to get and start point index - NWP peer cache. - For example: - 1. Get max of 3 full services from index 0.Up to 3 full services - from index 0 are inserted into pBuffer (services that are in indexes 0,1,2). - 2. Get max of 4 full services from index 3.Up to 4 full services - from index 3 are inserted into pBuffer (services that are in indexes 3,4,5,6). - 3. Get max of 2 int services from index 6.Up to 2 int services - from index 6 are inserted into pBuffer (services that are in indexes 6,7). - - See below - command parameters. - - \param[in] indexOffset - The start index in the peer cache that from it the first service is returned. - \param[in] MaxServiceCount - The Max services that can be returned if existed or if not exceed the max index - in the peer cache - \param[in] Flags - an ENUM number that means which service struct to use (means which types of service to fill) - - use SlNetAppGetFullServiceWithTextIpv4List_t - - use SlNetAppGetFullServiceIpv4List_t - - use SlNetAppGetShortServiceIpv4List_t - - \param[out] Buffer - The Services are inserted into this buffer. In the struct form according to the bit that is set in the Flags - input parameter. - - \return ServiceFoundCount - The number of the services that were inserted into the buffer. zero means no service is found - negative number means an error - \sa sl_NetAppMDNSRegisterService - \note - \warning - if the out pBuffer size is bigger than an RX packet(1480), than - an error is returned because there - is no place in the RX packet. - The size is a multiply of MaxServiceCount and size of service struct(that is set - according to flag value). -*/ - -#if _SL_INCLUDE_FUNC(sl_NetAppGetServiceList) -_i16 sl_NetAppGetServiceList(const _u8 IndexOffest, - const _u8 MaxServiceCount, - const _u8 Flags, - _i8 *pBuffer, - const _u32 RxBufferLength - ); - -#endif - -/*! - \brief Unregister mDNS service - This function deletes the mDNS service from the mDNS package and the database. - - The mDNS service that is to be unregistered is a service that the application no longer wishes to provide. \n - The service name should be the full service name according to RFC - of the DNS-SD - meaning the value in name field in the SRV answer. - - Examples for service names: - 1. PC1._ipp._tcp.local - 2. PC2_server._ftp._tcp.local - - \param[in] pServiceName Full service name. \n - Example for service name: - 1. PC1._ipp._tcp.local - 2. PC2_server._ftp._tcp.local - \param[in] ServiceLen The length of the service. - \return On success, zero is returned - \sa sl_NetAppMDNSRegisterService - \note - \warning - The size of the service length should be smaller than 255. -*/ -#if _SL_INCLUDE_FUNC(sl_NetAppMDNSUnRegisterService) -_i16 sl_NetAppMDNSUnRegisterService(const _i8 *pServiceName,const _u8 ServiceNameLen); -#endif - -/*! - \brief Register a new mDNS service - \par - This function registers a new mDNS service to the mDNS package and the DB. - - This registered service is a service offered by the application. - The service name should be full service name according to RFC - of the DNS-SD - meaning the value in name field in the SRV answer. - Example for service name: - 1. PC1._ipp._tcp.local - 2. PC2_server._ftp._tcp.local - - If the option is_unique is set, mDNS probes the service name to make sure - it is unique before starting to announce the service on the network. - Instance is the instance portion of the service name. - - \param[in] ServiceLen The length of the service. - \param[in] TextLen The length of the service should be smaller than 64. - \param[in] port The port on this target host port. - \param[in] TTL The TTL of the service - \param[in] Options bitwise parameters: \n - - bit 0 - service is unique (means that the service needs to be unique) - - bit 31 - for internal use if the service should be added or deleted (set means ADD). - - bit 1-30 for future. - - \param[in] pServiceName The service name. - Example for service name: \n - 1. PC1._ipp._tcp.local - 2. PC2_server._ftp._tcp.local - - \param[in] pText The description of the service. - should be as mentioned in the RFC - (according to type of the service IPP,FTP...) - - \return On success, zero is returned - Possible error codes: - - Maximum advertise services are already configured. - Delete another existed service that is registered and then register again the new service - - Trying to register a service that is already exists - - Trying to delete service that does not existed - - Illegal service name according to the RFC - - Retry request - - Illegal length of one of the mDNS Set functions - - mDNS is not operational as the device has no IP.Connect the device to an AP to get an IP address. - - mDNS parameters error - - mDNS internal cache error - - mDNS internal error - - Adding a service is not allowed as it is already exist (duplicate service) - - mDNS is not running - - Host name error. Host name format is not allowed according to RFC 1033,1034,1035, 6763 - - List size buffer is bigger than internally allowed in the NWP (API get service list), - change the APIs parameters to decrease the size of the list - - - \sa sl_NetAppMDNSUnRegisterService - - \warning 1) Temporary - there is an allocation on stack of internal buffer. - Its size is NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH. \n - It means that the sum of the text length and service name length cannot be bigger than - NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.\n - If it is - An error is returned. \n - 2) According to now from certain constraints the variables parameters are set in the - attribute part (contain constant parameters) -*/ -#if _SL_INCLUDE_FUNC(sl_NetAppMDNSRegisterService) -_i16 sl_NetAppMDNSRegisterService( const _i8* pServiceName, - const _u8 ServiceNameLen, - const _i8* pText, - const _u8 TextLen, - const _u16 Port, - const _u32 TTL, - _u32 Options); -#endif - -/*! - \brief send ICMP ECHO_REQUEST to network hosts - - Ping uses the ICMP protocol's mandatory ECHO_REQUEST - - \param[in] pPingParams Pointer to the ping request structure: \n - - if flags parameter is set to 0, ping will report back once all requested pings are done (as defined by TotalNumberOfAttempts). \n - - if flags parameter is set to 1, ping will report back after every ping, for TotalNumberOfAttempts. - - if flags parameter is set to 2, ping will stop after the first successful ping, and report back for the successful ping, as well as any preceding failed ones. - For stopping an ongoing ping activity, set parameters IP address to 0 - - \param[in] family SL_AF_INET or SL_AF_INET6 - \param[out] pReport Ping pReport - \param[out] pCallback Callback function upon completion. - If callback is NULL, the API is blocked until data arrives - - - \return On success, zero is returned. On error, -1 is returned - SL_POOL_IS_EMPTY may be return in case there are no resources in the system - In this case try again later or increase MAX_CONCURRENT_ACTIONS - - \sa sl_NetAppPingReport - \note Only one sl_NetAppPingStart can be handled at a time. - Calling this API while the same command is called from another thread, may result - in one of the two scenarios: - 1. The command will wait (internal) until the previous command finish, and then be executed. - 2. There are not enough resources and SL_POOL_IS_EMPTY error will return. - In this case, MAX_CONCURRENT_ACTIONS can be increased (result in memory increase) or try - again later to issue the command. - \warning - \par Example: - \code - - An example of sending 20 ping requests and reporting results to a callback routine when - all requests are sent: - - // callback routine - void pingRes(SlPingReport_t* pReport) - { - // handle ping results - } - - // ping activation - void PingTest() - { - SlPingReport_t report; - SlPingStartCommand_t pingCommand; - - pingCommand.Ip = SL_IPV4_VAL(10,1,1,200); // destination IP address is 10.1.1.200 - pingCommand.PingSize = 150; // size of ping, in bytes - pingCommand.PingIntervalTime = 100; // delay between pings, in milliseconds - pingCommand.PingRequestTimeout = 1000; // timeout for every ping in milliseconds - pingCommand.TotalNumberOfAttempts = 20; // max number of ping requests. 0 - forever - pingCommand.Flags = 0; // report only when finished - - sl_NetAppPingStart( &pingCommand, SL_AF_INET, &report, pingRes ) ; - } - - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_NetAppPingStart) -_i16 sl_NetAppPingStart(const SlPingStartCommand_t* pPingParams,const _u8 family,SlPingReport_t *pReport,const P_SL_DEV_PING_CALLBACK pPingCallback); -#endif - -/*! - \brief Internal function for setting network application configurations - - \return On success, zero is returned. On error, -1 is - returned - - \param[in] AppId Application id, could be one of the following: \n - - SL_NET_APP_HTTP_SERVER_ID - - SL_NET_APP_DHCP_SERVER_ID - - SL_NET_APP_MDNS_ID - - SL_NET_APP_DEVICE_CONFIG_ID - - \param[in] SetOptions set option, could be one of the following: \n - - SL_NET_APP_DHCP_SERVER_ID - - NETAPP_SET_DHCP_SRV_BASIC_OPT - - SL_NET_APP_HTTP_SERVER_ID - - NETAPP_SET_GET_HTTP_OPT_PORT_NUMBER - - NETAPP_SET_GET_HTTP_OPT_AUTH_CHECK - - NETAPP_SET_GET_HTTP_OPT_AUTH_NAME - - NETAPP_SET_GET_HTTP_OPT_AUTH_PASSWORD - - NETAPP_SET_GET_HTTP_OPT_AUTH_REALM - - NETAPP_SET_GET_HTTP_OPT_ROM_PAGES_ACCESS - - SL_NET_APP_MDNS_ID - - NETAPP_SET_GET_MDNS_CONT_QUERY_OPT - - NETAPP_SET_GET_MDNS_QEVETN_MASK_OPT - - NETAPP_SET_GET_MDNS_TIMING_PARAMS_OPT - - SL_NET_APP_DEVICE_CONFIG_ID - - NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN - - NETAPP_SET_GET_DEV_CONF_OPT_DOMAIN_NAME - - - \param[in] OptionLen option structure length - - \param[in] pOptionValues pointer to the option structure - \sa - \note - \warning - \par - \code - Set DHCP Server (AP mode) parameters example: - - SlNetAppDhcpServerBasicOpt_t dhcpParams; - _u8 outLen = sizeof(SlNetAppDhcpServerBasicOpt_t); - dhcpParams.lease_time = 4096; // lease time (in seconds) of the IP Address - dhcpParams.ipv4_addr_start = SL_IPV4_VAL(192,168,1,10); // first IP Address for allocation. IP Address should be set as Hex number - i.e. 0A0B0C01 for (10.11.12.1) - dhcpParams.ipv4_addr_last = SL_IPV4_VAL(192,168,1,16); // last IP Address for allocation. IP Address should be set as Hex number - i.e. 0A0B0C01 for (10.11.12.1) - sl_NetAppStop(SL_NET_APP_DHCP_SERVER_ID); // Stop DHCP server before settings - sl_NetAppSet(SL_NET_APP_DHCP_SERVER_ID, NETAPP_SET_DHCP_SRV_BASIC_OPT, outLen, (_u8* )&dhcpParams); // set parameters - sl_NetAppStart(SL_NET_APP_DHCP_SERVER_ID); // Start DHCP server with new settings - \endcode - \code - Set Device URN name example: - - Device name, maximum length of 33 characters - Device name affects URN name, own SSID name in AP mode, and WPS file "device name" in WPS I.E (STA-WPS / P2P) - In case no device URN name set, the default name is "mysimplelink" - Allowed characters in device name are: 'a - z' , 'A - Z' , '0-9' and '-' - - _u8 *my_device = "MY-SIMPLELINK-DEV"; - sl_NetAppSet (SL_NET_APP_DEVICE_CONFIG_ID, NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN, strlen(my_device), (_u8 *) my_device); - \endcode - -*/ -#if _SL_INCLUDE_FUNC(sl_NetAppSet) -_i32 sl_NetAppSet(const _u8 AppId ,const _u8 Option,const _u8 OptionLen,const _u8 *pOptionValue); -#endif - -/*! - \brief Internal function for getting network applications configurations - - \return On success, zero is returned. On error, -1 is - returned - - \param[in] AppId Application id, could be one of the following: \n - - SL_NET_APP_HTTP_SERVER_ID - - SL_NET_APP_DHCP_SERVER_ID - - SL_NET_APP_MDNS_ID - - SL_NET_APP_DEVICE_CONFIG_ID - - \param[in] SetOptions set option, could be one of the following: \n - - SL_NET_APP_DHCP_SERVER_ID - - NETAPP_SET_DHCP_SRV_BASIC_OPT - - SL_NET_APP_HTTP_SERVER_ID - - NETAPP_SET_GET_HTTP_OPT_PORT_NUMBER - - NETAPP_SET_GET_HTTP_OPT_AUTH_CHECK - - NETAPP_SET_GET_HTTP_OPT_AUTH_NAME - - NETAPP_SET_GET_HTTP_OPT_AUTH_PASSWORD - - NETAPP_SET_GET_HTTP_OPT_AUTH_REALM - - NETAPP_SET_GET_HTTP_OPT_ROM_PAGES_ACCESS - - SL_NET_APP_MDNS_ID - - NETAPP_SET_GET_MDNS_CONT_QUERY_OPT - - NETAPP_SET_GET_MDNS_QEVETN_MASK_OPT - - NETAPP_SET_GET_MDNS_TIMING_PARAMS_OPT - - SL_NET_APP_DEVICE_CONFIG_ID - - NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN - - NETAPP_SET_GET_DEV_CONF_OPT_DOMAIN_NAME - - - \param[in] OptionLen The length of the allocated memory as input, when the - function complete, the value of this parameter would be - the len that actually read from the device. - If the device return length that is longer from the input - value, the function will cut the end of the returned structure - and will return ESMALLBUF - - \param[out] pValues pointer to the option structure which will be filled with the response from the device - - \sa - \note - \warning - \par - \code - Get DHCP Server parameters example: - - SlNetAppDhcpServerBasicOpt_t dhcpParams; - _u8 outLen = sizeof(SlNetAppDhcpServerBasicOpt_t); - sl_NetAppGet(SL_NET_APP_DHCP_SERVER_ID, NETAPP_SET_DHCP_SRV_BASIC_OPT, &outLen, (_u8* )&dhcpParams); - - printf("DHCP Start IP %d.%d.%d.%d End IP %d.%d.%d.%d Lease time seconds %d\n", - SL_IPV4_BYTE(dhcpParams.ipv4_addr_start,3),SL_IPV4_BYTE(dhcpParams.ipv4_addr_start,2), - SL_IPV4_BYTE(dhcpParams.ipv4_addr_start,1),SL_IPV4_BYTE(dhcpParams.ipv4_addr_start,0), - SL_IPV4_BYTE(dhcpParams.ipv4_addr_last,3),SL_IPV4_BYTE(dhcpParams.ipv4_addr_last,2), - SL_IPV4_BYTE(dhcpParams.ipv4_addr_last,1),SL_IPV4_BYTE(dhcpParams.ipv4_addr_last,0), - dhcpParams.lease_time); - \endcode - \code - Get Device URN name example: - Maximum length of 33 characters of device name. - Device name affects URN name, own SSID name in AP mode, and WPS file "device name" in WPS I.E (STA-WPS / P2P) - in case no device URN name set, the default name is "mysimplelink" - - _u8 my_device_name[35]; - sl_NetAppGet (SL_NET_APP_DEVICE_CONFIG_ID, NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN, strlen(my_device_name), (_u8 *)my_device_name); - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_NetAppGet) -_i32 sl_NetAppGet(const _u8 AppId,const _u8 Option,_u8 *pOptionLen, _u8 *pOptionValue); -#endif - - - -/*! - - Close the Doxygen group. - @} - - */ - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __NETAPP_H__ */ - diff --git a/drivers/cc3100/inc/netcfg.h b/drivers/cc3100/inc/netcfg.h deleted file mode 100644 index cc8cfbcaaf..0000000000 --- a/drivers/cc3100/inc/netcfg.h +++ /dev/null @@ -1,283 +0,0 @@ -/* - * netcfg.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" - - -#ifndef __NETCFG_H__ -#define __NETCFG_H__ - - -#ifdef __cplusplus -extern "C" { -#endif - - - -/*! - - \addtogroup netcfg - @{ - -*/ - - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ - -#define SL_MAC_ADDR_LEN (6) -#define SL_IPV4_VAL(add_3,add_2,add_1,add_0) ((((_u32)add_3 << 24) & 0xFF000000) | (((_u32)add_2 << 16) & 0xFF0000) | (((_u32)add_1 << 8) & 0xFF00) | ((_u32)add_0 & 0xFF) ) -#define SL_IPV4_BYTE(val,index) ( (val >> (index*8)) & 0xFF ) - -#define IPCONFIG_MODE_DISABLE_IPV4 (0) -#define IPCONFIG_MODE_ENABLE_IPV4 (1) - -/*****************************************************************************/ -/* Structure/Enum declarations */ -/*****************************************************************************/ -typedef enum -{ - SL_MAC_ADDRESS_SET = 1, - SL_MAC_ADDRESS_GET = 2, - SL_IPV4_STA_P2P_CL_GET_INFO = 3, - SL_IPV4_STA_P2P_CL_DHCP_ENABLE = 4, - SL_IPV4_STA_P2P_CL_STATIC_ENABLE = 5, - SL_IPV4_AP_P2P_GO_GET_INFO = 6, - SL_IPV4_AP_P2P_GO_STATIC_ENABLE = 7, - SL_SET_HOST_RX_AGGR = 8, - MAX_SETTINGS = 0xFF -}Sl_NetCfg_e; - - -typedef struct -{ - _u32 ipV4; - _u32 ipV4Mask; - _u32 ipV4Gateway; - _u32 ipV4DnsServer; -}SlNetCfgIpV4Args_t; - - -/*****************************************************************************/ -/* Function prototypes */ -/*****************************************************************************/ - -/*! - \brief Internal function for setting network configurations - - \return On success, zero is returned. On error, -1 is - returned - - \param[in] ConfigId configuration id - \param[in] ConfigOpt configurations option - \param[in] ConfigLen configurations len - \param[in] pValues configurations values - - \sa - \note - \warning - - \par Examples: - \code - SL_MAC_ADDRESS_SET: - - Setting MAC address to the Device. - The new MAC address will override the default MAC address and it be saved in the FileSystem. - Requires restarting the device for updating this setting. - - _u8 MAC_Address[6]; - MAC_Address[0] = 0x8; - MAC_Address[1] = 0x0; - MAC_Address[2] = 0x28; - MAC_Address[3] = 0x22; - MAC_Address[4] = 0x69; - MAC_Address[5] = 0x31; - sl_NetCfgSet(SL_MAC_ADDRESS_SET,1,SL_MAC_ADDR_LEN,(_u8 *)newMacAddress); - sl_Stop(0); - sl_Start(NULL,NULL,NULL); - \endcode - - \code - SL_IPV4_STA_P2P_CL_STATIC_ENABLE: - - Setting a static IP address to the device working in STA mode or P2P client. - The IP address will be stored in the FileSystem. - In order to disable the static IP and get the address assigned from DHCP one should use SL_STA_P2P_CL_IPV4_DHCP_SET - - SlNetCfgIpV4Args_t ipV4; - ipV4.ipV4 = (_u32)SL_IPV4_VAL(10,1,1,201); // _u32 IP address - ipV4.ipV4Mask = (_u32)SL_IPV4_VAL(255,255,255,0); // _u32 Subnet mask for this STA/P2P - ipV4.ipV4Gateway = (_u32)SL_IPV4_VAL(10,1,1,1); // _u32 Default gateway address - ipV4.ipV4DnsServer = (_u32)SL_IPV4_VAL(8,16,32,64); // _u32 DNS server address - - sl_NetCfgSet(SL_IPV4_STA_P2P_CL_STATIC_ENABLE,IPCONFIG_MODE_ENABLE_IPV4,sizeof(SlNetCfgIpV4Args_t),(_u8 *)&ipV4); - sl_Stop(0); - sl_Start(NULL,NULL,NULL); - \endcode - - \code - SL_IPV4_STA_P2P_CL_DHCP_ENABLE: - - Setting IP address by DHCP to FileSystem using WLAN sta mode or P2P client. - This should be done once if using Serial Flash. - This is the system's default mode for acquiring an IP address after WLAN connection. - _u8 val = 1; - sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,IPCONFIG_MODE_ENABLE_IPV4,1,&val); - sl_Stop(0); - sl_Start(NULL,NULL,NULL); - \endcode - - \code - SL_IPV4_AP_P2P_GO_STATIC_ENABLE: - - Setting a static IP address to the device working in AP mode or P2P go. - The IP address will be stored in the FileSystem. Requires restart. - - SlNetCfgIpV4Args_t ipV4; - ipV4.ipV4 = (_u32)SL_IPV4_VAL(10,1,1,201); // _u32 IP address - ipV4.ipV4Mask = (_u32)SL_IPV4_VAL(255,255,255,0); // _u32 Subnet mask for this AP/P2P - ipV4.ipV4Gateway = (_u32)SL_IPV4_VAL(10,1,1,1); // _u32 Default gateway address - ipV4.ipV4DnsServer = (_u32)SL_IPV4_VAL(8,16,32,64); // _u32 DNS server address - - sl_NetCfgSet(SL_IPV4_AP_P2P_GO_STATIC_ENABLE,IPCONFIG_MODE_ENABLE_IPV4,sizeof(SlNetCfgIpV4Args_t),(_u8 *)&ipV4); - sl_Stop(0); - sl_Start(NULL,NULL,NULL); - \endcode - - -*/ -#if _SL_INCLUDE_FUNC(sl_NetCfgSet) -_i32 sl_NetCfgSet(const _u8 ConfigId,const _u8 ConfigOpt,const _u8 ConfigLen,const _u8 *pValues); -#endif - - -/*! - \brief Internal function for getting network configurations - - \return On success, zero is returned. On error, -1 is - returned - - \param[in] ConfigId configuration id - - \param[out] pConfigOpt Get configurations option - - \param[out] pConfigLen The length of the allocated memory as input, when the - function complete, the value of this parameter would be - the len that actually read from the device.\n - If the device return length that is longer from the input - value, the function will cut the end of the returned structure - and will return ESMALLBUF - - \param[out] pValues - get configurations values - - \sa - \note - \warning - \par Examples: - \code - SL_MAC_ADDRESS_GET: - - Get the device MAC address. - The returned MAC address is taken from FileSystem first. If the MAC address was not set by SL_MAC_ADDRESS_SET, the default MAC address - is retrieved from HW. - - _u8 macAddressVal[SL_MAC_ADDR_LEN]; - _u8 macAddressLen = SL_MAC_ADDR_LEN; - sl_NetCfgGet(SL_MAC_ADDRESS_GET,NULL,&macAddressLen,(_u8 *)macAddressVal); - - \endcode - - \code - SL_IPV4_STA_P2P_CL_GET_INFO: - - Get IP address from WLAN station or P2P client. A DHCP flag is returned to indicate if the IP address is static or from DHCP. - - _u8 len = sizeof(SlNetCfgIpV4Args_t); - _u8 dhcpIsOn = 0; - SlNetCfgIpV4Args_t ipV4 = {0}; - sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&dhcpIsOn,&len,(_u8 *)&ipV4); - - printf("DHCP is %s IP %d.%d.%d.%d MASK %d.%d.%d.%d GW %d.%d.%d.%d DNS %d.%d.%d.%d\n", - (dhcpIsOn > 0) ? "ON" : "OFF", - SL_IPV4_BYTE(ipV4.ipV4,3),SL_IPV4_BYTE(ipV4.ipV4,2),SL_IPV4_BYTE(ipV4.ipV4,1),SL_IPV4_BYTE(ipV4.ipV4,0), - SL_IPV4_BYTE(ipV4.ipV4Mask,3),SL_IPV4_BYTE(ipV4.ipV4Mask,2),SL_IPV4_BYTE(ipV4.ipV4Mask,1),SL_IPV4_BYTE(ipV4.ipV4Mask,0), - SL_IPV4_BYTE(ipV4.ipV4Gateway,3),SL_IPV4_BYTE(ipV4.ipV4Gateway,2),SL_IPV4_BYTE(ipV4.ipV4Gateway,1),SL_IPV4_BYTE(ipV4.ipV4Gateway,0), - SL_IPV4_BYTE(ipV4.ipV4DnsServer,3),SL_IPV4_BYTE(ipV4.ipV4DnsServer,2),SL_IPV4_BYTE(ipV4.ipV4DnsServer,1),SL_IPV4_BYTE(ipV4.ipV4DnsServer,0)); - - \endcode - - \code - SL_IPV4_AP_P2P_GO_GET_INFO: - - Get static IP address for AP or P2P go. - - _u8 len = sizeof(SlNetCfgIpV4Args_t); - _u8 dhcpIsOn = 0; // this flag is meaningless on AP/P2P go. - SlNetCfgIpV4Args_t ipV4 = {0}; - sl_NetCfgGet(SL_IPV4_AP_P2P_GO_GET_INFO,&dhcpIsOn,&len,(_u8 *)&ipV4); - - printf("IP %d.%d.%d.%d MASK %d.%d.%d.%d GW %d.%d.%d.%d DNS %d.%d.%d.%d\n", - SL_IPV4_BYTE(ipV4.ipV4,3),SL_IPV4_BYTE(ipV4.ipV4,2),SL_IPV4_BYTE(ipV4.ipV4,1),SL_IPV4_BYTE(ipV4.ipV4,0), - SL_IPV4_BYTE(ipV4.ipV4Mask,3),SL_IPV4_BYTE(ipV4.ipV4Mask,2),SL_IPV4_BYTE(ipV4.ipV4Mask,1),SL_IPV4_BYTE(ipV4.ipV4Mask,0), - SL_IPV4_BYTE(ipV4.ipV4Gateway,3),SL_IPV4_BYTE(ipV4.ipV4Gateway,2),SL_IPV4_BYTE(ipV4.ipV4Gateway,1),SL_IPV4_BYTE(ipV4.ipV4Gateway,0), - SL_IPV4_BYTE(ipV4.ipV4DnsServer,3),SL_IPV4_BYTE(ipV4.ipV4DnsServer,2),SL_IPV4_BYTE(ipV4.ipV4DnsServer,1),SL_IPV4_BYTE(ipV4.ipV4DnsServer,0)); - - \endcode - - -*/ -#if _SL_INCLUDE_FUNC(sl_NetCfgGet) -_i32 sl_NetCfgGet(const _u8 ConfigId ,_u8 *pConfigOpt, _u8 *pConfigLen, _u8 *pValues); -#endif - -/*! - - Close the Doxygen group. - @} - - */ - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __NETCFG_H__ */ - diff --git a/drivers/cc3100/inc/nonos.h b/drivers/cc3100/inc/nonos.h deleted file mode 100644 index 568c0ff26e..0000000000 --- a/drivers/cc3100/inc/nonos.h +++ /dev/null @@ -1,325 +0,0 @@ -/* - * nonos.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - -#ifndef __NONOS_H__ -#define __NONOS_H__ - -#ifdef __cplusplus -extern "C" { -#endif - - -#ifndef SL_PLATFORM_MULTI_THREADED - -/* This function call the user defined function, if defined, from the sync wait loop */ -/* The use case of this function is to allow nonos system to call a user function to put the device into sleep */ -/* The wake up should be activated after getting an interrupt from the device to Host */ -/* The user function must return without blocking to prevent a delay on the event handling */ -/* -#define _SlSyncWaitLoopCallback UserSleepFunction -*/ - - - -#define NONOS_WAIT_FOREVER 0xFF -#define NONOS_NO_WAIT 0x00 - -#define NONOS_RET_OK (0) -#define NONOS_RET_ERR (0xFF) -#define OSI_OK NONOS_RET_OK - -#define __NON_OS_SYNC_OBJ_CLEAR_VALUE 0x11 -#define __NON_OS_SYNC_OBJ_SIGNAL_VALUE 0x22 -#define __NON_OS_LOCK_OBJ_UNLOCK_VALUE 0x33 -#define __NON_OS_LOCK_OBJ_LOCK_VALUE 0x44 - -/*! - \brief type definition for the return values of this adaptation layer -*/ -typedef _i8 _SlNonOsRetVal_t; - -/*! - \brief type definition for a time value -*/ -typedef _u8 _SlNonOsTime_t; - -/*! - \brief type definition for a sync object container - - Sync object is object used to synchronize between two threads or thread and interrupt handler. - One thread is waiting on the object and the other thread send a signal, which then - release the waiting thread. - The signal must be able to be sent from interrupt context. - This object is generally implemented by binary semaphore or events. -*/ -typedef _u8 _SlNonOsSemObj_t; - - -#define _SlTime_t _SlNonOsTime_t - -#define _SlSyncObj_t _SlNonOsSemObj_t - -#define _SlLockObj_t _SlNonOsSemObj_t - -#define SL_OS_WAIT_FOREVER NONOS_WAIT_FOREVER - -#define SL_OS_RET_CODE_OK NONOS_RET_OK - -#define SL_OS_NO_WAIT NONOS_NO_WAIT - - - - - -/*! - \brief This function creates a sync object - - The sync object is used for synchronization between different thread or ISR and - a thread. - - \param pSyncObj - pointer to the sync object control block - - \return upon successful creation the function return 0 - Otherwise, a negative value indicating the error code shall be returned - \note - \warning -*/ -#define _SlNonOsSyncObjCreate(pSyncObj) _SlNonOsSemSet(pSyncObj,__NON_OS_SYNC_OBJ_CLEAR_VALUE) - -/*! - \brief This function deletes a sync object - - \param pSyncObj - pointer to the sync object control block - - \return upon successful deletion the function should return 0 - Otherwise, a negative value indicating the error code shall be returned - \note - \warning -*/ -#define _SlNonOsSyncObjDelete(pSyncObj) _SlNonOsSemSet(pSyncObj,0) - -/*! - \brief This function generates a sync signal for the object. - - All suspended threads waiting on this sync object are resumed - - \param pSyncObj - pointer to the sync object control block - - \return upon successful signaling the function should return 0 - Otherwise, a negative value indicating the error code shall be returned - \note the function could be called from ISR context - \warning -*/ -#define _SlNonOsSyncObjSignal(pSyncObj) _SlNonOsSemSet(pSyncObj,__NON_OS_SYNC_OBJ_SIGNAL_VALUE) - -/*! - \brief This function waits for a sync signal of the specific sync object - - \param pSyncObj - pointer to the sync object control block - \param Timeout - numeric value specifies the maximum number of mSec to - stay suspended while waiting for the sync signal - Currently, the simple link driver uses only two values: - - NONOS_WAIT_FOREVER - - NONOS_NO_WAIT - - \return upon successful reception of the signal within the timeout window return 0 - Otherwise, a negative value indicating the error code shall be returned - \note - \warning -*/ -#define _SlNonOsSyncObjWait(pSyncObj , Timeout) _SlNonOsSemGet(pSyncObj,__NON_OS_SYNC_OBJ_SIGNAL_VALUE,__NON_OS_SYNC_OBJ_CLEAR_VALUE,Timeout) - -/*! - \brief This function clears a sync object - - \param pSyncObj - pointer to the sync object control block - - \return upon successful clearing the function should return 0 - Otherwise, a negative value indicating the error code shall be returned - \note - \warning -*/ -#define _SlNonOsSyncObjClear(pSyncObj) _SlNonOsSemSet(pSyncObj,__NON_OS_SYNC_OBJ_CLEAR_VALUE) - -/*! - \brief This function creates a locking object. - - The locking object is used for protecting a shared resources between different - threads. - - \param pLockObj - pointer to the locking object control block - - \return upon successful creation the function should return 0 - Otherwise, a negative value indicating the error code shall be returned - \note - \warning -*/ -#define _SlNonOsLockObjCreate(pLockObj) _SlNonOsSemSet(pLockObj,__NON_OS_LOCK_OBJ_UNLOCK_VALUE) - -/*! - \brief This function deletes a locking object. - - \param pLockObj - pointer to the locking object control block - - \return upon successful deletion the function should return 0 - Otherwise, a negative value indicating the error code shall be returned - \note - \warning -*/ -#define _SlNonOsLockObjDelete(pLockObj) _SlNonOsSemSet(pLockObj,0) - -/*! - \brief This function locks a locking object. - - All other threads that call this function before this thread calls - the _SlNonOsLockObjUnlock would be suspended - - \param pLockObj - pointer to the locking object control block - \param Timeout - numeric value specifies the maximum number of mSec to - stay suspended while waiting for the locking object - Currently, the simple link driver uses only two values: - - NONOS_WAIT_FOREVER - - NONOS_NO_WAIT - - - \return upon successful reception of the locking object the function should return 0 - Otherwise, a negative value indicating the error code shall be returned - \note - \warning -*/ -#define _SlNonOsLockObjLock(pLockObj , Timeout) _SlNonOsSemGet(pLockObj,__NON_OS_LOCK_OBJ_UNLOCK_VALUE,__NON_OS_LOCK_OBJ_LOCK_VALUE,Timeout) - -/*! - \brief This function unlock a locking object. - - \param pLockObj - pointer to the locking object control block - - \return upon successful unlocking the function should return 0 - Otherwise, a negative value indicating the error code shall be returned - \note - \warning -*/ -#define _SlNonOsLockObjUnlock(pLockObj) _SlNonOsSemSet(pLockObj,__NON_OS_LOCK_OBJ_UNLOCK_VALUE) - - -/*! - \brief This function call the pEntry callback from a different context - - \param pEntry - pointer to the entry callback function - - \param pValue - pointer to any type of memory structure that would be - passed to pEntry callback from the execution thread. - - \param flags - execution flags - reserved for future usage - - \return upon successful registration of the spawn the function return 0 - (the function is not blocked till the end of the execution of the function - and could be returned before the execution is actually completed) - Otherwise, a negative value indicating the error code shall be returned - \note - \warning -*/ -_SlNonOsRetVal_t _SlNonOsSpawn(_SlSpawnEntryFunc_t pEntry , void* pValue , _u32 flags); - - -/*! - \brief This function must be called from the main loop in non-os paltforms - - \param None - - \return 0 - No more activities - 1 - Activity still in progress - \note - \warning -*/ -_SlNonOsRetVal_t _SlNonOsMainLoopTask(void); - -extern _SlNonOsRetVal_t _SlNonOsSemGet(_SlNonOsSemObj_t* pSyncObj, _SlNonOsSemObj_t WaitValue, _SlNonOsSemObj_t SetValue, _SlNonOsTime_t Timeout); -extern _SlNonOsRetVal_t _SlNonOsSemSet(_SlNonOsSemObj_t* pSemObj , _SlNonOsSemObj_t Value); -extern _SlNonOsRetVal_t _SlNonOsSpawn(_SlSpawnEntryFunc_t pEntry , void* pValue , _u32 flags); - -#if (defined(_SlSyncWaitLoopCallback)) -extern void _SlSyncWaitLoopCallback(void); -#endif - - -/***************************************************************************** - - Overwrite SimpleLink driver OS adaptation functions - - - *****************************************************************************/ - -#undef sl_SyncObjCreate -#define sl_SyncObjCreate(pSyncObj,pName) _SlNonOsSemSet(pSyncObj,__NON_OS_SYNC_OBJ_CLEAR_VALUE) - -#undef sl_SyncObjDelete -#define sl_SyncObjDelete(pSyncObj) _SlNonOsSemSet(pSyncObj,0) - -#undef sl_SyncObjSignal -#define sl_SyncObjSignal(pSyncObj) _SlNonOsSemSet(pSyncObj,__NON_OS_SYNC_OBJ_SIGNAL_VALUE) - -#undef sl_SyncObjSignalFromIRQ -#define sl_SyncObjSignalFromIRQ(pSyncObj) _SlNonOsSemSet(pSyncObj,__NON_OS_SYNC_OBJ_SIGNAL_VALUE) - -#undef sl_SyncObjWait -#define sl_SyncObjWait(pSyncObj,Timeout) _SlNonOsSemGet(pSyncObj,__NON_OS_SYNC_OBJ_SIGNAL_VALUE,__NON_OS_SYNC_OBJ_CLEAR_VALUE,Timeout) - -#undef sl_LockObjCreate -#define sl_LockObjCreate(pLockObj,pName) _SlNonOsSemSet(pLockObj,__NON_OS_LOCK_OBJ_UNLOCK_VALUE) - -#undef sl_LockObjDelete -#define sl_LockObjDelete(pLockObj) _SlNonOsSemSet(pLockObj,0) - -#undef sl_LockObjLock -#define sl_LockObjLock(pLockObj,Timeout) _SlNonOsSemGet(pLockObj,__NON_OS_LOCK_OBJ_UNLOCK_VALUE,__NON_OS_LOCK_OBJ_LOCK_VALUE,Timeout) - -#undef sl_LockObjUnlock -#define sl_LockObjUnlock(pLockObj) _SlNonOsSemSet(pLockObj,__NON_OS_LOCK_OBJ_UNLOCK_VALUE) - -#undef sl_Spawn -#define sl_Spawn(pEntry,pValue,flags) _SlNonOsSpawn(pEntry,pValue,flags) - -#undef _SlTaskEntry -#define _SlTaskEntry _SlNonOsMainLoopTask - -#endif /* !SL_PLATFORM_MULTI_THREADED */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif diff --git a/drivers/cc3100/inc/objInclusion.h b/drivers/cc3100/inc/objInclusion.h deleted file mode 100644 index cfe875e76e..0000000000 --- a/drivers/cc3100/inc/objInclusion.h +++ /dev/null @@ -1,322 +0,0 @@ -/* - * objInclusion.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - -#include - -#ifndef OBJINCLUSION_H_ -#define OBJINCLUSION_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -/****************************************************************************** - - For future use - -*******************************************************************************/ - -#define __inln /* if inline functions requiered: #define __inln inline */ - -#define SL_DEVICE /* Device silo is currently always mandatory */ - - - -/****************************************************************************** - - Qualifiers for package customizations - -*******************************************************************************/ - -#if defined (SL_DEVICE) -#define __dev 1 -#else -#define __dev 0 -#endif - -#if defined (SL_DEVICE) && defined (SL_INC_EXT_API) -#define __dev__ext 1 -#else -#define __dev__ext 0 -#endif - - -#if (!defined (SL_PLATFORM_MULTI_THREADED)) || (!defined (SL_PLATFORM_EXTERNAL_SPAWN)) -#define __int__spwn 1 -#else -#define __int__spwn 0 -#endif - -#if defined (SL_INC_NET_APP_PKG) -#define __nap 1 -#else -#define __nap 0 -#endif - -#if defined (SL_INC_NET_APP_PKG) && defined (SL_INC_SOCK_CLIENT_SIDE_API) -#define __nap__clt 1 -#else -#define __nap__clt 0 -#endif - -#if defined (SL_INC_NET_APP_PKG) && defined (SL_INC_EXT_API) -#define __nap__ext 1 -#else -#define __nap__ext 0 -#endif - -#if defined (SL_INC_NET_CFG_PKG) -#define __ncg 1 -#else -#define __ncg 0 -#endif - -#if defined (SL_INC_NET_CFG_PKG) && defined (SL_INC_EXT_API) -#define __ncg__ext 1 -#else -#define __ncg__ext 0 -#endif - -#if defined (SL_INC_NVMEM_PKG) -#define __nvm 1 -#else -#define __nvm 0 -#endif - -#if defined (SL_INC_SOCKET_PKG) -#define __sck 1 -#else -#define __sck 0 -#endif - -#if defined (SL_INC_SOCKET_PKG) && defined (SL_INC_EXT_API) -#define __sck__ext 1 -#else -#define __sck__ext 0 -#endif - -#if defined (SL_INC_SOCKET_PKG) && defined (SL_INC_SOCK_SERVER_SIDE_API) -#define __sck__srv 1 -#else -#define __sck__srv 0 -#endif - -#if defined (SL_INC_SOCKET_PKG) && defined (SL_INC_SOCK_CLIENT_SIDE_API) -#define __sck__clt 1 -#else -#define __sck__clt 0 -#endif - -#if defined (SL_INC_SOCKET_PKG) && defined (SL_INC_SOCK_RECV_API) -#define __sck__rcv 1 -#else -#define __sck__rcv 0 -#endif - -#if defined (SL_INC_SOCKET_PKG) && defined (SL_INC_SOCK_SEND_API) -#define __sck__snd 1 -#else -#define __sck__snd 0 -#endif - -#if defined (SL_INC_WLAN_PKG) -#define __wln 1 -#else -#define __wln 0 -#endif - -#if defined (SL_INC_WLAN_PKG) && defined (SL_INC_EXT_API) -#define __wln__ext 1 -#else -#define __wln__ext 0 -#endif - -/* The return 1 is the function need to be included in the output */ -#define _SL_INCLUDE_FUNC(Name) (_SL_INC_##Name) - -/* Driver */ -#define _SL_INC_sl_NetAppStart __nap__ext -#define _SL_INC_sl_NetAppStop __nap__ext - -#define _SL_INC_sl_NetAppDnsGetHostByName __nap__clt - - -#define _SL_INC_sl_NetAppDnsGetHostByService __nap__ext -#define _SL_INC_sl_NetAppMDNSRegisterService __nap__ext -#define _SL_INC_sl_NetAppMDNSUnRegisterService __nap__ext -#define _SL_INC_sl_NetAppMDNSRegisterUnregisterService __nap__ext -#define _SL_INC_sl_NetAppGetServiceList __nap__ext - - -#define _SL_INC_sl_DnsGetHostByAddr __nap__ext -#define _SL_INC_sl_NetAppPingStart __nap__ext -#define _SL_INC_sl_NetAppPingReport __nap__ext -#define _SL_INC_sl_NetAppSet __nap__ext -#define _SL_INC_sl_NetAppGet __nap__ext - - -/* FS */ -#define _SL_INC_sl_FsOpen __nvm - -#define _SL_INC_sl_FsClose __nvm - -#define _SL_INC_sl_FsRead __nvm - -#define _SL_INC_sl_FsWrite __nvm - -#define _SL_INC_sl_FsGetInfo __nvm - -#define _SL_INC_sl_FsDel __nvm - -/* netcfg */ -#define _SL_INC_sl_MacAdrrSet __ncg - -#define _SL_INC_sl_MacAdrrGet __ncg - -#define _SL_INC_sl_NetCfgGet __ncg - -#define _SL_INC_sl_NetCfgSet __ncg - - -/* socket */ -#define _SL_INC_sl_Socket __sck - -#define _SL_INC_sl_Close __sck - -#define _SL_INC_sl_Accept __sck__srv - -#define _SL_INC_sl_Bind __sck - -#define _SL_INC_sl_Listen __sck__srv - -#define _SL_INC_sl_Connect __sck__clt - -#define _SL_INC_sl_Select __sck - -#define _SL_INC_sl_SetSockOpt __sck - -#define _SL_INC_sl_GetSockOpt __sck__ext - -#define _SL_INC_sl_Recv __sck__rcv - -#define _SL_INC_sl_RecvFrom __sck__rcv - -#define _SL_INC_sl_Write __sck__snd - -#define _SL_INC_sl_Send __sck__snd - -#define _SL_INC_sl_SendTo __sck__snd - -#define _SL_INC_sl_Htonl __sck - -#define _SL_INC_sl_Htons __sck - -/* wlan */ -#define _SL_INC_sl_WlanConnect __wln__ext - -#define _SL_INC_sl_WlanDisconnect __wln__ext - -#define _SL_INC_sl_WlanProfileAdd __wln__ext - -#define _SL_INC_sl_WlanProfileGet __wln__ext - -#define _SL_INC_sl_WlanProfileDel __wln__ext - -#define _SL_INC_sl_WlanPolicySet __wln__ext - -#define _SL_INC_sl_WlanPolicyGet __wln__ext - -#define _SL_INC_sl_WlanGetNetworkList __wln__ext - -#define _SL_INC_sl_WlanRxFilterAdd __wln__ext - -#define _SL_INC_sl_WlanRxFilterSet __wln__ext - -#define _SL_INC_sl_WlanRxFilterGet __wln__ext - -#define _SL_INC_sl_SmartConfigStart __wln - -#define _SL_INC_sl_SmartConfigOptSet __wln__ext - - -#define _SL_INC_sl_WlanSmartConfigStart __wln - -#define _SL_INC_sl_WlanSmartConfigStop __wln - -#define _SL_INC_sl_WlanSetMode __wln - -#define _SL_INC_sl_WlanSet __wln - -#define _SL_INC_sl_WlanGet __wln - -#define _SL_INC_sl_SmartConfigOptSet __wln__ext - -#define _SL_INC_sl_SmartConfigOptGet __wln__ext - -#define _SL_INC_sl_WlanRxStatStart __wln__ext - -#define _SL_INC_sl_WlanRxStatStop __wln__ext - -#define _SL_INC_sl_WlanRxStatGet __wln__ext - - -/* device */ -#define _SL_INC_sl_Task __int__spwn - -#define _SL_INC_sl_Start __dev - -#define _SL_INC_sl_Stop __dev - -#define _SL_INC_sl_StatusGet __dev - -#ifdef SL_IF_TYPE_UART -#define _SL_INC_sl_UartSetMode __dev__ext -#endif - -#define _SL_INC_sl_EventMaskGet __dev__ext - -#define _SL_INC_sl_EventMaskSet __dev__ext - -#define _SL_INC_sl_DevGet __dev__ext - -#define _SL_INC_sl_DevSet __dev__ext - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /*OBJINCLUSION_H_ */ diff --git a/drivers/cc3100/inc/protocol.h b/drivers/cc3100/inc/protocol.h deleted file mode 100644 index 8a1299a6ab..0000000000 --- a/drivers/cc3100/inc/protocol.h +++ /dev/null @@ -1,1182 +0,0 @@ -/* - * protocol.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - -/*******************************************************************************\ -* -* FILE NAME: protocol.h -* -* DESCRIPTION: Constant and data structure definitions and function -* prototypes for the SL protocol module, which implements -* processing of SimpleLink Commands. -* -* AUTHOR: -* -\*******************************************************************************/ - -#ifndef _SL_PROTOCOL_TYPES_H_ -#define _SL_PROTOCOL_TYPES_H_ - -/**************************************************************************** -** -** User I/F pools definitions -** -****************************************************************************/ - -/**************************************************************************** -** -** Definitions for SimpleLink Commands -** -****************************************************************************/ - - -/* pattern for LE 8/16/32 or BE*/ -#define H2N_SYNC_PATTERN {0xBBDDEEFF,0x4321,0x34,0x12} -#define H2N_CNYS_PATTERN {0xBBDDEEFF,0x8765,0x78,0x56} - -#define H2N_DUMMY_PATTERN (_u32)0xFFFFFFFF -#define N2H_SYNC_PATTERN (_u32)0xABCDDCBA -#define SYNC_PATTERN_LEN (_u32)sizeof(_u32) -#define UART_SET_MODE_MAGIC_CODE (_u32)0xAA55AA55 -#define SPI_16BITS_BUG(pattern) (_u32)((_u32)pattern & (_u32)0xFFFF7FFF) -#define SPI_8BITS_BUG(pattern) (_u32)((_u32)pattern & (_u32)0xFFFFFF7F) - - - -typedef struct -{ - _u16 Opcode; - _u16 Len; -}_SlGenericHeader_t; - - -typedef struct -{ - _u32 Long; - _u16 Short; - _u8 Byte1; - _u8 Byte2; -}_SlSyncPattern_t; - -typedef _SlGenericHeader_t _SlCommandHeader_t; - -typedef struct -{ - _SlGenericHeader_t GenHeader; - _u8 TxPoolCnt; - _u8 DevStatus; - _u8 SocketTXFailure; - _u8 SocketNonBlocking; -}_SlResponseHeader_t; - -#define _SL_RESP_SPEC_HDR_SIZE (sizeof(_SlResponseHeader_t) - sizeof(_SlGenericHeader_t)) -#define _SL_RESP_HDR_SIZE sizeof(_SlResponseHeader_t) -#define _SL_CMD_HDR_SIZE sizeof(_SlCommandHeader_t) - -#define _SL_RESP_ARGS_START(_pMsg) (((_SlResponseHeader_t *)(_pMsg)) + 1) - -/* Used only in NWP! */ -typedef struct -{ - _SlCommandHeader_t sl_hdr; - _u8 func_args_start; -} T_SCMD; - - -#define WLAN_CONN_STATUS_BIT 0x01 -#define EVENTS_Q_STATUS_BIT 0x02 -#define PENDING_RCV_CMD_BIT 0x04 -#define FW_BUSY_PACKETS_BIT 0x08 - -#define INIT_STA_OK 0x11111111 -#define INIT_STA_ERR 0x22222222 -#define INIT_AP_OK 0x33333333 -#define INIT_AP_ERR 0x44444444 -#define INIT_P2P_OK 0x55555555 -#define INIT_P2P_ERR 0x66666666 - -/**************************************************************************** -** OPCODES -****************************************************************************/ -#define SL_IPV4_IPV6_OFFSET ( 9 ) -#define SL_OPCODE_IPV4 ( 0x0 << SL_IPV4_IPV6_OFFSET ) -#define SL_OPCODE_IPV6 ( 0x1 << SL_IPV4_IPV6_OFFSET ) - -#define SL_SYNC_ASYNC_OFFSET ( 10 ) -#define SL_OPCODE_SYNC (0x1 << SL_SYNC_ASYNC_OFFSET ) -#define SL_OPCODE_SILO_OFFSET ( 11 ) -#define SL_OPCODE_SILO_MASK ( 0xF << SL_OPCODE_SILO_OFFSET ) -#define SL_OPCODE_SILO_DEVICE ( 0x0 << SL_OPCODE_SILO_OFFSET ) -#define SL_OPCODE_SILO_WLAN ( 0x1 << SL_OPCODE_SILO_OFFSET ) -#define SL_OPCODE_SILO_SOCKET ( 0x2 << SL_OPCODE_SILO_OFFSET ) -#define SL_OPCODE_SILO_NETAPP ( 0x3 << SL_OPCODE_SILO_OFFSET ) -#define SL_OPCODE_SILO_NVMEM ( 0x4 << SL_OPCODE_SILO_OFFSET ) -#define SL_OPCODE_SILO_NETCFG ( 0x5 << SL_OPCODE_SILO_OFFSET ) - -#define SL_FAMILY_SHIFT (0x4) -#define SL_FLAGS_MASK (0xF) - -#define SL_OPCODE_DEVICE_INITCOMPLETE 0x0008 -#define SL_OPCODE_DEVICE_ABORT 0x000C -#define SL_OPCODE_DEVICE_STOP_COMMAND 0x8473 -#define SL_OPCODE_DEVICE_STOP_RESPONSE 0x0473 -#define SL_OPCODE_DEVICE_STOP_ASYNC_RESPONSE 0x0073 -#define SL_OPCODE_DEVICE_DEVICEASYNCDUMMY 0x0063 - -#define SL_OPCODE_DEVICE_VERSIONREADCOMMAND 0x8470 -#define SL_OPCODE_DEVICE_VERSIONREADRESPONSE 0x0470 -#define SL_OPCODE_DEVICE_DEVICEASYNCFATALERROR 0x0078 -#define SL_OPCODE_WLAN_WLANCONNECTCOMMAND 0x8C80 -#define SL_OPCODE_WLAN_WLANCONNECTRESPONSE 0x0C80 -#define SL_OPCODE_WLAN_WLANASYNCCONNECTEDRESPONSE 0x0880 -#define SL_OPCODE_WLAN_P2P_DEV_FOUND 0x0830 -#define SL_OPCODE_WLAN_CONNECTION_FAILED 0x0831 -#define SL_OPCODE_WLAN_P2P_NEG_REQ_RECEIVED 0x0832 - -#define SL_OPCODE_WLAN_WLANDISCONNECTCOMMAND 0x8C81 -#define SL_OPCODE_WLAN_WLANDISCONNECTRESPONSE 0x0C81 -#define SL_OPCODE_WLAN_WLANASYNCDISCONNECTEDRESPONSE 0x0881 -#define SL_OPCODE_WLAN_WLANCONNECTEAPCOMMAND 0x8C82 -#define SL_OPCODE_WLAN_WLANCONNECTEAPCRESPONSE 0x0C82 -#define SL_OPCODE_WLAN_PROFILEADDCOMMAND 0x8C83 -#define SL_OPCODE_WLAN_PROFILEADDRESPONSE 0x0C83 -#define SL_OPCODE_WLAN_PROFILEGETCOMMAND 0x8C84 -#define SL_OPCODE_WLAN_PROFILEGETRESPONSE 0x0C84 -#define SL_OPCODE_WLAN_PROFILEDELCOMMAND 0x8C85 -#define SL_OPCODE_WLAN_PROFILEDELRESPONSE 0x0C85 -#define SL_OPCODE_WLAN_POLICYSETCOMMAND 0x8C86 -#define SL_OPCODE_WLAN_POLICYSETRESPONSE 0x0C86 -#define SL_OPCODE_WLAN_POLICYGETCOMMAND 0x8C87 -#define SL_OPCODE_WLAN_POLICYGETRESPONSE 0x0C87 -#define SL_OPCODE_WLAN_FILTERADD 0x8C88 -#define SL_OPCODE_WLAN_FILTERADDRESPONSE 0x0C88 -#define SL_OPCODE_WLAN_FILTERGET 0x8C89 -#define SL_OPCODE_WLAN_FILTERGETRESPONSE 0x0C89 -#define SL_OPCODE_WLAN_FILTERDELETE 0x8C8A -#define SL_OPCODE_WLAN_FILTERDELETERESPOSNE 0x0C8A -#define SL_OPCODE_WLAN_WLANGETSTATUSCOMMAND 0x8C8F -#define SL_OPCODE_WLAN_WLANGETSTATUSRESPONSE 0x0C8F -#define SL_OPCODE_WLAN_STARTTXCONTINUESCOMMAND 0x8CAA -#define SL_OPCODE_WLAN_STARTTXCONTINUESRESPONSE 0x0CAA -#define SL_OPCODE_WLAN_STOPTXCONTINUESCOMMAND 0x8CAB -#define SL_OPCODE_WLAN_STOPTXCONTINUESRESPONSE 0x0CAB -#define SL_OPCODE_WLAN_STARTRXSTATCOMMAND 0x8CAC -#define SL_OPCODE_WLAN_STARTRXSTATRESPONSE 0x0CAC -#define SL_OPCODE_WLAN_STOPRXSTATCOMMAND 0x8CAD -#define SL_OPCODE_WLAN_STOPRXSTATRESPONSE 0x0CAD -#define SL_OPCODE_WLAN_GETRXSTATCOMMAND 0x8CAF -#define SL_OPCODE_WLAN_GETRXSTATRESPONSE 0x0CAF -#define SL_OPCODE_WLAN_POLICYSETCOMMANDNEW 0x8CB0 -#define SL_OPCODE_WLAN_POLICYSETRESPONSENEW 0x0CB0 -#define SL_OPCODE_WLAN_POLICYGETCOMMANDNEW 0x8CB1 -#define SL_OPCODE_WLAN_POLICYGETRESPONSENEW 0x0CB1 - -#define SL_OPCODE_WLAN_SMART_CONFIG_START_COMMAND 0x8CB2 -#define SL_OPCODE_WLAN_SMART_CONFIG_START_RESPONSE 0x0CB2 -#define SL_OPCODE_WLAN_SMART_CONFIG_START_ASYNC_RESPONSE 0x08B2 -#define SL_OPCODE_WLAN_SMART_CONFIG_STOP_COMMAND 0x8CB3 -#define SL_OPCODE_WLAN_SMART_CONFIG_STOP_RESPONSE 0x0CB3 -#define SL_OPCODE_WLAN_SMART_CONFIG_STOP_ASYNC_RESPONSE 0x08B3 -#define SL_OPCODE_WLAN_SET_MODE 0x8CB4 -#define SL_OPCODE_WLAN_SET_MODE_RESPONSE 0x0CB4 -#define SL_OPCODE_WLAN_CFG_SET 0x8CB5 -#define SL_OPCODE_WLAN_CFG_SET_RESPONSE 0x0CB5 -#define SL_OPCODE_WLAN_CFG_GET 0x8CB6 -#define SL_OPCODE_WLAN_CFG_GET_RESPONSE 0x0CB6 -#define SL_OPCODE_WLAN_STA_CONNECTED 0x082E -#define SL_OPCODE_WLAN_STA_DISCONNECTED 0x082F -#define SL_OPCODE_WLAN_EAP_PROFILEADDCOMMAND 0x8C67 -#define SL_OPCODE_WLAN_EAP_PROFILEADDCOMMAND_RESPONSE 0x0C67 - -#define SL_OPCODE_SOCKET_SOCKET 0x9401 -#define SL_OPCODE_SOCKET_SOCKETRESPONSE 0x1401 -#define SL_OPCODE_SOCKET_CLOSE 0x9402 -#define SL_OPCODE_SOCKET_CLOSERESPONSE 0x1402 -#define SL_OPCODE_SOCKET_ACCEPT 0x9403 -#define SL_OPCODE_SOCKET_ACCEPTRESPONSE 0x1403 -#define SL_OPCODE_SOCKET_ACCEPTASYNCRESPONSE 0x1003 -#define SL_OPCODE_SOCKET_ACCEPTASYNCRESPONSE_V6 0x1203 -#define SL_OPCODE_SOCKET_BIND 0x9404 -#define SL_OPCODE_SOCKET_BIND_V6 0x9604 -#define SL_OPCODE_SOCKET_BINDRESPONSE 0x1404 -#define SL_OPCODE_SOCKET_LISTEN 0x9405 -#define SL_OPCODE_SOCKET_LISTENRESPONSE 0x1405 -#define SL_OPCODE_SOCKET_CONNECT 0x9406 -#define SL_OPCODE_SOCKET_CONNECT_V6 0x9606 -#define SL_OPCODE_SOCKET_CONNECTRESPONSE 0x1406 -#define SL_OPCODE_SOCKET_CONNECTASYNCRESPONSE 0x1006 -#define SL_OPCODE_SOCKET_SELECT 0x9407 -#define SL_OPCODE_SOCKET_SELECTRESPONSE 0x1407 -#define SL_OPCODE_SOCKET_SELECTASYNCRESPONSE 0x1007 -#define SL_OPCODE_SOCKET_SETSOCKOPT 0x9408 -#define SL_OPCODE_SOCKET_SETSOCKOPTRESPONSE 0x1408 -#define SL_OPCODE_SOCKET_GETSOCKOPT 0x9409 -#define SL_OPCODE_SOCKET_GETSOCKOPTRESPONSE 0x1409 -#define SL_OPCODE_SOCKET_RECV 0x940A -#define SL_OPCODE_SOCKET_RECVASYNCRESPONSE 0x100A -#define SL_OPCODE_SOCKET_RECVFROM 0x940B -#define SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE 0x100B -#define SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE_V6 0x120B -#define SL_OPCODE_SOCKET_SEND 0x940C -#define SL_OPCODE_SOCKET_SENDTO 0x940D -#define SL_OPCODE_SOCKET_SENDTO_V6 0x960D -#define SL_OPCODE_SOCKET_TXFAILEDASYNCRESPONSE 0x100E -#define SL_OPCODE_SOCKET_SOCKETASYNCEVENT 0x100F -#define SL_OPCODE_NETAPP_START_COMMAND 0x9C0A -#define SL_OPCODE_NETAPP_START_RESPONSE 0x1C0A -#define SL_OPCODE_NETAPP_NETAPPSTARTRESPONSE 0x1C0A -#define SL_OPCODE_NETAPP_STOP_COMMAND 0x9C61 -#define SL_OPCODE_NETAPP_STOP_RESPONSE 0x1C61 -#define SL_OPCODE_NETAPP_NETAPPSET 0x9C0B -#define SL_OPCODE_NETAPP_NETAPPSETRESPONSE 0x1C0B -#define SL_OPCODE_NETAPP_NETAPPGET 0x9C27 -#define SL_OPCODE_NETAPP_NETAPPGETRESPONSE 0x1C27 -#define SL_OPCODE_NETAPP_DNSGETHOSTBYNAME 0x9C20 -#define SL_OPCODE_NETAPP_DNSGETHOSTBYNAMERESPONSE 0x1C20 -#define SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE 0x1820 -#define SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE_V6 0x1A20 -#define SL_OPCODE_NETAPP_NETAPP_MDNS_LOOKUP_SERVICE 0x9C71 -#define SL_OPCODE_NETAPP_NETAPP_MDNS_LOOKUP_SERVICE_RESPONSE 0x1C72 -#define SL_OPCODE_NETAPP_MDNSREGISTERSERVICE 0x9C34 -#define SL_OPCODE_NETAPP_MDNSREGISTERSERVICERESPONSE 0x1C34 -#define SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICE 0x9C35 -#define SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICERESPONSE 0x1C35 -#define SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICEASYNCRESPONSE 0x1835 -#define SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICEASYNCRESPONSE_V6 0x1A35 -#define SL_OPCODE_NETAPP_DNSGETHOSTBYADDR 0x9C26 -#define SL_OPCODE_NETAPP_DNSGETHOSTBYADDR_V6 0x9E26 -#define SL_OPCODE_NETAPP_DNSGETHOSTBYADDRRESPONSE 0x1C26 -#define SL_OPCODE_NETAPP_DNSGETHOSTBYADDRASYNCRESPONSE 0x1826 -#define SL_OPCODE_NETAPP_PINGSTART 0x9C21 -#define SL_OPCODE_NETAPP_PINGSTART_V6 0x9E21 -#define SL_OPCODE_NETAPP_PINGSTARTRESPONSE 0x1C21 -#define SL_OPCODE_NETAPP_PINGREPORTREQUEST 0x9C22 -#define SL_OPCODE_NETAPP_PINGREPORTREQUESTRESPONSE 0x1822 -#define SL_OPCODE_NETAPP_PINGSTOP 0x9C23 -#define SL_OPCODE_NETAPP_PINGSTOPRESPONSE 0x1C23 -#define SL_OPCODE_NETAPP_ARPFLUSH 0x9C24 -#define SL_OPCODE_NETAPP_ARPFLUSHRESPONSE 0x1C24 -#define SL_OPCODE_NETAPP_IPACQUIRED 0x1825 -#define SL_OPCODE_NETAPP_IPV4_LOST 0x1832 -#define SL_OPCODE_NETAPP_DHCP_IPV4_ACQUIRE_TIMEOUT 0x1833 -#define SL_OPCODE_NETAPP_IPACQUIRED_V6 0x1A25 -#define SL_OPCODE_NETAPP_IPERFSTARTCOMMAND 0x9C28 -#define SL_OPCODE_NETAPP_IPERFSTARTRESPONSE 0x1C28 -#define SL_OPCODE_NETAPP_IPERFSTOPCOMMAND 0x9C29 -#define SL_OPCODE_NETAPP_IPERFSTOPRESPONSE 0x1C29 -#define SL_OPCODE_NETAPP_CTESTSTARTCOMMAND 0x9C2A -#define SL_OPCODE_NETAPP_CTESTSTARTRESPONSE 0x1C2A -#define SL_OPCODE_NETAPP_CTESTASYNCRESPONSE 0x182A -#define SL_OPCODE_NETAPP_CTESTSTOPCOMMAND 0x9C2B -#define SL_OPCODE_NETAPP_CTESTSTOPRESPONSE 0x1C2B -#define SL_OPCODE_NETAPP_IP_LEASED 0x182C -#define SL_OPCODE_NETAPP_IP_RELEASED 0x182D -#define SL_OPCODE_NETAPP_HTTPGETTOKENVALUE 0x182E -#define SL_OPCODE_NETAPP_HTTPSENDTOKENVALUE 0x9C2F -#define SL_OPCODE_NETAPP_HTTPPOSTTOKENVALUE 0x1830 -#define SL_OPCODE_NVMEM_FILEOPEN 0xA43C -#define SL_OPCODE_NVMEM_FILEOPENRESPONSE 0x243C -#define SL_OPCODE_NVMEM_FILECLOSE 0xA43D -#define SL_OPCODE_NVMEM_FILECLOSERESPONSE 0x243D -#define SL_OPCODE_NVMEM_FILEREADCOMMAND 0xA440 -#define SL_OPCODE_NVMEM_FILEREADRESPONSE 0x2440 -#define SL_OPCODE_NVMEM_FILEWRITECOMMAND 0xA441 -#define SL_OPCODE_NVMEM_FILEWRITERESPONSE 0x2441 -#define SL_OPCODE_NVMEM_FILEGETINFOCOMMAND 0xA442 -#define SL_OPCODE_NVMEM_FILEGETINFORESPONSE 0x2442 -#define SL_OPCODE_NVMEM_FILEDELCOMMAND 0xA443 -#define SL_OPCODE_NVMEM_FILEDELRESPONSE 0x2443 -#define SL_OPCODE_NVMEM_NVMEMFORMATCOMMAND 0xA444 -#define SL_OPCODE_NVMEM_NVMEMFORMATRESPONSE 0x2444 - -#define SL_OPCODE_DEVICE_SETDEBUGLEVELCOMMAND 0x846A -#define SL_OPCODE_DEVICE_SETDEBUGLEVELRESPONSE 0x046A - -#define SL_OPCODE_DEVICE_NETCFG_SET_COMMAND 0x8432 -#define SL_OPCODE_DEVICE_NETCFG_SET_RESPONSE 0x0432 -#define SL_OPCODE_DEVICE_NETCFG_GET_COMMAND 0x8433 -#define SL_OPCODE_DEVICE_NETCFG_GET_RESPONSE 0x0433 -/* */ -#define SL_OPCODE_DEVICE_SETUARTMODECOMMAND 0x846B -#define SL_OPCODE_DEVICE_SETUARTMODERESPONSE 0x046B -#define SL_OPCODE_DEVICE_SSISIZESETCOMMAND 0x846B -#define SL_OPCODE_DEVICE_SSISIZESETRESPONSE 0x046B - -/* */ -#define SL_OPCODE_DEVICE_EVENTMASKSET 0x8464 -#define SL_OPCODE_DEVICE_EVENTMASKSETRESPONSE 0x0464 -#define SL_OPCODE_DEVICE_EVENTMASKGET 0x8465 -#define SL_OPCODE_DEVICE_EVENTMASKGETRESPONSE 0x0465 - -#define SL_OPCODE_DEVICE_DEVICEGET 0x8466 -#define SL_OPCODE_DEVICE_DEVICEGETRESPONSE 0x0466 -#define SL_OPCODE_DEVICE_DEVICESET 0x84B7 -#define SL_OPCODE_DEVICE_DEVICESETRESPONSE 0x04B7 - -#define SL_OPCODE_WLAN_SCANRESULTSGETCOMMAND 0x8C8C -#define SL_OPCODE_WLAN_SCANRESULTSGETRESPONSE 0x0C8C -#define SL_OPCODE_WLAN_SMARTCONFIGOPTSET 0x8C8D -#define SL_OPCODE_WLAN_SMARTCONFIGOPTSETRESPONSE 0x0C8D -#define SL_OPCODE_WLAN_SMARTCONFIGOPTGET 0x8C8E -#define SL_OPCODE_WLAN_SMARTCONFIGOPTGETRESPONSE 0x0C8E - - -/* Rx Filters opcodes */ -#define SL_OPCODE_WLAN_WLANRXFILTERADDCOMMAND 0x8C6C -#define SL_OPCODE_WLAN_WLANRXFILTERADDRESPONSE 0x0C6C -#define SL_OPCODE_WLAN_WLANRXFILTERSETCOMMAND 0x8C6D -#define SL_OPCODE_WLAN_WLANRXFILTERSETRESPONSE 0x0C6D -#define SL_OPCODE_WLAN_WLANRXFILTERGETSTATISTICSINFOCOMMAND 0x8C6E -#define SL_OPCODE_WLAN_WLANRXFILTERGETSTATISTICSINFORESPONSE 0x0C6E -#define SL_OPCODE_WLAN_WLANRXFILTERGETCOMMAND 0x8C6F -#define SL_OPCODE_WLAN_WLANRXFILTERGETRESPONSE 0x0C6F -#define SL_OPCODE_WLAN_WLANRXFILTERGETINFO 0x8C70 -#define SL_OPCODE_WLAN_WLANRXFILTERGETINFORESPONSE 0x0C70 - - -/******************************************************************************************/ -/* Device structs */ -/******************************************************************************************/ -typedef _u32 InitStatus_t; - - -typedef struct -{ - _i32 Status; -}InitComplete_t; - -typedef struct -{ - _i16 status; - _u16 padding; - -}_BasicResponse_t; - -typedef struct -{ - _u16 Timeout; - _u16 padding; -}_DevStopCommand_t; - -typedef struct -{ - _u32 group; - _u32 mask; -}_DevMaskEventSetCommand_t; - -typedef _BasicResponse_t _DevMaskEventSetResponse_t; - - -typedef struct -{ - _u32 group; -}_DevMaskEventGetCommand_t; - - -typedef struct -{ - _u32 group; - _u32 mask; -}_DevMaskEventGetResponse_t; - - -typedef struct -{ - _u32 group; -}_DevStatusGetCommand_t; - - -typedef struct -{ - _u32 group; - _u32 status; -}_DevStatusGetResponse_t; - -typedef struct -{ - _u32 ChipId; - _u32 FwVersion[4]; - _u8 PhyVersion[4]; -}_Device_VersionReadResponsePart_t; - -typedef struct -{ - _Device_VersionReadResponsePart_t part; - _u32 NwpVersion[4]; - _u16 RomVersion; - _u16 Padding; -}_Device_VersionReadResponseFull_t; - - -typedef struct -{ - _u32 BaudRate; - _u8 FlowControlEnable; -}_DevUartSetModeCommand_t; - -typedef _BasicResponse_t _DevUartSetModeResponse_t; - -/******************************************************/ - -typedef struct -{ - _u8 SsiSizeInBytes; - _u8 Padding[3]; -}_StellarisSsiSizeSet_t; - -/*****************************************************************************************/ -/* WLAN structs */ -/*****************************************************************************************/ -#define MAXIMAL_PASSWORD_LENGTH (64) - -typedef struct{ - _u8 SecType; - _u8 SsidLen; - _u8 Bssid[6]; - _u8 PasswordLen; -}_WlanConnectCommon_t; - -#define SSID_STRING(pCmd) (_i8 *)((_WlanConnectCommon_t *)(pCmd) + 1) -#define PASSWORD_STRING(pCmd) (SSID_STRING(pCmd) + ((_WlanConnectCommon_t *)(pCmd))->SsidLen) - -typedef struct{ - _WlanConnectCommon_t Common; - _u8 UserLen; - _u8 AnonUserLen; - _u8 CertIndex; - _u32 EapBitmask; -}_WlanConnectEapCommand_t; - -#define EAP_SSID_STRING(pCmd) (_i8 *)((_WlanConnectEapCommand_t *)(pCmd) + 1) -#define EAP_PASSWORD_STRING(pCmd) (EAP_SSID_STRING(pCmd) + ((_WlanConnectEapCommand_t *)(pCmd))->Common.SsidLen) -#define EAP_USER_STRING(pCmd) (EAP_PASSWORD_STRING(pCmd) + ((_WlanConnectEapCommand_t *)(pCmd))->Common.PasswordLen) -#define EAP_ANON_USER_STRING(pCmd) (EAP_USER_STRING(pCmd) + ((_WlanConnectEapCommand_t *)(pCmd))->UserLen) - - -typedef struct -{ - _u8 PolicyType; - _u8 Padding; - _u8 PolicyOption; - _u8 PolicyOptionLen; -}_WlanPoliciySetGet_t; - - -typedef struct{ - _u32 minDwellTime; - _u32 maxDwellTime; - _u32 numProbeResponse; - _u32 G_Channels_mask; - _i32 rssiThershold; - _i32 snrThershold; - _i32 defaultTXPower; - _u16 intervalList[16]; -}_WlanScanParamSetCommand_t; - - -typedef struct{ - _i8 SecType; - _u8 SsidLen; - _u8 Priority; - _u8 Bssid[6]; - _u8 PasswordLen; - _u8 WepKeyId; -}_WlanAddGetProfile_t; - - -typedef struct{ - _WlanAddGetProfile_t Common; - _u8 UserLen; - _u8 AnonUserLen; - _u8 CertIndex; - _u16 padding; - _u32 EapBitmask; -}_WlanAddGetEapProfile_t; - - - - -#define PROFILE_SSID_STRING(pCmd) ((_i8 *)((_WlanAddGetProfile_t *)(pCmd) + 1)) -#define PROFILE_PASSWORD_STRING(pCmd) (PROFILE_SSID_STRING(pCmd) + ((_WlanAddGetProfile_t *)(pCmd))->SsidLen) - -#define EAP_PROFILE_SSID_STRING(pCmd) (_i8 *)((_WlanAddGetEapProfile_t *)(pCmd) + 1) -#define EAP_PROFILE_PASSWORD_STRING(pCmd) (EAP_PROFILE_SSID_STRING(pCmd) + ((_WlanAddGetEapProfile_t *)(pCmd))->Common.SsidLen) -#define EAP_PROFILE_USER_STRING(pCmd) (EAP_PROFILE_PASSWORD_STRING(pCmd) + ((_WlanAddGetEapProfile_t *)(pCmd))->Common.PasswordLen) -#define EAP_PROFILE_ANON_USER_STRING(pCmd) (EAP_PROFILE_USER_STRING(pCmd) + ((_WlanAddGetEapProfile_t *)(pCmd))->UserLen) - - - -typedef struct -{ - _u8 index; - _u8 padding[3]; -}_WlanProfileDelGetCommand_t; - -typedef _BasicResponse_t _WlanGetNetworkListResponse_t; - -typedef struct -{ - _u8 index; - _u8 count; - _i8 padding[2]; -}_WlanGetNetworkListCommand_t; - - - - -typedef struct -{ - _u32 groupIdBitmask; - _u8 cipher; - _u8 publicKeyLen; - _u8 group1KeyLen; - _u8 group2KeyLen; -}_WlanSmartConfigStartCommand_t; - -#define SMART_CONFIG_START_PUBLIC_KEY_STRING(pCmd) ((_i8 *)((_WlanSmartConfigStartCommand_t *)(pCmd) + 1)) -#define SMART_CONFIG_START_GROUP1_KEY_STRING(pCmd) ((_i8 *) (SMART_CONFIG_START_PUBLIC_KEY_STRING(pCmd) + ((_WlanSmartConfigStartCommand_t *)(pCmd))->publicKeyLen)) -#define SMART_CONFIG_START_GROUP2_KEY_STRING(pCmd) ((_i8 *) (SMART_CONFIG_START_GROUP1_KEY_STRING(pCmd) + ((_WlanSmartConfigStartCommand_t *)(pCmd))->group1KeyLen)) - - - -typedef struct -{ - _u8 mode; - _u8 padding[3]; -}_WlanSetMode_t; - - - - -typedef struct -{ - _u16 Status; - _u16 ConfigId; - _u16 ConfigOpt; - _u16 ConfigLen; -}_WlanCfgSetGet_t; - - -/* ******************************************************************************/ -/* RX filters - Start */ -/* ******************************************************************************/ -/* -- 80 bytes */ -typedef struct _WlanRxFilterAddCommand_t -{ - /* -- 1 byte */ - SlrxFilterRuleType_t RuleType; - /* -- 1 byte */ - SlrxFilterFlags_t FilterFlags; - /* -- 1 byte */ - SlrxFilterID_t FilterId; - /* -- 1 byte */ - _u8 Padding; - /* -- 56 byte */ - SlrxFilterRule_t Rule; - /* -- 12 byte ( 3 padding ) */ - SlrxFilterTrigger_t Trigger; - /* -- 8 byte */ - SlrxFilterAction_t Action; -}_WlanRxFilterAddCommand_t; - - - -/* -- 4 bytes */ -typedef struct l_WlanRxFilterAddCommandReponse_t -{ - /* -- 1 byte */ - SlrxFilterID_t FilterId; - /* -- 1 Byte */ - _u8 Status; - /* -- 2 byte */ - _u8 Padding[2]; - -}_WlanRxFilterAddCommandReponse_t; - - - -/* - * \struct _WlanRxFilterSetCommand_t - */ -typedef struct _WlanRxFilterSetCommand_t -{ - _u16 InputBufferLength; - /* 1 byte */ - SLrxFilterOperation_t RxFilterOperation; - _u8 Padding[1]; -}_WlanRxFilterSetCommand_t; - -/** - * \struct _WlanRxFilterSetCommandReponse_t - */ -typedef struct _WlanRxFilterSetCommandReponse_t -{ - /* 1 byte */ - _u8 Status; - /* 3 bytes */ - _u8 Padding[3]; - -}_WlanRxFilterSetCommandReponse_t; - -/** - * \struct _WlanRxFilterGetCommand_t - */ -typedef struct _WlanRxFilterGetCommand_t -{ - _u16 OutputBufferLength; - /* 1 byte */ - SLrxFilterOperation_t RxFilterOperation; - _u8 Padding[1]; -}_WlanRxFilterGetCommand_t; - -/** - * \struct _WlanRxFilterGetCommandReponse_t - */ -typedef struct _WlanRxFilterGetCommandReponse_t -{ - /* 1 byte */ - _u8 Status; - /* 1 bytes */ - _u8 Padding; - /* 2 byte */ - _u16 OutputBufferLength; - -}_WlanRxFilterGetCommandReponse_t; - - - -/* ******************************************************************************/ -/* RX filters -- End */ -/* ******************************************************************************/ - -typedef struct -{ - _u16 status; - _u8 WlanRole; /* 0 = station, 2 = AP */ - _u8 Ipv6Enabled; - _u8 Ipv6DhcpEnabled; - - _u32 ipV6Global[4]; - _u32 ipV6Local[4]; - _u32 ipV6DnsServer[4]; - _u8 Ipv6DhcpState; - -}_NetappIpV6configRetArgs_t; - - -typedef struct -{ - _u8 ipV4[4]; - _u8 ipV4Mask[4]; - _u8 ipV4Gateway[4]; - _u8 ipV4DnsServer[4]; - _u8 ipV4Start[4]; - _u8 ipV4End[4]; -}_NetCfgIpV4AP_Args_t; - - - -typedef struct -{ - _u16 status; - _u8 MacAddr[6]; -} _MAC_Address_SetGet_t; - - -typedef struct -{ - _u16 Status; - _u16 ConfigId; - _u16 ConfigOpt; - _u16 ConfigLen; -}_NetCfgSetGet_t; - -typedef struct -{ - _u16 Status; - _u16 DeviceSetId; - _u16 Option; - _u16 ConfigLen; -}_DeviceSetGet_t; - - - - -/******************************************************************************************/ -/* Socket structs */ -/******************************************************************************************/ - -typedef struct -{ - _u8 Domain; - _u8 Type; - _u8 Protocol; - _u8 Padding; -}_SocketCommand_t; - - -typedef struct -{ - _i16 statusOrLen; - _u8 sd; - _u8 padding; -}_SocketResponse_t; - -typedef struct -{ - _u8 sd; - _u8 family; - _u8 padding1; - _u8 padding2; -}_AcceptCommand_t; - - -typedef struct -{ - _i16 statusOrLen; - _u8 sd; - _u8 family; - _u16 port; - _u16 paddingOrAddr; - _u32 address; -}_SocketAddrAsyncIPv4Response_t; - -typedef struct -{ - _i16 statusOrLen; - _u8 sd; - _u8 family; - _u16 port; - _u8 address[6]; -}_SocketAddrAsyncIPv6EUI48Response_t; -typedef struct -{ - _i16 statusOrLen; - _u8 sd; - _u8 family; - _u16 port; - _u16 paddingOrAddr; - _u32 address[4]; -}_SocketAddrAsyncIPv6Response_t; - - -typedef struct -{ - _i16 lenOrPadding; - _u8 sd; - _u8 FamilyAndFlags; - _u16 port; - _u16 paddingOrAddr; - _u32 address; -}_SocketAddrIPv4Command_t; - -typedef struct -{ - _i16 lenOrPadding; - _u8 sd; - _u8 FamilyAndFlags; - _u16 port; - _u8 address[6]; -}_SocketAddrIPv6EUI48Command_t; -typedef struct -{ - _i16 lenOrPadding; - _u8 sd; - _u8 FamilyAndFlags; - _u16 port; - _u16 paddingOrAddr; - _u32 address[4]; -}_SocketAddrIPv6Command_t; - -typedef union { - _SocketAddrIPv4Command_t IpV4; - _SocketAddrIPv6EUI48Command_t IpV6EUI48; -#ifdef SL_SUPPORT_IPV6 - _SocketAddrIPv6Command_t IpV6; -#endif -} _SocketAddrCommand_u; - -typedef union { - _SocketAddrAsyncIPv4Response_t IpV4; - _SocketAddrAsyncIPv6EUI48Response_t IpV6EUI48; -#ifdef SL_SUPPORT_IPV6 - _SocketAddrAsyncIPv6Response_t IpV6; -#endif -} _SocketAddrResponse_u; - -typedef struct -{ - _u8 sd; - _u8 backlog; - _u8 padding1; - _u8 padding2; -}_ListenCommand_t; - -typedef struct -{ - _u8 sd; - _u8 padding0; - _u8 padding1; - _u8 padding2; -}_CloseCommand_t; - - -typedef struct -{ - _u8 nfds; - _u8 readFdsCount; - _u8 writeFdsCount; - _u8 padding; - _u16 readFds; - _u16 writeFds; - _u16 tv_usec; - _u16 tv_sec; -}_SelectCommand_t; - - -typedef struct -{ - _u16 status; - _u8 readFdsCount; - _u8 writeFdsCount; - _u16 readFds; - _u16 writeFds; -}_SelectAsyncResponse_t; - -typedef struct -{ - _u8 sd; - _u8 level; - _u8 optionName; - _u8 optionLen; -}_setSockOptCommand_t; - -typedef struct -{ - _u8 sd; - _u8 level; - _u8 optionName; - _u8 optionLen; -}_getSockOptCommand_t; - -typedef struct -{ - _i16 status; - _u8 sd; - _u8 optionLen; -}_getSockOptResponse_t; - - -typedef struct -{ - _u16 StatusOrLen; - _u8 sd; - _u8 FamilyAndFlags; -}_sendRecvCommand_t; - -/***************************************************************************************** -* NETAPP structs -******************************************************************************************/ - - -typedef _BasicResponse_t _NetAppStartStopResponse_t; - -typedef struct -{ - _u32 appId; -}_NetAppStartStopCommand_t; - -typedef struct -{ - _u16 Status; - _u16 AppId; - _u16 ConfigOpt; - _u16 ConfigLen; -}_NetAppSetGet_t; -typedef struct -{ - _u16 port_number; -} _NetAppHttpServerGetSet_port_num_t; - -typedef struct -{ - _u8 auth_enable; -}_NetAppHttpServerGetSet_auth_enable_t; - -typedef struct _sl_NetAppHttpServerGetToken_t -{ - _u8 token_name_len; - _u8 padd1; - _u16 padd2; -}sl_NetAppHttpServerGetToken_t; - -typedef struct _sl_NetAppHttpServerSendToken_t -{ - _u8 token_value_len; - _u8 token_name_len; - _u8 token_name[MAX_TOKEN_NAME_LEN]; - _u16 padd; -}sl_NetAppHttpServerSendToken_t; - -typedef struct _sl_NetAppHttpServerPostToken_t -{ - _u8 post_action_len; - _u8 token_name_len; - _u8 token_value_len; - _u8 padding; -}sl_NetAppHttpServerPostToken_t; - - -typedef struct -{ - _u16 Len; - _u8 family; - _u8 padding; -}_GetHostByNameCommand_t; - -typedef struct -{ - _u16 status; - _u16 padding; - _u32 ip0; - _u32 ip1; - _u32 ip2; - _u32 ip3; -}_GetHostByNameIPv6AsyncResponse_t; - -typedef struct -{ - _u16 status; - _u8 padding1; - _u8 padding2; - _u32 ip0; -}_GetHostByNameIPv4AsyncResponse_t; - - - - -typedef enum -{ - CTST_BSD_UDP_TX, - CTST_BSD_UDP_RX, - CTST_BSD_TCP_TX, - CTST_BSD_TCP_RX, - CTST_BSD_TCP_SERVER_BI_DIR, - CTST_BSD_TCP_CLIENT_BI_DIR, - CTST_BSD_UDP_BI_DIR, - CTST_BSD_RAW_TX, - CTST_BSD_RAW_RX, - CTST_BSD_RAW_BI_DIR, - CTST_BSD_SECURED_TCP_TX, - CTST_BSD_SECURED_TCP_RX, - CTST_BSD_SECURED_TCP_SERVER_BI_DIR, - CTST_BSD_SECURED_TCP_CLIENT_BI_DIR - }CommTest_e; - -typedef struct _sl_protocol_CtestStartCommand_t -{ - _u32 Test; - _u16 DestPort; - _u16 SrcPort; - _u32 DestAddr[4]; - _u32 PayloadSize; - _u32 timeout; - _u32 csEnabled; - _u32 secure; - _u32 rawProtocol; - _u8 reserved1[4]; -}_CtestStartCommand_t; - -typedef struct -{ - _u8 test; - _u8 socket; - _i16 status; - _u32 startTime; - _u32 endTime; - _u16 txKbitsSec; - _u16 rxKbitsSec; - _u32 outOfOrderPackets; - _u32 missedPackets; - _i16 token; -}_CtestAsyncResponse_t; - -typedef struct -{ - _u32 pingIntervalTime; - _u16 PingSize; - _u16 pingRequestTimeout; - _u32 totalNumberOfAttempts; - _u32 flags; - _u32 ip0; - _u32 ip1OrPaadding; - _u32 ip2OrPaadding; - _u32 ip3OrPaadding; -}_PingStartCommand_t; - -typedef struct -{ - _u16 status; - _u16 rttMin; - _u16 rttMax; - _u16 rttAvg; - _u32 numSuccsessPings; - _u32 numSendsPings; - _u32 testTime; -}_PingReportResponse_t; - - -typedef struct -{ - _u32 ip; - _u32 gateway; - _u32 dns; -}_IpV4AcquiredAsync_t; - - -typedef enum -{ - ACQUIRED_IPV6_LOCAL = 1, - ACQUIRED_IPV6_GLOBAL -}IpV6AcquiredType_e; - - -typedef struct -{ - _u32 type; - _u32 ip[4]; - _u32 gateway[4]; - _u32 dns[4]; -}_IpV6AcquiredAsync_t; - - -typedef union -{ - _SocketCommand_t EventMask; - _sendRecvCommand_t DeviceInit; -}_device_commands_t; - -/***************************************************************************************** -* FS structs -******************************************************************************************/ - -typedef struct -{ - _u32 FileHandle; - _u32 Offset; - _u16 Len; - _u16 Padding; -}_FsReadCommand_t; - -typedef struct -{ - _u32 Mode; - _u32 Token; -}_FsOpenCommand_t; - -typedef struct -{ - _u32 FileHandle; - _u32 Token; -}_FsOpenResponse_t; - - -typedef struct -{ - _u32 FileHandle; - _u32 CertificFileNameLength; - _u32 SignatureLen; -}_FsCloseCommand_t; - - -typedef _BasicResponse_t _FsReadResponse_t; -typedef _BasicResponse_t _FsDeleteResponse_t; -typedef _BasicResponse_t _FsCloseResponse_t; - -typedef struct -{ - _u16 Status; - _u16 flags; - _u32 FileLen; - _u32 AllocatedLen; - _u32 Token[4]; -}_FsGetInfoResponse_t; - -typedef struct -{ - _u8 DeviceID; - _u8 Padding[3]; -}_FsFormatCommand_t; - -typedef _BasicResponse_t _FsFormatResponse_t; - -typedef struct -{ - _u32 Token; -}_FsDeleteCommand_t; - -typedef _FsDeleteCommand_t _FsGetInfoCommand_t; - -typedef struct -{ - _u32 FileHandle; - _u32 Offset; - _u16 Len; - _u16 Padding; -}_FsWriteCommand_t; - -typedef _BasicResponse_t _FsWriteResponse_t; - - - -/* TODO: Set MAx Async Payload length depending on flavor (Tiny, Small, etc.) */ - - -#ifdef SL_TINY_EXT -#define SL_ASYNC_MAX_PAYLOAD_LEN 120 /* size must be aligned to 4 */ -#else -#define SL_ASYNC_MAX_PAYLOAD_LEN 160 /* size must be aligned to 4 */ -#endif - -#define SL_ASYNC_MAX_MSG_LEN (_SL_RESP_HDR_SIZE + SL_ASYNC_MAX_PAYLOAD_LEN) - -#define RECV_ARGS_SIZE (sizeof(_SocketResponse_t)) -#define RECVFROM_IPV4_ARGS_SIZE (sizeof(_SocketAddrAsyncIPv4Response_t)) -#define RECVFROM_IPV6_ARGS_SIZE (sizeof(_SocketAddrAsyncIPv6Response_t)) - -#define SL_IPV4_ADDRESS_SIZE (sizeof(_u32)) -#define SL_IPV6_ADDRESS_SIZE (4 * sizeof(_u32)) - -#endif /* _SL_PROTOCOL_TYPES_H_ */ diff --git a/drivers/cc3100/inc/simplelink.h b/drivers/cc3100/inc/simplelink.h deleted file mode 100644 index 19ca17f0c7..0000000000 --- a/drivers/cc3100/inc/simplelink.h +++ /dev/null @@ -1,948 +0,0 @@ -/* - * simplelink.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - - -/*! - \mainpage SimpleLink Driver - - \section intro_sec Introduction - - The SimpleLink CC31xx/CC2xx family allows to add Wi-Fi and networking capabilities - to low-cost embedded products without having prior Wi-Fi, RF or networking expertise. - The CC31xx/CC32xx is an ideal solution for microcontroller-based sensor and control - applications such as home appliances, home automation and smart metering. - The CC31xx/CC32xx has integrated a comprehensive TCP/IP network stack, Wi-Fi driver and - security supplicant leading to easier portability to microcontrollers, to an - ultra-low memory footprint, all without compromising the capabilities and robustness - of the final application. - - - - \section modules_sec Module Names - To make it simple, TI's SimpleLink CC31xx/CC32xx platform capabilities were divided into modules by topic (Silo). - These capabilities range from basic device management through wireless - network configuration, standard BSD socket and much more. - Listed below are the various modules in the SimpleLink CC31xx/CC32xx driver: - -# \ref device - controls the behaviour of the CC31xx/CC32xx device (start/stop, events masking and obtaining specific device status) - -# \ref wlan - controls the use of the WiFi WLAN module including: - - Connection features, such as: profiles, policies, SmartConfig� - - Advanced WLAN features, such as: scans, rx filters and rx statistics collection - -# \ref socket - controls standard client/server sockets programming options and capabilities - -# \ref netapp - activates networking applications, such as: HTTP Server, DHCP Server, Ping, DNS and mDNS. - -# \ref netcfg - controls the configuration of the device addresses (i.e. IP and MAC addresses) - -# \ref FileSystem - provides file system capabilities to TI's CC31XX that can be used by both the CC31XX device and the user. - - - \section proting_sec Porting Guide - - The porting of the SimpleLink driver to any new platform is based on few simple steps. - This guide takes you through this process step by step. Please follow the instructions - carefully to avoid any problems during this process and to enable efficient and proper - work with the device. - Please notice that all modifications and porting adjustments of the driver should be - made in the user.h header file only. - Keep making any of the changes only in this file will ensure smoothly transaction to - new versions of the driver at the future! - - - \subsection porting_step1 Step 1 - Create your own user.h file - - The first step is to create a user.h file that will include your configurations and - adjustments. You can use the empty template provided as part of this driver or - you can choose to base your file on file from one of the wide range of examples - applications provided by Texas Instruments - - - \subsection porting_step2 Step 2 - Select the capabilities set required for your application - - Texas Instruments made a lot of efforts to build set of predefined capability sets that would - fit most of the target application. - It is recommended to try and choose one of this predefined capabilities set before going to - build your own customized set. If you find compatible set you can skip the rest of this step. - - The available sets are: - -# SL_TINY - Compatible to be used on platforms with very limited resources. Provides - the best in class foot print in terms of Code and Data consumption. - -# SL_SMALL - Compatible to most common networking applications. Provide the most - common APIs with decent balance between code size, data size, functionality - and performances - -# SL_FULL - Provide access to all SimpleLink functionalities - - - \subsection porting_step3 Step 3 - Bind the device enable/disable output line - - The enable/disable line (nHib) provide mechanism to enter the device into the least current - consumption mode. This mode could be used when no traffic is required (tx/rx). - when this line is not connected to any IO of the host this define should be left empty. - Not connecting this line results in ability to start the driver only once. - - - \subsection porting_step4 Step 4 - Writing your interface communication driver - - The SimpleLink device support several standard communication protocol among SPI and - UART. Depending on your needs and your hardware design, you should choose the - communication channel type. - The interface for this communication channel should include 4 simple access functions: - -# open - -# close - -# read - -# write - - The way this driver would be implemented is directly effecting the efficiency and - the performances of the SimpleLink device on this platform. - If your system has DMA you should consider to use it in order to increase the utilization - of the communication channel - If you have enough memory resources you should consider using a buffer to increase the - efficiency of the write operations. - - - \subsection porting_step5 Step 5 - Choose your memory management model - - The SimpleLink driver support two memory models: - -# Static (default) - -# Dynamic - - If you choose to work in dynamic model you will have to provide alloc and free functions - to be used by the Simple Link driver otherwise nothing need to be done. - - - \subsection porting_step6 Step 6 - OS adaptation - - The SimpleLink driver could run on two kind of platforms: - -# Non-Os / Single Threaded (default) - -# Multi-Threaded - - If you choose to work in multi-threaded environment under operating system you will have to - provide some basic adaptation routines to allow the driver to protect access to resources - for different threads (locking object) and to allow synchronization between threads (sync objects). - In additional the driver support running without dedicated thread allocated solely to the simple - link driver. If you choose to work in this mode, you should also supply a spawn method that - will enable to run function on a temporary context. - - - \subsection porting_step7 Step 7 - Set your asynchronous event handlers routines - - The SimpleLink device generate asynchronous events in several situations. - These asynchronous events could be masked. - In order to catch these events you have to provide handler routines. - Please notice that if you not provide a handler routine and the event is received, - the driver will drop this event without any indication of this drop. - - - \subsection porting_step8 Step 8 - Run diagnostic tools to validate the correctness of your porting - - The driver is delivered with some porting diagnostic tools to simplify the porting validation process - and to reduce issues latter. It is very important to follow carefully this process. - - The diagnostic process include: - -# Validating Interface Communication Driver - -# Validating OS adaptation layer - -# Validating HW integrity - -# Validating basic work with the device - - - \section sw_license License - - * - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - - - -#ifndef __SIMPLELINK_H__ -#define __SIMPLELINK_H__ - -#include "user.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - - -/*! \attention Async event activation notes - Function prototypes for event callback handlers - Event handler function names should be defined in the user.h file - e.g. - "#define sl_WlanEvtHdlr SLWlanEventHandler" - Indicates all WLAN events are handled by User func "SLWlanEventHandler" - Important notes: - 1. Event handlers cannot activate another SimpleLink API from the event's context - 2. Event's data is valid during event's context. Any application data - which is required for the user application should be copied or marked - into user's variables - 3. It is not recommended to delay the execution of the event callback handler - -*/ - -/*! - - \addtogroup UserEvents - @{ - -*/ - - -/*****************************************************************************/ -/* Macro declarations for Host Driver version */ -/*****************************************************************************/ -#define SL_DRIVER_VERSION "1.0.0.10" -#define SL_MAJOR_VERSION_NUM 1L -#define SL_MINOR_VERSION_NUM 0L -#define SL_VERSION_NUM 0L -#define SL_SUB_VERSION_NUM 10L - - -/*****************************************************************************/ -/* Macro declarations for predefined configurations */ -/*****************************************************************************/ - -#ifdef SL_TINY -#undef SL_INC_ARG_CHECK -#undef SL_INC_EXT_API -#undef SL_INC_SOCK_SERVER_SIDE_API -#undef SL_INC_WLAN_PKG -#undef SL_INC_NET_CFG_PKG -#undef SL_INC_FS_PKG -#undef SL_INC_SET_UART_MODE -#undef SL_INC_STD_BSD_API_NAMING -#undef SL_INC_SOCK_CLIENT_SIDE_API -#undef SL_INC_NET_APP_PKG -#undef SL_INC_SOCK_RECV_API -#undef SL_INC_SOCK_SEND_API -#undef SL_INC_SOCKET_PKG -#endif - -#ifdef SL_SMALL -#undef SL_INC_EXT_API -#undef SL_INC_NET_APP_PKG -#undef SL_INC_NET_CFG_PKG -#undef SL_INC_FS_PKG -#define SL_INC_ARG_CHECK -#define SL_INC_WLAN_PKG -#define SL_INC_SOCKET_PKG -#define SL_INC_SOCK_CLIENT_SIDE_API -#define SL_INC_SOCK_SERVER_SIDE_API -#define SL_INC_SOCK_RECV_API -#define SL_INC_SOCK_SEND_API -#define SL_INC_SET_UART_MODE -#endif - -#ifdef SL_FULL -#define SL_INC_EXT_API -#define SL_INC_NET_APP_PKG -#define SL_INC_NET_CFG_PKG -#define SL_INC_FS_PKG -#define SL_INC_ARG_CHECK -#define SL_INC_WLAN_PKG -#define SL_INC_SOCKET_PKG -#define SL_INC_SOCK_CLIENT_SIDE_API -#define SL_INC_SOCK_SERVER_SIDE_API -#define SL_INC_SOCK_RECV_API -#define SL_INC_SOCK_SEND_API -#define SL_INC_SET_UART_MODE -#endif - -#define SL_RET_CODE_OK (0) -#define SL_RET_CODE_INVALID_INPUT (-2) -#define SL_RET_CODE_SELF_ERROR (-3) -#define SL_RET_CODE_NWP_IF_ERROR (-4) -#define SL_RET_CODE_MALLOC_ERROR (-5) - -#define sl_Memcpy memcpy -#define sl_Memset memset - -#define sl_SyncObjClear(pObj) sl_SyncObjWait(pObj,SL_OS_NO_WAIT) - -#ifndef SL_TINY_EXT -#define SL_MAX_SOCKETS (8) -#else -#define SL_MAX_SOCKETS (2) -#endif - - -/*****************************************************************************/ -/* Types definitions */ -/*****************************************************************************/ -typedef void (*_SlSpawnEntryFunc_t)(void* pValue); - -#ifndef NULL -#define NULL (0) -#endif - -#ifndef FALSE -#define FALSE (0) -#endif - -#ifndef TRUE -#define TRUE (!FALSE) -#endif - -#ifndef OK -#define OK (0) -#endif - -#ifndef _SL_USER_TYPES - typedef unsigned char _u8; - typedef signed char _i8; - - typedef unsigned short _u16; - typedef signed short _i16; - - typedef unsigned long _u32; - typedef signed long _i32; - #define _volatile volatile - #define _const const -#endif - -typedef _u16 _SlOpcode_t; -typedef _u8 _SlArgSize_t; -typedef _i16 _SlDataSize_t; -typedef _i16 _SlReturnVal_t; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - - - -/* - * This event status used to block or continue the event propagation - * through all the registered external libs/user application - * - */ - - typedef enum { - EVENT_PROPAGATION_BLOCK = 0, - EVENT_PROPAGATION_CONTINUE - - } _SlEventPropogationStatus_e; - - - - - - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ - -#ifdef SL_PLATFORM_MULTI_THREADED - #include "spawn.h" -#else - #include "nonos.h" -#endif - - -/* - objInclusion.h and user.h must be included before all api header files - objInclusion.h must be the last arrangement just before including the API header files - since it based on the other configurations to decide which object should be included -*/ -#include "objInclusion.h" -#include "trace.h" -#include "fs.h" -#include "socket.h" -#include "netapp.h" -#include "wlan.h" -#include "device.h" -#include "netcfg.h" -#include "wlan_rx_filters.h" - - - /* The general events dispatcher which is - * initialized to the user handler */ -#ifdef sl_GeneralEvtHdlr -#define _SlDrvHandleGeneralEvents sl_GeneralEvtHdlr -#endif - - /* The wlan events dispatcher which is - * initialized to the user handler */ -#ifdef sl_WlanEvtHdlr -#define _SlDrvHandleWlanEvents sl_WlanEvtHdlr -#endif - - /* The NetApp events dispatcher which is - * initialized to the user handler */ -#ifdef sl_NetAppEvtHdlr -#define _SlDrvHandleNetAppEvents sl_NetAppEvtHdlr -#endif - - /* The http server events dispatcher which is - * initialized to the user handler if exists */ -#ifdef sl_HttpServerCallback -#define _SlDrvHandleHttpServerEvents sl_HttpServerCallback -#endif - - /* The socket events dispatcher which is - * initialized to the user handler */ -#ifdef sl_SockEvtHdlr -#define _SlDrvHandleSockEvents sl_SockEvtHdlr -#endif - - -#ifndef __CONCAT -#define __CONCAT(x,y) x ## y -#endif -#define __CONCAT2(x,y) __CONCAT(x,y) - - -/* - * The section below handles the external lib event registration - * according to the desired events it specified in its API header file. - * The external lib should be first installed by the user (see user.h) - */ -#ifdef SL_EXT_LIB_1 - - /* General Event Registration */ - #if __CONCAT2(SL_EXT_LIB_1, _NOTIFY_GENERAL_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_1, _GeneralEventHdl) (SlDeviceEvent_t *); - #define SlExtLib1GeneralEventHandler __CONCAT2(SL_EXT_LIB_1, _GeneralEventHdl) - - #undef EXT_LIB_REGISTERED_GENERAL_EVENTS - #define EXT_LIB_REGISTERED_GENERAL_EVENTS - #endif - - /* Wlan Event Registration */ - #if __CONCAT2(SL_EXT_LIB_1, _NOTIFY_WLAN_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_1, _WlanEventHdl) (SlWlanEvent_t *); - #define SlExtLib1WlanEventHandler __CONCAT2(SL_EXT_LIB_1, _WlanEventHdl) - - #undef EXT_LIB_REGISTERED_WLAN_EVENTS - #define EXT_LIB_REGISTERED_WLAN_EVENTS - #endif - - /* NetApp Event Registration */ - #if __CONCAT2(SL_EXT_LIB_1, _NOTIFY_NETAPP_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_1, _NetAppEventHdl) (SlNetAppEvent_t *); - #define SlExtLib1NetAppEventHandler __CONCAT2(SL_EXT_LIB_1, _NetAppEventHdl) - - #undef EXT_LIB_REGISTERED_NETAPP_EVENTS - #define EXT_LIB_REGISTERED_NETAPP_EVENTS - #endif - - /* Http Server Event Registration */ - #if __CONCAT2(SL_EXT_LIB_1, _NOTIFY_HTTP_SERVER_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_1, _HttpServerEventHdl) (SlHttpServerEvent_t* , SlHttpServerResponse_t*); - #define SlExtLib1HttpServerEventHandler __CONCAT2(SL_EXT_LIB_1, _HttpServerEventHdl) - - #undef EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS - #define EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS - #endif - - /* Socket Event Registration */ - #if __CONCAT2(SL_EXT_LIB_1, _NOTIFY_SOCK_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_1, _SockEventHdl) (SlSockEvent_t *); - #define SlExtLib1SockEventHandler __CONCAT2(SL_EXT_LIB_1, _SockEventHdl) - - #undef EXT_LIB_REGISTERED_SOCK_EVENTS - #define EXT_LIB_REGISTERED_SOCK_EVENTS - #endif - -#endif - - -#ifdef SL_EXT_LIB_2 - - /* General Event Registration */ - #if __CONCAT2(SL_EXT_LIB_2, _NOTIFY_GENERAL_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_2, _GeneralEventHdl) (SlDeviceEvent_t *); - #define SlExtLib2GeneralEventHandler __CONCAT2(SL_EXT_LIB_2, _GeneralEventHdl) - - #undef EXT_LIB_REGISTERED_GENERAL_EVENTS - #define EXT_LIB_REGISTERED_GENERAL_EVENTS - #endif - - /* Wlan Event Registration */ - #if __CONCAT2(SL_EXT_LIB_2, _NOTIFY_WLAN_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_2, _WlanEventHdl) (SlWlanEvent_t *); - #define SlExtLib2WlanEventHandler __CONCAT2(SL_EXT_LIB_2, _WlanEventHdl) - - #undef EXT_LIB_REGISTERED_WLAN_EVENTS - #define EXT_LIB_REGISTERED_WLAN_EVENTS - #endif - - /* NetApp Event Registration */ - #if __CONCAT2(SL_EXT_LIB_2, _NOTIFY_NETAPP_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_2, _NetAppEventHdl) (SlNetAppEvent_t *); - #define SlExtLib2NetAppEventHandler __CONCAT2(SL_EXT_LIB_2, _NetAppEventHdl) - - #undef EXT_LIB_REGISTERED_NETAPP_EVENTS - #define EXT_LIB_REGISTERED_NETAPP_EVENTS - #endif - - /* Http Server Event Registration */ - #if __CONCAT2(SL_EXT_LIB_2, _NOTIFY_HTTP_SERVER_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_2, _HttpServerEventHdl) (SlHttpServerEvent_t* , SlHttpServerResponse_t*); - #define SlExtLib2HttpServerEventHandler __CONCAT2(SL_EXT_LIB_2, _HttpServerEventHdl) - - #undef EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS - #define EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS - #endif - - /* Socket Event Registration */ - #if __CONCAT2(SL_EXT_LIB_2, _NOTIFY_SOCK_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_2, _SockEventHdl) (SlSockEvent_t *); - #define SlExtLib2SockEventHandler __CONCAT2(SL_EXT_LIB_2, _SockEventHdl) - - #undef EXT_LIB_REGISTERED_SOCK_EVENTS - #define EXT_LIB_REGISTERED_SOCK_EVENTS - #endif - -#endif - - -#ifdef SL_EXT_LIB_3 - - /* General Event Registration */ - #if __CONCAT2(SL_EXT_LIB_3, _NOTIFY_GENERAL_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_3, _GeneralEventHdl) (SlDeviceEvent_t *); - #define SlExtLib3GeneralEventHandler __CONCAT2(SL_EXT_LIB_3, _GeneralEventHdl) - - #undef EXT_LIB_REGISTERED_GENERAL_EVENTS - #define EXT_LIB_REGISTERED_GENERAL_EVENTS - #endif - - /* Wlan Event Registration */ - #if __CONCAT2(SL_EXT_LIB_3, _NOTIFY_WLAN_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_3, _WlanEventHdl) (SlWlanEvent_t *); - #define SlExtLib3WlanEventHandler __CONCAT2(SL_EXT_LIB_3, _WlanEventHdl) - - #undef EXT_LIB_REGISTERED_WLAN_EVENTS - #define EXT_LIB_REGISTERED_WLAN_EVENTS - #endif - - /* NetApp Event Registration */ - #if __CONCAT2(SL_EXT_LIB_3, _NOTIFY_NETAPP_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_3, _NetAppEventHdl) (SlNetAppEvent_t *); - #define SlExtLib3NetAppEventHandler __CONCAT2(SL_EXT_LIB_3, _NetAppEventHdl) - - #undef EXT_LIB_REGISTERED_NETAPP_EVENTS - #define EXT_LIB_REGISTERED_NETAPP_EVENTS - #endif - - /* Http Server Event Registration */ - #if __CONCAT2(SL_EXT_LIB_3, _NOTIFY_HTTP_SERVER_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_3, _HttpServerEventHdl) (SlHttpServerEvent_t* , SlHttpServerResponse_t*); - #define SlExtLib3HttpServerEventHandler __CONCAT2(SL_EXT_LIB_3, _HttpServerEventHdl) - - #undef EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS - #define EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS - #endif - - /* Socket Event Registration */ - #if __CONCAT2(SL_EXT_LIB_3, _NOTIFY_SOCK_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_3, _SockEventHdl) (SlSockEvent_t *); - #define SlExtLib3SockEventHandler __CONCAT2(SL_EXT_LIB_3, _SockEventHdl) - - #undef EXT_LIB_REGISTERED_SOCK_EVENTS - #define EXT_LIB_REGISTERED_SOCK_EVENTS - #endif - -#endif - - -#ifdef SL_EXT_LIB_4 - - /* General Event Registration */ - #if __CONCAT2(SL_EXT_LIB_4, _NOTIFY_GENERAL_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_4, _GeneralEventHdl) (SlDeviceEvent_t *); - #define SlExtLib4GeneralEventHandler __CONCAT2(SL_EXT_LIB_4, _GeneralEventHdl) - - #undef EXT_LIB_REGISTERED_GENERAL_EVENTS - #define EXT_LIB_REGISTERED_GENERAL_EVENTS - #endif - - /* Wlan Event Registration */ - #if __CONCAT2(SL_EXT_LIB_4, _NOTIFY_WLAN_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_4, _WlanEventHdl) (SlWlanEvent_t *); - #define SlExtLib4WlanEventHandler __CONCAT2(SL_EXT_LIB_4, _WlanEventHdl) - - #undef EXT_LIB_REGISTERED_WLAN_EVENTS - #define EXT_LIB_REGISTERED_WLAN_EVENTS - #endif - - /* NetApp Event Registration */ - #if __CONCAT2(SL_EXT_LIB_4, _NOTIFY_NETAPP_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_4, _NetAppEventHdl) (SlNetAppEvent_t *); - #define SlExtLib4NetAppEventHandler __CONCAT2(SL_EXT_LIB_4, _NetAppEventHdl) - - #undef EXT_LIB_REGISTERED_NETAPP_EVENTS - #define EXT_LIB_REGISTERED_NETAPP_EVENTS - #endif - - /* Http Server Event Registration */ - #if __CONCAT2(SL_EXT_LIB_4, _NOTIFY_HTTP_SERVER_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_4, _HttpServerEventHdl) (SlHttpServerEvent_t* , SlHttpServerResponse_t*); - #define SlExtLib4HttpServerEventHandler __CONCAT2(SL_EXT_LIB_4, _HttpServerEventHdl) - - #undef EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS - #define EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS - #endif - - /* Socket Event Registration */ - #if __CONCAT2(SL_EXT_LIB_4, _NOTIFY_SOCK_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_4, _SockEventHdl) (SlSockEvent_t *); - #define SlExtLib4SockEventHandler __CONCAT2(SL_EXT_LIB_4, _SockEventHdl) - - #undef EXT_LIB_REGISTERED_SOCK_EVENTS - #define EXT_LIB_REGISTERED_SOCK_EVENTS - #endif - -#endif - - -#ifdef SL_EXT_LIB_5 - - /* General Event Registration */ - #if __CONCAT2(SL_EXT_LIB_5, _NOTIFY_GENERAL_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_5, _GeneralEventHdl) (SlDeviceEvent_t *); - #define SlExtLib5GeneralEventHandler __CONCAT2(SL_EXT_LIB_5, _GeneralEventHdl) - - #undef EXT_LIB_REGISTERED_GENERAL_EVENTS - #define EXT_LIB_REGISTERED_GENERAL_EVENTS - #endif - - /* Wlan Event Registration */ - #if __CONCAT2(SL_EXT_LIB_5, _NOTIFY_WLAN_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_5, _WlanEventHdl) (SlWlanEvent_t *); - #define SlExtLib5WlanEventHandler __CONCAT2(SL_EXT_LIB_5, _WlanEventHdl) - - #undef EXT_LIB_REGISTERED_WLAN_EVENTS - #define EXT_LIB_REGISTERED_WLAN_EVENTS - #endif - - /* NetApp Event Registration */ - #if __CONCAT2(SL_EXT_LIB_5, _NOTIFY_NETAPP_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_5, _NetAppEventHdl) (SlNetAppEvent_t *); - #define SlExtLib5NetAppEventHandler __CONCAT2(SL_EXT_LIB_5, _NetAppEventHdl) - - #undef EXT_LIB_REGISTERED_NETAPP_EVENTS - #define EXT_LIB_REGISTERED_NETAPP_EVENTS - #endif - - /* Http Server Event Registration */ - #if __CONCAT2(SL_EXT_LIB_5, _NOTIFY_HTTP_SERVER_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_5, _HttpServerEventHdl) (SlHttpServerEvent_t* , SlHttpServerResponse_t*); - #define SlExtLib5HttpServerEventHandler __CONCAT2(SL_EXT_LIB_5, _HttpServerEventHdl) - - #undef EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS - #define EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS - #endif - - /* Socket Event Registration */ - #if __CONCAT2(SL_EXT_LIB_5, _NOTIFY_SOCK_EVENT) - extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_5, _SockEventHdl) (SlSockEvent_t *); - #define SlExtLib5SockEventHandler __CONCAT2(SL_EXT_LIB_5, _SockEventHdl) - - #undef EXT_LIB_REGISTERED_SOCK_EVENTS - #define EXT_LIB_REGISTERED_SOCK_EVENTS - #endif - -#endif - - - -#if defined(EXT_LIB_REGISTERED_GENERAL_EVENTS) -extern void _SlDrvHandleGeneralEvents(SlDeviceEvent_t *slGeneralEvent); -#endif - -#if defined(EXT_LIB_REGISTERED_WLAN_EVENTS) -extern void _SlDrvHandleWlanEvents(SlWlanEvent_t *slWlanEvent); -#endif - -#if defined (EXT_LIB_REGISTERED_NETAPP_EVENTS) -extern void _SlDrvHandleNetAppEvents(SlNetAppEvent_t *slNetAppEvent); -#endif - -#if defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS) -extern void _SlDrvHandleHttpServerEvents(SlHttpServerEvent_t *slHttpServerEvent, SlHttpServerResponse_t *slHttpServerResponse); -#endif - - -#if defined(EXT_LIB_REGISTERED_SOCK_EVENTS) -extern void _SlDrvHandleSockEvents(SlSockEvent_t *slSockEvent); -#endif - - -typedef void (*_SlSpawnEntryFunc_t)(void* pValue); - - -/* Async functions description*/ - -/*! - \brief General async event for inspecting general events - - \param[out] pSlDeviceEvent pointer to SlDeviceEvent_t - - \par - Parameters: \n - - pSlDeviceEvent->Event = SL_DEVICE_FATAL_ERROR_EVENT - - pSlDeviceEvent->EventData.deviceEvent fields: - - status: An error code indication from the device - - sender: The sender originator which is based on SlErrorSender_e enum - - - pSlDeviceEvent->Event = SL_DEVICE_ABORT_ERROR_EVENT - Indicates a severe error occured and the device stopped - - pSlDeviceEvent->EventData.deviceReport fields: - - AbortType: An idication of the event type - - AbortData: Additional info about the data error - - - \par Example for fatal error: - \code - printf(General Event Handler - ID=%d Sender=%d\n\n", - pSlDeviceEvent->EventData.deviceEvent.status, // status of the general event - pSlDeviceEvent->EventData.deviceEvent.sender); // sender type - \endcode - \par Example for abort request: - \code - printf(Abort type =%d Abort Data=%d\n\n", - pSlDeviceEvent->EventData.deviceReport.AbortType, - pSlDeviceEvent->EventData.deviceReport.AbortData); - - \endcode -*/ -#if (defined(sl_GeneralEvtHdlr)) -extern void sl_GeneralEvtHdlr(SlDeviceEvent_t *pSlDeviceEvent); -#endif - - -/*! - \brief WLAN Async event handler - - \param[out] pSlWlanEvent pointer to SlWlanEvent_t data - - \par - Parameters: - - - pSlWlanEvent->Event = SL_WLAN_CONNECT_EVENT , STA or P2P client connection indication event - - pSlWlanEvent->EventData.STAandP2PModeWlanConnected main fields: - - ssid_name - - ssid_len - - bssid - - go_peer_device_name - - go_peer_device_name_len - - - pSlWlanEvent->Event = SL_WLAN_DISCONNECT_EVENT , STA or P2P client disconnection event - - pSlWlanEvent->EventData.STAandP2PModeDisconnected main fields: - - ssid_name - - ssid_len - - reason_code - - - pSlWlanEvent->Event = SL_WLAN_STA_CONNECTED_EVENT , AP/P2P(Go) connected STA/P2P(Client) - - pSlWlanEvent->EventData.APModeStaConnected fields: - - go_peer_device_name - - mac - - go_peer_device_name_len - - wps_dev_password_id - - own_ssid: relevant for event sta-connected only - - own_ssid_len: relevant for event sta-connected only - - - pSlWlanEvent->Event = SL_WLAN_STA_DISCONNECTED_EVENT , AP/P2P(Go) disconnected STA/P2P(Client) - - pSlWlanEvent->EventData.APModestaDisconnected fields: - - go_peer_device_name - - mac - - go_peer_device_name_len - - wps_dev_password_id - - own_ssid: relevant for event sta-connected only - - own_ssid_len: relevant for event sta-connected only - - - pSlWlanEvent->Event = SL_WLAN_SMART_CONFIG_COMPLETE_EVENT - - pSlWlanEvent->EventData.smartConfigStartResponse fields: - - status - - ssid_len - - ssid - - private_token_len - - private_token - - - pSlWlanEvent->Event = SL_WLAN_SMART_CONFIG_STOP_EVENT - - pSlWlanEvent->EventData.smartConfigStopResponse fields: - - status - - - pSlWlanEvent->Event = SL_WLAN_P2P_DEV_FOUND_EVENT - - pSlWlanEvent->EventData.P2PModeDevFound fields: - - go_peer_device_name - - mac - - go_peer_device_name_len - - wps_dev_password_id - - own_ssid: relevant for event sta-connected only - - own_ssid_len: relevant for event sta-connected only - - - pSlWlanEvent->Event = SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT - - pSlWlanEvent->EventData.P2PModeNegReqReceived fields - - go_peer_device_name - - mac - - go_peer_device_name_len - - wps_dev_password_id - - own_ssid: relevant for event sta-connected only - - - pSlWlanEvent->Event = SL_WLAN_CONNECTION_FAILED_EVENT , P2P only - - pSlWlanEvent->EventData.P2PModewlanConnectionFailure fields: - - status -*/ -#if (defined(sl_WlanEvtHdlr)) -extern void sl_WlanEvtHdlr(SlWlanEvent_t* pSlWlanEvent); -#endif - - -/*! - \brief NETAPP Async event handler - - \param[out] pSlNetApp pointer to SlNetAppEvent_t data - - \par - Parameters: - - pSlNetApp->Event = SL_NETAPP_IPV4_IPACQUIRED_EVENT, IPV4 acquired event - - pSlNetApp->EventData.ipAcquiredV4 fields: - - ip - - gateway - - dns - - - pSlNetApp->Event = SL_NETAPP_IP_LEASED_EVENT, AP or P2P go dhcp lease event - - pSlNetApp->EventData.ipLeased fields: - - ip_address - - lease_time - - mac - - - pSlNetApp->Event = SL_NETAPP_IP_RELEASED_EVENT, AP or P2P go dhcp ip release event - - pSlNetApp->EventData.ipReleased fields - - ip_address - - mac - - reason - -*/ -#if (defined(sl_NetAppEvtHdlr)) -extern void sl_NetAppEvtHdlr(SlNetAppEvent_t* pSlNetApp); -#endif - -/*! - \brief Socket Async event handler - - \param[out] pSlSockEvent pointer to SlSockEvent_t data - - \par - Parameters:\n - - pSlSockEvent->Event = SL_SOCKET_TX_FAILED_EVENT - - pSlSockEvent->SockTxFailData fields: - - sd - - status - - pSlSockEvent->Event = SL_SOCKET_ASYNC_EVENT - - pSlSockEvent->SockAsyncData fields: - - sd - - type: SSL_ACCEPT or RX_FRAGMENTATION_TOO_BIG or OTHER_SIDE_CLOSE_SSL_DATA_NOT_ENCRYPTED - - val - -*/ -#if (defined(sl_SockEvtHdlr)) -extern void sl_SockEvtHdlr(SlSockEvent_t* pSlSockEvent); -#endif - -/*! - \brief HTTP server async event - - \param[out] pSlHttpServerEvent pointer to SlHttpServerEvent_t - \param[in] pSlHttpServerResponse pointer to SlHttpServerResponse_t - - \par - Parameters: \n - - - pSlHttpServerEvent->Event = SL_NETAPP_HTTPGETTOKENVALUE_EVENT - - pSlHttpServerEvent->EventData fields: - - httpTokenName - - data - - len - - pSlHttpServerResponse->ResponseData fields: - - data - - len - - - pSlHttpServerEvent->Event = SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT - - pSlHttpServerEvent->EventData.httpPostData fields: - - action - - token_name - - token_value - - pSlHttpServerResponse->ResponseData fields: - - data - - len - -*/ -#if (defined(sl_HttpServerCallback)) -extern void sl_HttpServerCallback(SlHttpServerEvent_t *pSlHttpServerEvent, SlHttpServerResponse_t *pSlHttpServerResponse); -#endif -/*! - - Close the Doxygen group. - @} - - */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __SIMPLELINK_H__ */ - diff --git a/drivers/cc3100/inc/socket.h b/drivers/cc3100/inc/socket.h deleted file mode 100644 index 81554d4afc..0000000000 --- a/drivers/cc3100/inc/socket.h +++ /dev/null @@ -1,1573 +0,0 @@ -/* - * socket.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" - -#ifndef __SL_SOCKET_H__ -#define __SL_SOCKET_H__ - - - - -#ifdef __cplusplus -extern "C" { -#endif - -/*! - - \addtogroup socket - @{ - -*/ - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ - -#define SL_FD_SETSIZE SL_MAX_SOCKETS /* Number of sockets to select on - same is max sockets! */ -#define BSD_SOCKET_ID_MASK (0x0F) /* Index using the LBS 4 bits for socket id 0-7 */ -/* Define some BSD protocol constants. */ -#define SL_SOCK_STREAM (1) /* TCP Socket */ -#define SL_SOCK_DGRAM (2) /* UDP Socket */ -#define SL_SOCK_RAW (3) /* Raw socket */ -#define SL_IPPROTO_TCP (6) /* TCP Raw Socket */ -#define SL_IPPROTO_UDP (17) /* UDP Raw Socket */ -#define SL_IPPROTO_RAW (255) /* Raw Socket */ -#define SL_SEC_SOCKET (100) /* Secured Socket Layer (SSL,TLS) */ - -/* Address families. */ -#define SL_AF_INET (2) /* IPv4 socket (UDP, TCP, etc) */ -#define SL_AF_INET6 (3) /* IPv6 socket (UDP, TCP, etc) */ -#define SL_AF_INET6_EUI_48 (9) -#define SL_AF_RF (6) /* data include RF parameter, All layer by user (Wifi could be disconnected) */ -#define SL_AF_PACKET (17) -/* Protocol families, same as address families. */ -#define SL_PF_INET AF_INET -#define SL_PF_INET6 AF_INET6 -#define SL_INADDR_ANY (0) /* bind any address */ - -/* error codes */ -#define SL_SOC_ERROR (-1) /* Failure. */ -#define SL_SOC_OK ( 0) /* Success. */ -#define SL_INEXE (-8) /* socket command in execution */ -#define SL_EBADF (-9) /* Bad file number */ -#define SL_ENSOCK (-10) /* The system limit on the total number of open socket, has been reached */ -#define SL_EAGAIN (-11) /* Try again */ -#define SL_EWOULDBLOCK SL_EAGAIN -#define SL_ENOMEM (-12) /* Out of memory */ -#define SL_EACCES (-13) /* Permission denied */ -#define SL_EFAULT (-14) /* Bad address */ -#define SL_ECLOSE (-15) /* close socket operation failed to transmit all queued packets */ -#define SL_EALREADY_ENABLED (-21) /* Transceiver - Transceiver already ON. there could be only one */ -#define SL_EINVAL (-22) /* Invalid argument */ -#define SL_EAUTO_CONNECT_OR_CONNECTING (-69) /* Transceiver - During connection, connected or auto mode started */ -#define SL_CONNECTION_PENDING (-72) /* Transceiver - Device is connected, disconnect first to open transceiver */ -#define SL_EUNSUPPORTED_ROLE (-86) /* Transceiver - Trying to start when WLAN role is AP or P2P GO */ -#define SL_EDESTADDRREQ (-89) /* Destination address required */ -#define SL_EPROTOTYPE (-91) /* Protocol wrong type for socket */ -#define SL_ENOPROTOOPT (-92) /* Protocol not available */ -#define SL_EPROTONOSUPPORT (-93) /* Protocol not supported */ -#define SL_ESOCKTNOSUPPORT (-94) /* Socket type not supported */ -#define SL_EOPNOTSUPP (-95) /* Operation not supported on transport endpoint */ -#define SL_EAFNOSUPPORT (-97) /* Address family not supported by protocol */ -#define SL_EADDRINUSE (-98) /* Address already in use */ -#define SL_EADDRNOTAVAIL (-99) /* Cannot assign requested address */ -#define SL_ENETUNREACH (-101) /* Network is unreachable */ -#define SL_ENOBUFS (-105) /* No buffer space available */ -#define SL_EOBUFF SL_ENOBUFS -#define SL_EISCONN (-106) /* Transport endpoint is already connected */ -#define SL_ENOTCONN (-107) /* Transport endpoint is not connected */ -#define SL_ETIMEDOUT (-110) /* Connection timed out */ -#define SL_ECONNREFUSED (-111) /* Connection refused */ -#define SL_EALREADY (-114) /* Non blocking connect in progress, try again */ - -#define SL_ESEC_RSA_WRONG_TYPE_E (-130) /* RSA wrong block type for RSA function */ -#define SL_ESEC_RSA_BUFFER_E (-131) /* RSA buffer error, output too small or */ -#define SL_ESEC_BUFFER_E (-132) /* output buffer too small or input too large */ -#define SL_ESEC_ALGO_ID_E (-133) /* setting algo id error */ -#define SL_ESEC_PUBLIC_KEY_E (-134) /* setting public key error */ -#define SL_ESEC_DATE_E (-135) /* setting date validity error */ -#define SL_ESEC_SUBJECT_E (-136) /* setting subject name error */ -#define SL_ESEC_ISSUER_E (-137) /* setting issuer name error */ -#define SL_ESEC_CA_TRUE_E (-138) /* setting CA basic constraint true error */ -#define SL_ESEC_EXTENSIONS_E (-139) /* setting extensions error */ -#define SL_ESEC_ASN_PARSE_E (-140) /* ASN parsing error, invalid input */ -#define SL_ESEC_ASN_VERSION_E (-141) /* ASN version error, invalid number */ -#define SL_ESEC_ASN_GETINT_E (-142) /* ASN get big _i16 error, invalid data */ -#define SL_ESEC_ASN_RSA_KEY_E (-143) /* ASN key init error, invalid input */ -#define SL_ESEC_ASN_OBJECT_ID_E (-144) /* ASN object id error, invalid id */ -#define SL_ESEC_ASN_TAG_NULL_E (-145) /* ASN tag error, not null */ -#define SL_ESEC_ASN_EXPECT_0_E (-146) /* ASN expect error, not zero */ -#define SL_ESEC_ASN_BITSTR_E (-147) /* ASN bit string error, wrong id */ -#define SL_ESEC_ASN_UNKNOWN_OID_E (-148) /* ASN oid error, unknown sum id */ -#define SL_ESEC_ASN_DATE_SZ_E (-149) /* ASN date error, bad size */ -#define SL_ESEC_ASN_BEFORE_DATE_E (-150) /* ASN date error, current date before */ -#define SL_ESEC_ASN_AFTER_DATE_E (-151) /* ASN date error, current date after */ -#define SL_ESEC_ASN_SIG_OID_E (-152) /* ASN signature error, mismatched oid */ -#define SL_ESEC_ASN_TIME_E (-153) /* ASN time error, unknown time type */ -#define SL_ESEC_ASN_INPUT_E (-154) /* ASN input error, not enough data */ -#define SL_ESEC_ASN_SIG_CONFIRM_E (-155) /* ASN sig error, confirm failure */ -#define SL_ESEC_ASN_SIG_HASH_E (-156) /* ASN sig error, unsupported hash type */ -#define SL_ESEC_ASN_SIG_KEY_E (-157) /* ASN sig error, unsupported key type */ -#define SL_ESEC_ASN_DH_KEY_E (-158) /* ASN key init error, invalid input */ -#define SL_ESEC_ASN_NTRU_KEY_E (-159) /* ASN ntru key decode error, invalid input */ -#define SL_ESEC_ECC_BAD_ARG_E (-170) /* ECC input argument of wrong type */ -#define SL_ESEC_ASN_ECC_KEY_E (-171) /* ASN ECC bad input */ -#define SL_ESEC_ECC_CURVE_OID_E (-172) /* Unsupported ECC OID curve type */ -#define SL_ESEC_BAD_FUNC_ARG (-173) /* Bad function argument provided */ -#define SL_ESEC_NOT_COMPILED_IN (-174) /* Feature not compiled in */ -#define SL_ESEC_UNICODE_SIZE_E (-175) /* Unicode password too big */ -#define SL_ESEC_NO_PASSWORD (-176) /* no password provided by user */ -#define SL_ESEC_ALT_NAME_E (-177) /* alt name size problem, too big */ -#define SL_ESEC_AES_GCM_AUTH_E (-180) /* AES-GCM Authentication check failure */ -#define SL_ESEC_AES_CCM_AUTH_E (-181) /* AES-CCM Authentication check failure */ -#define SL_SOCKET_ERROR_E (-208) /* Error state on socket */ - -#define SL_ESEC_MEMORY_ERROR (-203) /* out of memory */ -#define SL_ESEC_VERIFY_FINISHED_ERROR (-204) /* verify problem on finished */ -#define SL_ESEC_VERIFY_MAC_ERROR (-205) /* verify mac problem */ -#define SL_ESEC_UNKNOWN_HANDSHAKE_TYPE (-207) /* weird handshake type */ -#define SL_ESEC_SOCKET_ERROR_E (-208) /* error state on socket */ -#define SL_ESEC_SOCKET_NODATA (-209) /* expected data, not there */ -#define SL_ESEC_INCOMPLETE_DATA (-210) /* don't have enough data to complete task */ -#define SL_ESEC_UNKNOWN_RECORD_TYPE (-211) /* unknown type in record hdr */ -#define SL_ESEC_FATAL_ERROR (-213) /* recvd alert fatal error */ -#define SL_ESEC_ENCRYPT_ERROR (-214) /* error during encryption */ -#define SL_ESEC_NO_PEER_KEY (-216) /* need peer's key */ -#define SL_ESEC_NO_PRIVATE_KEY (-217) /* need the private key */ -#define SL_ESEC_RSA_PRIVATE_ERROR (-218) /* error during rsa priv op */ -#define SL_ESEC_NO_DH_PARAMS (-219) /* server missing DH params */ -#define SL_ESEC_BUILD_MSG_ERROR (-220) /* build message failure */ -#define SL_ESEC_BAD_HELLO (-221) /* client hello malformed */ -#define SL_ESEC_DOMAIN_NAME_MISMATCH (-222) /* peer subject name mismatch */ -#define SL_ESEC_WANT_READ (-223) /* want read, call again */ -#define SL_ESEC_NOT_READY_ERROR (-224) /* handshake layer not ready */ -#define SL_ESEC_PMS_VERSION_ERROR (-225) /* pre m secret version error */ -#define SL_ESEC_VERSION_ERROR (-226) /* record layer version error */ -#define SL_ESEC_WANT_WRITE (-227) /* want write, call again */ -#define SL_ESEC_BUFFER_ERROR (-228) /* malformed buffer input */ -#define SL_ESEC_VERIFY_CERT_ERROR (-229) /* verify cert error */ -#define SL_ESEC_VERIFY_SIGN_ERROR (-230) /* verify sign error */ - -#define SL_ESEC_LENGTH_ERROR (-241) /* record layer length error */ -#define SL_ESEC_PEER_KEY_ERROR (-242) /* can't decode peer key */ -#define SL_ESEC_ZERO_RETURN (-243) /* peer sent close notify */ -#define SL_ESEC_SIDE_ERROR (-244) /* wrong client/server type */ -#define SL_ESEC_NO_PEER_CERT (-245) /* peer didn't send key */ -#define SL_ESEC_ECC_CURVETYPE_ERROR (-250) /* Bad ECC Curve Type */ -#define SL_ESEC_ECC_CURVE_ERROR (-251) /* Bad ECC Curve */ -#define SL_ESEC_ECC_PEERKEY_ERROR (-252) /* Bad Peer ECC Key */ -#define SL_ESEC_ECC_MAKEKEY_ERROR (-253) /* Bad Make ECC Key */ -#define SL_ESEC_ECC_EXPORT_ERROR (-254) /* Bad ECC Export Key */ -#define SL_ESEC_ECC_SHARED_ERROR (-255) /* Bad ECC Shared Secret */ -#define SL_ESEC_NOT_CA_ERROR (-257) /* Not a CA cert error */ -#define SL_ESEC_BAD_PATH_ERROR (-258) /* Bad path for opendir */ -#define SL_ESEC_BAD_CERT_MANAGER_ERROR (-259) /* Bad Cert Manager */ -#define SL_ESEC_MAX_CHAIN_ERROR (-268) /* max chain depth exceeded */ -#define SL_ESEC_SUITES_ERROR (-271) /* suites pointer error */ -#define SL_ESEC_SSL_NO_PEM_HEADER (-272) /* no PEM header found */ -#define SL_ESEC_OUT_OF_ORDER_E (-273) /* out of order message */ -#define SL_ESEC_SANITY_CIPHER_E (-275) /* sanity check on cipher error */ -#define SL_ESEC_GEN_COOKIE_E (-277) /* Generate Cookie Error */ -#define SL_ESEC_NO_PEER_VERIFY (-278) /* Need peer cert verify Error */ -#define SL_ESEC_UNKNOWN_SNI_HOST_NAME_E (-281) /* Unrecognized host name Error */ -/* begin negotiation parameter errors */ -#define SL_ESEC_UNSUPPORTED_SUITE (-290) /* unsupported cipher suite */ -#define SL_ESEC_MATCH_SUITE_ERROR (-291 ) /* can't match cipher suite */ - -/* ssl tls security start with -300 offset */ -#define SL_ESEC_CLOSE_NOTIFY (-300) /* ssl/tls alerts */ -#define SL_ESEC_UNEXPECTED_MESSAGE (-310) /* ssl/tls alerts */ -#define SL_ESEC_BAD_RECORD_MAC (-320) /* ssl/tls alerts */ -#define SL_ESEC_DECRYPTION_FAILED (-321) /* ssl/tls alerts */ -#define SL_ESEC_RECORD_OVERFLOW (-322) /* ssl/tls alerts */ -#define SL_ESEC_DECOMPRESSION_FAILURE (-330) /* ssl/tls alerts */ -#define SL_ESEC_HANDSHAKE_FAILURE (-340) /* ssl/tls alerts */ -#define SL_ESEC_NO_CERTIFICATE (-341) /* ssl/tls alerts */ -#define SL_ESEC_BAD_CERTIFICATE (-342) /* ssl/tls alerts */ -#define SL_ESEC_UNSUPPORTED_CERTIFICATE (-343) /* ssl/tls alerts */ -#define SL_ESEC_CERTIFICATE_REVOKED (-344) /* ssl/tls alerts */ -#define SL_ESEC_CERTIFICATE_EXPIRED (-345) /* ssl/tls alerts */ -#define SL_ESEC_CERTIFICATE_UNKNOWN (-346) /* ssl/tls alerts */ -#define SL_ESEC_ILLEGAL_PARAMETER (-347) /* ssl/tls alerts */ -#define SL_ESEC_UNKNOWN_CA (-348) /* ssl/tls alerts */ -#define SL_ESEC_ACCESS_DENIED (-349) /* ssl/tls alerts */ -#define SL_ESEC_DECODE_ERROR (-350) /* ssl/tls alerts */ -#define SL_ESEC_DECRYPT_ERROR (-351) /* ssl/tls alerts */ -#define SL_ESEC_EXPORT_RESTRICTION (-360) /* ssl/tls alerts */ -#define SL_ESEC_PROTOCOL_VERSION (-370) /* ssl/tls alerts */ -#define SL_ESEC_INSUFFICIENT_SECURITY (-371) /* ssl/tls alerts */ -#define SL_ESEC_INTERNAL_ERROR (-380) /* ssl/tls alerts */ -#define SL_ESEC_USER_CANCELLED (-390) /* ssl/tls alerts */ -#define SL_ESEC_NO_RENEGOTIATION (-400) /* ssl/tls alerts */ -#define SL_ESEC_UNSUPPORTED_EXTENSION (-410) /* ssl/tls alerts */ -#define SL_ESEC_CERTIFICATE_UNOBTAINABLE (-411) /* ssl/tls alerts */ -#define SL_ESEC_UNRECOGNIZED_NAME (-412) /* ssl/tls alerts */ -#define SL_ESEC_BAD_CERTIFICATE_STATUS_RESPONSE (-413) /* ssl/tls alerts */ -#define SL_ESEC_BAD_CERTIFICATE_HASH_VALUE (-414) /* ssl/tls alerts */ -/* propierty secure */ -#define SL_ESECGENERAL (-450) /* error secure level general error */ -#define SL_ESECDECRYPT (-451) /* error secure level, decrypt recv packet fail */ -#define SL_ESECCLOSED (-452) /* secure layrer is closed by other size , tcp is still connected */ -#define SL_ESECSNOVERIFY (-453) /* Connected without server verification */ -#define SL_ESECNOCAFILE (-454) /* error secure level CA file not found*/ -#define SL_ESECMEMORY (-455) /* error secure level No memory space available */ -#define SL_ESECBADCAFILE (-456) /* error secure level bad CA file */ -#define SL_ESECBADCERTFILE (-457) /* error secure level bad Certificate file */ -#define SL_ESECBADPRIVATEFILE (-458) /* error secure level bad private file */ -#define SL_ESECBADDHFILE (-459) /* error secure level bad DH file */ -#define SL_ESECT00MANYSSLOPENED (-460) /* MAX SSL Sockets are opened */ -#define SL_ESECDATEERROR (-461) /* connected with certificate date verification error */ -#define SL_ESECHANDSHAKETIMEDOUT (-462) /* connection timed out due to handshake time */ - -/* end error codes */ - -/* Max payload size by protocol */ -#define SL_SOCKET_PAYLOAD_TYPE_MASK (0xF0) /*4 bits type, 4 bits sockets id */ -#define SL_SOCKET_PAYLOAD_TYPE_UDP_IPV4 (0x00) /* 1472 bytes */ -#define SL_SOCKET_PAYLOAD_TYPE_TCP_IPV4 (0x10) /* 1460 bytes */ -#define SL_SOCKET_PAYLOAD_TYPE_UDP_IPV6 (0x20) /* 1452 bytes */ -#define SL_SOCKET_PAYLOAD_TYPE_TCP_IPV6 (0x30) /* 1440 bytes */ -#define SL_SOCKET_PAYLOAD_TYPE_UDP_IPV4_SECURE (0x40) /* */ -#define SL_SOCKET_PAYLOAD_TYPE_TCP_IPV4_SECURE (0x50) /* */ -#define SL_SOCKET_PAYLOAD_TYPE_UDP_IPV6_SECURE (0x60) /* */ -#define SL_SOCKET_PAYLOAD_TYPE_TCP_IPV6_SECURE (0x70) /* */ -#define SL_SOCKET_PAYLOAD_TYPE_RAW_TRANCEIVER (0x80) /* 1536 bytes */ -#define SL_SOCKET_PAYLOAD_TYPE_RAW_PACKET (0x90) /* 1536 bytes */ -#define SL_SOCKET_PAYLOAD_TYPE_RAW_IP4 (0xa0) -#define SL_SOCKET_PAYLOAD_TYPE_RAW_IP6 (SL_SOCKET_PAYLOAD_TYPE_RAW_IP4 ) - - - -#define SL_SOL_SOCKET (1) /* Define the socket option category. */ -#define SL_IPPROTO_IP (2) /* Define the IP option category. */ -#define SL_SOL_PHY_OPT (3) /* Define the PHY option category. */ - -#define SL_SO_RCVBUF (8) /* Setting TCP receive buffer size */ -#define SL_SO_KEEPALIVE (9) /* Connections are kept alive with periodic messages */ -#define SL_SO_RCVTIMEO (20) /* Enable receive timeout */ -#define SL_SO_NONBLOCKING (24) /* Enable . disable nonblocking mode */ -#define SL_SO_SECMETHOD (25) /* security metohd */ -#define SL_SO_SECURE_MASK (26) /* security mask */ -#define SL_SO_SECURE_FILES (27) /* security files */ -#define SL_SO_CHANGE_CHANNEL (28) /* This option is available only when transceiver started */ -#define SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME (30) /* This option used to configue secure file */ -#define SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME (31) /* This option used to configue secure file */ -#define SL_SO_SECURE_FILES_CA_FILE_NAME (32) /* This option used to configue secure file */ -#define SL_SO_SECURE_FILES_DH_KEY_FILE_NAME (33) /* This option used to configue secure file */ - -#define SL_IP_MULTICAST_IF (60) /* Specify outgoing multicast interface */ -#define SL_IP_MULTICAST_TTL (61) /* Specify the TTL value to use for outgoing multicast packet. */ -#define SL_IP_ADD_MEMBERSHIP (65) /* Join IPv4 multicast membership */ -#define SL_IP_DROP_MEMBERSHIP (66) /* Leave IPv4 multicast membership */ -#define SL_IP_HDRINCL (67) /* Raw socket IPv4 header included. */ -#define SL_IP_RAW_RX_NO_HEADER (68) /* Proprietary socket option that does not includeIPv4/IPv6 header (and extension headers) on received raw sockets*/ -#define SL_IP_RAW_IPV6_HDRINCL (69) /* Transmitted buffer over IPv6 socket contains IPv6 header. */ - -#define SL_SO_PHY_RATE (100) /* WLAN Transmit rate */ -#define SL_SO_PHY_TX_POWER (101) /* TX Power level */ -#define SL_SO_PHY_NUM_FRAMES_TO_TX (102) /* Number of frames to transmit */ -#define SL_SO_PHY_PREAMBLE (103) /* Preamble for transmission */ - -#define SL_SO_SEC_METHOD_SSLV3 (0) /* security metohd SSL v3*/ -#define SL_SO_SEC_METHOD_TLSV1 (1) /* security metohd TLS v1*/ -#define SL_SO_SEC_METHOD_TLSV1_1 (2) /* security metohd TLS v1_1*/ -#define SL_SO_SEC_METHOD_TLSV1_2 (3) /* security metohd TLS v1_2*/ -#define SL_SO_SEC_METHOD_SSLv3_TLSV1_2 (4) /* use highest possible version from SSLv3 - TLS 1.2*/ -#define SL_SO_SEC_METHOD_DLSV1 (5) /* security metohd DTL v1 */ - -#define SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA (1 << 0) -#define SL_SEC_MASK_SSL_RSA_WITH_RC4_128_MD5 (1 << 1) -#define SL_SEC_MASK_TLS_RSA_WITH_AES_256_CBC_SHA (1 << 2) -#define SL_SEC_MASK_TLS_DHE_RSA_WITH_AES_256_CBC_SHA (1 << 3) -#define SL_SEC_MASK_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (1 << 4) -#define SL_SEC_MASK_TLS_ECDHE_RSA_WITH_RC4_128_SHA (1 << 5) -#define SL_SEC_MASK_TLS_RSA_WITH_AES_128_CBC_SHA256 (1 << 6) -#define SL_SEC_MASK_TLS_RSA_WITH_AES_256_CBC_SHA256 (1 << 7) -#define SL_SEC_MASK_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 (1 << 8) -#define SL_SEC_MASK_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 (1 << 9) - - -#define SL_SEC_MASK_SECURE_DEFAULT ((SL_SEC_MASK_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 << 1) - 1) - -#define SL_MSG_DONTWAIT (0x00000008) /* Nonblocking IO */ - -/* AP DHCP Server - IP Release reason code */ -#define SL_IP_LEASE_PEER_RELEASE (0) -#define SL_IP_LEASE_PEER_DECLINE (1) -#define SL_IP_LEASE_EXPIRED (2) - -/* possible types when receiving SL_SOCKET_ASYNC_EVENT*/ -#define SSL_ACCEPT (1) /* accept failed due to ssl issue ( tcp pass) */ -#define RX_FRAGMENTATION_TOO_BIG (2) /* connection less mode, rx packet fragmentation > 16K, packet is being released */ -#define OTHER_SIDE_CLOSE_SSL_DATA_NOT_ENCRYPTED (3) /* remote side down from secure to unsecure */ - - - -#ifdef SL_INC_STD_BSD_API_NAMING - -#define FD_SETSIZE SL_FD_SETSIZE - -#define SOCK_STREAM SL_SOCK_STREAM -#define SOCK_DGRAM SL_SOCK_DGRAM -#define SOCK_RAW SL_SOCK_RAW -#define IPPROTO_TCP SL_IPPROTO_TCP -#define IPPROTO_UDP SL_IPPROTO_UDP -#define IPPROTO_RAW SL_IPPROTO_RAW - -#define AF_INET SL_AF_INET -#define AF_INET6 SL_AF_INET6 -#define AF_INET6_EUI_48 SL_AF_INET6_EUI_48 -#define AF_RF SL_AF_RF -#define AF_PACKET SL_AF_PACKET - -#define PF_INET SL_PF_INET -#define PF_INET6 SL_PF_INET6 - -#define INADDR_ANY SL_INADDR_ANY -#define ERROR SL_SOC_ERROR -#define INEXE SL_INEXE -#define EBADF SL_EBADF -#define ENSOCK SL_ENSOCK -#define EAGAIN SL_EAGAIN -#define EWOULDBLOCK SL_EWOULDBLOCK -#define ENOMEM SL_ENOMEM -#define EACCES SL_EACCES -#define EFAULT SL_EFAULT -#define EINVAL SL_EINVAL -#define EDESTADDRREQ SL_EDESTADDRREQ -#define EPROTOTYPE SL_EPROTOTYPE -#define ENOPROTOOPT SL_ENOPROTOOPT -#define EPROTONOSUPPORT SL_EPROTONOSUPPORT -#define ESOCKTNOSUPPORT SL_ESOCKTNOSUPPORT -#define EOPNOTSUPP SL_EOPNOTSUPP -#define EAFNOSUPPORT SL_EAFNOSUPPORT -#define EADDRINUSE SL_EADDRINUSE -#define EADDRNOTAVAIL SL_EADDRNOTAVAIL -#define ENETUNREACH SL_ENETUNREACH -#define ENOBUFS SL_ENOBUFS -#define EOBUFF SL_EOBUFF -#define EISCONN SL_EISCONN -#define ENOTCONN SL_ENOTCONN -#define ETIMEDOUT SL_ETIMEDOUT -#define ECONNREFUSED SL_ECONNREFUSED - -#define SOL_SOCKET SL_SOL_SOCKET -#define IPPROTO_IP SL_IPPROTO_IP -#define SO_KEEPALIVE SL_SO_KEEPALIVE - -#define SO_RCVTIMEO SL_SO_RCVTIMEO -#define SO_NONBLOCKING SL_SO_NONBLOCKING - -#define IP_MULTICAST_IF SL_IP_MULTICAST_IF -#define IP_MULTICAST_TTL SL_IP_MULTICAST_TTL -#define IP_ADD_MEMBERSHIP SL_IP_ADD_MEMBERSHIP -#define IP_DROP_MEMBERSHIP SL_IP_DROP_MEMBERSHIP - -#define socklen_t SlSocklen_t -#define timeval SlTimeval_t -#define sockaddr SlSockAddr_t -#define in6_addr SlIn6Addr_t -#define sockaddr_in6 SlSockAddrIn6_t -#define in_addr SlInAddr_t -#define sockaddr_in SlSockAddrIn_t - -#define MSG_DONTWAIT SL_MSG_DONTWAIT - -#define FD_SET SL_FD_SET -#define FD_CLR SL_FD_CLR -#define FD_ISSET SL_FD_ISSET -#define FD_ZERO SL_FD_ZERO -#define fd_set SlFdSet_t - -#define socket sl_Socket -#define close sl_Close -#define accept sl_Accept -#define bind sl_Bind -#define listen sl_Listen -#define connect sl_Connect -#define select sl_Select -#define setsockopt sl_SetSockOpt -#define getsockopt sl_GetSockOpt -#define recv sl_Recv -#define recvfrom sl_RecvFrom -#define write sl_Write -#define send sl_Send -#define sendto sl_SendTo -#define gethostbyname sl_NetAppDnsGetHostByName -#define htonl sl_Htonl -#define ntohl sl_Ntohl -#define htons sl_Htons -#define ntohs sl_Ntohs -#endif - -/*****************************************************************************/ -/* Structure/Enum declarations */ -/*****************************************************************************/ - -/* Internet address */ -typedef struct SlInAddr_t -{ -#ifndef s_addr - _u32 s_addr; /* Internet address 32 bits */ -#else - union S_un { - struct { _u8 s_b1,s_b2,s_b3,s_b4; } S_un_b; - struct { _u8 s_w1,s_w2; } S_un_w; - _u32 S_addr; - } S_un; -#endif -}SlInAddr_t; - - -/* sockopt */ -typedef struct -{ - _u32 KeepaliveEnabled; /* 0 = disabled;1 = enabled; default = 1*/ -}SlSockKeepalive_t; - -typedef struct -{ - _u32 ReuseaddrEnabled; /* 0 = disabled; 1 = enabled; default = 1*/ -}SlSockReuseaddr_t; - -typedef struct -{ - _u32 Winsize; /* receive window size for tcp sockets */ -}SlSockWinsize_t; - -typedef struct -{ - _u32 NonblockingEnabled;/* 0 = disabled;1 = enabled;default = 1*/ -}SlSockNonblocking_t; - - -typedef struct -{ - _u8 sd; - _u8 type; - _i16 val; - _u8* pExtraInfo; -} SlSocketAsyncEvent_t; - -typedef struct -{ - _i16 status; - _u8 sd; - _u8 padding; -} SlSockTxFailEventData_t; - - -typedef union -{ - SlSockTxFailEventData_t SockTxFailData; - SlSocketAsyncEvent_t SockAsyncData; -} SlSockEventData_u; - - -typedef struct -{ - _u32 Event; - SlSockEventData_u socketAsyncEvent; -} SlSockEvent_t; - - - - - - -typedef struct -{ - _u32 secureMask; -} SlSockSecureMask; - -typedef struct -{ - _u8 secureMethod; -} SlSockSecureMethod; - -typedef enum -{ - SL_BSD_SECURED_PRIVATE_KEY_IDX = 0, - SL_BSD_SECURED_CERTIFICATE_IDX, - SL_BSD_SECURED_CA_IDX, - SL_BSD_SECURED_DH_IDX -}slBsd_secureSocketFilesIndex_e; - -typedef struct -{ - SlInAddr_t imr_multiaddr; /* The IPv4 multicast address to join */ - SlInAddr_t imr_interface; /* The interface to use for this group */ -} SlSockIpMreq; - - -/* sockopt */ -typedef _u32 SlTime_t; -typedef _u32 SlSuseconds_t; - -typedef struct SlTimeval_t -{ - SlTime_t tv_sec; /* Seconds */ - SlSuseconds_t tv_usec; /* Microseconds */ -}SlTimeval_t; - -typedef _u16 SlSocklen_t; - -/* IpV4 socket address */ -typedef struct SlSockAddr_t -{ - _u16 sa_family; /* Address family (e.g. , AF_INET) */ - _u8 sa_data[14]; /* Protocol- specific address information*/ -}SlSockAddr_t; - - -/* IpV6 or Ipv6 EUI64 */ -typedef struct SlIn6Addr_t -{ - union - { - _u8 _S6_u8[16]; - _u32 _S6_u32[4]; - } _S6_un; -}SlIn6Addr_t; - -typedef struct SlSockAddrIn6_t -{ - _u16 sin6_family; /* AF_INET6 || AF_INET6_EUI_48*/ - _u16 sin6_port; /* Transport layer port. */ - _u32 sin6_flowinfo; /* IPv6 flow information. */ - SlIn6Addr_t sin6_addr; /* IPv6 address. */ - _u32 sin6_scope_id; /* set of interfaces for a scope. */ -}SlSockAddrIn6_t; - -/* Socket address, Internet style. */ - -typedef struct SlSockAddrIn_t -{ - _u16 sin_family; /* Internet Protocol (AF_INET). */ - _u16 sin_port; /* Address port (16 bits). */ - SlInAddr_t sin_addr; /* Internet address (32 bits). */ - _i8 sin_zero[8]; /* Not used. */ -}SlSockAddrIn_t; - -typedef struct -{ - _u32 ip; - _u32 gateway; - _u32 dns; -}SlIpV4AcquiredAsync_t; - -typedef struct -{ - _u32 type; - _u32 ip[4]; - _u32 gateway[4]; - _u32 dns[4]; -}SlIpV6AcquiredAsync_t; - -typedef struct -{ - _u32 ip_address; - _u32 lease_time; - _u8 mac[6]; - _u16 padding; -}SlIpLeasedAsync_t; - -typedef struct -{ - _u32 ip_address; - _u8 mac[6]; - _u16 reason; -}SlIpReleasedAsync_t; - - -typedef union -{ - SlIpV4AcquiredAsync_t ipAcquiredV4; /*SL_NETAPP_IPV4_IPACQUIRED_EVENT*/ - SlIpV6AcquiredAsync_t ipAcquiredV6; /*SL_NETAPP_IPV6_IPACQUIRED_EVENT*/ - _u32 sd; /*SL_SOCKET_TX_FAILED_EVENT*/ - SlIpLeasedAsync_t ipLeased; /* SL_NETAPP_IP_LEASED_EVENT */ - SlIpReleasedAsync_t ipReleased; /* SL_NETAPP_IP_RELEASED_EVENT */ -} SlNetAppEventData_u; - -typedef struct -{ - _u32 Event; - SlNetAppEventData_u EventData; -}SlNetAppEvent_t; - - -typedef struct sock_secureFiles -{ - _u8 secureFiles[4]; -}SlSockSecureFiles_t; - - -typedef struct SlFdSet_t /* The select socket array manager */ -{ - _u32 fd_array[(SL_FD_SETSIZE + 31)/32]; /* Bit map of SOCKET Descriptors */ -} SlFdSet_t; - -typedef struct -{ - _u8 rate; /* Recevied Rate */ - _u8 channel; /* The received channel*/ - _i8 rssi; /* The computed RSSI value in db of current frame */ - _u8 padding; /* pad to align to 32 bits */ - _u32 timestamp; /* Timestamp in microseconds, */ -}SlTransceiverRxOverHead_t; - - - -/*****************************************************************************/ -/* Function prototypes */ -/*****************************************************************************/ - -/*! - - \brief create an endpoint for communication - - The socket function creates a new socket of a certain socket type, identified - by an integer number, and allocates system resources to it. - This function is called by the application layer to obtain a socket handle. - - \param[in] domain specifies the protocol family of the created socket. - For example: - AF_INET for network protocol IPv4 - AF_RF for starting transceiver mode. Notes: - - sending and receiving any packet overriding 802.11 header - - for optimized power consumption the socket will be started in TX - only mode until receive command is activated - AF_INET6 for IPv6 - - - \param[in] type specifies the communication semantic, one of: - SOCK_STREAM (reliable stream-oriented service or Stream Sockets) - SOCK_DGRAM (datagram service or Datagram Sockets) - SOCK_RAW (raw protocols atop the network layer) - when used with AF_RF: - SOCK_DGRAM - L2 socket - SOCK_RAW - L1 socket - bypass WLAN CCA (Clear Channel Assessment) - - \param[in] protocol specifies a particular transport to be used with - the socket. - The most common are IPPROTO_TCP, IPPROTO_SCTP, IPPROTO_UDP, - IPPROTO_DCCP. - The value 0 may be used to select a default - protocol from the selected domain and type - - - \return On success, socket handle that is used for consequent socket operations. - A successful return code should be a positive number (int16) - On error, a negative (int16) value will be returned specifying the error code. - SL_EAFNOSUPPORT - illegal domain parameter - SL_EPROTOTYPE - illegal type parameter - SL_EACCES - permission denied - SL_ENSOCK - exceeded maximal number of socket - SL_ENOMEM - memory allocation error - SL_EINVAL - error in socket configuration - SL_EPROTONOSUPPORT - illegal protocol parameter - SL_EOPNOTSUPP - illegal combination of protocol and type parameters - - - \sa sl_Close - \note belongs to \ref basic_api - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_Socket) -_i16 sl_Socket(_i16 Domain, _i16 Type, _i16 Protocol); -#endif - -/*! - \brief gracefully close socket - - This function causes the system to release resources allocated to a socket. \n - In case of TCP, the connection is terminated. - - \param[in] sd socket handle (received in sl_Socket) - - \return On success, zero is returned. - On error, a negative number is returned. - - \sa sl_Socket - \note belongs to \ref ext_api - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_Close) -_i16 sl_Close(_i16 sd); -#endif - -/*! - \brief Accept a connection on a socket - - This function is used with connection-based socket types (SOCK_STREAM). - It extracts the first connection request on the queue of pending - connections, creates a new connected socket, and returns a new file - descriptor referring to that socket. - The newly created socket is not in the listening state. The - original socket sd is unaffected by this call. - The argument sd is a socket that has been created with - sl_Socket(), bound to a local address with sl_Bind(), and is - listening for connections after a sl_Listen(). The argument \b - \e addr is a pointer to a sockaddr structure. This structure - is filled in with the address of the peer socket, as known to - the communications layer. The exact format of the address - returned addr is determined by the socket's address family. - The \b \e addrlen argument is a value-result argument: it - should initially contain the size of the structure pointed to - by addr, on return it will contain the actual length (in - bytes) of the address returned. - - \param[in] sd socket descriptor (handle) - \param[out] addr the argument addr is a pointer - to a sockaddr structure. This - structure is filled in with the - address of the peer socket, as - known to the communications - layer. The exact format of the - address returned addr is - determined by the socket's - address\n - sockaddr:\n - code for the - address format. On this version - only AF_INET is supported.\n - - socket address, the length - depends on the code format - \param[out] addrlen the addrlen argument is a value-result - argument: it should initially contain the - size of the structure pointed to by addr - - \return On success, a socket handle. - On a non-blocking accept a possible negative value is SL_EAGAIN. - On failure, negative value. - SL_POOL_IS_EMPTY may be return in case there are no resources in the system - In this case try again later or increase MAX_CONCURRENT_ACTIONS - - \sa sl_Socket sl_Bind sl_Listen - \note belongs to \ref server_side - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_Accept) -_i16 sl_Accept(_i16 sd, SlSockAddr_t *addr, SlSocklen_t *addrlen); -#endif - -/*! - \brief assign a name to a socket - - This function gives the socket the local address addr. - addr is addrlen bytes long. Traditionally, this is called - When a socket is created with socket, it exists in a name - space (address family) but has no name assigned. - It is necessary to assign a local address before a SOCK_STREAM - socket may receive connections. - - \param[in] sd socket descriptor (handle) - \param[in] addr specifies the destination - addrs\n sockaddr:\n - code for - the address format. On this - version only AF_INET is - supported.\n - socket address, - the length depends on the code - format - \param[in] addrlen contains the size of the structure pointed to by addr - - \return On success, zero is returned. On error, a negative error code is returned. - - \sa sl_Socket sl_Accept sl_Listen - \note belongs to \ref basic_api - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_Bind) -_i16 sl_Bind(_i16 sd, const SlSockAddr_t *addr, _i16 addrlen); -#endif - -/*! - \brief listen for connections on a socket - - The willingness to accept incoming connections and a queue - limit for incoming connections are specified with listen(), - and then the connections are accepted with accept. - The listen() call applies only to sockets of type SOCK_STREAM - The backlog parameter defines the maximum length the queue of - pending connections may grow to. - - \param[in] sd socket descriptor (handle) - \param[in] backlog specifies the listen queue depth. - - - \return On success, zero is returned. On error, a negative error code is returned. - - \sa sl_Socket sl_Accept sl_Bind - \note belongs to \ref server_side - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_Listen) -_i16 sl_Listen(_i16 sd, _i16 backlog); -#endif - -/*! - \brief Initiate a connection on a socket - - Function connects the socket referred to by the socket - descriptor sd, to the address specified by addr. The addrlen - argument specifies the size of addr. The format of the - address in addr is determined by the address space of the - socket. If it is of type SOCK_DGRAM, this call specifies the - peer with which the socket is to be associated; this address - is that to which datagrams are to be sent, and the only - address from which datagrams are to be received. If the - socket is of type SOCK_STREAM, this call attempts to make a - connection to another socket. The other socket is specified - by address, which is an address in the communications space - of the socket. - - - \param[in] sd socket descriptor (handle) - \param[in] addr specifies the destination addr\n - sockaddr:\n - code for the - address format. On this version - only AF_INET is supported.\n - - socket address, the length - depends on the code format - - \param[in] addrlen contains the size of the structure pointed - to by addr - - \return On success, a socket handle. - On a non-blocking connect a possible negative value is SL_EALREADY. - On failure, negative value. - SL_POOL_IS_EMPTY may be return in case there are no resources in the system - In this case try again later or increase MAX_CONCURRENT_ACTIONS - - \sa sl_Socket - \note belongs to \ref client_side - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_Connect) -_i16 sl_Connect(_i16 sd, const SlSockAddr_t *addr, _i16 addrlen); -#endif - -/*! - \brief Monitor socket activity - - Select allow a program to monitor multiple file descriptors, - waiting until one or more of the file descriptors become - "ready" for some class of I/O operation - - - \param[in] nfds the highest-numbered file descriptor in any of the - three sets, plus 1. - \param[out] readsds socket descriptors list for read monitoring and accept monitoring - \param[out] writesds socket descriptors list for connect monitoring only, write monitoring is not supported, non blocking connect is supported - \param[out] exceptsds socket descriptors list for exception monitoring, not supported. - \param[in] timeout is an upper bound on the amount of time elapsed - before select() returns. Null or above 0xffff seconds means - infinity timeout. The minimum timeout is 10 milliseconds, - less than 10 milliseconds will be set automatically to 10 milliseconds. - Max microseconds supported is 0xfffc00. - - \return On success, select() returns the number of - file descriptors contained in the three returned - descriptor sets (that is, the total number of bits that - are set in readfds, writefds, exceptfds) which may be - zero if the timeout expires before anything interesting - happens. On error, a negative value is returned. - readsds - return the sockets on which Read request will - return without delay with valid data. - writesds - return the sockets on which Write request - will return without delay. - exceptsds - return the sockets closed recently. - SL_POOL_IS_EMPTY may be return in case there are no resources in the system - In this case try again later or increase MAX_CONCURRENT_ACTIONS - - \sa sl_Socket - \note If the timeout value set to less than 5ms it will automatically set - to 5ms to prevent overload of the system - belongs to \ref basic_api - - Only one sl_Select can be handled at a time. - Calling this API while the same command is called from another thread, may result - in one of the two scenarios: - 1. The command will wait (internal) until the previous command finish, and then be executed. - 2. There are not enough resources and SL_POOL_IS_EMPTY error will return. - In this case, MAX_CONCURRENT_ACTIONS can be increased (result in memory increase) or try - again later to issue the command. - - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_Select) -_i16 sl_Select(_i16 nfds, SlFdSet_t *readsds, SlFdSet_t *writesds, SlFdSet_t *exceptsds, struct SlTimeval_t *timeout); - - -/*! - \brief Select's SlFdSet_t SET function - - Sets current socket descriptor on SlFdSet_t container -*/ -void SL_FD_SET(_i16 fd, SlFdSet_t *fdset); - -/*! - \brief Select's SlFdSet_t CLR function - - Clears current socket descriptor on SlFdSet_t container -*/ -void SL_FD_CLR(_i16 fd, SlFdSet_t *fdset); - - -/*! - \brief Select's SlFdSet_t ISSET function - - Checks if current socket descriptor is set (TRUE/FALSE) - - \return Returns TRUE if set, FALSE if unset - -*/ -_i16 SL_FD_ISSET(_i16 fd, SlFdSet_t *fdset); - -/*! - \brief Select's SlFdSet_t ZERO function - - Clears all socket descriptors from SlFdSet_t -*/ -void SL_FD_ZERO(SlFdSet_t *fdset); - - - -#endif - -/*! - \brief set socket options - - This function manipulate the options associated with a socket. - Options may exist at multiple protocol levels; they are always - present at the uppermost socket level. - - When manipulating socket options the level at which the option resides - and the name of the option must be specified. To manipulate options at - the socket level, level is specified as SOL_SOCKET. To manipulate - options at any other level the protocol number of the appropriate proto- - col controlling the option is supplied. For example, to indicate that an - option is to be interpreted by the TCP protocol, level should be set to - the protocol number of TCP; - - The parameters optval and optlen are used to access optval - - ues for setsockopt(). For getsockopt() they identify a - buffer in which the value for the requested option(s) are to - be returned. For getsockopt(), optlen is a value-result - parameter, initially containing the size of the buffer - pointed to by option_value, and modified on return to - indicate the actual size of the value returned. If no option - value is to be supplied or returned, option_value may be - NULL. - - \param[in] sd socket handle - \param[in] level defines the protocol level for this option - - SL_SOL_SOCKET Socket level configurations (L4, transport layer) - - SL_IPPROTO_IP IP level configurations (L3, network layer) - - SL_SOL_PHY_OPT Link level configurations (L2, link layer) - \param[in] optname defines the option name to interrogate - - SL_SOL_SOCKET - - SL_SO_KEEPALIVE \n - Enable/Disable periodic keep alive. - Keeps TCP connections active by enabling the periodic transmission of messages \n - Timeout is 5 minutes.\n - Default: Enabled \n - This options takes SlSockKeepalive_t struct as parameter - - SL_SO_RCVTIMEO \n - Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. \n - Default: No timeout \n - This options takes SlTimeval_t struct as parameter - - SL_SO_RCVBUF \n - Sets tcp max recv window size. \n - This options takes SlSockWinsize_t struct as parameter - - SL_SO_NONBLOCKING \n - Sets socket to non-blocking operation Impacts: connect, accept, send, sendto, recv and recvfrom. \n - Default: Blocking. - This options takes SlSockNonblocking_t struct as parameter - - SL_SO_SECMETHOD \n - Sets method to tcp secured socket (SL_SEC_SOCKET) \n - Default: SL_SO_SEC_METHOD_SSLv3_TLSV1_2 \n - This options takes SlSockSecureMethod struct as parameter - - SL_SO_SEC_MASK \n - Sets specific cipher to tcp secured socket (SL_SEC_SOCKET) \n - Default: "Best" cipher suitable to method \n - This options takes SlSockSecureMask struct as parameter - - SL_SO_SECURE_FILES_CA_FILE_NAME \n - Map secured socket to CA file by name \n - This options takes _u8 buffer as parameter - - SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME \n - Map secured socket to private key by name \n - This options takes _u8 buffer as parameter - - SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME \n - Map secured socket to certificate file by name \n - This options takes _u8 buffer as parameter - - SL_SO_SECURE_FILES_DH_KEY_FILE_NAME \n - Map secured socket to Diffie Hellman file by name \n - This options takes _u8 buffer as parameter - - SL_SO_CHANGE_CHANNEL \n - Sets channel in transceiver mode. - This options takes _u32 as channel number parameter - - SL_IPPROTO_IP - - SL_IP_MULTICAST_TTL \n - Set the time-to-live value of outgoing multicast packets for this socket. \n - This options takes _u8 as parameter - - SL_IP_ADD_MEMBERSHIP \n - UDP socket, Join a multicast group. \n - This options takes SlSockIpMreq struct as parameter - - SL_IP_DROP_MEMBERSHIP \n - UDP socket, Leave a multicast group \n - This options takes SlSockIpMreq struct as parameter - - SL_IP_RAW_RX_NO_HEADER \n - Raw socket remove IP header from received data. \n - Default: data includes ip header \n - This options takes _u32 as parameter - - SL_IP_HDRINCL \n - RAW socket only, the IPv4 layer generates an IP header when sending a packet unless \n - the IP_HDRINCL socket option is enabled on the socket. \n - When it is enabled, the packet must contain an IP header. \n - Default: disabled, IPv4 header generated by Network Stack \n - This options takes _u32 as parameter - - SL_IP_RAW_IPV6_HDRINCL (inactive) \n - RAW socket only, the IPv6 layer generates an IP header when sending a packet unless \n - the IP_HDRINCL socket option is enabled on the socket. When it is enabled, the packet must contain an IP header \n - Default: disabled, IPv4 header generated by Network Stack \n - This options takes _u32 as parameter - - SL_SOL_PHY_OPT - - SL_SO_PHY_RATE \n - RAW socket, set WLAN PHY transmit rate \n - The values are based on RateIndex_e \n - This options takes _u32 as parameter - - SL_SO_PHY_TX_POWER \n - RAW socket, set WLAN PHY TX power \n - Valid rage is 1-15 \n - This options takes _u32 as parameter - - SL_SO_PHY_NUM_FRAMES_TO_TX \n - RAW socket, set number of frames to transmit in transceiver mode. - Default: 1 packet - This options takes _u32 as parameter - - SL_SO_PHY_PREAMBLE \n - RAW socket, set WLAN PHY preamble for Long/Short\n - This options takes _u32 as parameter - - \param[in] optval specifies a value for the option - \param[in] optlen specifies the length of the - option value - - \return On success, zero is returned. - On error, a negative value is returned. - \sa sl_getsockopt - \note belongs to \ref basic_api - \warning - \par Examples: - \par - SL_SO_KEEPALIVE: (disable Keepalive) - \code - SlSockKeepalive_t enableOption; - enableOption.KeepaliveEnabled = 0; - sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_KEEPALIVE, (_u8 *)&enableOption,sizeof(enableOption)); - \endcode - \par - SL_SO_RCVTIMEO: - \code - struct SlTimeval_t timeVal; - timeVal.tv_sec = 1; // Seconds - timeVal.tv_usec = 0; // Microseconds. 10000 microseconds resolution - sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_RCVTIMEO, (_u8 *)&timeVal, sizeof(timeVal)); // Enable receive timeout - \endcode - \par - SL_SO_RCVBUF: - \code - SlSockWinsize_t size; - size.Winsize = 3000; // bytes - sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_RCVBUF, (_u8 *)&size, sizeof(size)); - \endcode - \par - SL_SO_NONBLOCKING: - \code - SlSockNonblocking_t enableOption; - enableOption.NonblockingEnabled = 1; - sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_NONBLOCKING, (_u8 *)&enableOption,sizeof(enableOption)); // Enable/disable nonblocking mode - \endcode - \par - SL_SO_SECMETHOD: - \code - SlSockSecureMethod method; - method.secureMethod = SL_SO_SEC_METHOD_SSLV3; // security method we want to use - SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET); - sl_SetSockOpt(SockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, (_u8 *)&method, sizeof(method)); - \endcode - \par - SL_SO_SECURE_MASK: - \code - SlSockSecureMask cipher; - cipher.secureMask = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA; // cipher type - SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET); - sl_SetSockOpt(SockID, SL_SOL_SOCKET, SL_SO_SEC_MASK,(_u8 *)&cipher, sizeof(cipher)); - \endcode - \par - SL_SO_SECURE_FILES_CA_FILE_NAME: - \code - sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_SECURE_FILES_CA_FILE_NAME,"exuifaxCaCert.der",strlen("exuifaxCaCert.der")); - \endcode - - \par - SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME: - \code - sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME,"myPrivateKey.der",strlen("myPrivateKey.der")); - \endcode - - \par - SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME: - \code - sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME,"myCertificate.der",strlen("myCertificate.der")); - \endcode - - \par - SL_SO_SECURE_FILES_DH_KEY_FILE_NAME: - \code - sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_SECURE_FILES_DH_KEY_FILE_NAME,"myDHinServerMode.der",strlen("myDHinServerMode.der")); - \endcode - - \par - SL_IP_MULTICAST_TTL: - \code - _u8 ttl = 20; - sl_SetSockOpt(SockID, SL_IPPROTO_IP, SL_IP_MULTICAST_TTL, &ttl, sizeof(ttl)); - \endcode - - \par - SL_IP_ADD_MEMBERSHIP: - \code - SlSockIpMreq mreq; - sl_SetSockOpt(SockID, SL_IPPROTO_IP, SL_IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)); - \endcode - - \par - SL_IP_DROP_MEMBERSHIP: - \code - SlSockIpMreq mreq; - sl_SetSockOpt(SockID, SL_IPPROTO_IP, SL_IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq)); - \endcode - - \par - SL_SO_CHANGE_CHANNEL: - \code - _u32 newChannel = 6; // range is 1-13 - sl_SetSockOpt(SockID, SL_SOL_SOCKET, SL_SO_CHANGE_CHANNEL, &newChannel, sizeof(newChannel)); - \endcode - - \par - SL_IP_RAW_RX_NO_HEADER: - \code - _u32 header = 1; // remove ip header - sl_SetSockOpt(SockID, SL_IPPROTO_IP, SL_IP_RAW_RX_NO_HEADER, &header, sizeof(header)); - \endcode - - \par - SL_IP_HDRINCL: - \code - _u32 header = 1; - sl_SetSockOpt(SockID, SL_IPPROTO_IP, SL_IP_HDRINCL, &header, sizeof(header)); - \endcode - \par - SL_IP_RAW_IPV6_HDRINCL: - \code - _u32 header = 1; - sl_SetSockOpt(SockID, SL_IPPROTO_IP, SL_IP_RAW_IPV6_HDRINCL, &header, sizeof(header)); - \endcode - - \par - SL_SO_PHY_RATE: - \code - _u32 rate = 6; // see wlan.h RateIndex_e for values - sl_SetSockOpt(SockID, SL_SOL_PHY_OPT, SL_SO_PHY_RATE, &rate, sizeof(rate)); - \endcode - - \par - SL_SO_PHY_TX_POWER: - \code - _u32 txpower = 1; // valid range is 1-15 - sl_SetSockOpt(SockID, SL_SOL_PHY_OPT, SL_SO_PHY_TX_POWER, &txpower, sizeof(txpower)); - \endcode - - \par - SL_SO_PHY_NUM_FRAMES_TO_TX: - \code - _u32 numframes = 1; - sl_SetSockOpt(SockID, SL_SOL_PHY_OPT, SL_SO_PHY_NUM_FRAMES_TO_TX, &numframes, sizeof(numframes)); - \endcode - - \par - SL_SO_PHY_PREAMBLE: - \code - _u32 preamble = 1; - sl_SetSockOpt(SockID, SL_SOL_PHY_OPT, SL_SO_PHY_PREAMBLE, &preamble, sizeof(preamble)); - \endcode - -*/ -#if _SL_INCLUDE_FUNC(sl_SetSockOpt) -_i16 sl_SetSockOpt(_i16 sd, _i16 level, _i16 optname, const void *optval, SlSocklen_t optlen); -#endif - -/*! - \brief Get socket options - - This function manipulate the options associated with a socket. - Options may exist at multiple protocol levels; they are always - present at the uppermost socket level. - - When manipulating socket options the level at which the option resides - and the name of the option must be specified. To manipulate options at - the socket level, level is specified as SOL_SOCKET. To manipulate - options at any other level the protocol number of the appropriate proto- - col controlling the option is supplied. For example, to indicate that an - option is to be interpreted by the TCP protocol, level should be set to - the protocol number of TCP; - - The parameters optval and optlen are used to access optval - - ues for setsockopt(). For getsockopt() they identify a - buffer in which the value for the requested option(s) are to - be returned. For getsockopt(), optlen is a value-result - parameter, initially containing the size of the buffer - pointed to by option_value, and modified on return to - indicate the actual size of the value returned. If no option - value is to be supplied or returned, option_value may be - NULL. - - - \param[in] sd socket handle - \param[in] level defines the protocol level for this option - \param[in] optname defines the option name to interrogate - \param[out] optval specifies a value for the option - \param[out] optlen specifies the length of the - option value - - \return On success, zero is returned. - On error, a negative value is returned. - \sa sl_SetSockOpt - \note See sl_SetSockOpt - belongs to \ref ext_api - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_GetSockOpt) -_i16 sl_GetSockOpt(_i16 sd, _i16 level, _i16 optname, void *optval, SlSocklen_t *optlen); -#endif - -/*! - \brief read data from TCP socket - - function receives a message from a connection-mode socket - - \param[in] sd socket handle - \param[out] buf Points to the buffer where the - message should be stored. - \param[in] Len Specifies the length in bytes of - the buffer pointed to by the buffer argument. - Range: 1-16000 bytes - \param[in] flags Specifies the type of message - reception. On this version, this parameter is not - supported. - - \return return the number of bytes received, - or a negative value if an error occurred. - using a non-blocking recv a possible negative value is SL_EAGAIN. - SL_POOL_IS_EMPTY may be return in case there are no resources in the system - In this case try again later or increase MAX_CONCURRENT_ACTIONS - - \sa sl_RecvFrom - \note belongs to \ref recv_api - \warning - \par Examples: - \code An example of receiving data using TCP socket: - - SlSockAddrIn_t Addr; - SlSockAddrIn_t LocalAddr; - _i16 AddrSize = sizeof(SlSockAddrIn_t); - _i16 SockID, newSockID; - _i16 Status; - _i8 Buf[RECV_BUF_LEN]; - - LocalAddr.sin_family = SL_AF_INET; - LocalAddr.sin_port = sl_Htons(5001); - LocalAddr.sin_addr.s_addr = 0; - - Addr.sin_family = SL_AF_INET; - Addr.sin_port = sl_Htons(5001); - Addr.sin_addr.s_addr = sl_Htonl(SL_IPV4_VAL(10,1,1,200)); - - SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); - Status = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, AddrSize); - Status = sl_Listen(SockID, 0); - newSockID = sl_Accept(SockID, (SlSockAddr_t*)&Addr, (SlSocklen_t*) &AddrSize); - Status = sl_Recv(newSockID, Buf, 1460, 0); - \endcode - \code Example code for Rx transceiver mode using a raw socket - _i8 buffer[1536]; - _i16 sd; - _u16 size; - SlTransceiverRxOverHead_t *transHeader; - sd = sl_Socket(SL_AF_RF,SL_SOCK_RAW,11); // channel 11 - while(1) - { - size = sl_Recv(sd,buffer,1536,0); - transHeader = (SlTransceiverRxOverHead_t *)buffer; - printf("RSSI is %d frame type is 0x%x size %d\n",transHeader->rssi,buffer[sizeof(SlTransceiverRxOverHead_t)],size); - } - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_Recv) -_i16 sl_Recv(_i16 sd, void *buf, _i16 Len, _i16 flags); -#endif - -/*! - \brief read data from socket - - function receives a message from a connection-mode or - connectionless-mode socket - - \param[in] sd socket handle - \param[out] buf Points to the buffer where the message should be stored. - \param[in] Len Specifies the length in bytes of the buffer pointed to by the buffer argument. - Range: 1-16000 bytes - \param[in] flags Specifies the type of message - reception. On this version, this parameter is not - supported. - \param[in] from pointer to an address structure - indicating the source - address.\n sockaddr:\n - code - for the address format. On this - version only AF_INET is - supported.\n - socket address, - the length depends on the code - format - \param[in] fromlen source address structure - size. This parameter MUST be set to the size of the structure pointed to by addr. - - - \return return the number of bytes received, - or a negative value if an error occurred. - using a non-blocking recv a possible negative value is SL_EAGAIN. - SL_RET_CODE_INVALID_INPUT (-2) will be returned if fromlen has incorrect length. - SL_POOL_IS_EMPTY may be return in case there are no resources in the system - In this case try again later or increase MAX_CONCURRENT_ACTIONS - - \sa sl_Recv - \note belongs to \ref recv_api - \warning - \par Example: - \code An example of receiving data: - - SlSockAddrIn_t Addr; - SlSockAddrIn_t LocalAddr; - _i16 AddrSize = sizeof(SlSockAddrIn_t); - _i16 SockID; - _i16 Status; - _i8 Buf[RECV_BUF_LEN]; - - LocalAddr.sin_family = SL_AF_INET; - LocalAddr.sin_port = sl_Htons(5001); - LocalAddr.sin_addr.s_addr = 0; - - SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); - Status = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, AddrSize); - Status = sl_RecvFrom(SockID, Buf, 1472, 0, (SlSockAddr_t *)&Addr, (SlSocklen_t*)&AddrSize); - - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_RecvFrom) -_i16 sl_RecvFrom(_i16 sd, void *buf, _i16 Len, _i16 flags, SlSockAddr_t *from, SlSocklen_t *fromlen); -#endif - -/*! - \brief write data to TCP socket - - This function is used to transmit a message to another socket. - Returns immediately after sending data to device. - In case of TCP failure an async event SL_SOCKET_TX_FAILED_EVENT is going to - be received. - In case of a RAW socket (transceiver mode), extra 4 bytes should be reserved at the end of the - frame data buffer for WLAN FCS - - \param[in] sd socket handle - \param[in] buf Points to a buffer containing - the message to be sent - \param[in] Len message size in bytes. Range: 1-1460 bytes - \param[in] flags Specifies the type of message - transmission. On this version, this parameter is not - supported for TCP. - For transceiver mode, the SL_RAW_RF_TX_PARAMS macro can be used to determine - transmission parameters (channel,rate,tx_power,preamble) - - - \return Return the number of bytes transmitted, - or -1 if an error occurred - - \sa sl_SendTo - \note belongs to \ref send_api - \warning - \par Example: - \code An example of sending data: - - SlSockAddrIn_t Addr; - _i16 AddrSize = sizeof(SlSockAddrIn_t); - _i16 SockID; - _i16 Status; - _i8 Buf[SEND_BUF_LEN]; - - Addr.sin_family = SL_AF_INET; - Addr.sin_port = sl_Htons(5001); - Addr.sin_addr.s_addr = sl_Htonl(SL_IPV4_VAL(10,1,1,200)); - - SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); - Status = sl_Connect(SockID, (SlSockAddr_t *)&Addr, AddrSize); - Status = sl_Send(SockID, Buf, 1460, 0 ); - - \endcode - */ -#if _SL_INCLUDE_FUNC(sl_Send ) -_i16 sl_Send(_i16 sd, const void *buf, _i16 Len, _i16 flags); -#endif - -/*! - \brief write data to socket - - This function is used to transmit a message to another socket - (connection less socket SOCK_DGRAM, SOCK_RAW). - Returns immediately after sending data to device. - In case of transmission failure an async event SL_SOCKET_TX_FAILED_EVENT is going to - be received. - - \param[in] sd socket handle - \param[in] buf Points to a buffer containing - the message to be sent - \param[in] Len message size in bytes. Range: 1-1460 bytes - \param[in] flags Specifies the type of message - transmission. On this version, this parameter is not - supported - \param[in] to pointer to an address structure - indicating the destination - address.\n sockaddr:\n - code - for the address format. On this - version only AF_INET is - supported.\n - socket address, - the length depends on the code - format - \param[in] tolen destination address structure size - - \return Return the number of transmitted bytes, - or -1 if an error occurred - - \sa sl_Send - \note belongs to \ref send_api - \warning - \par Example: - \code An example of sending data: - - SlSockAddrIn_t Addr; - _i16 AddrSize = sizeof(SlSockAddrIn_t); - _i16 SockID; - _i16 Status; - _i8 Buf[SEND_BUF_LEN]; - - Addr.sin_family = SL_AF_INET; - Addr.sin_port = sl_Htons(5001); - Addr.sin_addr.s_addr = sl_Htonl(SL_IPV4_VAL(10,1,1,200)); - - SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); - Status = sl_SendTo(SockID, Buf, 1472, 0, (SlSockAddr_t *)&Addr, AddrSize); - - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_SendTo) -_i16 sl_SendTo(_i16 sd, const void *buf, _i16 Len, _i16 flags, const SlSockAddr_t *to, SlSocklen_t tolen); -#endif - -/*! - \brief Reorder the bytes of a 32-bit unsigned value - - This function is used to Reorder the bytes of a 32-bit unsigned value from processor order to network order. - - \param[in] var variable to reorder - - \return Return the reorder variable, - - \sa sl_SendTo sl_Bind sl_Connect sl_RecvFrom sl_Accept - \note belongs to \ref send_api - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_Htonl ) -_u32 sl_Htonl( _u32 val ); - -#define sl_Ntohl sl_Htonl /* Reorder the bytes of a 16-bit unsigned value from network order to processor orde. */ -#endif - -/*! - \brief Reorder the bytes of a 16-bit unsigned value - - This function is used to Reorder the bytes of a 16-bit unsigned value from processor order to network order. - - \param[in] var variable to reorder - - \return Return the reorder variable, - - \sa sl_SendTo sl_Bind sl_Connect sl_RecvFrom sl_Accept - \note belongs to \ref send_api - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_Htons ) -_u16 sl_Htons( _u16 val ); - -#define sl_Ntohs sl_Htons /* Reorder the bytes of a 16-bit unsigned value from network order to processor orde. */ -#endif - -/*! - - Close the Doxygen group. - @} - - */ - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __SOCKET_H__ */ - - diff --git a/drivers/cc3100/inc/spawn.h b/drivers/cc3100/inc/spawn.h deleted file mode 100644 index 82c112d2e1..0000000000 --- a/drivers/cc3100/inc/spawn.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * spawn.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - -#ifndef __NONOS_H__ -#define __NONOS_H__ - -#ifdef __cplusplus -extern "C" { -#endif - - -#if (defined (SL_PLATFORM_MULTI_THREADED)) && (!defined (SL_PLATFORM_EXTERNAL_SPAWN)) - -extern void _SlInternalSpawnTaskEntry(); -extern _i16 _SlInternalSpawn(_SlSpawnEntryFunc_t pEntry , void* pValue , _u32 flags); - -#undef sl_Spawn -#define sl_Spawn(pEntry,pValue,flags) _SlInternalSpawn(pEntry,pValue,flags) - -#undef _SlTaskEntry -#define _SlTaskEntry _SlInternalSpawnTaskEntry - - -#endif - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif diff --git a/drivers/cc3100/inc/trace.h b/drivers/cc3100/inc/trace.h deleted file mode 100644 index 4ca42c7701..0000000000 --- a/drivers/cc3100/inc/trace.h +++ /dev/null @@ -1,173 +0,0 @@ -/* - * trace.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - - - -#include "simplelink.h" - -#ifndef __SIMPLELINK_TRACE_H__ -#define __SIMPLELINK_TRACE_H__ - - -#ifdef __cplusplus -extern "C" { -#endif - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ - -#define SL_SYNC_SCAN_THRESHOLD (( _u32 )2000) - -#define _SL_ASSERT(expr) { ASSERT(expr); } -#define _SL_ERROR(expr, error) { if(!(expr)){return (error); } } - -#define SL_HANDLING_ASSERT 2 -#define SL_HANDLING_ERROR 1 -#define SL_HANDLING_NONE 0 - -#define SL_SELF_COND_HANDLING SL_HANDLING_NONE -#define SL_PROTOCOL_HANDLING SL_HANDLING_NONE -#define SL_DRV_RET_CODE_HANDLING SL_HANDLING_NONE -#define SL_NWP_IF_HANDLING SL_HANDLING_NONE -#define SL_OSI_RET_OK_HANDLING SL_HANDLING_NONE -#define SL_MALLOC_OK_HANDLING SL_HANDLING_NONE -#define SL_USER_ARGS_HANDLING SL_HANDLING_NONE - -#if (SL_DRV_RET_CODE_HANDLING == SL_HANDLING_ASSERT) -#define VERIFY_RET_OK(Func) {_SlReturnVal_t _RetVal = (Func); _SL_ASSERT((_SlReturnVal_t)SL_OS_RET_CODE_OK == _RetVal)} -#elif (SL_DRV_RET_CODE_HANDLING == SL_HANDLING_ERROR) -#define VERIFY_RET_OK(Func) {_SlReturnVal_t _RetVal = (Func); if (SL_OS_RET_CODE_OK != _RetVal) return _RetVal;} -#else -#define VERIFY_RET_OK(Func) (Func); -#endif - -#if (SL_PROTOCOL_HANDLING == SL_HANDLING_ASSERT) -#define VERIFY_PROTOCOL(expr) _SL_ASSERT(expr) -#elif (SL_PROTOCOL_HANDLING == SL_HANDLING_ERROR) -#define VERIFY_PROTOCOL(expr) _SL_ERROR(expr, SL_RET_CODE_PROTOCOL_ERROR) -#else -#define VERIFY_PROTOCOL(expr) -#endif - -#if (defined(PROTECT_SOCKET_ASYNC_RESP) && (SL_SELF_COND_HANDLING == SL_HANDLING_ASSERT)) -#define VERIFY_SOCKET_CB(expr) _SL_ASSERT(expr) -#elif (defined(PROTECT_SOCKET_ASYNC_RESP) && (SL_SELF_COND_HANDLING == SL_HANDLING_ERROR)) -#define VERIFY_SOCKET_CB(expr) _SL_ERROR(expr, SL_RET_CODE_SELF_ERROR) -#else -#define VERIFY_SOCKET_CB(expr) -#endif - -#if (SL_NWP_IF_HANDLING == SL_HANDLING_ASSERT) -#define NWP_IF_WRITE_CHECK(fd,pBuff,len) { _i16 RetSize, ExpSize = (len); RetSize = sl_IfWrite((fd),(pBuff),ExpSize); _SL_ASSERT(ExpSize == RetSize)} -#define NWP_IF_READ_CHECK(fd,pBuff,len) { _i16 RetSize, ExpSize = (len); RetSize = sl_IfRead((fd),(pBuff),ExpSize); _SL_ASSERT(ExpSize == RetSize)} -#elif (SL_NWP_IF_HANDLING == SL_HANDLING_ERROR) -#define NWP_IF_WRITE_CHECK(fd,pBuff,len) { _SL_ERROR((len == sl_IfWrite((fd),(pBuff),(len))), SL_RET_CODE_NWP_IF_ERROR);} -#define NWP_IF_READ_CHECK(fd,pBuff,len) { _SL_ERROR((len == sl_IfRead((fd),(pBuff),(len))), SL_RET_CODE_NWP_IF_ERROR);} -#else -#define NWP_IF_WRITE_CHECK(fd,pBuff,len) { sl_IfWrite((fd),(pBuff),(len));} -#define NWP_IF_READ_CHECK(fd,pBuff,len) { sl_IfRead((fd),(pBuff),(len));} -#endif - -#if (SL_OSI_RET_OK_HANDLING == SL_HANDLING_ASSERT) -#define OSI_RET_OK_CHECK(Func) {_SlReturnVal_t _RetVal = (Func); _SL_ASSERT((_SlReturnVal_t)SL_OS_RET_CODE_OK == _RetVal)} -#elif (SL_OSI_RET_OK_HANDLING == SL_HANDLING_ERROR) -#define OSI_RET_OK_CHECK(Func) {_SlReturnVal_t _RetVal = (Func); if (SL_OS_RET_CODE_OK != _RetVal) return _RetVal;} -#else -#define OSI_RET_OK_CHECK(Func) (Func); -#endif - -#if (SL_MALLOC_OK_HANDLING == SL_HANDLING_ASSERT) -#define MALLOC_OK_CHECK(Ptr) _SL_ASSERT(NULL != Ptr) -#elif (SL_MALLOC_OK_HANDLING == SL_HANDLING_ERROR) -#define MALLOC_OK_CHECK(Ptr) _SL_ERROR((NULL != Ptr), SL_RET_CODE_MALLOC_ERROR) -#else -#define MALLOC_OK_CHECK(Ptr) -#endif - -#ifdef SL_INC_ARG_CHECK - -#if (SL_USER_ARGS_HANDLING == SL_HANDLING_ASSERT) -#define ARG_CHECK_PTR(Ptr) _SL_ASSERT(NULL != Ptr) -#elif (SL_USER_ARGS_HANDLING == SL_HANDLING_ERROR) -#define ARG_CHECK_PTR(Ptr) _SL_ERROR((NULL != Ptr), SL_RET_CODE_INVALID_INPUT) -#else -#define ARG_CHECK_PTR(Ptr) -#endif - -#else -#define ARG_CHECK_PTR(Ptr) -#endif - -#define SL_TRACE0(level,msg_id,str) -#define SL_TRACE1(level,msg_id,str,p1) -#define SL_TRACE2(level,msg_id,str,p1,p2) -#define SL_TRACE3(level,msg_id,str,p1,p2,p3) -#define SL_TRACE4(level,msg_id,str,p1,p2,p3,p4) -#define SL_ERROR_TRACE(msg_id,str) -#define SL_ERROR_TRACE1(msg_id,str,p1) -#define SL_ERROR_TRACE2(msg_id,str,p1,p2) -#define SL_ERROR_TRACE3(msg_id,str,p1,p2,p3) -#define SL_ERROR_TRACE4(msg_id,str,p1,p2,p3,p4) -#define SL_TRACE_FLUSH() - -/* #define SL_DBG_CNT_ENABLE */ -#ifdef SL_DBG_CNT_ENABLE -#define _SL_DBG_CNT_INC(Cnt) g_DbgCnt. ## Cnt++ -#define _SL_DBG_SYNC_LOG(index,value) {if(index < SL_DBG_SYNC_LOG_SIZE){*(_u32 *)&g_DbgCnt.SyncLog[index] = *(_u32 *)(value);}} - -#else -#define _SL_DBG_CNT_INC(Cnt) -#define _SL_DBG_SYNC_LOG(index,value) -#endif - -#define SL_DBG_LEVEL_1 1 -#define SL_DBG_LEVEL_2 2 -#define SL_DBG_LEVEL_3 4 -#define SL_DBG_LEVEL_MASK (SL_DBG_LEVEL_2|SL_DBG_LEVEL_3) - -#define SL_INCLUDE_DBG_FUNC(Name) ((Name ## _DBG_LEVEL) & SL_DBG_LEVEL_MASK) - -#define _SlDrvPrintStat_DBG_LEVEL SL_DBG_LEVEL_3 -#define _SlDrvOtherFunc_DBG_LEVEL SL_DBG_LEVEL_1 - -#ifdef __cplusplus -} -#endif - - -#endif /*__SIMPLELINK_TRACE_H__*/ - diff --git a/drivers/cc3100/inc/wlan.h b/drivers/cc3100/inc/wlan.h deleted file mode 100644 index 156b94eab8..0000000000 --- a/drivers/cc3100/inc/wlan.h +++ /dev/null @@ -1,1308 +0,0 @@ -/* - * wlan.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" - -#ifndef __WLAN_H__ -#define __WLAN_H__ - - - - -#ifdef __cplusplus -extern "C" { -#endif - - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ - -/*! - - \addtogroup wlan - @{ - -*/ - -#define SL_BSSID_LENGTH (6) -#define MAXIMAL_SSID_LENGTH (32) - -#define NUM_OF_RATE_INDEXES (20) -#define SIZE_OF_RSSI_HISTOGRAM (6) - -/* WLAN Disconnect Reason Codes */ -#define SL_DISCONNECT_RESERVED_0 (0) -#define SL_DISCONNECT_UNSPECIFIED_REASON (1) -#define SL_PREVIOUS_AUTHENTICATION_NO_LONGER_VALID (2) -#define SL_DEAUTHENTICATED_BECAUSE_SENDING_STATION_IS_LEAVING (3) -#define SL_DISASSOCIATED_DUE_TO_INACTIVITY (4) -#define SL_DISASSOCIATED_BECAUSE_AP_IS_UNABLE_TO_HANDLE_ALL_CURRENTLY_ASSOCIATED_STATIONS (5) -#define SL_CLASS_2_FRAME_RECEIVED_FROM_NONAUTHENTICATED_STATION (6) -#define SL_CLASS_3_FRAME_RECEIVED_FROM_NONASSOCIATED_STATION (7) -#define SL_DISASSOCIATED_BECAUSE_SENDING_STATION_IS_LEAVING_BSS (8) -#define SL_STATION_REQUESTING_ASSOCIATION_IS_NOT_AUTHENTICATED_WITH_RESPONDING_STATION (9) -#define SL_DISASSOCIATED_BECAUSE_THE_INFORMATION_IN_THE_POWER_CAPABILITY_ELEMENT_IS_UNACCEPTABLE (10) -#define SL_DISASSOCIATED_BECAUSE_THE_INFORMATION_IN_THE_SUPPORTED_CHANNELS_ELEMENT_IS_UNACCEPTABLE (11) -#define SL_DISCONNECT_RESERVED_1 (12) -#define SL_INVALID_INFORMATION_ELEMENT (13) -#define SL_MESSAGE_INTEGRITY_CODE_MIC_FAILURE (14) -#define SL_FOUR_WAY_HANDSHAKE_TIMEOUT (15) -#define SL_GROUP_KEY_HANDSHAKE_TIMEOUT (16) -#define SL_RE_ASSOCIATION_REQUEST_PROBE_RESPONSE_BEACON_FRAME (17) -#define SL_INVALID_GROUP_CIPHER (18) -#define SL_INVALID_PAIRWISE_CIPHER (19) -#define SL_INVALID_AKMP (20) -#define SL_UNSUPPORTED_RSN_INFORMATION_ELEMENT_VERSION (21) -#define SL_INVALID_RSN_INFORMATION_ELEMENT_CAPABILITIES (22) -#define SL_IEEE_802_1X_AUTHENTICATION_FAILED (23) -#define SL_CIPHER_SUITE_REJECTED_BECAUSE_OF_THE_SECURITY_POLICY (24) -#define SL_DISCONNECT_RESERVED_2 (25) -#define SL_DISCONNECT_RESERVED_3 (26) -#define SL_DISCONNECT_RESERVED_4 (27) -#define SL_DISCONNECT_RESERVED_5 (28) -#define SL_DISCONNECT_RESERVED_6 (29) -#define SL_DISCONNECT_RESERVED_7 (30) -#define SL_DISCONNECT_RESERVED_8 (31) -#define SL_USER_INITIATED_DISCONNECTION (200) - -/* Wlan error codes */ -#define SL_ERROR_KEY_ERROR (-3) -#define SL_ERROR_INVALID_ROLE (-71) -#define SL_ERROR_INVALID_SECURITY_TYPE (-84) -#define SL_ERROR_PASSPHRASE_TOO_LONG (-85) -#define SL_ERROR_WPS_NO_PIN_OR_WRONG_PIN_LEN (-87) -#define SL_ERROR_EAP_WRONG_METHOD (-88) -#define SL_ERROR_PASSWORD_ERROR (-89) -#define SL_ERROR_EAP_ANONYMOUS_LEN_ERROR (-90) -#define SL_ERROR_SSID_LEN_ERROR (-91) -#define SL_ERROR_USER_ID_LEN_ERROR (-92) -#define SL_ERROR_ILLEGAL_WEP_KEY_INDEX (-95) -#define SL_ERROR_INVALID_DWELL_TIME_VALUES (-96) -#define SL_ERROR_INVALID_POLICY_TYPE (-97) -#define SL_ERROR_PM_POLICY_INVALID_OPTION (-98) -#define SL_ERROR_PM_POLICY_INVALID_PARAMS (-99) -#define SL_ERROR_WIFI_ALREADY_DISCONNECTED (-129) -#define SL_ERROR_WIFI_NOT_CONNECTED (-59) - - - -#define SL_SEC_TYPE_OPEN (0) -#define SL_SEC_TYPE_WEP (1) -#define SL_SEC_TYPE_WPA (2) /* deprecated */ -#define SL_SEC_TYPE_WPA_WPA2 (2) -#define SL_SEC_TYPE_WPS_PBC (3) -#define SL_SEC_TYPE_WPS_PIN (4) -#define SL_SEC_TYPE_WPA_ENT (5) -#define SL_SEC_TYPE_P2P_PBC (6) -#define SL_SEC_TYPE_P2P_PIN_KEYPAD (7) -#define SL_SEC_TYPE_P2P_PIN_DISPLAY (8) -#define SL_SEC_TYPE_P2P_PIN_AUTO (9) /* NOT Supported yet */ - - - -#define SL_SCAN_SEC_TYPE_OPEN (0) -#define SL_SCAN_SEC_TYPE_WEP (1) -#define SL_SCAN_SEC_TYPE_WPA (2) -#define SL_SCAN_SEC_TYPE_WPA2 (3) - - - -#define TLS (0x1) -#define MSCHAP (0x0) -#define PSK (0x2) -#define TTLS (0x10) -#define PEAP0 (0x20) -#define PEAP1 (0x40) -#define FAST (0x80) - -#define FAST_AUTH_PROVISIONING (0x02) -#define FAST_UNAUTH_PROVISIONING (0x01) -#define FAST_NO_PROVISIONING (0x00) - -#define EAPMETHOD_PHASE2_SHIFT (8) -#define EAPMETHOD_PAIRWISE_CIPHER_SHIFT (19) -#define EAPMETHOD_GROUP_CIPHER_SHIFT (27) - -#define WPA_CIPHER_CCMP (0x1) -#define WPA_CIPHER_TKIP (0x2) -#define CC31XX_DEFAULT_CIPHER (WPA_CIPHER_CCMP | WPA_CIPHER_TKIP) - -#define EAPMETHOD(phase1,phase2,pairwise_cipher,group_cipher) \ -((phase1) | \ - ((phase2) << EAPMETHOD_PHASE2_SHIFT ) |\ - ((_u32)(pairwise_cipher) << EAPMETHOD_PAIRWISE_CIPHER_SHIFT ) |\ - ((_u32)(group_cipher) << EAPMETHOD_GROUP_CIPHER_SHIFT )) - -/* phase1 phase2 pairwise_cipher group_cipher */ -#define SL_ENT_EAP_METHOD_TLS EAPMETHOD(TLS , 0 , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER) -#define SL_ENT_EAP_METHOD_TTLS_TLS EAPMETHOD(TTLS , TLS , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER) -#define SL_ENT_EAP_METHOD_TTLS_MSCHAPv2 EAPMETHOD(TTLS , MSCHAP , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER) -#define SL_ENT_EAP_METHOD_TTLS_PSK EAPMETHOD(TTLS , PSK , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER) -#define SL_ENT_EAP_METHOD_PEAP0_TLS EAPMETHOD(PEAP0 , TLS , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER) -#define SL_ENT_EAP_METHOD_PEAP0_MSCHAPv2 EAPMETHOD(PEAP0 , MSCHAP , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER) -#define SL_ENT_EAP_METHOD_PEAP0_PSK EAPMETHOD(PEAP0 , PSK , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER) -#define SL_ENT_EAP_METHOD_PEAP1_TLS EAPMETHOD(PEAP1 , TLS , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER) -#define SL_ENT_EAP_METHOD_PEAP1_MSCHAPv2 EAPMETHOD(PEAP1 , MSCHAP , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER) -#define SL_ENT_EAP_METHOD_PEAP1_PSK EAPMETHOD(PEAP1 , PSK , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER) -#define SL_ENT_EAP_METHOD_FAST_AUTH_PROVISIONING EAPMETHOD(FAST , FAST_AUTH_PROVISIONING , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER) -#define SL_ENT_EAP_METHOD_FAST_UNAUTH_PROVISIONING EAPMETHOD(FAST , FAST_UNAUTH_PROVISIONING , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER) -#define SL_ENT_EAP_METHOD_FAST_NO_PROVISIONING EAPMETHOD(FAST , FAST_NO_PROVISIONING , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER) - -#define SL_LONG_PREAMBLE (0) -#define SL_SHORT_PREAMBLE (1) - -#define SL_RAW_RF_TX_PARAMS_CHANNEL_SHIFT (0) -#define SL_RAW_RF_TX_PARAMS_RATE_SHIFT (6) -#define SL_RAW_RF_TX_PARAMS_POWER_SHIFT (11) -#define SL_RAW_RF_TX_PARAMS_PREAMBLE_SHIFT (15) - -#define SL_RAW_RF_TX_PARAMS(chan,rate,power,preamble) \ - ((chan << SL_RAW_RF_TX_PARAMS_CHANNEL_SHIFT) | \ - (rate << SL_RAW_RF_TX_PARAMS_RATE_SHIFT) | \ - (power << SL_RAW_RF_TX_PARAMS_POWER_SHIFT) | \ - (preamble << SL_RAW_RF_TX_PARAMS_PREAMBLE_SHIFT)) - - -/* wlan config application IDs */ -#define SL_WLAN_CFG_AP_ID (0) -#define SL_WLAN_CFG_GENERAL_PARAM_ID (1) -#define SL_WLAN_CFG_P2P_PARAM_ID (2) - -/* wlan AP Config set/get options */ -#define WLAN_AP_OPT_SSID (0) -#define WLAN_AP_OPT_CHANNEL (3) -#define WLAN_AP_OPT_HIDDEN_SSID (4) -#define WLAN_AP_OPT_SECURITY_TYPE (6) -#define WLAN_AP_OPT_PASSWORD (7) -#define WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE (9) -#define WLAN_GENERAL_PARAM_OPT_STA_TX_POWER (10) -#define WLAN_GENERAL_PARAM_OPT_AP_TX_POWER (11) - -#define WLAN_P2P_OPT_DEV_NAME (12) -#define WLAN_P2P_OPT_DEV_TYPE (13) -#define WLAN_P2P_OPT_CHANNEL_N_REGS (14) -#define WLAN_GENERAL_PARAM_OPT_INFO_ELEMENT (16) -#define WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS (18) /* change the scan channels and RSSI threshold using this configuration option */ - -/* SmartConfig CIPHER options */ -#define SMART_CONFIG_CIPHER_SFLASH (0) /* password is not delivered by the application. The Simple Manager should */ - /* check if the keys are stored in the Flash. */ -#define SMART_CONFIG_CIPHER_AES (1) /* AES (other types are not supported) */ -#define SMART_CONFIG_CIPHER_NONE (0xFF) /* do not check in the flash */ - - -#define SL_POLICY_CONNECTION (0x10) -#define SL_POLICY_SCAN (0x20) -#define SL_POLICY_PM (0x30) -#define SL_POLICY_P2P (0x40) - -#define VAL_2_MASK(position,value) ((1 & (value))<<(position)) -#define MASK_2_VAL(position,mask) (((1 << position) & (mask)) >> (position)) - -#define SL_CONNECTION_POLICY(Auto,Fast,Open,anyP2P,autoSmartConfig) (VAL_2_MASK(0,Auto) | VAL_2_MASK(1,Fast) | VAL_2_MASK(2,Open) | VAL_2_MASK(3,anyP2P) | VAL_2_MASK(4,autoSmartConfig)) -#define SL_SCAN_POLICY_EN(policy) (MASK_2_VAL(0,policy)) -#define SL_SCAN_POLICY(Enable) (VAL_2_MASK(0,Enable)) - - -#define SL_NORMAL_POLICY (0) -#define SL_LOW_LATENCY_POLICY (1) -#define SL_LOW_POWER_POLICY (2) -#define SL_ALWAYS_ON_POLICY (3) -#define SL_LONG_SLEEP_INTERVAL_POLICY (4) - -#define SL_P2P_ROLE_NEGOTIATE (3) -#define SL_P2P_ROLE_GROUP_OWNER (15) -#define SL_P2P_ROLE_CLIENT (0) - -#define SL_P2P_NEG_INITIATOR_ACTIVE (0) -#define SL_P2P_NEG_INITIATOR_PASSIVE (1) -#define SL_P2P_NEG_INITIATOR_RAND_BACKOFF (2) - -#define POLICY_VAL_2_OPTIONS(position,mask,policy) ((mask & policy) << position ) - -#define SL_P2P_POLICY(p2pNegType,p2pNegInitiator) (POLICY_VAL_2_OPTIONS(0,0xF,(p2pNegType > SL_P2P_ROLE_GROUP_OWNER ? SL_P2P_ROLE_GROUP_OWNER : p2pNegType)) | \ - POLICY_VAL_2_OPTIONS(4,0x1,(p2pNegType > SL_P2P_ROLE_GROUP_OWNER ? 1:0)) | \ - POLICY_VAL_2_OPTIONS(5,0x3, p2pNegInitiator)) - - -/* Info elements */ - -#define INFO_ELEMENT_DEFAULT_ID (0) /* 221 will be used */ - -/* info element size is up to 252 bytes (+ 3 bytes of OUI). */ -#define INFO_ELEMENT_MAX_SIZE (252) - -/* For AP - the total length of all info elements is 300 bytes (for example - 4 info elements of 75 bytes each) */ -#define INFO_ELEMENT_MAX_TOTAL_LENGTH_AP (300) -/* For P2P - the total length of all info elements is 150 bytes (for example - 4 info elements of 40 bytes each) */ -#define INFO_ELEMENT_MAX_TOTAL_LENGTH_P2P_GO (160) - -#define INFO_ELEMENT_AP_ROLE (0) -#define INFO_ELEMENT_P2P_GO_ROLE (1) - -/* we support up to 4 info elements per Role. */ -#define MAX_PRIVATE_INFO_ELEMENTS_SUPPROTED (4) - -#define INFO_ELEMENT_DEFAULT_OUI_0 (0x08) -#define INFO_ELEMENT_DEFAULT_OUI_1 (0x00) -#define INFO_ELEMENT_DEFAULT_OUI_2 (0x28) - -#define INFO_ELEMENT_DEFAULT_OUI (0x000000) /* 08, 00, 28 will be used */ - -/*****************************************************************************/ -/* Structure/Enum declarations */ -/*****************************************************************************/ - -typedef enum -{ - RATE_1M = 1, - RATE_2M = 2, - RATE_5_5M = 3, - RATE_11M = 4, - RATE_6M = 6, - RATE_9M = 7, - RATE_12M = 8, - RATE_18M = 9, - RATE_24M = 10, - RATE_36M = 11, - RATE_48M = 12, - RATE_54M = 13, - RATE_MCS_0 = 14, - RATE_MCS_1 = 15, - RATE_MCS_2 = 16, - RATE_MCS_3 = 17, - RATE_MCS_4 = 18, - RATE_MCS_5 = 19, - RATE_MCS_6 = 20, - RATE_MCS_7 = 21, - MAX_NUM_RATES = 0xFF -}SlRateIndex_e; - -typedef enum { - DEV_PW_DEFAULT=0, - DEV_PW_PIN_KEYPAD=1, - DEV_PW_PUSH_BUTTON=4, - DEV_PW_PIN_DISPLAY=5 -} sl_p2p_dev_password_method; - - -typedef struct -{ - _u32 status; - _u32 ssid_len; - _u8 ssid[32]; - _u32 private_token_len; - _u8 private_token[32]; -}slSmartConfigStartAsyncResponse_t; - -typedef struct -{ - _u16 status; - _u16 padding; -}slSmartConfigStopAsyncResponse_t; - -typedef struct -{ - _u16 status; - _u16 padding; -}slWlanConnFailureAsyncResponse_t; - -typedef struct -{ - _u8 connection_type;/* 0-STA,3-P2P_CL */ - _u8 ssid_len; - _u8 ssid_name[32]; - _u8 go_peer_device_name_len; - _u8 go_peer_device_name[32]; - _u8 bssid[6]; - _u8 reason_code; - _u8 padding[2]; -} slWlanConnectAsyncResponse_t; - -typedef struct -{ - _u8 go_peer_device_name[32]; - _u8 mac[6]; - _u8 go_peer_device_name_len; - _u8 wps_dev_password_id; - _u8 own_ssid[32];/* relevant for event sta-connected only */ - _u8 own_ssid_len;/* relevant for event sta-connected only */ - _u8 padding[3]; -}slPeerInfoAsyncResponse_t; - - -typedef union -{ - slSmartConfigStartAsyncResponse_t smartConfigStartResponse; /*SL_WLAN_SMART_CONFIG_COMPLETE_EVENT*/ - slSmartConfigStopAsyncResponse_t smartConfigStopResponse; /*SL_WLAN_SMART_CONFIG_STOP_EVENT */ - slPeerInfoAsyncResponse_t APModeStaConnected; /* SL_WLAN_STA_CONNECTED_EVENT - relevant only in AP mode - holds information regarding a new STA connection */ - slPeerInfoAsyncResponse_t APModestaDisconnected; /* SL_WLAN_STA_DISCONNECTED_EVENT - relevant only in AP mode - holds information regarding a STA disconnection */ - slWlanConnectAsyncResponse_t STAandP2PModeWlanConnected; /* SL_WLAN_CONNECT_EVENT - relevant only in STA and P2P mode - holds information regarding a new connection */ - slWlanConnectAsyncResponse_t STAandP2PModeDisconnected; /* SL_WLAN_DISCONNECT_EVENT - relevant only in STA and P2P mode - holds information regarding a disconnection */ - slPeerInfoAsyncResponse_t P2PModeDevFound; /* SL_WLAN_P2P_DEV_FOUND_EVENT - relevant only in P2P mode */ - slPeerInfoAsyncResponse_t P2PModeNegReqReceived; /* SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT - relevant only in P2P mode */ - slWlanConnFailureAsyncResponse_t P2PModewlanConnectionFailure; /* SL_WLAN_CONNECTION_FAILED_EVENT - relevant only in P2P mode */ - -} SlWlanEventData_u; - -typedef struct -{ - _u32 Event; - SlWlanEventData_u EventData; -} SlWlanEvent_t; - - -typedef struct -{ - _u32 ReceivedValidPacketsNumber; /* sum of the packets that been received OK (include filtered) */ - _u32 ReceivedFcsErrorPacketsNumber; /* sum of the packets that been dropped due to FCS error */ - _u32 ReceivedAddressMismatchPacketsNumber; /* sum of the packets that been received but filtered out by one of the HW filters */ - _i16 AvarageDataCtrlRssi; /* average RSSI for all valid data packets received */ - _i16 AvarageMgMntRssi; /* average RSSI for all valid management packets received */ - _u16 RateHistogram[NUM_OF_RATE_INDEXES]; /* rate histogram for all valid packets received */ - _u16 RssiHistogram[SIZE_OF_RSSI_HISTOGRAM]; /* RSSI histogram from -40 until -87 (all below and above\n RSSI will appear in the first and last cells */ - _u32 StartTimeStamp; /* the time stamp started collecting the statistics in uSec */ - _u32 GetTimeStamp; /* the time stamp called the get statistics command */ -}SlGetRxStatResponse_t; - - -typedef struct -{ - _u8 ssid[MAXIMAL_SSID_LENGTH]; - _u8 ssid_len; - _u8 sec_type; - _u8 bssid[SL_BSSID_LENGTH]; - _i8 rssi; - _i8 reserved[3]; -}Sl_WlanNetworkEntry_t; - - -typedef struct -{ - _u8 Type; - _i8* Key; - _u8 KeyLen; -}SlSecParams_t; - -typedef struct -{ - _i8* User; - _u8 UserLen; - _i8* AnonUser; - _u8 AnonUserLen; - _u8 CertIndex; /* not supported */ - _u32 EapMethod; -}SlSecParamsExt_t; - -typedef struct -{ - _i8 User[32]; - _u8 UserLen; - _i8 AnonUser[32]; - _u8 AnonUserLen; - _u8 CertIndex; /* not supported */ - _u32 EapMethod; -}SlGetSecParamsExt_t; - -typedef enum -{ - ROLE_STA = 0, - ROLE_AP = 2, - ROLE_P2P = 3, - ROLE_STA_ERR = -1, /* Failure to load MAC/PHY in STA role */ - ROLE_AP_ERR = -ROLE_AP, /* Failure to load MAC/PHY in AP role */ - ROLE_P2P_ERR = -ROLE_P2P /* Failure to load MAC/PHY in P2P role */ -}SlWlanMode_t; - -typedef struct -{ - _u32 G_Channels_mask; - _i32 rssiThershold; -}slWlanScanParamCommand_t; - - -typedef struct -{ - _u8 id; - _u8 oui[3]; - _u16 length; - _u8 data[252]; -} sl_protocol_InfoElement_t; - -typedef struct -{ - _u8 index; /* 0 - MAX_PRIVATE_INFO_ELEMENTS_SUPPROTED */ - _u8 role; /* bit0: AP = 0, GO = 1 */ - sl_protocol_InfoElement_t ie; -} sl_protocol_WlanSetInfoElement_t; - - -/*****************************************************************************/ -/* Function prototypes */ -/*****************************************************************************/ - - -/*! - \brief Connect to wlan network as a station - - \param[in] pName up to 32 bytes in case of STA the name is the SSID of the Access Point - \param[in] NameLen name length - \param[in] pMacAddr 6 bytes for MAC address - \param[in] pSecParams Security parameters (use NULL key for SL_SEC_TYPE_OPEN) - Security types options: \n - - SL_SEC_TYPE_OPEN - - SL_SEC_TYPE_WEP - - SL_SEC_TYPE_WPA_WPA2 - - SL_SEC_TYPE_WPA_ENT - - SL_SEC_TYPE_WPS_PBC - - SL_SEC_TYPE_WPS_PIN - - \param[in] pSecExtParams Enterprise parameters (set NULL in case Enterprise parameters is not in use) - - \return On success, zero is returned. On error, negative is returned - In case error number (-71) is returned, it indicates a connection was activated while the device it running in AP role - - \sa sl_WlanDisconnect - \note belongs to \ref ext_api - \warning In this version only single enterprise mode could be used - SL_SEC_TYPE_WPA is a deprecated definition, the new definition is SL_SEC_TYPE_WPA_WPA2 -*/ -#if _SL_INCLUDE_FUNC(sl_WlanConnect) -_i16 sl_WlanConnect(const _i8* pName,const _i16 NameLen,const _u8 *pMacAddr,const SlSecParams_t* pSecParams ,const SlSecParamsExt_t* pSecExtParams); -#endif - -/*! - \brief wlan disconnect - - Disconnect connection - - \return 0 disconnected done, other already disconnected - - \sa sl_WlanConnect - \note belongs to \ref ext_api - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_WlanDisconnect) -_i16 sl_WlanDisconnect(void); -#endif - -/*! - \brief add profile - - When auto start is enabled, the device connects to a - station from the profiles table. Up to 7 profiles are - supported. If several profiles configured the device chose - the highest priority profile, within each priority group, - device will chose profile based on security policy, signal - strength, etc parameters. - - - \param[in] pName up to 32 bytes in case of STA the name is the - SSID of the Access Point - in case of P2P the name is the remote device name - \param[in] NameLen name length - \param[in] pMacAddr 6 bytes for MAC address - \param[in] pSecParams Security parameters - security type - (SL_SEC_TYPE_OPEN,SL_SEC_TYPE_WEP,SL_SEC_TYPE_WPA_WPA2, - SL_SEC_TYPE_P2P_PBC,SL_SEC_TYPE_P2P_PIN_KEYPAD,SL_SEC_TYPE_P2P_PIN_DISPLAY, SL_SEC_TYPE_WPA_ENT), key, and key length - in case of p2p security type pin the key refers to pin code - \param[in] pSecExtParams Enterprise parameters - identity, identity length, - Anonymous, Anonymous length, CertIndex (not supported, - certificates need to be placed in a specific file ID), - EapMethod.Use NULL in case Enterprise parameters is not in use - - \param[in] Priority profile priority. Lowest priority: 0 - \param[in] Options Not supported - - \return On success, profile stored index is returned. On error, negative value is returned - - \sa sl_WlanProfileGet , sl_WlanProfileDel - \note belongs to \ref ext_api - \warning Only one Enterprise profile is supported. - Please Note that in case of adding an existing profile (compared by pName,pMACAddr and security type) - the old profile will be deleted and the same index will be returned. - SL_SEC_TYPE_WPA is a deprecated definition, the new definition is SL_SEC_TYPE_WPA_WPA2 - -*/ -#if _SL_INCLUDE_FUNC(sl_WlanProfileAdd) -_i16 sl_WlanProfileAdd(const _i8* pName,const _i16 NameLen,const _u8 *pMacAddr,const SlSecParams_t* pSecParams ,const SlSecParamsExt_t* pSecExtParams,const _u32 Priority,const _u32 Options); -#endif - -/*! - \brief get profile - - read profile from the device - - \param[in] Index profile stored index, if index does not exists - error is return - \param[out] pName up to 32 bytes, in case of sta mode the name of the Access Point - in case of p2p mode the name of the Remote Device - \param[out] pNameLen name length - \param[out] pMacAddr 6 bytes for MAC address - \param[out] pSecParams security parameters - security type - (SL_SEC_TYPE_OPEN, SL_SEC_TYPE_WEP, SL_SEC_TYPE_WPA_WPA2 or - SL_SEC_TYPE_WPS_PBC, SL_SEC_TYPE_WPS_PIN, SL_SEC_TYPE_WPA_ENT,SL_SEC_TYPE_P2P_PBC,SL_SEC_TYPE_P2P_PIN_KEYPAD or SL_SEC_TYPE_P2P_PIN_DISPLAY), key and key length are not - in case of p2p security type pin the key refers to pin code - return due to security reasons. - \param[out] pSecExtParams enterprise parameters - identity, identity - length, Anonymous, Anonymous length - CertIndex (not supported), EapMethod. - \param[out] Priority profile priority - - \return On success, Profile security type is returned (0 or positive number). On error, -1 is - returned - - \sa sl_WlanProfileAdd , sl_WlanProfileDel - \note belongs to \ref ext_api - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_WlanProfileGet) -_i16 sl_WlanProfileGet(const _i16 Index,_i8* pName, _i16 *pNameLen, _u8 *pMacAddr, SlSecParams_t* pSecParams, SlGetSecParamsExt_t* pSecExtParams, _u32 *pPriority); -#endif - -/*! - \brief Delete WLAN profile - - Delete WLAN profile - - \param[in] index number of profile to delete.Possible values are 0 to 6. - Index value 255 will delete all saved profiles - - \return On success, zero is returned. On error, -1 is - returned - - \sa sl_WlanProfileAdd , sl_WlanProfileGet - \note belongs to \ref ext_api - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_WlanProfileDel) -_i16 sl_WlanProfileDel(const _i16 Index); -#endif - -/*! - \brief Set policy values - - \param[in] Type Type of policy to be modified. The Options are:\n - - SL_POLICY_CONNECTION - - SL_POLICY_SCAN - - SL_POLICY_PM - - SL_POLICY_P2P - \param[in] Policy The option value which depends on action type - \param[in] pVal An optional value pointer - \param[in] ValLen An optional value length, in bytes - \return On success, zero is returned. On error, -1 is - returned - \sa sl_WlanPolicyGet - \note belongs to \ref ext_api - \warning - \par - SL_POLICY_CONNECTION type defines three options available to connect the CC31xx device to the AP: \n - - - If Auto Connect is set, the CC31xx device tries to automatically reconnect to one of its stored profiles, each time the connection fails or the device is rebooted.\n - To set this option, use: \n - sl_WlanPolicySet(SL_POLICY_CONNECTION,SL_CONNECTION_POLICY(1,0,0,0,0),NULL,0) - - If Fast Connect is set, the CC31xx device tries to establish a fast connection to AP. \n - To set this option, use: \n - sl_WlanPolicySet(SL_POLICY_CONNECTION,SL_CONNECTION_POLICY(0,1,0,0,0),NULL,0) - - (relevant for P2P mode only) - If Any P2P is set, CC31xx/CC32xx device tries to automatically connect to the first P2P device available, \n - supporting push button only. To set this option, use: \n - sl_WlanPolicySet(SL_POLICY_CONNECTION,SL_CONNECTION_POLICY(0,0,0,1,0),NULL,0) - - For auto smart config upon restart (any command from Host will end this state) use: \n - sl_WlanPolicySet(SL_POLICY_CONNECTION,SL_CONNECTION_POLICY(0,0,0,0,1),NULL,0) \n - The options above could be combined to a single action, if more than one action is required. \n - \par - SL_POLICY_SCAN defines system scan time interval.Default interval is 10 minutes. \n - After settings scan interval, an immediate scan is activated. The next scan will be based on the interval settings. \n - - For example, setting scan interval to 1 minute interval use: \n - _u32 intervalInSeconds = 60; \n - #define SL_SCAN_ENABLE 1 \n - sl_WlanPolicySet(SL_POLICY_SCAN,SL_SCAN_ENABLE, (_u8 *)&intervalInSeconds,sizeof(intervalInSeconds)); \n - - - For example, disable scan: \n - #define SL_SCAN_DISABLE 0 \n - sl_WlanPolicySet(SL_POLICY_SCAN,SL_SCAN_DISABLE,0,0); \n - \par - SL_POLICY_PM defines a power management policy for Station mode only: - - For setting normal power management (default) policy use: sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL,0) - - For setting low latency power management policy use: sl_WlanPolicySet(SL_POLICY_PM , SL_LOW_LATENCY_POLICY, NULL,0) - - For setting low power management policy use: sl_WlanPolicySet(SL_POLICY_PM , SL_LOW_POWER_POLICY, NULL,0) - - For setting always on power management policy use: sl_WlanPolicySet(SL_POLICY_PM , SL_ALWAYS_ON_POLICY, NULL,0) - - For setting Long Sleep Interval policy use: \n - _u16 PolicyBuff[4] = {0,0,800,0}; // PolicyBuff[2] is max sleep time in mSec \n - sl_WlanPolicySet(SL_POLICY_PM , SL_LONG_SLEEP_INTERVAL_POLICY, (_u8*)PolicyBuff,sizeof(PolicyBuff)); \n - - SL_POLICY_P2P defines p2p negotiation policy parameters for P2P role: - - To set intent negotiation value, set on of the following: - SL_P2P_ROLE_NEGOTIATE - intent 3 - SL_P2P_ROLE_GROUP_OWNER - intent 15 - SL_P2P_ROLE_CLIENT - intent 0 - - To set negotiation initiator value (initiator policy of first negotiation action frame), set on of the following: - SL_P2P_NEG_INITIATOR_ACTIVE - SL_P2P_NEG_INITIATOR_PASSIVE - SL_P2P_NEG_INITIATOR_RAND_BACKOFF - For example: \n - sl_WlanPolicySet(SL_POLICY_P2P, SL_P2P_POLICY(SL_P2P_ROLE_NEGOTIATE,SL_P2P_NEG_INITIATOR_RAND_BACKOFF),NULL,0) - -*/ -#if _SL_INCLUDE_FUNC(sl_WlanPolicySet) -_i16 sl_WlanPolicySet(const _u8 Type , const _u8 Policy, _u8 *pVal,const _u8 ValLen); -#endif -/*! - \brief get policy values - - \param[in] Type SL_POLICY_CONNECTION, SL_POLICY_SCAN, SL_POLICY_PM,SL_POLICY_P2P \n - - \param[in] Policy argument may be set to any value \n - - \param[out] The returned values, depends on each policy type, will be stored in the allocated buffer pointed by pVal - with a maximum buffer length set by the calling function and pointed to by argument *pValLen - - \return On success, zero is returned. On error, -1 is returned - - \sa sl_WlanPolicySet - - \note belongs to \ref ext_api - - \warning The value pointed by the argument *pValLen should be set to a value different from 0 and - greater than the buffer length returned from the SL device. Otherwise, an error will be returned. - -*/ -#if _SL_INCLUDE_FUNC(sl_WlanPolicyGet) -_i16 sl_WlanPolicyGet(const _u8 Type , _u8 Policy,_u8 *pVal,_u8 *pValLen); -#endif -/*! - \brief Gets the WLAN scan operation results - - Gets scan results , gets entry from scan result table - - \param[in] Index - Starting index identifier (range 0-19) for getting scan results - \param[in] Count - How many entries to fetch. Max is (20-"Index"). - \param[out] pEntries - pointer to an allocated Sl_WlanNetworkEntry_t. - the number of array items should match "Count" - sec_type: SL_SCAN_SEC_TYPE_OPEN, SL_SCAN_SEC_TYPE_WEP, SL_SCAN_SEC_TYPE_WPA or SL_SCAN_SEC_TYPE_WPA2 - - - \return Number of valid networks list items - - \sa - \note belongs to \ref ext_api - \warning This command do not initiate any active scanning action - \par Example: - \code An example of fetching max 10 results: - - Sl_WlanNetworkEntry_t netEntries[10]; - _i16 resultsCount = sl_WlanGetNetworkList(0,10,&netEntries[0]); - for(i=0; i< resultsCount; i++) - { - printf("%s\n",netEntries[i].ssid); - } - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_WlanGetNetworkList) -_i16 sl_WlanGetNetworkList(const _u8 Index,const _u8 Count, Sl_WlanNetworkEntry_t *pEntries); -#endif - -/*! - \brief Start collecting wlan RX statistics, for unlimited time. - - \return On success, zero is returned. On error, -1 is returned - - \sa sl_WlanRxStatStop sl_WlanRxStatGet - \note belongs to \ref ext_api - \warning - \par Example: - \code Getting wlan RX statistics: - - void RxStatCollectTwice() - { - SlGetRxStatResponse_t rxStat; - _i16 rawSocket; - _i8 DataFrame[200]; - struct SlTimeval_t timeval; - timeval.tv_sec = 0; // Seconds - timeval.tv_usec = 20000; // Microseconds. 10000 microseconds resolution - - sl_WlanRxStatStart(); // set statistics mode - - rawSocket = sl_Socket(SL_AF_RF, SL_SOCK_RAW, eChannel); - // set timeout - in case we have no activity for the specified channel - sl_SetSockOpt(rawSocket,SL_SOL_SOCKET,SL_SO_RCVTIMEO, &timeval, sizeof(timeval)); // Enable receive timeout - status = sl_Recv(rawSocket, DataFrame, sizeof(DataFrame), 0); - - Sleep(1000); // sleep for 1 sec - sl_WlanRxStatGet(&rxStat,0); // statistics has been cleared upon read - Sleep(1000); // sleep for 1 sec - sl_WlanRxStatGet(&rxStat,0); - - } - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_WlanRxStatStart) -_i16 sl_WlanRxStatStart(void); -#endif - - -/*! - \brief Stop collecting wlan RX statistic, (if previous called sl_WlanRxStatStart) - - \return On success, zero is returned. On error, -1 is returned - - \sa sl_WlanRxStatStart sl_WlanRxStatGet - \note belongs to \ref ext_api - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_WlanRxStatStop) -_i16 sl_WlanRxStatStop(void); -#endif - - -/*! - \brief Get wlan RX statistics. upon calling this command, the statistics counters will be cleared. - - \param[in] Flags should be 0 ( not applicable right now, will be added the future ) - \param[in] pRxStat a pointer to SlGetRxStatResponse_t filled with Rx statistics results - \return On success, zero is returned. On error, -1 is returned - - \sa sl_WlanRxStatStart sl_WlanRxStatStop - \note belongs to \ref ext_api - \warning -*/ -#if _SL_INCLUDE_FUNC(sl_WlanRxStatGet) -_i16 sl_WlanRxStatGet(SlGetRxStatResponse_t *pRxStat,const _u32 Flags); -#endif - - -/*! - \brief Stop Smart Config procedure. Once Smart Config will be stopped, - Asynchronous event will be received - SL_OPCODE_WLAN_SMART_CONFIG_STOP_ASYNC_RESPONSE. - - \param[in] none - \param[out] none - - \return 0 - if Stop Smart Config is about to be executed without errors. - - \sa sl_WlanSmartConfigStart - \note belongs to \ref ext_api - \warning - -*/ -#if _SL_INCLUDE_FUNC(sl_WlanSmartConfigStop) -_i16 sl_WlanSmartConfigStop(void); -#endif - -/*! - \brief Start Smart Config procedure - \par - The target of the procedure is to let the \n - device to gain the network parameters: SSID and Password (if network is secured) \n - and to connect to it once located in the network range. \n - An external application should be used on a device connected to any mobile network. \n - The external application will transmit over the air the network parameters in secured manner.\n - The Password may be decrypted using a Key. \n - The decryption method may be decided in the command or embedded in the Flash. \n - The procedure can be activated for 1-3 group ID in the range of BIT_0 - BIT_15 where the default group ID id 0 (BIT_0) \n - Once Smart Config has ended successfully, Asynchronous event will be received - \n - SL_OPCODE_WLAN_SMART_CONFIG_START_ASYNC_RESPONSE. \n - The Event will hold the SSID and an extra field that might have been delivered as well (i.e. - device name) - - \param[in] groupIdBitmask - each bit represent a group ID that should be searched. - The Default group ID id BIT_0. 2 more group can be searched - in addition. The range is BIT_0 - BIT_15. - \param[in] chiper - 0: check in flash, 1 - AES, 0xFF - do not check in flash - \param[in] publicKeyLen - public key len (used for the default group ID - BIT_0) - \param[in] group1KeyLen - group ID1 length - \param[in] group2KeyLen - group ID2 length - \param[in] publicKey - public key (used for the default group ID - BIT_0) - \param[in] group1Key - group ID1 key - \param[in] group2Key - group ID2 key - - \param[out] none - - \return 0 - if Smart Config started successfully. - - \sa sl_WlanSmartConfigStop - \note belongs to \ref ext_api - \warning - \par - \code An example of starting smart Config on group ID's 0 + 1 + 2 - - sl_WlanSmartConfigStart(7, //group ID's (BIT_0 | BIT_1 | BIT_2) - 1, //decrypt key by AES method - 16, //decryption key length for group ID0 - 16, //decryption key length for group ID1 - 16, //decryption key length for group ID2 - "Key0Key0Key0Key0", //decryption key for group ID0 - "Key1Key1Key1Key1", //decryption key for group ID1 - "Key2Key2Key2Key2" //decryption key for group ID2 - ); - \endcode -*/ -#if _SL_INCLUDE_FUNC(sl_WlanSmartConfigStart) -_i16 sl_WlanSmartConfigStart(const _u32 groupIdBitmask, - const _u8 cipher, - const _u8 publicKeyLen, - const _u8 group1KeyLen, - const _u8 group2KeyLen, - const _u8* publicKey, - const _u8* group1Key, - const _u8* group2Key); -#endif - - -/*! - \brief Wlan set mode - - Setting WLAN mode - - \param[in] mode - WLAN mode to start the CC31xx device. Possible options are: - - ROLE_STA - for WLAN station mode - - ROLE_AP - for WLAN AP mode - - ROLE_P2P -for WLAN P2P mode - \return 0 - if mode was set correctly - \sa sl_Start sl_Stop - \note belongs to \ref ext_api - \warning After setting the mode the system must be restarted for activating the new mode - \par Example: - \code - //Switch from any role to STA: - sl_WlanSetMode(ROLE_STA); - sl_Stop(0); - sl_Start(NULL,NULL,NULL); - \endcode - -*/ -#if _SL_INCLUDE_FUNC(sl_WlanSetMode) -_i16 sl_WlanSetMode(const _u8 mode); -#endif - - -/*! - \brief Internal function for setting WLAN configurations - - \return On success, zero is returned. On error one of the following error codes returned: - - CONF_ERROR (-1) - - CONF_NVMEM_ACCESS_FAILED (-2) - - CONF_OLD_FILE_VERSION (-3) - - CONF_ERROR_NO_SUCH_COUNTRY_CODE (-4) - - - \param[in] ConfigId - configuration id - - SL_WLAN_CFG_AP_ID - - SL_WLAN_CFG_GENERAL_PARAM_ID - - SL_WLAN_CFG_P2P_PARAM_ID - - \param[in] ConfigOpt - configurations option - - SL_WLAN_CFG_AP_ID - - WLAN_AP_OPT_SSID \n - Set SSID for AP mode. \n - This options takes _u8 buffer as parameter - - WLAN_AP_OPT_CHANNEL \n - Set channel for AP mode. \n - The channel is dependant on the country code which is set. i.e. for "US" the channel should be in the range of [1-11] \n - This option takes _u8 as a parameter - - WLAN_AP_OPT_HIDDEN_SSID \n - Set Hidden SSID Mode for AP mode.Hidden options: \n - 0: disabled \n - 1: Send empty (length=0) SSID in beacon and ignore probe request for broadcast SSID \n - 2: Clear SSID (ASCII 0), but keep the original length (this may be required with some \n - clients that do not support empty SSID) and ignore probe requests for broadcast SSID \n - This option takes _u8 as a parameter - - WLAN_AP_OPT_SECURITY_TYPE \n - Set Security type for AP mode. Security options are: - - Open security: SL_SEC_TYPE_OPEN - - WEP security: SL_SEC_TYPE_WEP - - WPA security: SL_SEC_TYPE_WPA_WPA2 \n - This option takes _u8 pointer as a parameter - - WLAN_AP_OPT_PASSWORD \n - Set Password for for AP mode (for WEP or for WPA): \n - Password - for WPA: 8 - 63 characters \n - for WEP: 5 / 13 characters (ascii) \n - This options takes _u8 buffer as parameter - - SL_WLAN_CFG_GENERAL_PARAM_ID - - WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS \n - Set scan parameters. - This option uses slWlanScanParamCommand_t as parameter - - WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE \n - Set Country Code for AP mode \n - This options takes _u8 2 bytes buffer as parameter - - WLAN_GENERAL_PARAM_OPT_STA_TX_POWER \n - Set STA mode Tx power level \n - Number between 0-15, as dB offset from max power (0 will set MAX power) \n - This options takes _u8 as parameter - - WLAN_GENERAL_PARAM_OPT_AP_TX_POWER - Set AP mode Tx power level \n - Number between 0-15, as dB offset from max power (0 will set MAX power) \n - This options takes _u8 as parameter - - WLAN_GENERAL_PARAM_OPT_INFO_ELEMENT - Set Info Element for AP mode. \n - The Application can set up to MAX_PRIVATE_INFO_ELEMENTS_SUPPROTED info elements per Role (AP / P2P GO). \n - To delete an info element use the relevant index and length = 0. \n - The Application can set up to MAX_PRIVATE_INFO_ELEMENTS_SUPPROTED to the same role. \n - However, for AP - no more than INFO_ELEMENT_MAX_TOTAL_LENGTH_AP bytes can be stored for all info elements. \n - For P2P GO - no more than INFO_ELEMENT_MAX_TOTAL_LENGTH_P2P_GO bytes can be stored for all info elements. \n - This option takes sl_protocol_WlanSetInfoElement_t as parameter - - SL_WLAN_CFG_P2P_PARAM_ID - - WLAN_P2P_OPT_DEV_TYPE \n - Set P2P Device type.Maximum length of 17 characters. Device type is published under P2P I.E, \n - allows to make devices easier to recognize. \n - In case no device type is set, the default type is "1-0050F204-1" \n - This options takes _u8 buffer as parameter - - WLAN_P2P_OPT_CHANNEL_N_REGS \n - Set P2P Channels. \n - listen channel (either 1/6/11 for 2.4GHz) \n - listen regulatory class (81 for 2.4GHz) \n - oper channel (either 1/6/11 for 2.4GHz) \n - oper regulatory class (81 for 2.4GHz) \n - listen channel and regulatory class will determine the device listen channel during p2p find listen phase \n - oper channel and regulatory class will determine the operating channel preferred by this device (in case it is group owner this will be the operating channel) \n - channels should be one of the social channels (1/6/11). In case no listen/oper channel selected, a random 1/6/11 will be selected. - This option takes pointer to _u8[4] as parameter - - \param[in] ConfigLen - configurations len - - \param[in] pValues - configurations values - - \sa - \note - \warning - \par Examples: - \par - WLAN_AP_OPT_SSID: - \code - _u8 str[33]; - memset(str, 0, 33); - memcpy(str, ssid, len); // ssid string of 32 characters - sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_SSID, strlen(ssid), str); - \endcode - \par - WLAN_AP_OPT_CHANNEL: - \code - _u8 val = channel; - sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_CHANNEL, 1, (_u8 *)&val); - \endcode - \par - WLAN_AP_OPT_HIDDEN_SSID: - \code - _u8 val = hidden; - sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_HIDDEN_SSID, 1, (_u8 *)&val); - \endcode - \par - WLAN_AP_OPT_SECURITY_TYPE: - \code - _u8 val = SL_SEC_TYPE_WPA_WPA2; - sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_SECURITY_TYPE, 1, (_u8 *)&val); - \endcode - \par - WLAN_AP_OPT_PASSWORD: - \code - _u8 str[65]; - _u16 len = strlen(password); - memset(str, 0, 65); - memcpy(str, password, len); - sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_PASSWORD, len, (_u8 *)str); - \endcode - \par - WLAN_GENERAL_PARAM_OPT_STA_TX_POWER: - \code - _u8 stapower=(_u8)power; - sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_STA_TX_POWER,1,(_u8 *)&stapower); - \endcode - \par - WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS: - \code - slWlanScanParamCommand_t ScanParamConfig; - ScanParamConfig.G_Channels_mask = 0x01; // bit mask for channels:1 means channel 1 is enabled, 3 means channels 1 + 2 are enabled - ScanParamConfig.rssiThershold = -70; // only for RSSI level which is higher than -70 - sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID ,WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS,sizeof(slWlanScanParamCommand_t),(_u8*)&ScanParamConfig); - \endcode - - \par - WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE: - \code - _u8* str = (_u8 *) country; // string of 2 characters. i.e. - "US" - sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE, 2, str); - \endcode - \par - WLAN_GENERAL_PARAM_OPT_AP_TX_POWER: - \code - _u8 appower=(_u8)power; - sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_AP_TX_POWER,1,(_u8 *)&appower); - \endcode - \par - WLAN_P2P_OPT_DEV_TYPE: - \code - _u8 str[17]; - _u16 len = strlen(device_type); - memset(str, 0, 17); - memcpy(str, device_type, len); - sl_WlanSet(SL_WLAN_CFG_P2P_PARAM_ID, WLAN_P2P_OPT_DEV_TYPE, len, str); - \endcode - \par - WLAN_P2P_OPT_CHANNEL_N_REGS: - \code - _u8 str[4]; - str[0] = (_u8)11; // listen channel - str[1] = (_u8)81; // listen regulatory class - str[2] = (_u8)6; // oper channel - str[3] = (_u8)81; // oper regulatory class - sl_WlanSet(SL_WLAN_CFG_P2P_PARAM_ID, WLAN_P2P_OPT_CHANNEL_N_REGS, 4, str); - \endcode - \par - WLAN_GENERAL_PARAM_OPT_INFO_ELEMENT: - \code - sl_protocol_WlanSetInfoElement_t infoele; - infoele.index = Index; // Index of the info element. range: 0 - MAX_PRIVATE_INFO_ELEMENTS_SUPPROTED - infoele.role = Role; // INFO_ELEMENT_AP_ROLE (0) or INFO_ELEMENT_P2P_GO_ROLE (1) - infoele.ie.id = Id; // Info element ID. if INFO_ELEMENT_DEFAULT_ID (0) is set, ID will be set to 221. - // Organization unique ID. If all 3 bytes are zero - it will be replaced with 08,00,28. - infoele.ie.oui[0] = Oui0; // Organization unique ID first Byte - infoele.ie.oui[1] = Oui1; // Organization unique ID second Byte - infoele.ie.oui[2] = Oui2; // Organization unique ID third Byte - infoele.ie.length = Len; // Length of the info element. must be smaller than 253 bytes - memset(infoele.ie.data, 0, INFO_ELEMENT_MAX_SIZE); - if ( Len <= INFO_ELEMENT_MAX_SIZE ) - { - memcpy(infoele.ie.data, IE, Len); // Info element. length of the info element is [0-252] - sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID,WLAN_GENERAL_PARAM_OPT_INFO_ELEMENT,sizeof(sl_protocol_WlanSetInfoElement_t),(_u8* ) &infoele); - } - sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID,WLAN_GENERAL_PARAM_OPT_INFO_ELEMENT,sizeof(sl_protocol_WlanSetInfoElement_t),(_u8* ) &infoele); - \endcode - -*/ -#if _SL_INCLUDE_FUNC(sl_WlanSet) -_i16 sl_WlanSet(const _u16 ConfigId ,const _u16 ConfigOpt,const _u16 ConfigLen,const _u8 *pValues); -#endif - -/*! - \brief Internal function for getting WLAN configurations - - \return On success, zero is returned. On error, -1 is - returned - - \param[in] ConfigId - configuration id - - SL_WLAN_CFG_AP_ID - - SL_WLAN_CFG_GENERAL_PARAM_ID - - SL_WLAN_CFG_P2P_PARAM_ID - - \param[out] pConfigOpt - get configurations option - - SL_WLAN_CFG_AP_ID - - WLAN_AP_OPT_SSID \n - Get SSID for AP mode. \n - Get up to 32 characters of SSID \n - This options takes _u8 as parameter - - WLAN_AP_OPT_CHANNEL \n - Get channel for AP mode. \n - This option takes _u8 as a parameter - - WLAN_AP_OPT_HIDDEN_SSID \n - Get Hidden SSID Mode for AP mode.Hidden options: \n - 0: disabled \n - 1: Send empty (length=0) SSID in beacon and ignore probe request for broadcast SSID \n - 2: Clear SSID (ASCII 0), but keep the original length (this may be required with some \n - clients that do not support empty SSID) and ignore probe requests for broadcast SSID \n - This option takes _u8 as a parameter - - WLAN_AP_OPT_SECURITY_TYPE \n - Get Security type for AP mode. Security options are: - - Open security: SL_SEC_TYPE_OPEN - - WEP security: SL_SEC_TYPE_WEP - - WPA security: SL_SEC_TYPE_WPA_WPA2 \n - This option takes _u8 as a parameter - - WLAN_AP_OPT_PASSWORD \n - Get Password for for AP mode (for WEP or for WPA): \n - Returns password - string, fills up to 64 characters. \n - This options takes _u8 buffer as parameter - - SL_WLAN_CFG_GENERAL_PARAM_ID - - WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS \n - Get scan parameters. - This option uses slWlanScanParamCommand_t as parameter - - WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE \n - Get Country Code for AP mode \n - This options takes _u8 buffer as parameter - - WLAN_GENERAL_PARAM_OPT_STA_TX_POWER \n - Get STA mode Tx power level \n - Number between 0-15, as dB offset from max power (0 indicates MAX power) \n - This options takes _u8 as parameter - - WLAN_GENERAL_PARAM_OPT_AP_TX_POWER - Get AP mode Tx power level \n - Number between 0-15, as dB offset from max power (0 indicates MAX power) \n - This options takes _u8 as parameter - - SL_WLAN_CFG_P2P_PARAM_ID - - WLAN_P2P_OPT_CHANNEL_N_REGS \n - Get P2P Channels. \n - listen channel (either 1/6/11 for 2.4GHz) \n - listen regulatory class (81 for 2.4GHz) \n - oper channel (either 1/6/11 for 2.4GHz) \n - oper regulatory class (81 for 2.4GHz) \n - listen channel and regulatory class will determine the device listen channel during p2p find listen phase \n - oper channel and regulatory class will determine the operating channel preferred by this device (in case it is group owner this will be the operating channel) \n - channels should be one of the social channels (1/6/11). In case no listen/oper channel selected, a random 1/6/11 will be selected. \n - This option takes pointer to _u8[4] as parameter - - \param[out] pConfigLen - The length of the allocated memory as input, when the - function complete, the value of this parameter would be - the len that actually read from the device. - If the device return length that is longer from the input - value, the function will cut the end of the returned structure - and will return SL_ESMALLBUF. - - - \param[out] pValues - get configurations values - - \sa sl_WlanSet - - \note - - \warning - - \par Examples: - \par - WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS: - \code - slWlanScanParamCommand_t ScanParamConfig; - _u16 Option = WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS; - _u16 OptionLen = sizeof(slWlanScanParamCommand_t); - sl_WlanGet(SL_WLAN_CFG_GENERAL_PARAM_ID ,&Option,&OptionLen,(_u8 *)&ScanParamConfig); - \endcode - \par - WLAN_GENERAL_PARAM_OPT_AP_TX_POWER: - \code - _i8 TXPower = 0; - _u16 Option = WLAN_GENERAL_PARAM_OPT_AP_TX_POWER; - _u16 OptionLen = sizeof(_i8); - sl_WlanGet(SL_WLAN_CFG_GENERAL_PARAM_ID ,&Option,&OptionLen,(_u8 *)&TXPower); - \endcode - \par - WLAN_GENERAL_PARAM_OPT_STA_TX_POWER: - \code - _i8 TXPower = 0; - _u16 Option = WLAN_GENERAL_PARAM_OPT_STA_TX_POWER; - _u16 OptionLen = sizeof(_i8); - - sl_WlanGet(SL_WLAN_CFG_GENERAL_PARAM_ID ,&Option,&OptionLen,(_u8 *)&TXPower); - \endcode - \par - WLAN_P2P_OPT_DEV_TYPE: - \code - _i8 device_type[18]; - _u16 len = 18; - _u16 config_opt = WLAN_P2P_OPT_DEV_TYPE; - sl_WlanGet(SL_WLAN_CFG_P2P_PARAM_ID, &config_opt , &len, (_u8* )device_type); - \endcode - \par - WLAN_AP_OPT_SSID: - \code - _i8 ssid[32]; - _u16 len = 32; - _u16 config_opt = WLAN_AP_OPT_SSID; - sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt , &len, (_u8* )ssid); - \endcode - \par - WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE: - \code - _i8 country[3]; - _u16 len = 3; - _u16 config_opt = WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE; - sl_WlanGet(SL_WLAN_CFG_GENERAL_PARAM_ID, &config_opt, &len, (_u8* )country); - \endcode - \par - WLAN_AP_OPT_CHANNEL: - \code - _i8 channel; - _u16 len = 1; - _u16 config_opt = WLAN_AP_OPT_CHANNEL; - sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt, &len, (_u8* )&channel); - \endcode - \par - WLAN_AP_OPT_HIDDEN_SSID: - \code - _u8 hidden; - _u16 len = 1; - _u16 config_opt = WLAN_AP_OPT_HIDDEN_SSID; - sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt, &len, (_u8* )&hidden); - \endcode - \par - WLAN_AP_OPT_SECURITY_TYPE: - \code - _u8 sec_type; - _u16 len = 1; - _u16 config_opt = WLAN_AP_OPT_SECURITY_TYPE; - sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt, &len, (_u8* )&sec_type); - \endcode - \par - WLAN_AP_OPT_PASSWORD: - \code - _u8 password[64]; - _u16 len = 64; - memset(password,0,64); - _u16 config_opt = WLAN_AP_OPT_PASSWORD; - sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt, &len, (_u8* )password); - - \endcode - \par - WLAN_P2P_OPT_CHANNEL_N_REGS: - \code - _u16 listen_channel,listen_reg,oper_channel,oper_reg; - _u16 len = 4; - _u16 config_opt = WLAN_P2P_OPT_CHANNEL_N_REGS; - _u8 channel_n_regs[4]; - sl_WlanGet(SL_WLAN_CFG_P2P_PARAM_ID, &config_opt, &len, (_u8* )channel_n_regs); - listen_channel = channel_n_regs[0]; - listen_reg = channel_n_regs[1]; - oper_channel = channel_n_regs[2]; - oper_reg = channel_n_regs[3]; - \endcode -*/ - -#if _SL_INCLUDE_FUNC(sl_WlanGet) -_i16 sl_WlanGet(const _u16 ConfigId, _u16 *pConfigOpt,_u16 *pConfigLen, _u8 *pValues); -#endif -/*! - - Close the Doxygen group. - @} - - */ - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __WLAN_H__ */ - diff --git a/drivers/cc3100/inc/wlan_rx_filters.h b/drivers/cc3100/inc/wlan_rx_filters.h deleted file mode 100644 index 8bd712f0df..0000000000 --- a/drivers/cc3100/inc/wlan_rx_filters.h +++ /dev/null @@ -1,932 +0,0 @@ -/* - * wlan_rx_filters.h - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" - -#ifndef RX_FILTERS_PREPROCESSOR_CLI_IF_H_ -#define RX_FILTERS_PREPROCESSOR_CLI_IF_H_ - - - -#ifdef __cplusplus -extern "C" { -#endif - - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ - -/*! - * \def SL_RX_FILTER_MAX_FILTERS - * The Max number of filters for 64 filters - */ -#define SL_RX_FILTER_MAX_FILTERS 64 - -/*! - * \def SL_RX_FILTER_MAX_PRE_PREPARED_FILTERS_SETS - * The Max number of software filters - */ -#define SL_RX_FILTER_MAX_PRE_PREPARED_FILTERS_SETS (32) -/*! - * \def SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS - * - */ -#define SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS (2) -/*! - * \def SL_RX_FILTER_NUM_OF_FILTER_PAYLOAD_ARGS - * - */ -#define SL_RX_FILTER_NUM_OF_FILTER_PAYLOAD_ARGS (2) -/*! - * \def SL_RX_FILTER_NUM_OF_FILTER_PAYLOAD_ARGS - * - */ -#define SL_RX_FILTER_NUM_OF_COMBINATION_TYPE_ARGS (2) -/*! - * \def SL_RX_FILTER_LENGTH_OF_REGX_PATTERN_LENGTH - * - */ -#define SL_RX_FILTER_LENGTH_OF_REGX_PATTERN_LENGTH (32) - - -/* List of possible error numbers */ -#define RXFL_OK (0) /* O.K */ -#define RXFL_OUTPUT_OR_INPUT_BUFFER_LENGTH_TOO_SMALL (76) /* ! The output buffer length is smaller than required for that operation */ -#define RXFL_DEPENDENT_FILTER_SOFTWARE_FILTER_NOT_FIT (75) /* Node filter can't be child of software filter and vice_versa */ -#define RXFL_DEPENDENCY_IS_NOT_PERSISTENT (74) /* Dependency filter is not persistent */ -#define RXFL_SYSTEM_STATE_NOT_SUPPORTED_FOR_THIS_FILTER (72) /* System state is not supported */ -#define RXFL_TRIGGER_USE_REG5_TO_REG8 (71) /* Only counters 5 - 8 are allowed, for Tigger */ -#define RXFL_TRIGGER_USE_REG1_TO_REG4 (70) /* Only counters 1 - 4 are allowed, for trigger */ -#define RXFL_ACTION_USE_REG5_TO_REG8 (69) /* Only counters 5 - 8 are allowed, for action */ -#define RXFL_ACTION_USE_REG1_TO_REG4 (68) /* Only counters 1 - 4 are allowed, for action */ -#define RXFL_FIELD_SUPPORT_ONLY_EQUAL_AND_NOTEQUAL (67) /* Rule compare function Id is out of range */ -#define RXFL_WRONG_MULTICAST_BROADCAST_ADDRESS (66) /* The address should be of type mutlicast or broadcast */ -#define RXFL_THE_FILTER_IS_NOT_OF_HEADER_TYPE (65) /* The filter should be of header type */ -#define RXFL_WRONG_COMPARE_FUNC_FOR_BROADCAST_ADDRESS (64) /* The compare funcion is not suitable for broadcast address */ -#define RXFL_WRONG_MULTICAST_ADDRESS (63) /* The address should be of muticast type */ -#define RXFL_DEPENDENT_FILTER_IS_NOT_PERSISTENT (62) /* The dependency filter is not persistent */ -#define RXFL_DEPENDENT_FILTER_IS_NOT_ENABLED (61) /* The dependency filter is not enabled */ -#define RXFL_FILTER_HAS_CHILDS (60) /* The filter has childs and can't be removed */ -#define RXFL_CHILD_IS_ENABLED (59) /* Can't disable filter while the child is enabled */ -#define RXFL_DEPENDENCY_IS_DISABLED (58) /* Can't enable filetr in case its depndency filter is disabled */ -#define RXFL_NUMBER_OF_CONNECTION_POINTS_EXCEEDED (52) /* Number of connection points exceeded */ -#define RXFL_DEPENDENT_FILTER_DEPENDENCY_ACTION_IS_DROP (51) /* The dependent filter has Drop action, thus the filter can't be created */ -#define RXFL_FILTER_DO_NOT_EXISTS (50) /* The filter doesn't exists */ -#define RXFL_DEPEDENCY_NOT_ON_THE_SAME_LAYER (49) /* The filter and its dependency must be on the same layer */ -#define RXFL_NUMBER_OF_ARGS_EXCEEDED (48) /* Number of arguments excceded */ -#define RXFL_ACTION_NO_REG_NUMBER (47) /* Action require counter number */ -#define RXFL_DEPENDENT_FILTER_LAYER_DO_NOT_FIT (46) /* the filter and its dependency should be from the same layer */ -#define RXFL_DEPENDENT_FILTER_SYSTEM_STATE_DO_NOT_FIT (45) /* The filter and its dependency system state don't fit */ -#define RXFL_DEPENDENT_FILTER_DO_NOT_EXIST_2 (44) /* The parent filter don't exist */ -#define RXFL_DEPENDENT_FILTER_DO_NOT_EXIST_1 (43) /* The parent filter is null */ -#define RXFL_RULE_HEADER_ACTION_TYPE_NOT_SUPPORTED (42) /* The action type is not supported */ -#define RXFL_RULE_HEADER_TRIGGER_COMPARE_FUNC_OUT_OF_RANGE (41) /* The Trigger comparision function is out of range */ -#define RXFL_RULE_HEADER_TRIGGER_OUT_OF_RANGE (40) /* The Trigger is out of range */ -#define RXFL_RULE_HEADER_COMPARE_FUNC_OUT_OF_RANGE (39) /* The rule compare function is out of range */ -#define RXFL_FRAME_TYPE_NOT_SUPPORTED (38) /* ASCII frame type string is illegal */ -#define RXFL_RULE_FIELD_ID_NOT_SUPPORTED (37) /* Rule field ID is out of range */ -#define RXFL_RULE_HEADER_FIELD_ID_ASCII_NOT_SUPPORTED (36) /* This ASCII field ID is not supported */ -#define RXFL_RULE_HEADER_NOT_SUPPORTED (35) /* The header rule is not supported on current release */ -#define RXFL_RULE_HEADER_OUT_OF_RANGE (34) /* The header rule is out of range */ -#define RXFL_RULE_HEADER_COMBINATION_OPERATOR_OUT_OF_RANGE (33) /* Combination function Id is out of ramge */ -#define RXFL_RULE_HEADER_FIELD_ID_OUT_OF_RANGE (32) /* rule field Id is out of range */ -#define RXFL_UPDATE_NOT_SUPPORTED (31) /* Update not supported */ -#define RXFL_NO_FILTERS_ARE_DEFINED (24) /* No filters are defined in the system */ -#define RXFL_NUMBER_OF_FILTER_EXCEEDED (23) /* Number of max filters excceded */ - - -/******************************************************************************/ -/* Type declarations */ -/******************************************************************************/ - -/*! - - - * \typedef SlrxFilterID_t - * Unique filter ID which is allocated by the system , negative number means error - */ -typedef _i8 SlrxFilterID_t; - - -/*! - * \typedef SlrxFilterCompareMask_t - * The mask is used for the rule comparison function - */ -typedef _u8 SlrxFilterCompareMask_t; - -/*! - * \typedef SlrxFilterIdMask_t - * Representation of filters Id as a bit field - * The bit field is used to declare which filters are involved - * in operation. Number of filter can be up to 128 filters. i.e. 128 bits are needed. - * On the current release, up to 64 filters can be defined. - */ -typedef _u8 SlrxFilterIdMask_t[128/8]; - -/*! - * \typedef SlrxFilterPrePreparedFilters_t - * Describes the supported software filter sets, - */ -typedef _u8 SlrxFilterPrePreparedFilters_t; -#define SL_ARP_AUTO_REPLY_PRE_PREPARED_FILTERS (0) -#define SL_MULTICASTSIPV4_DROP_PREPREPARED_FILTERS (1) -#define SL_MULTICASTSIPV6_DROP_PREPREPARED_FILTERS (2) -#define SL_MULTICASTSWIFI_DROP_PREPREPARED_FILTERS (3) - - - -/*! - * \typedef SlrxFilterPrePreparedFiltersMask_t - * Describes the supported software filter sets, - * each bit represents different software filter set - * The filter sets are defined at SlrxFilterPrePreparedFilters_t - */ -typedef _u8 SlrxFilterPrePreparedFiltersMask_t[SL_RX_FILTER_MAX_PRE_PREPARED_FILTERS_SETS/8]; - - -/*! \typedef SlrxFilterRegxPattern_t - * The struct contains the regular expression pattern which is used in case of payload rule. - * Not supported in the current release - */ -typedef struct SlrxFilterRegxPattern_t -{ - _u8 x[SL_RX_FILTER_LENGTH_OF_REGX_PATTERN_LENGTH]; -}SlrxFilterRegxPattern_t; - - -/*! \typedef SlrxFilterAsciiArg_t - * The buffer is used to provide container for ASCII argument, which may be used in case of HEADER rule. - * example for ASCII argument can be : IP = 256.0.67.1 - */ -typedef _u8 SlrxFilterAsciiArg_t; - - -/*! \typedef SlrxFilterBinaryArg_t - * The buffer provides container for binary argument, which may be used in case of HEADER rule - */ -typedef _u8 SlrxFilterBinaryArg_t ; - - -/*! \typedef SlrxFilterActionArg_t - * Provides container for the filter action argument. - * for example: in case action is to send automatic response , the argument is the template to be used for the automatic response. - * - * - */ -typedef _u8 SlrxFilterActionArg_t ; - - - -/*! \typedef SlrxFilterOffset_t - * The offset relative to the packet payload start location. - * Not supported on current release - */ -typedef _u32 SlrxFilterOffset_t; - - - -/*! \typedef SlrxFilterRuleType_t - * Enumerates the different filter types. - * On the current release only HEADER and COMBINATION are supported. - */ -typedef _u8 SlrxFilterRuleType_t; -/* possible values for SlrxFilterRuleType_t */ -#define HEADER (0) -#define COMBINATION (1) -#define EXACT_PATTERN (2) -#define LIKELIHOOD_PATTERN (3) -#define ALWAYS_TRUE (4) -#define NUM_OF_FILTER_TYPES (5) - - -/*! \typedef SlrxFilterFlags_t - * Bit field which sets the behaviour of the RX filter - * - */ - -#define RX_FILTER_BINARY (0x1) -#define RX_FILTER_PERSISTENT (0x8) -#define RX_FILTER_ENABLE (0x10) - -typedef union SlrxFilterFlags_t -{ - - /* struct - { */ - /*! - * The filter argument can be set as binary argument or ASCII arguments. - * When the bit is on the argument are binary. - */ - /* _u8 Binary: 1; */ - /*! - * - */ - /* _u8 AutoSort : 1; */ - /*! - * - */ - /* _u8 AutoFaultDetect : 1; */ - /*! - * When the bit is on it means the the node is enabled . - */ - /* _u8 Enabled : 1; */ - /* _u8 padding : 3; */ - /* - };*/ - - _u8 IntRepresentation; - -}SlrxFilterFlags_t; - -/*! \typedef SlrxFilterCompareFunction_t - * Used as comparison function for the header type arguments - * - */ -typedef _u8 SlrxFilterCompareFunction_t; -/* Possible values for SlrxFilterCompareFunction_t */ -#define COMPARE_FUNC_IN_BETWEEN (0) -#define COMPARE_FUNC_EQUAL (1) -#define COMPARE_FUNC_NOT_EQUAL_TO (2) -#define COMPARE_FUNC_NOT_IN_BETWEEN (3) -#define COMPARE_FUNC_NUM_OF_FILTER_COMPARE_FUNC (4) - -/*! \typedef SlrxFilterCompareFunction_t - * Used as comparison function for the header type arguments - * - */ -typedef _u8 SlrxTriggerCompareFunction_t; -/* Possible values for SlrxTriggerCompareFunction_t */ -#define TRIGGER_COMPARE_FUNC_EQUAL (0) -/* arg1 == protocolVal ,not supported in current release */ -#define TRIGGER_COMPARE_FUNC_NOT_EQUAL_TO (1) -/* arg1 == protocolVal */ -#define TRIGGER_COMPARE_FUNC_SMALLER_THAN (2) -/* arg1 == protocolVal */ -#define TRIGGER_COMPARE_FUNC_BIGGER_THAN (3) -/* definition */ -#define TRIGGER_COMPARE_FUNC_NUM_OF_FILTER_COMPARE_FUNC (4) - - -/*! \typedef SlrxFilterHdrField_t - * Provides list of possible header types which may be defined as part of the rule - * - */ -typedef _u8 SlrxFilterHdrField_t; -/* Possible values for SlrxFilterHdrField_t */ -#define NULL_FIELD_ID_TYPE (0) -/* 802.11 control\data\management */ -#define FRAME_TYPE_FIELD (1) -/* 802.11 beacon\probe\.. */ -#define FRAME_SUBTYPE_FIELD (2) - /* 802.11 bssid type */ -#define BSSID_FIELD (3) - /* */ -#define MAC_SRC_ADDRESS_FIELD (4) - /* */ -#define MAC_DST_ADDRESS_FIELD (5) -/* */ -#define FRAME_LENGTH_FIELD (6) -/* */ -#define PROTOCOL_TYPE_FIELD (7) - /* */ -#define IP_VERSION_FIELD (8) - /* TCP / UDP */ -#define IP_PROTOCOL_FIELD (9) - /* */ -#define IPV4_SRC_ADRRESS_FIELD (10) -/* */ -#define IPV4_DST_ADDRESS_FIELD (11) -/* */ -#define IPV6_SRC_ADRRESS_FIELD (12) -/* */ -#define IPV6_DST_ADDRESS_FIELD (13) - /* */ -#define SRC_PORT_FIELD (14) - /* */ -#define DST_PORT_FIELD (15) - /* Definition */ -#define NUM_OF_FIELD_NAME_FIELD (16) - -/*! \union SlrxFilterHeaderArg_t - * The structure holds the header ARGS which are used in case of HDR rule. - */ -/* -- 36 bytes */ -typedef union SlrxFilterHeaderArg_t -{ - /*----------------------------- Large size ---------------------------------*/ - /*! buffer for binary arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS - * example : IPV6 16 bytes, 39 characters - * ipv6 Ascii address: 2001:0db8:3c4d:0015:0000:0000:abcd:ef12 - */ - - SlrxFilterBinaryArg_t RxFilterDB16BytesRuleArgs[SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS][16 ]; /* Binary Values for comparition */ - /*! buffer for ASCII arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS - * example : IPV6 16 bytes, 39 characters - * ipv6 Ascii address: 2001:0db8:3c4d:0015:0000:0000:abcd:ef12 - * Ascii format for ipV6 is not supported - */ - /*----------------------------- Medium size ---------------------------------*/ - /*! buffer for binary arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS - * MAC address: 6 bytes, 17 chars - */ - SlrxFilterBinaryArg_t RxFilterDB6BytesRuleArgs[SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS][6]; /* Binary Values for comparition */ - /*! - * ! buffer for ASCII arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS - * IP address: 4 bytes, 15 chars - * 2 bytes are added for padding - */ - SlrxFilterAsciiArg_t RxFilterDB18BytesAsciiRuleArgs[SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS][18]; /* Ascii Values for comparison */ - /*----------------------------- Small size ---------------------------------*/ - /*! buffer for binary arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS - * IP address: 4 bytes, 15 chars - * Port: 2 bytes, chars: 5 chars - */ - SlrxFilterBinaryArg_t RxFilterDB4BytesRuleArgs[SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS][4]; /* Binary Values for comparison */ - /*! buffer for ASCII arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS - * Port: 2 bytes, chars: 5 chars - */ - SlrxFilterAsciiArg_t RxFilterDB5BytesRuleAsciiArgs[SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS][5]; /* Ascii Values for comparison */ - /*----------------------------- 1 byte size ---------------------------------*/ - /*! buffer for binary arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS - */ - SlrxFilterBinaryArg_t RxFilterDB1BytesRuleArgs[SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS][1]; /* Binary Values for comparison */ -}SlrxFilterHeaderArg_t; - - - -/*! \typedef SlrxFilterRuleHeaderArgsAndMask_t - * Structure which defines the Header Args and mask - */ -/* -- 52 bytes */ -typedef struct SlrxFilterRuleHeaderArgsAndMask_t -{ - /*! Argument for the comparison function */ - /* -- 36 byte */ - SlrxFilterHeaderArg_t RuleHeaderArgs; - - /*! the mask is used in order to enable partial comparison, - * Use the 0xFFFFFFFF in case you don't want to use mask - */ - /* -- 16 bytes */ - SlrxFilterCompareMask_t RuleHeaderArgsMask[16]; - -}SlrxFilterRuleHeaderArgsAndMask_t; - -/*! \typedef SlrxFilterHeaderType_t - * Structure which defines the Header rule - * The header rule defines compare function on the protocol header - * For example destMacAddre is between ( 12:6::78:77, 12:6::78:90 ) - * - */ -/* -- 56 byte */ -typedef struct SlrxFilterHeaderType_t -{ - /*! see :: SlrxFilterRuleHeaderArgsAndMask_t */ - /* -- 52 bytes */ - SlrxFilterRuleHeaderArgsAndMask_t RuleHeaderArgsAndMask; - - /*! Packet HDR field which will be compared to the argument */ - /* -- 1 byte */ - SlrxFilterHdrField_t RuleHeaderfield; - - /* -- 1 byte */ - /*! type of the comparison function - * see :: SlrxFilterCompareFunction_t - */ - SlrxFilterCompareFunction_t RuleCompareFunc; - - /*! padding */ - /* -- 2 bytes */ - _u8 RulePadding[2]; - -}SlrxFilterHeaderType_t; - -/*! \typedef SlrxFilterPayloadType_t - * Structure which defines payload rule. - * Not supported on current release. - */ -/* -- 40 byte */ -typedef struct SlrxFilterPayloadType_t -{ - /*! Not supported on current release */ - /* -- 32 byte */ - SlrxFilterRegxPattern_t RegxPattern; - /*! Not supported on current release */ - /* -- 4 byte */ - SlrxFilterOffset_t LowerOffset; - /*! Not supported on current release */ - /* -- 4 byte */ - SlrxFilterOffset_t UpperOffset; -}SlrxFilterPayloadType_t; - -/*! \typedef SlrxFilterCombinationTypeOperator_t - * Enumerate the optional operators for the combination type - * filterID1 is located in the first arg , filterId2 is the second arg,see ::SlrxFilterCombinationType_t.CombinationFilterId - */ -typedef _u8 SlrxFilterCombinationTypeOperator_t; -/* Possible values for SlrxFilterCombinationTypeOperator_t */ -/*! !filterID1 */ -#define COMBINED_FUNC_NOT (0) -/*! filterID1 && filterID2 */ -#define COMBINED_FUNC_AND (1) -/*! filterID1 && filterID2 */ -#define COMBINED_FUNC_OR (2) - -/*! \typedef SlrxFilterCombinationType_t - * Defines the structure which define the combination type filter - * The combined filter enable to make operation on one or two filter, - * for example !filterId1 or and(filterId2,filterId3). - * - */ -/* -- 4 byte */ -typedef struct SlrxFilterCombinationType_t -{ - /* ! combination operator */ - /* -- 1 byte */ - SlrxFilterCombinationTypeOperator_t CombinationTypeOperator; - /* ! filterID, may be one or two depends on the combination operator type */ - /* -- 2 byte */ - SlrxFilterID_t CombinationFilterId[SL_RX_FILTER_NUM_OF_COMBINATION_TYPE_ARGS]; - /* ! Padding */ - /* -- 1 byte */ - _u8 Padding; -}SlrxFilterCombinationType_t; - - -/*! \typedef SlrxFilterRule_t - * Rule structure composed of behavioral flags and the filter rule definitions - * - */ -/* -- 56 byte */ -typedef union SlrxFilterRule_t -{ - /* ! Header type rule , see explanation on the ::SlrxFilterHeaderType_t structure */ - /* -- 56 byte */ - SlrxFilterHeaderType_t HeaderType; - /* ! Payload rule, not supported in current release */ - /* -- 40 byte */ - SlrxFilterPayloadType_t PayLoadHeaderType; /* future for exact pattern or like hood pattern */ - /* ! Combined type rule , see explanation in ::SlrxFilterCombinationType_t structure */ - /* -- 4 byte */ - SlrxFilterCombinationType_t CombinationType; -}SlrxFilterRule_t; - -/*! \typedef SlrxFilterTriggerRoles_t - * Bit field which represents the roleId possible values - * In the current release only Station/AP roles are supported. - */ -#define RX_FILTER_ROLE_AP (1) -#define RX_FILTER_ROLE_STA (2) -#define RX_FILTER_ROLE_PROMISCUOUS (4) -#define RX_FILTER_ROLE_NULL (0) - -typedef union SlrxFilterTriggerRoles_t -{ -/* struct */ -/* { */ -/* _u8 RoleAP :1; */ -/* _u8 RoleStation :1; */ - /* The filter is activated only in Promiscuous mode */ -/* _u8 PromiscuousMode :1; */ -/* _u8 RoleReserved :5; */ -/* }; */ - /* ! Bit fiels of the Filter role */ - _u8 IntRepresentation; - -}SlrxFilterTriggerRoles_t; - -/*! \typedef SlrxFilterTriggerConnectionStates_t - * Bit field representing the possible values of the When section of the rule - * - */ -#define RX_FILTER_CONNECTION_STATE_STA_CONNECTED (1) -#define RX_FILTER_CONNECTION_STATE_STA_NOT_CONNECTED (2) -#define RX_FILTER_CONNECTION_STATE_STA_HAS_IP (4) -#define RX_FILTER_CONNECTION_STATE_STA_HAS_NO_IP (8) - -typedef union SlrxFilterTriggerConnectionStates_t -{ -/* struct */ -/* { */ -/* _u8 RoleStationWiFiConnected :1; */ -/* _u8 RoleStationWiFiDisconneted:1; */ -/* _u8 RoleStationWiFiHasIp:1; */ -/* _u8 RoleStationWiFiHasNoIp:1; */ -/* _u8 RoleStationWiFiSocketOpened:1; */ -/* _u8 RoleStationWiFiSocketclosed:1; */ -/* }; */ -/* */ - /* ! */ - _u8 IntRepresentation; - -}SlrxFilterTriggerConnectionStates_t; - -/*! \typedef SlrxFilterDBTriggerArg_t - * Provides container for entering the filter 'when' argument. - * The current release support 'When rules' which has no arguments. - * For example : - * When connect to specific AP -- the AP bssid is the argument. - * - */ -typedef _u32 SlrxFilterDBTriggerArg_t; - - - -/*! \typedef SlrxFilterCounterId_t - * the counter ID we have 4 counters - */ -typedef _u8 SlrxFilterCounterId_t; -/* Possible values for SlrxFilterCounterId_t */ -#define NO_TRIGGER (0) -#define RX_FILTER_COUNTER1 (1) -#define RX_FILTER_COUNTER2 (2) -#define RX_FILTER_COUNTER3 (3) -#define RX_FILTER_COUNTER4 (4) -#define RX_FILTER_COUNTER5 (5) -#define RX_FILTER_COUNTER6 (6) -#define RX_FILTER_COUNTER7 (7) -#define RX_FILTER_COUNTER8 (8) -#define MAX_RX_FILTER_COUNTER (9) - - - -/*! \typedef SlrxFilterActionArgs_t - * Possible value for filter action args - * - */ - -typedef _u8 SlrxFilterActionArgs_t; -/* Possible values for SlrxFilterActionArgs_t */ -#define ACTION_ARG_REG_1_4 (0) - /* ! Can be use as counter */ -#define ACTION_ARG_TEMPLATE (1) - /* ! Can be use as counter */ -#define ACTION_ARG_EVENT (2) - -/* ! GPIO number */ -#define ACTION_ARG_GPIO (4) -/*! - * \def SL_RX_FILTER_NUM_OF_BYTES_FOR_ACTIONS_ARGS - * - */ -#define SL_RX_FILTER_NUM_OF_BYTES_FOR_ACTIONS_ARGS (5) - - - - -/*! \typedef SlrxFilterTrigger_t - * The filter trigger, determine when the filter is triggered, - * The filter is triggered in the following condition :\n - * 1. The filter parent is triggered\n - * 2. The requested connection type exists, i.e. wlan_connect\n - * 3. The filter role is the same as the system role\n - * - */ -/* -- 12 byte */ -typedef struct SlrxFilterTrigger_t -{ - /*! The parent filter ID, this is the way to build filter tree. */ - /* NULL value means tree root. - */ - /* -- 1 byte */ - SlrxFilterID_t ParentFilterID; - /* ! See ::SlrxFilterCounterId_t explanation */ - /* -- 1 byte */ - SlrxFilterCounterId_t Trigger; - /* ! See :: SlrxFilterTriggerConnectionStates_t */ - /* -- 1 byte */ - SlrxFilterTriggerConnectionStates_t TriggerArgConnectionState; - /* ! See ::SlrxFilterTriggerRoles_t */ - /* -- 1 byte */ - SlrxFilterTriggerRoles_t TriggerArgRoleStatus; - /* ! The Trigger arguments are in the same order as the Trigger bit field order. */ - /* -- 4 byte */ - SlrxFilterDBTriggerArg_t TriggerArg; - /** The compare function which will be operate for each bit that is turned on in the ::SlrxFilterTrigger_t.Trigger field, - * for example , in case the second bit in the Trigger function is on the second function in the list will be executed. - * - */ - /* -- 1 byte */ - SlrxTriggerCompareFunction_t TriggerCompareFunction; - - /* ! padding */ - /* -- 3 byte */ - _u8 Padding[3]; -} SlrxFilterTrigger_t; - -/*! \typedef SlrxFilterActionType_t - * The actions are executed only if the filter is matched,\n - * In case of false match the packet is transfered to the HOST. \n - * The action is composed of bit field structure, - * up to 2 actions can be defined per filter. - * - */ -#define RX_FILTER_ACTION_NULL (0x0) -#define RX_FILTER_ACTION_DROP (0x1) -#define RX_FILTER_ACTION_GPIO (0x2) -#define RX_FILTER_ACTION_ON_REG_INCREASE (0x4) -#define RX_FILTER_ACTION_ON_REG_DECREASE (0x8) -#define RX_FILTER_ACTION_ON_REG_RESET (0x10) -#define RX_FILTER_ACTION_SEND_TEMPLATE (0x20) /* unsupported */ -#define RX_FILTER_ACTION_EVENT_TO_HOST (0x40) /* unsupported */ - -typedef union SlrxFilterActionType_t -{ -/* struct */ -/* { */ - /* ! No action to execute the packet is dropped,drop is always on leaf. */ - /* ! If not dropped ,The packet is passed to the next filter or in case it is the last filter to the host */ -/* _u8 ActionDrop : 1; */ - /* ! Not Supported in the current release */ -/* _u8 ActionGpio : 1; */ - /*! action can increase counter registers. - * 1 = Increase - * 2 = decrease - * 3 = reset - */ -/* _u8 ActionOnREGIncrease : 1; */ -/* _u8 ActionOnREGDecrease : 1; */ -/* _u8 ActionOnREGReset : 1; */ - - /* ! Not Supported in the current release */ -/* _u8 ActionSendTemplate : 1; */ - /* ! Not Supported in the current release */ -/* _u8 ActionEventToHost: 1; */ -/* _u8 padding: 1; */ -/* }; */ - - _u8 IntRepresentation; - -}SlrxFilterActionType_t; - -/*! \typedef SlrxFilterAction_t - * Several actions can be defined,\n - * The action is executed in case the filter rule is matched. - */ -/* -- 8 byte */ -typedef struct SlrxFilterAction_t -{ - /* -- 1 byte */ - /* ! Determine which actions are supported */ - SlrxFilterActionType_t ActionType; - /* ! Buffer for the action arguments */ - /** - * location 0 - The counter to increase - * In case the action is of type "increase" the arg will contain the counter number, - * The counter number values are as in ::SlrxFilterCounterId_t.\n - * location 1 - The template arg.\n - * location 2 - The event arg.\n - * - */ - /* -- 5 byte */ - SlrxFilterActionArg_t ActionArg[SL_RX_FILTER_NUM_OF_BYTES_FOR_ACTIONS_ARGS]; - - /* ! Padding */ - /* - 2 Bytes */ - _u8 Padding[2]; - -} SlrxFilterAction_t; - - -/*! \struct _WlanRxFilterOperationCommandBuff_t - * The structure is used for the interface HOST NWP.\n - * The supported operation : \n - * ::ENABLE_DISABLE_RX_FILTER,\n - * ::REMOVE_RX_FILTER,\n - * - */ -/* 20 bytes */ -typedef struct _WlanRxFilterOperationCommandBuff_t -{ - /* -- 16 bytes */ - SlrxFilterIdMask_t FilterIdMask; - /* 4 bytes */ - _u8 Padding[4]; -}_WlanRxFilterOperationCommandBuff_t; - - - -/* -- 56 bytes */ -typedef struct _WlanRxFilterUpdateArgsCommandBuff_t -{ - /* -- 1 bytes */ - _u8 FilterId; - - /* -- 1 bytes */ - /* ! the args representation */ - _u8 BinaryRepresentation; - - /* -- 52 byte */ - SlrxFilterRuleHeaderArgsAndMask_t FilterRuleHeaderArgsAndMask; - - /* -- 2 bytes */ - _u8 Padding[2]; -}_WlanRxFilterUpdateArgsCommandBuff_t; - - -/*! \typedef _WlanRxFilterRetrieveEnableStatusCommandResponseBuff_t - * The structure is used for the interface HOST NWP.\n - * - */ -/* -- 16 bytes */ -typedef struct _WlanRxFilterRetrieveEnableStatusCommandResponseBuff_t -{ - - /* ! the filter set bit map */ - /* -- 16 bytes */ - SlrxFilterIdMask_t FilterIdMask; - -}_WlanRxFilterRetrieveEnableStatusCommandResponseBuff_t; - - -/*! \struct _WlanRxFilterPrePreparedFiltersCommandBuff_t - * The function enables to perform operations on pre-prepared filters - * - */ -typedef struct _WlanRxFilterPrePreparedFiltersCommandBuff_t -{ - /* ! the filter set bit map */ - /* -- 4 bytes */ - SlrxFilterPrePreparedFiltersMask_t FilterPrePreparedFiltersMask; - -}_WlanRxFilterPrePreparedFiltersCommandBuff_t; - - -/*! \typedef sl_protocol_WlanRxFilterPrePreparedFiltersCommandResponseBuff_t - * - */ -/*-- 4 bytes */ -typedef struct _WlanRxFilterPrePreparedFiltersCommandResponseBuff_t -{ - /* -- 4 bytes */ - /* ! the filter set bit map */ - SlrxFilterPrePreparedFiltersMask_t FilterPrePreparedFiltersMask; - -}_WlanRxFilterPrePreparedFiltersCommandResponseBuff_t; - - - -typedef _u8 SLrxFilterOperation_t; -#define SL_ENABLE_DISABLE_RX_FILTER (0) -#define SL_REMOVE_RX_FILTER (1) -#define SL_STORE_RX_FILTERS (2) -#define SL_UPDATE_RX_FILTER_ARGS (3) -#define SL_FILTER_RETRIEVE_ENABLE_STATE (4) -#define SL_FILTER_PRE_PREPARED_RETRIEVE_CREATE_REMOVE_STATE (5) -#define SL_FILTER_PRE_PREPARED_SET_CREATE_REMOVE_STATE (6) - - -/* Bit manipulation for 8 bit */ -#define ISBITSET8(x,i) ((x[i>>3] & (0x80>>(i&7)))!=0) /* < Is bit set, 8 bit unsigned numbers = x , location = i */ -#define SETBIT8(x,i) x[i>>3]|=(0x80>>(i&7)); /* < Set bit,8 bit unsigned numbers = x , location = i */ -#define CLEARBIT8(x,i) x[i>>3]&=(0x80>>(i&7))^0xFF; /* < Clear bit,8 bit unsigned numbers = x , location = i */ - - -/*********************************************************************************************/ -/* Function prototypes */ -/*********************************************************************************************/ - -/*! - - \addtogroup wlan - @{ - -*/ - - -/*! - \brief Adds new filter rule to the system - - \param[in] RuleType The rule type - \param[in] FilterFlags Flags which set the type of header rule Args and sets the persistent flag - \param[in] pRule Determine the filter rule logic - \param[in] pTrigger Determine when the rule is triggered also sets rule parent. - \param[in] pAction Sets the action to be executed in case the match functions pass - \param[out] pFilterId The filterId which was created - - \return On success, zero is returned. Otherwise error code is returned - */ -#if _SL_INCLUDE_FUNC(sl_WlanRxFilterAdd) -SlrxFilterID_t sl_WlanRxFilterAdd( SlrxFilterRuleType_t RuleType, - SlrxFilterFlags_t FilterFlags, - const SlrxFilterRule_t* const Rule, - const SlrxFilterTrigger_t* const Trigger, - const SlrxFilterAction_t* const Action, - SlrxFilterID_t* pFilterId); - -#endif - - - - - -/*! - \brief Sets parameters to Rx filters - - \param[in] RxFilterOperation - possible operations : - - SL_ENABLE_DISABLE_RX_FILTER - Enables\disables filter in a filter list - - SL_REMOVE_RX_FILTER - Removes filter from memory ( to remove from flash call SL_STORE_RX_FILTERS after this command) - - SL_STORE_RX_FILTERS - Save the filters for persistent - - SL_UPDATE_RX_FILTER_ARGS - Update the arguments of existing filter - - SL_FILTER_PRE_PREPARED_SET_CREATE_REMOVE_STATE - Change the default creation of the pre-prepared filters - - \param[in] pInputBuffer options: - The buffer input is _WlanRxFilterOperationCommandBuff_t: - - SL_ENABLE_DISABLE_RX_FILTER - - SL_REMOVE_RX_FILTER - - SL_STORE_RX_FILTERS - The buffer input is _WlanRxFilterUpdateArgsCommandBuff_t: - - SL_UPDATE_RX_FILTER_ARGS - The buffer input is _WlanRxFilterPrePreparedFiltersCommandBuff_t: - - SL_FILTER_PRE_PREPARED_SET_CREATE_REMOVE_STATE - - \param[in] InputbufferLength The length in byte of the input buffer - - \return On success, zero is returned. Otherwise error code is returned - */ - -#if _SL_INCLUDE_FUNC(sl_WlanRxFilterSet) -_i16 sl_WlanRxFilterSet( const SLrxFilterOperation_t RxFilterOperation, - const _u8* const pInputBuffer, - _u16 InputbufferLength); -#endif - -/*! - \brief Gets parameters of Rx filters - - \param[in] RxFilterOperation - possible operations : - - SL_FILTER_RETRIEVE_ENABLE_STATE - Retrieves the enable disable status - - SL_FILTER_PRE_PREPARED_RETRIEVE_CREATE_REMOVE_STATE - Retrieves the pre-prepared filters creation status - - \param[in] pOutputBuffer - The buffer input is _WlanRxFilterRetrieveEnableStatusCommandResponseBuff_t: - - SL_FILTER_RETRIEVE_ENABLE_STATE - The buffer input is _WlanRxFilterPrePreparedFiltersCommandResponseBuff_t: - - SL_FILTER_PRE_PREPARED_RETRIEVE_CREATE_REMOVE_STATE - - \param[in] OutputbufferLength The length in byte of the output buffer - - \return On success, zero is returned. Otherwise error code is returned -*/ - -#if _SL_INCLUDE_FUNC(sl_WlanRxFilterGet) -_i16 sl_WlanRxFilterGet(const SLrxFilterOperation_t RxFilterOperation, - _u8* pOutputBuffer, - _u16 OutputbufferLength); -#endif - - -/*! - - Close the Doxygen group. - @} - - */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* RX_FILTERS_PREPROCESSOR_CLI_IF_H_ */ - - diff --git a/drivers/cc3100/src/device.c b/drivers/cc3100/src/device.c deleted file mode 100644 index 3d4028fb4a..0000000000 --- a/drivers/cc3100/src/device.c +++ /dev/null @@ -1,557 +0,0 @@ -/* -* device.c - CC31xx/CC32xx Host Driver Implementation -* -* Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ -* -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - - - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" -#include "protocol.h" -#include "flowcont.h" -#include "driver.h" - - -/*****************************************************************************/ -/* Internal functions */ -/*****************************************************************************/ - -const _i8 StartResponseLUT[8] = -{ - ROLE_UNKNOWN_ERR, - ROLE_STA, - ROLE_STA_ERR, - ROLE_AP, - ROLE_AP_ERR, - ROLE_P2P, - ROLE_P2P_ERR, - ROLE_UNKNOWN_ERR -}; - - - -_i16 _sl_GetStartResponseConvert(_u32 Status) -{ - return (_i16)StartResponseLUT[Status & 0x7]; -} - -/*****************************************************************************/ -/* API Functions */ -/*****************************************************************************/ - - - -/*****************************************************************************/ -/* sl_Task */ -/*****************************************************************************/ -#if _SL_INCLUDE_FUNC(sl_Task) -void sl_Task(void) -{ -#ifdef _SlTaskEntry - _SlTaskEntry(); -#endif -} -#endif - -/*****************************************************************************/ -/* sl_Start */ -/*****************************************************************************/ -#if _SL_INCLUDE_FUNC(sl_Start) -_i16 sl_Start(const void* pIfHdl, _i8* pDevName, const P_INIT_CALLBACK pInitCallBack) -{ - _i16 ObjIdx = MAX_CONCURRENT_ACTIONS; - InitComplete_t AsyncRsp; - - /* Perform any preprocessing before enable networking services */ - sl_DeviceEnablePreamble(); - - /* ControlBlock init */ - _SlDrvDriverCBInit(); - - /* open the interface: usually SPI or UART */ - if (NULL == pIfHdl) - { - g_pCB->FD = sl_IfOpen((void *)pDevName, 0); - } - else - { - g_pCB->FD = (_SlFd_t)pIfHdl; - } - - ObjIdx = _SlDrvProtectAsyncRespSetting((_u8 *)&AsyncRsp, START_STOP_ID, SL_MAX_SOCKETS); - - if (MAX_CONCURRENT_ACTIONS == ObjIdx) - { - return SL_POOL_IS_EMPTY; - } - - if( g_pCB->FD >= (_SlFd_t)0) - { - sl_DeviceDisable(); - - sl_IfRegIntHdlr((SL_P_EVENT_HANDLER)_SlDrvRxIrqHandler, NULL); - - g_pCB->pInitCallback = pInitCallBack; - sl_DeviceEnable(); - - if (NULL == pInitCallBack) - { - _SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj); - - /* release Pool Object */ - _SlDrvReleasePoolObj(g_pCB->FunctionParams.AsyncExt.ActionIndex); - return _sl_GetStartResponseConvert(AsyncRsp.Status); - } - else - { - return SL_RET_CODE_OK; - } - } - return SL_BAD_INTERFACE; -} -#endif - -/*************************************************************************** -_sl_HandleAsync_InitComplete - handles init complete signalling to -a waiting object -****************************************************************************/ -void _sl_HandleAsync_InitComplete(void *pVoidBuf) -{ - InitComplete_t *pMsgArgs = (InitComplete_t *)_SL_RESP_ARGS_START(pVoidBuf); - - _SlDrvProtectionObjLockWaitForever(); - - if(g_pCB->pInitCallback) - { - g_pCB->pInitCallback(_sl_GetStartResponseConvert(pMsgArgs->Status)); - } - else - { - sl_Memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(InitComplete_t)); - _SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj); - } - - _SlDrvProtectionObjUnLock(); - - if(g_pCB->pInitCallback) - { - _SlDrvReleasePoolObj(g_pCB->FunctionParams.AsyncExt.ActionIndex); - } - -} - -/*************************************************************************** -_sl_HandleAsync_Stop - handles stop signalling to -a waiting object -****************************************************************************/ -void _sl_HandleAsync_Stop(void *pVoidBuf) -{ - _BasicResponse_t *pMsgArgs = (_BasicResponse_t *)_SL_RESP_ARGS_START(pVoidBuf); - - VERIFY_SOCKET_CB(NULL != g_pCB->StopCB.pAsyncRsp); - - _SlDrvProtectionObjLockWaitForever(); - - sl_Memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(_BasicResponse_t)); - - _SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj); - _SlDrvProtectionObjUnLock(); - - return; -} - - -/***************************************************************************** -sl_stop -******************************************************************************/ -typedef union -{ - _DevStopCommand_t Cmd; - _BasicResponse_t Rsp; -}_SlStopMsg_u; - -const _SlCmdCtrl_t _SlStopCmdCtrl = -{ - SL_OPCODE_DEVICE_STOP_COMMAND, - sizeof(_DevStopCommand_t), - sizeof(_BasicResponse_t) -}; - -#if _SL_INCLUDE_FUNC(sl_Stop) -_i16 sl_Stop(const _u16 timeout) -{ - _i16 RetVal=0; - _SlStopMsg_u Msg; - _BasicResponse_t AsyncRsp; - _i8 ObjIdx = MAX_CONCURRENT_ACTIONS; - /* if timeout is 0 the shutdown is forced immediately */ - if( 0 == timeout ) - { - sl_IfRegIntHdlr(NULL, NULL); - sl_DeviceDisable(); - RetVal = sl_IfClose(g_pCB->FD); - - } - else - { - /* let the device make the shutdown using the defined timeout */ - Msg.Cmd.Timeout = timeout; - - ObjIdx = _SlDrvProtectAsyncRespSetting((_u8 *)&AsyncRsp, START_STOP_ID, SL_MAX_SOCKETS); - if (MAX_CONCURRENT_ACTIONS == ObjIdx) - { - return SL_POOL_IS_EMPTY; - } - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlStopCmdCtrl, &Msg, NULL)); - - if(SL_OS_RET_CODE_OK == (_i16)Msg.Rsp.status) - { - _SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj); - Msg.Rsp.status = AsyncRsp.status; - RetVal = Msg.Rsp.status; - } - - _SlDrvReleasePoolObj(ObjIdx); - sl_IfRegIntHdlr(NULL, NULL); - sl_DeviceDisable(); - sl_IfClose(g_pCB->FD); - } - _SlDrvDriverCBDeinit(); - - return RetVal; -} -#endif - - -/***************************************************************************** -sl_EventMaskSet -*****************************************************************************/ -typedef union -{ - _DevMaskEventSetCommand_t Cmd; - _BasicResponse_t Rsp; -}_SlEventMaskSetMsg_u; - - - - -#if _SL_INCLUDE_FUNC(sl_EventMaskSet) - -const _SlCmdCtrl_t _SlEventMaskSetCmdCtrl = -{ - SL_OPCODE_DEVICE_EVENTMASKSET, - sizeof(_DevMaskEventSetCommand_t), - sizeof(_BasicResponse_t) -}; - - -_i16 sl_EventMaskSet(const _u8 EventClass ,const _u32 Mask) -{ - _SlEventMaskSetMsg_u Msg; - - Msg.Cmd.group = EventClass; - Msg.Cmd.mask = Mask; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlEventMaskSetCmdCtrl, &Msg, NULL)); - - return (_i16)Msg.Rsp.status; -} -#endif - -/****************************************************************************** -sl_EventMaskGet -******************************************************************************/ -typedef union -{ - _DevMaskEventGetCommand_t Cmd; - _DevMaskEventGetResponse_t Rsp; -}_SlEventMaskGetMsg_u; - - - -#if _SL_INCLUDE_FUNC(sl_EventMaskGet) - -const _SlCmdCtrl_t _SlEventMaskGetCmdCtrl = -{ - SL_OPCODE_DEVICE_EVENTMASKGET, - sizeof(_DevMaskEventGetCommand_t), - sizeof(_DevMaskEventGetResponse_t) -}; - - -_i16 sl_EventMaskGet(const _u8 EventClass,_u32 *pMask) -{ - _SlEventMaskGetMsg_u Msg; - - Msg.Cmd.group = EventClass; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlEventMaskGetCmdCtrl, &Msg, NULL)); - - *pMask = Msg.Rsp.mask; - return SL_RET_CODE_OK; -} -#endif - - - -/****************************************************************************** -sl_DevGet -******************************************************************************/ - -typedef union -{ - _DeviceSetGet_t Cmd; - _DeviceSetGet_t Rsp; -}_SlDeviceMsgGet_u; - - - -#if _SL_INCLUDE_FUNC(sl_DevGet) - -const _SlCmdCtrl_t _SlDeviceGetCmdCtrl = -{ - SL_OPCODE_DEVICE_DEVICEGET, - sizeof(_DeviceSetGet_t), - sizeof(_DeviceSetGet_t) -}; - -_i32 sl_DevGet(const _u8 DeviceGetId,_u8 *pOption,_u8 *pConfigLen, _u8 *pValues) -{ - _SlDeviceMsgGet_u Msg; - _SlCmdExt_t CmdExt; - - if (*pConfigLen == 0) - { - return SL_EZEROLEN; - } - - if( pOption ) - { - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.RxPayloadLen = *pConfigLen; - CmdExt.pRxPayload = (_u8 *)pValues; - - Msg.Cmd.DeviceSetId = DeviceGetId; - - Msg.Cmd.Option = (_u16)*pOption; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlDeviceGetCmdCtrl, &Msg, &CmdExt)); - - if( pOption ) - { - *pOption = (_u8)Msg.Rsp.Option; - } - - if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) - { - *pConfigLen = (_u8)CmdExt.RxPayloadLen; - return SL_ESMALLBUF; - } - else - { - *pConfigLen = (_u8)CmdExt.ActualRxPayloadLen; - } - - return (_i16)Msg.Rsp.Status; - } - else - { - return -1; - } -} -#endif - -/****************************************************************************** -sl_DevSet -******************************************************************************/ -typedef union -{ - _DeviceSetGet_t Cmd; - _BasicResponse_t Rsp; -}_SlDeviceMsgSet_u; - - - -#if _SL_INCLUDE_FUNC(sl_DevSet) - -const _SlCmdCtrl_t _SlDeviceSetCmdCtrl = -{ - SL_OPCODE_DEVICE_DEVICESET, - sizeof(_DeviceSetGet_t), - sizeof(_BasicResponse_t) -}; - -_i32 sl_DevSet(const _u8 DeviceSetId ,const _u8 Option,const _u8 ConfigLen,const _u8 *pValues) -{ - _SlDeviceMsgSet_u Msg; - _SlCmdExt_t CmdExt; - - - _SlDrvResetCmdExt(&CmdExt); - - CmdExt.TxPayloadLen = (ConfigLen+3) & (~3); - CmdExt.pTxPayload = (_u8 *)pValues; - - Msg.Cmd.DeviceSetId = DeviceSetId; - Msg.Cmd.ConfigLen = ConfigLen; - Msg.Cmd.Option = Option; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlDeviceSetCmdCtrl, &Msg, &CmdExt)); - - return (_i16)Msg.Rsp.status; -} -#endif - - -/****************************************************************************** -_SlDrvDeviceEventHandler - handles internally device async events -******************************************************************************/ -void _SlDrvDeviceEventHandler(void* pArgs) -{ - _SlResponseHeader_t *pHdr = (_SlResponseHeader_t *)pArgs; - - switch(pHdr->GenHeader.Opcode) - { - case SL_OPCODE_DEVICE_INITCOMPLETE: - _sl_HandleAsync_InitComplete(pHdr); - break; - case SL_OPCODE_DEVICE_STOP_ASYNC_RESPONSE: - _sl_HandleAsync_Stop(pHdr); - break; - - - case SL_OPCODE_DEVICE_ABORT: - { -#if defined (sl_GeneralEvtHdlr) || defined(EXT_LIB_REGISTERED_GENERAL_EVENTS) - SlDeviceEvent_t devHandler; - devHandler.Event = SL_DEVICE_ABORT_ERROR_EVENT; - devHandler.EventData.deviceReport.AbortType = *((_u32*)pArgs + 2); - devHandler.EventData.deviceReport.AbortData = *((_u32*)pArgs + 3); - _SlDrvHandleGeneralEvents(&devHandler); -#endif - } - break; - - case SL_OPCODE_DEVICE_DEVICEASYNCFATALERROR: -#if defined (sl_GeneralEvtHdlr) || defined(EXT_LIB_REGISTERED_GENERAL_EVENTS) - { - _BasicResponse_t *pMsgArgs = (_BasicResponse_t *)_SL_RESP_ARGS_START(pHdr); - SlDeviceEvent_t devHandler; - devHandler.Event = SL_DEVICE_FATAL_ERROR_EVENT; - devHandler.EventData.deviceEvent.status = pMsgArgs->status & 0xFF; - devHandler.EventData.deviceEvent.sender = (SlErrorSender_e)((pMsgArgs->status >> 8) & 0xFF); - _SlDrvHandleGeneralEvents(&devHandler); - } -#endif - break; - default: - SL_ERROR_TRACE2(MSG_306, "ASSERT: _SlDrvDeviceEventHandler : invalid opcode = 0x%x = %1", pHdr->GenHeader.Opcode, pHdr->GenHeader.Opcode); - } -} - - -/****************************************************************************** -sl_UartSetMode -******************************************************************************/ -#ifdef SL_IF_TYPE_UART -typedef union -{ - _DevUartSetModeCommand_t Cmd; - _DevUartSetModeResponse_t Rsp; -}_SlUartSetModeMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_UartSetMode) - - -const _SlCmdCtrl_t _SlUartSetModeCmdCtrl = -{ - SL_OPCODE_DEVICE_SETUARTMODECOMMAND, - sizeof(_DevUartSetModeCommand_t), - sizeof(_DevUartSetModeResponse_t) -}; - -_i16 sl_UartSetMode(const SlUartIfParams_t* pUartParams) -{ - _SlUartSetModeMsg_u Msg; - _u32 magicCode = 0xFFFFFFFF; - - Msg.Cmd.BaudRate = pUartParams->BaudRate; - Msg.Cmd.FlowControlEnable = pUartParams->FlowControlEnable; - - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlUartSetModeCmdCtrl, &Msg, NULL)); - - /* cmd response OK, we can continue with the handshake */ - if (SL_RET_CODE_OK == Msg.Rsp.status) - { - sl_IfMaskIntHdlr(); - - /* Close the comm port */ - sl_IfClose(g_pCB->FD); - - /* Re-open the comm port */ - sl_IfOpen((void * )pUartParams, UART_IF_OPEN_FLAG_RE_OPEN); - - sl_IfUnMaskIntHdlr(); - - /* send the magic code and wait for the response */ - sl_IfWrite(g_pCB->FD, (_u8* )&magicCode, 4); - - magicCode = UART_SET_MODE_MAGIC_CODE; - sl_IfWrite(g_pCB->FD, (_u8* )&magicCode, 4); - - /* clear magic code */ - magicCode = 0; - - /* wait (blocking) till the magic code to be returned from device */ - sl_IfRead(g_pCB->FD, (_u8* )&magicCode, 4); - - /* check for the received magic code matching */ - if (UART_SET_MODE_MAGIC_CODE != magicCode) - { - _SL_ASSERT(0); - } - } - - return (_i16)Msg.Rsp.status; -} -#endif -#endif - - diff --git a/drivers/cc3100/src/driver.c b/drivers/cc3100/src/driver.c deleted file mode 100644 index 817ff0edc6..0000000000 --- a/drivers/cc3100/src/driver.c +++ /dev/null @@ -1,1843 +0,0 @@ -/* -* driver.c - CC31xx/CC32xx Host Driver Implementation -* -* Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ -* -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" -#include "protocol.h" -#include "driver.h" -#include "flowcont.h" - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ - -#define _SL_PENDING_RX_MSG(pDriverCB) (RxIrqCnt != (pDriverCB)->RxDoneCnt) - -/* 2 LSB of the N2H_SYNC_PATTERN are for sequence number -only in SPI interface -support backward sync pattern */ -#define N2H_SYNC_PATTERN_SEQ_NUM_BITS ((_u32)0x00000003) /* Bits 0..1 - use the 2 LBS for seq num */ -#define N2H_SYNC_PATTERN_SEQ_NUM_EXISTS ((_u32)0x00000004) /* Bit 2 - sign that sequence number exists in the sync pattern */ -#define N2H_SYNC_PATTERN_MASK ((_u32)0xFFFFFFF8) /* Bits 3..31 - constant SYNC PATTERN */ -#define N2H_SYNC_SPI_BUGS_MASK ((_u32)0x7FFF7F7F) /* Bits 7,15,31 - ignore the SPI (8,16,32 bites bus) error bits */ -#define BUF_SYNC_SPIM(pBuf) ((*(_u32 *)(pBuf)) & N2H_SYNC_SPI_BUGS_MASK) - -_u8 _SlDrvProtectAsyncRespSetting(_u8 *pAsyncRsp, _u8 ActionID, _u8 SocketID); -#define N2H_SYNC_SPIM (N2H_SYNC_PATTERN & N2H_SYNC_SPI_BUGS_MASK) -#define N2H_SYNC_SPIM_WITH_SEQ(TxSeqNum) ((N2H_SYNC_SPIM & N2H_SYNC_PATTERN_MASK) | N2H_SYNC_PATTERN_SEQ_NUM_EXISTS | ((TxSeqNum) & (N2H_SYNC_PATTERN_SEQ_NUM_BITS))) -#define MATCH_WOUT_SEQ_NUM(pBuf) ( BUF_SYNC_SPIM(pBuf) == N2H_SYNC_SPIM ) -#define MATCH_WITH_SEQ_NUM(pBuf, TxSeqNum) ( BUF_SYNC_SPIM(pBuf) == (N2H_SYNC_SPIM_WITH_SEQ(TxSeqNum)) ) -#define N2H_SYNC_PATTERN_MATCH(pBuf, TxSeqNum) \ - ( \ - ( (*((_u32 *)pBuf) & N2H_SYNC_PATTERN_SEQ_NUM_EXISTS) && ( MATCH_WITH_SEQ_NUM(pBuf, TxSeqNum) ) ) || \ - ( !(*((_u32 *)pBuf) & N2H_SYNC_PATTERN_SEQ_NUM_EXISTS) && ( MATCH_WOUT_SEQ_NUM(pBuf ) ) ) \ - ) - -#define OPCODE(_ptr) (((_SlResponseHeader_t *)(_ptr))->GenHeader.Opcode) -#define RSP_PAYLOAD_LEN(_ptr) (((_SlResponseHeader_t *)(_ptr))->GenHeader.Len - _SL_RESP_SPEC_HDR_SIZE) -#define SD(_ptr) (((_SocketAddrResponse_u *)(_ptr))->IpV4.sd) -/* Actual size of Recv/Recvfrom response data */ -#define ACT_DATA_SIZE(_ptr) (((_SocketAddrResponse_u *)(_ptr))->IpV4.statusOrLen) - - - - -/* General Events handling*/ -#if defined (EXT_LIB_REGISTERED_GENERAL_EVENTS) - -typedef _SlEventPropogationStatus_e (*general_callback) (SlDeviceEvent_t *); - -static const general_callback general_callbacks[] = -{ -#ifdef SlExtLib1GeneralEventHandler - SlExtLib1GeneralEventHandler, -#endif - -#ifdef SlExtLib2GeneralEventHandler - SlExtLib2GeneralEventHandler, -#endif - -#ifdef SlExtLib3GeneralEventHandler - SlExtLib3GeneralEventHandler, -#endif - -#ifdef SlExtLib4GeneralEventHandler - SlExtLib4GeneralEventHandler, -#endif - -#ifdef SlExtLib5GeneralEventHandler - SlExtLib5GeneralEventHandler, -#endif -}; - -#undef _SlDrvHandleGeneralEvents - -/******************************************************************** - _SlDrvHandleGeneralEvents - Iterates through all the general(device) event handlers which are - registered by the external libs/user application. -*********************************************************************/ -void _SlDrvHandleGeneralEvents(SlDeviceEvent_t *slGeneralEvent) -{ - _u8 i; - - /* Iterate over all the extenal libs handlers */ - for ( i = 0 ; i < sizeof(general_callbacks)/sizeof(general_callbacks[0]) ; i++ ) - { - if (EVENT_PROPAGATION_BLOCK == general_callbacks[i](slGeneralEvent) ) - { - /* exit immediately and do not call the user specific handler as well */ - return; - } - } - -/* At last call the Application specific handler if registered */ -#ifdef sl_GeneralEvtHdlr - sl_GeneralEvtHdlr(slGeneralEvent); -#endif - -} -#endif - - - -/* WLAN Events handling*/ - -#if defined (EXT_LIB_REGISTERED_WLAN_EVENTS) - -typedef _SlEventPropogationStatus_e (*wlan_callback) (SlWlanEvent_t *); - -static wlan_callback wlan_callbacks[] = -{ -#ifdef SlExtLib1WlanEventHandler - SlExtLib1WlanEventHandler, -#endif - -#ifdef SlExtLib2WlanEventHandler - SlExtLib2WlanEventHandler, -#endif - -#ifdef SlExtLib3WlanEventHandler - SlExtLib3WlanEventHandler, -#endif - -#ifdef SlExtLib4WlanEventHandler - SlExtLib4WlanEventHandler, -#endif - -#ifdef SlExtLib5WlanEventHandler - SlExtLib5WlanEventHandler, -#endif -}; - -#undef _SlDrvHandleWlanEvents - -/*********************************************************** - _SlDrvHandleWlanEvents - Iterates through all the wlan event handlers which are - registered by the external libs/user application. -************************************************************/ -void _SlDrvHandleWlanEvents(SlWlanEvent_t *slWlanEvent) -{ - _u8 i; - - /* Iterate over all the extenal libs handlers */ - for ( i = 0 ; i < sizeof(wlan_callbacks)/sizeof(wlan_callbacks[0]) ; i++ ) - { - if ( EVENT_PROPAGATION_BLOCK == wlan_callbacks[i](slWlanEvent) ) - { - /* exit immediately and do not call the user specific handler as well */ - return; - } - } - -/* At last call the Application specific handler if registered */ -#ifdef sl_WlanEvtHdlr - sl_WlanEvtHdlr(slWlanEvent); -#endif - -} -#endif - - -/* NetApp Events handling */ -#if defined (EXT_LIB_REGISTERED_NETAPP_EVENTS) - -typedef _SlEventPropogationStatus_e (*netApp_callback) (SlNetAppEvent_t *); - -static const netApp_callback netApp_callbacks[] = -{ -#ifdef SlExtLib1NetAppEventHandler - SlExtLib1NetAppEventHandler, -#endif - -#ifdef SlExtLib2NetAppEventHandler - SlExtLib2NetAppEventHandler, -#endif - -#ifdef SlExtLib3NetAppEventHandler - SlExtLib3NetAppEventHandler, -#endif - -#ifdef SlExtLib4NetAppEventHandler - SlExtLib4NetAppEventHandler, -#endif - -#ifdef SlExtLib5NetAppEventHandler - SlExtLib5NetAppEventHandler, -#endif -}; - -#undef _SlDrvHandleNetAppEvents - -/************************************************************ - _SlDrvHandleNetAppEvents - Iterates through all the net app event handlers which are - registered by the external libs/user application. -************************************************************/ -void _SlDrvHandleNetAppEvents(SlNetAppEvent_t *slNetAppEvent) -{ - _u8 i; - - /* Iterate over all the extenal libs handlers */ - for ( i = 0 ; i < sizeof(netApp_callbacks)/sizeof(netApp_callbacks[0]) ; i++ ) - { - if (EVENT_PROPAGATION_BLOCK == netApp_callbacks[i](slNetAppEvent) ) - { - /* exit immediately and do not call the user specific handler as well */ - return; - } - } - -/* At last call the Application specific handler if registered */ -#ifdef sl_NetAppEvtHdlr - sl_NetAppEvtHdlr(slNetAppEvent); -#endif - -} -#endif - - -/* Http Server Events handling */ -#if defined (EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS) - -typedef _SlEventPropogationStatus_e (*httpServer_callback) (SlHttpServerEvent_t*, SlHttpServerResponse_t*); - -static const httpServer_callback httpServer_callbacks[] = -{ -#ifdef SlExtLib1HttpServerEventHandler - SlExtLib1HttpServerEventHandler, -#endif - -#ifdef SlExtLib2HttpServerEventHandler - SlExtLib2HttpServerEventHandler, -#endif - -#ifdef SlExtLib3HttpServerEventHandler - SlExtLib3HttpServerEventHandler, -#endif - -#ifdef SlExtLib4HttpServerEventHandler - SlExtLib4HttpServerEventHandler, -#endif - -#ifdef SlExtLib5HttpServerEventHandler - SlExtLib5HttpServerEventHandler, -#endif -}; - -#undef _SlDrvHandleHttpServerEvents - -/******************************************************************* - _SlDrvHandleHttpServerEvents - Iterates through all the http server event handlers which are - registered by the external libs/user application. -********************************************************************/ -void _SlDrvHandleHttpServerEvents(SlHttpServerEvent_t *slHttpServerEvent, SlHttpServerResponse_t *slHttpServerResponse) -{ - _u8 i; - - /* Iterate over all the external libs handlers */ - for ( i = 0 ; i < sizeof(httpServer_callbacks)/sizeof(httpServer_callbacks[0]) ; i++ ) - { - if ( EVENT_PROPAGATION_BLOCK == httpServer_callbacks[i](slHttpServerEvent, slHttpServerResponse) ) - { - /* exit immediately and do not call the user specific handler as well */ - return; - } - } - -/* At last call the Application specific handler if registered */ -#ifdef sl_HttpServerCallback - sl_HttpServerCallback(slHttpServerEvent, slHttpServerResponse); -#endif - -} -#endif - - -/* Socket Events */ -#if defined (EXT_LIB_REGISTERED_SOCK_EVENTS) - -typedef _SlEventPropogationStatus_e (*sock_callback) (SlSockEvent_t *); - -static const sock_callback sock_callbacks[] = -{ -#ifdef SlExtLib1SockEventHandler - SlExtLib1SockEventHandler, -#endif - -#ifdef SlExtLib2SockEventHandler - SlExtLib2SockEventHandler, -#endif - -#ifdef SlExtLib3SockEventHandler - SlExtLib3SockEventHandler, -#endif - -#ifdef SlExtLib4SockEventHandler - SlExtLib4SockEventHandler, -#endif - -#ifdef SlExtLib5SockEventHandler - SlExtLib5SockEventHandler, -#endif -}; - -/************************************************************* - _SlDrvHandleSockEvents - Iterates through all the socket event handlers which are - registered by the external libs/user application. -**************************************************************/ -void _SlDrvHandleSockEvents(SlSockEvent_t *slSockEvent) -{ - _u8 i; - - /* Iterate over all the external libs handlers */ - for ( i = 0 ; i < sizeof(sock_callbacks)/sizeof(sock_callbacks[0]) ; i++ ) - { - if ( EVENT_PROPAGATION_BLOCK == sock_callbacks[i](slSockEvent) ) - { - /* exit immediately and do not call the user specific handler as well */ - return; - } - } - -/* At last call the Application specific handler if registered */ -#ifdef sl_SockEvtHdlr - sl_SockEvtHdlr(slSockEvent); -#endif - -} - -#endif - - -#if (SL_MEMORY_MGMT != SL_MEMORY_MGMT_DYNAMIC) -typedef struct -{ - _u32 Align; - _SlDriverCb_t DriverCB; - _u8 AsyncRespBuf[SL_ASYNC_MAX_MSG_LEN]; -}_SlStatMem_t; - -_SlStatMem_t g_StatMem; -#endif - -_u8 _SlDrvProtectAsyncRespSetting(_u8 *pAsyncRsp, _u8 ActionID, _u8 SocketID) -{ - _u8 ObjIdx; - - - /* Use Obj to issue the command, if not available try later */ - ObjIdx = _SlDrvWaitForPoolObj(ActionID, SocketID); - - if (MAX_CONCURRENT_ACTIONS != ObjIdx) - { - _SlDrvProtectionObjLockWaitForever(); - g_pCB->ObjPool[ObjIdx].pRespArgs = pAsyncRsp; - _SlDrvProtectionObjUnLock(); - } - - return ObjIdx; -} - - -/*****************************************************************************/ -/* Variables */ -/*****************************************************************************/ -const _SlSyncPattern_t g_H2NSyncPattern = H2N_SYNC_PATTERN; -const _SlSyncPattern_t g_H2NCnysPattern = H2N_CNYS_PATTERN; -_volatile _u8 RxIrqCnt; - -#ifndef SL_TINY_EXT -const _SlActionLookup_t _SlActionLookupTable[] = -{ - {ACCEPT_ID, SL_OPCODE_SOCKET_ACCEPTASYNCRESPONSE, (_SlSpawnEntryFunc_t)_sl_HandleAsync_Accept}, - {CONNECT_ID, SL_OPCODE_SOCKET_CONNECTASYNCRESPONSE,(_SlSpawnEntryFunc_t)_sl_HandleAsync_Connect}, - {SELECT_ID, SL_OPCODE_SOCKET_SELECTASYNCRESPONSE,(_SlSpawnEntryFunc_t)_sl_HandleAsync_Select}, - {GETHOSYBYNAME_ID, SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE,(_SlSpawnEntryFunc_t)_sl_HandleAsync_DnsGetHostByName}, - {GETHOSYBYSERVICE_ID, SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICEASYNCRESPONSE,(_SlSpawnEntryFunc_t)_sl_HandleAsync_DnsGetHostByService}, - {PING_ID, SL_OPCODE_NETAPP_PINGREPORTREQUESTRESPONSE, (_SlSpawnEntryFunc_t)_sl_HandleAsync_PingResponse}, - {START_STOP_ID, SL_OPCODE_DEVICE_STOP_ASYNC_RESPONSE,(_SlSpawnEntryFunc_t)_sl_HandleAsync_Stop} -}; -#else -const _SlActionLookup_t _SlActionLookupTable[] = -{ - {CONNECT_ID, SL_OPCODE_SOCKET_CONNECTASYNCRESPONSE,(_SlSpawnEntryFunc_t)_sl_HandleAsync_Connect}, - {GETHOSYBYNAME_ID, SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE,(_SlSpawnEntryFunc_t)_sl_HandleAsync_DnsGetHostByName}, - {START_STOP_ID, SL_OPCODE_DEVICE_STOP_ASYNC_RESPONSE,(_SlSpawnEntryFunc_t)_sl_HandleAsync_Stop} -}; -#endif - - - -typedef struct -{ - _u16 opcode; - _u8 event; -} OpcodeKeyVal_t; - -/* The table translates opcode to user's event type */ -const OpcodeKeyVal_t OpcodeTranslateTable[] = -{ -{SL_OPCODE_WLAN_SMART_CONFIG_START_ASYNC_RESPONSE, SL_WLAN_SMART_CONFIG_COMPLETE_EVENT}, -{SL_OPCODE_WLAN_SMART_CONFIG_STOP_ASYNC_RESPONSE,SL_WLAN_SMART_CONFIG_STOP_EVENT}, -{SL_OPCODE_WLAN_STA_CONNECTED, SL_WLAN_STA_CONNECTED_EVENT}, -{SL_OPCODE_WLAN_STA_DISCONNECTED,SL_WLAN_STA_DISCONNECTED_EVENT}, -{SL_OPCODE_WLAN_P2P_DEV_FOUND,SL_WLAN_P2P_DEV_FOUND_EVENT}, -{SL_OPCODE_WLAN_P2P_NEG_REQ_RECEIVED, SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT}, -{SL_OPCODE_WLAN_CONNECTION_FAILED, SL_WLAN_CONNECTION_FAILED_EVENT}, -{SL_OPCODE_WLAN_WLANASYNCCONNECTEDRESPONSE, SL_WLAN_CONNECT_EVENT}, -{SL_OPCODE_WLAN_WLANASYNCDISCONNECTEDRESPONSE, SL_WLAN_DISCONNECT_EVENT}, -{SL_OPCODE_NETAPP_IPACQUIRED, SL_NETAPP_IPV4_IPACQUIRED_EVENT}, -{SL_OPCODE_NETAPP_IPACQUIRED_V6, SL_NETAPP_IPV6_IPACQUIRED_EVENT}, -{SL_OPCODE_NETAPP_IP_LEASED, SL_NETAPP_IP_LEASED_EVENT}, -{SL_OPCODE_NETAPP_IP_RELEASED, SL_NETAPP_IP_RELEASED_EVENT}, -{SL_OPCODE_SOCKET_TXFAILEDASYNCRESPONSE, SL_SOCKET_TX_FAILED_EVENT}, -{SL_OPCODE_SOCKET_SOCKETASYNCEVENT, SL_SOCKET_ASYNC_EVENT} -}; - - - -_SlDriverCb_t* g_pCB = NULL; -P_SL_DEV_PING_CALLBACK pPingCallBackFunc = NULL; -_u8 gFirstCmdMode = 0; - -/*****************************************************************************/ -/* Function prototypes */ -/*****************************************************************************/ -_SlReturnVal_t _SlDrvMsgRead(void); -_SlReturnVal_t _SlDrvMsgWrite(_SlCmdCtrl_t *pCmdCtrl,_SlCmdExt_t *pCmdExt, _u8 *pTxRxDescBuff); -_SlReturnVal_t _SlDrvMsgReadCmdCtx(void); -_SlReturnVal_t _SlDrvMsgReadSpawnCtx(void *pValue); -void _SlDrvClassifyRxMsg(_SlOpcode_t Opcode ); -_SlReturnVal_t _SlDrvRxHdrRead(_u8 *pBuf, _u8 *pAlignSize); -void _SlDrvShiftDWord(_u8 *pBuf); -void _SlDrvDriverCBInit(void); -void _SlAsyncEventGenericHandler(void); -_u8 _SlDrvWaitForPoolObj(_u8 ActionID, _u8 SocketID); -void _SlDrvReleasePoolObj(_u8 pObj); -void _SlRemoveFromList(_u8* ListIndex, _u8 ItemIndex); -_SlReturnVal_t _SlFindAndSetActiveObj(_SlOpcode_t Opcode, _u8 Sd); - - -/*****************************************************************************/ -/* Internal functions */ -/*****************************************************************************/ - - -/***************************************************************************** -_SlDrvDriverCBInit - init Driver Control Block -*****************************************************************************/ - -void _SlDrvDriverCBInit(void) -{ - _u8 Idx =0; - -#if (SL_MEMORY_MGMT == SL_MEMORY_MGMT_DYNAMIC) - g_pCB = sl_Malloc(sizeof(_SlDriverCb_t)); -#else - g_pCB = &(g_StatMem.DriverCB); -#endif - MALLOC_OK_CHECK(g_pCB); - - - _SlDrvMemZero(g_pCB, sizeof(_SlDriverCb_t)); - RxIrqCnt = 0; - OSI_RET_OK_CHECK( sl_SyncObjCreate(&g_pCB->CmdSyncObj, "CmdSyncObj") ); - sl_SyncObjClear(&g_pCB->CmdSyncObj); - - OSI_RET_OK_CHECK( sl_LockObjCreate(&g_pCB->GlobalLockObj, "GlobalLockObj") ); - OSI_RET_OK_CHECK( sl_LockObjCreate(&g_pCB->ProtectionLockObj, "ProtectionLockObj") ); - - /* Init Drv object */ - _SlDrvMemZero(&g_pCB->ObjPool[0], MAX_CONCURRENT_ACTIONS*sizeof(_SlPoolObj_t)); - - /* place all Obj in the free list*/ - g_pCB->FreePoolIdx = 0; - - for (Idx = 0 ; Idx < MAX_CONCURRENT_ACTIONS ; Idx++) - { - g_pCB->ObjPool[Idx].NextIndex = Idx + 1; - g_pCB->ObjPool[Idx].AdditionalData = SL_MAX_SOCKETS; - - OSI_RET_OK_CHECK( sl_SyncObjCreate(&g_pCB->ObjPool[Idx].SyncObj, "SyncObj")); - sl_SyncObjClear(&g_pCB->ObjPool[Idx].SyncObj); - } - - g_pCB->ActivePoolIdx = MAX_CONCURRENT_ACTIONS; - g_pCB->PendingPoolIdx = MAX_CONCURRENT_ACTIONS; - - /* Flow control init */ - g_pCB->FlowContCB.TxPoolCnt = FLOW_CONT_MIN; - OSI_RET_OK_CHECK(sl_LockObjCreate(&g_pCB->FlowContCB.TxLockObj, "TxLockObj")); - OSI_RET_OK_CHECK(sl_SyncObjCreate(&g_pCB->FlowContCB.TxSyncObj, "TxSyncObj")); - - gFirstCmdMode = 0; - -} - -/***************************************************************************** -_SlDrvDriverCBDeinit - De init Driver Control Block -*****************************************************************************/ -void _SlDrvDriverCBDeinit() -{ - _u8 Idx =0; - - /* Flow control de-init */ - g_pCB->FlowContCB.TxPoolCnt = 0; - OSI_RET_OK_CHECK(sl_LockObjDelete(&g_pCB->FlowContCB.TxLockObj)); - OSI_RET_OK_CHECK(sl_SyncObjDelete(&g_pCB->FlowContCB.TxSyncObj)); - - OSI_RET_OK_CHECK( sl_SyncObjDelete(&g_pCB->CmdSyncObj) ); - OSI_RET_OK_CHECK( sl_LockObjDelete(&g_pCB->GlobalLockObj) ); - OSI_RET_OK_CHECK( sl_LockObjDelete(&g_pCB->ProtectionLockObj) ); - - #ifndef SL_TINY_EXT - for (Idx = 0; Idx < MAX_CONCURRENT_ACTIONS; Idx++) - #endif - { - OSI_RET_OK_CHECK( sl_SyncObjDelete(&g_pCB->ObjPool[Idx].SyncObj) ); - } - - g_pCB->FreePoolIdx = 0; - g_pCB->PendingPoolIdx = MAX_CONCURRENT_ACTIONS; - g_pCB->ActivePoolIdx = MAX_CONCURRENT_ACTIONS; - -#if (SL_MEMORY_MGMT == SL_MEMORY_MGMT_DYNAMIC) - sl_Free(g_pCB); -#else - g_pCB = NULL; -#endif - - - g_pCB = NULL; -} - -/***************************************************************************** -_SlDrvRxIrqHandler - Interrupt handler -*****************************************************************************/ -void _SlDrvRxIrqHandler(void *pValue) -{ - sl_IfMaskIntHdlr(); - - RxIrqCnt++; - - if (TRUE == g_pCB->IsCmdRespWaited) - { - OSI_RET_OK_CHECK( sl_SyncObjSignalFromIRQ(&g_pCB->CmdSyncObj) ); - } - else - { - sl_Spawn((_SlSpawnEntryFunc_t)_SlDrvMsgReadSpawnCtx, NULL, 0); - } -} - -/***************************************************************************** -_SlDrvCmdOp -*****************************************************************************/ -_SlReturnVal_t _SlDrvCmdOp( - _SlCmdCtrl_t *pCmdCtrl , - void *pTxRxDescBuff , - _SlCmdExt_t *pCmdExt) -{ - _SlReturnVal_t RetVal; - - - _SlDrvObjLockWaitForever(&g_pCB->GlobalLockObj); - - g_pCB->IsCmdRespWaited = TRUE; - - SL_TRACE0(DBG_MSG, MSG_312, "_SlDrvCmdOp: call _SlDrvMsgWrite"); - - - /* send the message */ - RetVal = _SlDrvMsgWrite(pCmdCtrl, pCmdExt, pTxRxDescBuff); - - if(SL_OS_RET_CODE_OK == RetVal) - { - -#ifndef SL_IF_TYPE_UART - /* Waiting for SPI to stabilize after first command */ - if( 0 == gFirstCmdMode ) - { - volatile _u32 CountVal = 0; - gFirstCmdMode = 1; - CountVal = CPU_FREQ_IN_MHZ*USEC_DELAY; - while( CountVal-- ); - } -#endif - /* wait for respond */ - RetVal = _SlDrvMsgReadCmdCtx(); /* will free global lock */ - SL_TRACE0(DBG_MSG, MSG_314, "_SlDrvCmdOp: exited _SlDrvMsgReadCmdCtx"); - } - else - { - _SlDrvObjUnLock(&g_pCB->GlobalLockObj); - } - - return RetVal; -} - - - -/***************************************************************************** -_SlDrvDataReadOp -*****************************************************************************/ -_SlReturnVal_t _SlDrvDataReadOp( - _SlSd_t Sd, - _SlCmdCtrl_t *pCmdCtrl , - void *pTxRxDescBuff , - _SlCmdExt_t *pCmdExt) -{ - _SlReturnVal_t RetVal; - _u8 ObjIdx = MAX_CONCURRENT_ACTIONS; - _SlArgsData_t pArgsData; - - /* Validate input arguments */ - VERIFY_PROTOCOL(NULL != pCmdExt->pRxPayload); - - /* If zero bytes is requested, return error. */ - /* This allows us not to fill remote socket's IP address in return arguments */ - VERIFY_PROTOCOL(0 != pCmdExt->RxPayloadLen); - - /* Validate socket */ - if((Sd & BSD_SOCKET_ID_MASK) >= SL_MAX_SOCKETS) - { - return SL_EBADF; - } - - /*Use Obj to issue the command, if not available try later*/ - ObjIdx = (_u8)_SlDrvWaitForPoolObj(RECV_ID, Sd & BSD_SOCKET_ID_MASK); - - if (MAX_CONCURRENT_ACTIONS == ObjIdx) - { - return SL_POOL_IS_EMPTY; - } - - _SlDrvProtectionObjLockWaitForever(); - - pArgsData.pData = pCmdExt->pRxPayload; - pArgsData.pArgs = (_u8 *)pTxRxDescBuff; - g_pCB->ObjPool[ObjIdx].pRespArgs = (_u8 *)&pArgsData; - - _SlDrvProtectionObjUnLock(); - - - /* Do Flow Control check/update for DataWrite operation */ - _SlDrvObjLockWaitForever(&g_pCB->FlowContCB.TxLockObj); - - - /* Clear SyncObj for the case it was signalled before TxPoolCnt */ - /* dropped below '1' (last Data buffer was taken) */ - /* OSI_RET_OK_CHECK( sl_SyncObjClear(&g_pCB->FlowContCB.TxSyncObj) ); */ - sl_SyncObjClear(&g_pCB->FlowContCB.TxSyncObj); - - if(g_pCB->FlowContCB.TxPoolCnt <= FLOW_CONT_MIN) - { - - /* If TxPoolCnt was increased by other thread at this moment, - TxSyncObj won't wait here */ - _SlDrvSyncObjWaitForever(&g_pCB->FlowContCB.TxSyncObj); - - } - - _SlDrvObjLockWaitForever(&g_pCB->GlobalLockObj); - - - VERIFY_PROTOCOL(g_pCB->FlowContCB.TxPoolCnt > FLOW_CONT_MIN); - g_pCB->FlowContCB.TxPoolCnt--; - - _SlDrvObjUnLock(&g_pCB->FlowContCB.TxLockObj); - - /* send the message */ - RetVal = _SlDrvMsgWrite(pCmdCtrl, pCmdExt, (_u8 *)pTxRxDescBuff); - - _SlDrvObjUnLock(&g_pCB->GlobalLockObj); - - - if(SL_OS_RET_CODE_OK == RetVal) - { - /* Wait for response message. Will be signaled by _SlDrvMsgRead. */ - _SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj); - } - - _SlDrvReleasePoolObj(ObjIdx); - return RetVal; -} - -/* ******************************************************************************/ -/* _SlDrvDataWriteOp */ -/* ******************************************************************************/ -_SlReturnVal_t _SlDrvDataWriteOp( - _SlSd_t Sd, - _SlCmdCtrl_t *pCmdCtrl , - void *pTxRxDescBuff , - _SlCmdExt_t *pCmdExt) -{ - _SlReturnVal_t RetVal = SL_EAGAIN; /* initiated as SL_EAGAIN for the non blocking mode */ - while( 1 ) - { - /* Do Flow Control check/update for DataWrite operation */ - _SlDrvObjLockWaitForever(&g_pCB->FlowContCB.TxLockObj); - - /* Clear SyncObj for the case it was signalled before TxPoolCnt */ - /* dropped below '1' (last Data buffer was taken) */ - /* OSI_RET_OK_CHECK( sl_SyncObjClear(&g_pCB->FlowContCB.TxSyncObj) ); */ - sl_SyncObjClear(&g_pCB->FlowContCB.TxSyncObj); - - /* we have indication that the last send has failed - socket is no longer valid for operations */ - if(g_pCB->SocketTXFailure & (1<<(Sd & BSD_SOCKET_ID_MASK))) - { - _SlDrvObjUnLock(&g_pCB->FlowContCB.TxLockObj); - return SL_SOC_ERROR; - } - if(g_pCB->FlowContCB.TxPoolCnt <= FLOW_CONT_MIN + 1) - { - /* we have indication that this socket is set as blocking and we try to */ - /* unblock it - return an error */ - if( g_pCB->SocketNonBlocking & (1<< (Sd & BSD_SOCKET_ID_MASK))) - { - _SlDrvObjUnLock(&g_pCB->FlowContCB.TxLockObj); - return RetVal; - } - /* If TxPoolCnt was increased by other thread at this moment, */ - /* TxSyncObj won't wait here */ - _SlDrvSyncObjWaitForever(&g_pCB->FlowContCB.TxSyncObj); - } - if(g_pCB->FlowContCB.TxPoolCnt > FLOW_CONT_MIN + 1 ) - { - break; - } - else - { - _SlDrvObjUnLock(&g_pCB->FlowContCB.TxLockObj); - } - } - - _SlDrvObjLockWaitForever(&g_pCB->GlobalLockObj); - - - VERIFY_PROTOCOL(g_pCB->FlowContCB.TxPoolCnt > FLOW_CONT_MIN + 1 ); - g_pCB->FlowContCB.TxPoolCnt--; - - _SlDrvObjUnLock(&g_pCB->FlowContCB.TxLockObj); - - /* send the message */ - RetVal = _SlDrvMsgWrite(pCmdCtrl, pCmdExt, pTxRxDescBuff); - - _SlDrvObjUnLock(&g_pCB->GlobalLockObj); - - return RetVal; -} - -/* ******************************************************************************/ -/* _SlDrvMsgWrite */ -/* ******************************************************************************/ -_SlReturnVal_t _SlDrvMsgWrite(_SlCmdCtrl_t *pCmdCtrl,_SlCmdExt_t *pCmdExt, _u8 *pTxRxDescBuff) -{ - _u8 sendRxPayload = FALSE; - VERIFY_PROTOCOL(NULL != pCmdCtrl); - - g_pCB->FunctionParams.pCmdCtrl = pCmdCtrl; - g_pCB->FunctionParams.pTxRxDescBuff = pTxRxDescBuff; - g_pCB->FunctionParams.pCmdExt = pCmdExt; - - g_pCB->TempProtocolHeader.Opcode = pCmdCtrl->Opcode; - g_pCB->TempProtocolHeader.Len = _SL_PROTOCOL_CALC_LEN(pCmdCtrl, pCmdExt); - - if (pCmdExt && pCmdExt->RxPayloadLen < 0 && pCmdExt->TxPayloadLen) - { - pCmdExt->RxPayloadLen = pCmdExt->RxPayloadLen * (-1); /* change sign */ - sendRxPayload = TRUE; - g_pCB->TempProtocolHeader.Len = g_pCB->TempProtocolHeader.Len + pCmdExt->RxPayloadLen; - } - -#ifdef SL_START_WRITE_STAT - sl_IfStartWriteSequence(g_pCB->FD); -#endif - -#ifdef SL_IF_TYPE_UART - /* Write long sync pattern */ - NWP_IF_WRITE_CHECK(g_pCB->FD, (_u8 *)&g_H2NSyncPattern.Long, 2*SYNC_PATTERN_LEN); -#else - /* Write short sync pattern */ - NWP_IF_WRITE_CHECK(g_pCB->FD, (_u8 *)&g_H2NSyncPattern.Short, SYNC_PATTERN_LEN); -#endif - - /* Header */ - NWP_IF_WRITE_CHECK(g_pCB->FD, (_u8 *)&g_pCB->TempProtocolHeader, _SL_CMD_HDR_SIZE); - - /* Descriptors */ - if (pTxRxDescBuff && pCmdCtrl->TxDescLen > 0) - { - NWP_IF_WRITE_CHECK(g_pCB->FD, pTxRxDescBuff, - _SL_PROTOCOL_ALIGN_SIZE(pCmdCtrl->TxDescLen)); - } - - /* A special mode where Rx payload and Rx length are used as Tx as well */ - /* This mode requires no Rx payload on the response and currently used by fs_Close and sl_Send on */ - /* transceiver mode */ - if (sendRxPayload == TRUE ) - { - NWP_IF_WRITE_CHECK(g_pCB->FD, pCmdExt->pRxPayload, - _SL_PROTOCOL_ALIGN_SIZE(pCmdExt->RxPayloadLen)); - } - - /* Payload */ - if (pCmdExt && pCmdExt->TxPayloadLen > 0) - { - /* If the message has payload, it is mandatory that the message's arguments are protocol aligned. */ - /* Otherwise the aligning of arguments will create a gap between arguments and payload. */ - VERIFY_PROTOCOL(_SL_IS_PROTOCOL_ALIGNED_SIZE(pCmdCtrl->TxDescLen)); - - NWP_IF_WRITE_CHECK(g_pCB->FD, pCmdExt->pTxPayload, - _SL_PROTOCOL_ALIGN_SIZE(pCmdExt->TxPayloadLen)); - } - - - _SL_DBG_CNT_INC(MsgCnt.Write); - -#ifdef SL_START_WRITE_STAT - sl_IfEndWriteSequence(g_pCB->FD); -#endif - - return SL_OS_RET_CODE_OK; -} - -/* ******************************************************************************/ -/* _SlDrvMsgRead */ -/* ******************************************************************************/ -_SlReturnVal_t _SlDrvMsgRead(void) -{ - /* alignment for small memory models */ - union - { - _u8 TempBuf[_SL_RESP_HDR_SIZE]; - _u32 DummyBuf[2]; - } uBuf; - _u8 TailBuffer[4]; - _u16 LengthToCopy; - _u16 AlignedLengthRecv; - _u8 AlignSize; - _u8 *pAsyncBuf = NULL; - _u16 OpCode; - _u16 RespPayloadLen; - _u8 sd = SL_MAX_SOCKETS; - _SlRxMsgClass_e RxMsgClass; - - - /* save params in global CB */ - g_pCB->FunctionParams.AsyncExt.pAsyncBuf = NULL; - g_pCB->FunctionParams.AsyncExt.AsyncEvtHandler= NULL; - - - VERIFY_RET_OK(_SlDrvRxHdrRead((_u8*)(uBuf.TempBuf), &AlignSize)); - - OpCode = OPCODE(uBuf.TempBuf); - RespPayloadLen = RSP_PAYLOAD_LEN(uBuf.TempBuf); - - - /* 'Init Compelete' message bears no valid FlowControl info */ - if(SL_OPCODE_DEVICE_INITCOMPLETE != OpCode) - { - g_pCB->FlowContCB.TxPoolCnt = ((_SlResponseHeader_t *)uBuf.TempBuf)->TxPoolCnt; - g_pCB->SocketNonBlocking = ((_SlResponseHeader_t *)uBuf.TempBuf)->SocketNonBlocking; - g_pCB->SocketTXFailure = ((_SlResponseHeader_t *)uBuf.TempBuf)->SocketTXFailure; - - if(g_pCB->FlowContCB.TxPoolCnt > FLOW_CONT_MIN) - { - _SlDrvSyncObjSignal(&g_pCB->FlowContCB.TxSyncObj); - } - } - - /* Find the RX messaage class and set its async event handler */ - _SlDrvClassifyRxMsg(OpCode); - - RxMsgClass = g_pCB->FunctionParams.AsyncExt.RxMsgClass; - - - switch(RxMsgClass) - { - case ASYNC_EVT_CLASS: - - VERIFY_PROTOCOL(NULL == pAsyncBuf); - -#if (SL_MEMORY_MGMT == SL_MEMORY_MGMT_DYNAMIC) - g_pCB->FunctionParams.AsyncExt.pAsyncBuf = sl_Malloc(SL_ASYNC_MAX_MSG_LEN); -#else - g_pCB->FunctionParams.AsyncExt.pAsyncBuf = g_StatMem.AsyncRespBuf; -#endif - /* set the local pointer to the allocated one */ - pAsyncBuf = g_pCB->FunctionParams.AsyncExt.pAsyncBuf; - - /* clear the async buffer */ - _SlDrvMemZero(pAsyncBuf, SL_ASYNC_MAX_MSG_LEN); - - MALLOC_OK_CHECK(pAsyncBuf); - - sl_Memcpy(pAsyncBuf, uBuf.TempBuf, _SL_RESP_HDR_SIZE); - if (_SL_PROTOCOL_ALIGN_SIZE(RespPayloadLen) <= SL_ASYNC_MAX_PAYLOAD_LEN) - { - AlignedLengthRecv = _SL_PROTOCOL_ALIGN_SIZE(RespPayloadLen); - } - else - { - AlignedLengthRecv = _SL_PROTOCOL_ALIGN_SIZE(SL_ASYNC_MAX_PAYLOAD_LEN); - } - if (RespPayloadLen > 0) - { - NWP_IF_READ_CHECK(g_pCB->FD, - pAsyncBuf + _SL_RESP_HDR_SIZE, - AlignedLengthRecv); - } - /* In case ASYNC RX buffer length is smaller then the received data length, dump the rest */ - if ((_SL_PROTOCOL_ALIGN_SIZE(RespPayloadLen) > SL_ASYNC_MAX_PAYLOAD_LEN)) - { - AlignedLengthRecv = _SL_PROTOCOL_ALIGN_SIZE(RespPayloadLen) - SL_ASYNC_MAX_PAYLOAD_LEN; - while (AlignedLengthRecv > 0) - { - NWP_IF_READ_CHECK(g_pCB->FD,TailBuffer,4); - AlignedLengthRecv = AlignedLengthRecv - 4; - } - } - - _SlDrvProtectionObjLockWaitForever(); - - if ( -#ifndef SL_TINY_EXT - (SL_OPCODE_SOCKET_ACCEPTASYNCRESPONSE == OpCode) || - (SL_OPCODE_SOCKET_ACCEPTASYNCRESPONSE_V6 == OpCode) || -#endif - (SL_OPCODE_SOCKET_CONNECTASYNCRESPONSE == OpCode) - ) - { - /* go over the active list if exist to find obj waiting for this Async event */ - sd = ((((_SocketResponse_t *)(pAsyncBuf + _SL_RESP_HDR_SIZE))->sd) & BSD_SOCKET_ID_MASK); - } - _SlFindAndSetActiveObj(OpCode, sd); - - _SlDrvProtectionObjUnLock(); - - break; - case RECV_RESP_CLASS: - { - _u8 ExpArgSize; /* Expected size of Recv/Recvfrom arguments */ - - switch(OpCode) - { - case SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE: - ExpArgSize = RECVFROM_IPV4_ARGS_SIZE; - break; -#ifndef SL_TINY_EXT - case SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE_V6: - ExpArgSize = RECVFROM_IPV6_ARGS_SIZE; - break; -#endif - default: - /* SL_OPCODE_SOCKET_RECVASYNCRESPONSE: */ - ExpArgSize = RECV_ARGS_SIZE; - } - - /* Read first 4 bytes of Recv/Recvfrom response to get SocketId and actual */ - /* response data length */ - NWP_IF_READ_CHECK(g_pCB->FD, &uBuf.TempBuf[4], RECV_ARGS_SIZE); - - /* Validate Socket ID and Received Length value. */ - VERIFY_PROTOCOL((SD(&uBuf.TempBuf[4])& BSD_SOCKET_ID_MASK) < SL_MAX_SOCKETS); - - _SlDrvProtectionObjLockWaitForever(); - - /* go over the active list if exist to find obj waiting for this Async event */ - VERIFY_RET_OK(_SlFindAndSetActiveObj(OpCode,SD(&uBuf.TempBuf[4]) & BSD_SOCKET_ID_MASK)); - - /* Verify data is waited on this socket. The pArgs should have been set by _SlDrvDataReadOp(). */ - VERIFY_SOCKET_CB(NULL != ((_SlArgsData_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pData))->pArgs); - - sl_Memcpy( ((_SlArgsData_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->pArgs, &uBuf.TempBuf[4], RECV_ARGS_SIZE); - - if(ExpArgSize > RECV_ARGS_SIZE) - { - NWP_IF_READ_CHECK(g_pCB->FD, - ((_SlArgsData_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->pArgs + RECV_ARGS_SIZE, - ExpArgSize - RECV_ARGS_SIZE); - } - - /* Here g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pData contains requested(expected) Recv/Recvfrom DataSize. */ - /* Overwrite requested DataSize with actual one. */ - /* If error is received, this information will be read from arguments. */ - if(ACT_DATA_SIZE(&uBuf.TempBuf[4]) > 0) - { - VERIFY_SOCKET_CB(NULL != ((_SlArgsData_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->pData); - - /* Read 4 bytes aligned from interface */ - /* therefore check the requested length and read only */ - /* 4 bytes aligned data. The rest unaligned (if any) will be read */ - /* and copied to a TailBuffer */ - LengthToCopy = ACT_DATA_SIZE(&uBuf.TempBuf[4]) & (3); - AlignedLengthRecv = ACT_DATA_SIZE(&uBuf.TempBuf[4]) & (~3); - if( AlignedLengthRecv >= 4) - { - NWP_IF_READ_CHECK(g_pCB->FD,((_SlArgsData_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->pData,AlignedLengthRecv ); - } - /* copy the unaligned part, if any */ - if( LengthToCopy > 0) - { - NWP_IF_READ_CHECK(g_pCB->FD,TailBuffer,4); - /* copy TailBuffer unaligned part (1/2/3 bytes) */ - sl_Memcpy(((_SlArgsData_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->pData + AlignedLengthRecv,TailBuffer,LengthToCopy); - } - } - _SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj); - _SlDrvProtectionObjUnLock(); - } - break; - - case CMD_RESP_CLASS: - - /* Some commands pass a maximum arguments size. */ - /* In this case Driver will send extra dummy patterns to NWP if */ - /* the response message is smaller than maximum. */ - /* When RxDescLen is not exact, using RxPayloadLen is forbidden! */ - /* If such case cannot be avoided - parse message here to detect */ - /* arguments/payload border. */ - NWP_IF_READ_CHECK(g_pCB->FD, - g_pCB->FunctionParams.pTxRxDescBuff, - _SL_PROTOCOL_ALIGN_SIZE(g_pCB->FunctionParams.pCmdCtrl->RxDescLen)); - - if((NULL != g_pCB->FunctionParams.pCmdExt) && (0 != g_pCB->FunctionParams.pCmdExt->RxPayloadLen)) - { - /* Actual size of command's response payload: - */ - _i16 ActDataSize = RSP_PAYLOAD_LEN(uBuf.TempBuf) - g_pCB->FunctionParams.pCmdCtrl->RxDescLen; - - g_pCB->FunctionParams.pCmdExt->ActualRxPayloadLen = ActDataSize; - - /* Check that the space prepared by user for the response data is sufficient. */ - if(ActDataSize <= 0) - { - g_pCB->FunctionParams.pCmdExt->RxPayloadLen = 0; - } - else - { - /* In case the user supplied Rx buffer length which is smaller then the received data length, copy according to user length */ - if (ActDataSize > g_pCB->FunctionParams.pCmdExt->RxPayloadLen) - { - LengthToCopy = g_pCB->FunctionParams.pCmdExt->RxPayloadLen & (3); - AlignedLengthRecv = g_pCB->FunctionParams.pCmdExt->RxPayloadLen & (~3); - } - else - { - LengthToCopy = ActDataSize & (3); - AlignedLengthRecv = ActDataSize & (~3); - } - /* Read 4 bytes aligned from interface */ - /* therefore check the requested length and read only */ - /* 4 bytes aligned data. The rest unaligned (if any) will be read */ - /* and copied to a TailBuffer */ - - if( AlignedLengthRecv >= 4) - { - NWP_IF_READ_CHECK(g_pCB->FD, - g_pCB->FunctionParams.pCmdExt->pRxPayload, - AlignedLengthRecv ); - - } - /* copy the unaligned part, if any */ - if( LengthToCopy > 0) - { - NWP_IF_READ_CHECK(g_pCB->FD,TailBuffer,4); - /* copy TailBuffer unaligned part (1/2/3 bytes) */ - sl_Memcpy(g_pCB->FunctionParams.pCmdExt->pRxPayload + AlignedLengthRecv, - TailBuffer, - LengthToCopy); - ActDataSize = ActDataSize-4; - } - /* In case the user supplied Rx buffer length which is smaller then the received data length, dump the rest */ - if (ActDataSize > g_pCB->FunctionParams.pCmdExt->RxPayloadLen) - { - /* calculate the rest of the data size to dump */ - AlignedLengthRecv = ActDataSize - (g_pCB->FunctionParams.pCmdExt->RxPayloadLen & (~3)); - while( AlignedLengthRecv > 0) - { - NWP_IF_READ_CHECK(g_pCB->FD,TailBuffer, 4 ); - AlignedLengthRecv = AlignedLengthRecv - 4; - } - } - } - } - break; - - default: - /* DUMMY_MSG_CLASS: Flow control message has no payload. */ - break; - } - - if(AlignSize > 0) - { - NWP_IF_READ_CHECK(g_pCB->FD, uBuf.TempBuf, AlignSize); - } - - _SL_DBG_CNT_INC(MsgCnt.Read); - - /* Unmask Interrupt call */ - sl_IfUnMaskIntHdlr(); - - return SL_OS_RET_CODE_OK; -} - - -/* ******************************************************************************/ -/* _SlAsyncEventGenericHandler */ -/* ******************************************************************************/ -void _SlAsyncEventGenericHandler(void) -{ - _u32 SlAsyncEvent = 0; - _u8 OpcodeFound = FALSE; - _u8 i; - - _u32* pEventLocation = NULL; /* This pointer will override the async buffer with the translated event type */ - _SlResponseHeader_t *pHdr = (_SlResponseHeader_t *)g_pCB->FunctionParams.AsyncExt.pAsyncBuf; - - - /* if no async event registered nothing to do..*/ - if (g_pCB->FunctionParams.AsyncExt.AsyncEvtHandler == NULL) - return; - - /* Iterate through all the opcode in the table */ - for (i=0; i< (sizeof(OpcodeTranslateTable) / sizeof(OpcodeKeyVal_t)); i++) - { - if (OpcodeTranslateTable[i].opcode == pHdr->GenHeader.Opcode) - { - SlAsyncEvent = OpcodeTranslateTable[i].event; - OpcodeFound = TRUE; - break; - } - } - - /* No Async event found in the table */ - if (OpcodeFound == FALSE) - { - /* This case handles all the async events handlers of the DEVICE & SOCK Silos which are handled internally. - For these cases we send the async even buffer as is */ - g_pCB->FunctionParams.AsyncExt.AsyncEvtHandler(g_pCB->FunctionParams.AsyncExt.pAsyncBuf); - } - else - { - /* calculate the event type location to be filled in the async buffer */ - pEventLocation = (_u32*)(g_pCB->FunctionParams.AsyncExt.pAsyncBuf + sizeof (_SlResponseHeader_t) - sizeof(SlAsyncEvent) ); - - /* Override the async buffer (before the data starts ) with our event type */ - *pEventLocation = SlAsyncEvent; - - /* call the event handler registered by the user with our async buffer which now holds - the User's event type and its related data */ - g_pCB->FunctionParams.AsyncExt.AsyncEvtHandler(pEventLocation); - } - - -} - - -/* ******************************************************************************/ -/* _SlDrvMsgReadCmdCtx */ -/* ******************************************************************************/ -_SlReturnVal_t _SlDrvMsgReadCmdCtx(void) -{ - - /* after command response is received and isCmdRespWaited */ - /* flag is set FALSE, it is necessary to read out all */ - /* Async messages in Commands context, because ssiDma_IsrHandleSignalFromSlave */ - /* could have dispatched some Async messages to g_NwpIf.CmdSyncObj */ - /* after command response but before this response has been processed */ - /* by spi_singleRead and isCmdRespWaited was set FALSE. */ - while (TRUE == g_pCB->IsCmdRespWaited) - { - if(_SL_PENDING_RX_MSG(g_pCB)) - { - VERIFY_RET_OK(_SlDrvMsgRead()); - g_pCB->RxDoneCnt++; - - if (CMD_RESP_CLASS == g_pCB->FunctionParams.AsyncExt.RxMsgClass) - { - g_pCB->IsCmdRespWaited = FALSE; - - /* In case CmdResp has been read without waiting on CmdSyncObj - that */ - /* Sync object. That to prevent old signal to be processed. */ - sl_SyncObjClear(&g_pCB->CmdSyncObj); - } - else if (ASYNC_EVT_CLASS == g_pCB->FunctionParams.AsyncExt.RxMsgClass) - { - /* If Async event has been read in CmdResp context, check whether */ - /* there is a handler for this event. If there is, spawn specific */ - /* handler. Otherwise free the event's buffer. */ - /* This way there will be no "dry shots" from CmdResp context to */ - /* temporary context, i.e less waste of CPU and faster buffer */ - /* release. */ - _SlAsyncEventGenericHandler(); - - -#if (SL_MEMORY_MGMT == SL_MEMORY_MGMT_DYNAMIC) - sl_Free(g_pCB->FunctionParams.AsyncExt.pAsyncBuf); -#else - g_pCB->FunctionParams.AsyncExt.pAsyncBuf = NULL; -#endif - } - } - else - { - /* CmdSyncObj will be signaled by IRQ */ - _SlDrvSyncObjWaitForever(&g_pCB->CmdSyncObj); - } - } - - /* If there are more pending Rx Msgs after CmdResp is received, */ - /* that means that these are Async, Dummy or Read Data Msgs. */ - /* Spawn _SlDrvMsgReadSpawnCtx to trigger reading these messages from */ - /* Temporary context. */ - /* sl_Spawn is activated, using a different context */ - - _SlDrvObjUnLock(&g_pCB->GlobalLockObj); - - if(_SL_PENDING_RX_MSG(g_pCB)) - { - sl_Spawn((_SlSpawnEntryFunc_t)_SlDrvMsgReadSpawnCtx, NULL, 0); - } - - return SL_OS_RET_CODE_OK; -} - -/* ******************************************************************************/ -/* _SlDrvMsgReadSpawnCtx */ -/* ******************************************************************************/ -_SlReturnVal_t _SlDrvMsgReadSpawnCtx(void *pValue) -{ -#ifdef SL_POLLING_MODE_USED - _i16 retCode = OSI_OK; - /* for polling based systems */ - do - { - retCode = sl_LockObjLock(&g_pCB->GlobalLockObj, 0); - if ( OSI_OK != retCode ) - { - if (TRUE == g_pCB->IsCmdRespWaited) - { - _SlDrvSyncObjSignal(&g_pCB->CmdSyncObj); - return SL_RET_CODE_OK; - } - } - - } - while (OSI_OK != retCode); - -#else - _SlDrvObjLockWaitForever(&g_pCB->GlobalLockObj); -#endif - - - /* Messages might have been read by CmdResp context. Therefore after */ - /* getting LockObj, check again where the Pending Rx Msg is still present. */ - if(FALSE == (_SL_PENDING_RX_MSG(g_pCB))) - { - _SlDrvObjUnLock(&g_pCB->GlobalLockObj); - - return SL_RET_CODE_OK; - } - - VERIFY_RET_OK(_SlDrvMsgRead()); - - g_pCB->RxDoneCnt++; - - switch(g_pCB->FunctionParams.AsyncExt.RxMsgClass) - { - case ASYNC_EVT_CLASS: - /* If got here and protected by LockObj a message is waiting */ - /* to be read */ - VERIFY_PROTOCOL(NULL != g_pCB->FunctionParams.AsyncExt.pAsyncBuf); - - _SlAsyncEventGenericHandler(); - -#if (SL_MEMORY_MGMT == SL_MEMORY_MGMT_DYNAMIC) - sl_Free(g_pCB->FunctionParams.AsyncExt.pAsyncBuf); -#else - g_pCB->FunctionParams.AsyncExt.pAsyncBuf = NULL; -#endif - break; - case DUMMY_MSG_CLASS: - case RECV_RESP_CLASS: - /* These types are legal in this context. Do nothing */ - break; - case CMD_RESP_CLASS: - /* Command response is illegal in this context. */ - /* No 'break' here: Assert! */ - default: - VERIFY_PROTOCOL(0); - } - - _SlDrvObjUnLock(&g_pCB->GlobalLockObj); - - return(SL_RET_CODE_OK); -} - - - -/* - -#define SL_OPCODE_SILO_DEVICE ( 0x0 << SL_OPCODE_SILO_OFFSET ) -#define SL_OPCODE_SILO_WLAN ( 0x1 << SL_OPCODE_SILO_OFFSET ) -#define SL_OPCODE_SILO_SOCKET ( 0x2 << SL_OPCODE_SILO_OFFSET ) -#define SL_OPCODE_SILO_NETAPP ( 0x3 << SL_OPCODE_SILO_OFFSET ) -#define SL_OPCODE_SILO_NVMEM ( 0x4 << SL_OPCODE_SILO_OFFSET ) -#define SL_OPCODE_SILO_NETCFG ( 0x5 << SL_OPCODE_SILO_OFFSET ) - - -*/ - -/* The Lookup table below holds the event handlers to be called according to the incoming - RX message SILO type */ -const _SlSpawnEntryFunc_t RxMsgClassLUT[] = { - (_SlSpawnEntryFunc_t)_SlDrvDeviceEventHandler, /* SL_OPCODE_SILO_DEVICE */ -#if defined(sl_WlanEvtHdlr) || defined(EXT_LIB_REGISTERED_WLAN_EVENTS) - (_SlSpawnEntryFunc_t)_SlDrvHandleWlanEvents, /* SL_OPCODE_SILO_WLAN */ -#else - NULL, -#endif -#if defined (sl_SockEvtHdlr) || defined(EXT_LIB_REGISTERED_SOCK_EVENTS) - (_SlSpawnEntryFunc_t)_SlDrvHandleSockEvents, /* SL_OPCODE_SILO_SOCKET */ -#else - NULL, -#endif - -#if defined(sl_NetAppEvtHdlr) || defined(EXT_LIB_REGISTERED_NETAPP_EVENTS) - (_SlSpawnEntryFunc_t)_SlDrvHandleNetAppEvents, /* SL_OPCODE_SILO_NETAPP */ -#else - NULL, -#endif - NULL, /* SL_OPCODE_SILO_NVMEM */ - NULL, /* SL_OPCODE_SILO_NETCFG */ - NULL, - NULL -}; - - -/* ******************************************************************************/ -/* _SlDrvClassifyRxMsg */ -/* ******************************************************************************/ -void _SlDrvClassifyRxMsg( - _SlOpcode_t Opcode) -{ - _SlSpawnEntryFunc_t AsyncEvtHandler = NULL; - _SlRxMsgClass_e RxMsgClass = CMD_RESP_CLASS; - _u8 Silo; - - - if (0 == (SL_OPCODE_SYNC & Opcode)) - { /* Async event has received */ - - if (SL_OPCODE_DEVICE_DEVICEASYNCDUMMY == Opcode) - { - RxMsgClass = DUMMY_MSG_CLASS; - } - else if ( (SL_OPCODE_SOCKET_RECVASYNCRESPONSE == Opcode) || (SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE == Opcode) -#ifndef SL_TINY_EXT - || (SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE_V6 == Opcode) -#endif - ) - { - RxMsgClass = RECV_RESP_CLASS; - } - else - { - /* This is Async Event class message */ - RxMsgClass = ASYNC_EVT_CLASS; - - /* Despite the fact that 4 bits are allocated in the SILO field, we actually have only 6 SILOs - So we can use the 8 options of SILO in look up table */ - Silo = ((Opcode >> SL_OPCODE_SILO_OFFSET) & 0x7); - - VERIFY_PROTOCOL(Silo < (sizeof(RxMsgClassLUT)/sizeof(_SlSpawnEntryFunc_t))); - - /* Set the async event hander according to the LUT */ - AsyncEvtHandler = RxMsgClassLUT[Silo]; - - if ((SL_OPCODE_NETAPP_HTTPGETTOKENVALUE == Opcode) || (SL_OPCODE_NETAPP_HTTPPOSTTOKENVALUE == Opcode)) - { - AsyncEvtHandler = _SlDrvNetAppEventHandler; - } -#ifndef SL_TINY_EXT - else if (SL_OPCODE_NETAPP_PINGREPORTREQUESTRESPONSE == Opcode) - { - AsyncEvtHandler = (_SlSpawnEntryFunc_t)_sl_HandleAsync_PingResponse; - } -#endif - } - } - - g_pCB->FunctionParams.AsyncExt.RxMsgClass = RxMsgClass; - g_pCB->FunctionParams.AsyncExt.AsyncEvtHandler = AsyncEvtHandler; - -} - - -/* ******************************************************************************/ -/* _SlDrvRxHdrRead */ -/* ******************************************************************************/ -_SlReturnVal_t _SlDrvRxHdrRead(_u8 *pBuf, _u8 *pAlignSize) -{ - _u32 SyncCnt = 0; - _u8 ShiftIdx; - -#ifndef SL_IF_TYPE_UART - /* 1. Write CNYS pattern to NWP when working in SPI mode only */ - NWP_IF_WRITE_CHECK(g_pCB->FD, (_u8 *)&g_H2NCnysPattern.Short, SYNC_PATTERN_LEN); -#endif - - /* 2. Read 4 bytes (protocol aligned) */ - NWP_IF_READ_CHECK(g_pCB->FD, &pBuf[0], 4); - _SL_DBG_SYNC_LOG(SyncCnt,pBuf); - - /* Wait for SYNC_PATTERN_LEN from the device */ - while ( ! N2H_SYNC_PATTERN_MATCH(pBuf, g_pCB->TxSeqNum) ) - { - /* 3. Debug limit of scan */ - VERIFY_PROTOCOL(SyncCnt < SL_SYNC_SCAN_THRESHOLD); - - /* 4. Read next 4 bytes to Low 4 bytes of buffer */ - if(0 == (SyncCnt % (_u32)SYNC_PATTERN_LEN)) - { - NWP_IF_READ_CHECK(g_pCB->FD, &pBuf[4], 4); - _SL_DBG_SYNC_LOG(SyncCnt,pBuf); - } - - /* 5. Shift Buffer Up for checking if the sync is shifted */ - for(ShiftIdx = 0; ShiftIdx< 7; ShiftIdx++) - { - pBuf[ShiftIdx] = pBuf[ShiftIdx+1]; - } - pBuf[7] = 0; - - SyncCnt++; - } - - /* 5. Sync pattern found. If needed, complete number of read bytes to multiple of 4 (protocol align) */ - SyncCnt %= SYNC_PATTERN_LEN; - - if(SyncCnt > 0) - { - *(_u32 *)&pBuf[0] = *(_u32 *)&pBuf[4]; - NWP_IF_READ_CHECK(g_pCB->FD, &pBuf[SYNC_PATTERN_LEN - SyncCnt], (_u16)SyncCnt); - } - else - { - NWP_IF_READ_CHECK(g_pCB->FD, &pBuf[0], 4); - } - - /* 6. Scan for Double pattern. */ - while ( N2H_SYNC_PATTERN_MATCH(pBuf, g_pCB->TxSeqNum) ) - { - _SL_DBG_CNT_INC(Work.DoubleSyncPattern); - NWP_IF_READ_CHECK(g_pCB->FD, &pBuf[0], SYNC_PATTERN_LEN); - } - g_pCB->TxSeqNum++; - - /* 7. Here we've read Generic Header (4 bytes). Read the Resp Specific header (4 more bytes). */ - NWP_IF_READ_CHECK(g_pCB->FD, &pBuf[SYNC_PATTERN_LEN], _SL_RESP_SPEC_HDR_SIZE); - - /* 8. Here we've read the entire Resp Header. */ - /* Return number bytes needed to be sent after read for NWP Rx 4-byte alignment (protocol alignment) */ - *pAlignSize = (_u8)((SyncCnt > 0) ? (SYNC_PATTERN_LEN - SyncCnt) : 0); - - return SL_RET_CODE_OK; -} - -/* ***************************************************************************** */ -/* _SlDrvBasicCmd */ -/* ***************************************************************************** */ -typedef union -{ - _BasicResponse_t Rsp; -}_SlBasicCmdMsg_u; - - -#ifndef SL_TINY_EXT -_i16 _SlDrvBasicCmd(_SlOpcode_t Opcode) -{ - _SlBasicCmdMsg_u Msg = {{0, 0}}; - _SlCmdCtrl_t CmdCtrl; - - CmdCtrl.Opcode = Opcode; - CmdCtrl.TxDescLen = 0; - CmdCtrl.RxDescLen = sizeof(_BasicResponse_t); - - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&CmdCtrl, &Msg, NULL)); - - return (_i16)Msg.Rsp.status; -} - -/***************************************************************************** - _SlDrvCmdSend - Send SL command without waiting for command response - This function is unprotected and the caller should make - sure global lock is active -*****************************************************************************/ -_SlReturnVal_t _SlDrvCmdSend( - _SlCmdCtrl_t *pCmdCtrl , - void *pTxRxDescBuff , - _SlCmdExt_t *pCmdExt) -{ - _SlReturnVal_t RetVal; - _u8 IsCmdRespWaitedOriginalVal; - - _SlFunctionParams_t originalFuncParms; - - /* save the current RespWait flag before clearing it */ - IsCmdRespWaitedOriginalVal = g_pCB->IsCmdRespWaited; - - /* save the current command parameters */ - sl_Memcpy(&originalFuncParms, &g_pCB->FunctionParams, sizeof(_SlFunctionParams_t)); - - g_pCB->IsCmdRespWaited = FALSE; - - SL_TRACE0(DBG_MSG, MSG_312, "_SlDrvCmdSend: call _SlDrvMsgWrite"); - - /* send the message */ - RetVal = _SlDrvMsgWrite(pCmdCtrl, pCmdExt, pTxRxDescBuff); - - /* restore the original RespWait flag */ - g_pCB->IsCmdRespWaited = IsCmdRespWaitedOriginalVal; - - /* restore the original command parameters */ - sl_Memcpy(&g_pCB->FunctionParams, &originalFuncParms, sizeof(_SlFunctionParams_t)); - - return RetVal; - - -} -#endif - -/* ***************************************************************************** */ -/* _SlDrvWaitForPoolObj */ -/* ***************************************************************************** */ -_u8 _SlDrvWaitForPoolObj(_u8 ActionID, _u8 SocketID) -{ - _u8 CurrObjIndex = MAX_CONCURRENT_ACTIONS; - - /* Get free object */ - _SlDrvProtectionObjLockWaitForever(); - if (MAX_CONCURRENT_ACTIONS > g_pCB->FreePoolIdx) - { - /* save the current obj index */ - CurrObjIndex = g_pCB->FreePoolIdx; - /* set the new free index */ -#ifndef SL_TINY_EXT - if (MAX_CONCURRENT_ACTIONS > g_pCB->ObjPool[CurrObjIndex].NextIndex) - { - g_pCB->FreePoolIdx = g_pCB->ObjPool[CurrObjIndex].NextIndex; - } - else -#endif - { - /* No further free actions available */ - g_pCB->FreePoolIdx = MAX_CONCURRENT_ACTIONS; - } - } - else - { - _SlDrvProtectionObjUnLock(); - return CurrObjIndex; - } - g_pCB->ObjPool[CurrObjIndex].ActionID = (_u8)ActionID; - if (SL_MAX_SOCKETS > SocketID) - { - g_pCB->ObjPool[CurrObjIndex].AdditionalData = SocketID; - } -#ifndef SL_TINY_EXT - /*In case this action is socket related, SocketID bit will be on - In case SocketID is set to SL_MAX_SOCKETS, the socket is not relevant to the action. In that case ActionID bit will be on */ - while ( ( (SL_MAX_SOCKETS > SocketID) && (g_pCB->ActiveActionsBitmap & (1<ActiveActionsBitmap & (1<ObjPool[CurrObjIndex].NextIndex = g_pCB->PendingPoolIdx; - g_pCB->PendingPoolIdx = CurrObjIndex; - _SlDrvProtectionObjUnLock(); - - /* wait for action to be free */ - _SlDrvSyncObjWaitForever(&g_pCB->ObjPool[CurrObjIndex].SyncObj); - - /* set params and move to active (remove from pending list at _SlDrvReleasePoolObj) */ - _SlDrvProtectionObjLockWaitForever(); - } -#endif - /* mark as active. Set socket as active if action is on socket, otherwise mark action as active */ - if (SL_MAX_SOCKETS > SocketID) - { - g_pCB->ActiveActionsBitmap |= (1<ActiveActionsBitmap |= (1<ObjPool[CurrObjIndex].NextIndex = g_pCB->ActivePoolIdx; - g_pCB->ActivePoolIdx = CurrObjIndex; - /* unlock */ - _SlDrvProtectionObjUnLock(); - return CurrObjIndex; -} - -/* ******************************************************************************/ -/* _SlDrvReleasePoolObj */ -/* ******************************************************************************/ -void _SlDrvReleasePoolObj(_u8 ObjIdx) -{ -#ifndef SL_TINY_EXT - _u8 PendingIndex; -#endif - - _SlDrvProtectionObjLockWaitForever(); - - /* In Tiny mode, there is only one object pool so no pending actions are available */ -#ifndef SL_TINY_EXT - /* go over the pending list and release other pending action if needed */ - PendingIndex = g_pCB->PendingPoolIdx; - - while(MAX_CONCURRENT_ACTIONS > PendingIndex) - { - /* In case this action is socket related, SocketID is in use, otherwise will be set to SL_MAX_SOCKETS */ - if ( (g_pCB->ObjPool[PendingIndex].ActionID == g_pCB->ObjPool[ObjIdx].ActionID) && - ( (SL_MAX_SOCKETS == (g_pCB->ObjPool[PendingIndex].AdditionalData & BSD_SOCKET_ID_MASK)) || - ((SL_MAX_SOCKETS > (g_pCB->ObjPool[ObjIdx].AdditionalData & BSD_SOCKET_ID_MASK)) && ( (g_pCB->ObjPool[PendingIndex].AdditionalData & BSD_SOCKET_ID_MASK) == (g_pCB->ObjPool[ObjIdx].AdditionalData & BSD_SOCKET_ID_MASK) ))) ) - { - /* remove from pending list */ - _SlRemoveFromList(&g_pCB->PendingPoolIdx, PendingIndex); - _SlDrvSyncObjSignal(&g_pCB->ObjPool[PendingIndex].SyncObj); - break; - } - PendingIndex = g_pCB->ObjPool[PendingIndex].NextIndex; - } -#endif - - if (SL_MAX_SOCKETS > (g_pCB->ObjPool[ObjIdx].AdditionalData & BSD_SOCKET_ID_MASK)) - { - /* unset socketID */ - g_pCB->ActiveActionsBitmap &= ~(1<<(g_pCB->ObjPool[ObjIdx].AdditionalData & BSD_SOCKET_ID_MASK)); - } - else - { - /* unset actionID */ - g_pCB->ActiveActionsBitmap &= ~(1<ObjPool[ObjIdx].ActionID); - } - - /* delete old data */ - g_pCB->ObjPool[ObjIdx].pRespArgs = NULL; - g_pCB->ObjPool[ObjIdx].ActionID = 0; - g_pCB->ObjPool[ObjIdx].AdditionalData = SL_MAX_SOCKETS; - - /* remove from active list */ - _SlRemoveFromList(&g_pCB->ActivePoolIdx, ObjIdx); - /* move to free list */ - g_pCB->ObjPool[ObjIdx].NextIndex = g_pCB->FreePoolIdx; - g_pCB->FreePoolIdx = ObjIdx; - _SlDrvProtectionObjUnLock(); -} - - -/* ******************************************************************************/ -/* _SlRemoveFromList */ -/* ******************************************************************************/ -void _SlRemoveFromList(_u8 *ListIndex, _u8 ItemIndex) -{ -#ifndef SL_TINY_EXT - _u8 Idx; -#endif - - if (MAX_CONCURRENT_ACTIONS == g_pCB->ObjPool[*ListIndex].NextIndex) - { - *ListIndex = MAX_CONCURRENT_ACTIONS; - } - /* As MAX_CONCURRENT_ACTIONS is equal to 1 in Tiny mode */ -#ifndef SL_TINY_EXT - /* need to remove the first item in the list and therefore update the global which holds this index */ - else if (*ListIndex == ItemIndex) - { - *ListIndex = g_pCB->ObjPool[ItemIndex].NextIndex; - } - else - { - Idx = *ListIndex; - - while(MAX_CONCURRENT_ACTIONS > Idx) - { - /* remove from list */ - if (g_pCB->ObjPool[Idx].NextIndex == ItemIndex) - { - g_pCB->ObjPool[Idx].NextIndex = g_pCB->ObjPool[ItemIndex].NextIndex; - break; - } - - Idx = g_pCB->ObjPool[Idx].NextIndex; - } - } -#endif -} - - -/* ******************************************************************************/ -/* _SlFindAndSetActiveObj */ -/* ******************************************************************************/ -_SlReturnVal_t _SlFindAndSetActiveObj(_SlOpcode_t Opcode, _u8 Sd) -{ - _u8 ActiveIndex; - - ActiveIndex = g_pCB->ActivePoolIdx; - /* go over the active list if exist to find obj waiting for this Async event */ -#ifndef SL_TINY_EXT - while (MAX_CONCURRENT_ACTIONS > ActiveIndex) -#else - /* Only one Active action is availabe in tiny mode, so we can replace the loop with if condition */ - if (MAX_CONCURRENT_ACTIONS > ActiveIndex) -#endif - { - /* unset the Ipv4\IPv6 bit in the opcode if family bit was set */ - if (g_pCB->ObjPool[ActiveIndex].AdditionalData & SL_NETAPP_FAMILY_MASK) - { - Opcode &= ~SL_OPCODE_IPV6; - } - - if ((g_pCB->ObjPool[ActiveIndex].ActionID == RECV_ID) && (Sd == g_pCB->ObjPool[ActiveIndex].AdditionalData) && - ( (SL_OPCODE_SOCKET_RECVASYNCRESPONSE == Opcode) || (SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE == Opcode) -#ifndef SL_TINY_EXT - || (SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE_V6 == Opcode) -#endif - ) - - ) - { - g_pCB->FunctionParams.AsyncExt.ActionIndex = ActiveIndex; - return SL_RET_CODE_OK; - } - /* In case this action is socket related, SocketID is in use, otherwise will be set to SL_MAX_SOCKETS */ - if ( (_SlActionLookupTable[ g_pCB->ObjPool[ActiveIndex].ActionID - MAX_SOCKET_ENUM_IDX].ActionAsyncOpcode == Opcode) && - ( ((Sd == (g_pCB->ObjPool[ActiveIndex].AdditionalData & BSD_SOCKET_ID_MASK) ) && (SL_MAX_SOCKETS > Sd)) || (SL_MAX_SOCKETS == (g_pCB->ObjPool[ActiveIndex].AdditionalData & BSD_SOCKET_ID_MASK)) ) ) - { - /* set handler */ - g_pCB->FunctionParams.AsyncExt.AsyncEvtHandler = _SlActionLookupTable[ g_pCB->ObjPool[ActiveIndex].ActionID - MAX_SOCKET_ENUM_IDX].AsyncEventHandler; - g_pCB->FunctionParams.AsyncExt.ActionIndex = ActiveIndex; - return SL_RET_CODE_OK; - } - ActiveIndex = g_pCB->ObjPool[ActiveIndex].NextIndex; - } - - return SL_RET_CODE_SELF_ERROR; - - - -} - - -/* Wrappers for the object functions */ - -void _SlDrvSyncObjWaitForever(_SlSyncObj_t *pSyncObj) -{ - OSI_RET_OK_CHECK(sl_SyncObjWait(pSyncObj, SL_OS_WAIT_FOREVER)); -} - -void _SlDrvSyncObjSignal(_SlSyncObj_t *pSyncObj) -{ - OSI_RET_OK_CHECK(sl_SyncObjSignal(pSyncObj)); -} - -void _SlDrvObjLockWaitForever(_SlLockObj_t *pLockObj) -{ - OSI_RET_OK_CHECK(sl_LockObjLock(pLockObj, SL_OS_WAIT_FOREVER)); -} - -void _SlDrvProtectionObjLockWaitForever() -{ - OSI_RET_OK_CHECK(sl_LockObjLock(&g_pCB->ProtectionLockObj, SL_OS_WAIT_FOREVER)); - -} - -void _SlDrvObjUnLock(_SlLockObj_t *pLockObj) -{ - OSI_RET_OK_CHECK(sl_LockObjUnlock(pLockObj)); - -} - -void _SlDrvProtectionObjUnLock() -{ - OSI_RET_OK_CHECK(sl_LockObjUnlock(&g_pCB->ProtectionLockObj)); -} - - -void _SlDrvMemZero(void* Addr, _u16 size) -{ - sl_Memset(Addr, 0, size); -} - - -void _SlDrvResetCmdExt(_SlCmdExt_t* pCmdExt) -{ - _SlDrvMemZero(pCmdExt, sizeof (_SlCmdExt_t)); -} - - - - diff --git a/drivers/cc3100/src/flowcont.c b/drivers/cc3100/src/flowcont.c deleted file mode 100644 index 889241ea2b..0000000000 --- a/drivers/cc3100/src/flowcont.c +++ /dev/null @@ -1,71 +0,0 @@ -/* - * flowcont.c - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - - - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" -#include "protocol.h" -#include "driver.h" -#include "flowcont.h" - - -/*****************************************************************************/ -/* _SlDrvFlowContInit */ -/*****************************************************************************/ -void _SlDrvFlowContInit(void) -{ - g_pCB->FlowContCB.TxPoolCnt = FLOW_CONT_MIN; - - OSI_RET_OK_CHECK(sl_LockObjCreate(&g_pCB->FlowContCB.TxLockObj, "TxLockObj")); - - OSI_RET_OK_CHECK(sl_SyncObjCreate(&g_pCB->FlowContCB.TxSyncObj, "TxSyncObj")); -} - -/*****************************************************************************/ -/* _SlDrvFlowContDeinit */ -/*****************************************************************************/ -void _SlDrvFlowContDeinit(void) -{ - g_pCB->FlowContCB.TxPoolCnt = 0; - - OSI_RET_OK_CHECK(sl_LockObjDelete(&g_pCB->FlowContCB.TxLockObj)); - - OSI_RET_OK_CHECK(sl_SyncObjDelete(&g_pCB->FlowContCB.TxSyncObj)); -} - diff --git a/drivers/cc3100/src/fs.c b/drivers/cc3100/src/fs.c deleted file mode 100644 index cc2e9987d0..0000000000 --- a/drivers/cc3100/src/fs.c +++ /dev/null @@ -1,424 +0,0 @@ -/* - * fs.c - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - - - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" -#include "protocol.h" -#include "driver.h" - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ -#define sl_min(a,b) (((a) < (b)) ? (a) : (b)) -#define MAX_NVMEM_CHUNK_SIZE 1460 - -/*****************************************************************************/ -/* Internal functions */ -/*****************************************************************************/ - -/*****************************************************************************/ -/* _sl_Strlen */ -/*****************************************************************************/ -_u16 _sl_Strlen(const _u8 *buffer) -{ - _u16 len = 0; - if( buffer != NULL ) - { - while(*buffer++) len++; - } - return len; -} - -/*****************************************************************************/ -/* _sl_GetCreateFsMode */ -/*****************************************************************************/ -_u32 _sl_GetCreateFsMode(_u32 maxSizeInBytes,_u32 accessFlags) -{ - _u32 granIdx = 0; - _u32 granNum = 0; - _u32 granTable[_FS_MAX_MODE_SIZE_GRAN] = {256,1024,4096,16384,65536}; - for(granIdx= _FS_MODE_SIZE_GRAN_256B ;granIdx< _FS_MAX_MODE_SIZE_GRAN;granIdx++) - { - if( granTable[granIdx]*255 >= maxSizeInBytes ) - break; - } - granNum = maxSizeInBytes/granTable[granIdx]; - if( maxSizeInBytes % granTable[granIdx] != 0 ) - granNum++; - - return _FS_MODE(_FS_MODE_OPEN_WRITE_CREATE_IF_NOT_EXIST, granIdx, granNum, accessFlags); -} - -/*****************************************************************************/ -/* API functions */ -/*****************************************************************************/ - -/*****************************************************************************/ -/* sl_FsOpen */ -/*****************************************************************************/ -typedef union -{ - _FsOpenCommand_t Cmd; - _FsOpenResponse_t Rsp; -}_SlFsOpenMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_FsOpen) - -const _SlCmdCtrl_t _SlFsOpenCmdCtrl = -{ - SL_OPCODE_NVMEM_FILEOPEN, - sizeof(_FsOpenCommand_t), - sizeof(_FsOpenResponse_t) -}; - -_i32 sl_FsOpen(const _u8 *pFileName,const _u32 AccessModeAndMaxSize, _u32 *pToken,_i32 *pFileHandle) -{ - _SlReturnVal_t RetVal; - _SlFsOpenMsg_u Msg; - _SlCmdExt_t CmdExt; - - CmdExt.TxPayloadLen = (_sl_Strlen(pFileName)+4) & (~3); /* add 4: 1 for NULL and the 3 for align */ - CmdExt.RxPayloadLen = 0; - CmdExt.pTxPayload = (_u8*)pFileName; - CmdExt.pRxPayload = NULL; - - Msg.Cmd.Mode = AccessModeAndMaxSize; - - if(pToken != NULL) - { - Msg.Cmd.Token = *pToken; - } - else - { - Msg.Cmd.Token = 0; - } - - RetVal = _SlDrvCmdOp((_SlCmdCtrl_t *)&_SlFsOpenCmdCtrl, &Msg, &CmdExt); - *pFileHandle = Msg.Rsp.FileHandle; - if (pToken != NULL) - { - *pToken = Msg.Rsp.Token; - } - - /* in case of an error, return the erros file handler as an error code */ - if( *pFileHandle < 0 ) - { - return *pFileHandle; - } - return (_i32)RetVal; -} -#endif - -/*****************************************************************************/ -/* sl_FsClose */ -/*****************************************************************************/ -typedef union -{ - _FsCloseCommand_t Cmd; - _BasicResponse_t Rsp; -}_SlFsCloseMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_FsClose) - -const _SlCmdCtrl_t _SlFsCloseCmdCtrl = -{ - SL_OPCODE_NVMEM_FILECLOSE, - sizeof(_FsCloseCommand_t), - sizeof(_FsCloseResponse_t) -}; - -_i16 sl_FsClose(const _i32 FileHdl, const _u8* pCeritificateFileName,const _u8* pSignature ,const _u32 SignatureLen) -{ - _SlFsCloseMsg_u Msg = {{0, 0}}; - _SlCmdExt_t ExtCtrl; - - Msg.Cmd.FileHandle = FileHdl; - if( pCeritificateFileName != NULL ) - { - Msg.Cmd.CertificFileNameLength = (_sl_Strlen(pCeritificateFileName)+4) & (~3); /* add 4: 1 for NULL and the 3 for align */ - } - Msg.Cmd.SignatureLen = SignatureLen; - - ExtCtrl.TxPayloadLen = ((SignatureLen+3) & (~3)); /* align */ - ExtCtrl.pTxPayload = (_u8*)pSignature; - ExtCtrl.RxPayloadLen = (_i16)Msg.Cmd.CertificFileNameLength; - ExtCtrl.pRxPayload = (_u8*)pCeritificateFileName; /* Add signature */ - - if(ExtCtrl.pRxPayload != NULL && ExtCtrl.RxPayloadLen != 0) - { - ExtCtrl.RxPayloadLen = ExtCtrl.RxPayloadLen * (-1); - } - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlFsCloseCmdCtrl, &Msg, &ExtCtrl)); - - return (_i16)((_i16)Msg.Rsp.status); -} -#endif - - -/*****************************************************************************/ -/* sl_FsRead */ -/*****************************************************************************/ -typedef union -{ - _FsReadCommand_t Cmd; - _FsReadResponse_t Rsp; -}_SlFsReadMsg_u; - -#if _SL_INCLUDE_FUNC(sl_FsRead) - - -const _SlCmdCtrl_t _SlFsReadCmdCtrl = -{ - SL_OPCODE_NVMEM_FILEREADCOMMAND, - sizeof(_FsReadCommand_t), - sizeof(_FsReadResponse_t) -}; - -_i32 sl_FsRead(const _i32 FileHdl,_u32 Offset, _u8* pData,_u32 Len) -{ - _SlFsReadMsg_u Msg; - _SlCmdExt_t ExtCtrl; - _u16 ChunkLen; - _SlReturnVal_t RetVal =0; - _i32 RetCount = 0; - - ExtCtrl.TxPayloadLen = 0; - ExtCtrl.pTxPayload = NULL; - - ChunkLen = (_u16)sl_min(MAX_NVMEM_CHUNK_SIZE,Len); - ExtCtrl.RxPayloadLen = ChunkLen; - ExtCtrl.pRxPayload = (_u8 *)(pData); - Msg.Cmd.Offset = Offset; - Msg.Cmd.Len = ChunkLen; - Msg.Cmd.FileHandle = FileHdl; - do - { - RetVal = _SlDrvCmdOp((_SlCmdCtrl_t *)&_SlFsReadCmdCtrl, &Msg, &ExtCtrl); - if(SL_OS_RET_CODE_OK == RetVal) - { - if( Msg.Rsp.status < 0) - { - if( RetCount > 0) - { - return RetCount; - } - else - { - return Msg.Rsp.status; - } - } - RetCount += (_i32)Msg.Rsp.status; - Len -= ChunkLen; - Offset += ChunkLen; - Msg.Cmd.Offset = Offset; - ExtCtrl.pRxPayload += ChunkLen; - ChunkLen = (_u16)sl_min(MAX_NVMEM_CHUNK_SIZE,Len); - ExtCtrl.RxPayloadLen = ChunkLen; - Msg.Cmd.Len = ChunkLen; - Msg.Cmd.FileHandle = FileHdl; - } - else - { - return RetVal; - } - }while(ChunkLen > 0); - - return (_i32)RetCount; -} -#endif - -/*****************************************************************************/ -/* sl_FsWrite */ -/*****************************************************************************/ -typedef union -{ - _FsWriteCommand_t Cmd; - _FsWriteResponse_t Rsp; -}_SlFsWriteMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_FsWrite) - -const _SlCmdCtrl_t _SlFsWriteCmdCtrl = -{ - SL_OPCODE_NVMEM_FILEWRITECOMMAND, - sizeof(_FsWriteCommand_t), - sizeof(_FsWriteResponse_t) -}; - -_i32 sl_FsWrite(const _i32 FileHdl,_u32 Offset, _u8* pData,_u32 Len) -{ - _SlFsWriteMsg_u Msg; - _SlCmdExt_t ExtCtrl; - _u16 ChunkLen; - _SlReturnVal_t RetVal; - _i32 RetCount = 0; - - ExtCtrl.RxPayloadLen = 0; - ExtCtrl.pRxPayload = NULL; - - ChunkLen = (_u16)sl_min(MAX_NVMEM_CHUNK_SIZE,Len); - ExtCtrl.TxPayloadLen = ChunkLen; - ExtCtrl.pTxPayload = (_u8 *)(pData); - Msg.Cmd.Offset = Offset; - Msg.Cmd.Len = ChunkLen; - Msg.Cmd.FileHandle = FileHdl; - - do - { - - RetVal = _SlDrvCmdOp((_SlCmdCtrl_t *)&_SlFsWriteCmdCtrl, &Msg, &ExtCtrl); - if(SL_OS_RET_CODE_OK == RetVal) - { - if( Msg.Rsp.status < 0) - { - if( RetCount > 0) - { - return RetCount; - } - else - { - return Msg.Rsp.status; - } - } - - RetCount += (_i32)Msg.Rsp.status; - Len -= ChunkLen; - Offset += ChunkLen; - Msg.Cmd.Offset = Offset; - ExtCtrl.pTxPayload += ChunkLen; - ChunkLen = (_u16)sl_min(MAX_NVMEM_CHUNK_SIZE,Len); - ExtCtrl.TxPayloadLen = ChunkLen; - Msg.Cmd.Len = ChunkLen; - Msg.Cmd.FileHandle = FileHdl; - } - else - { - return RetVal; - } - }while(ChunkLen > 0); - - return (_i32)RetCount; -} -#endif - -/*****************************************************************************/ -/* sl_FsGetInfo */ -/*****************************************************************************/ -typedef union -{ - _FsGetInfoCommand_t Cmd; - _FsGetInfoResponse_t Rsp; -}_SlFsGetInfoMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_FsGetInfo) - - -const _SlCmdCtrl_t _SlFsGetInfoCmdCtrl = -{ - SL_OPCODE_NVMEM_FILEGETINFOCOMMAND, - sizeof(_FsGetInfoCommand_t), - sizeof(_FsGetInfoResponse_t) -}; - -_i16 sl_FsGetInfo(const _u8 *pFileName,const _u32 Token,SlFsFileInfo_t* pFsFileInfo) -{ - _SlFsGetInfoMsg_u Msg; - _SlCmdExt_t CmdExt; - - CmdExt.TxPayloadLen = (_sl_Strlen(pFileName)+4) & (~3); /* add 4: 1 for NULL and the 3 for align */ - CmdExt.RxPayloadLen = 0; - CmdExt.pTxPayload = (_u8*)pFileName; - CmdExt.pRxPayload = NULL; - Msg.Cmd.Token = Token; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlFsGetInfoCmdCtrl, &Msg, &CmdExt)); - - pFsFileInfo->flags = Msg.Rsp.flags; - pFsFileInfo->FileLen = Msg.Rsp.FileLen; - pFsFileInfo->AllocatedLen = Msg.Rsp.AllocatedLen; - pFsFileInfo->Token[0] = Msg.Rsp.Token[0]; - pFsFileInfo->Token[1] = Msg.Rsp.Token[1]; - pFsFileInfo->Token[2] = Msg.Rsp.Token[2]; - pFsFileInfo->Token[3] = Msg.Rsp.Token[3]; - return (_i16)((_i16)Msg.Rsp.Status); -} -#endif - -/*****************************************************************************/ -/* sl_FsDel */ -/*****************************************************************************/ -typedef union -{ - _FsDeleteCommand_t Cmd; - _FsDeleteResponse_t Rsp; -}_SlFsDeleteMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_FsDel) - -const _SlCmdCtrl_t _SlFsDeleteCmdCtrl = -{ - SL_OPCODE_NVMEM_FILEDELCOMMAND, - sizeof(_FsDeleteCommand_t), - sizeof(_FsDeleteResponse_t) -}; - -_i16 sl_FsDel(const _u8 *pFileName,const _u32 Token) -{ - _SlFsDeleteMsg_u Msg; - _SlCmdExt_t CmdExt; - - CmdExt.TxPayloadLen = (_sl_Strlen(pFileName)+4) & (~3); /* add 4: 1 for NULL and the 3 for align */ - CmdExt.RxPayloadLen = 0; - CmdExt.pTxPayload = (_u8*)pFileName; - CmdExt.pRxPayload = NULL; - Msg.Cmd.Token = Token; - - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlFsDeleteCmdCtrl, &Msg, &CmdExt)); - - return (_i16)((_i16)Msg.Rsp.status); -} -#endif diff --git a/drivers/cc3100/src/netapp.c b/drivers/cc3100/src/netapp.c deleted file mode 100644 index 11bcdefadf..0000000000 --- a/drivers/cc3100/src/netapp.c +++ /dev/null @@ -1,1304 +0,0 @@ -/* - * netapp.c - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - - - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" -#include "protocol.h" -#include "driver.h" - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ -#define NETAPP_MDNS_OPTIONS_ADD_SERVICE_BIT ((_u32)0x1 << 31) - -#ifdef SL_TINY -#define NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH 63 -#else -#define NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH 255 -#endif - - -/*****************************************************************************/ -/* Functions prototypes */ -/*****************************************************************************/ -void _sl_HandleAsync_DnsGetHostByName(void *pVoidBuf); - -#ifndef SL_TINY_EXT -void _sl_HandleAsync_DnsGetHostByService(void *pVoidBuf); -void _sl_HandleAsync_PingResponse(void *pVoidBuf); -#endif - -void CopyPingResultsToReport(_PingReportResponse_t *pResults,SlPingReport_t *pReport); -_i16 sl_NetAppMDNSRegisterUnregisterService(const _i8* pServiceName, - const _u8 ServiceNameLen, - const _i8* pText, - const _u8 TextLen, - const _u16 Port, - const _u32 TTL, - const _u32 Options); - -#if defined(sl_HttpServerCallback) || defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS) -_u16 _sl_NetAppSendTokenValue(slHttpServerData_t * Token); -#endif -typedef union -{ - _NetAppStartStopCommand_t Cmd; - _NetAppStartStopResponse_t Rsp; -}_SlNetAppStartStopMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_NetAppStart) - -const _SlCmdCtrl_t _SlNetAppStartCtrl = -{ - SL_OPCODE_NETAPP_START_COMMAND, - sizeof(_NetAppStartStopCommand_t), - sizeof(_NetAppStartStopResponse_t) -}; - -_i16 sl_NetAppStart(const _u32 AppBitMap) -{ - _SlNetAppStartStopMsg_u Msg; - Msg.Cmd.appId = AppBitMap; - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetAppStartCtrl, &Msg, NULL)); - - return Msg.Rsp.status; -} -#endif - -/***************************************************************************** - sl_NetAppStop -*****************************************************************************/ -#if _SL_INCLUDE_FUNC(sl_NetAppStop) - - -const _SlCmdCtrl_t _SlNetAppStopCtrl = -{ - SL_OPCODE_NETAPP_STOP_COMMAND, - sizeof(_NetAppStartStopCommand_t), - sizeof(_NetAppStartStopResponse_t) -}; - - - -_i16 sl_NetAppStop(const _u32 AppBitMap) -{ - _SlNetAppStartStopMsg_u Msg; - Msg.Cmd.appId = AppBitMap; - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetAppStopCtrl, &Msg, NULL)); - - return Msg.Rsp.status; -} -#endif - - -/******************************************************************************/ -/* sl_NetAppGetServiceList */ -/******************************************************************************/ -typedef struct -{ - _u8 IndexOffest; - _u8 MaxServiceCount; - _u8 Flags; - _i8 Padding; -}NetappGetServiceListCMD_t; - -typedef union -{ - NetappGetServiceListCMD_t Cmd; - _BasicResponse_t Rsp; -}_SlNetappGetServiceListMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_NetAppGetServiceList) - -const _SlCmdCtrl_t _SlGetServiceListeCtrl = -{ - SL_OPCODE_NETAPP_NETAPP_MDNS_LOOKUP_SERVICE, - sizeof(NetappGetServiceListCMD_t), - sizeof(_BasicResponse_t) -}; - -_i16 sl_NetAppGetServiceList(const _u8 IndexOffest, - const _u8 MaxServiceCount, - const _u8 Flags, - _i8 *pBuffer, - const _u32 RxBufferLength - ) -{ - - _i32 retVal= 0; - _SlNetappGetServiceListMsg_u Msg; - _SlCmdExt_t CmdExt; - _u16 ServiceSize = 0; - _u16 BufferSize = 0; - - /* - Calculate RX pBuffer size - WARNING: - if this size is BufferSize than 1480 error should be returned because there - is no place in the RX packet. - */ - switch(Flags) - { - case SL_NET_APP_FULL_SERVICE_WITH_TEXT_IPV4_TYPE: - ServiceSize = sizeof(SlNetAppGetFullServiceWithTextIpv4List_t); - break; - - case SL_NET_APP_FULL_SERVICE_IPV4_TYPE: - ServiceSize = sizeof(SlNetAppGetFullServiceIpv4List_t); - break; - - case SL_NET_APP_SHORT_SERVICE_IPV4_TYPE: - ServiceSize = sizeof(SlNetAppGetShortServiceIpv4List_t); - break; - - default: - ServiceSize = sizeof(_BasicResponse_t); - break; - } - - - - BufferSize = MaxServiceCount * ServiceSize; - - /*Check the size of the requested services is smaller than size of the user buffer. - If not an error is returned in order to avoid overwriting memory. */ - if(RxBufferLength <= BufferSize) - { - return SL_ERROR_NETAPP_RX_BUFFER_LENGTH_ERROR; - } - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.RxPayloadLen = BufferSize; - CmdExt.pRxPayload = (_u8 *)pBuffer; - - Msg.Cmd.IndexOffest = IndexOffest; - Msg.Cmd.MaxServiceCount = MaxServiceCount; - Msg.Cmd.Flags = Flags; - Msg.Cmd.Padding = 0; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlGetServiceListeCtrl, &Msg, &CmdExt)); - retVal = Msg.Rsp.status; - - return (_i16)retVal; -} - -#endif - -/*****************************************************************************/ -/* sl_mDNSRegisterService */ -/*****************************************************************************/ -/* - * The below struct depicts the constant parameters of the command/API RegisterService. - * - 1. ServiceLen - The length of the service should be smaller than NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH. - 2. TextLen - The length of the text should be smaller than NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH. - 3. port - The port on this target host. - 4. TTL - The TTL of the service - 5. Options - bitwise parameters: - bit 0 - is unique (means if the service needs to be unique) - bit 31 - for internal use if the service should be added or deleted (set means ADD). - bit 1-30 for future. - - NOTE: - - 1. There are another variable parameter is this API which is the service name and the text. - 2. According to now there is no warning and Async event to user on if the service is a unique. -* - */ - - -typedef struct -{ - _u8 ServiceNameLen; - _u8 TextLen; - _u16 Port; - _u32 TTL; - _u32 Options; -}NetappMdnsSetService_t; - -typedef union -{ - NetappMdnsSetService_t Cmd; - _BasicResponse_t Rsp; -}_SlNetappMdnsRegisterServiceMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_NetAppMDNSRegisterUnregisterService) - -const _SlCmdCtrl_t _SlRegisterServiceCtrl = -{ - SL_OPCODE_NETAPP_MDNSREGISTERSERVICE, - sizeof(NetappMdnsSetService_t), - sizeof(_BasicResponse_t) -}; - -/****************************************************************************** - - sl_NetAppMDNSRegisterService - - CALLER user from its host - - - DESCRIPTION: - Add/delete service - The function manipulates the command that register the service and call - to the NWP in order to add/delete the service to/from the mDNS package and to/from the DB. - - This register service is a service offered by the application. - This unregister service is a service offered by the application before. - - The service name should be full service name according to RFC - of the DNS-SD - means the value in name field in SRV answer. - - Example for service name: - 1. PC1._ipp._tcp.local - 2. PC2_server._ftp._tcp.local - - If the option is_unique is set, mDNS probes the service name to make sure - it is unique before starting to announce the service on the network. - Instance is the instance portion of the service name. - - - - - PARAMETERS: - - The command is from constant parameters and variables parameters. - - Constant parameters are: - - ServiceLen - The length of the service. - TextLen - The length of the service should be smaller than 64. - port - The port on this target host. - TTL - The TTL of the service - Options - bitwise parameters: - bit 0 - is unique (means if the service needs to be unique) - bit 31 - for internal use if the service should be added or deleted (set means ADD). - bit 1-30 for future. - - The variables parameters are: - - Service name(full service name) - The service name. - Example for service name: - 1. PC1._ipp._tcp.local - 2. PC2_server._ftp._tcp.local - - Text - The description of the service. - should be as mentioned in the RFC - (according to type of the service IPP,FTP...) - - NOTE - pay attention - - 1. Temporary - there is an allocation on stack of internal buffer. - Its size is NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH. - It means that the sum of the text length and service name length cannot be bigger than - NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH. - If it is - An error is returned. - - 2. According to now from certain constraints the variables parameters are set in the - attribute part (contain constant parameters) - - - - RETURNS: Status - the immediate response of the command status. - 0 means success. - - - -******************************************************************************/ -_i16 sl_NetAppMDNSRegisterUnregisterService( const _i8* pServiceName, - const _u8 ServiceNameLen, - const _i8* pText, - const _u8 TextLen, - const _u16 Port, - const _u32 TTL, - const _u32 Options) - -{ - _SlNetappMdnsRegisterServiceMsg_u Msg; - _SlCmdExt_t CmdExt ; - _i8 ServiceNameAndTextBuffer[NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH]; - _i8 *TextPtr; - - /* - - NOTE - pay attention - - 1. Temporary - there is an allocation on stack of internal buffer. - Its size is NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH. - It means that the sum of the text length and service name length cannot be bigger than - NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH. - If it is - An error is returned. - - 2. According to now from certain constraints the variables parameters are set in the - attribute part (contain constant parameters) - - - */ - - /*build the attribute part of the command. - It contains the constant parameters of the command*/ - - Msg.Cmd.ServiceNameLen = ServiceNameLen; - Msg.Cmd.Options = Options; - Msg.Cmd.Port = Port; - Msg.Cmd.TextLen = TextLen; - Msg.Cmd.TTL = TTL; - - /*Build the payload part of the command - Copy the service name and text to one buffer. - NOTE - pay attention - The size of the service length + the text length should be smaller than 255, - Until the simplelink drive supports to variable length through SPI command. */ - if(TextLen + ServiceNameLen > (NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH - 1 )) /*-1 is for giving a place to set null termination at the end of the text*/ - { - return -1; - } - - _SlDrvMemZero(ServiceNameAndTextBuffer, NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH); - - - /*Copy the service name*/ - sl_Memcpy(ServiceNameAndTextBuffer, - pServiceName, - ServiceNameLen); - - if(TextLen > 0 ) - { - - TextPtr = &ServiceNameAndTextBuffer[ServiceNameLen]; - /*Copy the text just after the service name*/ - sl_Memcpy(TextPtr, - pText, - TextLen); - - - } - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.TxPayloadLen = (TextLen + ServiceNameLen); - CmdExt.pTxPayload = (_u8 *)ServiceNameAndTextBuffer; - - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlRegisterServiceCtrl, &Msg, &CmdExt)); - - return (_i16)Msg.Rsp.status; - - -} -#endif - -/**********************************************************************************************/ -#if _SL_INCLUDE_FUNC(sl_NetAppMDNSRegisterService) - -_i16 sl_NetAppMDNSRegisterService( const _i8* pServiceName, - const _u8 ServiceNameLen, - const _i8* pText, - const _u8 TextLen, - const _u16 Port, - const _u32 TTL, - _u32 Options) - -{ - - /* - - NOTE - pay attention - - 1. Temporary - there is an allocation on stack of internal buffer. - Its size is NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH. - It means that the sum of the text length and service name length cannot be bigger than - NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH. - If it is - An error is returned. - - 2. According to now from certain constraints the variables parameters are set in the - attribute part (contain constant parameters) - - */ - - /*Set the add service bit in the options parameter. - In order not use different opcodes for the register service and unregister service - bit 31 in option is taken for this purpose. if it is set it means in NWP that the service should be added - if it is cleared it means that the service should be deleted and there is only meaning to pServiceName - and ServiceNameLen values. */ - Options |= NETAPP_MDNS_OPTIONS_ADD_SERVICE_BIT; - - return sl_NetAppMDNSRegisterUnregisterService( pServiceName, - ServiceNameLen, - pText, - TextLen, - Port, - TTL, - Options); - - -} -#endif -/**********************************************************************************************/ - - - -/**********************************************************************************************/ -#if _SL_INCLUDE_FUNC(sl_NetAppMDNSUnRegisterService) - -_i16 sl_NetAppMDNSUnRegisterService( const _i8* pServiceName, - const _u8 ServiceNameLen) - - -{ - _u32 Options = 0; - - /* - - NOTE - pay attention - - The size of the service length should be smaller than 255, - Until the simplelink drive supports to variable length through SPI command. - - - */ - - /*Clear the add service bit in the options parameter. - In order not use different opcodes for the register service and unregister service - bit 31 in option is taken for this purpose. if it is set it means in NWP that the service should be added - if it is cleared it means that the service should be deleted and there is only meaning to pServiceName - and ServiceNameLen values.*/ - - Options &= (~NETAPP_MDNS_OPTIONS_ADD_SERVICE_BIT); - - return sl_NetAppMDNSRegisterUnregisterService( pServiceName, - ServiceNameLen, - NULL, - 0, - 0, - 0, - Options); - - -} -#endif -/**********************************************************************************************/ - - - -/*****************************************************************************/ -/* sl_DnsGetHostByService */ -/*****************************************************************************/ -/* - * The below struct depicts the constant parameters of the command/API sl_DnsGetHostByService. - * - 1. ServiceLen - The length of the service should be smaller than 255. - 2. AddrLen - TIPv4 or IPv6 (SL_AF_INET , SL_AF_INET6). -* - */ - -typedef struct -{ - _u8 ServiceLen; - _u8 AddrLen; - _u16 Padding; -}_GetHostByServiceCommand_t; - - - -/* - * The below structure depict the constant parameters that are returned in the Async event answer - * according to command/API sl_DnsGetHostByService for IPv4 and IPv6. - * - 1Status - The status of the response. - 2.Address - Contains the IP address of the service. - 3.Port - Contains the port of the service. - 4.TextLen - Contains the max length of the text that the user wants to get. - it means that if the test of service is bigger that its value than - the text is cut to inout_TextLen value. - Output: Contain the length of the text that is returned. Can be full text or part - of the text (see above). - -* - */ -typedef struct -{ - _u16 Status; - _u16 TextLen; - _u32 Port; - _u32 Address; -}_GetHostByServiceIPv4AsyncResponse_t; - - -typedef struct -{ - _u16 Status; - _u16 TextLen; - _u32 Port; - _u32 Address[4]; -}_GetHostByServiceIPv6AsyncResponse_t; - - -typedef union -{ - _GetHostByServiceIPv4AsyncResponse_t IpV4; - _GetHostByServiceIPv6AsyncResponse_t IpV6; -}_GetHostByServiceAsyncResponseAttribute_u; - -/* - * The below struct contains pointers to the output parameters that the user gives - * - */ -typedef struct -{ - _i16 Status; - _u32 *out_pAddr; - _u32 *out_pPort; - _u16 *inout_TextLen; /* in: max len , out: actual len */ - _i8 *out_pText; -}_GetHostByServiceAsyncResponse_t; - - -typedef union -{ - _GetHostByServiceCommand_t Cmd; - _BasicResponse_t Rsp; -}_SlGetHostByServiceMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_NetAppDnsGetHostByService) - -const _SlCmdCtrl_t _SlGetHostByServiceCtrl = -{ - SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICE, - sizeof(_GetHostByServiceCommand_t), - sizeof(_BasicResponse_t) -}; - -/******************************************************************************/ - -_i32 sl_NetAppDnsGetHostByService(_i8 *pServiceName, /* string containing all (or only part): name + subtype + service */ - const _u8 ServiceLen, - const _u8 Family, /* 4-IPv4 , 16-IPv6 */ - _u32 pAddr[], - _u32 *pPort, - _u16 *pTextLen, /* in: max len , out: actual len */ - _i8 *pText - ) -{ - _SlGetHostByServiceMsg_u Msg; - _SlCmdExt_t CmdExt ; - _GetHostByServiceAsyncResponse_t AsyncRsp; - _u8 ObjIdx = MAX_CONCURRENT_ACTIONS; - -/* - Note: - 1. The return's attributes are belonged to first service that is found. - It can be other services with the same service name will response to - the query. The results of these responses are saved in the peer cache of the NWP, and - should be read by another API. - - 2. Text length can be 120 bytes only - not more - It is because of constraints in the NWP on the buffer that is allocated for the Async event. - - 3.The API waits to Async event by blocking. It means that the API is finished only after an Async event - is sent by the NWP. - - 4.No rolling option!!! - only PTR type is sent. - - -*/ - /*build the attribute part of the command. - It contains the constant parameters of the command */ - - Msg.Cmd.ServiceLen = ServiceLen; - Msg.Cmd.AddrLen = Family; - - /*Build the payload part of the command - Copy the service name and text to one buffer.*/ - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.TxPayloadLen = ServiceLen; - CmdExt.pTxPayload = (_u8 *)pServiceName; - - /*set pointers to the output parameters (the returned parameters). - This pointers are belonged to local struct that is set to global Async response parameter. - It is done in order not to run more than one sl_DnsGetHostByService at the same time. - The API should be run only if global parameter is pointed to NULL. */ - AsyncRsp.out_pText = pText; - AsyncRsp.inout_TextLen = (_u16* )pTextLen; - AsyncRsp.out_pPort = pPort; - AsyncRsp.out_pAddr = (_u32 *)pAddr; - - - ObjIdx = _SlDrvProtectAsyncRespSetting((_u8*)&AsyncRsp, GETHOSYBYSERVICE_ID, SL_MAX_SOCKETS); - - if (MAX_CONCURRENT_ACTIONS == ObjIdx) - { - return SL_POOL_IS_EMPTY; - } - - - if (SL_AF_INET6 == Family) - { - g_pCB->ObjPool[ObjIdx].AdditionalData |= SL_NETAPP_FAMILY_MASK; - } - /* Send the command */ - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlGetHostByServiceCtrl, &Msg, &CmdExt)); - - - - /* If the immediate reponse is O.K. than wait for aSYNC event response. */ - if(SL_RET_CODE_OK == Msg.Rsp.status) - { - _SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj); - - /* If we are - it means that Async event was sent. - The results are copied in the Async handle return functions */ - - Msg.Rsp.status = AsyncRsp.Status; - } - - _SlDrvReleasePoolObj(ObjIdx); - return Msg.Rsp.status; -} -#endif - -/******************************************************************************/ - -/****************************************************************************** - _sl_HandleAsync_DnsGetHostByService - - CALLER NWP - Async event on sl_DnsGetHostByService with IPv4 Family - - - DESCRIPTION: - - Async event on sl_DnsGetHostByService command with IPv4 Family. - Return service attributes like IP address, port and text according to service name. - The user sets a service name Full/Part (see example below), and should get the: - 1. IP of the service - 2. The port of service. - 3. The text of service. - - Hence it can make a connection to the specific service and use it. - It is similar to get host by name method. - - It is done by a single shot query with PTR type on the service name. - - - - Note: - 1. The return's attributes are belonged to first service that is found. - It can be other services with the same service name will response to - the query. The results of these responses are saved in the peer cache of the NWP, and - should be read by another API. - - - PARAMETERS: - - pVoidBuf - is point to opcode of the event. - it contains the outputs that are given to the user - - outputs description: - - 1.out_pAddr[] - output: Contain the IP address of the service. - 2.out_pPort - output: Contain the port of the service. - 3.inout_TextLen - Input: Contain the max length of the text that the user wants to get. - it means that if the test of service is bigger that its value than - the text is cut to inout_TextLen value. - Output: Contain the length of the text that is returned. Can be full text or part - of the text (see above). - - 4.out_pText - Contain the text of the service (full or part see above- inout_TextLen description). - - * - - - RETURNS: success or fail. - - - - - -******************************************************************************/ -#ifndef SL_TINY_EXT -void _sl_HandleAsync_DnsGetHostByService(void *pVoidBuf) -{ - - _GetHostByServiceAsyncResponse_t* Res; - _u16 TextLen; - _u16 UserTextLen; - - - /*pVoidBuf - is point to opcode of the event.*/ - - /*set pMsgArgs to point to the attribute of the event.*/ - _GetHostByServiceIPv4AsyncResponse_t *pMsgArgs = (_GetHostByServiceIPv4AsyncResponse_t *)_SL_RESP_ARGS_START(pVoidBuf); - - VERIFY_SOCKET_CB(NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs); - - /*IPv6*/ - if(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].AdditionalData & SL_NETAPP_FAMILY_MASK) - { - return; - } - /*IPv4*/ - else - { - /************************************************************************************************* - - 1. Copy the attribute part of the evnt to the attribute part of the response - sl_Memcpy(g_pCB->GetHostByServiceCB.pAsyncRsp, pMsgArgs, sizeof(_GetHostByServiceIPv4AsyncResponse_t)); - - set to TextLen the text length of the service.*/ - TextLen = pMsgArgs->TextLen; - - /*Res pointed to mDNS global object struct */ - Res = (_GetHostByServiceAsyncResponse_t*)g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs; - - - - /*It is 4 bytes so we avoid from memcpy*/ - Res->out_pAddr[0] = pMsgArgs->Address; - Res->out_pPort[0] = pMsgArgs->Port; - Res->Status = pMsgArgs->Status; - - /*set to TextLen the text length of the user (input fromthe user).*/ - UserTextLen = Res->inout_TextLen[0]; - - /*Cut the service text if the user requested for smaller text.*/ - UserTextLen = (TextLen <= UserTextLen) ? TextLen : UserTextLen; - Res->inout_TextLen[0] = UserTextLen ; - - /************************************************************************************************** - - 2. Copy the payload part of the evnt (the text) to the payload part of the response - the lenght of the copy is according to the text length in the attribute part. */ - - - sl_Memcpy(Res->out_pText , - (_i8 *)(& pMsgArgs[1]) , /* & pMsgArgs[1] -> 1st byte after the fixed header = 1st byte of variable text.*/ - UserTextLen ); - - - /**************************************************************************************************/ - - _SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj); - return; - } -} - -/*****************************************************************************/ -/* _sl_HandleAsync_DnsGetHostByAddr */ -/*****************************************************************************/ -void _sl_HandleAsync_DnsGetHostByAddr(void *pVoidBuf) -{ - SL_TRACE0(DBG_MSG, MSG_303, "STUB: _sl_HandleAsync_DnsGetHostByAddr not implemented yet!"); - return; -} -#endif - -/*****************************************************************************/ -/* sl_DnsGetHostByName */ -/*****************************************************************************/ -typedef union -{ - _GetHostByNameIPv4AsyncResponse_t IpV4; - _GetHostByNameIPv6AsyncResponse_t IpV6; -}_GetHostByNameAsyncResponse_u; - -typedef union -{ - _GetHostByNameCommand_t Cmd; - _BasicResponse_t Rsp; -}_SlGetHostByNameMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_NetAppDnsGetHostByName) -const _SlCmdCtrl_t _SlGetHostByNameCtrl = -{ - SL_OPCODE_NETAPP_DNSGETHOSTBYNAME, - sizeof(_GetHostByNameCommand_t), - sizeof(_BasicResponse_t) -}; - -_i16 sl_NetAppDnsGetHostByName(_i8 * hostname,const _u16 usNameLen, _u32* out_ip_addr,const _u8 family) -{ - _SlGetHostByNameMsg_u Msg; - _SlCmdExt_t ExtCtrl; - _GetHostByNameAsyncResponse_u AsyncRsp; - _u8 ObjIdx = MAX_CONCURRENT_ACTIONS; - - - _SlDrvResetCmdExt(&ExtCtrl); - ExtCtrl.TxPayloadLen = usNameLen; - ExtCtrl.pTxPayload = (_u8 *)hostname; - - Msg.Cmd.Len = usNameLen; - Msg.Cmd.family = family; - - /*Use Obj to issue the command, if not available try later */ - ObjIdx = (_u8)_SlDrvWaitForPoolObj(GETHOSYBYNAME_ID,SL_MAX_SOCKETS); - if (MAX_CONCURRENT_ACTIONS == ObjIdx) - { - return SL_POOL_IS_EMPTY; - } - - _SlDrvProtectionObjLockWaitForever(); - - g_pCB->ObjPool[ObjIdx].pRespArgs = (_u8 *)&AsyncRsp; - /*set bit to indicate IPv6 address is expected */ - if (SL_AF_INET6 == family) - { - g_pCB->ObjPool[ObjIdx].AdditionalData |= SL_NETAPP_FAMILY_MASK; - } - - _SlDrvProtectionObjUnLock(); - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlGetHostByNameCtrl, &Msg, &ExtCtrl)); - - if(SL_RET_CODE_OK == Msg.Rsp.status) - { - _SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj); - - Msg.Rsp.status = AsyncRsp.IpV4.status; - - if(SL_OS_RET_CODE_OK == (_i16)Msg.Rsp.status) - { - sl_Memcpy((_i8 *)out_ip_addr, - (_i8 *)&AsyncRsp.IpV4.ip0, - (SL_AF_INET == family) ? SL_IPV4_ADDRESS_SIZE : SL_IPV6_ADDRESS_SIZE); - } - } - _SlDrvReleasePoolObj(ObjIdx); - return Msg.Rsp.status; -} -#endif - - -/******************************************************************************/ -/* _sl_HandleAsync_DnsGetHostByName */ -/******************************************************************************/ -void _sl_HandleAsync_DnsGetHostByName(void *pVoidBuf) -{ - _GetHostByNameIPv4AsyncResponse_t *pMsgArgs = (_GetHostByNameIPv4AsyncResponse_t *)_SL_RESP_ARGS_START(pVoidBuf); - - _SlDrvProtectionObjLockWaitForever(); - - VERIFY_SOCKET_CB(NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs); - - /*IPv6 */ - if(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].AdditionalData & SL_NETAPP_FAMILY_MASK) - { - sl_Memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(_GetHostByNameIPv6AsyncResponse_t)); - } - /*IPv4 */ - else - { - sl_Memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(_GetHostByNameIPv4AsyncResponse_t)); - } - _SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj); - _SlDrvProtectionObjUnLock(); - return; -} - - -#ifndef SL_TINY_EXT -void CopyPingResultsToReport(_PingReportResponse_t *pResults,SlPingReport_t *pReport) -{ - pReport->PacketsSent = pResults->numSendsPings; - pReport->PacketsReceived = pResults->numSuccsessPings; - pReport->MinRoundTime = pResults->rttMin; - pReport->MaxRoundTime = pResults->rttMax; - pReport->AvgRoundTime = pResults->rttAvg; - pReport->TestTime = pResults->testTime; -} - -/*****************************************************************************/ -/* _sl_HandleAsync_PingResponse */ -/*****************************************************************************/ -void _sl_HandleAsync_PingResponse(void *pVoidBuf) -{ - _PingReportResponse_t *pMsgArgs = (_PingReportResponse_t *)_SL_RESP_ARGS_START(pVoidBuf); - SlPingReport_t pingReport; - - if(pPingCallBackFunc) - { - CopyPingResultsToReport(pMsgArgs,&pingReport); - pPingCallBackFunc(&pingReport); - } - else - { - - _SlDrvProtectionObjLockWaitForever(); - - VERIFY_SOCKET_CB(NULL != g_pCB->PingCB.PingAsync.pAsyncRsp); - - if (NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs) - { - sl_Memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(_PingReportResponse_t)); - _SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj); - } - _SlDrvProtectionObjUnLock(); - } - return; -} -#endif - -/*****************************************************************************/ -/* sl_PingStart */ -/*****************************************************************************/ -typedef union -{ - _PingStartCommand_t Cmd; - _PingReportResponse_t Rsp; -}_SlPingStartMsg_u; - - -typedef enum -{ - CMD_PING_TEST_RUNNING = 0, - CMD_PING_TEST_STOPPED -}_SlPingStatus_e; - - -#if _SL_INCLUDE_FUNC(sl_NetAppPingStart) -_i16 sl_NetAppPingStart(const SlPingStartCommand_t* pPingParams,const _u8 family,SlPingReport_t *pReport,const P_SL_DEV_PING_CALLBACK pPingCallback) -{ - _SlCmdCtrl_t CmdCtrl = {0, sizeof(_PingStartCommand_t), sizeof(_BasicResponse_t)}; - _SlPingStartMsg_u Msg; - _PingReportResponse_t PingRsp; - _u8 ObjIdx = MAX_CONCURRENT_ACTIONS; - - if( 0 == pPingParams->Ip ) - {/* stop any ongoing ping */ - return _SlDrvBasicCmd(SL_OPCODE_NETAPP_PINGSTOP); - } - - if(SL_AF_INET == family) - { - CmdCtrl.Opcode = SL_OPCODE_NETAPP_PINGSTART; - sl_Memcpy(&Msg.Cmd.ip0, &pPingParams->Ip, SL_IPV4_ADDRESS_SIZE); - } - else - { - CmdCtrl.Opcode = SL_OPCODE_NETAPP_PINGSTART_V6; - sl_Memcpy(&Msg.Cmd.ip0, &pPingParams->Ip, SL_IPV6_ADDRESS_SIZE); - } - - Msg.Cmd.pingIntervalTime = pPingParams->PingIntervalTime; - Msg.Cmd.PingSize = pPingParams->PingSize; - Msg.Cmd.pingRequestTimeout = pPingParams->PingRequestTimeout; - Msg.Cmd.totalNumberOfAttempts = pPingParams->TotalNumberOfAttempts; - Msg.Cmd.flags = pPingParams->Flags; - - - if( pPingCallback ) - { - pPingCallBackFunc = pPingCallback; - } - else - { - /*Use Obj to issue the command, if not available try later */ - ObjIdx = (_u8)_SlDrvWaitForPoolObj(PING_ID,SL_MAX_SOCKETS); - if (MAX_CONCURRENT_ACTIONS == ObjIdx) - { - return SL_POOL_IS_EMPTY; - } - OSI_RET_OK_CHECK(sl_LockObjLock(&g_pCB->ProtectionLockObj, SL_OS_WAIT_FOREVER)); - /* async response handler for non callback mode */ - g_pCB->ObjPool[ObjIdx].pRespArgs = (_u8 *)&PingRsp; - pPingCallBackFunc = NULL; - OSI_RET_OK_CHECK(sl_LockObjUnlock(&g_pCB->ProtectionLockObj)); - } - - - VERIFY_RET_OK(_SlDrvCmdOp(&CmdCtrl, &Msg, NULL)); - /*send the command*/ - if(CMD_PING_TEST_RUNNING == (_i16)Msg.Rsp.status || CMD_PING_TEST_STOPPED == (_i16)Msg.Rsp.status ) - { - /* block waiting for results if no callback function is used */ - if( NULL == pPingCallback ) - { - _SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj); - - if( SL_OS_RET_CODE_OK == (_i16)PingRsp.status ) - { - CopyPingResultsToReport(&PingRsp,pReport); - } - _SlDrvReleasePoolObj(ObjIdx); - } - } - else - { /* ping failure, no async response */ - if( NULL == pPingCallback ) - { - _SlDrvReleasePoolObj(ObjIdx); - } - } - - return Msg.Rsp.status; -} -#endif - -/*****************************************************************************/ -/* sl_NetAppSet */ -/*****************************************************************************/ -typedef union -{ - _NetAppSetGet_t Cmd; - _BasicResponse_t Rsp; -}_SlNetAppMsgSet_u; - - -#if _SL_INCLUDE_FUNC(sl_NetAppSet) - -const _SlCmdCtrl_t _SlNetAppSetCmdCtrl = -{ - SL_OPCODE_NETAPP_NETAPPSET, - sizeof(_NetAppSetGet_t), - sizeof(_BasicResponse_t) -}; - -_i32 sl_NetAppSet(const _u8 AppId ,const _u8 Option,const _u8 OptionLen,const _u8 *pOptionValue) -{ - _SlNetAppMsgSet_u Msg; - _SlCmdExt_t CmdExt; - - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.TxPayloadLen = (OptionLen+3) & (~3); - CmdExt.pTxPayload = (_u8 *)pOptionValue; - - - Msg.Cmd.AppId = AppId; - Msg.Cmd.ConfigLen = OptionLen; - Msg.Cmd.ConfigOpt = Option; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetAppSetCmdCtrl, &Msg, &CmdExt)); - - return (_i16)Msg.Rsp.status; -} -#endif - -/*****************************************************************************/ -/* sl_NetAppSendTokenValue */ -/*****************************************************************************/ -typedef union -{ - sl_NetAppHttpServerSendToken_t Cmd; - _BasicResponse_t Rsp; -}_SlNetAppMsgSendTokenValue_u; - - - -#if defined(sl_HttpServerCallback) || defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS) -const _SlCmdCtrl_t _SlNetAppSendTokenValueCmdCtrl = -{ - SL_OPCODE_NETAPP_HTTPSENDTOKENVALUE, - sizeof(sl_NetAppHttpServerSendToken_t), - sizeof(_BasicResponse_t) -}; - -_u16 _sl_NetAppSendTokenValue(slHttpServerData_t * Token_value) -{ - _SlNetAppMsgSendTokenValue_u Msg; - _SlCmdExt_t CmdExt; - - CmdExt.TxPayloadLen = (Token_value->value_len+3) & (~3); - CmdExt.RxPayloadLen = 0; - CmdExt.pTxPayload = (_u8 *) Token_value->token_value; - CmdExt.pRxPayload = NULL; - - Msg.Cmd.token_value_len = Token_value->value_len; - Msg.Cmd.token_name_len = Token_value->name_len; - sl_Memcpy(&Msg.Cmd.token_name[0], Token_value->token_name, Token_value->name_len); - - - VERIFY_RET_OK(_SlDrvCmdSend((_SlCmdCtrl_t *)&_SlNetAppSendTokenValueCmdCtrl, &Msg, &CmdExt)); - - return Msg.Rsp.status; -} -#endif - - -/*****************************************************************************/ -/* sl_NetAppGet */ -/*****************************************************************************/ -typedef union -{ - _NetAppSetGet_t Cmd; - _NetAppSetGet_t Rsp; -}_SlNetAppMsgGet_u; - - -#if _SL_INCLUDE_FUNC(sl_NetAppGet) -const _SlCmdCtrl_t _SlNetAppGetCmdCtrl = -{ - SL_OPCODE_NETAPP_NETAPPGET, - sizeof(_NetAppSetGet_t), - sizeof(_NetAppSetGet_t) -}; - -_i32 sl_NetAppGet(const _u8 AppId,const _u8 Option,_u8 *pOptionLen, _u8 *pOptionValue) -{ - _SlNetAppMsgGet_u Msg; - _SlCmdExt_t CmdExt; - - if (*pOptionLen == 0) - { - return SL_EZEROLEN; - } - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.RxPayloadLen = *pOptionLen; - CmdExt.pRxPayload = (_u8 *)pOptionValue; - - Msg.Cmd.AppId = AppId; - Msg.Cmd.ConfigOpt = Option; - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetAppGetCmdCtrl, &Msg, &CmdExt)); - - - if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) - { - *pOptionLen = (_u8)CmdExt.RxPayloadLen; - return SL_ESMALLBUF; - } - else - { - *pOptionLen = (_u8)CmdExt.ActualRxPayloadLen; - } - - return (_i16)Msg.Rsp.Status; -} -#endif - - -/*****************************************************************************/ -/* _SlDrvNetAppEventHandler */ -/*****************************************************************************/ -void _SlDrvNetAppEventHandler(void* pArgs) -{ - _SlResponseHeader_t *pHdr = (_SlResponseHeader_t *)pArgs; -#if defined(sl_HttpServerCallback) || defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS) - SlHttpServerEvent_t httpServerEvent; - SlHttpServerResponse_t httpServerResponse; -#endif - - switch(pHdr->GenHeader.Opcode) - { - case SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE: - case SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE_V6: - _sl_HandleAsync_DnsGetHostByName(pArgs); - break; -#ifndef SL_TINY_EXT - case SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICEASYNCRESPONSE: - case SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICEASYNCRESPONSE_V6: - _sl_HandleAsync_DnsGetHostByService(pArgs); - break; - case SL_OPCODE_NETAPP_PINGREPORTREQUESTRESPONSE: - _sl_HandleAsync_PingResponse(pArgs); - break; -#endif - -#if defined(sl_HttpServerCallback) || defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS) - case SL_OPCODE_NETAPP_HTTPGETTOKENVALUE: - { - _u8 *pTokenName; - slHttpServerData_t Token_value; - sl_NetAppHttpServerGetToken_t *httpGetToken = (sl_NetAppHttpServerGetToken_t *)_SL_RESP_ARGS_START(pHdr); - pTokenName = (_u8 *)((sl_NetAppHttpServerGetToken_t *)httpGetToken + 1); - - httpServerResponse.Response = SL_NETAPP_HTTPSETTOKENVALUE; - httpServerResponse.ResponseData.token_value.len = MAX_TOKEN_VALUE_LEN; - - /* Reuse the async buffer for getting the token value response from the user */ - httpServerResponse.ResponseData.token_value.data = (_u8 *)_SL_RESP_ARGS_START(pHdr) + MAX_TOKEN_NAME_LEN; - - httpServerEvent.Event = SL_NETAPP_HTTPGETTOKENVALUE_EVENT; - httpServerEvent.EventData.httpTokenName.len = httpGetToken->token_name_len; - httpServerEvent.EventData.httpTokenName.data = pTokenName; - - Token_value.token_name = pTokenName; - - _SlDrvHandleHttpServerEvents (&httpServerEvent, &httpServerResponse); - - Token_value.value_len = httpServerResponse.ResponseData.token_value.len; - Token_value.name_len = httpServerEvent.EventData.httpTokenName.len; - Token_value.token_value = httpServerResponse.ResponseData.token_value.data; - - - _sl_NetAppSendTokenValue(&Token_value); - } - break; - - case SL_OPCODE_NETAPP_HTTPPOSTTOKENVALUE: - { - _u8 *pPostParams; - - sl_NetAppHttpServerPostToken_t *httpPostTokenArgs = (sl_NetAppHttpServerPostToken_t *)_SL_RESP_ARGS_START(pHdr); - pPostParams = (_u8 *)((sl_NetAppHttpServerPostToken_t *)httpPostTokenArgs + 1); - - httpServerEvent.Event = SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT; - - httpServerEvent.EventData.httpPostData.action.len = httpPostTokenArgs->post_action_len; - httpServerEvent.EventData.httpPostData.action.data = pPostParams; - pPostParams+=httpPostTokenArgs->post_action_len; - - httpServerEvent.EventData.httpPostData.token_name.len = httpPostTokenArgs->token_name_len; - httpServerEvent.EventData.httpPostData.token_name.data = pPostParams; - pPostParams+=httpPostTokenArgs->token_name_len; - - httpServerEvent.EventData.httpPostData.token_value.len = httpPostTokenArgs->token_value_len; - httpServerEvent.EventData.httpPostData.token_value.data = pPostParams; - - httpServerResponse.Response = SL_NETAPP_RESPONSE_NONE; - - _SlDrvHandleHttpServerEvents (&httpServerEvent, &httpServerResponse); - - } - break; -#endif - - - default: - SL_ERROR_TRACE2(MSG_305, "ASSERT: _SlDrvNetAppEventHandler : invalid opcode = 0x%x = %1", pHdr->GenHeader.Opcode, pHdr->GenHeader.Opcode); - VERIFY_PROTOCOL(0); - } -} - diff --git a/drivers/cc3100/src/netcfg.c b/drivers/cc3100/src/netcfg.c deleted file mode 100644 index 3674e0720e..0000000000 --- a/drivers/cc3100/src/netcfg.c +++ /dev/null @@ -1,150 +0,0 @@ -/* -* netcfg.c - CC31xx/CC32xx Host Driver Implementation -* -* Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ -* -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - - - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" -#include "protocol.h" -#include "driver.h" - -/*****************************************************************************/ -/* sl_NetCfgSet */ -/*****************************************************************************/ -typedef union -{ - _NetCfgSetGet_t Cmd; - _BasicResponse_t Rsp; -}_SlNetCfgMsgSet_u; - -#if _SL_INCLUDE_FUNC(sl_NetCfgSet) - -const _SlCmdCtrl_t _SlNetCfgSetCmdCtrl = -{ - SL_OPCODE_DEVICE_NETCFG_SET_COMMAND, - sizeof(_NetCfgSetGet_t), - sizeof(_BasicResponse_t) -}; - -_i32 sl_NetCfgSet(const _u8 ConfigId ,const _u8 ConfigOpt,const _u8 ConfigLen,const _u8 *pValues) -{ - _SlNetCfgMsgSet_u Msg; - _SlCmdExt_t CmdExt; - - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.TxPayloadLen = (ConfigLen+3) & (~3); - CmdExt.pTxPayload = (_u8 *)pValues; - - - Msg.Cmd.ConfigId = ConfigId; - Msg.Cmd.ConfigLen = ConfigLen; - Msg.Cmd.ConfigOpt = ConfigOpt; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetCfgSetCmdCtrl, &Msg, &CmdExt)); - - return (_i16)Msg.Rsp.status; -} -#endif - - -/*****************************************************************************/ -/* sl_NetCfgGet */ -/*****************************************************************************/ -typedef union -{ - _NetCfgSetGet_t Cmd; - _NetCfgSetGet_t Rsp; -}_SlNetCfgMsgGet_u; - -#if _SL_INCLUDE_FUNC(sl_NetCfgGet) - -const _SlCmdCtrl_t _SlNetCfgGetCmdCtrl = -{ - SL_OPCODE_DEVICE_NETCFG_GET_COMMAND, - sizeof(_NetCfgSetGet_t), - sizeof(_NetCfgSetGet_t) -}; - -_i32 sl_NetCfgGet(const _u8 ConfigId, _u8 *pConfigOpt,_u8 *pConfigLen, _u8 *pValues) -{ - _SlNetCfgMsgGet_u Msg; - _SlCmdExt_t CmdExt; - - if (*pConfigLen == 0) - { - return SL_EZEROLEN; - } - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.RxPayloadLen = *pConfigLen; - CmdExt.pRxPayload = (_u8 *)pValues; - Msg.Cmd.ConfigLen = *pConfigLen; - Msg.Cmd.ConfigId = ConfigId; - - if( pConfigOpt ) - { - Msg.Cmd.ConfigOpt = (_u16)*pConfigOpt; - } - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetCfgGetCmdCtrl, &Msg, &CmdExt)); - - if( pConfigOpt ) - { - *pConfigOpt = (_u8)Msg.Rsp.ConfigOpt; - } - if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) - { - *pConfigLen = (_u8)CmdExt.RxPayloadLen; - if( SL_MAC_ADDRESS_GET == ConfigId ) - { - return SL_RET_CODE_OK; /* sp fix */ - } - else - { - return SL_ESMALLBUF; - } - } - else - { - *pConfigLen = (_u8)CmdExt.ActualRxPayloadLen; - } - - return (_i16)Msg.Rsp.Status; -} -#endif - diff --git a/drivers/cc3100/src/nonos.c b/drivers/cc3100/src/nonos.c deleted file mode 100644 index a20e895765..0000000000 --- a/drivers/cc3100/src/nonos.c +++ /dev/null @@ -1,171 +0,0 @@ -/* -* nonos.c - CC31xx/CC32xx Host Driver Implementation -* -* Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ -* -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - - - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" -#include "protocol.h" -#include "driver.h" - -#ifndef SL_PLATFORM_MULTI_THREADED - -#include "nonos.h" - -#ifndef SL_TINY_EXT -#define NONOS_MAX_SPAWN_ENTRIES 5 -#else -#define NONOS_MAX_SPAWN_ENTRIES 1 -#endif - - -typedef struct -{ - _SlSpawnEntryFunc_t pEntry; - void* pValue; -}_SlNonOsSpawnEntry_t; - -typedef struct -{ - _SlNonOsSpawnEntry_t SpawnEntries[NONOS_MAX_SPAWN_ENTRIES]; -}_SlNonOsCB_t; - -_SlNonOsCB_t g__SlNonOsCB; - - -_SlNonOsRetVal_t _SlNonOsSemSet(_SlNonOsSemObj_t* pSemObj , _SlNonOsSemObj_t Value) -{ - *pSemObj = Value; - return NONOS_RET_OK; -} - -_SlNonOsRetVal_t _SlNonOsSemGet(_SlNonOsSemObj_t* pSyncObj, _SlNonOsSemObj_t WaitValue, _SlNonOsSemObj_t SetValue, _SlNonOsTime_t Timeout) -{ -#ifdef _SlSyncWaitLoopCallback - _SlNonOsTime_t timeOutRequest = Timeout; -#endif - while (Timeout>0) - { - if (WaitValue == *pSyncObj) - { - *pSyncObj = SetValue; - break; - } - if (Timeout != NONOS_WAIT_FOREVER) - { - Timeout--; - } - _SlNonOsMainLoopTask(); -#ifdef _SlSyncWaitLoopCallback - if( (__NON_OS_SYNC_OBJ_SIGNAL_VALUE == WaitValue) && (timeOutRequest != NONOS_NO_WAIT) ) - { - if (WaitValue == *pSyncObj) - { - *pSyncObj = SetValue; - break; - } - _SlSyncWaitLoopCallback(); - } -#endif - } - - if (0 == Timeout) - { - return NONOS_RET_ERR; - } - else - { - return NONOS_RET_OK; - } -} - - -_SlNonOsRetVal_t _SlNonOsSpawn(_SlSpawnEntryFunc_t pEntry , void* pValue , _u32 flags) -{ - _i8 i = 0; - -#ifndef SL_TINY_EXT - for (i=0 ; ipEntry) - { - pE->pValue = pValue; - pE->pEntry = pEntry; -#ifndef SL_TINY_EXT - break; -#endif - } - } - - - return NONOS_RET_OK; -} - - -_SlNonOsRetVal_t _SlNonOsMainLoopTask(void) -{ - _i8 i=0; - - -#ifndef SL_TINY_EXT - for (i=0 ; ipEntry; - - if (NULL != pF) - { - if(RxIrqCnt != (g_pCB)->RxDoneCnt) - { - pF(0); /* (pValue) */ - } - - pE->pEntry = NULL; - pE->pValue = NULL; - } - } - - return NONOS_RET_OK; -} - - -#endif /*(SL_PLATFORM != SL_PLATFORM_NON_OS)*/ diff --git a/drivers/cc3100/src/socket.c b/drivers/cc3100/src/socket.c deleted file mode 100644 index 8ef9e09745..0000000000 --- a/drivers/cc3100/src/socket.c +++ /dev/null @@ -1,1150 +0,0 @@ -/* - * socket.c - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - - - - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" -#include "protocol.h" -#include "driver.h" - - -void _sl_BuildAddress(const SlSockAddr_t *addr, _SocketAddrCommand_u *pCmd); -void _sl_HandleAsync_Connect(void *pVoidBuf); - -#ifndef SL_TINY_EXT -void _sl_ParseAddress(_SocketAddrResponse_u *pRsp, SlSockAddr_t *addr, SlSocklen_t *addrlen); -void _sl_HandleAsync_Accept(void *pVoidBuf); -void _sl_HandleAsync_Select(void *pVoidBuf); -#endif -_u16 _sl_TruncatePayloadByProtocol(const _i16 pSd, const _u16 length); - -/*******************************************************************************/ -/* Functions */ -/*******************************************************************************/ - - - /* Note: parsing of family and port in the generic way for all IPV4, IPV6 and EUI48 */ - /* is possible as _i32 as these parameters are in the same offset and size for these */ - /* three families. */ -#define SL_SOCKET_PAYLOAD_BASE (1350) - -const _u8 _SlPayloadByProtocolLUT[16] = -{ - (1472 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_UDP_IPV4 */ - (1460 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_TCP_IPV4 */ - (1452 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_UDP_IPV6 */ - (1440 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_TCP_IPV6 */ - (1386 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_TCP_IPV4_SECURE */ - (1386 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_UDP_IPV4_SECURE */ - (1396 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_UDP_IPV6_SECURE */ - (1396 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_TCP_IPV6_SECURE */ - (1476 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_RAW_TRANCEIVER */ - (1514 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_RAW_PACKET */ - (1480 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_RAW_IP4 */ - (1480 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_RAW_IP6 */ - (1440 - SL_SOCKET_PAYLOAD_BASE), /* Default */ - (1440 - SL_SOCKET_PAYLOAD_BASE), /* Default */ - (1440 - SL_SOCKET_PAYLOAD_BASE), /* Default */ - (1440 - SL_SOCKET_PAYLOAD_BASE) /* Default */ -}; - - - -/* ******************************************************************************/ -/* _sl_BuildAddress */ -/* ******************************************************************************/ -void _sl_BuildAddress(const SlSockAddr_t *addr, _SocketAddrCommand_u *pCmd) -{ - - /* Note: parsing of family and port in the generic way for all IPV4, IPV6 and EUI48 - is possible as long as these parameters are in the same offset and size for these - three families. */ - pCmd->IpV4.FamilyAndFlags = (addr->sa_family << 4) & 0xF0; - pCmd->IpV4.port = ((SlSockAddrIn_t *)addr)->sin_port; - - if(SL_AF_INET == addr->sa_family) - { - pCmd->IpV4.address = ((SlSockAddrIn_t *)addr)->sin_addr.s_addr; - } - else if (SL_AF_INET6_EUI_48 == addr->sa_family ) - { - sl_Memcpy( pCmd->IpV6EUI48.address,((SlSockAddrIn6_t *)addr)->sin6_addr._S6_un._S6_u8, 6); - } -#ifdef SL_SUPPORT_IPV6 - else - { - sl_Memcpy(pCmd->IpV6.address, ((sockaddr_in6 *)addr)->sin6_addr._S6_un._S6_u32, 16 ); - } -#endif -} - - -/***************************************************************************** - _sl_TruncatePayloadByProtocol -*****************************************************************************/ -_u16 _sl_TruncatePayloadByProtocol(const _i16 sd, const _u16 length) -{ - unsigned int maxLength; - - - maxLength = SL_SOCKET_PAYLOAD_BASE + _SlPayloadByProtocolLUT[((sd & SL_SOCKET_PAYLOAD_TYPE_MASK) >> 4)]; - - - - if( length > maxLength ) - { - return maxLength; - } - else - { - return length; - } -} - -/*******************************************************************************/ -/* _sl_ParseAddress */ -/*******************************************************************************/ - -#ifndef SL_TINY_EXT -void _sl_ParseAddress(_SocketAddrResponse_u *pRsp, SlSockAddr_t *addr, SlSocklen_t *addrlen) -{ - /* Note: parsing of family and port in the generic way for all IPV4, IPV6 and EUI48 */ - /* is possible as long as these parameters are in the same offset and size for these */ - /* three families. */ - addr->sa_family = pRsp->IpV4.family; - ((SlSockAddrIn_t *)addr)->sin_port = pRsp->IpV4.port; - - *addrlen = (SL_AF_INET == addr->sa_family) ? sizeof(SlSockAddrIn_t) : sizeof(SlSockAddrIn6_t); - - if(SL_AF_INET == addr->sa_family) - { - ((SlSockAddrIn_t *)addr)->sin_addr.s_addr = pRsp->IpV4.address; - } - else if (SL_AF_INET6_EUI_48 == addr->sa_family ) - { - sl_Memcpy(((SlSockAddrIn6_t *)addr)->sin6_addr._S6_un._S6_u8, pRsp->IpV6EUI48.address, 6); - } -#ifdef SL_SUPPORT_IPV6 - else - { - sl_Memcpy(((sockaddr_in6 *)addr)->sin6_addr._S6_un._S6_u32, pRsp->IpV6.address, 16); - } -#endif -} - -#endif - -/*******************************************************************************/ -/* sl_Socket */ -/*******************************************************************************/ -typedef union -{ - _u32 Dummy; - _SocketCommand_t Cmd; - _SocketResponse_t Rsp; -}_SlSockSocketMsg_u; - - - -#if _SL_INCLUDE_FUNC(sl_Socket) - -const _SlCmdCtrl_t _SlSockSocketCmdCtrl = -{ - SL_OPCODE_SOCKET_SOCKET, - sizeof(_SocketCommand_t), - sizeof(_SocketResponse_t) -}; - -_i16 sl_Socket(_i16 Domain, _i16 Type, _i16 Protocol) -{ - _SlSockSocketMsg_u Msg; - - Msg.Cmd.Domain = (_u8)Domain; - Msg.Cmd.Type = (_u8)Type; - Msg.Cmd.Protocol = (_u8)Protocol; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlSockSocketCmdCtrl, &Msg, NULL)); - - if( Msg.Rsp.statusOrLen < 0 ) - { - return( Msg.Rsp.statusOrLen ); - } - else - { - return (_i16)((_u8)Msg.Rsp.sd); -} -} -#endif - -/*******************************************************************************/ -/* sl_Close */ -/*******************************************************************************/ -typedef union -{ - _CloseCommand_t Cmd; - _SocketResponse_t Rsp; -}_SlSockCloseMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_Close) - -const _SlCmdCtrl_t _SlSockCloseCmdCtrl = -{ - SL_OPCODE_SOCKET_CLOSE, - sizeof(_CloseCommand_t), - sizeof(_SocketResponse_t) -}; - -_i16 sl_Close(_i16 sd) -{ - _SlSockCloseMsg_u Msg; - - Msg.Cmd.sd = (_u8)sd; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlSockCloseCmdCtrl, &Msg, NULL)); - - return Msg.Rsp.statusOrLen; -} -#endif - -/*******************************************************************************/ -/* sl_Bind */ -/*******************************************************************************/ -typedef union -{ - _SocketAddrCommand_u Cmd; - _SocketResponse_t Rsp; -}_SlSockBindMsg_u; - -#if _SL_INCLUDE_FUNC(sl_Bind) -_i16 sl_Bind(_i16 sd, const SlSockAddr_t *addr, _i16 addrlen) -{ - _SlSockBindMsg_u Msg; - _SlCmdCtrl_t CmdCtrl = {0, 0, sizeof(_SocketResponse_t)}; - - switch(addr->sa_family) - { - case SL_AF_INET : - CmdCtrl.Opcode = SL_OPCODE_SOCKET_BIND; - CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv4Command_t); - break; -#ifndef SL_TINY_EXT - case SL_AF_INET6_EUI_48: - CmdCtrl.Opcode = SL_OPCODE_SOCKET_BIND_V6; - CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv6EUI48Command_t); - break; - -#ifdef SL_SUPPORT_IPV6 - case AF_INET6: - CmdCtrl.Opcode = SL_OPCODE_SOCKET_BIND_V6; - CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv6Command_t); - break; -#endif -#endif - - - case SL_AF_RF : - default: - return SL_RET_CODE_INVALID_INPUT; - } - - Msg.Cmd.IpV4.lenOrPadding = 0; - Msg.Cmd.IpV4.sd = (_u8)sd; - - _sl_BuildAddress(addr, &Msg.Cmd); - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&CmdCtrl, &Msg, NULL)); - - return Msg.Rsp.statusOrLen; -} -#endif - -/*******************************************************************************/ -/* sl_Sendto */ -/*******************************************************************************/ -typedef union -{ - _SocketAddrCommand_u Cmd; - /* no response for 'sendto' commands*/ -}_SlSendtoMsg_u; - -#if _SL_INCLUDE_FUNC(sl_SendTo) -_i16 sl_SendTo(_i16 sd, const void *pBuf, _i16 Len, _i16 flags, const SlSockAddr_t *to, SlSocklen_t tolen) -{ - _SlSendtoMsg_u Msg; - _SlCmdCtrl_t CmdCtrl = {0, 0, 0}; - _SlCmdExt_t CmdExt; - _u16 ChunkLen; - _i16 RetVal; - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.TxPayloadLen = (_u16)Len; - CmdExt.pTxPayload = (_u8 *)pBuf; - - switch(to->sa_family) - { - case SL_AF_INET: - CmdCtrl.Opcode = SL_OPCODE_SOCKET_SENDTO; - CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv4Command_t); - break; -#ifndef SL_TINY_EXT - case SL_AF_INET6_EUI_48: - CmdCtrl.Opcode = SL_OPCODE_SOCKET_BIND_V6; - CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv6EUI48Command_t); - break; -#ifdef SL_SUPPORT_IPV6 - case AF_INET6: - CmdCtrl.Opcode = SL_OPCODE_SOCKET_SENDTO_V6; - CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv6Command_t); - break; -#endif -#endif - case SL_AF_RF: - default: - return SL_RET_CODE_INVALID_INPUT; - } - - ChunkLen = _sl_TruncatePayloadByProtocol(sd,Len); - Msg.Cmd.IpV4.lenOrPadding = ChunkLen; - CmdExt.TxPayloadLen = ChunkLen; - - Msg.Cmd.IpV4.sd = (_u8)sd; - - _sl_BuildAddress(to, &Msg.Cmd); - - Msg.Cmd.IpV4.FamilyAndFlags |= flags & 0x0F; - - do - { - RetVal = _SlDrvDataWriteOp((_SlSd_t)sd, &CmdCtrl, &Msg, &CmdExt); - - if(SL_OS_RET_CODE_OK == RetVal) - { - CmdExt.pTxPayload += ChunkLen; - ChunkLen = (_u16)((_u8 *)pBuf + Len - CmdExt.pTxPayload); - ChunkLen = _sl_TruncatePayloadByProtocol(sd,ChunkLen); - CmdExt.TxPayloadLen = ChunkLen; - Msg.Cmd.IpV4.lenOrPadding = ChunkLen; - } - else - { - return RetVal; - } - }while(ChunkLen > 0); - - return (_i16)Len; -} -#endif - -/*******************************************************************************/ -/* sl_Recvfrom */ -/*******************************************************************************/ -typedef union -{ - _sendRecvCommand_t Cmd; - _SocketAddrResponse_u Rsp; -}_SlRecvfromMsg_u; - -const _SlCmdCtrl_t _SlRecvfomCmdCtrl = -{ - SL_OPCODE_SOCKET_RECVFROM, - sizeof(_sendRecvCommand_t), - sizeof(_SocketAddrResponse_u) -}; - - - -#if _SL_INCLUDE_FUNC(sl_RecvFrom) -_i16 sl_RecvFrom(_i16 sd, void *buf, _i16 Len, _i16 flags, SlSockAddr_t *from, SlSocklen_t *fromlen) -{ - _SlRecvfromMsg_u Msg; - _SlCmdExt_t CmdExt; - _i16 RetVal; - - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.RxPayloadLen = Len; - CmdExt.pRxPayload = (_u8 *)buf; - - Msg.Cmd.sd = (_u8)sd; - Msg.Cmd.StatusOrLen = Len; - /* no size truncation in recv path */ - CmdExt.RxPayloadLen = Msg.Cmd.StatusOrLen; - - - Msg.Cmd.FamilyAndFlags = flags & 0x0F; - - - if(sizeof(SlSockAddrIn_t) == *fromlen) - { - Msg.Cmd.FamilyAndFlags |= (SL_AF_INET << 4); - } - else if (sizeof(SlSockAddrIn6_t) == *fromlen) - { - Msg.Cmd.FamilyAndFlags |= (SL_AF_INET6 << 4); - } - else - { - return SL_RET_CODE_INVALID_INPUT; - } - - RetVal = _SlDrvDataReadOp((_SlSd_t)sd, (_SlCmdCtrl_t *)&_SlRecvfomCmdCtrl, &Msg, &CmdExt); - if( RetVal != SL_OS_RET_CODE_OK ) - { - return RetVal; - } - - RetVal = Msg.Rsp.IpV4.statusOrLen; - - if(RetVal >= 0) - { - VERIFY_PROTOCOL(sd == Msg.Rsp.IpV4.sd); -#if 0 - _sl_ParseAddress(&Msg.Rsp, from, fromlen); -#else - from->sa_family = Msg.Rsp.IpV4.family; - if(SL_AF_INET == from->sa_family) - { - ((SlSockAddrIn_t *)from)->sin_port = Msg.Rsp.IpV4.port; - ((SlSockAddrIn_t *)from)->sin_addr.s_addr = Msg.Rsp.IpV4.address; - *fromlen = sizeof(SlSockAddrIn_t); - } - else if (SL_AF_INET6_EUI_48 == from->sa_family ) - { - ((SlSockAddrIn6_t *)from)->sin6_port = Msg.Rsp.IpV6EUI48.port; - sl_Memcpy(((SlSockAddrIn6_t *)from)->sin6_addr._S6_un._S6_u8, Msg.Rsp.IpV6EUI48.address, 6); - } -#ifdef SL_SUPPORT_IPV6 - else if(AF_INET6 == from->sa_family) - { - VERIFY_PROTOCOL(*fromlen >= sizeof(sockaddr_in6)); - - ((sockaddr_in6 *)from)->sin6_port = Msg.Rsp.IpV6.port; - sl_Memcpy(((sockaddr_in6 *)from)->sin6_addr._S6_un._S6_u32, Msg.Rsp.IpV6.address, 16); - *fromlen = sizeof(sockaddr_in6); - } -#endif -#endif - } - - return (_i16)RetVal; -} -#endif - -/*******************************************************************************/ -/* sl_Connect */ -/*******************************************************************************/ -typedef union -{ - _SocketAddrCommand_u Cmd; - _SocketResponse_t Rsp; -}_SlSockConnectMsg_u; - -#if _SL_INCLUDE_FUNC(sl_Connect) -_i16 sl_Connect(_i16 sd, const SlSockAddr_t *addr, _i16 addrlen) -{ - _SlSockConnectMsg_u Msg; - _SlReturnVal_t RetVal; - _SlCmdCtrl_t CmdCtrl = {0, 0, sizeof(_SocketResponse_t)}; - _SocketResponse_t AsyncRsp; - _u8 ObjIdx = MAX_CONCURRENT_ACTIONS; - - - switch(addr->sa_family) - { - case SL_AF_INET : - CmdCtrl.Opcode = SL_OPCODE_SOCKET_CONNECT; - CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv4Command_t); - /* Do nothing - cmd already initialized to this type */ - break; - case SL_AF_INET6_EUI_48: - CmdCtrl.Opcode = SL_OPCODE_SOCKET_CONNECT_V6; - CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv6EUI48Command_t); - break; -#ifdef SL_SUPPORT_IPV6 - case AF_INET6: - CmdCtrl.Opcode = SL_OPCODE_SOCKET_CONNECT_V6; - CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv6Command_t); - break; -#endif - case SL_AF_RF: - default: - return SL_RET_CODE_INVALID_INPUT; - } - - Msg.Cmd.IpV4.lenOrPadding = 0; - Msg.Cmd.IpV4.sd = (_u8)sd; - - _sl_BuildAddress(addr, &Msg.Cmd); - - - ObjIdx = _SlDrvProtectAsyncRespSetting((_u8*)&AsyncRsp, CONNECT_ID, sd & BSD_SOCKET_ID_MASK); - - if (MAX_CONCURRENT_ACTIONS == ObjIdx) - { - return SL_POOL_IS_EMPTY; - } - - /* send the command */ - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&CmdCtrl, &Msg, NULL)); - VERIFY_PROTOCOL(Msg.Rsp.sd == sd) - - RetVal = Msg.Rsp.statusOrLen; - - if(SL_RET_CODE_OK == RetVal) - { - /* wait for async and get Data Read parameters */ - _SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj); - - VERIFY_PROTOCOL(AsyncRsp.sd == sd); - - RetVal = AsyncRsp.statusOrLen; - } - - - - _SlDrvReleasePoolObj(ObjIdx); - return RetVal; -} - -#endif - - -/*******************************************************************************/ -/* _sl_HandleAsync_Connect */ -/*******************************************************************************/ -void _sl_HandleAsync_Connect(void *pVoidBuf) -{ - _SocketResponse_t *pMsgArgs = (_SocketResponse_t *)_SL_RESP_ARGS_START(pVoidBuf); - - _SlDrvProtectionObjLockWaitForever(); - - VERIFY_PROTOCOL((pMsgArgs->sd & BSD_SOCKET_ID_MASK) <= SL_MAX_SOCKETS); - VERIFY_SOCKET_CB(NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs); - - - ((_SocketResponse_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->sd = pMsgArgs->sd; - ((_SocketResponse_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->statusOrLen = pMsgArgs->statusOrLen; - - - _SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj); - _SlDrvProtectionObjUnLock(); - return; -} - -/*******************************************************************************/ -/* sl_Send */ -/*******************************************************************************/ -typedef union -{ - _sendRecvCommand_t Cmd; - /* no response for 'sendto' commands*/ -}_SlSendMsg_u; - -const _SlCmdCtrl_t _SlSendCmdCtrl = -{ - SL_OPCODE_SOCKET_SEND, - sizeof(_sendRecvCommand_t), - 0 -}; - -#if _SL_INCLUDE_FUNC(sl_Send) -_i16 sl_Send(_i16 sd, const void *pBuf, _i16 Len, _i16 flags) -{ - _SlSendMsg_u Msg; - _SlCmdExt_t CmdExt; - _u16 ChunkLen; - _i16 RetVal; - _u32 tempVal; - _u8 runSingleChunk = FALSE; - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.TxPayloadLen = Len; - CmdExt.pTxPayload = (_u8 *)pBuf; - - /* Only for RAW transceiver type socket, relay the flags parameter in the 2 bytes (4 byte aligned) before the actual payload */ - if ((sd & SL_SOCKET_PAYLOAD_TYPE_MASK) == SL_SOCKET_PAYLOAD_TYPE_RAW_TRANCEIVER) - { - tempVal = flags; - CmdExt.pRxPayload = (_u8 *)&tempVal; - CmdExt.RxPayloadLen = -4; /* mark as Rx data to send */ - runSingleChunk = TRUE; - } - else - { - CmdExt.pRxPayload = NULL; - } - - ChunkLen = _sl_TruncatePayloadByProtocol(sd,Len); - CmdExt.TxPayloadLen = ChunkLen; - Msg.Cmd.StatusOrLen = ChunkLen; - Msg.Cmd.sd = (_u8)sd; - Msg.Cmd.FamilyAndFlags |= flags & 0x0F; - - do - { - RetVal = _SlDrvDataWriteOp((_u8)sd, (_SlCmdCtrl_t *)&_SlSendCmdCtrl, &Msg, &CmdExt); - if(SL_OS_RET_CODE_OK == RetVal) - { - CmdExt.pTxPayload += ChunkLen; - ChunkLen = (_u8 *)pBuf + Len - CmdExt.pTxPayload; - ChunkLen = _sl_TruncatePayloadByProtocol(sd,ChunkLen); - CmdExt.TxPayloadLen = ChunkLen; - Msg.Cmd.StatusOrLen = ChunkLen; - } - else - { - return RetVal; - } - }while((ChunkLen > 0) && (runSingleChunk==FALSE)); - - return (_i16)Len; -} -#endif - -/*******************************************************************************/ -/* sl_Listen */ -/*******************************************************************************/ -typedef union -{ - _ListenCommand_t Cmd; - _BasicResponse_t Rsp; -}_SlListenMsg_u; - - - -#if _SL_INCLUDE_FUNC(sl_Listen) - -const _SlCmdCtrl_t _SlListenCmdCtrl = -{ - SL_OPCODE_SOCKET_LISTEN, - sizeof(_ListenCommand_t), - sizeof(_BasicResponse_t), -}; - -_i16 sl_Listen(_i16 sd, _i16 backlog) -{ - _SlListenMsg_u Msg; - - Msg.Cmd.sd = (_u8)sd; - Msg.Cmd.backlog = (_u8)backlog; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlListenCmdCtrl, &Msg, NULL)); - - return (_i16)Msg.Rsp.status; -} -#endif - -/*******************************************************************************/ -/* sl_Accept */ -/*******************************************************************************/ -typedef union -{ - _AcceptCommand_t Cmd; - _SocketResponse_t Rsp; -}_SlSockAcceptMsg_u; - - - -#if _SL_INCLUDE_FUNC(sl_Accept) - -const _SlCmdCtrl_t _SlAcceptCmdCtrl = -{ - SL_OPCODE_SOCKET_ACCEPT, - sizeof(_AcceptCommand_t), - sizeof(_BasicResponse_t), -}; - -_i16 sl_Accept(_i16 sd, SlSockAddr_t *addr, SlSocklen_t *addrlen) -{ - _SlSockAcceptMsg_u Msg; - _SlReturnVal_t RetVal; - _SocketAddrResponse_u AsyncRsp; - - _u8 ObjIdx = MAX_CONCURRENT_ACTIONS; - - - Msg.Cmd.sd = (_u8)sd; - Msg.Cmd.family = (sizeof(SlSockAddrIn_t) == *addrlen) ? SL_AF_INET : SL_AF_INET6; - - - ObjIdx = _SlDrvProtectAsyncRespSetting((_u8*)&AsyncRsp, ACCEPT_ID, sd & BSD_SOCKET_ID_MASK ); - - if (MAX_CONCURRENT_ACTIONS == ObjIdx) - { - return SL_POOL_IS_EMPTY; - } - - /* send the command */ - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlAcceptCmdCtrl, &Msg, NULL)); - VERIFY_PROTOCOL(Msg.Rsp.sd == sd); - - RetVal = Msg.Rsp.statusOrLen; - - if(SL_OS_RET_CODE_OK == RetVal) - { - /* wait for async and get Data Read parameters */ - _SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj); - - VERIFY_PROTOCOL(AsyncRsp.IpV4.sd == sd); - - RetVal = AsyncRsp.IpV4.statusOrLen; - if( (NULL != addr) && (NULL != addrlen) ) - { -#if 0 /* Kept for backup */ - _sl_ParseAddress(&AsyncRsp, addr, addrlen); -#else - addr->sa_family = AsyncRsp.IpV4.family; - - if(SL_AF_INET == addr->sa_family) - { - if( *addrlen == sizeof( SlSockAddrIn_t ) ) - { - ((SlSockAddrIn_t *)addr)->sin_port = AsyncRsp.IpV4.port; - ((SlSockAddrIn_t *)addr)->sin_addr.s_addr = AsyncRsp.IpV4.address; - } - else - { - *addrlen = 0; - } - } - else if (SL_AF_INET6_EUI_48 == addr->sa_family ) - { - if( *addrlen == sizeof( SlSockAddrIn6_t ) ) - { - ((SlSockAddrIn6_t *)addr)->sin6_port = AsyncRsp.IpV6EUI48.port ; - /* will be called from here and from _sl_BuildAddress*/ - sl_Memcpy(((SlSockAddrIn6_t *)addr)->sin6_addr._S6_un._S6_u8, AsyncRsp.IpV6EUI48.address, 6); - } - else - { - *addrlen = 0; - } - } -#ifdef SL_SUPPORT_IPV6 - else - { - if( *addrlen == sizeof( sockaddr_in6 ) ) - { - ((sockaddr_in6 *)addr)->sin6_port = AsyncRsp.IpV6.port ; - sl_Memcpy(((sockaddr_in6 *)addr)->sin6_addr._S6_un._S6_u32, AsyncRsp.IpV6.address, 16); - } - else - { - *addrlen = 0; - } - } -#endif -#endif - } - } - - _SlDrvReleasePoolObj(ObjIdx); - return (_i16)RetVal; -} -#endif - - -/*******************************************************************************/ -/* sl_Htonl */ -/*******************************************************************************/ -_u32 sl_Htonl( _u32 val ) -{ - _u32 i = 1; - _i8 *p = (_i8 *)&i; - if (p[0] == 1) /* little endian */ - { - p[0] = ((_i8* )&val)[3]; - p[1] = ((_i8* )&val)[2]; - p[2] = ((_i8* )&val)[1]; - p[3] = ((_i8* )&val)[0]; - return i; - } - else /* big endian */ - { - return val; - } -} - -/*******************************************************************************/ -/* sl_Htonl */ -/*******************************************************************************/ -_u16 sl_Htons( _u16 val ) -{ - _i16 i = 1; - _i8 *p = (_i8 *)&i; - if (p[0] == 1) /* little endian */ - { - p[0] = ((_i8* )&val)[1]; - p[1] = ((_i8* )&val)[0]; - return i; - } - else /* big endian */ - { - return val; - } -} - -/*******************************************************************************/ -/* _sl_HandleAsync_Accept */ -/*******************************************************************************/ -#ifndef SL_TINY_EXT -void _sl_HandleAsync_Accept(void *pVoidBuf) -{ - _SocketAddrResponse_u *pMsgArgs = (_SocketAddrResponse_u *)_SL_RESP_ARGS_START(pVoidBuf); - - _SlDrvProtectionObjLockWaitForever(); - - VERIFY_PROTOCOL(( pMsgArgs->IpV4.sd & BSD_SOCKET_ID_MASK) <= SL_MAX_SOCKETS); - VERIFY_SOCKET_CB(NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs); - - sl_Memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs,sizeof(_SocketAddrResponse_u)); - _SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj); - - _SlDrvProtectionObjUnLock(); - return; -} - -/*******************************************************************************/ -/* _sl_HandleAsync_Select */ -/*******************************************************************************/ -void _sl_HandleAsync_Select(void *pVoidBuf) -{ - _SelectAsyncResponse_t *pMsgArgs = (_SelectAsyncResponse_t *)_SL_RESP_ARGS_START(pVoidBuf); - - _SlDrvProtectionObjLockWaitForever(); - - VERIFY_SOCKET_CB(NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs); - - sl_Memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(_SelectAsyncResponse_t)); - - _SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj); - _SlDrvProtectionObjUnLock(); - - return; -} - -#endif - -/*******************************************************************************/ -/* sl_Recv */ -/*******************************************************************************/ -typedef union -{ - _sendRecvCommand_t Cmd; - _SocketResponse_t Rsp; -}_SlRecvMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_Recv) - -const _SlCmdCtrl_t _SlRecvCmdCtrl = -{ - SL_OPCODE_SOCKET_RECV, - sizeof(_sendRecvCommand_t), - sizeof(_SocketResponse_t) -}; - - -_i16 sl_Recv(_i16 sd, void *pBuf, _i16 Len, _i16 flags) -{ - _SlRecvMsg_u Msg; - _SlCmdExt_t CmdExt; - _SlReturnVal_t status; - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.RxPayloadLen = Len; - CmdExt.pRxPayload = (_u8 *)pBuf; - - Msg.Cmd.sd = (_u8)sd; - Msg.Cmd.StatusOrLen = Len; - - /* no size truncation in recv path */ - CmdExt.RxPayloadLen = Msg.Cmd.StatusOrLen; - - Msg.Cmd.FamilyAndFlags = flags & 0x0F; - - status = _SlDrvDataReadOp((_SlSd_t)sd, (_SlCmdCtrl_t *)&_SlRecvCmdCtrl, &Msg, &CmdExt); - if( status != SL_OS_RET_CODE_OK ) - { - return status; - } - - /* if the Device side sends less than expected it is not the Driver's role */ - /* the returned value could be smaller than the requested size */ - return (_i16)Msg.Rsp.statusOrLen; -} -#endif - -/*******************************************************************************/ -/* sl_SetSockOpt */ -/*******************************************************************************/ -typedef union -{ - _setSockOptCommand_t Cmd; - _SocketResponse_t Rsp; -}_SlSetSockOptMsg_u; - -const _SlCmdCtrl_t _SlSetSockOptCmdCtrl = -{ - SL_OPCODE_SOCKET_SETSOCKOPT, - sizeof(_setSockOptCommand_t), - sizeof(_SocketResponse_t) -}; - -#if _SL_INCLUDE_FUNC(sl_SetSockOpt) -_i16 sl_SetSockOpt(_i16 sd, _i16 level, _i16 optname, const void *optval, SlSocklen_t optlen) -{ - _SlSetSockOptMsg_u Msg; - _SlCmdExt_t CmdExt; - - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.TxPayloadLen = optlen; - CmdExt.pTxPayload = (_u8 *)optval; - - Msg.Cmd.sd = (_u8)sd; - Msg.Cmd.level = (_u8)level; - Msg.Cmd.optionLen = (_u8)optlen; - Msg.Cmd.optionName = (_u8)optname; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlSetSockOptCmdCtrl, &Msg, &CmdExt)); - - return (_i16)Msg.Rsp.statusOrLen; -} -#endif - -/*******************************************************************************/ -/* sl_GetSockOpt */ -/*******************************************************************************/ -typedef union -{ - _getSockOptCommand_t Cmd; - _getSockOptResponse_t Rsp; -}_SlGetSockOptMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_GetSockOpt) - -const _SlCmdCtrl_t _SlGetSockOptCmdCtrl = -{ - SL_OPCODE_SOCKET_GETSOCKOPT, - sizeof(_getSockOptCommand_t), - sizeof(_getSockOptResponse_t) -}; - -_i16 sl_GetSockOpt(_i16 sd, _i16 level, _i16 optname, void *optval, SlSocklen_t *optlen) -{ - _SlGetSockOptMsg_u Msg; - _SlCmdExt_t CmdExt; - - if (*optlen == 0) - { - return SL_EZEROLEN; - } - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.RxPayloadLen = *optlen; - CmdExt.pRxPayload = optval; - - Msg.Cmd.sd = (_u8)sd; - Msg.Cmd.level = (_u8)level; - Msg.Cmd.optionLen = (_u8)(*optlen); - Msg.Cmd.optionName = (_u8)optname; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlGetSockOptCmdCtrl, &Msg, &CmdExt)); - - if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) - { - *optlen = Msg.Rsp.optionLen; - return SL_ESMALLBUF; - } - else - { - *optlen = (_u8)CmdExt.ActualRxPayloadLen; - } - return (_i16)Msg.Rsp.status; -} -#endif - -/*******************************************************************************/ -/* sl_Select */ -/* ******************************************************************************/ -typedef union -{ - _SelectCommand_t Cmd; - _BasicResponse_t Rsp; -}_SlSelectMsg_u; - - - -#ifndef SL_TINY_EXT -#if _SL_INCLUDE_FUNC(sl_Select) - -const _SlCmdCtrl_t _SlSelectCmdCtrl = -{ - SL_OPCODE_SOCKET_SELECT, - sizeof(_SelectCommand_t), - sizeof(_BasicResponse_t) -}; - - -_i16 sl_Select(_i16 nfds, SlFdSet_t *readsds, SlFdSet_t *writesds, SlFdSet_t *exceptsds, struct SlTimeval_t *timeout) -{ - _SlSelectMsg_u Msg; - _SelectAsyncResponse_t AsyncRsp; - _u8 ObjIdx = MAX_CONCURRENT_ACTIONS; - - Msg.Cmd.nfds = (_u8)nfds; - Msg.Cmd.readFdsCount = 0; - Msg.Cmd.writeFdsCount = 0; - - Msg.Cmd.readFds = 0; - Msg.Cmd.writeFds = 0; - - - if( readsds ) - { - Msg.Cmd.readFds = (_u16)readsds->fd_array[0]; - } - if( writesds ) - { - Msg.Cmd.writeFds = (_u16)writesds->fd_array[0]; - } - if( NULL == timeout ) - { - Msg.Cmd.tv_sec = 0xffff; - Msg.Cmd.tv_usec = 0xffff; - } - else - { - if( 0xffff <= timeout->tv_sec ) - { - Msg.Cmd.tv_sec = 0xffff; - } - else - { - Msg.Cmd.tv_sec = (_u16)timeout->tv_sec; - } - timeout->tv_usec = timeout->tv_usec >> 10; /* convert to milliseconds */ - if( 0xffff <= timeout->tv_usec ) - { - Msg.Cmd.tv_usec = 0xffff; - } - else - { - Msg.Cmd.tv_usec = (_u16)timeout->tv_usec; - } - } - - /* Use Obj to issue the command, if not available try later */ - ObjIdx = _SlDrvProtectAsyncRespSetting((_u8*)&AsyncRsp, SELECT_ID, SL_MAX_SOCKETS); - - if (MAX_CONCURRENT_ACTIONS == ObjIdx) - { - return SL_POOL_IS_EMPTY; - } - - - /* send the command */ - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlSelectCmdCtrl, &Msg, NULL)); - - if(SL_OS_RET_CODE_OK == (_i16)Msg.Rsp.status) - { - _SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj); - - Msg.Rsp.status = AsyncRsp.status; - - if( ((_i16)Msg.Rsp.status) >= 0 ) - { - if( readsds ) - { - readsds->fd_array[0] = AsyncRsp.readFds; - } - if( writesds ) - { - writesds->fd_array[0] = AsyncRsp.writeFds; - } - } - } - - _SlDrvReleasePoolObj(ObjIdx); - return (_i16)Msg.Rsp.status; -} - -/* Select helper functions */ -/*******************************************************************************/ -/* SL_FD_SET */ -/* ******************************************************************************/ -void SL_FD_SET(_i16 fd, SlFdSet_t *fdset) -{ - fdset->fd_array[0] |= (1<< (fd & BSD_SOCKET_ID_MASK)); -} -/*******************************************************************************/ -/* SL_FD_CLR */ -/*******************************************************************************/ -void SL_FD_CLR(_i16 fd, SlFdSet_t *fdset) -{ - fdset->fd_array[0] &= ~(1<< (fd & BSD_SOCKET_ID_MASK)); -} -/*******************************************************************************/ -/* SL_FD_ISSET */ -/*******************************************************************************/ -_i16 SL_FD_ISSET(_i16 fd, SlFdSet_t *fdset) -{ - if( fdset->fd_array[0] & (1<< (fd & BSD_SOCKET_ID_MASK)) ) - { - return 1; - } - return 0; -} -/*******************************************************************************/ -/* SL_FD_ZERO */ -/*******************************************************************************/ -void SL_FD_ZERO(SlFdSet_t *fdset) -{ - fdset->fd_array[0] = 0; -} - -#endif -#endif - - - diff --git a/drivers/cc3100/src/spawn.c b/drivers/cc3100/src/spawn.c deleted file mode 100644 index bb5575818b..0000000000 --- a/drivers/cc3100/src/spawn.c +++ /dev/null @@ -1,197 +0,0 @@ -/* - * spawn.c - CC31xx/CC32xx Host Driver Implementation - * - * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ - * - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -*/ - - - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" - - -#if (defined (SL_PLATFORM_MULTI_THREADED)) && (!defined (SL_PLATFORM_EXTERNAL_SPAWN)) - -#define _SL_MAX_INTERNAL_SPAWN_ENTRIES 10 - -typedef struct _SlInternalSpawnEntry_t -{ - _SlSpawnEntryFunc_t pEntry; - void* pValue; - struct _SlInternalSpawnEntry_t* pNext; -}_SlInternalSpawnEntry_t; - -typedef struct -{ - _SlInternalSpawnEntry_t SpawnEntries[_SL_MAX_INTERNAL_SPAWN_ENTRIES]; - _SlInternalSpawnEntry_t* pFree; - _SlInternalSpawnEntry_t* pWaitForExe; - _SlInternalSpawnEntry_t* pLastInWaitList; - _SlSyncObj_t SyncObj; - _SlLockObj_t LockObj; -}_SlInternalSpawnCB_t; - -_SlInternalSpawnCB_t g_SlInternalSpawnCB; - - -void _SlInternalSpawnTaskEntry() -{ - _i16 i; - _SlInternalSpawnEntry_t* pEntry; - _u8 LastEntry; - - /* create and lock the locking object. lock in order to avoid race condition - on the first creation */ - sl_LockObjCreate(&g_SlInternalSpawnCB.LockObj,"SlSpawnProtect"); - sl_LockObjLock(&g_SlInternalSpawnCB.LockObj,SL_OS_NO_WAIT); - - /* create and clear the sync object */ - sl_SyncObjCreate(&g_SlInternalSpawnCB.SyncObj,"SlSpawnSync"); - sl_SyncObjWait(&g_SlInternalSpawnCB.SyncObj,SL_OS_NO_WAIT); - - g_SlInternalSpawnCB.pFree = &g_SlInternalSpawnCB.SpawnEntries[0]; - g_SlInternalSpawnCB.pWaitForExe = NULL; - g_SlInternalSpawnCB.pLastInWaitList = NULL; - - /* create the link list between the entries */ - for (i=0 ; i<_SL_MAX_INTERNAL_SPAWN_ENTRIES - 1 ; i++) - { - g_SlInternalSpawnCB.SpawnEntries[i].pNext = &g_SlInternalSpawnCB.SpawnEntries[i+1]; - g_SlInternalSpawnCB.SpawnEntries[i].pEntry = NULL; - } - g_SlInternalSpawnCB.SpawnEntries[i].pNext = NULL; - - _SlDrvObjUnLock(&g_SlInternalSpawnCB.LockObj); - - /* here we ready to execute entries */ - - while (TRUE) - { - sl_SyncObjWait(&g_SlInternalSpawnCB.SyncObj,SL_OS_WAIT_FOREVER); - /* go over all entries that already waiting for execution */ - LastEntry = FALSE; - do - { - /* get entry to execute */ - _SlDrvObjLockWaitForever(&g_SlInternalSpawnCB.LockObj); - - pEntry = g_SlInternalSpawnCB.pWaitForExe; - if ( NULL == pEntry ) - { - _SlDrvObjUnLock(&g_SlInternalSpawnCB.LockObj); - break; - } - g_SlInternalSpawnCB.pWaitForExe = pEntry->pNext; - if (pEntry == g_SlInternalSpawnCB.pLastInWaitList) - { - g_SlInternalSpawnCB.pLastInWaitList = NULL; - LastEntry = TRUE; - } - - _SlDrvObjUnLock(&g_SlInternalSpawnCB.LockObj); - - /* pEntry could be null in case that the sync was already set by some - of the entries during execution of earlier entry */ - if (NULL != pEntry) - { - pEntry->pEntry(pEntry->pValue); - /* free the entry */ - - _SlDrvObjLockWaitForever(&g_SlInternalSpawnCB.LockObj); - - pEntry->pNext = g_SlInternalSpawnCB.pFree; - g_SlInternalSpawnCB.pFree = pEntry; - - - if (NULL != g_SlInternalSpawnCB.pWaitForExe) - { - /* new entry received meanwhile */ - LastEntry = FALSE; - } - - _SlDrvObjUnLock(&g_SlInternalSpawnCB.LockObj); - - } - - }while (!LastEntry); - } -} - - -_i16 _SlInternalSpawn(_SlSpawnEntryFunc_t pEntry , void* pValue , _u32 flags) -{ - _i16 Res = 0; - _SlInternalSpawnEntry_t* pSpawnEntry; - - if (NULL == pEntry) - { - Res = -1; - } - else - { - _SlDrvObjLockWaitForever(&g_SlInternalSpawnCB.LockObj); - - pSpawnEntry = g_SlInternalSpawnCB.pFree; - g_SlInternalSpawnCB.pFree = pSpawnEntry->pNext; - - pSpawnEntry->pEntry = pEntry; - pSpawnEntry->pValue = pValue; - pSpawnEntry->pNext = NULL; - - if (NULL == g_SlInternalSpawnCB.pWaitForExe) - { - g_SlInternalSpawnCB.pWaitForExe = pSpawnEntry; - g_SlInternalSpawnCB.pLastInWaitList = pSpawnEntry; - } - else - { - g_SlInternalSpawnCB.pLastInWaitList->pNext = pSpawnEntry; - g_SlInternalSpawnCB.pLastInWaitList = pSpawnEntry; - } - - _SlDrvObjUnLock(&g_SlInternalSpawnCB.LockObj); - - /* this sync is called after releasing the lock object to avoid unnecessary context switches */ - _SlDrvSyncObjSignal(&g_SlInternalSpawnCB.SyncObj); - } - - return Res; -} - - - - - -#endif diff --git a/drivers/cc3100/src/wlan.c b/drivers/cc3100/src/wlan.c deleted file mode 100644 index 59adf02f02..0000000000 --- a/drivers/cc3100/src/wlan.c +++ /dev/null @@ -1,1006 +0,0 @@ -/* -* wlan.c - CC31xx/CC32xx Host Driver Implementation -* -* Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ -* -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the -* distribution. -* -* Neither the name of Texas Instruments Incorporated nor the names of -* its contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - - - -/*****************************************************************************/ -/* Include files */ -/*****************************************************************************/ -#include "simplelink.h" -#include "protocol.h" -#include "driver.h" - -/*****************************************************************************/ -/* Macro declarations */ -/*****************************************************************************/ -#define MAX_SSID_LEN (32) -#define MAX_KEY_LEN (63) -#define MAX_USER_LEN (32) -#define MAX_ANON_USER_LEN (32) -#define MAX_SMART_CONFIG_KEY (16) - - -/***************************************************************************** -sl_WlanConnect -*****************************************************************************/ -typedef struct -{ - _WlanConnectEapCommand_t Args; - _i8 Strings[MAX_SSID_LEN + MAX_KEY_LEN + MAX_USER_LEN + MAX_ANON_USER_LEN]; -}_WlanConnectCmd_t; - -typedef union -{ - _WlanConnectCmd_t Cmd; - _BasicResponse_t Rsp; -}_SlWlanConnectMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_WlanConnect) -_i16 sl_WlanConnect(const _i8* pName,const _i16 NameLen,const _u8 *pMacAddr,const SlSecParams_t* pSecParams ,const SlSecParamsExt_t* pSecExtParams) -{ - _SlWlanConnectMsg_u Msg; - _SlCmdCtrl_t CmdCtrl; - - sl_Memset (&Msg, 0, sizeof(Msg)); - - CmdCtrl.TxDescLen = 0;/* init */ - CmdCtrl.RxDescLen = sizeof(_BasicResponse_t); - - /* verify SSID length */ - VERIFY_PROTOCOL(NameLen <= MAX_SSID_LEN); - /* verify SSID is not NULL */ - if( NULL == pName ) - { - return SL_INVALPARAM; - } - /* update SSID length */ - Msg.Cmd.Args.Common.SsidLen = (_u8)NameLen; - - /* Profile with no security */ - /* Enterprise security profile */ - if (NULL != pSecExtParams) - { - /* Update command opcode */ - CmdCtrl.Opcode = SL_OPCODE_WLAN_WLANCONNECTEAPCOMMAND; - CmdCtrl.TxDescLen += sizeof(_WlanConnectEapCommand_t); - /* copy SSID */ - sl_Memcpy(EAP_SSID_STRING(&Msg), pName, NameLen); - CmdCtrl.TxDescLen += NameLen; - /* Copy password if supplied */ - if ((NULL != pSecParams) && (pSecParams->KeyLen > 0)) - { - /* update security type */ - Msg.Cmd.Args.Common.SecType = pSecParams->Type; - /* verify key length */ - if (pSecParams->KeyLen > MAX_KEY_LEN) - { - return SL_INVALPARAM; - } - /* update key length */ - Msg.Cmd.Args.Common.PasswordLen = pSecParams->KeyLen; - ARG_CHECK_PTR(pSecParams->Key); - /* copy key */ - sl_Memcpy(EAP_PASSWORD_STRING(&Msg), pSecParams->Key, pSecParams->KeyLen); - CmdCtrl.TxDescLen += pSecParams->KeyLen; - } - else - { - Msg.Cmd.Args.Common.PasswordLen = 0; - } - - ARG_CHECK_PTR(pSecExtParams); - /* Update Eap bitmask */ - Msg.Cmd.Args.EapBitmask = pSecExtParams->EapMethod; - /* Update Certificate file ID index - currently not supported */ - Msg.Cmd.Args.CertIndex = pSecExtParams->CertIndex; - /* verify user length */ - if (pSecExtParams->UserLen > MAX_USER_LEN) - { - return SL_INVALPARAM; - } - Msg.Cmd.Args.UserLen = pSecExtParams->UserLen; - /* copy user name (identity) */ - if(pSecExtParams->UserLen > 0) - { - sl_Memcpy(EAP_USER_STRING(&Msg), pSecExtParams->User, pSecExtParams->UserLen); - CmdCtrl.TxDescLen += pSecExtParams->UserLen; - } - /* verify Anonymous user length */ - if (pSecExtParams->AnonUserLen > MAX_ANON_USER_LEN) - { - return SL_INVALPARAM; - } - Msg.Cmd.Args.AnonUserLen = pSecExtParams->AnonUserLen; - /* copy Anonymous user */ - if(pSecExtParams->AnonUserLen > 0) - { - sl_Memcpy(EAP_ANON_USER_STRING(&Msg), pSecExtParams->AnonUser, pSecExtParams->AnonUserLen); - CmdCtrl.TxDescLen += pSecExtParams->AnonUserLen; - } - - } - - /* Regular or open security profile */ - else - { - /* Update command opcode */ - CmdCtrl.Opcode = SL_OPCODE_WLAN_WLANCONNECTCOMMAND; - CmdCtrl.TxDescLen += sizeof(_WlanConnectCommon_t); - /* copy SSID */ - sl_Memcpy(SSID_STRING(&Msg), pName, NameLen); - CmdCtrl.TxDescLen += NameLen; - /* Copy password if supplied */ - if( NULL != pSecParams ) - { - /* update security type */ - Msg.Cmd.Args.Common.SecType = pSecParams->Type; - /* verify key length is valid */ - if (pSecParams->KeyLen > MAX_KEY_LEN) - { - return SL_INVALPARAM; - } - /* update key length */ - Msg.Cmd.Args.Common.PasswordLen = pSecParams->KeyLen; - CmdCtrl.TxDescLen += pSecParams->KeyLen; - /* copy key (could be no key in case of WPS pin) */ - if( NULL != pSecParams->Key ) - { - sl_Memcpy(PASSWORD_STRING(&Msg), pSecParams->Key, pSecParams->KeyLen); - } - } - /* Profile with no security */ - else - { - Msg.Cmd.Args.Common.PasswordLen = 0; - Msg.Cmd.Args.Common.SecType = SL_SEC_TYPE_OPEN; - } - } - /* If BSSID is not null, copy to buffer, otherwise set to 0 */ - if(NULL != pMacAddr) - { - sl_Memcpy(Msg.Cmd.Args.Common.Bssid, pMacAddr, sizeof(Msg.Cmd.Args.Common.Bssid)); - } - else - { - _SlDrvMemZero(Msg.Cmd.Args.Common.Bssid, sizeof(Msg.Cmd.Args.Common.Bssid)); - } - - - VERIFY_RET_OK ( _SlDrvCmdOp(&CmdCtrl, &Msg, NULL)); - - return (_i16)Msg.Rsp.status; -} -#endif - -/*******************************************************************************/ -/* sl_Disconnect */ -/* ******************************************************************************/ -#if _SL_INCLUDE_FUNC(sl_WlanDisconnect) -_i16 sl_WlanDisconnect(void) -{ - return _SlDrvBasicCmd(SL_OPCODE_WLAN_WLANDISCONNECTCOMMAND); -} -#endif - -/******************************************************************************/ -/* sl_PolicySet */ -/******************************************************************************/ -typedef union -{ - _WlanPoliciySetGet_t Cmd; - _BasicResponse_t Rsp; -}_SlPolicyMsg_u; - -#if _SL_INCLUDE_FUNC(sl_WlanPolicySet) - -const _SlCmdCtrl_t _SlPolicySetCmdCtrl = -{ - SL_OPCODE_WLAN_POLICYSETCOMMAND, - sizeof(_WlanPoliciySetGet_t), - sizeof(_BasicResponse_t) -}; - -_i16 sl_WlanPolicySet(const _u8 Type , const _u8 Policy, _u8 *pVal,const _u8 ValLen) -{ - _SlPolicyMsg_u Msg; - _SlCmdExt_t CmdExt; - - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.TxPayloadLen = ValLen; - CmdExt.pTxPayload = (_u8 *)pVal; - - - Msg.Cmd.PolicyType = Type; - Msg.Cmd.PolicyOption = Policy; - Msg.Cmd.PolicyOptionLen = ValLen; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlPolicySetCmdCtrl, &Msg, &CmdExt)); - - return (_i16)Msg.Rsp.status; -} -#endif - - -/******************************************************************************/ -/* sl_PolicyGet */ -/******************************************************************************/ -typedef union -{ - _WlanPoliciySetGet_t Cmd; - _WlanPoliciySetGet_t Rsp; -}_SlPolicyGetMsg_u; - -#if _SL_INCLUDE_FUNC(sl_WlanPolicyGet) - -const _SlCmdCtrl_t _SlPolicyGetCmdCtrl = -{ - SL_OPCODE_WLAN_POLICYGETCOMMAND, - sizeof(_WlanPoliciySetGet_t), - sizeof(_WlanPoliciySetGet_t) -}; - -_i16 sl_WlanPolicyGet(const _u8 Type ,_u8 Policy,_u8 *pVal,_u8 *pValLen) -{ - _SlPolicyGetMsg_u Msg; - _SlCmdExt_t CmdExt; - - if (*pValLen == 0) - { - return SL_EZEROLEN; - } - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.RxPayloadLen = *pValLen; - CmdExt.pRxPayload = pVal; - - Msg.Cmd.PolicyType = Type; - Msg.Cmd.PolicyOption = Policy; - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlPolicyGetCmdCtrl, &Msg, &CmdExt)); - - - if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) - { - *pValLen = Msg.Rsp.PolicyOptionLen; - return SL_ESMALLBUF; - } - else - { - /* no pointer valus, fill the results into _i8 */ - *pValLen = (_u8)CmdExt.ActualRxPayloadLen; - if( 0 == CmdExt.ActualRxPayloadLen ) - { - *pValLen = 1; - pVal[0] = Msg.Rsp.PolicyOption; - } - } - return (_i16)SL_OS_RET_CODE_OK; -} -#endif - - -/*******************************************************************************/ -/* sl_ProfileAdd */ -/*******************************************************************************/ -typedef struct -{ - _WlanAddGetEapProfile_t Args; - _i8 Strings[MAX_SSID_LEN + MAX_KEY_LEN + MAX_USER_LEN + MAX_ANON_USER_LEN]; -}_SlProfileParams_t; - -typedef union -{ - _SlProfileParams_t Cmd; - _BasicResponse_t Rsp; -}_SlProfileAddMsg_u; - - - -#if _SL_INCLUDE_FUNC(sl_WlanProfileAdd) -_i16 sl_WlanProfileAdd(const _i8* pName,const _i16 NameLen,const _u8 *pMacAddr,const SlSecParams_t* pSecParams ,const SlSecParamsExt_t* pSecExtParams,const _u32 Priority,const _u32 Options) -{ - _SlProfileAddMsg_u Msg; - _SlCmdCtrl_t CmdCtrl = {0}; - CmdCtrl.TxDescLen = 0;/* init */ - CmdCtrl.RxDescLen = sizeof(_BasicResponse_t); - - /* update priority */ - Msg.Cmd.Args.Common.Priority = (_u8)Priority; - /* verify SSID is not NULL */ - if( NULL == pName ) - { - return SL_INVALPARAM; - } - /* verify SSID length */ - VERIFY_PROTOCOL(NameLen <= MAX_SSID_LEN); - /* update SSID length */ - Msg.Cmd.Args.Common.SsidLen = (_u8)NameLen; - - - /* Enterprise security profile */ - if (NULL != pSecExtParams) - { - /* Update command opcode */ - CmdCtrl.Opcode = SL_OPCODE_WLAN_EAP_PROFILEADDCOMMAND; - CmdCtrl.TxDescLen += sizeof(_WlanAddGetEapProfile_t); - - /* copy SSID */ - sl_Memcpy(EAP_PROFILE_SSID_STRING(&Msg), pName, NameLen); - CmdCtrl.TxDescLen += NameLen; - - /* Copy password if supplied */ - if ((NULL != pSecParams) && (pSecParams->KeyLen > 0)) - { - /* update security type */ - Msg.Cmd.Args.Common.SecType = pSecParams->Type; - - if( SL_SEC_TYPE_WEP == Msg.Cmd.Args.Common.SecType ) - { - Msg.Cmd.Args.Common.WepKeyId = 0; - } - - /* verify key length */ - if (pSecParams->KeyLen > MAX_KEY_LEN) - { - return SL_INVALPARAM; - } - VERIFY_PROTOCOL(pSecParams->KeyLen <= MAX_KEY_LEN); - /* update key length */ - Msg.Cmd.Args.Common.PasswordLen = pSecParams->KeyLen; - CmdCtrl.TxDescLen += pSecParams->KeyLen; - ARG_CHECK_PTR(pSecParams->Key); - /* copy key */ - sl_Memcpy(EAP_PROFILE_PASSWORD_STRING(&Msg), pSecParams->Key, pSecParams->KeyLen); - } - else - { - Msg.Cmd.Args.Common.PasswordLen = 0; - } - - ARG_CHECK_PTR(pSecExtParams); - /* Update Eap bitmask */ - Msg.Cmd.Args.EapBitmask = pSecExtParams->EapMethod; - /* Update Certificate file ID index - currently not supported */ - Msg.Cmd.Args.CertIndex = pSecExtParams->CertIndex; - /* verify user length */ - if (pSecExtParams->UserLen > MAX_USER_LEN) - { - return SL_INVALPARAM; - } - Msg.Cmd.Args.UserLen = pSecExtParams->UserLen; - /* copy user name (identity) */ - if(pSecExtParams->UserLen > 0) - { - sl_Memcpy(EAP_PROFILE_USER_STRING(&Msg), pSecExtParams->User, pSecExtParams->UserLen); - CmdCtrl.TxDescLen += pSecExtParams->UserLen; - } - - /* verify Anonymous user length (for tunneled) */ - if (pSecExtParams->AnonUserLen > MAX_ANON_USER_LEN) - { - return SL_INVALPARAM; - } - Msg.Cmd.Args.AnonUserLen = pSecExtParams->AnonUserLen; - - /* copy Anonymous user */ - if(pSecExtParams->AnonUserLen > 0) - { - sl_Memcpy(EAP_PROFILE_ANON_USER_STRING(&Msg), pSecExtParams->AnonUser, pSecExtParams->AnonUserLen); - CmdCtrl.TxDescLen += pSecExtParams->AnonUserLen; - } - - } - /* Regular or open security profile */ - else - { - /* Update command opcode */ - CmdCtrl.Opcode = SL_OPCODE_WLAN_PROFILEADDCOMMAND; - /* update commnad length */ - CmdCtrl.TxDescLen += sizeof(_WlanAddGetProfile_t); - - if (NULL != pName) - { - /* copy SSID */ - sl_Memcpy(PROFILE_SSID_STRING(&Msg), pName, NameLen); - CmdCtrl.TxDescLen += NameLen; - } - - /* Copy password if supplied */ - if( NULL != pSecParams ) - { - /* update security type */ - Msg.Cmd.Args.Common.SecType = pSecParams->Type; - - if( SL_SEC_TYPE_WEP == Msg.Cmd.Args.Common.SecType ) - { - Msg.Cmd.Args.Common.WepKeyId = 0; - } - - /* verify key length */ - if (pSecParams->KeyLen > MAX_KEY_LEN) - { - return SL_INVALPARAM; - } - /* update key length */ - Msg.Cmd.Args.Common.PasswordLen = pSecParams->KeyLen; - CmdCtrl.TxDescLen += pSecParams->KeyLen; - /* copy key (could be no key in case of WPS pin) */ - if( NULL != pSecParams->Key ) - { - sl_Memcpy(PROFILE_PASSWORD_STRING(&Msg), pSecParams->Key, pSecParams->KeyLen); - } - } - else - { - Msg.Cmd.Args.Common.SecType = SL_SEC_TYPE_OPEN; - Msg.Cmd.Args.Common.PasswordLen = 0; - } - - } - - - /* If BSSID is not null, copy to buffer, otherwise set to 0 */ - if(NULL != pMacAddr) - { - sl_Memcpy(Msg.Cmd.Args.Common.Bssid, pMacAddr, sizeof(Msg.Cmd.Args.Common.Bssid)); - } - else - { - _SlDrvMemZero(Msg.Cmd.Args.Common.Bssid, sizeof(Msg.Cmd.Args.Common.Bssid)); - } - - VERIFY_RET_OK(_SlDrvCmdOp(&CmdCtrl, &Msg, NULL)); - - return (_i16)Msg.Rsp.status; -} -#endif -/*******************************************************************************/ -/* sl_ProfileGet */ -/*******************************************************************************/ -typedef union -{ - _WlanProfileDelGetCommand_t Cmd; - _SlProfileParams_t Rsp; -}_SlProfileGetMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_WlanProfileGet) - -const _SlCmdCtrl_t _SlProfileGetCmdCtrl = -{ - SL_OPCODE_WLAN_PROFILEGETCOMMAND, - sizeof(_WlanProfileDelGetCommand_t), - sizeof(_SlProfileParams_t) -}; - -_i16 sl_WlanProfileGet(const _i16 Index,_i8* pName, _i16 *pNameLen, _u8 *pMacAddr, SlSecParams_t* pSecParams, SlGetSecParamsExt_t* pEntParams, _u32 *pPriority) -{ - _SlProfileGetMsg_u Msg; - Msg.Cmd.index = (_u8)Index; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlProfileGetCmdCtrl, &Msg, NULL)); - - pSecParams->Type = Msg.Rsp.Args.Common.SecType; - /* since password is not transferred in getprofile, password length should always be zero */ - pSecParams->KeyLen = Msg.Rsp.Args.Common.PasswordLen; - if (NULL != pEntParams) - { - pEntParams->UserLen = Msg.Rsp.Args.UserLen; - /* copy user name */ - if (pEntParams->UserLen > 0) - { - sl_Memcpy(pEntParams->User, EAP_PROFILE_USER_STRING(&Msg), pEntParams->UserLen); - } - pEntParams->AnonUserLen = Msg.Rsp.Args.AnonUserLen; - /* copy anonymous user name */ - if (pEntParams->AnonUserLen > 0) - { - sl_Memcpy(pEntParams->AnonUser, EAP_PROFILE_ANON_USER_STRING(&Msg), pEntParams->AnonUserLen); - } - } - - *pNameLen = Msg.Rsp.Args.Common.SsidLen; - *pPriority = Msg.Rsp.Args.Common.Priority; - - if (NULL != Msg.Rsp.Args.Common.Bssid) - { - sl_Memcpy(pMacAddr, Msg.Rsp.Args.Common.Bssid, sizeof(Msg.Rsp.Args.Common.Bssid)); - } - - sl_Memcpy(pName, EAP_PROFILE_SSID_STRING(&Msg), *pNameLen); - - return (_i16)Msg.Rsp.Args.Common.SecType; - -} -#endif -/*******************************************************************************/ -/* sl_ProfileDel */ -/*******************************************************************************/ -typedef union -{ - _WlanProfileDelGetCommand_t Cmd; - _BasicResponse_t Rsp; -}_SlProfileDelMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_WlanProfileDel) - -const _SlCmdCtrl_t _SlProfileDelCmdCtrl = -{ - SL_OPCODE_WLAN_PROFILEDELCOMMAND, - sizeof(_WlanProfileDelGetCommand_t), - sizeof(_BasicResponse_t) -}; - -_i16 sl_WlanProfileDel(const _i16 Index) -{ - _SlProfileDelMsg_u Msg; - - Msg.Cmd.index = (_u8)Index; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlProfileDelCmdCtrl, &Msg, NULL)); - - return (_i16)Msg.Rsp.status; -} -#endif - - -/******************************************************************************/ -/* sl_WlanGetNetworkList */ -/******************************************************************************/ -typedef union -{ - _WlanGetNetworkListCommand_t Cmd; - _WlanGetNetworkListResponse_t Rsp; -}_SlWlanGetNetworkListMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_WlanGetNetworkList) - -const _SlCmdCtrl_t _SlWlanGetNetworkListCtrl = -{ - SL_OPCODE_WLAN_SCANRESULTSGETCOMMAND, - sizeof(_WlanGetNetworkListCommand_t), - sizeof(_WlanGetNetworkListResponse_t) -}; - -_i16 sl_WlanGetNetworkList(const _u8 Index,const _u8 Count, Sl_WlanNetworkEntry_t *pEntries) -{ - _i16 retVal = 0; - _SlWlanGetNetworkListMsg_u Msg; - _SlCmdExt_t CmdExt; - - if (Count == 0) - { - return SL_EZEROLEN; - } - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.RxPayloadLen = sizeof(Sl_WlanNetworkEntry_t)*(Count); - CmdExt.pRxPayload = (_u8 *)pEntries; - - Msg.Cmd.index = Index; - Msg.Cmd.count = Count; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlWlanGetNetworkListCtrl, &Msg, &CmdExt)); - retVal = Msg.Rsp.status; - - return (_i16)retVal; -} -#endif - - - - - -/******************************************************************************/ -/* RX filters message command response structures */ -/******************************************************************************/ - -/* Set command */ -typedef union -{ - _WlanRxFilterAddCommand_t Cmd; - _WlanRxFilterAddCommandReponse_t Rsp; -}_SlrxFilterAddMsg_u; - - -/* Set command */ -typedef union _SlRxFilterSetMsg_u -{ - _WlanRxFilterSetCommand_t Cmd; - _WlanRxFilterSetCommandReponse_t Rsp; -}_SlRxFilterSetMsg_u; - - -/* Get command */ -typedef union _SlRxFilterGetMsg_u -{ - _WlanRxFilterGetCommand_t Cmd; - _WlanRxFilterGetCommandReponse_t Rsp; -}_SlRxFilterGetMsg_u; - -#if _SL_INCLUDE_FUNC(sl_WlanRxFilterAdd) - -const _SlCmdCtrl_t _SlRxFilterAddtCmdCtrl = -{ - SL_OPCODE_WLAN_WLANRXFILTERADDCOMMAND, - sizeof(_WlanRxFilterAddCommand_t), - sizeof(_WlanRxFilterAddCommandReponse_t) -}; - - -/***************************************************************************** - RX filters -*****************************************************************************/ -SlrxFilterID_t sl_WlanRxFilterAdd( SlrxFilterRuleType_t RuleType, - SlrxFilterFlags_t FilterFlags, - const SlrxFilterRule_t* const Rule, - const SlrxFilterTrigger_t* const Trigger, - const SlrxFilterAction_t* const Action, - SlrxFilterID_t* pFilterId) -{ - - - _SlrxFilterAddMsg_u Msg; - Msg.Cmd.RuleType = RuleType; - /* filterId is zero */ - Msg.Cmd.FilterId = 0; - Msg.Cmd.FilterFlags = FilterFlags; - sl_Memcpy( &(Msg.Cmd.Rule), Rule, sizeof(SlrxFilterRule_t) ); - sl_Memcpy( &(Msg.Cmd.Trigger), Trigger, sizeof(SlrxFilterTrigger_t) ); - sl_Memcpy( &(Msg.Cmd.Action), Action, sizeof(SlrxFilterAction_t) ); - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlRxFilterAddtCmdCtrl, &Msg, NULL) ); - *pFilterId = Msg.Rsp.FilterId; - return (_i16)Msg.Rsp.Status; - -} -#endif - - - -/*******************************************************************************/ -/* RX filters */ -/*******************************************************************************/ -#if _SL_INCLUDE_FUNC(sl_WlanRxFilterSet) - -const _SlCmdCtrl_t _SlRxFilterSetCmdCtrl = -{ - SL_OPCODE_WLAN_WLANRXFILTERSETCOMMAND, - sizeof(_WlanRxFilterSetCommand_t), - sizeof(_WlanRxFilterSetCommandReponse_t) -}; - -_i16 sl_WlanRxFilterSet(const SLrxFilterOperation_t RxFilterOperation, - const _u8* const pInputBuffer, - _u16 InputbufferLength) -{ - _SlRxFilterSetMsg_u Msg; - _SlCmdExt_t CmdExt; - - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.TxPayloadLen = InputbufferLength; - CmdExt.pTxPayload = (_u8 *)pInputBuffer; - - Msg.Cmd.RxFilterOperation = RxFilterOperation; - Msg.Cmd.InputBufferLength = InputbufferLength; - - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlRxFilterSetCmdCtrl, &Msg, &CmdExt) ); - - - return (_i16)Msg.Rsp.Status; -} -#endif - -/******************************************************************************/ -/* RX filters */ -/******************************************************************************/ -#if _SL_INCLUDE_FUNC(sl_WlanRxFilterGet) - -const _SlCmdCtrl_t _SlRxFilterGetCmdCtrl = -{ - SL_OPCODE_WLAN_WLANRXFILTERGETCOMMAND, - sizeof(_WlanRxFilterGetCommand_t), - sizeof(_WlanRxFilterGetCommandReponse_t) -}; - - -_i16 sl_WlanRxFilterGet(const SLrxFilterOperation_t RxFilterOperation, - _u8* pOutputBuffer, - _u16 OutputbufferLength) -{ - _SlRxFilterGetMsg_u Msg; - _SlCmdExt_t CmdExt; - - if (OutputbufferLength == 0) - { - return SL_EZEROLEN; - } - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.RxPayloadLen = OutputbufferLength; - CmdExt.pRxPayload = (_u8 *)pOutputBuffer; - - Msg.Cmd.RxFilterOperation = RxFilterOperation; - Msg.Cmd.OutputBufferLength = OutputbufferLength; - - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlRxFilterGetCmdCtrl, &Msg, &CmdExt) ); - - if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) - { - return SL_ESMALLBUF; - } - - return (_i16)Msg.Rsp.Status; -} -#endif - -/*******************************************************************************/ -/* sl_WlanRxStatStart */ -/*******************************************************************************/ -#if _SL_INCLUDE_FUNC(sl_WlanRxStatStart) -_i16 sl_WlanRxStatStart(void) -{ - return _SlDrvBasicCmd(SL_OPCODE_WLAN_STARTRXSTATCOMMAND); -} -#endif - -#if _SL_INCLUDE_FUNC(sl_WlanRxStatStop) -_i16 sl_WlanRxStatStop(void) -{ - return _SlDrvBasicCmd(SL_OPCODE_WLAN_STOPRXSTATCOMMAND); -} -#endif - -#if _SL_INCLUDE_FUNC(sl_WlanRxStatGet) -_i16 sl_WlanRxStatGet(SlGetRxStatResponse_t *pRxStat,const _u32 Flags) -{ - _SlCmdCtrl_t CmdCtrl = {SL_OPCODE_WLAN_GETRXSTATCOMMAND, 0, sizeof(SlGetRxStatResponse_t)}; - - _SlDrvMemZero(pRxStat, sizeof(SlGetRxStatResponse_t)); - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&CmdCtrl, pRxStat, NULL)); - - return 0; -} -#endif - - - -/******************************************************************************/ -/* sl_WlanSmartConfigStop */ -/******************************************************************************/ -#if _SL_INCLUDE_FUNC(sl_WlanSmartConfigStop) -_i16 sl_WlanSmartConfigStop(void) -{ - return _SlDrvBasicCmd(SL_OPCODE_WLAN_SMART_CONFIG_STOP_COMMAND); -} -#endif - - -/******************************************************************************/ -/* sl_WlanSmartConfigStart */ -/******************************************************************************/ - - -typedef struct -{ - _WlanSmartConfigStartCommand_t Args; - _i8 Strings[3 * MAX_SMART_CONFIG_KEY]; /* public key + groupId1 key + groupId2 key */ -}_SlSmartConfigStart_t; - -typedef union -{ - _SlSmartConfigStart_t Cmd; - _BasicResponse_t Rsp; -}_SlSmartConfigStartMsg_u; - -#if _SL_INCLUDE_FUNC(sl_WlanSmartConfigStart) - -const _SlCmdCtrl_t _SlSmartConfigStartCmdCtrl = -{ - SL_OPCODE_WLAN_SMART_CONFIG_START_COMMAND, - sizeof(_SlSmartConfigStart_t), - sizeof(_BasicResponse_t) -}; - -_i16 sl_WlanSmartConfigStart( const _u32 groupIdBitmask, - const _u8 cipher, - const _u8 publicKeyLen, - const _u8 group1KeyLen, - const _u8 group2KeyLen, - const _u8* pPublicKey, - const _u8* pGroup1Key, - const _u8* pGroup2Key) -{ - _SlSmartConfigStartMsg_u Msg; - - Msg.Cmd.Args.groupIdBitmask = (_u8)groupIdBitmask; - Msg.Cmd.Args.cipher = (_u8)cipher; - Msg.Cmd.Args.publicKeyLen = (_u8)publicKeyLen; - Msg.Cmd.Args.group1KeyLen = (_u8)group1KeyLen; - Msg.Cmd.Args.group2KeyLen = (_u8)group2KeyLen; - - /* copy keys (if exist) after command (one after another) */ - sl_Memcpy(SMART_CONFIG_START_PUBLIC_KEY_STRING(&Msg), pPublicKey, publicKeyLen); - sl_Memcpy(SMART_CONFIG_START_GROUP1_KEY_STRING(&Msg), pGroup1Key, group1KeyLen); - sl_Memcpy(SMART_CONFIG_START_GROUP2_KEY_STRING(&Msg), pGroup2Key, group2KeyLen); - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlSmartConfigStartCmdCtrl , &Msg, NULL)); - - return (_i16)Msg.Rsp.status; - - -} -#endif - - -/*******************************************************************************/ -/* sl_WlanSetMode */ -/*******************************************************************************/ -typedef union -{ - _WlanSetMode_t Cmd; - _BasicResponse_t Rsp; -}_SlwlanSetModeMsg_u; - -#if _SL_INCLUDE_FUNC(sl_WlanSetMode) - -const _SlCmdCtrl_t _SlWlanSetModeCmdCtrl = -{ - SL_OPCODE_WLAN_SET_MODE, - sizeof(_WlanSetMode_t), - sizeof(_BasicResponse_t) -}; - -/* possible values are: -WLAN_SET_STA_MODE = 1 -WLAN_SET_AP_MODE = 2 -WLAN_SET_P2P_MODE = 3 */ -_i16 sl_WlanSetMode(const _u8 mode) -{ - _SlwlanSetModeMsg_u Msg; - - Msg.Cmd.mode = mode; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlWlanSetModeCmdCtrl , &Msg, NULL)); - - return (_i16)Msg.Rsp.status; -} -#endif - - - - -/*******************************************************************************/ -/* sl_WlanSet */ -/* ******************************************************************************/ -typedef union -{ - _WlanCfgSetGet_t Cmd; - _BasicResponse_t Rsp; -}_SlWlanCfgSetMsg_u; - - -#if _SL_INCLUDE_FUNC(sl_WlanSet) - -const _SlCmdCtrl_t _SlWlanCfgSetCmdCtrl = -{ - SL_OPCODE_WLAN_CFG_SET, - sizeof(_WlanCfgSetGet_t), - sizeof(_BasicResponse_t) -}; - -_i16 sl_WlanSet(const _u16 ConfigId ,const _u16 ConfigOpt,const _u16 ConfigLen,const _u8 *pValues) -{ - _SlWlanCfgSetMsg_u Msg; - _SlCmdExt_t CmdExt; - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.TxPayloadLen = (ConfigLen+3) & (~3); - CmdExt.pTxPayload = (_u8 *)pValues; - - Msg.Cmd.ConfigId = ConfigId; - Msg.Cmd.ConfigLen = ConfigLen; - Msg.Cmd.ConfigOpt = ConfigOpt; - - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlWlanCfgSetCmdCtrl, &Msg, &CmdExt)); - - return (_i16)Msg.Rsp.status; -} -#endif - - -/******************************************************************************/ -/* sl_WlanGet */ -/******************************************************************************/ -typedef union -{ - _WlanCfgSetGet_t Cmd; - _WlanCfgSetGet_t Rsp; -}_SlWlanCfgMsgGet_u; - -#if _SL_INCLUDE_FUNC(sl_WlanGet) - -const _SlCmdCtrl_t _SlWlanCfgGetCmdCtrl = -{ - SL_OPCODE_WLAN_CFG_GET, - sizeof(_WlanCfgSetGet_t), - sizeof(_WlanCfgSetGet_t) -}; - -_i16 sl_WlanGet(const _u16 ConfigId, _u16 *pConfigOpt,_u16 *pConfigLen, _u8 *pValues) -{ - _SlWlanCfgMsgGet_u Msg; - _SlCmdExt_t CmdExt; - - if (*pConfigLen == 0) - { - return SL_EZEROLEN; - } - - _SlDrvResetCmdExt(&CmdExt); - CmdExt.RxPayloadLen = *pConfigLen; - CmdExt.pRxPayload = (_u8 *)pValues; - - Msg.Cmd.ConfigId = ConfigId; - if( pConfigOpt ) - { - Msg.Cmd.ConfigOpt = (_u16)*pConfigOpt; - } - VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlWlanCfgGetCmdCtrl, &Msg, &CmdExt)); - - if( pConfigOpt ) - { - *pConfigOpt = (_u8)Msg.Rsp.ConfigOpt; - } - if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) - { - *pConfigLen = (_u8)CmdExt.RxPayloadLen; - return SL_ESMALLBUF; - } - else - { - *pConfigLen = (_u8)CmdExt.ActualRxPayloadLen; - } - - - return (_i16)Msg.Rsp.Status; -} -#endif diff --git a/drivers/dht/dht.c b/drivers/dht/dht.c deleted file mode 100644 index 5d92ae39a3..0000000000 --- a/drivers/dht/dht.c +++ /dev/null @@ -1,89 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2016 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include - -#include "py/runtime.h" -#include "py/mperrno.h" -#include "py/mphal.h" -#include "extmod/machine_pulse.h" -#include "drivers/dht/dht.h" - -STATIC mp_obj_t dht_readinto(mp_obj_t pin_in, mp_obj_t buf_in) { - mp_hal_pin_obj_t pin = mp_hal_get_pin_obj(pin_in); - mp_hal_pin_open_drain(pin); - - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_WRITE); - - if (bufinfo.len < 5) { - mp_raise_ValueError("buffer too small"); - } - - // issue start command - mp_hal_pin_od_high(pin); - mp_hal_delay_ms(250); - mp_hal_pin_od_low(pin); - mp_hal_delay_ms(18); - - mp_uint_t irq_state = mp_hal_quiet_timing_enter(); - - // release the line so the device can respond - mp_hal_pin_od_high(pin); - mp_hal_delay_us_fast(10); - - // wait for device to respond - mp_uint_t ticks = mp_hal_ticks_us(); - while (mp_hal_pin_read(pin) != 0) { - if ((mp_uint_t)(mp_hal_ticks_us() - ticks) > 100) { - goto timeout; - } - } - - // time pulse, should be 80us - ticks = machine_time_pulse_us(pin, 1, 150); - if ((mp_int_t)ticks < 0) { - goto timeout; - } - - // time 40 pulses for data (either 26us or 70us) - uint8_t *buf = bufinfo.buf; - for (int i = 0; i < 40; ++i) { - ticks = machine_time_pulse_us(pin, 1, 100); - if ((mp_int_t)ticks < 0) { - goto timeout; - } - buf[i / 8] = (buf[i / 8] << 1) | (ticks > 48); - } - - mp_hal_quiet_timing_exit(irq_state); - return mp_const_none; - -timeout: - mp_hal_quiet_timing_exit(irq_state); - mp_raise_OSError(MP_ETIMEDOUT); -} -MP_DEFINE_CONST_FUN_OBJ_2(dht_readinto_obj, dht_readinto); diff --git a/drivers/dht/dht.h b/drivers/dht/dht.h deleted file mode 100644 index 883e077961..0000000000 --- a/drivers/dht/dht.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef MICROPY_INCLUDED_DRIVERS_DHT_DHT_H -#define MICROPY_INCLUDED_DRIVERS_DHT_DHT_H - -#include "py/obj.h" - -MP_DECLARE_CONST_FUN_OBJ_2(dht_readinto_obj); - -#endif // MICROPY_INCLUDED_DRIVERS_DHT_DHT_H diff --git a/drivers/display/lcd160cr.py b/drivers/display/lcd160cr.py deleted file mode 100644 index dd9ab9985b..0000000000 --- a/drivers/display/lcd160cr.py +++ /dev/null @@ -1,474 +0,0 @@ -# Driver for official MicroPython LCD160CR display -# MIT license; Copyright (c) 2017 Damien P. George - -from micropython import const -from utime import sleep_ms -from ustruct import calcsize, pack_into -import uerrno, machine - -# for set_orient -PORTRAIT = const(0) -LANDSCAPE = const(1) -PORTRAIT_UPSIDEDOWN = const(2) -LANDSCAPE_UPSIDEDOWN = const(3) - -# for set_startup_deco; can be or'd -STARTUP_DECO_NONE = const(0) -STARTUP_DECO_MLOGO = const(1) -STARTUP_DECO_INFO = const(2) - -_uart_baud_table = { - 2400: 0, - 4800: 1, - 9600: 2, - 19200: 3, - 38400: 4, - 57600: 5, - 115200: 6, - 230400: 7, - 460800: 8, -} - -class LCD160CR: - def __init__(self, connect=None, *, pwr=None, i2c=None, spi=None, i2c_addr=98): - if connect in ('X', 'Y', 'XY', 'YX'): - i = connect[-1] - j = connect[0] - y = j + '4' - elif connect == 'C': - i = 2 - j = 2 - y = 'A7' - else: - if pwr is None or i2c is None or spi is None: - raise ValueError('must specify valid "connect" or all of "pwr", "i2c" and "spi"') - - if pwr is None: - pwr = machine.Pin(y, machine.Pin.OUT) - if i2c is None: - i2c = machine.I2C(i, freq=1000000) - if spi is None: - spi = machine.SPI(j, baudrate=13500000, polarity=0, phase=0) - - if not pwr.value(): - pwr(1) - sleep_ms(10) - # else: - # alread have power - # lets be optimistic... - - # set connections - self.pwr = pwr - self.i2c = i2c - self.spi = spi - self.i2c_addr = i2c_addr - - # create temp buffers and memoryviews - self.buf16 = bytearray(16) - self.buf19 = bytearray(19) - self.buf = [None] * 10 - for i in range(1, 10): - self.buf[i] = memoryview(self.buf16)[0:i] - self.buf1 = self.buf[1] - self.array4 = [0, 0, 0, 0] - - # set default orientation and window - self.set_orient(PORTRAIT) - self._fcmd2b('= n: - self.i2c.readfrom_into(self.i2c_addr, buf) - return - t -= 1 - sleep_ms(1) - raise OSError(uerrno.ETIMEDOUT) - - def oflush(self, n=255): - t = 5000 - while t: - self.i2c.readfrom_into(self.i2c_addr + 1, self.buf1) - r = self.buf1[0] - if r >= n: - return - t -= 1 - machine.idle() - raise OSError(uerrno.ETIMEDOUT) - - def iflush(self): - t = 5000 - while t: - self.i2c.readfrom_into(self.i2c_addr, self.buf16) - if self.buf16[0] == 0: - return - t -= 1 - sleep_ms(1) - raise OSError(uerrno.ETIMEDOUT) - - #### MISC METHODS #### - - @staticmethod - def rgb(r, g, b): - return ((b & 0xf8) << 8) | ((g & 0xfc) << 3) | (r >> 3) - - @staticmethod - def clip_line(c, w, h): - while True: - ca = ce = 0 - if c[1] < 0: - ca |= 8 - elif c[1] > h: - ca |= 4 - if c[0] < 0: - ca |= 1 - elif c[0] > w: - ca |= 2 - if c[3] < 0: - ce |= 8 - elif c[3] > h: - ce |= 4 - if c[2] < 0: - ce |= 1 - elif c[2] > w: - ce |= 2 - if ca & ce: - return False - elif ca | ce: - ca |= ce - if ca & 1: - if c[2] < c[0]: - c[0], c[2] = c[2], c[0] - c[1], c[3] = c[3], c[1] - c[1] += ((-c[0]) * (c[3] - c[1])) // (c[2] - c[0]) - c[0] = 0 - elif ca & 2: - if c[2] < c[0]: - c[0], c[2] = c[2], c[0] - c[1], c[3] = c[3], c[1] - c[3] += ((w - 1 - c[2]) * (c[3] - c[1])) // (c[2] - c[0]) - c[2] = w - 1 - elif ca & 4: - if c[0] == c[2]: - if c[1] >= h: - c[1] = h - 1 - if c[3] >= h: - c[3] = h - 1 - else: - if c[3] < c[1]: - c[0], c[2] = c[2], c[0] - c[1], c[3] = c[3], c[1] - c[2] += ((h - 1 - c[3]) * (c[2] - c[0])) // (c[3] - c[1]) - c[3] = h - 1 - else: - if c[0] == c[2]: - if c[1] < 0: - c[1] = 0 - if c[3] < 0: - c[3] = 0 - else: - if c[3] < c[1]: - c[0], c[2] = c[2], c[0] - c[1], c[3] = c[3], c[1] - c[0] += ((-c[1]) * (c[2] - c[0])) // (c[3] - c[1]) - c[1] = 0 - else: - return True - - #### SETUP COMMANDS #### - - def set_power(self, on): - self.pwr(on) - sleep_ms(15) - - def set_orient(self, orient): - self._fcmd2('= 2: - self.i2c.readfrom_into(self.i2c_addr, self.buf[3]) - return self.buf[3][1] | self.buf[3][2] << 8 - t -= 1 - sleep_ms(1) - raise OSError(uerrno.ETIMEDOUT) - - def get_line(self, x, y, buf): - l = len(buf) // 2 - self._fcmd2b('= l: - self.i2c.readfrom_into(self.i2c_addr, buf) - return - t -= 1 - sleep_ms(1) - raise OSError(uerrno.ETIMEDOUT) - - def screen_dump(self, buf, x=0, y=0, w=None, h=None): - if w is None: - w = self.w - x - if h is None: - h = self.h - y - if w <= 127: - line = bytearray(2 * w + 1) - line2 = None - else: - # split line if more than 254 bytes needed - buflen = (w + 1) // 2 - line = bytearray(2 * buflen + 1) - line2 = memoryview(line)[:2 * (w - buflen) + 1] - for i in range(min(len(buf) // (2 * w), h)): - ix = i * w * 2 - self.get_line(x, y + i, line) - buf[ix:ix + len(line) - 1] = memoryview(line)[1:] - ix += len(line) - 1 - if line2: - self.get_line(x + buflen, y + i, line2) - buf[ix:ix + len(line2) - 1] = memoryview(line2)[1:] - ix += len(line2) - 1 - - def screen_load(self, buf): - l = self.w * self.h * 2+2 - self._fcmd2b('= 0x200: - self._send(ar[n:n + 0x200]) - n += 0x200 - else: - self._send(ar[n:]) - while n < self.w * self.h * 2: - self._send(b'\x00') - n += 1 - - #### TEXT COMMANDS #### - - def set_pos(self, x, y): - self._fcmd2('= self.w or y >= self.h: - return - elif x < 0 or y < 0: - left = top = True - if x < 0: - left = False - w += x - x = 0 - if y < 0: - top = False - h += y - y = 0 - if cmd == 0x51 or cmd == 0x72: - # draw interior - self._fcmd2b('> 7 != 0 - - def get_touch(self): - self._send(b'\x02T') # implicit LCD output flush - b = self.buf[4] - self._waitfor(3, b) - return b[1] >> 7, b[2], b[3] - - #### ADVANCED COMMANDS #### - - def set_spi_win(self, x, y, w, h): - pack_into(' 32: - raise ValueError('length must be 32 or less') - self._fcmd2(' 0xffff: - raise ValueError('length must be 65535 or less') - self.oflush() - self._fcmd2(' 0: - s = '%6.3fV' % data[i] - else: - s = '%5.1f°C' % data[i] - if lcd.h == 160: - lcd.set_font(1, bold=0, scale=1) - else: - lcd.set_font(1, bold=0, scale=1, trans=1) - lcd.set_pos(45, lcd.h-60 + i * 16) - lcd.write(s) - -def test_features(lcd, orient=lcd160cr.PORTRAIT): - # if we run on pyboard then use ADC and RTC features - try: - import pyb - adc = pyb.ADCAll(12, 0xf0000) - rtc = pyb.RTC() - except: - adc = None - rtc = None - - # set orientation and clear screen - lcd = get_lcd(lcd) - lcd.set_orient(orient) - lcd.set_pen(0, 0) - lcd.erase() - - # create M-logo - mlogo = framebuf.FrameBuffer(bytearray(17 * 17 * 2), 17, 17, framebuf.RGB565) - mlogo.fill(0) - mlogo.fill_rect(1, 1, 15, 15, 0xffffff) - mlogo.vline(4, 4, 12, 0) - mlogo.vline(8, 1, 12, 0) - mlogo.vline(12, 4, 12, 0) - mlogo.vline(14, 13, 2, 0) - - # create inline framebuf - offx = 14 - offy = 19 - w = 100 - h = 75 - fbuf = framebuf.FrameBuffer(bytearray(w * h * 2), w, h, framebuf.RGB565) - lcd.set_spi_win(offx, offy, w, h) - - # initialise loop parameters - tx = ty = 0 - t0 = time.ticks_us() - - for i in range(300): - # update position of cross-hair - t, tx2, ty2 = lcd.get_touch() - if t: - tx2 -= offx - ty2 -= offy - if tx2 >= 0 and ty2 >= 0 and tx2 < w and ty2 < h: - tx, ty = tx2, ty2 - else: - tx = (tx + 1) % w - ty = (ty + 1) % h - - # create and show the inline framebuf - fbuf.fill(lcd.rgb(128 + int(64 * math.cos(0.1 * i)), 128, 192)) - fbuf.line(w // 2, h // 2, - w // 2 + int(40 * math.cos(0.2 * i)), - h // 2 + int(40 * math.sin(0.2 * i)), - lcd.rgb(128, 255, 64)) - fbuf.hline(0, ty, w, lcd.rgb(64, 64, 64)) - fbuf.vline(tx, 0, h, lcd.rgb(64, 64, 64)) - fbuf.rect(tx - 3, ty - 3, 7, 7, lcd.rgb(64, 64, 64)) - for phase in (-0.2, 0, 0.2): - x = w // 2 - 8 + int(50 * math.cos(0.05 * i + phase)) - y = h // 2 - 8 + int(32 * math.sin(0.05 * i + phase)) - fbuf.blit(mlogo, x, y) - for j in range(-3, 3): - fbuf.text('MicroPython', - 5, h // 2 + 9 * j + int(20 * math.sin(0.1 * (i + j))), - lcd.rgb(128 + 10 * j, 0, 128 - 10 * j)) - lcd.show_framebuf(fbuf) - - # show results from the ADC - if adc: - show_adc(lcd, adc) - - # show the time - if rtc: - lcd.set_pos(2, 0) - lcd.set_font(1) - t = rtc.datetime() - lcd.write('%4d-%02d-%02d %2d:%02d:%02d.%01d' % (t[0], t[1], t[2], t[4], t[5], t[6], t[7] // 100000)) - - # compute the frame rate - t1 = time.ticks_us() - dt = time.ticks_diff(t1, t0) - t0 = t1 - - # show the frame rate - lcd.set_pos(2, 9) - lcd.write('%.2f fps' % (1000000 / dt)) - -def test_mandel(lcd, orient=lcd160cr.PORTRAIT): - # set orientation and clear screen - lcd = get_lcd(lcd) - lcd.set_orient(orient) - lcd.set_pen(0, 0xffff) - lcd.erase() - - # function to compute Mandelbrot pixels - def in_set(c): - z = 0 - for i in range(32): - z = z * z + c - if abs(z) > 100: - return i - return 0 - - # cache width and height of LCD - w = lcd.w - h = lcd.h - - # create the buffer for each line and set SPI parameters - line = bytearray(w * 2) - lcd.set_spi_win(0, 0, w, h) - spi = lcd.fast_spi() - - # draw the Mandelbrot set line-by-line - hh = ((h - 1) / 3.2) - ww = ((w - 1) / 2.4) - for v in range(h): - for u in range(w): - c = in_set((v / hh - 2.3) + (u / ww - 1.2) * 1j) - if c < 16: - rgb = c << 12 | c << 6 - else: - rgb = 0xf800 | c << 6 - line[2 * u] = rgb - line[2 * u + 1] = rgb >> 8 - spi.write(line) - -def test_all(lcd, orient=lcd160cr.PORTRAIT): - lcd = get_lcd(lcd) - test_features(lcd, orient) - test_mandel(lcd, orient) - -print('To run all tests: test_all()') -print('Individual tests are: test_features, test_mandel') -print(' argument should be a connection, eg "X", or an LCD160CR object') diff --git a/drivers/display/ssd1306.py b/drivers/display/ssd1306.py deleted file mode 100644 index cd358d00e2..0000000000 --- a/drivers/display/ssd1306.py +++ /dev/null @@ -1,160 +0,0 @@ -# MicroPython SSD1306 OLED driver, I2C and SPI interfaces - -from micropython import const -import framebuf - - -# register definitions -SET_CONTRAST = const(0x81) -SET_ENTIRE_ON = const(0xa4) -SET_NORM_INV = const(0xa6) -SET_DISP = const(0xae) -SET_MEM_ADDR = const(0x20) -SET_COL_ADDR = const(0x21) -SET_PAGE_ADDR = const(0x22) -SET_DISP_START_LINE = const(0x40) -SET_SEG_REMAP = const(0xa0) -SET_MUX_RATIO = const(0xa8) -SET_COM_OUT_DIR = const(0xc0) -SET_DISP_OFFSET = const(0xd3) -SET_COM_PIN_CFG = const(0xda) -SET_DISP_CLK_DIV = const(0xd5) -SET_PRECHARGE = const(0xd9) -SET_VCOM_DESEL = const(0xdb) -SET_CHARGE_PUMP = const(0x8d) - - -class SSD1306: - def __init__(self, width, height, external_vcc): - self.width = width - self.height = height - self.external_vcc = external_vcc - self.pages = self.height // 8 - self.buffer = bytearray(self.pages * self.width) - fb = framebuf.FrameBuffer(self.buffer, self.width, self.height, framebuf.MONO_VLSB) - self.framebuf = fb - # Provide methods for accessing FrameBuffer graphics primitives. This is a - # workround because inheritance from a native class is currently unsupported. - # http://docs.micropython.org/en/latest/pyboard/library/framebuf.html - self.fill = fb.fill - self.pixel = fb.pixel - self.hline = fb.hline - self.vline = fb.vline - self.line = fb.line - self.rect = fb.rect - self.fill_rect = fb.fill_rect - self.text = fb.text - self.scroll = fb.scroll - self.blit = fb.blit - self.init_display() - - def init_display(self): - for cmd in ( - SET_DISP | 0x00, # off - # address setting - SET_MEM_ADDR, 0x00, # horizontal - # resolution and layout - SET_DISP_START_LINE | 0x00, - SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0 - SET_MUX_RATIO, self.height - 1, - SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0 - SET_DISP_OFFSET, 0x00, - SET_COM_PIN_CFG, 0x02 if self.height == 32 else 0x12, - # timing and driving scheme - SET_DISP_CLK_DIV, 0x80, - SET_PRECHARGE, 0x22 if self.external_vcc else 0xf1, - SET_VCOM_DESEL, 0x30, # 0.83*Vcc - # display - SET_CONTRAST, 0xff, # maximum - SET_ENTIRE_ON, # output follows RAM contents - SET_NORM_INV, # not inverted - # charge pump - SET_CHARGE_PUMP, 0x10 if self.external_vcc else 0x14, - SET_DISP | 0x01): # on - self.write_cmd(cmd) - self.fill(0) - self.show() - - def poweroff(self): - self.write_cmd(SET_DISP | 0x00) - - def poweron(self): - self.write_cmd(SET_DISP | 0x01) - - def contrast(self, contrast): - self.write_cmd(SET_CONTRAST) - self.write_cmd(contrast) - - def invert(self, invert): - self.write_cmd(SET_NORM_INV | (invert & 1)) - - def show(self): - x0 = 0 - x1 = self.width - 1 - if self.width == 64: - # displays with width of 64 pixels are shifted by 32 - x0 += 32 - x1 += 32 - self.write_cmd(SET_COL_ADDR) - self.write_cmd(x0) - self.write_cmd(x1) - self.write_cmd(SET_PAGE_ADDR) - self.write_cmd(0) - self.write_cmd(self.pages - 1) - self.write_data(self.buffer) - - -class SSD1306_I2C(SSD1306): - def __init__(self, width, height, i2c, addr=0x3c, external_vcc=False): - self.i2c = i2c - self.addr = addr - self.temp = bytearray(2) - super().__init__(width, height, external_vcc) - - def write_cmd(self, cmd): - self.temp[0] = 0x80 # Co=1, D/C#=0 - self.temp[1] = cmd - self.i2c.writeto(self.addr, self.temp) - - def write_data(self, buf): - self.temp[0] = self.addr << 1 - self.temp[1] = 0x40 # Co=0, D/C#=1 - self.i2c.start() - self.i2c.write(self.temp) - self.i2c.write(buf) - self.i2c.stop() - - -class SSD1306_SPI(SSD1306): - def __init__(self, width, height, spi, dc, res, cs, external_vcc=False): - self.rate = 10 * 1024 * 1024 - dc.init(dc.OUT, value=0) - res.init(res.OUT, value=0) - cs.init(cs.OUT, value=1) - self.spi = spi - self.dc = dc - self.res = res - self.cs = cs - import time - self.res(1) - time.sleep_ms(1) - self.res(0) - time.sleep_ms(10) - self.res(1) - super().__init__(width, height, external_vcc) - - def write_cmd(self, cmd): - self.spi.init(baudrate=self.rate, polarity=0, phase=0) - self.cs(1) - self.dc(0) - self.cs(0) - self.spi.write(bytearray([cmd])) - self.cs(1) - - def write_data(self, buf): - self.spi.init(baudrate=self.rate, polarity=0, phase=0) - self.cs(1) - self.dc(1) - self.cs(0) - self.spi.write(buf) - self.cs(1) diff --git a/drivers/memory/spiflash.c b/drivers/memory/spiflash.c deleted file mode 100644 index 08564d0540..0000000000 --- a/drivers/memory/spiflash.c +++ /dev/null @@ -1,199 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2016-2017 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include -#include - -#include "py/mperrno.h" -#include "py/mphal.h" -#include "extmod/machine_spi.h" -#include "drivers/memory/spiflash.h" - -#define CMD_WRITE (0x02) -#define CMD_READ (0x03) -#define CMD_WRDI (0x04) -#define CMD_RDSR (0x05) -#define CMD_WREN (0x06) -#define CMD_SEC_ERASE (0x20) -#define WAIT_SR_TIMEOUT (1000000) - -#define PAGE_SIZE (256) // maximum bytes we can write in one SPI transfer -#define SECTOR_SIZE (4096) // size of erase sector - -// Note: this code is not reentrant with this shared buffer -STATIC uint8_t buf[SECTOR_SIZE]; - -void mp_spiflash_init(mp_spiflash_t *self) { - mp_hal_pin_write(self->cs, 1); - mp_hal_pin_output(self->cs); - const mp_machine_spi_p_t *protocol = self->spi->type->protocol; - protocol->init(self->spi, 0, NULL, (mp_map_t*)&mp_const_empty_map); -} - -STATIC void mp_spiflash_acquire_bus(mp_spiflash_t *self) { - // can be used for actions needed to acquire bus - (void)self; -} - -STATIC void mp_spiflash_release_bus(mp_spiflash_t *self) { - // can be used for actions needed to release bus - (void)self; -} - -STATIC void mp_spiflash_transfer(mp_spiflash_t *self, size_t len, const uint8_t *src, uint8_t *dest) { - const mp_machine_spi_p_t *protocol = self->spi->type->protocol; - protocol->transfer(self->spi, len, src, dest); -} - -STATIC int mp_spiflash_wait_sr(mp_spiflash_t *self, uint8_t mask, uint8_t val, uint32_t timeout) { - uint8_t cmd[1] = {CMD_RDSR}; - mp_hal_pin_write(self->cs, 0); - mp_spiflash_transfer(self, 1, cmd, NULL); - for (; timeout; --timeout) { - mp_spiflash_transfer(self, 1, cmd, cmd); - if ((cmd[0] & mask) == val) { - break; - } - } - mp_hal_pin_write(self->cs, 1); - if ((cmd[0] & mask) == val) { - return 0; // success - } else if (timeout == 0) { - return -MP_ETIMEDOUT; - } else { - return -MP_EIO; - } -} - -STATIC int mp_spiflash_wait_wel1(mp_spiflash_t *self) { - return mp_spiflash_wait_sr(self, 2, 2, WAIT_SR_TIMEOUT); -} - -STATIC int mp_spiflash_wait_wip0(mp_spiflash_t *self) { - return mp_spiflash_wait_sr(self, 1, 0, WAIT_SR_TIMEOUT); -} - -STATIC void mp_spiflash_write_cmd(mp_spiflash_t *self, uint8_t cmd) { - mp_hal_pin_write(self->cs, 0); - mp_spiflash_transfer(self, 1, &cmd, NULL); - mp_hal_pin_write(self->cs, 1); -} - -STATIC int mp_spiflash_erase_sector(mp_spiflash_t *self, uint32_t addr) { - // enable writes - mp_spiflash_write_cmd(self, CMD_WREN); - - // wait WEL=1 - int ret = mp_spiflash_wait_wel1(self); - if (ret != 0) { - return ret; - } - - // erase the sector - mp_hal_pin_write(self->cs, 0); - uint8_t cmd[4] = {CMD_SEC_ERASE, addr >> 16, addr >> 8, addr}; - mp_spiflash_transfer(self, 4, cmd, NULL); - mp_hal_pin_write(self->cs, 1); - - // wait WIP=0 - return mp_spiflash_wait_wip0(self); -} - -STATIC int mp_spiflash_write_page(mp_spiflash_t *self, uint32_t addr, const uint8_t *src) { - // enable writes - mp_spiflash_write_cmd(self, CMD_WREN); - - // wait WEL=1 - int ret = mp_spiflash_wait_wel1(self); - if (ret != 0) { - return ret; - } - - // write the page - mp_hal_pin_write(self->cs, 0); - uint8_t cmd[4] = {CMD_WRITE, addr >> 16, addr >> 8, addr}; - mp_spiflash_transfer(self, 4, cmd, NULL); - mp_spiflash_transfer(self, PAGE_SIZE, src, NULL); - mp_hal_pin_write(self->cs, 1); - - // wait WIP=0 - return mp_spiflash_wait_wip0(self); -} - -void mp_spiflash_read(mp_spiflash_t *self, uint32_t addr, size_t len, uint8_t *dest) { - mp_spiflash_acquire_bus(self); - uint8_t cmd[4] = {CMD_READ, addr >> 16, addr >> 8, addr}; - mp_hal_pin_write(self->cs, 0); - mp_spiflash_transfer(self, 4, cmd, NULL); - mp_spiflash_transfer(self, len, dest, dest); - mp_hal_pin_write(self->cs, 1); - mp_spiflash_release_bus(self); -} - -int mp_spiflash_write(mp_spiflash_t *self, uint32_t addr, size_t len, const uint8_t *src) { - // TODO optimise so we don't need to erase multiple times for successive writes to a sector - - // align to 4096 sector - uint32_t offset = addr & 0xfff; - addr = (addr >> 12) << 12; - - // restriction for now, so we don't need to erase multiple pages - if (offset + len > sizeof(buf)) { - printf("mp_spiflash_write: len is too large\n"); - return -MP_EIO; - } - - mp_spiflash_acquire_bus(self); - - // read sector - uint8_t cmd[4] = {CMD_READ, addr >> 16, addr >> 8, addr}; - mp_hal_pin_write(self->cs, 0); - mp_spiflash_transfer(self, 4, cmd, NULL); - mp_spiflash_transfer(self, SECTOR_SIZE, buf, buf); - mp_hal_pin_write(self->cs, 1); - - // erase sector - int ret = mp_spiflash_erase_sector(self, addr); - if (ret != 0) { - mp_spiflash_release_bus(self); - return ret; - } - - // copy new block into buffer - memcpy(buf + offset, src, len); - - // write sector in pages of 256 bytes - for (int i = 0; i < SECTOR_SIZE; i += 256) { - ret = mp_spiflash_write_page(self, addr + i, buf + i); - if (ret != 0) { - mp_spiflash_release_bus(self); - return ret; - } - } - - mp_spiflash_release_bus(self); - return 0; // success -} diff --git a/drivers/nrf24l01/nrf24l01.py b/drivers/nrf24l01/nrf24l01.py deleted file mode 100644 index 7274a79278..0000000000 --- a/drivers/nrf24l01/nrf24l01.py +++ /dev/null @@ -1,252 +0,0 @@ -"""NRF24L01 driver for MicroPython -""" - -from micropython import const -import utime - -# nRF24L01+ registers -CONFIG = const(0x00) -EN_RXADDR = const(0x02) -SETUP_AW = const(0x03) -SETUP_RETR = const(0x04) -RF_CH = const(0x05) -RF_SETUP = const(0x06) -STATUS = const(0x07) -RX_ADDR_P0 = const(0x0a) -TX_ADDR = const(0x10) -RX_PW_P0 = const(0x11) -FIFO_STATUS = const(0x17) -DYNPD = const(0x1c) - -# CONFIG register -EN_CRC = const(0x08) # enable CRC -CRCO = const(0x04) # CRC encoding scheme; 0=1 byte, 1=2 bytes -PWR_UP = const(0x02) # 1=power up, 0=power down -PRIM_RX = const(0x01) # RX/TX control; 0=PTX, 1=PRX - -# RF_SETUP register -POWER_0 = const(0x00) # -18 dBm -POWER_1 = const(0x02) # -12 dBm -POWER_2 = const(0x04) # -6 dBm -POWER_3 = const(0x06) # 0 dBm -SPEED_1M = const(0x00) -SPEED_2M = const(0x08) -SPEED_250K = const(0x20) - -# STATUS register -RX_DR = const(0x40) # RX data ready; write 1 to clear -TX_DS = const(0x20) # TX data sent; write 1 to clear -MAX_RT = const(0x10) # max retransmits reached; write 1 to clear - -# FIFO_STATUS register -RX_EMPTY = const(0x01) # 1 if RX FIFO is empty - -# constants for instructions -R_RX_PL_WID = const(0x60) # read RX payload width -R_RX_PAYLOAD = const(0x61) # read RX payload -W_TX_PAYLOAD = const(0xa0) # write TX payload -FLUSH_TX = const(0xe1) # flush TX FIFO -FLUSH_RX = const(0xe2) # flush RX FIFO -NOP = const(0xff) # use to read STATUS register - -class NRF24L01: - def __init__(self, spi, cs, ce, channel=46, payload_size=16): - assert payload_size <= 32 - - self.buf = bytearray(1) - - # store the pins - self.spi = spi - self.cs = cs - self.ce = ce - - # init the SPI bus and pins - self.init_spi(4000000) - cs.init(cs.OUT, value=1) - ce.init(ce.OUT, value=0) - - # reset everything - self.ce(0) - self.cs(1) - self.payload_size = payload_size - self.pipe0_read_addr = None - utime.sleep_ms(5) - - # set address width to 5 bytes and check for device present - self.reg_write(SETUP_AW, 0b11) - if self.reg_read(SETUP_AW) != 0b11: - raise OSError("nRF24L01+ Hardware not responding") - - # disable dynamic payloads - self.reg_write(DYNPD, 0) - - # auto retransmit delay: 1750us - # auto retransmit count: 8 - self.reg_write(SETUP_RETR, (6 << 4) | 8) - - # set rf power and speed - self.set_power_speed(POWER_3, SPEED_250K) # Best for point to point links - - # init CRC - self.set_crc(2) - - # clear status flags - self.reg_write(STATUS, RX_DR | TX_DS | MAX_RT) - - # set channel - self.set_channel(channel) - - # flush buffers - self.flush_rx() - self.flush_tx() - - def init_spi(self, baudrate): - try: - master = self.spi.MASTER - except AttributeError: - self.spi.init(baudrate=baudrate, polarity=0, phase=0) - else: - self.spi.init(master, baudrate=baudrate, polarity=0, phase=0) - - def reg_read(self, reg): - self.cs(0) - self.spi.readinto(self.buf, reg) - self.spi.readinto(self.buf) - self.cs(1) - return self.buf[0] - - def reg_write_bytes(self, reg, buf): - self.cs(0) - self.spi.readinto(self.buf, 0x20 | reg) - self.spi.write(buf) - self.cs(1) - return self.buf[0] - - def reg_write(self, reg, value): - self.cs(0) - self.spi.readinto(self.buf, 0x20 | reg) - ret = self.buf[0] - self.spi.readinto(self.buf, value) - self.cs(1) - return ret - - def flush_rx(self): - self.cs(0) - self.spi.readinto(self.buf, FLUSH_RX) - self.cs(1) - - def flush_tx(self): - self.cs(0) - self.spi.readinto(self.buf, FLUSH_TX) - self.cs(1) - - # power is one of POWER_x defines; speed is one of SPEED_x defines - def set_power_speed(self, power, speed): - setup = self.reg_read(RF_SETUP) & 0b11010001 - self.reg_write(RF_SETUP, setup | power | speed) - - # length in bytes: 0, 1 or 2 - def set_crc(self, length): - config = self.reg_read(CONFIG) & ~(CRCO | EN_CRC) - if length == 0: - pass - elif length == 1: - config |= EN_CRC - else: - config |= EN_CRC | CRCO - self.reg_write(CONFIG, config) - - def set_channel(self, channel): - self.reg_write(RF_CH, min(channel, 125)) - - # address should be a bytes object 5 bytes long - def open_tx_pipe(self, address): - assert len(address) == 5 - self.reg_write_bytes(RX_ADDR_P0, address) - self.reg_write_bytes(TX_ADDR, address) - self.reg_write(RX_PW_P0, self.payload_size) - - # address should be a bytes object 5 bytes long - # pipe 0 and 1 have 5 byte address - # pipes 2-5 use same 4 most-significant bytes as pipe 1, plus 1 extra byte - def open_rx_pipe(self, pipe_id, address): - assert len(address) == 5 - assert 0 <= pipe_id <= 5 - if pipe_id == 0: - self.pipe0_read_addr = address - if pipe_id < 2: - self.reg_write_bytes(RX_ADDR_P0 + pipe_id, address) - else: - self.reg_write(RX_ADDR_P0 + pipe_id, address[0]) - self.reg_write(RX_PW_P0 + pipe_id, self.payload_size) - self.reg_write(EN_RXADDR, self.reg_read(EN_RXADDR) | (1 << pipe_id)) - - def start_listening(self): - self.reg_write(CONFIG, self.reg_read(CONFIG) | PWR_UP | PRIM_RX) - self.reg_write(STATUS, RX_DR | TX_DS | MAX_RT) - - if self.pipe0_read_addr is not None: - self.reg_write_bytes(RX_ADDR_P0, self.pipe0_read_addr) - - self.flush_rx() - self.flush_tx() - self.ce(1) - utime.sleep_us(130) - - def stop_listening(self): - self.ce(0) - self.flush_tx() - self.flush_rx() - - # returns True if any data available to recv - def any(self): - return not bool(self.reg_read(FIFO_STATUS) & RX_EMPTY) - - def recv(self): - # get the data - self.cs(0) - self.spi.readinto(self.buf, R_RX_PAYLOAD) - buf = self.spi.read(self.payload_size) - self.cs(1) - # clear RX ready flag - self.reg_write(STATUS, RX_DR) - - return buf - - # blocking wait for tx complete - def send(self, buf, timeout=500): - send_nonblock = self.send_start(buf) - start = utime.ticks_ms() - result = None - while result is None and utime.ticks_diff(utime.ticks_ms(), start) < timeout: - result = self.send_done() # 1 == success, 2 == fail - if result == 2: - raise OSError("send failed") - - # non-blocking tx - def send_start(self, buf): - # power up - self.reg_write(CONFIG, (self.reg_read(CONFIG) | PWR_UP) & ~PRIM_RX) - utime.sleep_us(150) - # send the data - self.cs(0) - self.spi.readinto(self.buf, W_TX_PAYLOAD) - self.spi.write(buf) - if len(buf) < self.payload_size: - self.spi.write(b'\x00' * (self.payload_size - len(buf))) # pad out data - self.cs(1) - - # enable the chip so it can send the data - self.ce(1) - utime.sleep_us(15) # needs to be >10us - self.ce(0) - - # returns None if send still in progress, 1 for success, 2 for fail - def send_done(self): - if not (self.reg_read(STATUS) & (TX_DS | MAX_RT)): - return None # tx not finished - - # either finished or failed: get and clear status flags, power down - status = self.reg_write(STATUS, RX_DR | TX_DS | MAX_RT) - self.reg_write(CONFIG, self.reg_read(CONFIG) & ~PWR_UP) - return 1 if status & TX_DS else 2 diff --git a/drivers/nrf24l01/nrf24l01test.py b/drivers/nrf24l01/nrf24l01test.py deleted file mode 100644 index 5413511c3b..0000000000 --- a/drivers/nrf24l01/nrf24l01test.py +++ /dev/null @@ -1,107 +0,0 @@ -"""Test for nrf24l01 module.""" - -import struct -import utime -from machine import Pin, SPI -from nrf24l01 import NRF24L01 - -pipes = (b'\xf0\xf0\xf0\xf0\xe1', b'\xf0\xf0\xf0\xf0\xd2') - -def master(): - nrf = NRF24L01(SPI(2), Pin('Y5'), Pin('Y4'), payload_size=8) - - nrf.open_tx_pipe(pipes[0]) - nrf.open_rx_pipe(1, pipes[1]) - nrf.start_listening() - - num_needed = 16 - num_successes = 0 - num_failures = 0 - led_state = 0 - - print('NRF24L01 master mode, sending %d packets...' % num_needed) - - while num_successes < num_needed and num_failures < num_needed: - # stop listening and send packet - nrf.stop_listening() - millis = utime.ticks_ms() - led_state = max(1, (led_state << 1) & 0x0f) - print('sending:', millis, led_state) - try: - nrf.send(struct.pack('ii', millis, led_state)) - except OSError: - pass - - # start listening again - nrf.start_listening() - - # wait for response, with 250ms timeout - start_time = utime.ticks_ms() - timeout = False - while not nrf.any() and not timeout: - if utime.ticks_diff(utime.ticks_ms(), start_time) > 250: - timeout = True - - if timeout: - print('failed, response timed out') - num_failures += 1 - - else: - # recv packet - got_millis, = struct.unpack('i', nrf.recv()) - - # print response and round-trip delay - print('got response:', got_millis, '(delay', utime.ticks_diff(utime.ticks_ms(), got_millis), 'ms)') - num_successes += 1 - - # delay then loop - utime.sleep_ms(250) - - print('master finished sending; successes=%d, failures=%d' % (num_successes, num_failures)) - -def slave(): - nrf = NRF24L01(SPI(2), Pin('Y5'), Pin('Y4'), payload_size=8) - - nrf.open_tx_pipe(pipes[1]) - nrf.open_rx_pipe(1, pipes[0]) - nrf.start_listening() - - print('NRF24L01 slave mode, waiting for packets... (ctrl-C to stop)') - - while True: - machine.idle() - if nrf.any(): - while nrf.any(): - buf = nrf.recv() - millis, led_state = struct.unpack('ii', buf) - print('received:', millis, led_state) - for led in leds: - if led_state & 1: - led.on() - else: - led.off() - led_state >>= 1 - utime.sleep_ms(15) - - nrf.stop_listening() - try: - nrf.send(struct.pack('i', millis)) - except OSError: - pass - print('sent response') - nrf.start_listening() - -try: - import pyb - leds = [pyb.LED(i + 1) for i in range(4)] -except: - leds = [] - -print('NRF24L01 test module loaded') -print('NRF24L01 pinout for test:') -print(' CE on Y4') -print(' CSN on Y5') -print(' SCK on Y6') -print(' MISO on Y7') -print(' MOSI on Y8') -print('run nrf24l01test.slave() on slave, then nrf24l01test.master() on master') diff --git a/drivers/onewire/ds18x20.py b/drivers/onewire/ds18x20.py deleted file mode 100644 index bf06094835..0000000000 --- a/drivers/onewire/ds18x20.py +++ /dev/null @@ -1,51 +0,0 @@ -# DS18x20 temperature sensor driver for MicroPython. -# MIT license; Copyright (c) 2016 Damien P. George - -from micropython import const - -_CONVERT = const(0x44) -_RD_SCRATCH = const(0xbe) -_WR_SCRATCH = const(0x4e) - -class DS18X20: - def __init__(self, onewire): - self.ow = onewire - self.buf = bytearray(9) - - def scan(self): - return [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28] - - def convert_temp(self): - self.ow.reset(True) - self.ow.writebyte(self.ow.SKIP_ROM) - self.ow.writebyte(_CONVERT) - - def read_scratch(self, rom): - self.ow.reset(True) - self.ow.select_rom(rom) - self.ow.writebyte(_RD_SCRATCH) - self.ow.readinto(self.buf) - if self.ow.crc8(self.buf): - raise Exception('CRC error') - return self.buf - - def write_scratch(self, rom, buf): - self.ow.reset(True) - self.ow.select_rom(rom) - self.ow.writebyte(_WR_SCRATCH) - self.ow.write(buf) - - def read_temp(self, rom): - buf = self.read_scratch(rom) - if rom[0] == 0x10: - if buf[1]: - t = buf[0] >> 1 | 0x80 - t = -((~t + 1) & 0xff) - else: - t = buf[0] >> 1 - return t - 0.25 + (buf[7] - buf[6]) / buf[7] - else: - t = buf[1] << 8 | buf[0] - if t & 0x8000: # sign bit set - t = -((t ^ 0xffff) + 1) - return t / 16 diff --git a/drivers/onewire/onewire.py b/drivers/onewire/onewire.py deleted file mode 100644 index 3309ba0d27..0000000000 --- a/drivers/onewire/onewire.py +++ /dev/null @@ -1,91 +0,0 @@ -# 1-Wire driver for MicroPython -# MIT license; Copyright (c) 2016 Damien P. George - -from micropython import const -import _onewire as _ow - -class OneWireError(Exception): - pass - -class OneWire: - SEARCH_ROM = const(0xf0) - MATCH_ROM = const(0x55) - SKIP_ROM = const(0xcc) - - def __init__(self, pin): - self.pin = pin - self.pin.init(pin.OPEN_DRAIN, pin.PULL_UP) - - def reset(self, required=False): - reset = _ow.reset(self.pin) - if required and not reset: - raise OneWireError - return reset - - def readbit(self): - return _ow.readbit(self.pin) - - def readbyte(self): - return _ow.readbyte(self.pin) - - def readinto(self, buf): - for i in range(len(buf)): - buf[i] = _ow.readbyte(self.pin) - - def writebit(self, value): - return _ow.writebit(self.pin, value) - - def writebyte(self, value): - return _ow.writebyte(self.pin, value) - - def write(self, buf): - for b in buf: - _ow.writebyte(self.pin, b) - - def select_rom(self, rom): - self.reset() - self.writebyte(MATCH_ROM) - self.write(rom) - - def scan(self): - devices = [] - diff = 65 - rom = False - for i in range(0xff): - rom, diff = self._search_rom(rom, diff) - if rom: - devices += [rom] - if diff == 0: - break - return devices - - def _search_rom(self, l_rom, diff): - if not self.reset(): - return None, 0 - self.writebyte(SEARCH_ROM) - if not l_rom: - l_rom = bytearray(8) - rom = bytearray(8) - next_diff = 0 - i = 64 - for byte in range(8): - r_b = 0 - for bit in range(8): - b = self.readbit() - if self.readbit(): - if b: # there are no devices or there is an error on the bus - return None, 0 - else: - if not b: # collision, two devices with different bit meaning - if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i): - b = 1 - next_diff = i - self.writebit(b) - if b: - r_b |= 1 << bit - i -= 1 - rom[byte] = r_b - return rom, next_diff - - def crc8(self, data): - return _ow.crc8(data) diff --git a/drivers/sdcard/sdcard.py b/drivers/sdcard/sdcard.py deleted file mode 100644 index 75a0c501ee..0000000000 --- a/drivers/sdcard/sdcard.py +++ /dev/null @@ -1,272 +0,0 @@ -""" -MicroPython driver for SD cards using SPI bus. - -Requires an SPI bus and a CS pin. Provides readblocks and writeblocks -methods so the device can be mounted as a filesystem. - -Example usage on pyboard: - - import pyb, sdcard, os - sd = sdcard.SDCard(pyb.SPI(1), pyb.Pin.board.X5) - pyb.mount(sd, '/sd2') - os.listdir('/') - -Example usage on ESP8266: - - import machine, sdcard, os - sd = sdcard.SDCard(machine.SPI(0), machine.Pin(15)) - os.umount() - os.VfsFat(sd, "") - os.listdir() - -""" - -from micropython import const -import time - - -_CMD_TIMEOUT = const(100) - -_R1_IDLE_STATE = const(1 << 0) -#R1_ERASE_RESET = const(1 << 1) -_R1_ILLEGAL_COMMAND = const(1 << 2) -#R1_COM_CRC_ERROR = const(1 << 3) -#R1_ERASE_SEQUENCE_ERROR = const(1 << 4) -#R1_ADDRESS_ERROR = const(1 << 5) -#R1_PARAMETER_ERROR = const(1 << 6) -_TOKEN_CMD25 = const(0xfc) -_TOKEN_STOP_TRAN = const(0xfd) -_TOKEN_DATA = const(0xfe) - - -class SDCard: - def __init__(self, spi, cs): - self.spi = spi - self.cs = cs - - self.cmdbuf = bytearray(6) - self.dummybuf = bytearray(512) - for i in range(512): - self.dummybuf[i] = 0xff - self.dummybuf_memoryview = memoryview(self.dummybuf) - - # initialise the card - self.init_card() - - def init_spi(self, baudrate): - try: - master = self.spi.MASTER - except AttributeError: - # on ESP8266 - self.spi.init(baudrate=baudrate, phase=0, polarity=0) - else: - # on pyboard - self.spi.init(master, baudrate=baudrate, phase=0, polarity=0) - - def init_card(self): - # init CS pin - self.cs.init(self.cs.OUT, value=1) - - # init SPI bus; use low data rate for initialisation - self.init_spi(100000) - - # clock card at least 100 cycles with cs high - for i in range(16): - self.spi.write(b'\xff') - - # CMD0: init card; should return _R1_IDLE_STATE (allow 5 attempts) - for _ in range(5): - if self.cmd(0, 0, 0x95) == _R1_IDLE_STATE: - break - else: - raise OSError("no SD card") - - # CMD8: determine card version - r = self.cmd(8, 0x01aa, 0x87, 4) - if r == _R1_IDLE_STATE: - self.init_card_v2() - elif r == (_R1_IDLE_STATE | _R1_ILLEGAL_COMMAND): - self.init_card_v1() - else: - raise OSError("couldn't determine SD card version") - - # get the number of sectors - # CMD9: response R2 (R1 byte + 16-byte block read) - if self.cmd(9, 0, 0, 0, False) != 0: - raise OSError("no response from SD card") - csd = bytearray(16) - self.readinto(csd) - if csd[0] & 0xc0 != 0x40: - raise OSError("SD card CSD format not supported") - self.sectors = ((csd[8] << 8 | csd[9]) + 1) * 2014 - #print('sectors', self.sectors) - - # CMD16: set block length to 512 bytes - if self.cmd(16, 512, 0) != 0: - raise OSError("can't set 512 block size") - - # set to high data rate now that it's initialised - self.init_spi(1320000) - - def init_card_v1(self): - for i in range(_CMD_TIMEOUT): - self.cmd(55, 0, 0) - if self.cmd(41, 0, 0) == 0: - self.cdv = 512 - #print("[SDCard] v1 card") - return - raise OSError("timeout waiting for v1 card") - - def init_card_v2(self): - for i in range(_CMD_TIMEOUT): - time.sleep_ms(50) - self.cmd(58, 0, 0, 4) - self.cmd(55, 0, 0) - if self.cmd(41, 0x40000000, 0) == 0: - self.cmd(58, 0, 0, 4) - self.cdv = 1 - #print("[SDCard] v2 card") - return - raise OSError("timeout waiting for v2 card") - - def cmd(self, cmd, arg, crc, final=0, release=True): - self.cs(0) - - # create and send the command - buf = self.cmdbuf - buf[0] = 0x40 | cmd - buf[1] = arg >> 24 - buf[2] = arg >> 16 - buf[3] = arg >> 8 - buf[4] = arg - buf[5] = crc - self.spi.write(buf) - - # wait for the response (response[7] == 0) - for i in range(_CMD_TIMEOUT): - response = self.spi.read(1, 0xff)[0] - if not (response & 0x80): - # this could be a big-endian integer that we are getting here - for j in range(final): - self.spi.write(b'\xff') - if release: - self.cs(1) - self.spi.write(b'\xff') - return response - - # timeout - self.cs(1) - self.spi.write(b'\xff') - return -1 - - def cmd_nodata(self, cmd): - self.spi.write(cmd) - self.spi.read(1, 0xff) # ignore stuff byte - for _ in range(_CMD_TIMEOUT): - if self.spi.read(1, 0xff)[0] == 0xff: - self.cs(1) - self.spi.write(b'\xff') - return 0 # OK - self.cs(1) - self.spi.write(b'\xff') - return 1 # timeout - - def readinto(self, buf): - self.cs(0) - - # read until start byte (0xff) - while self.spi.read(1, 0xff)[0] != 0xfe: - pass - - # read data - mv = self.dummybuf_memoryview[:len(buf)] - self.spi.write_readinto(mv, buf) - - # read checksum - self.spi.write(b'\xff') - self.spi.write(b'\xff') - - self.cs(1) - self.spi.write(b'\xff') - - def write(self, token, buf): - self.cs(0) - - # send: start of block, data, checksum - self.spi.read(1, token) - self.spi.write(buf) - self.spi.write(b'\xff') - self.spi.write(b'\xff') - - # check the response - if (self.spi.read(1, 0xff)[0] & 0x1f) != 0x05: - self.cs(1) - self.spi.write(b'\xff') - return - - # wait for write to finish - while self.spi.read(1, 0xff)[0] == 0: - pass - - self.cs(1) - self.spi.write(b'\xff') - - def write_token(self, token): - self.cs(0) - self.spi.read(1, token) - self.spi.write(b'\xff') - # wait for write to finish - while self.spi.read(1, 0xff)[0] == 0x00: - pass - - self.cs(1) - self.spi.write(b'\xff') - - def count(self): - return self.sectors - - def readblocks(self, block_num, buf): - nblocks, err = divmod(len(buf), 512) - assert nblocks and not err, 'Buffer length is invalid' - if nblocks == 1: - # CMD17: set read address for single block - if self.cmd(17, block_num * self.cdv, 0) != 0: - return 1 - # receive the data - self.readinto(buf) - else: - # CMD18: set read address for multiple blocks - if self.cmd(18, block_num * self.cdv, 0) != 0: - return 1 - offset = 0 - mv = memoryview(buf) - while nblocks: - self.readinto(mv[offset : offset + 512]) - offset += 512 - nblocks -= 1 - return self.cmd_nodata(b'\x0c') # cmd 12 - return 0 - - def writeblocks(self, block_num, buf): - nblocks, err = divmod(len(buf), 512) - assert nblocks and not err, 'Buffer length is invalid' - if nblocks == 1: - # CMD24: set write address for single block - if self.cmd(24, block_num * self.cdv, 0) != 0: - return 1 - - # send the data - self.write(_TOKEN_DATA, buf) - else: - # CMD25: set write address for first block - if self.cmd(25, block_num * self.cdv, 0) != 0: - return 1 - # send the data - offset = 0 - mv = memoryview(buf) - while nblocks: - self.write(_TOKEN_CMD25, mv[offset : offset + 512]) - offset += 512 - nblocks -= 1 - self.write_token(_TOKEN_STOP_TRAN) - return 0 diff --git a/drivers/sdcard/sdtest.py b/drivers/sdcard/sdtest.py deleted file mode 100644 index 438baa245d..0000000000 --- a/drivers/sdcard/sdtest.py +++ /dev/null @@ -1,57 +0,0 @@ -# Test for sdcard block protocol -# Peter hinch 30th Jan 2016 -import os, sdcard, pyb - -def sdtest(): - sd = sdcard.SDCard(pyb.SPI(1), pyb.Pin.board.X21) # Compatible with PCB - pyb.mount(sd, '/fc') - print('Filesystem check') - print(os.listdir('/fc')) - - line = 'abcdefghijklmnopqrstuvwxyz\n' - lines = line * 200 # 5400 chars - short = '1234567890\n' - - fn = '/fc/rats.txt' - print() - print('Multiple block read/write') - with open(fn,'w') as f: - n = f.write(lines) - print(n, 'bytes written') - n = f.write(short) - print(n, 'bytes written') - n = f.write(lines) - print(n, 'bytes written') - - with open(fn,'r') as f: - result1 = f.read() - print(len(result1), 'bytes read') - - fn = '/fc/rats1.txt' - print() - print('Single block read/write') - with open(fn,'w') as f: - n = f.write(short) # one block - print(n, 'bytes written') - - with open(fn,'r') as f: - result2 = f.read() - print(len(result2), 'bytes read') - - pyb.mount(None, '/fc') - - print() - print('Verifying data read back') - success = True - if result1 == ''.join((lines, short, lines)): - print('Large file Pass') - else: - print('Large file Fail') - success = False - if result2 == short: - print('Small file Pass') - else: - print('Small file Fail') - success = False - print() - print('Tests', 'passed' if success else 'failed') diff --git a/drivers/wiznet5k/README.md b/drivers/wiznet5k/README.md deleted file mode 100644 index 88f25a2b8d..0000000000 --- a/drivers/wiznet5k/README.md +++ /dev/null @@ -1,6 +0,0 @@ -This is the driver for the WIZnet5x00 series of Ethernet controllers. - -Adapted for MicroPython. - -Original source: https://github.com/Wiznet/W5500_EVB/tree/master/ioLibrary -Taken on: 30 August 2014 diff --git a/drivers/wiznet5k/ethernet/socket.c b/drivers/wiznet5k/ethernet/socket.c deleted file mode 100644 index ec25fcc793..0000000000 --- a/drivers/wiznet5k/ethernet/socket.c +++ /dev/null @@ -1,724 +0,0 @@ -//***************************************************************************** -// -//! \file socket.c -//! \brief SOCKET APIs Implements file. -//! \details SOCKET APIs like as Berkeley Socket APIs. -//! \version 1.0.3 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.3. Refer to M20140501 -//! 1. Implicit type casting -> Explicit type casting. -//! 2. replace 0x01 with PACK_REMAINED in recvfrom() -//! 3. Validation a destination ip in connect() & sendto(): -//! It occurs a fatal error on converting unint32 address if uint8* addr parameter is not aligned by 4byte address. -//! Copy 4 byte addr value into temporary uint32 variable and then compares it. -//! <2013/12/20> V1.0.2 Refer to M20131220 -//! Remove Warning. -//! <2013/11/04> V1.0.1 2nd Release. Refer to "20131104". -//! In sendto(), Add to clear timeout interrupt status (Sn_IR_TIMEOUT) -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#include - -#include "py/mpthread.h" -#include "socket.h" - -#define SOCK_ANY_PORT_NUM 0xC000; - -static uint16_t sock_any_port = SOCK_ANY_PORT_NUM; -static uint16_t sock_io_mode = 0; -static uint16_t sock_is_sending = 0; -static uint16_t sock_remained_size[_WIZCHIP_SOCK_NUM_] = {0,0,}; -static uint8_t sock_pack_info[_WIZCHIP_SOCK_NUM_] = {0,}; - -#if _WIZCHIP_ == 5200 - static uint16_t sock_next_rd[_WIZCHIP_SOCK_NUM_] ={0,}; -#endif - -#define CHECK_SOCKNUM() \ - do{ \ - if(sn > _WIZCHIP_SOCK_NUM_) return SOCKERR_SOCKNUM; \ - }while(0); \ - -#define CHECK_SOCKMODE(mode) \ - do{ \ - if((getSn_MR(sn) & 0x0F) != mode) return SOCKERR_SOCKMODE; \ - }while(0); \ - -#define CHECK_SOCKINIT() \ - do{ \ - if((getSn_SR(sn) != SOCK_INIT)) return SOCKERR_SOCKINIT; \ - }while(0); \ - -#define CHECK_SOCKDATA() \ - do{ \ - if(len == 0) return SOCKERR_DATALEN; \ - }while(0); \ - -void WIZCHIP_EXPORT(socket_reset)(void) { - sock_any_port = SOCK_ANY_PORT_NUM; - sock_io_mode = 0; - sock_is_sending = 0; - /* - memset(sock_remained_size, 0, _WIZCHIP_SOCK_NUM_ * sizeof(uint16_t)); - memset(sock_pack_info, 0, _WIZCHIP_SOCK_NUM_ * sizeof(uint8_t)); - */ - -#if _WIZCHIP_ == 5200 - memset(sock_next_rd, 0, _WIZCHIP_SOCK_NUM_ * sizeof(uint16_t)); -#endif -} - -int8_t WIZCHIP_EXPORT(socket)(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag) -{ - CHECK_SOCKNUM(); - switch(protocol) - { - case Sn_MR_TCP : - case Sn_MR_UDP : - case Sn_MR_MACRAW : - break; - #if ( _WIZCHIP_ < 5200 ) - case Sn_MR_IPRAW : - case Sn_MR_PPPoE : - break; - #endif - default : - return SOCKERR_SOCKMODE; - } - if((flag & 0x06) != 0) return SOCKERR_SOCKFLAG; -#if _WIZCHIP_ == 5200 - if(flag & 0x10) return SOCKERR_SOCKFLAG; -#endif - - if(flag != 0) - { - switch(protocol) - { - case Sn_MR_TCP: - if((flag & (SF_TCP_NODELAY|SF_IO_NONBLOCK))==0) return SOCKERR_SOCKFLAG; - break; - case Sn_MR_UDP: - if(flag & SF_IGMP_VER2) - { - if((flag & SF_MULTI_ENABLE)==0) return SOCKERR_SOCKFLAG; - } - #if _WIZCHIP_ == 5500 - if(flag & SF_UNI_BLOCK) - { - if((flag & SF_MULTI_ENABLE) == 0) return SOCKERR_SOCKFLAG; - } - #endif - break; - default: - break; - } - } - WIZCHIP_EXPORT(close)(sn); - setSn_MR(sn, (protocol | (flag & 0xF0))); - if(!port) - { - port = sock_any_port++; - if(sock_any_port == 0xFFF0) sock_any_port = SOCK_ANY_PORT_NUM; - } - setSn_PORT(sn,port); - setSn_CR(sn,Sn_CR_OPEN); - while(getSn_CR(sn)); - sock_io_mode |= ((flag & SF_IO_NONBLOCK) << sn); - sock_is_sending &= ~(1< freesize) len = freesize; // check size not to exceed MAX size. - while(1) - { - freesize = getSn_TX_FSR(sn); - tmp = getSn_SR(sn); - if ((tmp != SOCK_ESTABLISHED) && (tmp != SOCK_CLOSE_WAIT)) - { - WIZCHIP_EXPORT(close)(sn); - return SOCKERR_SOCKSTATUS; - } - if( (sock_io_mode & (1< freesize) ) return SOCK_BUSY; - if(len <= freesize) break; - MICROPY_THREAD_YIELD(); - } - wiz_send_data(sn, buf, len); - #if _WIZCHIP_ == 5200 - sock_next_rd[sn] = getSn_TX_RD(sn) + len; - #endif - setSn_CR(sn,Sn_CR_SEND); - /* wait to process the command... */ - while(getSn_CR(sn)); - sock_is_sending |= (1 << sn); - return len; -} - - -int32_t WIZCHIP_EXPORT(recv)(uint8_t sn, uint8_t * buf, uint16_t len) -{ - uint8_t tmp = 0; - uint16_t recvsize = 0; - CHECK_SOCKNUM(); - CHECK_SOCKMODE(Sn_MR_TCP); - CHECK_SOCKDATA(); - - recvsize = getSn_RxMAX(sn); - if(recvsize < len) len = recvsize; - while(1) - { - recvsize = getSn_RX_RSR(sn); - tmp = getSn_SR(sn); - if (tmp != SOCK_ESTABLISHED) - { - if(tmp == SOCK_CLOSE_WAIT) - { - if(recvsize != 0) break; - else if(getSn_TX_FSR(sn) == getSn_TxMAX(sn)) - { - // dpgeorge: Getting here seems to be an orderly shutdown of the - // socket, and trying to get POSIX behaviour we return 0 because: - // "If no messages are available to be received and the peer has per‐ - // formed an orderly shutdown, recv() shall return 0". - // TODO this return value clashes with SOCK_BUSY in non-blocking mode. - WIZCHIP_EXPORT(close)(sn); - return 0; - } - } - else - { - WIZCHIP_EXPORT(close)(sn); - return SOCKERR_SOCKSTATUS; - } - } - if((sock_io_mode & (1< freesize) len = freesize; // check size not to exceed MAX size. - while(1) - { - freesize = getSn_TX_FSR(sn); - if(getSn_SR(sn) == SOCK_CLOSED) return SOCKERR_SOCKCLOSED; - if( (sock_io_mode & (1< freesize) ) return SOCK_BUSY; - if(len <= freesize) break; - MICROPY_THREAD_YIELD(); - }; - wiz_send_data(sn, buf, len); - - #if _WIZCHIP_ == 5200 // for W5200 ARP errata - setSUBR(wizchip_getsubn()); - #endif - - setSn_CR(sn,Sn_CR_SEND); - /* wait to process the command... */ - while(getSn_CR(sn)); - while(1) - { - tmp = getSn_IR(sn); - if(tmp & Sn_IR_SENDOK) - { - setSn_IR(sn, Sn_IR_SENDOK); - break; - } - //M:20131104 - //else if(tmp & Sn_IR_TIMEOUT) return SOCKERR_TIMEOUT; - else if(tmp & Sn_IR_TIMEOUT) - { - setSn_IR(sn, Sn_IR_TIMEOUT); - #if _WIZCHIP_ == 5200 // for W5200 ARP errata - setSUBR((uint8_t*)"\x00\x00\x00\x00"); - #endif - return SOCKERR_TIMEOUT; - } - //////////// - MICROPY_THREAD_YIELD(); - } - #if _WIZCHIP_ == 5200 // for W5200 ARP errata - setSUBR((uint8_t*)"\x00\x00\x00\x00"); - #endif - return len; -} - - - -int32_t WIZCHIP_EXPORT(recvfrom)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t *port) -{ - uint8_t mr; - uint8_t head[8]; - uint16_t pack_len=0; - - CHECK_SOCKNUM(); - //CHECK_SOCKMODE(Sn_MR_UDP); - switch((mr=getSn_MR(sn)) & 0x0F) - { - case Sn_MR_UDP: - case Sn_MR_MACRAW: - break; - #if ( _WIZCHIP_ < 5200 ) - case Sn_MR_IPRAW: - case Sn_MR_PPPoE: - break; - #endif - default: - return SOCKERR_SOCKMODE; - } - CHECK_SOCKDATA(); - if(sock_remained_size[sn] == 0) - { - while(1) - { - pack_len = getSn_RX_RSR(sn); - if(getSn_SR(sn) == SOCK_CLOSED) return SOCKERR_SOCKCLOSED; - if( (sock_io_mode & (1< 1514) - { - WIZCHIP_EXPORT(close)(sn); - return SOCKFATAL_PACKLEN; - } - sock_pack_info[sn] = PACK_FIRST; - } - if(len < sock_remained_size[sn]) pack_len = len; - else pack_len = sock_remained_size[sn]; - wiz_recv_data(sn,buf,pack_len); - break; - #if ( _WIZCHIP_ < 5200 ) - case Sn_MR_IPRAW: - if(sock_remained_size[sn] == 0) - { - wiz_recv_data(sn, head, 6); - setSn_CR(sn,Sn_CR_RECV); - while(getSn_CR(sn)); - addr[0] = head[0]; - addr[1] = head[1]; - addr[2] = head[2]; - addr[3] = head[3]; - sock_remained_size[sn] = head[4]; - sock_remaiend_size[sn] = (sock_remained_size[sn] << 8) + head[5]; - sock_pack_info[sn] = PACK_FIRST; - } - // - // Need to packet length check - // - if(len < sock_remained_size[sn]) pack_len = len; - else pack_len = sock_remained_size[sn]; - wiz_recv_data(sn, buf, pack_len); // data copy. - break; - #endif - default: - wiz_recv_ignore(sn, pack_len); // data copy. - sock_remained_size[sn] = pack_len; - break; - } - setSn_CR(sn,Sn_CR_RECV); - /* wait to process the command... */ - while(getSn_CR(sn)) ; - sock_remained_size[sn] -= pack_len; - //M20140501 : replace 0x01 with PACK_REMAINED - //if(sock_remained_size[sn] != 0) sock_pack_info[sn] |= 0x01; - if(sock_remained_size[sn] != 0) sock_pack_info[sn] |= PACK_REMAINED; - // - return pack_len; -} - - -int8_t WIZCHIP_EXPORT(ctlsocket)(uint8_t sn, ctlsock_type cstype, void* arg) -{ - uint8_t tmp = 0; - CHECK_SOCKNUM(); - switch(cstype) - { - case CS_SET_IOMODE: - tmp = *((uint8_t*)arg); - if(tmp == SOCK_IO_NONBLOCK) sock_io_mode |= (1< explict type casting - //*((uint8_t*)arg) = (sock_io_mode >> sn) & 0x0001; - *((uint8_t*)arg) = (uint8_t)((sock_io_mode >> sn) & 0x0001); - // - break; - case CS_GET_MAXTXBUF: - *((uint16_t*)arg) = getSn_TxMAX(sn); - break; - case CS_GET_MAXRXBUF: - *((uint16_t*)arg) = getSn_RxMAX(sn); - break; - case CS_CLR_INTERRUPT: - if( (*(uint8_t*)arg) > SIK_ALL) return SOCKERR_ARG; - setSn_IR(sn,*(uint8_t*)arg); - break; - case CS_GET_INTERRUPT: - *((uint8_t*)arg) = getSn_IR(sn); - break; - case CS_SET_INTMASK: - if( (*(uint8_t*)arg) > SIK_ALL) return SOCKERR_ARG; - setSn_IMR(sn,*(uint8_t*)arg); - break; - case CS_GET_INTMASK: - *((uint8_t*)arg) = getSn_IMR(sn); - default: - return SOCKERR_ARG; - } - return SOCK_OK; -} - -int8_t WIZCHIP_EXPORT(setsockopt)(uint8_t sn, sockopt_type sotype, void* arg) -{ - // M20131220 : Remove warning - //uint8_t tmp; - CHECK_SOCKNUM(); - switch(sotype) - { - case SO_TTL: - setSn_TTL(sn,*(uint8_t*)arg); - break; - case SO_TOS: - setSn_TOS(sn,*(uint8_t*)arg); - break; - case SO_MSS: - setSn_MSSR(sn,*(uint16_t*)arg); - break; - case SO_DESTIP: - setSn_DIPR(sn, (uint8_t*)arg); - break; - case SO_DESTPORT: - setSn_DPORT(sn, *(uint16_t*)arg); - break; -#if _WIZCHIP_ != 5100 - case SO_KEEPALIVESEND: - CHECK_SOCKMODE(Sn_MR_TCP); - #if _WIZCHIP_ > 5200 - if(getSn_KPALVTR(sn) != 0) return SOCKERR_SOCKOPT; - #endif - setSn_CR(sn,Sn_CR_SEND_KEEP); - while(getSn_CR(sn) != 0) - { - // M20131220 - //if ((tmp = getSn_IR(sn)) & Sn_IR_TIMEOUT) - if (getSn_IR(sn) & Sn_IR_TIMEOUT) - { - setSn_IR(sn, Sn_IR_TIMEOUT); - return SOCKERR_TIMEOUT; - } - } - break; - #if _WIZCHIP_ > 5200 - case SO_KEEPALIVEAUTO: - CHECK_SOCKMODE(Sn_MR_TCP); - setSn_KPALVTR(sn,*(uint8_t*)arg); - break; - #endif -#endif - default: - return SOCKERR_ARG; - } - return SOCK_OK; -} - -int8_t WIZCHIP_EXPORT(getsockopt)(uint8_t sn, sockopt_type sotype, void* arg) -{ - CHECK_SOCKNUM(); - switch(sotype) - { - case SO_FLAG: - *(uint8_t*)arg = getSn_MR(sn) & 0xF0; - break; - case SO_TTL: - *(uint8_t*) arg = getSn_TTL(sn); - break; - case SO_TOS: - *(uint8_t*) arg = getSn_TOS(sn); - break; - case SO_MSS: - *(uint8_t*) arg = getSn_MSSR(sn); - case SO_DESTIP: - getSn_DIPR(sn, (uint8_t*)arg); - break; - case SO_DESTPORT: - *(uint16_t*) arg = getSn_DPORT(sn); - break; - #if _WIZCHIP_ > 5200 - case SO_KEEPALIVEAUTO: - CHECK_SOCKMODE(Sn_MR_TCP); - *(uint16_t*) arg = getSn_KPALVTR(sn); - break; - #endif - case SO_SENDBUF: - *(uint16_t*) arg = getSn_TX_FSR(sn); - case SO_RECVBUF: - *(uint16_t*) arg = getSn_RX_RSR(sn); - case SO_STATUS: - *(uint8_t*) arg = getSn_SR(sn); - break; - case SO_REMAINSIZE: - if(getSn_MR(sn) == Sn_MR_TCP) - *(uint16_t*)arg = getSn_RX_RSR(sn); - else - *(uint16_t*)arg = sock_remained_size[sn]; - break; - case SO_PACKINFO: - CHECK_SOCKMODE(Sn_MR_TCP); - *(uint8_t*)arg = sock_pack_info[sn]; - break; - default: - return SOCKERR_SOCKOPT; - } - return SOCK_OK; -} diff --git a/drivers/wiznet5k/ethernet/socket.h b/drivers/wiznet5k/ethernet/socket.h deleted file mode 100644 index 2f03a34eba..0000000000 --- a/drivers/wiznet5k/ethernet/socket.h +++ /dev/null @@ -1,472 +0,0 @@ -//***************************************************************************** -// -//! \file socket.h -//! \brief SOCKET APIs Header file. -//! \details SOCKET APIs like as berkeley socket api. -//! \version 1.0.2 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.2. Refer to M20140501 -//! 1. Modify the comment : SO_REMAINED -> PACK_REMAINED -//! 2. Add the comment as zero byte udp data reception in getsockopt(). -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** -/** - * @defgroup WIZnet_socket_APIs 1. WIZnet socket APIs - * @brief WIZnet socket APIs are based on Berkeley socket APIs, thus it has much similar name and interface. - * But there is a little bit of difference. - * @details - * Comparison between WIZnet and Berkeley SOCKET APIs - * - * - * - * - * - * - * - * - * - * - * - * - *
API WIZnet Berkeley
socket() O O
bind() X O
listen() O O
connect() O O
accept() X O
recv() O O
send() O O
recvfrom() O O
sendto() O O
closesocket() O
close() & disconnect()
O
- * There are @b bind() and @b accept() functions in @b Berkeley SOCKET API but, - * not in @b WIZnet SOCKET API. Because socket() of WIZnet is not only creating a SOCKET but also binding a local port number, - * and listen() of WIZnet is not only listening to connection request from client but also accepting the connection request. \n - * When you program "TCP SERVER" with Berkeley SOCKET API, you can use only one listen port. - * When the listen SOCKET accepts a connection request from a client, it keeps listening. - * After accepting the connection request, a new SOCKET is created and the new SOCKET is used in communication with the client. \n - * Following figure shows network flow diagram by Berkeley SOCKET API. - * @image html Berkeley_SOCKET.jpg "" - * But, When you program "TCP SERVER" with WIZnet SOCKET API, you can use as many as 8 listen SOCKET with same port number. \n - * Because there's no accept() in WIZnet SOCKET APIs, when the listen SOCKET accepts a connection request from a client, - * it is changed in order to communicate with the client. - * And the changed SOCKET is not listening any more and is dedicated for communicating with the client. \n - * If there're many listen SOCKET with same listen port number and a client requests a connection, - * the SOCKET which has the smallest SOCKET number accepts the request and is changed as communication SOCKET. \n - * Following figure shows network flow diagram by WIZnet SOCKET API. - * @image html WIZnet_SOCKET.jpg "" - */ -#ifndef _WIZCHIP_SOCKET_H_ -#define _WIZCHIP_SOCKET_H_ - -// use this macro for exported names to avoid name clashes -#define WIZCHIP_EXPORT(name) wizchip_ ## name - -#include "wizchip_conf.h" - -#define SOCKET uint8_t ///< SOCKET type define for legacy driver - -#define SOCK_OK 1 ///< Result is OK about socket process. -#define SOCK_BUSY 0 ///< Socket is busy on processing the operation. Valid only Non-block IO Mode. -#define SOCK_FATAL -1000 ///< Result is fatal error about socket process. - -#define SOCK_ERROR 0 -#define SOCKERR_SOCKNUM (SOCK_ERROR - 1) ///< Invalid socket number -#define SOCKERR_SOCKOPT (SOCK_ERROR - 2) ///< Invalid socket option -#define SOCKERR_SOCKINIT (SOCK_ERROR - 3) ///< Socket is not initialized -#define SOCKERR_SOCKCLOSED (SOCK_ERROR - 4) ///< Socket unexpectedly closed. -#define SOCKERR_SOCKMODE (SOCK_ERROR - 5) ///< Invalid socket mode for socket operation. -#define SOCKERR_SOCKFLAG (SOCK_ERROR - 6) ///< Invalid socket flag -#define SOCKERR_SOCKSTATUS (SOCK_ERROR - 7) ///< Invalid socket status for socket operation. -#define SOCKERR_ARG (SOCK_ERROR - 10) ///< Invalid argument. -#define SOCKERR_PORTZERO (SOCK_ERROR - 11) ///< Port number is zero -#define SOCKERR_IPINVALID (SOCK_ERROR - 12) ///< Invalid IP address -#define SOCKERR_TIMEOUT (SOCK_ERROR - 13) ///< Timeout occurred -#define SOCKERR_DATALEN (SOCK_ERROR - 14) ///< Data length is zero or greater than buffer max size. -#define SOCKERR_BUFFER (SOCK_ERROR - 15) ///< Socket buffer is not enough for data communication. - -#define SOCKFATAL_PACKLEN (SOCK_FATAL - 1) ///< Invalid packet length. Fatal Error. - -/* - * SOCKET FLAG - */ -#define SF_ETHER_OWN (Sn_MR_MFEN) ///< In \ref Sn_MR_MACRAW, Receive only the packet as broadcast, multicast and own packet -#define SF_IGMP_VER2 (Sn_MR_MC) ///< In \ref Sn_MR_UDP with \ref SF_MULTI_ENABLE, Select IGMP version 2. -#define SF_TCP_NODELAY (Sn_MR_ND) ///< In \ref Sn_MR_TCP, Use to nodelayed ack. -#define SF_MULTI_ENABLE (Sn_MR_MULTI) ///< In \ref Sn_MR_UDP, Enable multicast mode. - -#if _WIZCHIP_ == 5500 - #define SF_BROAD_BLOCK (Sn_MR_BCASTB) ///< In \ref Sn_MR_UDP or \ref Sn_MR_MACRAW, Block broadcast packet. Valid only in W5500 - #define SF_MULTI_BLOCK (Sn_MR_MMB) ///< In \ref Sn_MR_MACRAW, Block multicast packet. Valid only in W5500 - #define SF_IPv6_BLOCK (Sn_MR_MIP6B) ///< In \ref Sn_MR_MACRAW, Block IPv6 packet. Valid only in W5500 - #define SF_UNI_BLOCK (Sn_MR_UCASTB) ///< In \ref Sn_MR_UDP with \ref SF_MULTI_ENABLE. Valid only in W5500 -#endif - -#define SF_IO_NONBLOCK 0x01 ///< Socket nonblock io mode. It used parameter in \ref socket(). - -/* - * UDP & MACRAW Packet Infomation - */ -#define PACK_FIRST 0x80 ///< In Non-TCP packet, It indicates to start receiving a packet. -#define PACK_REMAINED 0x01 ///< In Non-TCP packet, It indicates to remain a packet to be received. -#define PACK_COMPLETED 0x00 ///< In Non-TCP packet, It indicates to complete to receive a packet. - -// resets all global state associated with the socket interface -void WIZCHIP_EXPORT(socket_reset)(void); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Open a socket. - * @details Initializes the socket with 'sn' passed as parameter and open. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param protocol Protocol type to operate such as TCP, UDP and MACRAW. - * @param port Port number to be bined. - * @param flag Socket flags as \ref SF_ETHER_OWN, \ref SF_IGMP_VER2, \ref SF_TCP_NODELAY, \ref SF_MULTI_ENABLE, \ref SF_IO_NONBLOCK and so on.\n - * Valid flags only in W5500 : @ref SF_BROAD_BLOCK, @ref SF_MULTI_BLOCK, @ref SF_IPv6_BLOCK, and @ref SF_UNI_BLOCK. - * @sa Sn_MR - * - * @return @b Success : The socket number @b 'sn' passed as parameter\n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number\n - * @ref SOCKERR_SOCKMODE - Not support socket mode as TCP, UDP, and so on. \n - * @ref SOCKERR_SOCKFLAG - Invaild socket flag. - */ -int8_t WIZCHIP_EXPORT(socket)(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Close a socket. - * @details It closes the socket with @b'sn' passed as parameter. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * - * @return @b Success : @ref SOCK_OK \n - * @b Fail : @ref SOCKERR_SOCKNUM - Invalid socket number - */ -int8_t WIZCHIP_EXPORT(close)(uint8_t sn); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Listen to a connection request from a client. - * @details It is listening to a connection request from a client. - * If connection request is accepted successfully, the connection is established. Socket sn is used in passive(server) mode. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @return @b Success : @ref SOCK_OK \n - * @b Fail :\n @ref SOCKERR_SOCKINIT - Socket is not initialized \n - * @ref SOCKERR_SOCKCLOSED - Socket closed unexpectedly. - */ -int8_t WIZCHIP_EXPORT(listen)(uint8_t sn); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Try to connect a server. - * @details It requests connection to the server with destination IP address and port number passed as parameter.\n - * @note It is valid only in TCP client mode. - * In block io mode, it does not return until connection is completed. - * In Non-block io mode, it return @ref SOCK_BUSY immediately. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param addr Pointer variable of destination IP address. It should be allocated 4 bytes. - * @param port Destination port number. - * - * @return @b Success : @ref SOCK_OK \n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number\n - * @ref SOCKERR_SOCKMODE - Invalid socket mode\n - * @ref SOCKERR_SOCKINIT - Socket is not initialized\n - * @ref SOCKERR_IPINVALID - Wrong server IP address\n - * @ref SOCKERR_PORTZERO - Server port zero\n - * @ref SOCKERR_TIMEOUT - Timeout occurred during request connection\n - * @ref SOCK_BUSY - In non-block io mode, it returned immediately\n - */ -int8_t WIZCHIP_EXPORT(connect)(uint8_t sn, uint8_t * addr, uint16_t port); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Try to disconnect a connection socket. - * @details It sends request message to disconnect the TCP socket 'sn' passed as parameter to the server or client. - * @note It is valid only in TCP server or client mode. \n - * In block io mode, it does not return until disconnection is completed. \n - * In Non-block io mode, it return @ref SOCK_BUSY immediately. \n - - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @return @b Success : @ref SOCK_OK \n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_TIMEOUT - Timeout occurred \n - * @ref SOCK_BUSY - Socket is busy. - */ -int8_t WIZCHIP_EXPORT(disconnect)(uint8_t sn); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Send data to the connected peer in TCP socket. - * @details It is used to send outgoing data to the connected socket. - * @note It is valid only in TCP server or client mode. It can't send data greater than socket buffer size. \n - * In block io mode, It doesn't return until data send is completed - socket buffer size is greater than data. \n - * In non-block io mode, It return @ref SOCK_BUSY immediately when socket buffer is not enough. \n - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer containing data to be sent. - * @param len The byte length of data in buf. - * @return @b Success : The sent data size \n - * @b Fail : \n @ref SOCKERR_SOCKSTATUS - Invalid socket status for socket operation \n - * @ref SOCKERR_TIMEOUT - Timeout occurred \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCK_BUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(send)(uint8_t sn, uint8_t * buf, uint16_t len); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Receive data from the connected peer. - * @details It is used to read incoming data from the connected socket.\n - * It waits for data as much as the application wants to receive. - * @note It is valid only in TCP server or client mode. It can't receive data greater than socket buffer size. \n - * In block io mode, it doesn't return until data reception is completed - data is filled as len in socket buffer. \n - * In non-block io mode, it return @ref SOCK_BUSY immediately when len is greater than data size in socket buffer. \n - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer to read incoming data. - * @param len The max data length of data in buf. - * @return @b Success : The real received data size \n - * @b Fail :\n - * @ref SOCKERR_SOCKSTATUS - Invalid socket status for socket operation \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCK_BUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(recv)(uint8_t sn, uint8_t * buf, uint16_t len); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Sends datagram to the peer with destination IP address and port number passed as parameter. - * @details It sends datagram of UDP or MACRAW to the peer with destination IP address and port number passed as parameter.\n - * Even if the connectionless socket has been previously connected to a specific address, - * the address and port number parameters override the destination address for that particular datagram only. - * @note In block io mode, It doesn't return until data send is completed - socket buffer size is greater than len. - * In non-block io mode, It return @ref SOCK_BUSY immediately when socket buffer is not enough. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer to send outgoing data. - * @param len The byte length of data in buf. - * @param addr Pointer variable of destination IP address. It should be allocated 4 bytes. - * @param port Destination port number. - * - * @return @b Success : The sent data size \n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKSTATUS - Invalid socket status for socket operation \n - * @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCKERR_IPINVALID - Wrong server IP address\n - * @ref SOCKERR_PORTZERO - Server port zero\n - * @ref SOCKERR_SOCKCLOSED - Socket unexpectedly closed \n - * @ref SOCKERR_TIMEOUT - Timeout occurred \n - * @ref SOCK_BUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(sendto)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t port); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Receive datagram of UDP or MACRAW - * @details This function is an application I/F function which is used to receive the data in other then TCP mode. \n - * This function is used to receive UDP and MAC_RAW mode, and handle the header as well. - * This function can divide to received the packet data. - * On the MACRAW SOCKET, the addr and port parameters are ignored. - * @note In block io mode, it doesn't return until data reception is completed - data is filled as len in socket buffer - * In non-block io mode, it return @ref SOCK_BUSY immediately when len is greater than data size in socket buffer. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer to read incoming data. - * @param len The max data length of data in buf. - * When the received packet size <= len, receives data as packet sized. - * When others, receives data as len. - * @param addr Pointer variable of destination IP address. It should be allocated 4 bytes. - * It is valid only when the first call recvfrom for receiving the packet. - * When it is valid, @ref packinfo[7] should be set as '1' after call @ref getsockopt(sn, SO_PACKINFO, &packinfo). - * @param port Pointer variable of destination port number. - * It is valid only when the first call recvform for receiving the packet. -* When it is valid, @ref packinfo[7] should be set as '1' after call @ref getsockopt(sn, SO_PACKINFO, &packinfo). - * - * @return @b Success : This function return real received data size for success.\n - * @b Fail : @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKBUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(recvfrom)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t *port); - - -///////////////////////////// -// SOCKET CONTROL & OPTION // -///////////////////////////// -#define SOCK_IO_BLOCK 0 ///< Socket Block IO Mode in @ref setsockopt(). -#define SOCK_IO_NONBLOCK 1 ///< Socket Non-block IO Mode in @ref setsockopt(). - -/** - * @defgroup DATA_TYPE DATA TYPE - */ - -/** - * @ingroup DATA_TYPE - * @brief The kind of Socket Interrupt. - * @sa Sn_IR, Sn_IMR, setSn_IR(), getSn_IR(), setSn_IMR(), getSn_IMR() - */ -typedef enum -{ - SIK_CONNECTED = (1 << 0), ///< connected - SIK_DISCONNECTED = (1 << 1), ///< disconnected - SIK_RECEIVED = (1 << 2), ///< data received - SIK_TIMEOUT = (1 << 3), ///< timeout occurred - SIK_SENT = (1 << 4), ///< send ok - SIK_ALL = 0x1F, ///< all interrupt -}sockint_kind; - -/** - * @ingroup DATA_TYPE - * @brief The type of @ref ctlsocket(). - */ -typedef enum -{ - CS_SET_IOMODE, ///< set socket IO mode with @ref SOCK_IO_BLOCK or @ref SOCK_IO_NONBLOCK - CS_GET_IOMODE, ///< get socket IO mode - CS_GET_MAXTXBUF, ///< get the size of socket buffer allocated in TX memory - CS_GET_MAXRXBUF, ///< get the size of socket buffer allocated in RX memory - CS_CLR_INTERRUPT, ///< clear the interrupt of socket with @ref sockint_kind - CS_GET_INTERRUPT, ///< get the socket interrupt. refer to @ref sockint_kind - CS_SET_INTMASK, ///< set the interrupt mask of socket with @ref sockint_kind - CS_GET_INTMASK ///< get the masked interrupt of socket. refer to @ref sockint_kind -}ctlsock_type; - - -/** - * @ingroup DATA_TYPE - * @brief The type of socket option in @ref setsockopt() or @ref getsockopt() - */ -typedef enum -{ - SO_FLAG, ///< Valid only in getsockopt(), For set flag of socket refer to flag in @ref socket(). - SO_TTL, ///< Set/Get TTL. @ref Sn_TTL ( @ref setSn_TTL(), @ref getSn_TTL() ) - SO_TOS, ///< Set/Get TOS. @ref Sn_TOS ( @ref setSn_TOS(), @ref getSn_TOS() ) - SO_MSS, ///< Set/Get MSS. @ref Sn_MSSR ( @ref setSn_MSSR(), @ref getSn_MSSR() ) - SO_DESTIP, ///< Set/Get the destination IP address. @ref Sn_DIPR ( @ref setSn_DIPR(), @ref getSn_DIPR() ) - SO_DESTPORT, ///< Set/Get the destination Port number. @ref Sn_DPORT ( @ref setSn_DPORT(), @ref getSn_DPORT() ) -#if _WIZCHIP_ != 5100 - SO_KEEPALIVESEND, ///< Valid only in setsockopt. Manually send keep-alive packet in TCP mode - #if _WIZCHIP_ > 5200 - SO_KEEPALIVEAUTO, ///< Set/Get keep-alive auto transmission timer in TCP mode - #endif -#endif - SO_SENDBUF, ///< Valid only in getsockopt. Get the free data size of Socekt TX buffer. @ref Sn_TX_FSR, @ref getSn_TX_FSR() - SO_RECVBUF, ///< Valid only in getsockopt. Get the received data size in socket RX buffer. @ref Sn_RX_RSR, @ref getSn_RX_RSR() - SO_STATUS, ///< Valid only in getsockopt. Get the socket status. @ref Sn_SR, @ref getSn_SR() - SO_REMAINSIZE, ///< Valid only in getsockopt. Get the remained packet size in other then TCP mode. - SO_PACKINFO ///< Valid only in getsockopt. Get the packet information as @ref PACK_FIRST, @ref PACK_REMAINED, and @ref PACK_COMPLETED in other then TCP mode. -}sockopt_type; - -/** - * @ingroup WIZnet_socket_APIs - * @brief Control socket. - * @details Control IO mode, Interrupt & Mask of socket and get the socket buffer information. - * Refer to @ref ctlsock_type. - * @param sn socket number - * @param cstype type of control socket. refer to @ref ctlsock_type. - * @param arg Data type and value is determined according to @ref ctlsock_type. \n - * - * - * - * - * - *
@b cstype @b data type@b value
@ref CS_SET_IOMODE \n @ref CS_GET_IOMODE uint8_t @ref SOCK_IO_BLOCK @ref SOCK_IO_NONBLOCK
@ref CS_GET_MAXTXBUF \n @ref CS_GET_MAXRXBUF uint16_t 0 ~ 16K
@ref CS_CLR_INTERRUPT \n @ref CS_GET_INTERRUPT \n @ref CS_SET_INTMASK \n @ref CS_GET_INTMASK @ref sockint_kind @ref SIK_CONNECTED, etc.
- * @return @b Success @ref SOCK_OK \n - * @b fail @ref SOCKERR_ARG - Invalid argument\n - */ -int8_t WIZCHIP_EXPORT(ctlsocket)(uint8_t sn, ctlsock_type cstype, void* arg); - -/** - * @ingroup WIZnet_socket_APIs - * @brief set socket options - * @details Set socket option like as TTL, MSS, TOS, and so on. Refer to @ref sockopt_type. - * - * @param sn socket number - * @param sotype socket option type. refer to @ref sockopt_type - * @param arg Data type and value is determined according to sotype. \n - * - * - * - * - * - * - * - * - * - *
@b sotype @b data type@b value
@ref SO_TTL uint8_t 0 ~ 255
@ref SO_TOS uint8_t 0 ~ 255
@ref SO_MSS uint16_t 0 ~ 65535
@ref SO_DESTIP uint8_t[4]
@ref SO_DESTPORT uint16_t 0 ~ 65535
@ref SO_KEEPALIVESEND null null
@ref SO_KEEPALIVEAUTO uint8_t 0 ~ 255
- * @return - * - @b Success : @ref SOCK_OK \n - * - @b Fail - * - @ref SOCKERR_SOCKNUM - Invalid Socket number \n - * - @ref SOCKERR_SOCKMODE - Invalid socket mode \n - * - @ref SOCKERR_SOCKOPT - Invalid socket option or its value \n - * - @ref SOCKERR_TIMEOUT - Timeout occurred when sending keep-alive packet \n - */ -int8_t WIZCHIP_EXPORT(setsockopt)(uint8_t sn, sockopt_type sotype, void* arg); - -/** - * @ingroup WIZnet_socket_APIs - * @brief get socket options - * @details Get socket option like as FLAG, TTL, MSS, and so on. Refer to @ref sockopt_type - * @param sn socket number - * @param sotype socket option type. refer to @ref sockopt_type - * @param arg Data type and value is determined according to sotype. \n - * - * - * - * - * - * - * - * - * - * - * - * - * - *
@b sotype @b data type@b value
@ref SO_FLAG uint8_t @ref SF_ETHER_OWN, etc...
@ref SO_TOS uint8_t 0 ~ 255
@ref SO_MSS uint16_t 0 ~ 65535
@ref SO_DESTIP uint8_t[4]
@ref SO_DESTPORT uint16_t
@ref SO_KEEPALIVEAUTO uint8_t 0 ~ 255
@ref SO_SENDBUF uint16_t 0 ~ 65535
@ref SO_RECVBUF uint16_t 0 ~ 65535
@ref SO_STATUS uint8_t @ref SOCK_ESTABLISHED, etc..
@ref SO_REMAINSIZE uint16_t 0~ 65535
@ref SO_PACKINFO uint8_t @ref PACK_FIRST, etc...
- * @return - * - @b Success : @ref SOCK_OK \n - * - @b Fail - * - @ref SOCKERR_SOCKNUM - Invalid Socket number \n - * - @ref SOCKERR_SOCKOPT - Invalid socket option or its value \n - * - @ref SOCKERR_SOCKMODE - Invalid socket mode \n - * @note - * The option as PACK_REMAINED and SO_PACKINFO is valid only in NON-TCP mode and after call @ref recvfrom(). \n - * When SO_PACKINFO value is PACK_FIRST and the return value of recvfrom() is zero, - * This means the zero byte UDP data(UDP Header only) received. - */ -int8_t WIZCHIP_EXPORT(getsockopt)(uint8_t sn, sockopt_type sotype, void* arg); - -#endif // _WIZCHIP_SOCKET_H_ diff --git a/drivers/wiznet5k/ethernet/w5200/w5200.c b/drivers/wiznet5k/ethernet/w5200/w5200.c deleted file mode 100644 index 8c3780792e..0000000000 --- a/drivers/wiznet5k/ethernet/w5200/w5200.c +++ /dev/null @@ -1,206 +0,0 @@ -// dpgeorge: this file taken from w5500/w5500.c and adapted to W5200 - -//***************************************************************************** -// -//! \file w5500.c -//! \brief W5500 HAL Interface. -//! \version 1.0.1 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.2 -//! 1. Implicit type casting -> Explicit type casting. Refer to M20140501 -//! Fixed the problem on porting into under 32bit MCU -//! Issued by Mathias ClauBen, wizwiki forum ID Think01 and bobh -//! Thank for your interesting and serious advices. -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.0.1 -//! 1. Remove warning -//! 2. WIZCHIP_READ_BUF WIZCHIP_WRITE_BUF in case _WIZCHIP_IO_MODE_SPI_FDM_ -//! for loop optimized(removed). refer to M20131220 -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#include "w5200.h" - -#define SMASK (0x7ff) /* tx buffer mask */ -#define RMASK (0x7ff) /* rx buffer mask */ -#define SSIZE (2048) /* max tx buffer size */ -#define RSIZE (2048) /* max rx buffer size */ - -#define TXBUF_BASE (0x8000) -#define RXBUF_BASE (0xc000) -#define SBASE(sn) (TXBUF_BASE + SSIZE * (sn)) /* tx buffer base for socket sn */ -#define RBASE(sn) (RXBUF_BASE + RSIZE * (sn)) /* rx buffer base for socket sn */ - -uint8_t WIZCHIP_READ(uint32_t AddrSel) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[4] = { - AddrSel >> 8, - AddrSel, - 0x00, - 0x01, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 4); - uint8_t ret; - WIZCHIP.IF.SPI._read_bytes(&ret, 1); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); - - return ret; -} - -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[5] = { - AddrSel >> 8, - AddrSel, - 0x80, - 0x01, - wb, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 5); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_READ_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[4] = { - AddrSel >> 8, - AddrSel, - 0x00 | ((len >> 8) & 0x7f), - len & 0xff, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 4); - WIZCHIP.IF.SPI._read_bytes(pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[4] = { - AddrSel >> 8, - AddrSel, - 0x80 | ((len >> 8) & 0x7f), - len & 0xff, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 4); - WIZCHIP.IF.SPI._write_bytes(pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -uint16_t getSn_TX_FSR(uint8_t sn) { - uint16_t val = 0, val1 = 0; - do { - val1 = (WIZCHIP_READ(Sn_TX_FSR(sn)) << 8) | WIZCHIP_READ(Sn_TX_FSR(sn) + 1); - if (val1 != 0) { - val = (WIZCHIP_READ(Sn_TX_FSR(sn)) << 8) | WIZCHIP_READ(Sn_TX_FSR(sn) + 1); - } - } while (val != val1); - return val; -} - -uint16_t getSn_RX_RSR(uint8_t sn) { - uint16_t val = 0, val1 = 0; - do { - val1 = (WIZCHIP_READ(Sn_RX_RSR(sn)) << 8) | WIZCHIP_READ(Sn_RX_RSR(sn) + 1); - if (val1 != 0) { - val = (WIZCHIP_READ(Sn_RX_RSR(sn)) << 8) | WIZCHIP_READ(Sn_RX_RSR(sn) + 1); - } - } while (val != val1); - return val; -} - -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len) { - if (len == 0) { - return; - } - - uint16_t ptr = getSn_TX_WR(sn); - uint16_t offset = ptr & SMASK; - uint32_t addr = offset + SBASE(sn); - - if (offset + len > SSIZE) { - // implement wrap-around circular buffer - uint16_t size = SSIZE - offset; - WIZCHIP_WRITE_BUF(addr, wizdata, size); - WIZCHIP_WRITE_BUF(SBASE(sn), wizdata + size, len - size); - } else { - WIZCHIP_WRITE_BUF(addr, wizdata, len); - } - - ptr += len; - setSn_TX_WR(sn, ptr); -} - -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len) { - if (len == 0) { - return; - } - - uint16_t ptr = getSn_RX_RD(sn); - uint16_t offset = ptr & RMASK; - uint16_t addr = RBASE(sn) + offset; - - if (offset + len > RSIZE) { - // implement wrap-around circular buffer - uint16_t size = RSIZE - offset; - WIZCHIP_READ_BUF(addr, wizdata, size); - WIZCHIP_READ_BUF(RBASE(sn), wizdata + size, len - size); - } else { - WIZCHIP_READ_BUF(addr, wizdata, len); - } - - ptr += len; - setSn_RX_RD(sn, ptr); -} - -void wiz_recv_ignore(uint8_t sn, uint16_t len) { - uint16_t ptr = getSn_RX_RD(sn); - ptr += len; - setSn_RX_RD(sn, ptr); -} diff --git a/drivers/wiznet5k/ethernet/w5200/w5200.h b/drivers/wiznet5k/ethernet/w5200/w5200.h deleted file mode 100644 index 63561940f8..0000000000 --- a/drivers/wiznet5k/ethernet/w5200/w5200.h +++ /dev/null @@ -1,2092 +0,0 @@ -// dpgeorge: this file taken from w5500/w5500.h and adapted to W5200 - -//***************************************************************************** -// -//! \file w5500.h -//! \brief W5500 HAL Header File. -//! \version 1.0.0 -//! \date 2013/10/21 -//! \par Revision history -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#ifndef _W5200_H_ -#define _W5200_H_ - -#include -#include "../wizchip_conf.h" -//#include "board.h" - -#define _W5200_IO_BASE_ 0x00000000 - -#define WIZCHIP_CREG_ADDR(addr) (_W5200_IO_BASE_ + (addr)) - -#define WIZCHIP_CH_BASE (0x4000) -#define WIZCHIP_CH_SIZE (0x100) -#define WIZCHIP_SREG_ADDR(sn, addr) (_W5200_IO_BASE_ + WIZCHIP_CH_BASE + (sn) * WIZCHIP_CH_SIZE + (addr)) - -////////////////////////////// -//-------------------------- defgroup --------------------------------- -/** - * @defgroup W5500 W5500 - * - * @brief WHIZCHIP register defines and I/O functions of @b W5500. - * - * - @ref WIZCHIP_register : @ref Common_register_group and @ref Socket_register_group - * - @ref WIZCHIP_IO_Functions : @ref Basic_IO_function, @ref Common_register_access_function and @ref Socket_register_access_function - */ - - -/** - * @defgroup WIZCHIP_register WIZCHIP register - * @ingroup W5500 - * - * @brief WHIZCHIP register defines register group of @b W5500. - * - * - @ref Common_register_group : Common register group - * - @ref Socket_register_group : \c SOCKET n register group - */ - - -/** - * @defgroup WIZCHIP_IO_Functions WIZCHIP I/O functions - * @ingroup W5500 - * - * @brief This supports the basic I/O functions for @ref WIZCHIP_register. - * - * - Basic I/O function \n - * WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() \n\n - * - * - @ref Common_register_group access functions \n - * -# @b Mode \n - * getMR(), setMR() - * -# @b Interrupt \n - * getIR(), setIR(), getIMR(), setIMR(), getSIR(), setSIR(), getSIMR(), setSIMR(), getINTLEVEL(), setINTLEVEL() - * -# Network Information \n - * getSHAR(), setSHAR(), getGAR(), setGAR(), getSUBR(), setSUBR(), getSIPR(), setSIPR() - * -# @b Retransmission \n - * getRCR(), setRCR(), getRTR(), setRTR() - * -# @b PPPoE \n - * getPTIMER(), setPTIMER(), getPMAGIC(), getPMAGIC(), getPSID(), setPSID(), getPHAR(), setPHAR(), getPMRU(), setPMRU() - * -# ICMP packet \n - * getUIPR(), getUPORTR() - * -# @b etc. \n - * getPHYCFGR(), setPHYCFGR(), getVERSIONR() \n\n - * - * - \ref Socket_register_group access functions \n - * -# SOCKET control \n - * getSn_MR(), setSn_MR(), getSn_CR(), setSn_CR(), getSn_IMR(), setSn_IMR(), getSn_IR(), setSn_IR() - * -# SOCKET information \n - * getSn_SR(), getSn_DHAR(), setSn_DHAR(), getSn_PORT(), setSn_PORT(), getSn_DIPR(), setSn_DIPR(), getSn_DPORT(), setSn_DPORT() - * getSn_MSSR(), setSn_MSSR() - * -# SOCKET communication \n - * getSn_RXBUF_SIZE(), setSn_RXBUF_SIZE(), getSn_TXBUF_SIZE(), setSn_TXBUF_SIZE() \n - * getSn_TX_RD(), getSn_TX_WR(), setSn_TX_WR() \n - * getSn_RX_RD(), setSn_RX_RD(), getSn_RX_WR() \n - * getSn_TX_FSR(), getSn_RX_RSR(), getSn_KPALVTR(), setSn_KPALVTR() - * -# IP header field \n - * getSn_FRAG(), setSn_FRAG(), getSn_TOS(), setSn_TOS() \n - * getSn_TTL(), setSn_TTL() - */ - - - -/** - * @defgroup Common_register_group Common register - * @ingroup WIZCHIP_register - * - * @brief Common register group\n - * It set the basic for the networking\n - * It set the configuration such as interrupt, network information, ICMP, etc. - * @details - * @sa MR : Mode register. - * @sa GAR, SUBR, SHAR, SIPR - * @sa INTLEVEL, IR, IMR, SIR, SIMR : Interrupt. - * @sa RTR, RCR : Data retransmission. - * @sa PTIMER, PMAGIC, PHAR, PSID, PMRU : PPPoE. - * @sa UIPR, UPORTR : ICMP message. - * @sa PHYCFGR, VERSIONR : etc. - */ - - - -/** - * @defgroup Socket_register_group Socket register - * @ingroup WIZCHIP_register - * - * @brief Socket register group.\n - * Socket register configures and control SOCKETn which is necessary to data communication. - * @details - * @sa Sn_MR, Sn_CR, Sn_IR, Sn_IMR : SOCKETn Control - * @sa Sn_SR, Sn_PORT, Sn_DHAR, Sn_DIPR, Sn_DPORT : SOCKETn Information - * @sa Sn_MSSR, Sn_TOS, Sn_TTL, Sn_KPALVTR, Sn_FRAG : Internet protocol. - * @sa Sn_RXBUF_SIZE, Sn_TXBUF_SIZE, Sn_TX_FSR, Sn_TX_RD, Sn_TX_WR, Sn_RX_RSR, Sn_RX_RD, Sn_RX_WR : Data communication - */ - - - - /** - * @defgroup Basic_IO_function Basic I/O function - * @ingroup WIZCHIP_IO_Functions - * @brief These are basic input/output functions to read values from register or write values to register. - */ - -/** - * @defgroup Common_register_access_function Common register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access common registers. - */ - -/** - * @defgroup Socket_register_access_function Socket register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access socket registers. - */ - -//------------------------------- defgroup end -------------------------------------------- -//----------------------------- W5500 Common Registers IOMAP ----------------------------- -/** - * @ingroup Common_register_group - * @brief Mode Register address(R/W)\n - * @ref MR is used for S/W reset, ping block mode, PPPoE mode and etc. - * @details Each bit of @ref MR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
RST Reserved WOL PB PPPoE Reserved FARP Reserved
- * - \ref MR_RST : Reset - * - \ref MR_WOL : Wake on LAN - * - \ref MR_PB : Ping block - * - \ref MR_PPPOE : PPPoE mode - * - \ref MR_FARP : Force ARP mode - */ -#define MR WIZCHIP_CREG_ADDR(0x0000) - -/** - * @ingroup Common_register_group - * @brief Gateway IP Register address(R/W) - * @details @ref GAR configures the default gateway address. - */ -#define GAR WIZCHIP_CREG_ADDR(0x0001) - -/** - * @ingroup Common_register_group - * @brief Subnet mask Register address(R/W) - * @details @ref SUBR configures the subnet mask address. - */ -#define SUBR WIZCHIP_CREG_ADDR(0x0005) - -/** - * @ingroup Common_register_group - * @brief Source MAC Register address(R/W) - * @details @ref SHAR configures the source hardware address. - */ -#define SHAR WIZCHIP_CREG_ADDR(0x0009) - -/** - * @ingroup Common_register_group - * @brief Source IP Register address(R/W) - * @details @ref SIPR configures the source IP address. - */ -#define SIPR WIZCHIP_CREG_ADDR(0x000f) - -/** - * @ingroup Common_register_group - * @brief Set Interrupt low level timer register address(R/W) - * @details @ref INTLEVEL configures the Interrupt Assert Time. - */ -//#define INTLEVEL (_W5500_IO_BASE_ + (0x0013 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Interrupt Register(R/W) - * @details @ref IR indicates the interrupt status. Each bit of @ref IR will be still until the bit will be written to by the host. - * If @ref IR is not equal to x00 INTn PIN is asserted to low until it is x00\n\n - * Each bit of @ref IR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
CONFLICT UNREACH PPPoE MP Reserved Reserved Reserved Reserved
- * - \ref IR_CONFLICT : IP conflict - * - \ref IR_UNREACH : Destination unreachable - * - \ref IR_PPPoE : PPPoE connection close - * - \ref IR_MP : Magic packet - */ -#define IR WIZCHIP_CREG_ADDR(0x0015) - -/** - * @ingroup Common_register_group - * @brief Interrupt mask register(R/W) - * @details @ref IMR is used to mask interrupts. Each bit of @ref IMR corresponds to each bit of @ref IR. - * When a bit of @ref IMR is and the corresponding bit of @ref IR is an interrupt will be issued. In other words, - * if a bit of @ref IMR is an interrupt will not be issued even if the corresponding bit of @ref IR is \n\n - * Each bit of @ref IMR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
IM_IR7 IM_IR6 IM_IR5 IM_IR4 Reserved Reserved Reserved Reserved
- * - \ref IM_IR7 : IP Conflict Interrupt Mask - * - \ref IM_IR6 : Destination unreachable Interrupt Mask - * - \ref IM_IR5 : PPPoE Close Interrupt Mask - * - \ref IM_IR4 : Magic Packet Interrupt Mask - */ -#define IMR WIZCHIP_CREG_ADDR(0x0016) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Register(R/W) - * @details @ref SIR indicates the interrupt status of Socket.\n - * Each bit of @ref SIR be still until @ref Sn_IR is cleared by the host.\n - * If @ref Sn_IR is not equal to x00 the n-th bit of @ref SIR is and INTn PIN is asserted until @ref SIR is x00 */ -//#define SIR (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Mask Register(R/W) - * @details Each bit of @ref SIMR corresponds to each bit of @ref SIR. - * When a bit of @ref SIMR is and the corresponding bit of @ref SIR is Interrupt will be issued. - * In other words, if a bit of @ref SIMR is an interrupt will be not issued even if the corresponding bit of @ref SIR is - */ -//#define SIMR (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Timeout register address( 1 is 100us )(R/W) - * @details @ref RTR configures the retransmission timeout period. The unit of timeout period is 100us and the default of @ref RTR is x07D0or 000 - * And so the default timeout period is 200ms(100us X 2000). During the time configured by @ref RTR, W5500 waits for the peer response - * to the packet that is transmitted by \ref Sn_CR (CONNECT, DISCON, CLOSE, SEND, SEND_MAC, SEND_KEEP command). - * If the peer does not respond within the @ref RTR time, W5500 retransmits the packet or issues timeout. - */ -#define RTR WIZCHIP_CREG_ADDR(0x0017) - -/** - * @ingroup Common_register_group - * @brief Retry count register(R/W) - * @details @ref RCR configures the number of time of retransmission. - * When retransmission occurs as many as ref RCR+1 Timeout interrupt is issued (@ref Sn_IR[TIMEOUT] = . - */ -#define RCR WIZCHIP_CREG_ADDR(0x0019) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Request Timer register in PPPoE mode(R/W) - * @details @ref PTIMER configures the time for sending LCP echo request. The unit of time is 25ms. - */ -#define PTIMER WIZCHIP_CREG_ADDR(0x0028) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Magic number register in PPPoE mode(R/W) - * @details @ref PMAGIC configures the 4bytes magic number to be used in LCP negotiation. - */ -#define PMAGIC WIZCHIP_CREG_ADDR(0x0029) - -/** - * @ingroup Common_register_group - * @brief PPP Destination MAC Register address(R/W) - * @details @ref PHAR configures the PPPoE server hardware address that is acquired during PPPoE connection process. - */ -//#define PHAR (_W5500_IO_BASE_ + (0x001E << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Session Identification Register(R/W) - * @details @ref PSID configures the PPPoE sever session ID acquired during PPPoE connection process. - */ -//#define PSID (_W5500_IO_BASE_ + (0x0024 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Maximum Segment Size(MSS) register(R/W) - * @details @ref PMRU configures the maximum receive unit of PPPoE. - */ -//#define PMRU (_W5500_IO_BASE_ + (0x0026 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable IP register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR indicates - * the destination IP address & port number respectively. - */ -//#define UIPR (_W5500_IO_BASE_ + (0x002a << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable Port register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR - * indicates the destination IP address & port number respectively. - */ -//#define UPORTR (_W5500_IO_BASE_ + (0x002e << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PHY Status Register(R/W) - * @details @ref PHYCFGR configures PHY operation mode and resets PHY. In addition, @ref PHYCFGR indicates the status of PHY such as duplex, Speed, Link. - */ -//#define PHYCFGR (_W5500_IO_BASE_ + (0x002E << 8) + (WIZCHIP_CREG_BLOCK << 3)) -#define PHYSTATUS WIZCHIP_CREG_ADDR(0x0035) - -// Reserved (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0031 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0032 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0033 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0034 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0035 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0036 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0037 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0038 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief chip version register address(R) - * @details @ref VERSIONR always indicates the W5500 version as @b 0x04. - */ -//#define VERSIONR (_W5200_IO_BASE_ + (0x0039 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - - -//----------------------------- W5500 Socket Registers IOMAP ----------------------------- -/** - * @ingroup Socket_register_group - * @brief socket Mode register(R/W) - * @details @ref Sn_MR configures the option or protocol type of Socket n.\n\n - * Each bit of @ref Sn_MR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
MULTI/MFEN BCASTB ND/MC/MMB UCASTB/MIP6B Protocol[3] Protocol[2] Protocol[1] Protocol[0]
- * - @ref Sn_MR_MULTI : Support UDP Multicasting - * - @ref Sn_MR_BCASTB : Broadcast block in UDP Multicasting - * - @ref Sn_MR_ND : No Delayed Ack(TCP) flag - * - @ref Sn_MR_MC : IGMP version used in UDP mulitcasting - * - @ref Sn_MR_MMB : Multicast Blocking in @ref Sn_MR_MACRAW mode - * - @ref Sn_MR_UCASTB : Unicast Block in UDP Multicating - * - @ref Sn_MR_MIP6B : IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * - Protocol - * - * - * - * - * - * - *
Protocol[3] Protocol[2] Protocol[1] Protocol[0] @b Meaning
0 0 0 0 Closed
0 0 0 1 TCP
0 0 1 0 UDP
0 1 0 0 MACRAW
- * - @ref Sn_MR_MACRAW : MAC LAYER RAW SOCK \n - * - @ref Sn_MR_UDP : UDP - * - @ref Sn_MR_TCP : TCP - * - @ref Sn_MR_CLOSE : Unused socket - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR(N) WIZCHIP_SREG_ADDR(N, 0x0000) - -/** - * @ingroup Socket_register_group - * @brief Socket command register(R/W) - * @details This is used to set the command for Socket n such as OPEN, CLOSE, CONNECT, LISTEN, SEND, and RECEIVE.\n - * After W5500 accepts the command, the @ref Sn_CR register is automatically cleared to 0x00. - * Even though @ref Sn_CR is cleared to 0x00, the command is still being processed.\n - * To check whether the command is completed or not, please check the @ref Sn_IR or @ref Sn_SR. - * - @ref Sn_CR_OPEN : Initialize or open socket. - * - @ref Sn_CR_LISTEN : Wait connection request in TCP mode(Server mode) - * - @ref Sn_CR_CONNECT : Send connection request in TCP mode(Client mode) - * - @ref Sn_CR_DISCON : Send closing request in TCP mode. - * - @ref Sn_CR_CLOSE : Close socket. - * - @ref Sn_CR_SEND : Update TX buffer pointer and send data. - * - @ref Sn_CR_SEND_MAC : Send data with MAC address, so without ARP process. - * - @ref Sn_CR_SEND_KEEP : Send keep alive message. - * - @ref Sn_CR_RECV : Update RX buffer pointer and receive data. - */ -#define Sn_CR(N) WIZCHIP_SREG_ADDR(N, 0x0001) - -/** - * @ingroup Socket_register_group - * @brief Socket interrupt register(R) - * @details @ref Sn_IR indicates the status of Socket Interrupt such as establishment, termination, receiving data, timeout).\n - * When an interrupt occurs and the corresponding bit of @ref Sn_IMR is the corresponding bit of @ref Sn_IR becomes \n - * In order to clear the @ref Sn_IR bit, the host should write the bit to \n - * - * - * - *
7 6 5 4 3 2 1 0
Reserved Reserved Reserved SEND_OK TIMEOUT RECV DISCON CON
- * - \ref Sn_IR_SENDOK : SEND_OK Interrupt - * - \ref Sn_IR_TIMEOUT : TIMEOUT Interrupt - * - \ref Sn_IR_RECV : RECV Interrupt - * - \ref Sn_IR_DISCON : DISCON Interrupt - * - \ref Sn_IR_CON : CON Interrupt - */ -#define Sn_IR(N) WIZCHIP_SREG_ADDR(N, 0x0002) - -/** - * @ingroup Socket_register_group - * @brief Socket status register(R) - * @details @ref Sn_SR indicates the status of Socket n.\n - * The status of Socket n is changed by @ref Sn_CR or some special control packet as SYN, FIN packet in TCP. - * @par Normal status - * - @ref SOCK_CLOSED : Closed - * - @ref SOCK_INIT : Initiate state - * - @ref SOCK_LISTEN : Listen state - * - @ref SOCK_ESTABLISHED : Success to connect - * - @ref SOCK_CLOSE_WAIT : Closing state - * - @ref SOCK_UDP : UDP socket - * - @ref SOCK_MACRAW : MAC raw mode socket - *@par Temporary status during changing the status of Socket n. - * - @ref SOCK_SYNSENT : This indicates Socket n sent the connect-request packet (SYN packet) to a peer. - * - @ref SOCK_SYNRECV : It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer. - * - @ref SOCK_FIN_WAIT : Connection state - * - @ref SOCK_CLOSING : Closing state - * - @ref SOCK_TIME_WAIT : Closing state - * - @ref SOCK_LAST_ACK : Closing state - */ -#define Sn_SR(N) WIZCHIP_SREG_ADDR(N, 0x0003) - -/** - * @ingroup Socket_register_group - * @brief source port register(R/W) - * @details @ref Sn_PORT configures the source port number of Socket n. - * It is valid when Socket n is used in TCP/UPD mode. It should be set before OPEN command is ordered. - */ -#define Sn_PORT(N) WIZCHIP_SREG_ADDR(N, 0x0004) - -/** - * @ingroup Socket_register_group - * @brief Peer MAC register address(R/W) - * @details @ref Sn_DHAR configures the destination hardware address of Socket n when using SEND_MAC command in UDP mode or - * it indicates that it is acquired in ARP-process by CONNECT/SEND command. - */ -#define Sn_DHAR(N) WIZCHIP_SREG_ADDR(N, 0x0006) - -/** - * @ingroup Socket_register_group - * @brief Peer IP register address(R/W) - * @details @ref Sn_DIPR configures or indicates the destination IP address of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In TCP client mode, it configures an IP address of �TCP serverbefore CONNECT command. - * In TCP server mode, it indicates an IP address of �TCP clientafter successfully establishing connection. - * In UDP mode, it configures an IP address of peer to be received the UDP packet by SEND or SEND_MAC command. - */ -#define Sn_DIPR(N) WIZCHIP_SREG_ADDR(N, 0x000c) - -/** - * @ingroup Socket_register_group - * @brief Peer port register address(R/W) - * @details @ref Sn_DPORT configures or indicates the destination port number of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In �TCP clientmode, it configures the listen port number of �TCP serverbefore CONNECT command. - * In �TCP Servermode, it indicates the port number of TCP client after successfully establishing connection. - * In UDP mode, it configures the port number of peer to be transmitted the UDP packet by SEND/SEND_MAC command. - */ -#define Sn_DPORT(N) WIZCHIP_SREG_ADDR(N, 0x0010) - -/** - * @ingroup Socket_register_group - * @brief Maximum Segment Size(Sn_MSSR0) register address(R/W) - * @details @ref Sn_MSSR configures or indicates the MTU(Maximum Transfer Unit) of Socket n. - */ -#define Sn_MSSR(N) WIZCHIP_SREG_ADDR(N, 0x0012) - -// Reserved (_W5500_IO_BASE_ + (0x0014 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief IP Type of Service(TOS) Register(R/W) - * @details @ref Sn_TOS configures the TOS(Type Of Service field in IP Header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TOS(N) WIZCHIP_SREG_ADDR(N, 0x0015) -/** - * @ingroup Socket_register_group - * @brief IP Time to live(TTL) Register(R/W) - * @details @ref Sn_TTL configures the TTL(Time To Live field in IP header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TTL(N) WIZCHIP_SREG_ADDR(N, 0x0016) -// Reserved (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001A << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Receive memory size register(R/W) - * @details @ref Sn_RXBUF_SIZE configures the RX buffer block size of Socket n. - * Socket n RX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data cannot be normally received from a peer. - * Although Socket n RX Buffer Block size is initially configured to 2Kbytes, - * user can re-configure its size using @ref Sn_RXBUF_SIZE. The total sum of @ref Sn_RXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data reception error is occurred. - */ -#define Sn_RXBUF_SIZE(N) WIZCHIP_SREG_ADDR(N, 0x001e) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory size register(R/W) - * @details @ref Sn_TXBUF_SIZE configures the TX buffer block size of Socket n. Socket n TX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data can�t be normally transmitted to a peer. - * Although Socket n TX Buffer Block size is initially configured to 2Kbytes, - * user can be re-configure its size using @ref Sn_TXBUF_SIZE. The total sum of @ref Sn_TXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data transmission error is occurred. - */ -#define Sn_TXBUF_SIZE(N) WIZCHIP_SREG_ADDR(N, 0x001f) - -/** - * @ingroup Socket_register_group - * @brief Transmit free memory size register(R) - * @details @ref Sn_TX_FSR indicates the free size of Socket n TX Buffer Block. It is initialized to the configured size by @ref Sn_TXBUF_SIZE. - * Data bigger than @ref Sn_TX_FSR should not be saved in the Socket n TX Buffer because the bigger data overwrites the previous saved data not yet sent. - * Therefore, check before saving the data to the Socket n TX Buffer, and if data is equal or smaller than its checked size, - * transmit the data with SEND/SEND_MAC command after saving the data in Socket n TX buffer. But, if data is bigger than its checked size, - * transmit the data after dividing into the checked size and saving in the Socket n TX buffer. - */ -#define Sn_TX_FSR(N) WIZCHIP_SREG_ADDR(N, 0x0020) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory read pointer register address(R) - * @details @ref Sn_TX_RD is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP. - * After its initialization, it is auto-increased by SEND command. - * SEND command transmits the saved data from the current @ref Sn_TX_RD to the @ref Sn_TX_WR in the Socket n TX Buffer. - * After transmitting the saved data, the SEND command increases the @ref Sn_TX_RD as same as the @ref Sn_TX_WR. - * If its increment value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_TX_RD(N) WIZCHIP_SREG_ADDR(N, 0x0022) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory write pointer register address(R/W) - * @details @ref Sn_TX_WR is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP.\n - * It should be read or be updated like as follows.\n - * 1. Read the starting address for saving the transmitting data.\n - * 2. Save the transmitting data from the starting address of Socket n TX buffer.\n - * 3. After saving the transmitting data, update @ref Sn_TX_WR to the increased value as many as transmitting data size. - * If the increment value exceeds the maximum value 0xFFFF(greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value.\n - * 4. Transmit the saved data in Socket n TX Buffer by using SEND/SEND command - */ -#define Sn_TX_WR(N) WIZCHIP_SREG_ADDR(N, 0x0024) - -/** - * @ingroup Socket_register_group - * @brief Received data size register(R) - * @details @ref Sn_RX_RSR indicates the data size received and saved in Socket n RX Buffer. - * @ref Sn_RX_RSR does not exceed the @ref Sn_RXBUF_SIZE and is calculated as the difference between - * �Socket n RX Write Pointer (@ref Sn_RX_WR)and �Socket n RX Read Pointer (@ref Sn_RX_RD) - */ -#define Sn_RX_RSR(N) WIZCHIP_SREG_ADDR(N, 0x0026) - -/** - * @ingroup Socket_register_group - * @brief Read point of Receive memory(R/W) - * @details @ref Sn_RX_RD is initialized by OPEN command. Make sure to be read or updated as follows.\n - * 1. Read the starting save address of the received data.\n - * 2. Read data from the starting address of Socket n RX Buffer.\n - * 3. After reading the received data, Update @ref Sn_RX_RD to the increased value as many as the reading size. - * If the increment value exceeds the maximum value 0xFFFF, that is, is greater than 0x10000 and the carry bit occurs, - * update with the lower 16bits value ignored the carry bit.\n - * 4. Order RECV command is for notifying the updated @ref Sn_RX_RD to W5500. - */ -#define Sn_RX_RD(N) WIZCHIP_SREG_ADDR(N, 0x0028) - -/** - * @ingroup Socket_register_group - * @brief Write point of Receive memory(R) - * @details @ref Sn_RX_WR is initialized by OPEN command and it is auto-increased by the data reception. - * If the increased value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_RX_WR(N) WIZCHIP_SREG_ADDR(N, 0x002a) - -/** - * @ingroup Socket_register_group - * @brief socket interrupt mask register(R) - * @details @ref Sn_IMR masks the interrupt of Socket n. - * Each bit corresponds to each bit of @ref Sn_IR. When a Socket n Interrupt is occurred and the corresponding bit of @ref Sn_IMR is - * the corresponding bit of @ref Sn_IR becomes When both the corresponding bit of @ref Sn_IMR and @ref Sn_IR are and the n-th bit of @ref IR is - * Host is interrupted by asserted INTn PIN to low. - */ -//#define Sn_IMR(N) (_W5500_IO_BASE_ + (0x002C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Fragment field value in IP header register(R/W) - * @details @ref Sn_FRAG configures the FRAG(Fragment field in IP header). - */ -//#define Sn_FRAG(N) (_W5500_IO_BASE_ + (0x002D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Keep Alive Timer register(R/W) - * @details @ref Sn_KPALVTR configures the transmitting timer of �KEEP ALIVE(KA)packet of SOCKETn. It is valid only in TCP mode, - * and ignored in other modes. The time unit is 5s. - * KA packet is transmittable after @ref Sn_SR is changed to SOCK_ESTABLISHED and after the data is transmitted or received to/from a peer at least once. - * In case of '@ref Sn_KPALVTR > 0', W5500 automatically transmits KA packet after time-period for checking the TCP connection (Auto-keepalive-process). - * In case of '@ref Sn_KPALVTR = 0', Auto-keep-alive-process will not operate, - * and KA packet can be transmitted by SEND_KEEP command by the host (Manual-keep-alive-process). - * Manual-keep-alive-process is ignored in case of '@ref Sn_KPALVTR > 0'. - */ -//#define Sn_KPALVTR(N) (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -//#define Sn_TSR(N) (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - - -//----------------------------- W5500 Register values ----------------------------- - -/* MODE register values */ -/** - * @brief Reset - * @details If this bit is All internal registers will be initialized. It will be automatically cleared as after S/W reset. - */ -#define MR_RST 0x80 - -/** - * @brief Wake on LAN - * @details 0 : Disable WOL mode\n - * 1 : Enable WOL mode\n - * If WOL mode is enabled and the received magic packet over UDP has been normally processed, the Interrupt PIN (INTn) asserts to low. - * When using WOL mode, the UDP Socket should be opened with any source port number. (Refer to Socket n Mode Register (@ref Sn_MR) for opening Socket.) - * @note The magic packet over UDP supported by W5500 consists of 6 bytes synchronization stream (xFFFFFFFFFFFF and - * 16 times Target MAC address stream in UDP payload. The options such like password are ignored. You can use any UDP source port number for WOL mode. - */ -#define MR_WOL 0x20 - -/** - * @brief Ping block - * @details 0 : Disable Ping block\n - * 1 : Enable Ping block\n - * If the bit is it blocks the response to a ping request. - */ -#define MR_PB 0x10 - -/** - * @brief Enable PPPoE - * @details 0 : DisablePPPoE mode\n - * 1 : EnablePPPoE mode\n - * If you use ADSL, this bit should be - */ -#define MR_PPPOE 0x08 - -/** - * @brief Enable UDP_FORCE_ARP CHECHK - * @details 0 : Disable Force ARP mode\n - * 1 : Enable Force ARP mode\n - * In Force ARP mode, It forces on sending ARP Request whenever data is sent. - */ -#define MR_FARP 0x02 - -/* IR register values */ -/** - * @brief Check IP conflict. - * @details Bit is set as when own source IP address is same with the sender IP address in the received ARP request. - */ -#define IR_CONFLICT 0x80 - -/** - * @brief Get the destination unreachable message in UDP sending. - * @details When receiving the ICMP (Destination port unreachable) packet, this bit is set as - * When this bit is Destination Information such as IP address and Port number may be checked with the corresponding @ref UIPR & @ref UPORTR. - */ -#define IR_UNREACH 0x40 - -/** - * @brief Get the PPPoE close message. - * @details When PPPoE is disconnected during PPPoE mode, this bit is set. - */ -#define IR_PPPoE 0x20 - -/** - * @brief Get the magic packet interrupt. - * @details When WOL mode is enabled and receives the magic packet over UDP, this bit is set. - */ -#define IR_MP 0x10 - - -/* PHYCFGR register value */ -#define PHYCFGR_RST ~(1<<7) //< For PHY reset, must operate AND mask. -#define PHYCFGR_OPMD (1<<6) // Configre PHY with OPMDC value -#define PHYCFGR_OPMDC_ALLA (7<<3) -#define PHYCFGR_OPMDC_PDOWN (6<<3) -#define PHYCFGR_OPMDC_NA (5<<3) -#define PHYCFGR_OPMDC_100FA (4<<3) -#define PHYCFGR_OPMDC_100F (3<<3) -#define PHYCFGR_OPMDC_100H (2<<3) -#define PHYCFGR_OPMDC_10F (1<<3) -#define PHYCFGR_OPMDC_10H (0<<3) -#define PHYCFGR_DPX_FULL (1<<2) -#define PHYCFGR_DPX_HALF (0<<2) -#define PHYCFGR_SPD_100 (1<<1) -#define PHYCFGR_SPD_10 (0<<1) -#define PHYCFGR_LNK_ON (1<<0) -#define PHYCFGR_LNK_OFF (0<<0) - -// PHYSTATUS register -#define PHYSTATUS_POWERDOWN (0x08) -#define PHYSTATUS_LINK (0x20) - -/* IMR register values */ -/** - * @brief IP Conflict Interrupt Mask. - * @details 0: Disable IP Conflict Interrupt\n - * 1: Enable IP Conflict Interrupt - */ -#define IM_IR7 0x80 - -/** - * @brief Destination unreachable Interrupt Mask. - * @details 0: Disable Destination unreachable Interrupt\n - * 1: Enable Destination unreachable Interrupt - */ -#define IM_IR6 0x40 - -/** - * @brief PPPoE Close Interrupt Mask. - * @details 0: Disable PPPoE Close Interrupt\n - * 1: Enable PPPoE Close Interrupt - */ -#define IM_IR5 0x20 - -/** - * @brief Magic Packet Interrupt Mask. - * @details 0: Disable Magic Packet Interrupt\n - * 1: Enable Magic Packet Interrupt - */ -#define IM_IR4 0x10 - -/* Sn_MR Default values */ -/** - * @brief Support UDP Multicasting - * @details 0 : disable Multicasting\n - * 1 : enable Multicasting\n - * This bit is applied only during UDP mode(P[3:0] = 010.\n - * To use multicasting, @ref Sn_DIPR & @ref Sn_DPORT should be respectively configured with the multicast group IP address & port number - * before Socket n is opened by OPEN command of @ref Sn_CR. - */ -#define Sn_MR_MULTI 0x80 - -/** - * @brief Broadcast block in UDP Multicasting. - * @details 0 : disable Broadcast Blocking\n - * 1 : enable Broadcast Blocking\n - * This bit blocks to receive broadcasting packet during UDP mode(P[3:0] = 010.\m - * In addition, This bit does when MACRAW mode(P[3:0] = 100 - */ -//#define Sn_MR_BCASTB 0x40 - -/** - * @brief No Delayed Ack(TCP), Multicast flag - * @details 0 : Disable No Delayed ACK option\n - * 1 : Enable No Delayed ACK option\n - * This bit is applied only during TCP mode (P[3:0] = 001.\n - * When this bit is It sends the ACK packet without delay as soon as a Data packet is received from a peer.\n - * When this bit is It sends the ACK packet after waiting for the timeout time configured by @ref RTR. - */ -#define Sn_MR_ND 0x20 - -/** - * @brief Unicast Block in UDP Multicasting - * @details 0 : disable Unicast Blocking\n - * 1 : enable Unicast Blocking\n - * This bit blocks receiving the unicast packet during UDP mode(P[3:0] = 010 and MULTI = - */ -//#define Sn_MR_UCASTB 0x10 - -/** - * @brief MAC LAYER RAW SOCK - * @details This configures the protocol mode of Socket n. - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR_MACRAW 0x04 - -#define Sn_MR_IPRAW 0x03 /**< IP LAYER RAW SOCK */ - -/** - * @brief UDP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_UDP 0x02 - -/** - * @brief TCP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_TCP 0x01 - -/** - * @brief Unused socket - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_CLOSE 0x00 - -/* Sn_MR values used with Sn_MR_MACRAW */ -/** - * @brief MAC filter enable in @ref Sn_MR_MACRAW mode - * @details 0 : disable MAC Filtering\n - * 1 : enable MAC Filtering\n - * This bit is applied only during MACRAW mode(P[3:0] = 100.\n - * When set as W5500 can only receive broadcasting packet or packet sent to itself. - * When this bit is W5500 can receive all packets on Ethernet. - * If user wants to implement Hybrid TCP/IP stack, - * it is recommended that this bit is set as for reducing host overhead to process the all received packets. - */ -#define Sn_MR_MFEN Sn_MR_MULTI - -/** - * @brief Multicast Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : using IGMP version 2\n - * 1 : using IGMP version 1\n - * This bit is applied only during UDP mode(P[3:0] = 010 and MULTI = - * It configures the version for IGMP messages (Join/Leave/Report). - */ -#define Sn_MR_MMB Sn_MR_ND - -/** - * @brief IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : disable IPv6 Blocking\n - * 1 : enable IPv6 Blocking\n - * This bit is applied only during MACRAW mode (P[3:0] = 100. It blocks to receiving the IPv6 packet. - */ -#define Sn_MR_MIP6B Sn_MR_UCASTB - -/* Sn_MR value used with Sn_MR_UDP & Sn_MR_MULTI */ -/** - * @brief IGMP version used in UDP mulitcasting - * @details 0 : disable Multicast Blocking\n - * 1 : enable Multicast Blocking\n - * This bit is applied only when MACRAW mode(P[3:0] = 100. It blocks to receive the packet with multicast MAC address. - */ -#define Sn_MR_MC Sn_MR_ND - -/* Sn_MR alternate values */ -/** - * @brief For Berkeley Socket API - */ -#define SOCK_STREAM Sn_MR_TCP - -/** - * @brief For Berkeley Socket API - */ -#define SOCK_DGRAM Sn_MR_UDP - - -/* Sn_CR values */ -/** - * @brief Initialize or open socket - * @details Socket n is initialized and opened according to the protocol selected in Sn_MR(P3:P0). - * The table below shows the value of @ref Sn_SR corresponding to @ref Sn_MR.\n - * - * - * - * - * - * - *
\b Sn_MR (P[3:0]) \b Sn_SR
Sn_MR_CLOSE (000
Sn_MR_TCP (001 SOCK_INIT (0x13)
Sn_MR_UDP (010 SOCK_UDP (0x22)
S0_MR_MACRAW (100 SOCK_MACRAW (0x02)
- */ -#define Sn_CR_OPEN 0x01 - -/** - * @brief Wait connection request in TCP mode(Server mode) - * @details This is valid only in TCP mode (Sn_MR(P3:P0) = Sn_MR_TCP). - * In this mode, Socket n operates as a �TCP serverand waits for connection-request (SYN packet) from any �TCP client - * The @ref Sn_SR changes the state from SOCK_INIT to SOCKET_LISTEN. - * When a �TCP clientconnection request is successfully established, - * the @ref Sn_SR changes from SOCK_LISTEN to SOCK_ESTABLISHED and the Sn_IR(0) becomes - * But when a �TCP clientconnection request is failed, Sn_IR(3) becomes and the status of @ref Sn_SR changes to SOCK_CLOSED. - */ -#define Sn_CR_LISTEN 0x02 - -/** - * @brief Send connection request in TCP mode(Client mode) - * @details To connect, a connect-request (SYN packet) is sent to b>TCP serverconfigured by @ref Sn_DIPR & Sn_DPORT(destination address & port). - * If the connect-request is successful, the @ref Sn_SR is changed to @ref SOCK_ESTABLISHED and the Sn_IR(0) becomes \n\n - * The connect-request fails in the following three cases.\n - * 1. When a @b ARPTO occurs (@ref Sn_IR[3] = ) because destination hardware address is not acquired through the ARP-process.\n - * 2. When a @b SYN/ACK packet is not received and @b TCPTO (Sn_IR(3) = )\n - * 3. When a @b RST packet is received instead of a @b SYN/ACK packet. In these cases, @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note This is valid only in TCP mode and operates when Socket n acts as b>TCP client - */ -#define Sn_CR_CONNECT 0x04 - -/** - * @brief Send closing request in TCP mode - * @details Regardless of b>TCP serveror b>TCP client the DISCON command processes the disconnect-process (b>Active closeor b>Passive close.\n - * @par Active close - * it transmits disconnect-request(FIN packet) to the connected peer\n - * @par Passive close - * When FIN packet is received from peer, a FIN packet is replied back to the peer.\n - * @details When the disconnect-process is successful (that is, FIN/ACK packet is received successfully), @ref Sn_SR is changed to @ref SOCK_CLOSED.\n - * Otherwise, TCPTO occurs (Sn_IR(3)=)= and then @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note Valid only in TCP mode. - */ -#define Sn_CR_DISCON 0x08 - -/** - * @brief Close socket - * @details Sn_SR is changed to @ref SOCK_CLOSED. - */ -#define Sn_CR_CLOSE 0x10 - -/** - * @brief Update TX buffer pointer and send data - * @details SEND transmits all the data in the Socket n TX buffer.\n - * For more details, please refer to Socket n TX Free Size Register (@ref Sn_TX_FSR), Socket n, - * TX Write Pointer Register(@ref Sn_TX_WR), and Socket n TX Read Pointer Register(@ref Sn_TX_RD). - */ -#define Sn_CR_SEND 0x20 - -/** - * @brief Send data with MAC address, so without ARP process - * @details The basic operation is same as SEND.\n - * Normally SEND transmits data after destination hardware address is acquired by the automatic ARP-process(Address Resolution Protocol).\n - * But SEND_MAC transmits data without the automatic ARP-process.\n - * In this case, the destination hardware address is acquired from @ref Sn_DHAR configured by host, instead of APR-process. - * @note Valid only in UDP mode. - */ -#define Sn_CR_SEND_MAC 0x21 - -/** - * @brief Send keep alive message - * @details It checks the connection status by sending 1byte keep-alive packet.\n - * If the peer can not respond to the keep-alive packet during timeout time, the connection is terminated and the timeout interrupt will occur. - * @note Valid only in TCP mode. - */ -#define Sn_CR_SEND_KEEP 0x22 - -/** - * @brief Update RX buffer pointer and receive data - * @details RECV completes the processing of the received data in Socket n RX Buffer by using a RX read pointer register (@ref Sn_RX_RD).\n - * For more details, refer to Socket n RX Received Size Register (@ref Sn_RX_RSR), Socket n RX Write Pointer Register (@ref Sn_RX_WR), - * and Socket n RX Read Pointer Register (@ref Sn_RX_RD). - */ -#define Sn_CR_RECV 0x40 - -/* Sn_IR values */ -/** - * @brief SEND_OK Interrupt - * @details This is issued when SEND command is completed. - */ -#define Sn_IR_SENDOK 0x10 - -/** - * @brief TIMEOUT Interrupt - * @details This is issued when ARPTO or TCPTO occurs. - */ -#define Sn_IR_TIMEOUT 0x08 - -/** - * @brief RECV Interrupt - * @details This is issued whenever data is received from a peer. - */ -#define Sn_IR_RECV 0x04 - -/** - * @brief DISCON Interrupt - * @details This is issued when FIN or FIN/ACK packet is received from a peer. - */ -#define Sn_IR_DISCON 0x02 - -/** - * @brief CON Interrupt - * @details This is issued one time when the connection with peer is successful and then @ref Sn_SR is changed to @ref SOCK_ESTABLISHED. - */ -#define Sn_IR_CON 0x01 - -/* Sn_SR values */ -/** - * @brief Closed - * @details This indicates that Socket n is released.\N - * When DICON, CLOSE command is ordered, or when a timeout occurs, it is changed to @ref SOCK_CLOSED regardless of previous status. - */ -#define SOCK_CLOSED 0x00 - -/** - * @brief Initiate state - * @details This indicates Socket n is opened with TCP mode.\N - * It is changed to @ref SOCK_INIT when Sn_MR(P[3:0]) = 001and OPEN command is ordered.\N - * After @ref SOCK_INIT, user can use LISTEN /CONNECT command. - */ -#define SOCK_INIT 0x13 - -/** - * @brief Listen state - * @details This indicates Socket n is operating as b>TCP servermode and waiting for connection-request (SYN packet) from a peer (b>TCP client.\n - * It will change to @ref SOCK_ESTALBLISHED when the connection-request is successfully accepted.\n - * Otherwise it will change to @ref SOCK_CLOSED after TCPTO occurred (Sn_IR(TIMEOUT) = . - */ -#define SOCK_LISTEN 0x14 - -/** - * @brief Connection state - * @details This indicates Socket n sent the connect-request packet (SYN packet) to a peer.\n - * It is temporarily shown when @ref Sn_SR is changed from @ref SOCK_INIT to @ref SOCK_ESTABLISHED by CONNECT command.\n - * If connect-accept(SYN/ACK packet) is received from the peer at SOCK_SYNSENT, it changes to @ref SOCK_ESTABLISHED.\n - * Otherwise, it changes to @ref SOCK_CLOSED after TCPTO (@ref Sn_IR[TIMEOUT] = is occurred. - */ -#define SOCK_SYNSENT 0x15 - -/** - * @brief Connection state - * @details It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer.\n - * If socket n sends the response (SYN/ACK packet) to the peer successfully, it changes to @ref SOCK_ESTABLISHED. \n - * If not, it changes to @ref SOCK_CLOSED after timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_SYNRECV 0x16 - -/** - * @brief Success to connect - * @details This indicates the status of the connection of Socket n.\n - * It changes to @ref SOCK_ESTABLISHED when the b>TCP SERVERprocessed the SYN packet from the b>TCP CLIENTduring @ref SOCK_LISTEN, or - * when the CONNECT command is successful.\n - * During @ref SOCK_ESTABLISHED, DATA packet can be transferred using SEND or RECV command. - */ -#define SOCK_ESTABLISHED 0x17 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_FIN_WAIT 0x18 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_CLOSING 0x1A - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_TIME_WAIT 0x1B - -/** - * @brief Closing state - * @details This indicates Socket n received the disconnect-request (FIN packet) from the connected peer.\n - * This is half-closing status, and data can be transferred.\n - * For full-closing, DISCON command is used. But For just-closing, CLOSE command is used. - */ -#define SOCK_CLOSE_WAIT 0x1C - -/** - * @brief Closing state - * @details This indicates Socket n is waiting for the response (FIN/ACK packet) to the disconnect-request (FIN packet) by passive-close.\n - * It changes to @ref SOCK_CLOSED when Socket n received the response successfully, or when timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_LAST_ACK 0x1D - -/** - * @brief UDP socket - * @details This indicates Socket n is opened in UDP mode(Sn_MR(P[3:0]) = 010.\n - * It changes to SOCK_UPD when Sn_MR(P[3:0]) = 010 and OPEN command is ordered.\n - * Unlike TCP mode, data can be transfered without the connection-process. - */ -#define SOCK_UDP 0x22 - -//#define SOCK_IPRAW 0x32 /**< IP raw mode socket */ - -/** - * @brief MAC raw mode socket - * @details This indicates Socket 0 is opened in MACRAW mode (S0_MR(P[3:0]) = 100and is valid only in Socket 0.\n - * It changes to SOCK_MACRAW when S0_MR(P[3:0] = 100and OPEN command is ordered.\n - * Like UDP mode socket, MACRAW mode Socket 0 can transfer a MAC packet (Ethernet frame) without the connection-process. - */ -#define SOCK_MACRAW 0x42 - -//#define SOCK_PPPOE 0x5F - -/* IP PROTOCOL */ -#define IPPROTO_IP 0 //< Dummy for IP -#define IPPROTO_ICMP 1 //< Control message protocol -#define IPPROTO_IGMP 2 //< Internet group management protocol -#define IPPROTO_GGP 3 //< Gateway^2 (deprecated) -#define IPPROTO_TCP 6 //< TCP -#define IPPROTO_PUP 12 //< PUP -#define IPPROTO_UDP 17 //< UDP -#define IPPROTO_IDP 22 //< XNS idp -#define IPPROTO_ND 77 //< UNOFFICIAL net disk protocol -#define IPPROTO_RAW 255 //< Raw IP packet - - -/** - * @brief Enter a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n \n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt.\n - * In OS environment, You can replace it to critical section api supported by OS. - * - * \sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * \sa WIZCHIP_CRITICAL_EXIT() - */ -#define WIZCHIP_CRITICAL_ENTER() WIZCHIP.CRIS._enter() - -/** - * @brief Exit a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n\n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt. \n - * In OS environment, You can replace it to critical section api supported by OS. - * - * @sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * @sa WIZCHIP_CRITICAL_ENTER() - */ -#ifdef _exit -#undef _exit -#endif -#define WIZCHIP_CRITICAL_EXIT() WIZCHIP.CRIS._exit() - - - -//////////////////////// -// Basic I/O Function // -//////////////////////// - -/** - * @ingroup Basic_IO_function - * @brief It reads 1 byte value from a register. - * @param AddrSel Register address - * @return The value of register - */ -uint8_t WIZCHIP_READ (uint32_t AddrSel); - -/** - * @ingroup Basic_IO_function - * @brief It writes 1 byte value to a register. - * @param AddrSel Register address - * @param wb Write data - * @return void - */ -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb ); - -/** - * @ingroup Basic_IO_function - * @brief It reads sequence data from registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to read data - * @param len Data length - */ -void WIZCHIP_READ_BUF (uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It writes sequence data to registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to write data - * @param len Data length - */ -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -///////////////////////////////// -// Common Register I/O function // -///////////////////////////////// -/** - * @ingroup Common_register_access_function - * @brief Set Mode Register - * @param (uint8_t)mr The value to be set. - * @sa getMR() - */ -#define setMR(mr) \ - WIZCHIP_WRITE(MR,mr) - - -/** - * @ingroup Common_register_access_function - * @brief Get Mode Register - * @return uint8_t. The value of Mode register. - * @sa setMR() - */ -#define getMR() \ - WIZCHIP_READ(MR) - -/** - * @ingroup Common_register_access_function - * @brief Set gateway IP address - * @param (uint8_t*)gar Pointer variable to set gateway IP address. It should be allocated 4 bytes. - * @sa getGAR() - */ -#define setGAR(gar) \ - WIZCHIP_WRITE_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Get gateway IP address - * @param (uint8_t*)gar Pointer variable to get gateway IP address. It should be allocated 4 bytes. - * @sa setGAR() - */ -#define getGAR(gar) \ - WIZCHIP_READ_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Set subnet mask address - * @param (uint8_t*)subr Pointer variable to set subnet mask address. It should be allocated 4 bytes. - * @sa getSUBR() - */ -#define setSUBR(subr) \ - WIZCHIP_WRITE_BUF(SUBR, subr,4) - - -/** - * @ingroup Common_register_access_function - * @brief Get subnet mask address - * @param (uint8_t*)subr Pointer variable to get subnet mask address. It should be allocated 4 bytes. - * @sa setSUBR() - */ -#define getSUBR(subr) \ - WIZCHIP_READ_BUF(SUBR, subr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set local MAC address - * @param (uint8_t*)shar Pointer variable to set local MAC address. It should be allocated 6 bytes. - * @sa getSHAR() - */ -#define setSHAR(shar) \ - WIZCHIP_WRITE_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local MAC address - * @param (uint8_t*)shar Pointer variable to get local MAC address. It should be allocated 6 bytes. - * @sa setSHAR() - */ -#define getSHAR(shar) \ - WIZCHIP_READ_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set local IP address - * @param (uint8_t*)sipr Pointer variable to set local IP address. It should be allocated 4 bytes. - * @sa getSIPR() - */ -#define setSIPR(sipr) \ - WIZCHIP_WRITE_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)sipr Pointer variable to get local IP address. It should be allocated 4 bytes. - * @sa setSIPR() - */ -#define getSIPR(sipr) \ - WIZCHIP_READ_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set INTLEVEL register - * @param (uint16_t)intlevel Value to set @ref INTLEVEL register. - * @sa getINTLEVEL() - */ -// dpgeorge: not yet implemented -#define setINTLEVEL(intlevel) (void)intlevel -#if 0 -#define setINTLEVEL(intlevel) {\ - WIZCHIP_WRITE(INTLEVEL, (uint8_t)(intlevel >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(INTLEVEL,1), (uint8_t) intlevel); \ - } -#endif - - -/** - * @ingroup Common_register_access_function - * @brief Get INTLEVEL register - * @return uint16_t. Value of @ref INTLEVEL register. - * @sa setINTLEVEL() - */ -// dpgeorge: not yet implemented -#define getINTLEVEL() (0) -#if 0 -#define getINTLEVEL() \ - ((WIZCHIP_READ(INTLEVEL) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(INTLEVEL,1))) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Set @ref IR register - * @param (uint8_t)ir Value to set @ref IR register. - * @sa getIR() - */ -#define setIR(ir) \ - WIZCHIP_WRITE(IR, (ir & 0xF0)) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IR register - * @return uint8_t. Value of @ref IR register. - * @sa setIR() - */ -#define getIR() \ - (WIZCHIP_READ(IR) & 0xF0) -/** - * @ingroup Common_register_access_function - * @brief Set @ref IMR register - * @param (uint8_t)imr Value to set @ref IMR register. - * @sa getIMR() - */ -#define setIMR(imr) \ - WIZCHIP_WRITE(IMR, imr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IMR register - * @return uint8_t. Value of @ref IMR register. - * @sa setIMR() - */ -#define getIMR() \ - WIZCHIP_READ(IMR) - - -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIR register - * @param (uint8_t)sir Value to set @ref SIR register. - * @sa getSIR() - */ -// dpgeorge: not yet implemented -#define setSIR(sir) ((void)sir) -#if 0 -#define setSIR(sir) \ - WIZCHIP_WRITE(SIR, sir) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIR register - * @return uint8_t. Value of @ref SIR register. - * @sa setSIR() - */ -// dpgeorge: not yet implemented -#define getSIR() (0) -#if 0 -#define getSIR() \ - WIZCHIP_READ(SIR) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIMR register - * @param (uint8_t)simr Value to set @ref SIMR register. - * @sa getSIMR() - */ -// dpgeorge: not yet implemented -#define setSIMR(simr) ((void)simr) -#if 0 -#define setSIMR(simr) \ - WIZCHIP_WRITE(SIMR, simr) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIMR register - * @return uint8_t. Value of @ref SIMR register. - * @sa setSIMR() - */ -// dpgeorge: not yet implemented -#define getSIMR() (0) -#if 0 -#define getSIMR() \ - WIZCHIP_READ(SIMR) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RTR register - * @param (uint16_t)rtr Value to set @ref RTR register. - * @sa getRTR() - */ -#define setRTR(rtr) {\ - WIZCHIP_WRITE(RTR, (uint8_t)(rtr >> 8)); \ - WIZCHIP_WRITE(RTR + 1, (uint8_t) rtr); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RTR register - * @return uint16_t. Value of @ref RTR register. - * @sa setRTR() - */ -#define getRTR() \ - ((WIZCHIP_READ(RTR) << 8) + WIZCHIP_READ(RTR + 1)) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RCR register - * @param (uint8_t)rcr Value to set @ref RCR register. - * @sa getRCR() - */ -#define setRCR(rcr) \ - WIZCHIP_WRITE(RCR, rcr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RCR register - * @return uint8_t. Value of @ref RCR register. - * @sa setRCR() - */ -#define getRCR() \ - WIZCHIP_READ(RCR) - -//================================================== test done =========================================================== - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PTIMER register - * @param (uint8_t)ptimer Value to set @ref PTIMER register. - * @sa getPTIMER() - */ -#define setPTIMER(ptimer) \ - WIZCHIP_WRITE(PTIMER, ptimer) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PTIMER register - * @return uint8_t. Value of @ref PTIMER register. - * @sa setPTIMER() - */ -#define getPTIMER() \ - WIZCHIP_READ(PTIMER) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMAGIC register - * @param (uint8_t)pmagic Value to set @ref PMAGIC register. - * @sa getPMAGIC() - */ -#define setPMAGIC(pmagic) \ - WIZCHIP_WRITE(PMAGIC, pmagic) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMAGIC register - * @return uint8_t. Value of @ref PMAGIC register. - * @sa setPMAGIC() - */ -#define getPMAGIC() \ - WIZCHIP_READ(PMAGIC) - -/** - * @ingroup Common_register_access_function - * @brief Set PHAR address - * @param (uint8_t*)phar Pointer variable to set PPP destination MAC register address. It should be allocated 6 bytes. - * @sa getPHAR() - */ -#if 0 -#define setPHAR(phar) \ - WIZCHIP_WRITE_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)phar Pointer variable to PPP destination MAC register address. It should be allocated 6 bytes. - * @sa setPHAR() - */ -#define getPHAR(phar) \ - WIZCHIP_READ_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PSID register - * @param (uint16_t)psid Value to set @ref PSID register. - * @sa getPSID() - */ -#define setPSID(psid) {\ - WIZCHIP_WRITE(PSID, (uint8_t)(psid >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PSID,1), (uint8_t) psid); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PSID register - * @return uint16_t. Value of @ref PSID register. - * @sa setPSID() - */ -//uint16_t getPSID(void); -#define getPSID() \ - ((WIZCHIP_READ(PSID) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PSID,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMRU register - * @param (uint16_t)pmru Value to set @ref PMRU register. - * @sa getPMRU() - */ -#define setPMRU(pmru) { \ - WIZCHIP_WRITE(PMRU, (uint8_t)(pmru>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PMRU,1), (uint8_t) pmru); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMRU register - * @return uint16_t. Value of @ref PMRU register. - * @sa setPMRU() - */ -#define getPMRU() \ - ((WIZCHIP_READ(PMRU) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PMRU,1))) - -/** - * @ingroup Common_register_access_function - * @brief Get unreachable IP address - * @param (uint8_t*)uipr Pointer variable to get unreachable IP address. It should be allocated 4 bytes. - */ -#define getUIPR(uipr) \ - WIZCHIP_READ_BUF(UIPR,uipr,6) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref UPORTR register - * @return uint16_t. Value of @ref UPORTR register. - */ -#define getUPORTR() \ - ((WIZCHIP_READ(UPORTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(UPORTR,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PHYCFGR register - * @param (uint8_t)phycfgr Value to set @ref PHYCFGR register. - * @sa getPHYCFGR() - */ -#define setPHYCFGR(phycfgr) \ - WIZCHIP_WRITE(PHYCFGR, phycfgr) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PHYCFGR register - * @return uint8_t. Value of @ref PHYCFGR register. - * @sa setPHYCFGR() - */ -#define getPHYSTATUS() \ - WIZCHIP_READ(PHYSTATUS) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref VERSIONR register - * @return uint8_t. Value of @ref VERSIONR register. - */ -/* -#define getVERSIONR() \ - WIZCHIP_READ(VERSIONR) - */ -///////////////////////////////////// - -/////////////////////////////////// -// Socket N register I/O function // -/////////////////////////////////// -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)mr Value to set @ref Sn_MR - * @sa getSn_MR() - */ -#define setSn_MR(sn, mr) \ - WIZCHIP_WRITE(Sn_MR(sn),mr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_MR. - * @sa setSn_MR() - */ -#define getSn_MR(sn) \ - WIZCHIP_READ(Sn_MR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)cr Value to set @ref Sn_CR - * @sa getSn_CR() - */ -#define setSn_CR(sn, cr) \ - WIZCHIP_WRITE(Sn_CR(sn), cr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_CR. - * @sa setSn_CR() - */ -#define getSn_CR(sn) \ - WIZCHIP_READ(Sn_CR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ir Value to set @ref Sn_IR - * @sa getSn_IR() - */ -#define setSn_IR(sn, ir) \ - WIZCHIP_WRITE(Sn_IR(sn), (ir & 0x1F)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IR. - * @sa setSn_IR() - */ -#define getSn_IR(sn) \ - (WIZCHIP_READ(Sn_IR(sn)) & 0x1F) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)imr Value to set @ref Sn_IMR - * @sa getSn_IMR() - */ -// dpgeorge: not yet implemented -#define setSn_IMR(sn, imr) (void)sn; (void)imr -#if 0 -#define setSn_IMR(sn, imr) \ - WIZCHIP_WRITE(Sn_IMR(sn), (imr & 0x1F)) -#endif - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IMR. - * @sa setSn_IMR() - */ -// dpgeorge: not yet implemented -#define getSn_IMR(sn) (0) -#if 0 -#define getSn_IMR(sn) \ - (WIZCHIP_READ(Sn_IMR(sn)) & 0x1F) -#endif - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_SR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_SR. - */ -#define getSn_SR(sn) \ - WIZCHIP_READ(Sn_SR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)port Value to set @ref Sn_PORT. - * @sa getSn_PORT() - */ -#define setSn_PORT(sn, port) { \ - WIZCHIP_WRITE(Sn_PORT(sn), (uint8_t)(port >> 8)); \ - WIZCHIP_WRITE(Sn_PORT(sn) + 1, (uint8_t) port); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_PORT. - * @sa setSn_PORT() - */ -#define getSn_PORT(sn) \ - ((WIZCHIP_READ(Sn_PORT(sn)) << 8) | WIZCHIP_READ(Sn_PORT(sn) + 1)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DHAR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to set socket n destination hardware address. It should be allocated 6 bytes. - * @sa getSn_DHAR() - */ -#define setSn_DHAR(sn, dhar) \ - WIZCHIP_WRITE_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to get socket n destination hardware address. It should be allocated 6 bytes. - * @sa setSn_DHAR() - */ -#define getSn_DHAR(sn, dhar) \ - WIZCHIP_READ_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to set socket n destination IP address. It should be allocated 4 bytes. - * @sa getSn_DIPR() - */ -#define setSn_DIPR(sn, dipr) \ - WIZCHIP_WRITE_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to get socket n destination IP address. It should be allocated 4 bytes. - * @sa SetSn_DIPR() - */ -#define getSn_DIPR(sn, dipr) \ - WIZCHIP_READ_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)dport Value to set @ref Sn_DPORT - * @sa getSn_DPORT() - */ -#define setSn_DPORT(sn, dport) { \ - WIZCHIP_WRITE(Sn_DPORT(sn), (uint8_t) (dport>>8)); \ - WIZCHIP_WRITE(Sn_DPORT(sn) + 1, (uint8_t) dport); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_DPORT. - * @sa setSn_DPORT() - */ -#define getSn_DPORT(sn) \ - ((WIZCHIP_READ(Sn_DPORT(sn)) << 8) + WIZCHIP_READ((Sn_DPORT(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)mss Value to set @ref Sn_MSSR - * @sa setSn_MSSR() - */ -#define setSn_MSSR(sn, mss) { \ - WIZCHIP_WRITE(Sn_MSSR(sn), (uint8_t)(mss>>8)); \ - WIZCHIP_WRITE((Sn_MSSR(sn)+1), (uint8_t) mss); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_MSSR. - * @sa setSn_MSSR() - */ -#define getSn_MSSR(sn) \ - ((WIZCHIP_READ(Sn_MSSR(sn)) << 8) + WIZCHIP_READ((Sn_MSSR(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)tos Value to set @ref Sn_TOS - * @sa getSn_TOS() - */ -#define setSn_TOS(sn, tos) \ - WIZCHIP_WRITE(Sn_TOS(sn), tos) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of Sn_TOS. - * @sa setSn_TOS() - */ -#define getSn_TOS(sn) \ - WIZCHIP_READ(Sn_TOS(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ttl Value to set @ref Sn_TTL - * @sa getSn_TTL() - */ -#define setSn_TTL(sn, ttl) \ - WIZCHIP_WRITE(Sn_TTL(sn), ttl) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TTL. - * @sa setSn_TTL() - */ -#define getSn_TTL(sn) \ - WIZCHIP_READ(Sn_TTL(sn)) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)rxbufsize Value to set @ref Sn_RXBUF_SIZE - * @sa getSn_RXBUF_SIZE() - */ -#define setSn_RXBUF_SIZE(sn, rxbufsize) \ - WIZCHIP_WRITE(Sn_RXBUF_SIZE(sn),rxbufsize) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_RXBUF_SIZE. - * @sa setSn_RXBUF_SIZE() - */ -#define getSn_RXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_RXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)txbufsize Value to set @ref Sn_TXBUF_SIZE - * @sa getSn_TXBUF_SIZE() - */ -#define setSn_TXBUF_SIZE(sn, txbufsize) \ - WIZCHIP_WRITE(Sn_TXBUF_SIZE(sn), txbufsize) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TXBUF_SIZE. - * @sa setSn_TXBUF_SIZE() - */ -#define getSn_TXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_TXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_FSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_FSR. - */ -uint16_t getSn_TX_FSR(uint8_t sn); - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_RD. - */ -#define getSn_TX_RD(sn) \ - ((WIZCHIP_READ(Sn_TX_RD(sn)) << 8) + WIZCHIP_READ((Sn_TX_RD(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)txwr Value to set @ref Sn_TX_WR - * @sa GetSn_TX_WR() - */ -#define setSn_TX_WR(sn, txwr) { \ - WIZCHIP_WRITE(Sn_TX_WR(sn), (uint8_t)(txwr>>8)); \ - WIZCHIP_WRITE((Sn_TX_WR(sn)+1), (uint8_t) txwr); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_WR. - * @sa setSn_TX_WR() - */ -#define getSn_TX_WR(sn) \ - ((WIZCHIP_READ(Sn_TX_WR(sn)) << 8) + WIZCHIP_READ((Sn_TX_WR(sn)+1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_RSR. - */ -uint16_t getSn_RX_RSR(uint8_t sn); - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)rxrd Value to set @ref Sn_RX_RD - * @sa getSn_RX_RD() - */ -#define setSn_RX_RD(sn, rxrd) { \ - WIZCHIP_WRITE(Sn_RX_RD(sn), (uint8_t)(rxrd>>8)); \ - WIZCHIP_WRITE((Sn_RX_RD(sn)+1), (uint8_t) rxrd); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @regurn uint16_t. Value of @ref Sn_RX_RD. - * @sa setSn_RX_RD() - */ -#define getSn_RX_RD(sn) \ - ((WIZCHIP_READ(Sn_RX_RD(sn)) << 8) + WIZCHIP_READ((Sn_RX_RD(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_WR. - */ -#define getSn_RX_WR(sn) \ - ((WIZCHIP_READ(Sn_RX_WR(sn)) << 8) + WIZCHIP_READ((Sn_RX_WR(sn)+1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)frag Value to set @ref Sn_FRAG - * @sa getSn_FRAD() - */ -#if 0 // dpgeorge -#define setSn_FRAG(sn, frag) { \ - WIZCHIP_WRITE(Sn_FRAG(sn), (uint8_t)(frag >>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1), (uint8_t) frag); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_FRAG. - * @sa setSn_FRAG() - */ -#define getSn_FRAG(sn) \ - ((WIZCHIP_READ(Sn_FRAG(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)kpalvt Value to set @ref Sn_KPALVTR - * @sa getSn_KPALVTR() - */ -#define setSn_KPALVTR(sn, kpalvt) \ - WIZCHIP_WRITE(Sn_KPALVTR(sn), kpalvt) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_KPALVTR. - * @sa setSn_KPALVTR() - */ -#define getSn_KPALVTR(sn) \ - WIZCHIP_READ(Sn_KPALVTR(sn)) - -////////////////////////////////////// -#endif - -///////////////////////////////////// -// Sn_TXBUF & Sn_RXBUF IO function // -///////////////////////////////////// -/** - * @brief Gets the max buffer size of socket sn passed as parameter. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n RX max buffer size. - */ -#define getSn_RxMAX(sn) \ - (getSn_RXBUF_SIZE(sn) << 10) - -/** - * @brief Gets the max buffer size of socket sn passed as parameters. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n TX max buffer size. - */ -//uint16_t getSn_TxMAX(uint8_t sn); -#define getSn_TxMAX(sn) \ - (getSn_TXBUF_SIZE(sn) << 10) - -void wiz_init(void); - -/** - * @ingroup Basic_IO_function - * @brief It copies data to internal TX memory - * - * @details This function reads the Tx write pointer register and after that, - * it copies the wizdata(pointer buffer) of the length of len(variable) bytes to internal TX memory - * and updates the Tx write pointer register. - * This function is being called by send() and sendto() function also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to write data - * @param len Data length - * @sa wiz_recv_data() - */ -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It copies data to your buffer from internal RX memory - * - * @details This function read the Rx read pointer register and after that, - * it copies the received data from internal RX memory - * to wizdata(pointer variable) of the length of len(variable) bytes. - * This function is being called by recv() also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to read data - * @param len Data length - * @sa wiz_send_data() - */ -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It discard the received data in RX memory. - * @details It discards the data of the length of len(variable) bytes in internal RX memory. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param len Data length - */ -void wiz_recv_ignore(uint8_t sn, uint16_t len); - -#endif // _W5500_H_ diff --git a/drivers/wiznet5k/ethernet/w5500/w5500.c b/drivers/wiznet5k/ethernet/w5500/w5500.c deleted file mode 100644 index 3107b1b71a..0000000000 --- a/drivers/wiznet5k/ethernet/w5500/w5500.c +++ /dev/null @@ -1,247 +0,0 @@ -//***************************************************************************** -// -//! \file w5500.c -//! \brief W5500 HAL Interface. -//! \version 1.0.1 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.2 -//! 1. Implicit type casting -> Explicit type casting. Refer to M20140501 -//! Fixed the problem on porting into under 32bit MCU -//! Issued by Mathias ClauBen, wizwiki forum ID Think01 and bobh -//! Thank for your interesting and serious advices. -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.0.1 -//! 1. Remove warning -//! 2. WIZCHIP_READ_BUF WIZCHIP_WRITE_BUF in case _WIZCHIP_IO_MODE_SPI_FDM_ -//! for loop optimized(removed). refer to M20131220 -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** -//#include -#include "w5500.h" - -#define _W5500_SPI_VDM_OP_ 0x00 -#define _W5500_SPI_FDM_OP_LEN1_ 0x01 -#define _W5500_SPI_FDM_OP_LEN2_ 0x02 -#define _W5500_SPI_FDM_OP_LEN4_ 0x03 - -//////////////////////////////////////////////////// - -#define LPC_SSP0 (0) - -static void Chip_SSP_ReadFrames_Blocking(int dummy, uint8_t *buf, uint32_t len) { - WIZCHIP.IF.SPI._read_bytes(buf, len); -} - -static void Chip_SSP_WriteFrames_Blocking(int dummy, const uint8_t *buf, uint32_t len) { - WIZCHIP.IF.SPI._write_bytes(buf, len); -} - -uint8_t WIZCHIP_READ(uint32_t AddrSel) -{ - uint8_t ret; - uint8_t spi_data[3]; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_READ_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //ret = WIZCHIP.IF.SPI._read_byte(); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 3); - Chip_SSP_ReadFrames_Blocking(LPC_SSP0, &ret, 1); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); - return ret; -} - -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb ) -{ - uint8_t spi_data[4]; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_WRITE_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //WIZCHIP.IF.SPI._write_byte(wb); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - spi_data[3] = wb; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 4); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_READ_BUF (uint32_t AddrSel, uint8_t* pBuf, uint16_t len) -{ - uint8_t spi_data[3]; - //uint16_t i; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_READ_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //for(i = 0; i < len; i++) - // pBuf[i] = WIZCHIP.IF.SPI._read_byte(); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 3); - Chip_SSP_ReadFrames_Blocking(LPC_SSP0, pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len) -{ - uint8_t spi_data[3]; - //uint16_t i; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_WRITE_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //for(i = 0; i < len; i++) - // WIZCHIP.IF.SPI._write_byte(pBuf[i]); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 3); - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - - -uint16_t getSn_TX_FSR(uint8_t sn) -{ - uint16_t val=0,val1=0; - - do - { - val1 = WIZCHIP_READ(Sn_TX_FSR(sn)); - val1 = (val1 << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_FSR(sn),1)); - if (val1 != 0) - { - val = WIZCHIP_READ(Sn_TX_FSR(sn)); - val = (val << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_FSR(sn),1)); - } - }while (val != val1); - return val; -} - - -uint16_t getSn_RX_RSR(uint8_t sn) -{ - uint16_t val=0,val1=0; - - do - { - val1 = WIZCHIP_READ(Sn_RX_RSR(sn)); - val1 = (val1 << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RSR(sn),1)); - if (val1 != 0) - { - val = WIZCHIP_READ(Sn_RX_RSR(sn)); - val = (val << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RSR(sn),1)); - } - }while (val != val1); - return val; -} - -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len) -{ - uint16_t ptr = 0; - uint32_t addrsel = 0; - - if(len == 0) return; - ptr = getSn_TX_WR(sn); - //M20140501 : implict type casting -> explict type casting - //addrsel = (ptr << 8) + (WIZCHIP_TXBUF_BLOCK(sn) << 3); - addrsel = ((uint32_t)ptr << 8) + (WIZCHIP_TXBUF_BLOCK(sn) << 3); - // - WIZCHIP_WRITE_BUF(addrsel,wizdata, len); - - ptr += len; - setSn_TX_WR(sn,ptr); -} - -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len) -{ - uint16_t ptr = 0; - uint32_t addrsel = 0; - - if(len == 0) return; - ptr = getSn_RX_RD(sn); - //M20140501 : implict type casting -> explict type casting - //addrsel = ((ptr << 8) + (WIZCHIP_RXBUF_BLOCK(sn) << 3); - addrsel = ((uint32_t)ptr << 8) + (WIZCHIP_RXBUF_BLOCK(sn) << 3); - // - WIZCHIP_READ_BUF(addrsel, wizdata, len); - ptr += len; - - setSn_RX_RD(sn,ptr); -} - - -void wiz_recv_ignore(uint8_t sn, uint16_t len) -{ - uint16_t ptr = 0; - - ptr = getSn_RX_RD(sn); - ptr += len; - setSn_RX_RD(sn,ptr); -} - diff --git a/drivers/wiznet5k/ethernet/w5500/w5500.h b/drivers/wiznet5k/ethernet/w5500/w5500.h deleted file mode 100644 index c2afb180eb..0000000000 --- a/drivers/wiznet5k/ethernet/w5500/w5500.h +++ /dev/null @@ -1,2057 +0,0 @@ -//***************************************************************************** -// -//! \file w5500.h -//! \brief W5500 HAL Header File. -//! \version 1.0.0 -//! \date 2013/10/21 -//! \par Revision history -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#ifndef _W5500_H_ -#define _W5500_H_ - -#include -#include "../wizchip_conf.h" - -#define _W5500_IO_BASE_ 0x00000000 - -#define _W5500_SPI_READ_ (0x00 << 2) //< SPI interface Read operation in Control Phase -#define _W5500_SPI_WRITE_ (0x01 << 2) //< SPI interface Write operation in Control Phase - -#define WIZCHIP_CREG_BLOCK 0x00 //< Common register block -#define WIZCHIP_SREG_BLOCK(N) (1+4*N) //< Socket N register block -#define WIZCHIP_TXBUF_BLOCK(N) (2+4*N) //< Socket N Tx buffer address block -#define WIZCHIP_RXBUF_BLOCK(N) (3+4*N) //< Socket N Rx buffer address block - -#define WIZCHIP_OFFSET_INC(ADDR, N) (ADDR + (N<<8)) //< Increase offset address - - -/////////////////////////////////////// -// Definition For Legacy Chip Driver // -/////////////////////////////////////// -#define IINCHIP_READ(ADDR) WIZCHIP_READ(ADDR) ///< The defined for legacy chip driver -#define IINCHIP_WRITE(ADDR,VAL) WIZCHIP_WRITE(ADDR,VAL) ///< The defined for legacy chip driver -#define IINCHIP_READ_BUF(ADDR,BUF,LEN) WIZCHIP_READ_BUF(ADDR,BUF,LEN) ///< The defined for legacy chip driver -#define IINCHIP_WRITE_BUF(ADDR,BUF,LEN) WIZCHIP_WRITE(ADDR,BUF,LEN) ///< The defined for legacy chip driver - -////////////////////////////// -//-------------------------- defgroup --------------------------------- -/** - * @defgroup W5500 W5500 - * - * @brief WHIZCHIP register defines and I/O functions of @b W5500. - * - * - @ref WIZCHIP_register : @ref Common_register_group and @ref Socket_register_group - * - @ref WIZCHIP_IO_Functions : @ref Basic_IO_function, @ref Common_register_access_function and @ref Socket_register_access_function - */ - - -/** - * @defgroup WIZCHIP_register WIZCHIP register - * @ingroup W5500 - * - * @brief WHIZCHIP register defines register group of @b W5500. - * - * - @ref Common_register_group : Common register group - * - @ref Socket_register_group : \c SOCKET n register group - */ - - -/** - * @defgroup WIZCHIP_IO_Functions WIZCHIP I/O functions - * @ingroup W5500 - * - * @brief This supports the basic I/O functions for @ref WIZCHIP_register. - * - * - Basic I/O function \n - * WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() \n\n - * - * - @ref Common_register_group access functions \n - * -# @b Mode \n - * getMR(), setMR() - * -# @b Interrupt \n - * getIR(), setIR(), getIMR(), setIMR(), getSIR(), setSIR(), getSIMR(), setSIMR(), getINTLEVEL(), setINTLEVEL() - * -# Network Information \n - * getSHAR(), setSHAR(), getGAR(), setGAR(), getSUBR(), setSUBR(), getSIPR(), setSIPR() - * -# @b Retransmission \n - * getRCR(), setRCR(), getRTR(), setRTR() - * -# @b PPPoE \n - * getPTIMER(), setPTIMER(), getPMAGIC(), getPMAGIC(), getPSID(), setPSID(), getPHAR(), setPHAR(), getPMRU(), setPMRU() - * -# ICMP packet \n - * getUIPR(), getUPORTR() - * -# @b etc. \n - * getPHYCFGR(), setPHYCFGR(), getVERSIONR() \n\n - * - * - \ref Socket_register_group access functions \n - * -# SOCKET control \n - * getSn_MR(), setSn_MR(), getSn_CR(), setSn_CR(), getSn_IMR(), setSn_IMR(), getSn_IR(), setSn_IR() - * -# SOCKET information \n - * getSn_SR(), getSn_DHAR(), setSn_DHAR(), getSn_PORT(), setSn_PORT(), getSn_DIPR(), setSn_DIPR(), getSn_DPORT(), setSn_DPORT() - * getSn_MSSR(), setSn_MSSR() - * -# SOCKET communication \n - * getSn_RXBUF_SIZE(), setSn_RXBUF_SIZE(), getSn_TXBUF_SIZE(), setSn_TXBUF_SIZE() \n - * getSn_TX_RD(), getSn_TX_WR(), setSn_TX_WR() \n - * getSn_RX_RD(), setSn_RX_RD(), getSn_RX_WR() \n - * getSn_TX_FSR(), getSn_RX_RSR(), getSn_KPALVTR(), setSn_KPALVTR() - * -# IP header field \n - * getSn_FRAG(), setSn_FRAG(), getSn_TOS(), setSn_TOS() \n - * getSn_TTL(), setSn_TTL() - */ - - - -/** - * @defgroup Common_register_group Common register - * @ingroup WIZCHIP_register - * - * @brief Common register group\n - * It set the basic for the networking\n - * It set the configuration such as interrupt, network information, ICMP, etc. - * @details - * @sa MR : Mode register. - * @sa GAR, SUBR, SHAR, SIPR - * @sa INTLEVEL, IR, IMR, SIR, SIMR : Interrupt. - * @sa RTR, RCR : Data retransmission. - * @sa PTIMER, PMAGIC, PHAR, PSID, PMRU : PPPoE. - * @sa UIPR, UPORTR : ICMP message. - * @sa PHYCFGR, VERSIONR : etc. - */ - - - -/** - * @defgroup Socket_register_group Socket register - * @ingroup WIZCHIP_register - * - * @brief Socket register group.\n - * Socket register configures and control SOCKETn which is necessary to data communication. - * @details - * @sa Sn_MR, Sn_CR, Sn_IR, Sn_IMR : SOCKETn Control - * @sa Sn_SR, Sn_PORT, Sn_DHAR, Sn_DIPR, Sn_DPORT : SOCKETn Information - * @sa Sn_MSSR, Sn_TOS, Sn_TTL, Sn_KPALVTR, Sn_FRAG : Internet protocol. - * @sa Sn_RXBUF_SIZE, Sn_TXBUF_SIZE, Sn_TX_FSR, Sn_TX_RD, Sn_TX_WR, Sn_RX_RSR, Sn_RX_RD, Sn_RX_WR : Data communication - */ - - - - /** - * @defgroup Basic_IO_function Basic I/O function - * @ingroup WIZCHIP_IO_Functions - * @brief These are basic input/output functions to read values from register or write values to register. - */ - -/** - * @defgroup Common_register_access_function Common register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access common registers. - */ - -/** - * @defgroup Socket_register_access_function Socket register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access socket registers. - */ - -//------------------------------- defgroup end -------------------------------------------- -//----------------------------- W5500 Common Registers IOMAP ----------------------------- -/** - * @ingroup Common_register_group - * @brief Mode Register address(R/W)\n - * @ref MR is used for S/W reset, ping block mode, PPPoE mode and etc. - * @details Each bit of @ref MR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
RST Reserved WOL PB PPPoE Reserved FARP Reserved
- * - \ref MR_RST : Reset - * - \ref MR_WOL : Wake on LAN - * - \ref MR_PB : Ping block - * - \ref MR_PPPOE : PPPoE mode - * - \ref MR_FARP : Force ARP mode - */ -#define MR (_W5500_IO_BASE_ + (0x0000 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Gateway IP Register address(R/W) - * @details @ref GAR configures the default gateway address. - */ -#define GAR (_W5500_IO_BASE_ + (0x0001 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Subnet mask Register address(R/W) - * @details @ref SUBR configures the subnet mask address. - */ -#define SUBR (_W5500_IO_BASE_ + (0x0005 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Source MAC Register address(R/W) - * @details @ref SHAR configures the source hardware address. - */ -#define SHAR (_W5500_IO_BASE_ + (0x0009 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Source IP Register address(R/W) - * @details @ref SIPR configures the source IP address. - */ -#define SIPR (_W5500_IO_BASE_ + (0x000F << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Set Interrupt low level timer register address(R/W) - * @details @ref INTLEVEL configures the Interrupt Assert Time. - */ -#define INTLEVEL (_W5500_IO_BASE_ + (0x0013 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Interrupt Register(R/W) - * @details @ref IR indicates the interrupt status. Each bit of @ref IR will be still until the bit will be written to by the host. - * If @ref IR is not equal to x00 INTn PIN is asserted to low until it is x00\n\n - * Each bit of @ref IR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
CONFLICT UNREACH PPPoE MP Reserved Reserved Reserved Reserved
- * - \ref IR_CONFLICT : IP conflict - * - \ref IR_UNREACH : Destination unreachable - * - \ref IR_PPPoE : PPPoE connection close - * - \ref IR_MP : Magic packet - */ -#define IR (_W5500_IO_BASE_ + (0x0015 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Interrupt mask register(R/W) - * @details @ref IMR is used to mask interrupts. Each bit of @ref IMR corresponds to each bit of @ref IR. - * When a bit of @ref IMR is and the corresponding bit of @ref IR is an interrupt will be issued. In other words, - * if a bit of @ref IMR is an interrupt will not be issued even if the corresponding bit of @ref IR is \n\n - * Each bit of @ref IMR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
IM_IR7 IM_IR6 IM_IR5 IM_IR4 Reserved Reserved Reserved Reserved
- * - \ref IM_IR7 : IP Conflict Interrupt Mask - * - \ref IM_IR6 : Destination unreachable Interrupt Mask - * - \ref IM_IR5 : PPPoE Close Interrupt Mask - * - \ref IM_IR4 : Magic Packet Interrupt Mask - */ -#define IMR (_W5500_IO_BASE_ + (0x0016 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Register(R/W) - * @details @ref SIR indicates the interrupt status of Socket.\n - * Each bit of @ref SIR be still until @ref Sn_IR is cleared by the host.\n - * If @ref Sn_IR is not equal to x00 the n-th bit of @ref SIR is and INTn PIN is asserted until @ref SIR is x00 */ -#define SIR (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Mask Register(R/W) - * @details Each bit of @ref SIMR corresponds to each bit of @ref SIR. - * When a bit of @ref SIMR is and the corresponding bit of @ref SIR is Interrupt will be issued. - * In other words, if a bit of @ref SIMR is an interrupt will be not issued even if the corresponding bit of @ref SIR is - */ -#define SIMR (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Timeout register address( 1 is 100us )(R/W) - * @details @ref RTR configures the retransmission timeout period. The unit of timeout period is 100us and the default of @ref RTR is x07D0or 000 - * And so the default timeout period is 200ms(100us X 2000). During the time configured by @ref RTR, W5500 waits for the peer response - * to the packet that is transmitted by \ref Sn_CR (CONNECT, DISCON, CLOSE, SEND, SEND_MAC, SEND_KEEP command). - * If the peer does not respond within the @ref RTR time, W5500 retransmits the packet or issues timeout. - */ -#define RTR (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Retry count register(R/W) - * @details @ref RCR configures the number of time of retransmission. - * When retransmission occurs as many as ref RCR+1 Timeout interrupt is issued (@ref Sn_IR[TIMEOUT] = . - */ -#define RCR (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Request Timer register in PPPoE mode(R/W) - * @details @ref PTIMER configures the time for sending LCP echo request. The unit of time is 25ms. - */ -#define PTIMER (_W5500_IO_BASE_ + (0x001C << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Magic number register in PPPoE mode(R/W) - * @details @ref PMAGIC configures the 4bytes magic number to be used in LCP negotiation. - */ -#define PMAGIC (_W5500_IO_BASE_ + (0x001D << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Destination MAC Register address(R/W) - * @details @ref PHAR configures the PPPoE server hardware address that is acquired during PPPoE connection process. - */ -#define PHAR (_W5500_IO_BASE_ + (0x001E << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Session Identification Register(R/W) - * @details @ref PSID configures the PPPoE sever session ID acquired during PPPoE connection process. - */ -#define PSID (_W5500_IO_BASE_ + (0x0024 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Maximum Segment Size(MSS) register(R/W) - * @details @ref PMRU configures the maximum receive unit of PPPoE. - */ -#define PMRU (_W5500_IO_BASE_ + (0x0026 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable IP register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR indicates - * the destination IP address & port number respectively. - */ -#define UIPR (_W5500_IO_BASE_ + (0x0028 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable Port register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR - * indicates the destination IP address & port number respectively. - */ -#define UPORTR (_W5500_IO_BASE_ + (0x002C << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PHY Status Register(R/W) - * @details @ref PHYCFGR configures PHY operation mode and resets PHY. In addition, @ref PHYCFGR indicates the status of PHY such as duplex, Speed, Link. - */ -#define PHYCFGR (_W5500_IO_BASE_ + (0x002E << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -// Reserved (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0031 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0032 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0033 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0034 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0035 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0036 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0037 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0038 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief chip version register address(R) - * @details @ref VERSIONR always indicates the W5500 version as @b 0x04. - */ -#define VERSIONR (_W5500_IO_BASE_ + (0x0039 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - - -//----------------------------- W5500 Socket Registers IOMAP ----------------------------- -/** - * @ingroup Socket_register_group - * @brief socket Mode register(R/W) - * @details @ref Sn_MR configures the option or protocol type of Socket n.\n\n - * Each bit of @ref Sn_MR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
MULTI/MFEN BCASTB ND/MC/MMB UCASTB/MIP6B Protocol[3] Protocol[2] Protocol[1] Protocol[0]
- * - @ref Sn_MR_MULTI : Support UDP Multicasting - * - @ref Sn_MR_BCASTB : Broadcast block in UDP Multicasting - * - @ref Sn_MR_ND : No Delayed Ack(TCP) flag - * - @ref Sn_MR_MC : IGMP version used in UDP mulitcasting - * - @ref Sn_MR_MMB : Multicast Blocking in @ref Sn_MR_MACRAW mode - * - @ref Sn_MR_UCASTB : Unicast Block in UDP Multicating - * - @ref Sn_MR_MIP6B : IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * - Protocol - * - * - * - * - * - * - *
Protocol[3] Protocol[2] Protocol[1] Protocol[0] @b Meaning
0 0 0 0 Closed
0 0 0 1 TCP
0 0 1 0 UDP
0 1 0 0 MACRAW
- * - @ref Sn_MR_MACRAW : MAC LAYER RAW SOCK \n - * - @ref Sn_MR_UDP : UDP - * - @ref Sn_MR_TCP : TCP - * - @ref Sn_MR_CLOSE : Unused socket - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR(N) (_W5500_IO_BASE_ + (0x0000 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Socket command register(R/W) - * @details This is used to set the command for Socket n such as OPEN, CLOSE, CONNECT, LISTEN, SEND, and RECEIVE.\n - * After W5500 accepts the command, the @ref Sn_CR register is automatically cleared to 0x00. - * Even though @ref Sn_CR is cleared to 0x00, the command is still being processed.\n - * To check whether the command is completed or not, please check the @ref Sn_IR or @ref Sn_SR. - * - @ref Sn_CR_OPEN : Initialize or open socket. - * - @ref Sn_CR_LISTEN : Wait connection request in TCP mode(Server mode) - * - @ref Sn_CR_CONNECT : Send connection request in TCP mode(Client mode) - * - @ref Sn_CR_DISCON : Send closing request in TCP mode. - * - @ref Sn_CR_CLOSE : Close socket. - * - @ref Sn_CR_SEND : Update TX buffer pointer and send data. - * - @ref Sn_CR_SEND_MAC : Send data with MAC address, so without ARP process. - * - @ref Sn_CR_SEND_KEEP : Send keep alive message. - * - @ref Sn_CR_RECV : Update RX buffer pointer and receive data. - */ -#define Sn_CR(N) (_W5500_IO_BASE_ + (0x0001 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Socket interrupt register(R) - * @details @ref Sn_IR indicates the status of Socket Interrupt such as establishment, termination, receiving data, timeout).\n - * When an interrupt occurs and the corresponding bit of @ref Sn_IMR is the corresponding bit of @ref Sn_IR becomes \n - * In order to clear the @ref Sn_IR bit, the host should write the bit to \n - * - * - * - *
7 6 5 4 3 2 1 0
Reserved Reserved Reserved SEND_OK TIMEOUT RECV DISCON CON
- * - \ref Sn_IR_SENDOK : SEND_OK Interrupt - * - \ref Sn_IR_TIMEOUT : TIMEOUT Interrupt - * - \ref Sn_IR_RECV : RECV Interrupt - * - \ref Sn_IR_DISCON : DISCON Interrupt - * - \ref Sn_IR_CON : CON Interrupt - */ -#define Sn_IR(N) (_W5500_IO_BASE_ + (0x0002 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Socket status register(R) - * @details @ref Sn_SR indicates the status of Socket n.\n - * The status of Socket n is changed by @ref Sn_CR or some special control packet as SYN, FIN packet in TCP. - * @par Normal status - * - @ref SOCK_CLOSED : Closed - * - @ref SOCK_INIT : Initiate state - * - @ref SOCK_LISTEN : Listen state - * - @ref SOCK_ESTABLISHED : Success to connect - * - @ref SOCK_CLOSE_WAIT : Closing state - * - @ref SOCK_UDP : UDP socket - * - @ref SOCK_MACRAW : MAC raw mode socket - *@par Temporary status during changing the status of Socket n. - * - @ref SOCK_SYNSENT : This indicates Socket n sent the connect-request packet (SYN packet) to a peer. - * - @ref SOCK_SYNRECV : It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer. - * - @ref SOCK_FIN_WAIT : Connection state - * - @ref SOCK_CLOSING : Closing state - * - @ref SOCK_TIME_WAIT : Closing state - * - @ref SOCK_LAST_ACK : Closing state - */ -#define Sn_SR(N) (_W5500_IO_BASE_ + (0x0003 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief source port register(R/W) - * @details @ref Sn_PORT configures the source port number of Socket n. - * It is valid when Socket n is used in TCP/UPD mode. It should be set before OPEN command is ordered. - */ -#define Sn_PORT(N) (_W5500_IO_BASE_ + (0x0004 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Peer MAC register address(R/W) - * @details @ref Sn_DHAR configures the destination hardware address of Socket n when using SEND_MAC command in UDP mode or - * it indicates that it is acquired in ARP-process by CONNECT/SEND command. - */ -#define Sn_DHAR(N) (_W5500_IO_BASE_ + (0x0006 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Peer IP register address(R/W) - * @details @ref Sn_DIPR configures or indicates the destination IP address of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In TCP client mode, it configures an IP address of �TCP serverbefore CONNECT command. - * In TCP server mode, it indicates an IP address of �TCP clientafter successfully establishing connection. - * In UDP mode, it configures an IP address of peer to be received the UDP packet by SEND or SEND_MAC command. - */ -#define Sn_DIPR(N) (_W5500_IO_BASE_ + (0x000C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Peer port register address(R/W) - * @details @ref Sn_DPORT configures or indicates the destination port number of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In �TCP clientmode, it configures the listen port number of �TCP serverbefore CONNECT command. - * In �TCP Servermode, it indicates the port number of TCP client after successfully establishing connection. - * In UDP mode, it configures the port number of peer to be transmitted the UDP packet by SEND/SEND_MAC command. - */ -#define Sn_DPORT(N) (_W5500_IO_BASE_ + (0x0010 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Maximum Segment Size(Sn_MSSR0) register address(R/W) - * @details @ref Sn_MSSR configures or indicates the MTU(Maximum Transfer Unit) of Socket n. - */ -#define Sn_MSSR(N) (_W5500_IO_BASE_ + (0x0012 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -// Reserved (_W5500_IO_BASE_ + (0x0014 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief IP Type of Service(TOS) Register(R/W) - * @details @ref Sn_TOS configures the TOS(Type Of Service field in IP Header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TOS(N) (_W5500_IO_BASE_ + (0x0015 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -/** - * @ingroup Socket_register_group - * @brief IP Time to live(TTL) Register(R/W) - * @details @ref Sn_TTL configures the TTL(Time To Live field in IP header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TTL(N) (_W5500_IO_BASE_ + (0x0016 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001A << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Receive memory size register(R/W) - * @details @ref Sn_RXBUF_SIZE configures the RX buffer block size of Socket n. - * Socket n RX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data cannot be normally received from a peer. - * Although Socket n RX Buffer Block size is initially configured to 2Kbytes, - * user can re-configure its size using @ref Sn_RXBUF_SIZE. The total sum of @ref Sn_RXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data reception error is occurred. - */ -#define Sn_RXBUF_SIZE(N) (_W5500_IO_BASE_ + (0x001E << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory size register(R/W) - * @details @ref Sn_TXBUF_SIZE configures the TX buffer block size of Socket n. Socket n TX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data can�t be normally transmitted to a peer. - * Although Socket n TX Buffer Block size is initially configured to 2Kbytes, - * user can be re-configure its size using @ref Sn_TXBUF_SIZE. The total sum of @ref Sn_TXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data transmission error is occurred. - */ -#define Sn_TXBUF_SIZE(N) (_W5500_IO_BASE_ + (0x001F << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit free memory size register(R) - * @details @ref Sn_TX_FSR indicates the free size of Socket n TX Buffer Block. It is initialized to the configured size by @ref Sn_TXBUF_SIZE. - * Data bigger than @ref Sn_TX_FSR should not be saved in the Socket n TX Buffer because the bigger data overwrites the previous saved data not yet sent. - * Therefore, check before saving the data to the Socket n TX Buffer, and if data is equal or smaller than its checked size, - * transmit the data with SEND/SEND_MAC command after saving the data in Socket n TX buffer. But, if data is bigger than its checked size, - * transmit the data after dividing into the checked size and saving in the Socket n TX buffer. - */ -#define Sn_TX_FSR(N) (_W5500_IO_BASE_ + (0x0020 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory read pointer register address(R) - * @details @ref Sn_TX_RD is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP. - * After its initialization, it is auto-increased by SEND command. - * SEND command transmits the saved data from the current @ref Sn_TX_RD to the @ref Sn_TX_WR in the Socket n TX Buffer. - * After transmitting the saved data, the SEND command increases the @ref Sn_TX_RD as same as the @ref Sn_TX_WR. - * If its increment value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_TX_RD(N) (_W5500_IO_BASE_ + (0x0022 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory write pointer register address(R/W) - * @details @ref Sn_TX_WR is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP.\n - * It should be read or be updated like as follows.\n - * 1. Read the starting address for saving the transmitting data.\n - * 2. Save the transmitting data from the starting address of Socket n TX buffer.\n - * 3. After saving the transmitting data, update @ref Sn_TX_WR to the increased value as many as transmitting data size. - * If the increment value exceeds the maximum value 0xFFFF(greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value.\n - * 4. Transmit the saved data in Socket n TX Buffer by using SEND/SEND command - */ -#define Sn_TX_WR(N) (_W5500_IO_BASE_ + (0x0024 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Received data size register(R) - * @details @ref Sn_RX_RSR indicates the data size received and saved in Socket n RX Buffer. - * @ref Sn_RX_RSR does not exceed the @ref Sn_RXBUF_SIZE and is calculated as the difference between - * �Socket n RX Write Pointer (@ref Sn_RX_WR)and �Socket n RX Read Pointer (@ref Sn_RX_RD) - */ -#define Sn_RX_RSR(N) (_W5500_IO_BASE_ + (0x0026 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Read point of Receive memory(R/W) - * @details @ref Sn_RX_RD is initialized by OPEN command. Make sure to be read or updated as follows.\n - * 1. Read the starting save address of the received data.\n - * 2. Read data from the starting address of Socket n RX Buffer.\n - * 3. After reading the received data, Update @ref Sn_RX_RD to the increased value as many as the reading size. - * If the increment value exceeds the maximum value 0xFFFF, that is, is greater than 0x10000 and the carry bit occurs, - * update with the lower 16bits value ignored the carry bit.\n - * 4. Order RECV command is for notifying the updated @ref Sn_RX_RD to W5500. - */ -#define Sn_RX_RD(N) (_W5500_IO_BASE_ + (0x0028 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Write point of Receive memory(R) - * @details @ref Sn_RX_WR is initialized by OPEN command and it is auto-increased by the data reception. - * If the increased value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_RX_WR(N) (_W5500_IO_BASE_ + (0x002A << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief socket interrupt mask register(R) - * @details @ref Sn_IMR masks the interrupt of Socket n. - * Each bit corresponds to each bit of @ref Sn_IR. When a Socket n Interrupt is occurred and the corresponding bit of @ref Sn_IMR is - * the corresponding bit of @ref Sn_IR becomes When both the corresponding bit of @ref Sn_IMR and @ref Sn_IR are and the n-th bit of @ref IR is - * Host is interrupted by asserted INTn PIN to low. - */ -#define Sn_IMR(N) (_W5500_IO_BASE_ + (0x002C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Fragment field value in IP header register(R/W) - * @details @ref Sn_FRAG configures the FRAG(Fragment field in IP header). - */ -#define Sn_FRAG(N) (_W5500_IO_BASE_ + (0x002D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Keep Alive Timer register(R/W) - * @details @ref Sn_KPALVTR configures the transmitting timer of �KEEP ALIVE(KA)packet of SOCKETn. It is valid only in TCP mode, - * and ignored in other modes. The time unit is 5s. - * KA packet is transmittable after @ref Sn_SR is changed to SOCK_ESTABLISHED and after the data is transmitted or received to/from a peer at least once. - * In case of '@ref Sn_KPALVTR > 0', W5500 automatically transmits KA packet after time-period for checking the TCP connection (Auto-keepalive-process). - * In case of '@ref Sn_KPALVTR = 0', Auto-keep-alive-process will not operate, - * and KA packet can be transmitted by SEND_KEEP command by the host (Manual-keep-alive-process). - * Manual-keep-alive-process is ignored in case of '@ref Sn_KPALVTR > 0'. - */ -#define Sn_KPALVTR(N) (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -//#define Sn_TSR(N) (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - - -//----------------------------- W5500 Register values ----------------------------- - -/* MODE register values */ -/** - * @brief Reset - * @details If this bit is All internal registers will be initialized. It will be automatically cleared as after S/W reset. - */ -#define MR_RST 0x80 - -/** - * @brief Wake on LAN - * @details 0 : Disable WOL mode\n - * 1 : Enable WOL mode\n - * If WOL mode is enabled and the received magic packet over UDP has been normally processed, the Interrupt PIN (INTn) asserts to low. - * When using WOL mode, the UDP Socket should be opened with any source port number. (Refer to Socket n Mode Register (@ref Sn_MR) for opening Socket.) - * @note The magic packet over UDP supported by W5500 consists of 6 bytes synchronization stream (xFFFFFFFFFFFF and - * 16 times Target MAC address stream in UDP payload. The options such like password are ignored. You can use any UDP source port number for WOL mode. - */ -#define MR_WOL 0x20 - -/** - * @brief Ping block - * @details 0 : Disable Ping block\n - * 1 : Enable Ping block\n - * If the bit is it blocks the response to a ping request. - */ -#define MR_PB 0x10 - -/** - * @brief Enable PPPoE - * @details 0 : DisablePPPoE mode\n - * 1 : EnablePPPoE mode\n - * If you use ADSL, this bit should be - */ -#define MR_PPPOE 0x08 - -/** - * @brief Enable UDP_FORCE_ARP CHECHK - * @details 0 : Disable Force ARP mode\n - * 1 : Enable Force ARP mode\n - * In Force ARP mode, It forces on sending ARP Request whenever data is sent. - */ -#define MR_FARP 0x02 - -/* IR register values */ -/** - * @brief Check IP conflict. - * @details Bit is set as when own source IP address is same with the sender IP address in the received ARP request. - */ -#define IR_CONFLICT 0x80 - -/** - * @brief Get the destination unreachable message in UDP sending. - * @details When receiving the ICMP (Destination port unreachable) packet, this bit is set as - * When this bit is Destination Information such as IP address and Port number may be checked with the corresponding @ref UIPR & @ref UPORTR. - */ -#define IR_UNREACH 0x40 - -/** - * @brief Get the PPPoE close message. - * @details When PPPoE is disconnected during PPPoE mode, this bit is set. - */ -#define IR_PPPoE 0x20 - -/** - * @brief Get the magic packet interrupt. - * @details When WOL mode is enabled and receives the magic packet over UDP, this bit is set. - */ -#define IR_MP 0x10 - - -/* PHYCFGR register value */ -#define PHYCFGR_RST ~(1<<7) //< For PHY reset, must operate AND mask. -#define PHYCFGR_OPMD (1<<6) // Configre PHY with OPMDC value -#define PHYCFGR_OPMDC_ALLA (7<<3) -#define PHYCFGR_OPMDC_PDOWN (6<<3) -#define PHYCFGR_OPMDC_NA (5<<3) -#define PHYCFGR_OPMDC_100FA (4<<3) -#define PHYCFGR_OPMDC_100F (3<<3) -#define PHYCFGR_OPMDC_100H (2<<3) -#define PHYCFGR_OPMDC_10F (1<<3) -#define PHYCFGR_OPMDC_10H (0<<3) -#define PHYCFGR_DPX_FULL (1<<2) -#define PHYCFGR_DPX_HALF (0<<2) -#define PHYCFGR_SPD_100 (1<<1) -#define PHYCFGR_SPD_10 (0<<1) -#define PHYCFGR_LNK_ON (1<<0) -#define PHYCFGR_LNK_OFF (0<<0) - -/* IMR register values */ -/** - * @brief IP Conflict Interrupt Mask. - * @details 0: Disable IP Conflict Interrupt\n - * 1: Enable IP Conflict Interrupt - */ -#define IM_IR7 0x80 - -/** - * @brief Destination unreachable Interrupt Mask. - * @details 0: Disable Destination unreachable Interrupt\n - * 1: Enable Destination unreachable Interrupt - */ -#define IM_IR6 0x40 - -/** - * @brief PPPoE Close Interrupt Mask. - * @details 0: Disable PPPoE Close Interrupt\n - * 1: Enable PPPoE Close Interrupt - */ -#define IM_IR5 0x20 - -/** - * @brief Magic Packet Interrupt Mask. - * @details 0: Disable Magic Packet Interrupt\n - * 1: Enable Magic Packet Interrupt - */ -#define IM_IR4 0x10 - -/* Sn_MR Default values */ -/** - * @brief Support UDP Multicasting - * @details 0 : disable Multicasting\n - * 1 : enable Multicasting\n - * This bit is applied only during UDP mode(P[3:0] = 010.\n - * To use multicasting, @ref Sn_DIPR & @ref Sn_DPORT should be respectively configured with the multicast group IP address & port number - * before Socket n is opened by OPEN command of @ref Sn_CR. - */ -#define Sn_MR_MULTI 0x80 - -/** - * @brief Broadcast block in UDP Multicasting. - * @details 0 : disable Broadcast Blocking\n - * 1 : enable Broadcast Blocking\n - * This bit blocks to receive broadcasting packet during UDP mode(P[3:0] = 010.\m - * In addition, This bit does when MACRAW mode(P[3:0] = 100 - */ -#define Sn_MR_BCASTB 0x40 - -/** - * @brief No Delayed Ack(TCP), Multicast flag - * @details 0 : Disable No Delayed ACK option\n - * 1 : Enable No Delayed ACK option\n - * This bit is applied only during TCP mode (P[3:0] = 001.\n - * When this bit is It sends the ACK packet without delay as soon as a Data packet is received from a peer.\n - * When this bit is It sends the ACK packet after waiting for the timeout time configured by @ref RTR. - */ -#define Sn_MR_ND 0x20 - -/** - * @brief Unicast Block in UDP Multicasting - * @details 0 : disable Unicast Blocking\n - * 1 : enable Unicast Blocking\n - * This bit blocks receiving the unicast packet during UDP mode(P[3:0] = 010 and MULTI = - */ -#define Sn_MR_UCASTB 0x10 - -/** - * @brief MAC LAYER RAW SOCK - * @details This configures the protocol mode of Socket n. - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR_MACRAW 0x04 - -//#define Sn_MR_IPRAW 0x03 /**< IP LAYER RAW SOCK */ - -/** - * @brief UDP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_UDP 0x02 - -/** - * @brief TCP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_TCP 0x01 - -/** - * @brief Unused socket - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_CLOSE 0x00 - -/* Sn_MR values used with Sn_MR_MACRAW */ -/** - * @brief MAC filter enable in @ref Sn_MR_MACRAW mode - * @details 0 : disable MAC Filtering\n - * 1 : enable MAC Filtering\n - * This bit is applied only during MACRAW mode(P[3:0] = 100.\n - * When set as W5500 can only receive broadcasting packet or packet sent to itself. - * When this bit is W5500 can receive all packets on Ethernet. - * If user wants to implement Hybrid TCP/IP stack, - * it is recommended that this bit is set as for reducing host overhead to process the all received packets. - */ -#define Sn_MR_MFEN Sn_MR_MULTI - -/** - * @brief Multicast Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : using IGMP version 2\n - * 1 : using IGMP version 1\n - * This bit is applied only during UDP mode(P[3:0] = 010 and MULTI = - * It configures the version for IGMP messages (Join/Leave/Report). - */ -#define Sn_MR_MMB Sn_MR_ND - -/** - * @brief IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : disable IPv6 Blocking\n - * 1 : enable IPv6 Blocking\n - * This bit is applied only during MACRAW mode (P[3:0] = 100. It blocks to receiving the IPv6 packet. - */ -#define Sn_MR_MIP6B Sn_MR_UCASTB - -/* Sn_MR value used with Sn_MR_UDP & Sn_MR_MULTI */ -/** - * @brief IGMP version used in UDP mulitcasting - * @details 0 : disable Multicast Blocking\n - * 1 : enable Multicast Blocking\n - * This bit is applied only when MACRAW mode(P[3:0] = 100. It blocks to receive the packet with multicast MAC address. - */ -#define Sn_MR_MC Sn_MR_ND - -/* Sn_MR alternate values */ -/** - * @brief For Berkeley Socket API - */ -#define SOCK_STREAM Sn_MR_TCP - -/** - * @brief For Berkeley Socket API - */ -#define SOCK_DGRAM Sn_MR_UDP - - -/* Sn_CR values */ -/** - * @brief Initialize or open socket - * @details Socket n is initialized and opened according to the protocol selected in Sn_MR(P3:P0). - * The table below shows the value of @ref Sn_SR corresponding to @ref Sn_MR.\n - * - * - * - * - * - * - *
\b Sn_MR (P[3:0]) \b Sn_SR
Sn_MR_CLOSE (000
Sn_MR_TCP (001 SOCK_INIT (0x13)
Sn_MR_UDP (010 SOCK_UDP (0x22)
S0_MR_MACRAW (100 SOCK_MACRAW (0x02)
- */ -#define Sn_CR_OPEN 0x01 - -/** - * @brief Wait connection request in TCP mode(Server mode) - * @details This is valid only in TCP mode (Sn_MR(P3:P0) = Sn_MR_TCP). - * In this mode, Socket n operates as a �TCP serverand waits for connection-request (SYN packet) from any �TCP client - * The @ref Sn_SR changes the state from SOCK_INIT to SOCKET_LISTEN. - * When a �TCP clientconnection request is successfully established, - * the @ref Sn_SR changes from SOCK_LISTEN to SOCK_ESTABLISHED and the Sn_IR(0) becomes - * But when a �TCP clientconnection request is failed, Sn_IR(3) becomes and the status of @ref Sn_SR changes to SOCK_CLOSED. - */ -#define Sn_CR_LISTEN 0x02 - -/** - * @brief Send connection request in TCP mode(Client mode) - * @details To connect, a connect-request (SYN packet) is sent to b>TCP serverconfigured by @ref Sn_DIPR & Sn_DPORT(destination address & port). - * If the connect-request is successful, the @ref Sn_SR is changed to @ref SOCK_ESTABLISHED and the Sn_IR(0) becomes \n\n - * The connect-request fails in the following three cases.\n - * 1. When a @b ARPTO occurs (@ref Sn_IR[3] = ) because destination hardware address is not acquired through the ARP-process.\n - * 2. When a @b SYN/ACK packet is not received and @b TCPTO (Sn_IR(3) = )\n - * 3. When a @b RST packet is received instead of a @b SYN/ACK packet. In these cases, @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note This is valid only in TCP mode and operates when Socket n acts as b>TCP client - */ -#define Sn_CR_CONNECT 0x04 - -/** - * @brief Send closing request in TCP mode - * @details Regardless of b>TCP serveror b>TCP client the DISCON command processes the disconnect-process (b>Active closeor b>Passive close.\n - * @par Active close - * it transmits disconnect-request(FIN packet) to the connected peer\n - * @par Passive close - * When FIN packet is received from peer, a FIN packet is replied back to the peer.\n - * @details When the disconnect-process is successful (that is, FIN/ACK packet is received successfully), @ref Sn_SR is changed to @ref SOCK_CLOSED.\n - * Otherwise, TCPTO occurs (Sn_IR(3)=)= and then @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note Valid only in TCP mode. - */ -#define Sn_CR_DISCON 0x08 - -/** - * @brief Close socket - * @details Sn_SR is changed to @ref SOCK_CLOSED. - */ -#define Sn_CR_CLOSE 0x10 - -/** - * @brief Update TX buffer pointer and send data - * @details SEND transmits all the data in the Socket n TX buffer.\n - * For more details, please refer to Socket n TX Free Size Register (@ref Sn_TX_FSR), Socket n, - * TX Write Pointer Register(@ref Sn_TX_WR), and Socket n TX Read Pointer Register(@ref Sn_TX_RD). - */ -#define Sn_CR_SEND 0x20 - -/** - * @brief Send data with MAC address, so without ARP process - * @details The basic operation is same as SEND.\n - * Normally SEND transmits data after destination hardware address is acquired by the automatic ARP-process(Address Resolution Protocol).\n - * But SEND_MAC transmits data without the automatic ARP-process.\n - * In this case, the destination hardware address is acquired from @ref Sn_DHAR configured by host, instead of APR-process. - * @note Valid only in UDP mode. - */ -#define Sn_CR_SEND_MAC 0x21 - -/** - * @brief Send keep alive message - * @details It checks the connection status by sending 1byte keep-alive packet.\n - * If the peer can not respond to the keep-alive packet during timeout time, the connection is terminated and the timeout interrupt will occur. - * @note Valid only in TCP mode. - */ -#define Sn_CR_SEND_KEEP 0x22 - -/** - * @brief Update RX buffer pointer and receive data - * @details RECV completes the processing of the received data in Socket n RX Buffer by using a RX read pointer register (@ref Sn_RX_RD).\n - * For more details, refer to Socket n RX Received Size Register (@ref Sn_RX_RSR), Socket n RX Write Pointer Register (@ref Sn_RX_WR), - * and Socket n RX Read Pointer Register (@ref Sn_RX_RD). - */ -#define Sn_CR_RECV 0x40 - -/* Sn_IR values */ -/** - * @brief SEND_OK Interrupt - * @details This is issued when SEND command is completed. - */ -#define Sn_IR_SENDOK 0x10 - -/** - * @brief TIMEOUT Interrupt - * @details This is issued when ARPTO or TCPTO occurs. - */ -#define Sn_IR_TIMEOUT 0x08 - -/** - * @brief RECV Interrupt - * @details This is issued whenever data is received from a peer. - */ -#define Sn_IR_RECV 0x04 - -/** - * @brief DISCON Interrupt - * @details This is issued when FIN or FIN/ACK packet is received from a peer. - */ -#define Sn_IR_DISCON 0x02 - -/** - * @brief CON Interrupt - * @details This is issued one time when the connection with peer is successful and then @ref Sn_SR is changed to @ref SOCK_ESTABLISHED. - */ -#define Sn_IR_CON 0x01 - -/* Sn_SR values */ -/** - * @brief Closed - * @details This indicates that Socket n is released.\N - * When DICON, CLOSE command is ordered, or when a timeout occurs, it is changed to @ref SOCK_CLOSED regardless of previous status. - */ -#define SOCK_CLOSED 0x00 - -/** - * @brief Initiate state - * @details This indicates Socket n is opened with TCP mode.\N - * It is changed to @ref SOCK_INIT when Sn_MR(P[3:0]) = 001and OPEN command is ordered.\N - * After @ref SOCK_INIT, user can use LISTEN /CONNECT command. - */ -#define SOCK_INIT 0x13 - -/** - * @brief Listen state - * @details This indicates Socket n is operating as b>TCP servermode and waiting for connection-request (SYN packet) from a peer (b>TCP client.\n - * It will change to @ref SOCK_ESTALBLISHED when the connection-request is successfully accepted.\n - * Otherwise it will change to @ref SOCK_CLOSED after TCPTO occurred (Sn_IR(TIMEOUT) = . - */ -#define SOCK_LISTEN 0x14 - -/** - * @brief Connection state - * @details This indicates Socket n sent the connect-request packet (SYN packet) to a peer.\n - * It is temporarily shown when @ref Sn_SR is changed from @ref SOCK_INIT to @ref SOCK_ESTABLISHED by CONNECT command.\n - * If connect-accept(SYN/ACK packet) is received from the peer at SOCK_SYNSENT, it changes to @ref SOCK_ESTABLISHED.\n - * Otherwise, it changes to @ref SOCK_CLOSED after TCPTO (@ref Sn_IR[TIMEOUT] = is occurred. - */ -#define SOCK_SYNSENT 0x15 - -/** - * @brief Connection state - * @details It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer.\n - * If socket n sends the response (SYN/ACK packet) to the peer successfully, it changes to @ref SOCK_ESTABLISHED. \n - * If not, it changes to @ref SOCK_CLOSED after timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_SYNRECV 0x16 - -/** - * @brief Success to connect - * @details This indicates the status of the connection of Socket n.\n - * It changes to @ref SOCK_ESTABLISHED when the b>TCP SERVERprocessed the SYN packet from the b>TCP CLIENTduring @ref SOCK_LISTEN, or - * when the CONNECT command is successful.\n - * During @ref SOCK_ESTABLISHED, DATA packet can be transferred using SEND or RECV command. - */ -#define SOCK_ESTABLISHED 0x17 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_FIN_WAIT 0x18 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_CLOSING 0x1A - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_TIME_WAIT 0x1B - -/** - * @brief Closing state - * @details This indicates Socket n received the disconnect-request (FIN packet) from the connected peer.\n - * This is half-closing status, and data can be transferred.\n - * For full-closing, DISCON command is used. But For just-closing, CLOSE command is used. - */ -#define SOCK_CLOSE_WAIT 0x1C - -/** - * @brief Closing state - * @details This indicates Socket n is waiting for the response (FIN/ACK packet) to the disconnect-request (FIN packet) by passive-close.\n - * It changes to @ref SOCK_CLOSED when Socket n received the response successfully, or when timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_LAST_ACK 0x1D - -/** - * @brief UDP socket - * @details This indicates Socket n is opened in UDP mode(Sn_MR(P[3:0]) = 010.\n - * It changes to SOCK_UPD when Sn_MR(P[3:0]) = 010 and OPEN command is ordered.\n - * Unlike TCP mode, data can be transfered without the connection-process. - */ -#define SOCK_UDP 0x22 - -//#define SOCK_IPRAW 0x32 /**< IP raw mode socket */ - -/** - * @brief MAC raw mode socket - * @details This indicates Socket 0 is opened in MACRAW mode (S0_MR(P[3:0]) = 100and is valid only in Socket 0.\n - * It changes to SOCK_MACRAW when S0_MR(P[3:0] = 100and OPEN command is ordered.\n - * Like UDP mode socket, MACRAW mode Socket 0 can transfer a MAC packet (Ethernet frame) without the connection-process. - */ -#define SOCK_MACRAW 0x42 - -//#define SOCK_PPPOE 0x5F - -/* IP PROTOCOL */ -#define IPPROTO_IP 0 //< Dummy for IP -#define IPPROTO_ICMP 1 //< Control message protocol -#define IPPROTO_IGMP 2 //< Internet group management protocol -#define IPPROTO_GGP 3 //< Gateway^2 (deprecated) -#define IPPROTO_TCP 6 //< TCP -#define IPPROTO_PUP 12 //< PUP -#define IPPROTO_UDP 17 //< UDP -#define IPPROTO_IDP 22 //< XNS idp -#define IPPROTO_ND 77 //< UNOFFICIAL net disk protocol -#define IPPROTO_RAW 255 //< Raw IP packet - - -/** - * @brief Enter a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n \n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt.\n - * In OS environment, You can replace it to critical section api supported by OS. - * - * \sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * \sa WIZCHIP_CRITICAL_EXIT() - */ -#define WIZCHIP_CRITICAL_ENTER() WIZCHIP.CRIS._enter() - -/** - * @brief Exit a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n\n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt. \n - * In OS environment, You can replace it to critical section api supported by OS. - * - * @sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * @sa WIZCHIP_CRITICAL_ENTER() - */ -#ifdef _exit -#undef _exit -#endif -#define WIZCHIP_CRITICAL_EXIT() WIZCHIP.CRIS._exit() - - - -//////////////////////// -// Basic I/O Function // -//////////////////////// - -/** - * @ingroup Basic_IO_function - * @brief It reads 1 byte value from a register. - * @param AddrSel Register address - * @return The value of register - */ -uint8_t WIZCHIP_READ (uint32_t AddrSel); - -/** - * @ingroup Basic_IO_function - * @brief It writes 1 byte value to a register. - * @param AddrSel Register address - * @param wb Write data - * @return void - */ -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb ); - -/** - * @ingroup Basic_IO_function - * @brief It reads sequence data from registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to read data - * @param len Data length - */ -void WIZCHIP_READ_BUF (uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It writes sequence data to registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to write data - * @param len Data length - */ -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -///////////////////////////////// -// Common Register I/O function // -///////////////////////////////// -/** - * @ingroup Common_register_access_function - * @brief Set Mode Register - * @param (uint8_t)mr The value to be set. - * @sa getMR() - */ -#define setMR(mr) \ - WIZCHIP_WRITE(MR,mr) - - -/** - * @ingroup Common_register_access_function - * @brief Get Mode Register - * @return uint8_t. The value of Mode register. - * @sa setMR() - */ -#define getMR() \ - WIZCHIP_READ(MR) - -/** - * @ingroup Common_register_access_function - * @brief Set gateway IP address - * @param (uint8_t*)gar Pointer variable to set gateway IP address. It should be allocated 4 bytes. - * @sa getGAR() - */ -#define setGAR(gar) \ - WIZCHIP_WRITE_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Get gateway IP address - * @param (uint8_t*)gar Pointer variable to get gateway IP address. It should be allocated 4 bytes. - * @sa setGAR() - */ -#define getGAR(gar) \ - WIZCHIP_READ_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Set subnet mask address - * @param (uint8_t*)subr Pointer variable to set subnet mask address. It should be allocated 4 bytes. - * @sa getSUBR() - */ -#define setSUBR(subr) \ - WIZCHIP_WRITE_BUF(SUBR, subr,4) - - -/** - * @ingroup Common_register_access_function - * @brief Get subnet mask address - * @param (uint8_t*)subr Pointer variable to get subnet mask address. It should be allocated 4 bytes. - * @sa setSUBR() - */ -#define getSUBR(subr) \ - WIZCHIP_READ_BUF(SUBR, subr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set local MAC address - * @param (uint8_t*)shar Pointer variable to set local MAC address. It should be allocated 6 bytes. - * @sa getSHAR() - */ -#define setSHAR(shar) \ - WIZCHIP_WRITE_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local MAC address - * @param (uint8_t*)shar Pointer variable to get local MAC address. It should be allocated 6 bytes. - * @sa setSHAR() - */ -#define getSHAR(shar) \ - WIZCHIP_READ_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set local IP address - * @param (uint8_t*)sipr Pointer variable to set local IP address. It should be allocated 4 bytes. - * @sa getSIPR() - */ -#define setSIPR(sipr) \ - WIZCHIP_WRITE_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)sipr Pointer variable to get local IP address. It should be allocated 4 bytes. - * @sa setSIPR() - */ -#define getSIPR(sipr) \ - WIZCHIP_READ_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set INTLEVEL register - * @param (uint16_t)intlevel Value to set @ref INTLEVEL register. - * @sa getINTLEVEL() - */ -#define setINTLEVEL(intlevel) {\ - WIZCHIP_WRITE(INTLEVEL, (uint8_t)(intlevel >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(INTLEVEL,1), (uint8_t) intlevel); \ - } - - -/** - * @ingroup Common_register_access_function - * @brief Get INTLEVEL register - * @return uint16_t. Value of @ref INTLEVEL register. - * @sa setINTLEVEL() - */ -#define getINTLEVEL() \ - ((WIZCHIP_READ(INTLEVEL) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(INTLEVEL,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref IR register - * @param (uint8_t)ir Value to set @ref IR register. - * @sa getIR() - */ -#define setIR(ir) \ - WIZCHIP_WRITE(IR, (ir & 0xF0)) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IR register - * @return uint8_t. Value of @ref IR register. - * @sa setIR() - */ -#define getIR() \ - (WIZCHIP_READ(IR) & 0xF0) -/** - * @ingroup Common_register_access_function - * @brief Set @ref IMR register - * @param (uint8_t)imr Value to set @ref IMR register. - * @sa getIMR() - */ -#define setIMR(imr) \ - WIZCHIP_WRITE(IMR, imr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IMR register - * @return uint8_t. Value of @ref IMR register. - * @sa setIMR() - */ -#define getIMR() \ - WIZCHIP_READ(IMR) - - -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIR register - * @param (uint8_t)sir Value to set @ref SIR register. - * @sa getSIR() - */ -#define setSIR(sir) \ - WIZCHIP_WRITE(SIR, sir) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIR register - * @return uint8_t. Value of @ref SIR register. - * @sa setSIR() - */ -#define getSIR() \ - WIZCHIP_READ(SIR) -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIMR register - * @param (uint8_t)simr Value to set @ref SIMR register. - * @sa getSIMR() - */ -#define setSIMR(simr) \ - WIZCHIP_WRITE(SIMR, simr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIMR register - * @return uint8_t. Value of @ref SIMR register. - * @sa setSIMR() - */ -#define getSIMR() \ - WIZCHIP_READ(SIMR) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RTR register - * @param (uint16_t)rtr Value to set @ref RTR register. - * @sa getRTR() - */ -#define setRTR(rtr) {\ - WIZCHIP_WRITE(RTR, (uint8_t)(rtr >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(RTR,1), (uint8_t) rtr); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RTR register - * @return uint16_t. Value of @ref RTR register. - * @sa setRTR() - */ -#define getRTR() \ - ((WIZCHIP_READ(RTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(RTR,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RCR register - * @param (uint8_t)rcr Value to set @ref RCR register. - * @sa getRCR() - */ -#define setRCR(rcr) \ - WIZCHIP_WRITE(RCR, rcr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RCR register - * @return uint8_t. Value of @ref RCR register. - * @sa setRCR() - */ -#define getRCR() \ - WIZCHIP_READ(RCR) - -//================================================== test done =========================================================== - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PTIMER register - * @param (uint8_t)ptimer Value to set @ref PTIMER register. - * @sa getPTIMER() - */ -#define setPTIMER(ptimer) \ - WIZCHIP_WRITE(PTIMER, ptimer) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PTIMER register - * @return uint8_t. Value of @ref PTIMER register. - * @sa setPTIMER() - */ -#define getPTIMER() \ - WIZCHIP_READ(PTIMER) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMAGIC register - * @param (uint8_t)pmagic Value to set @ref PMAGIC register. - * @sa getPMAGIC() - */ -#define setPMAGIC(pmagic) \ - WIZCHIP_WRITE(PMAGIC, pmagic) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMAGIC register - * @return uint8_t. Value of @ref PMAGIC register. - * @sa setPMAGIC() - */ -#define getPMAGIC() \ - WIZCHIP_READ(PMAGIC) - -/** - * @ingroup Common_register_access_function - * @brief Set PHAR address - * @param (uint8_t*)phar Pointer variable to set PPP destination MAC register address. It should be allocated 6 bytes. - * @sa getPHAR() - */ -#define setPHAR(phar) \ - WIZCHIP_WRITE_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)phar Pointer variable to PPP destination MAC register address. It should be allocated 6 bytes. - * @sa setPHAR() - */ -#define getPHAR(phar) \ - WIZCHIP_READ_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PSID register - * @param (uint16_t)psid Value to set @ref PSID register. - * @sa getPSID() - */ -#define setPSID(psid) {\ - WIZCHIP_WRITE(PSID, (uint8_t)(psid >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PSID,1), (uint8_t) psid); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PSID register - * @return uint16_t. Value of @ref PSID register. - * @sa setPSID() - */ -//uint16_t getPSID(void); -#define getPSID() \ - ((WIZCHIP_READ(PSID) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PSID,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMRU register - * @param (uint16_t)pmru Value to set @ref PMRU register. - * @sa getPMRU() - */ -#define setPMRU(pmru) { \ - WIZCHIP_WRITE(PMRU, (uint8_t)(pmru>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PMRU,1), (uint8_t) pmru); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMRU register - * @return uint16_t. Value of @ref PMRU register. - * @sa setPMRU() - */ -#define getPMRU() \ - ((WIZCHIP_READ(PMRU) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PMRU,1))) - -/** - * @ingroup Common_register_access_function - * @brief Get unreachable IP address - * @param (uint8_t*)uipr Pointer variable to get unreachable IP address. It should be allocated 4 bytes. - */ -#define getUIPR(uipr) \ - WIZCHIP_READ_BUF(UIPR,uipr,6) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref UPORTR register - * @return uint16_t. Value of @ref UPORTR register. - */ -#define getUPORTR() \ - ((WIZCHIP_READ(UPORTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(UPORTR,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PHYCFGR register - * @param (uint8_t)phycfgr Value to set @ref PHYCFGR register. - * @sa getPHYCFGR() - */ -#define setPHYCFGR(phycfgr) \ - WIZCHIP_WRITE(PHYCFGR, phycfgr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PHYCFGR register - * @return uint8_t. Value of @ref PHYCFGR register. - * @sa setPHYCFGR() - */ -#define getPHYCFGR() \ - WIZCHIP_READ(PHYCFGR) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref VERSIONR register - * @return uint8_t. Value of @ref VERSIONR register. - */ -#define getVERSIONR() \ - WIZCHIP_READ(VERSIONR) - -///////////////////////////////////// - -/////////////////////////////////// -// Socket N register I/O function // -/////////////////////////////////// -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)mr Value to set @ref Sn_MR - * @sa getSn_MR() - */ -#define setSn_MR(sn, mr) \ - WIZCHIP_WRITE(Sn_MR(sn),mr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_MR. - * @sa setSn_MR() - */ -#define getSn_MR(sn) \ - WIZCHIP_READ(Sn_MR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)cr Value to set @ref Sn_CR - * @sa getSn_CR() - */ -#define setSn_CR(sn, cr) \ - WIZCHIP_WRITE(Sn_CR(sn), cr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_CR. - * @sa setSn_CR() - */ -#define getSn_CR(sn) \ - WIZCHIP_READ(Sn_CR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ir Value to set @ref Sn_IR - * @sa getSn_IR() - */ -#define setSn_IR(sn, ir) \ - WIZCHIP_WRITE(Sn_IR(sn), (ir & 0x1F)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IR. - * @sa setSn_IR() - */ -#define getSn_IR(sn) \ - (WIZCHIP_READ(Sn_IR(sn)) & 0x1F) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)imr Value to set @ref Sn_IMR - * @sa getSn_IMR() - */ -#define setSn_IMR(sn, imr) \ - WIZCHIP_WRITE(Sn_IMR(sn), (imr & 0x1F)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IMR. - * @sa setSn_IMR() - */ -#define getSn_IMR(sn) \ - (WIZCHIP_READ(Sn_IMR(sn)) & 0x1F) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_SR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_SR. - */ -#define getSn_SR(sn) \ - WIZCHIP_READ(Sn_SR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)port Value to set @ref Sn_PORT. - * @sa getSn_PORT() - */ -#define setSn_PORT(sn, port) { \ - WIZCHIP_WRITE(Sn_PORT(sn), (uint8_t)(port >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_PORT(sn),1), (uint8_t) port); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_PORT. - * @sa setSn_PORT() - */ -#define getSn_PORT(sn) \ - ((WIZCHIP_READ(Sn_PORT(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_PORT(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DHAR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to set socket n destination hardware address. It should be allocated 6 bytes. - * @sa getSn_DHAR() - */ -#define setSn_DHAR(sn, dhar) \ - WIZCHIP_WRITE_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to get socket n destination hardware address. It should be allocated 6 bytes. - * @sa setSn_DHAR() - */ -#define getSn_DHAR(sn, dhar) \ - WIZCHIP_READ_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to set socket n destination IP address. It should be allocated 4 bytes. - * @sa getSn_DIPR() - */ -#define setSn_DIPR(sn, dipr) \ - WIZCHIP_WRITE_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to get socket n destination IP address. It should be allocated 4 bytes. - * @sa SetSn_DIPR() - */ -#define getSn_DIPR(sn, dipr) \ - WIZCHIP_READ_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)dport Value to set @ref Sn_DPORT - * @sa getSn_DPORT() - */ -#define setSn_DPORT(sn, dport) { \ - WIZCHIP_WRITE(Sn_DPORT(sn), (uint8_t) (dport>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_DPORT(sn),1), (uint8_t) dport); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_DPORT. - * @sa setSn_DPORT() - */ -#define getSn_DPORT(sn) \ - ((WIZCHIP_READ(Sn_DPORT(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_DPORT(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)mss Value to set @ref Sn_MSSR - * @sa setSn_MSSR() - */ -#define setSn_MSSR(sn, mss) { \ - WIZCHIP_WRITE(Sn_MSSR(sn), (uint8_t)(mss>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_MSSR(sn),1), (uint8_t) mss); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_MSSR. - * @sa setSn_MSSR() - */ -#define getSn_MSSR(sn) \ - ((WIZCHIP_READ(Sn_MSSR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_MSSR(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)tos Value to set @ref Sn_TOS - * @sa getSn_TOS() - */ -#define setSn_TOS(sn, tos) \ - WIZCHIP_WRITE(Sn_TOS(sn), tos) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of Sn_TOS. - * @sa setSn_TOS() - */ -#define getSn_TOS(sn) \ - WIZCHIP_READ(Sn_TOS(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ttl Value to set @ref Sn_TTL - * @sa getSn_TTL() - */ -#define setSn_TTL(sn, ttl) \ - WIZCHIP_WRITE(Sn_TTL(sn), ttl) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TTL. - * @sa setSn_TTL() - */ -#define getSn_TTL(sn) \ - WIZCHIP_READ(Sn_TTL(sn)) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)rxbufsize Value to set @ref Sn_RXBUF_SIZE - * @sa getSn_RXBUF_SIZE() - */ -#define setSn_RXBUF_SIZE(sn, rxbufsize) \ - WIZCHIP_WRITE(Sn_RXBUF_SIZE(sn),rxbufsize) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_RXBUF_SIZE. - * @sa setSn_RXBUF_SIZE() - */ -#define getSn_RXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_RXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)txbufsize Value to set @ref Sn_TXBUF_SIZE - * @sa getSn_TXBUF_SIZE() - */ -#define setSn_TXBUF_SIZE(sn, txbufsize) \ - WIZCHIP_WRITE(Sn_TXBUF_SIZE(sn), txbufsize) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TXBUF_SIZE. - * @sa setSn_TXBUF_SIZE() - */ -#define getSn_TXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_TXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_FSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_FSR. - */ -uint16_t getSn_TX_FSR(uint8_t sn); - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_RD. - */ -#define getSn_TX_RD(sn) \ - ((WIZCHIP_READ(Sn_TX_RD(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_RD(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)txwr Value to set @ref Sn_TX_WR - * @sa GetSn_TX_WR() - */ -#define setSn_TX_WR(sn, txwr) { \ - WIZCHIP_WRITE(Sn_TX_WR(sn), (uint8_t)(txwr>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_TX_WR(sn),1), (uint8_t) txwr); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_WR. - * @sa setSn_TX_WR() - */ -#define getSn_TX_WR(sn) \ - ((WIZCHIP_READ(Sn_TX_WR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_WR(sn),1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_RSR. - */ -uint16_t getSn_RX_RSR(uint8_t sn); - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)rxrd Value to set @ref Sn_RX_RD - * @sa getSn_RX_RD() - */ -#define setSn_RX_RD(sn, rxrd) { \ - WIZCHIP_WRITE(Sn_RX_RD(sn), (uint8_t)(rxrd>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_RX_RD(sn),1), (uint8_t) rxrd); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @regurn uint16_t. Value of @ref Sn_RX_RD. - * @sa setSn_RX_RD() - */ -#define getSn_RX_RD(sn) \ - ((WIZCHIP_READ(Sn_RX_RD(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RD(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_WR. - */ -#define getSn_RX_WR(sn) \ - ((WIZCHIP_READ(Sn_RX_WR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_WR(sn),1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)frag Value to set @ref Sn_FRAG - * @sa getSn_FRAD() - */ -#define setSn_FRAG(sn, frag) { \ - WIZCHIP_WRITE(Sn_FRAG(sn), (uint8_t)(frag >>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1), (uint8_t) frag); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_FRAG. - * @sa setSn_FRAG() - */ -#define getSn_FRAG(sn) \ - ((WIZCHIP_READ(Sn_FRAG(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)kpalvt Value to set @ref Sn_KPALVTR - * @sa getSn_KPALVTR() - */ -#define setSn_KPALVTR(sn, kpalvt) \ - WIZCHIP_WRITE(Sn_KPALVTR(sn), kpalvt) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_KPALVTR. - * @sa setSn_KPALVTR() - */ -#define getSn_KPALVTR(sn) \ - WIZCHIP_READ(Sn_KPALVTR(sn)) - -////////////////////////////////////// - -///////////////////////////////////// -// Sn_TXBUF & Sn_RXBUF IO function // -///////////////////////////////////// -/** - * @brief Gets the max buffer size of socket sn passed as parameter. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n RX max buffer size. - */ -#define getSn_RxMAX(sn) \ - (getSn_RXBUF_SIZE(sn) << 10) - -/** - * @brief Gets the max buffer size of socket sn passed as parameters. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n TX max buffer size. - */ -//uint16_t getSn_TxMAX(uint8_t sn); -#define getSn_TxMAX(sn) \ - (getSn_TXBUF_SIZE(sn) << 10) - -/** - * @ingroup Basic_IO_function - * @brief It copies data to internal TX memory - * - * @details This function reads the Tx write pointer register and after that, - * it copies the wizdata(pointer buffer) of the length of len(variable) bytes to internal TX memory - * and updates the Tx write pointer register. - * This function is being called by send() and sendto() function also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to write data - * @param len Data length - * @sa wiz_recv_data() - */ -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It copies data to your buffer from internal RX memory - * - * @details This function read the Rx read pointer register and after that, - * it copies the received data from internal RX memory - * to wizdata(pointer variable) of the length of len(variable) bytes. - * This function is being called by recv() also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to read data - * @param len Data length - * @sa wiz_send_data() - */ -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It discard the received data in RX memory. - * @details It discards the data of the length of len(variable) bytes in internal RX memory. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param len Data length - */ -void wiz_recv_ignore(uint8_t sn, uint16_t len); - -#endif // _W5500_H_ diff --git a/drivers/wiznet5k/ethernet/wizchip_conf.c b/drivers/wiznet5k/ethernet/wizchip_conf.c deleted file mode 100644 index 3e54d2c90b..0000000000 --- a/drivers/wiznet5k/ethernet/wizchip_conf.c +++ /dev/null @@ -1,662 +0,0 @@ -//****************************************************************************/ -//! -//! \file wizchip_conf.c -//! \brief WIZCHIP Config Header File. -//! \version 1.0.1 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.1 Refer to M20140501 -//! 1. Explicit type casting in wizchip_bus_readbyte() & wizchip_bus_writebyte() -// Issued by Mathias ClauBen. -//! uint32_t type converts into ptrdiff_t first. And then recoverting it into uint8_t* -//! For remove the warning when pointer type size is not 32bit. -//! If ptrdiff_t doesn't support in your complier, You should must replace ptrdiff_t into your suitable pointer type. -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//*****************************************************************************/ -//A20140501 : for use the type - ptrdiff_t -#include -// - -#include "wizchip_conf.h" -#include "socket.h" - -/** - * @brief Default function to enable interrupt. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cris_enter(void) {}; -/** - * @brief Default function to disable interrupt. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cris_exit(void) {}; -/** - * @brief Default function to select chip. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cs_select(void) {}; -/** - * @brief Default function to deselect chip. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cs_deselect(void) {}; -/** - * @brief Default function to read in direct or indirect interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ - //M20140501 : Explict pointer type casting -//uint8_t wizchip_bus_readbyte(uint32_t AddrSel) { return * ((volatile uint8_t *) AddrSel); }; -uint8_t wizchip_bus_readbyte(uint32_t AddrSel) { return * ((volatile uint8_t *)((ptrdiff_t) AddrSel)); }; -/** - * @brief Default function to write in direct or indirect interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ - -//M20140501 : Explict pointer type casting -//void wizchip_bus_writebyte(uint32_t AddrSel, uint8_t wb) { *((volatile uint8_t*) AddrSel) = wb; }; -void wizchip_bus_writebyte(uint32_t AddrSel, uint8_t wb) { *((volatile uint8_t*)((ptrdiff_t)AddrSel)) = wb; }; - -/** - * @brief Default function to read in SPI interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_spi_readbytes(uint8_t *buf, uint32_t len) {} -/** - * @brief Default function to write in SPI interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_spi_writebytes(const uint8_t *buf, uint32_t len) {} - -/** - * @\ref _WIZCHIP instance - */ -_WIZCHIP WIZCHIP = - { - .id = _WIZCHIP_ID_, - .if_mode = _WIZCHIP_IO_MODE_, - .CRIS._enter = wizchip_cris_enter, - .CRIS._exit = wizchip_cris_exit, - .CS._select = wizchip_cs_select, - .CS._deselect = wizchip_cs_deselect, - .IF.BUS._read_byte = wizchip_bus_readbyte, - .IF.BUS._write_byte = wizchip_bus_writebyte -// .IF.SPI._read_byte = wizchip_spi_readbyte, -// .IF.SPI._write_byte = wizchip_spi_writebyte - }; - -#if _WIZCHIP_ == 5200 // for W5200 ARP errata -static uint8_t _SUBN_[4]; // subnet -#endif -static uint8_t _DNS_[4]; // DNS server ip address -static dhcp_mode _DHCP_; // DHCP mode - -void reg_wizchip_cris_cbfunc(void(*cris_en)(void), void(*cris_ex)(void)) -{ - if(!cris_en || !cris_ex) - { - WIZCHIP.CRIS._enter = wizchip_cris_enter; - WIZCHIP.CRIS._exit = wizchip_cris_exit; - } - else - { - WIZCHIP.CRIS._enter = cris_en; - WIZCHIP.CRIS._exit = cris_ex; - } -} - -void reg_wizchip_cs_cbfunc(void(*cs_sel)(void), void(*cs_desel)(void)) -{ - if(!cs_sel || !cs_desel) - { - WIZCHIP.CS._select = wizchip_cs_select; - WIZCHIP.CS._deselect = wizchip_cs_deselect; - } - else - { - WIZCHIP.CS._select = cs_sel; - WIZCHIP.CS._deselect = cs_desel; - } -} - -void reg_wizchip_bus_cbfunc(uint8_t(*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, uint8_t wb)) -{ - while(!(WIZCHIP.if_mode & _WIZCHIP_IO_MODE_BUS_)); - - if(!bus_rb || !bus_wb) - { - WIZCHIP.IF.BUS._read_byte = wizchip_bus_readbyte; - WIZCHIP.IF.BUS._write_byte = wizchip_bus_writebyte; - } - else - { - WIZCHIP.IF.BUS._read_byte = bus_rb; - WIZCHIP.IF.BUS._write_byte = bus_wb; - } -} - -void reg_wizchip_spi_cbfunc(void (*spi_rb)(uint8_t *, uint32_t), void (*spi_wb)(const uint8_t *, uint32_t)) -{ - while(!(WIZCHIP.if_mode & _WIZCHIP_IO_MODE_SPI_)); - - if(!spi_rb || !spi_wb) - { - WIZCHIP.IF.SPI._read_bytes = wizchip_spi_readbytes; - WIZCHIP.IF.SPI._write_bytes = wizchip_spi_writebytes; - } - else - { - WIZCHIP.IF.SPI._read_bytes = spi_rb; - WIZCHIP.IF.SPI._write_bytes = spi_wb; - } -} - -int8_t ctlwizchip(ctlwizchip_type cwtype, void* arg) -{ - uint8_t tmp = 0; - uint8_t* ptmp[2] = {0,0}; - switch(cwtype) - { - case CW_RESET_WIZCHIP: - wizchip_sw_reset(); - break; - case CW_INIT_WIZCHIP: - if(arg != 0) - { - ptmp[0] = (uint8_t*)arg; - ptmp[1] = ptmp[0] + _WIZCHIP_SOCK_NUM_; - } - return wizchip_init(ptmp[0], ptmp[1]); - case CW_CLR_INTERRUPT: - wizchip_clrinterrupt(*((intr_kind*)arg)); - break; - case CW_GET_INTERRUPT: - *((intr_kind*)arg) = wizchip_getinterrupt(); - break; - case CW_SET_INTRMASK: - wizchip_setinterruptmask(*((intr_kind*)arg)); - break; - case CW_GET_INTRMASK: - *((intr_kind*)arg) = wizchip_getinterruptmask(); - break; - #if _WIZCHIP_ > 5100 - case CW_SET_INTRTIME: - setINTLEVEL(*(uint16_t*)arg); - break; - case CW_GET_INTRTIME: - *(uint16_t*)arg = getINTLEVEL(); - break; - #endif - case CW_GET_ID: - ((uint8_t*)arg)[0] = WIZCHIP.id[0]; - ((uint8_t*)arg)[1] = WIZCHIP.id[1]; - ((uint8_t*)arg)[2] = WIZCHIP.id[2]; - ((uint8_t*)arg)[3] = WIZCHIP.id[3]; - ((uint8_t*)arg)[4] = WIZCHIP.id[4]; - ((uint8_t*)arg)[5] = 0; - break; - #if _WIZCHIP_ == 5500 - case CW_RESET_PHY: - wizphy_reset(); - break; - case CW_SET_PHYCONF: - wizphy_setphyconf((wiz_PhyConf*)arg); - break; - case CW_GET_PHYCONF: - wizphy_getphyconf((wiz_PhyConf*)arg); - break; - case CW_GET_PHYSTATUS: - break; - case CW_SET_PHYPOWMODE: - return wizphy_setphypmode(*(uint8_t*)arg); - #endif - case CW_GET_PHYPOWMODE: - tmp = wizphy_getphypmode(); - if((int8_t)tmp == -1) return -1; - *(uint8_t*)arg = tmp; - break; - case CW_GET_PHYLINK: - tmp = wizphy_getphylink(); - if((int8_t)tmp == -1) return -1; - *(uint8_t*)arg = tmp; - break; - default: - return -1; - } - return 0; -} - - -int8_t ctlnetwork(ctlnetwork_type cntype, void* arg) -{ - - switch(cntype) - { - case CN_SET_NETINFO: - wizchip_setnetinfo((wiz_NetInfo*)arg); - break; - case CN_GET_NETINFO: - wizchip_getnetinfo((wiz_NetInfo*)arg); - break; - case CN_SET_NETMODE: - return wizchip_setnetmode(*(netmode_type*)arg); - case CN_GET_NETMODE: - *(netmode_type*)arg = wizchip_getnetmode(); - break; - case CN_SET_TIMEOUT: - wizchip_settimeout((wiz_NetTimeout*)arg); - break; - case CN_GET_TIMEOUT: - wizchip_gettimeout((wiz_NetTimeout*)arg); - break; - default: - return -1; - } - return 0; -} - -void wizchip_sw_reset(void) -{ - uint8_t gw[4], sn[4], sip[4]; - uint8_t mac[6]; - getSHAR(mac); - getGAR(gw); getSUBR(sn); getSIPR(sip); - setMR(MR_RST); - getMR(); // for delay - setSHAR(mac); - setGAR(gw); - setSUBR(sn); - setSIPR(sip); -} - -int8_t wizchip_init(uint8_t* txsize, uint8_t* rxsize) -{ - int8_t i; - int8_t tmp = 0; - wizchip_sw_reset(); - if(txsize) - { - tmp = 0; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - tmp += txsize[i]; - if(tmp > 16) return -1; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - setSn_TXBUF_SIZE(i, txsize[i]); - } - if(rxsize) - { - tmp = 0; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - tmp += rxsize[i]; - if(tmp > 16) return -1; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - setSn_RXBUF_SIZE(i, rxsize[i]); - } - - WIZCHIP_EXPORT(socket_reset)(); - - return 0; -} - -void wizchip_clrinterrupt(intr_kind intr) -{ - uint8_t ir = (uint8_t)intr; - uint8_t sir = (uint8_t)((uint16_t)intr >> 8); -#if _WIZCHIP_ < 5500 - ir |= (1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - ir |= (1 << 6); -#endif - -#if _WIZCHIP_ < 5200 - sir &= 0x0F; -#endif - -#if _WIZCHIP_ == 5100 - ir |= sir; - setIR(ir); -#else - setIR(ir); - setSIR(sir); -#endif -} - -intr_kind wizchip_getinterrupt(void) -{ - uint8_t ir = 0; - uint8_t sir = 0; - uint16_t ret = 0; -#if _WIZCHIP_ == 5100 - ir = getIR(); - sir = ir 0x0F; -#else - ir = getIR(); - sir = getSIR(); -#endif - -#if _WIZCHIP_ < 5500 - ir &= ~(1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - ir &= ~(1 << 6); -#endif - ret = sir; - ret = (ret << 8) + ir; - return (intr_kind)ret; -} - -void wizchip_setinterruptmask(intr_kind intr) -{ - uint8_t imr = (uint8_t)intr; - uint8_t simr = (uint8_t)((uint16_t)intr >> 8); -#if _WIZCHIP_ < 5500 - imr &= ~(1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - imr &= ~(1 << 6); -#endif - -#if _WIZCHIP_ < 5200 - simr &= 0x0F; -#endif - -#if _WIZCHIP_ == 5100 - imr |= simr; - setIMR(imr); -#else - setIMR(imr); - setSIMR(simr); -#endif -} - -intr_kind wizchip_getinterruptmask(void) -{ - uint8_t imr = 0; - uint8_t simr = 0; - uint16_t ret = 0; -#if _WIZCHIP_ == 5100 - imr = getIMR(); - simr = imr 0x0F; -#else - imr = getIMR(); - simr = getSIMR(); -#endif - -#if _WIZCHIP_ < 5500 - imr &= ~(1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - imr &= ~(1 << 6); // IK_DEST_UNREACH -#endif - ret = simr; - ret = (ret << 8) + imr; - return (intr_kind)ret; -} - -int8_t wizphy_getphylink(void) -{ - int8_t tmp; -#if _WIZCHIP_ == 5200 - if(getPHYSTATUS() & PHYSTATUS_LINK) - tmp = PHY_LINK_ON; - else - tmp = PHY_LINK_OFF; -#elif _WIZCHIP_ == 5500 - if(getPHYCFGR() & PHYCFGR_LNK_ON) - tmp = PHY_LINK_ON; - else - tmp = PHY_LINK_OFF; -#else - tmp = -1; -#endif - return tmp; -} - -#if _WIZCHIP_ > 5100 - -int8_t wizphy_getphypmode(void) -{ - int8_t tmp = 0; - #if _WIZCHIP_ == 5200 - if(getPHYSTATUS() & PHYSTATUS_POWERDOWN) - tmp = PHY_POWER_DOWN; - else - tmp = PHY_POWER_NORM; - #elif _WIZCHIP_ == 5500 - if(getPHYCFGR() & PHYCFGR_OPMDC_PDOWN) - tmp = PHY_POWER_DOWN; - else - tmp = PHY_POWER_NORM; - #else - tmp = -1; - #endif - return tmp; -} -#endif - -#if _WIZCHIP_ == 5500 -void wizphy_reset(void) -{ - uint8_t tmp = getPHYCFGR(); - tmp &= PHYCFGR_RST; - setPHYCFGR(tmp); - tmp = getPHYCFGR(); - tmp |= ~PHYCFGR_RST; - setPHYCFGR(tmp); -} - -void wizphy_setphyconf(wiz_PhyConf* phyconf) -{ - uint8_t tmp = 0; - if(phyconf->by == PHY_CONFBY_SW) - tmp |= PHYCFGR_OPMD; - else - tmp &= ~PHYCFGR_OPMD; - if(phyconf->mode == PHY_MODE_AUTONEGO) - tmp |= PHYCFGR_OPMDC_ALLA; - else - { - if(phyconf->duplex == PHY_DUPLEX_FULL) - { - if(phyconf->speed == PHY_SPEED_100) - tmp |= PHYCFGR_OPMDC_100F; - else - tmp |= PHYCFGR_OPMDC_10F; - } - else - { - if(phyconf->speed == PHY_SPEED_100) - tmp |= PHYCFGR_OPMDC_100H; - else - tmp |= PHYCFGR_OPMDC_10H; - } - } - setPHYCFGR(tmp); - wizphy_reset(); -} - -void wizphy_getphyconf(wiz_PhyConf* phyconf) -{ - uint8_t tmp = 0; - tmp = getPHYCFGR(); - phyconf->by = (tmp & PHYCFGR_OPMD) ? PHY_CONFBY_SW : PHY_CONFBY_HW; - switch(tmp & PHYCFGR_OPMDC_ALLA) - { - case PHYCFGR_OPMDC_ALLA: - case PHYCFGR_OPMDC_100FA: - phyconf->mode = PHY_MODE_AUTONEGO; - break; - default: - phyconf->mode = PHY_MODE_MANUAL; - break; - } - switch(tmp & PHYCFGR_OPMDC_ALLA) - { - case PHYCFGR_OPMDC_100FA: - case PHYCFGR_OPMDC_100F: - case PHYCFGR_OPMDC_100H: - phyconf->speed = PHY_SPEED_100; - break; - default: - phyconf->speed = PHY_SPEED_10; - break; - } - switch(tmp & PHYCFGR_OPMDC_ALLA) - { - case PHYCFGR_OPMDC_100FA: - case PHYCFGR_OPMDC_100F: - case PHYCFGR_OPMDC_10F: - phyconf->duplex = PHY_DUPLEX_FULL; - break; - default: - phyconf->duplex = PHY_DUPLEX_HALF; - break; - } -} - -void wizphy_getphystat(wiz_PhyConf* phyconf) -{ - uint8_t tmp = getPHYCFGR(); - phyconf->duplex = (tmp & PHYCFGR_DPX_FULL) ? PHY_DUPLEX_FULL : PHY_DUPLEX_HALF; - phyconf->speed = (tmp & PHYCFGR_SPD_100) ? PHY_SPEED_100 : PHY_SPEED_10; -} - -int8_t wizphy_setphypmode(uint8_t pmode) -{ - uint8_t tmp = 0; - tmp = getPHYCFGR(); - if((tmp & PHYCFGR_OPMD)== 0) return -1; - tmp &= ~PHYCFGR_OPMDC_ALLA; - if( pmode == PHY_POWER_DOWN) - tmp |= PHYCFGR_OPMDC_PDOWN; - else - tmp |= PHYCFGR_OPMDC_ALLA; - setPHYCFGR(tmp); - wizphy_reset(); - tmp = getPHYCFGR(); - if( pmode == PHY_POWER_DOWN) - { - if(tmp & PHYCFGR_OPMDC_PDOWN) return 0; - } - else - { - if(tmp & PHYCFGR_OPMDC_ALLA) return 0; - } - return -1; -} -#endif - - -void wizchip_setnetinfo(wiz_NetInfo* pnetinfo) -{ - setSHAR(pnetinfo->mac); - setGAR(pnetinfo->gw); - setSUBR(pnetinfo->sn); - setSIPR(pnetinfo->ip); -#if _WIZCHIP_ == 5200 // for W5200 ARP errata - _SUBN_[0] = pnetinfo->sn[0]; - _SUBN_[1] = pnetinfo->sn[1]; - _SUBN_[2] = pnetinfo->sn[2]; - _SUBN_[3] = pnetinfo->sn[3]; -#endif - _DNS_[0] = pnetinfo->dns[0]; - _DNS_[1] = pnetinfo->dns[1]; - _DNS_[2] = pnetinfo->dns[2]; - _DNS_[3] = pnetinfo->dns[3]; - _DHCP_ = pnetinfo->dhcp; -} - -void wizchip_getnetinfo(wiz_NetInfo* pnetinfo) -{ - getSHAR(pnetinfo->mac); - getGAR(pnetinfo->gw); - getSUBR(pnetinfo->sn); - getSIPR(pnetinfo->ip); -#if _WIZCHIP_ == 5200 // for W5200 ARP errata - pnetinfo->sn[0] = _SUBN_[0]; - pnetinfo->sn[1] = _SUBN_[1]; - pnetinfo->sn[2] = _SUBN_[2]; - pnetinfo->sn[3] = _SUBN_[3]; -#endif - pnetinfo->dns[0]= _DNS_[0]; - pnetinfo->dns[1]= _DNS_[1]; - pnetinfo->dns[2]= _DNS_[2]; - pnetinfo->dns[3]= _DNS_[3]; - pnetinfo->dhcp = _DHCP_; -} - -#if _WIZCHIP_ == 5200 // for W5200 ARP errata -uint8_t *wizchip_getsubn(void) { - return _SUBN_; -} -#endif - -int8_t wizchip_setnetmode(netmode_type netmode) -{ - uint8_t tmp = 0; -#if _WIZCHIP_ != 5500 - if(netmode & ~(NM_WAKEONLAN | NM_PPPOE | NM_PINGBLOCK)) return -1; -#else - if(netmode & ~(NM_WAKEONLAN | NM_PPPOE | NM_PINGBLOCK | NM_FORCEARP)) return -1; -#endif - tmp = getMR(); - tmp |= (uint8_t)netmode; - setMR(tmp); - return 0; -} - -netmode_type wizchip_getnetmode(void) -{ - return (netmode_type) getMR(); -} - -void wizchip_settimeout(wiz_NetTimeout* nettime) -{ - setRCR(nettime->retry_cnt); - setRTR(nettime->time_100us); -} - -void wizchip_gettimeout(wiz_NetTimeout* nettime) -{ - nettime->retry_cnt = getRCR(); - nettime->time_100us = getRTR(); -} diff --git a/drivers/wiznet5k/ethernet/wizchip_conf.h b/drivers/wiznet5k/ethernet/wizchip_conf.h deleted file mode 100644 index 4a7a7bd691..0000000000 --- a/drivers/wiznet5k/ethernet/wizchip_conf.h +++ /dev/null @@ -1,554 +0,0 @@ -//***************************************************************************** -// -//! \file wizchip_conf.h -//! \brief WIZCHIP Config Header File. -//! \version 1.0.0 -//! \date 2013/10/21 -//! \par Revision history -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -/** - * @defgroup extra_functions 2. WIZnet Extra Functions - * - * @brief These functions is optional function. It could be replaced at WIZCHIP I/O function because they were made by WIZCHIP I/O functions. - * @details There are functions of configuring WIZCHIP, network, interrupt, phy, network information and timer. \n - * - */ - -#ifndef _WIZCHIP_CONF_H_ -#define _WIZCHIP_CONF_H_ - -#include -/** - * @brief Select WIZCHIP. - * @todo You should select one, \b 5100, \b 5200 ,\b 5500 or etc. \n\n - * ex> #define \_WIZCHIP_ 5500 - */ -#ifndef _WIZCHIP_ -#define _WIZCHIP_ 5200 // 5100, 5200, 5500 -#endif - -#define _WIZCHIP_IO_MODE_NONE_ 0x0000 -#define _WIZCHIP_IO_MODE_BUS_ 0x0100 /**< Bus interface mode */ -#define _WIZCHIP_IO_MODE_SPI_ 0x0200 /**< SPI interface mode */ -//#define _WIZCHIP_IO_MODE_IIC_ 0x0400 -//#define _WIZCHIP_IO_MODE_SDIO_ 0x0800 -// Add to -// - -#define _WIZCHIP_IO_MODE_BUS_DIR_ (_WIZCHIP_IO_MODE_BUS_ + 1) /**< BUS interface mode for direct */ -#define _WIZCHIP_IO_MODE_BUS_INDIR_ (_WIZCHIP_IO_MODE_BUS_ + 2) /**< BUS interface mode for indirect */ - -#define _WIZCHIP_IO_MODE_SPI_VDM_ (_WIZCHIP_IO_MODE_SPI_ + 1) /**< SPI interface mode for variable length data*/ -#define _WIZCHIP_IO_MODE_SPI_FDM_ (_WIZCHIP_IO_MODE_SPI_ + 2) /**< SPI interface mode for fixed length data mode*/ - - -#if (_WIZCHIP_ == 5100) - #define _WIZCHIP_ID_ "W5100\0" -/** - * @brief Define interface mode. - * @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ , @ref \_WIZCHIP_IO_MODE_BUS_DIR_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_ - */ - -// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_DIR_ -// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_ - #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_ - -#elif (_WIZCHIP_ == 5200) - #define _WIZCHIP_ID_ "W5200\0" -/** - * @brief Define interface mode. - * @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_ - */ -// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_ - #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_ - #include "w5200/w5200.h" -#elif (_WIZCHIP_ == 5500) - #define _WIZCHIP_ID_ "W5500\0" - -/** - * @brief Define interface mode. \n - * @todo Should select interface mode as chip. - * - @ref \_WIZCHIP_IO_MODE_SPI_ \n - * -@ref \_WIZCHIP_IO_MODE_SPI_VDM_ : Valid only in @ref \_WIZCHIP_ == 5500 \n - * -@ref \_WIZCHIP_IO_MODE_SPI_FDM_ : Valid only in @ref \_WIZCHIP_ == 5500 \n - * - @ref \_WIZCHIP_IO_MODE_BUS_ \n - * - @ref \_WIZCHIP_IO_MODE_BUS_DIR_ \n - * - @ref \_WIZCHIP_IO_MODE_BUS_INDIR_ \n - * - Others will be defined in future. \n\n - * ex> #define \_WIZCHIP_IO_MODE_ \_WIZCHIP_IO_MODE_SPI_VDM_ - * - */ - //#define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_FDM_ - #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_VDM_ - #include "w5500/w5500.h" -#else - #error "Unknown defined _WIZCHIP_. You should define one of 5100, 5200, and 5500 !!!" -#endif - -#ifndef _WIZCHIP_IO_MODE_ - #error "Undefined _WIZCHIP_IO_MODE_. You should define it !!!" -#endif - -/** - * @brief Define I/O base address when BUS IF mode. - * @todo Should re-define it to fit your system when BUS IF Mode (@ref \_WIZCHIP_IO_MODE_BUS_, - * @ref \_WIZCHIP_IO_MODE_BUS_DIR_, @ref \_WIZCHIP_IO_MODE_BUS_INDIR_). \n\n - * ex> #define \_WIZCHIP_IO_BASE_ 0x00008000 - */ -#define _WIZCHIP_IO_BASE_ 0x00000000 // - -#if _WIZCHIP_IO_MODE_ & _WIZCHIP_IO_MODE_BUS - #ifndef _WIZCHIP_IO_BASE_ - #error "You should be define _WIZCHIP_IO_BASE to fit your system memory map." - #endif -#endif - -#if _WIZCHIP_ > 5100 - #define _WIZCHIP_SOCK_NUM_ 8 ///< The count of independant socket of @b WIZCHIP -#else - #define _WIZCHIP_SOCK_NUM_ 4 ///< The count of independant socket of @b WIZCHIP -#endif - - -/******************************************************** -* WIZCHIP BASIC IF functions for SPI, SDIO, I2C , ETC. -*********************************************************/ -/** - * @ingroup DATA_TYPE - * @brief The set of callback functions for W5500:@ref WIZCHIP_IO_Functions W5200:@ref WIZCHIP_IO_Functions_W5200 - */ -typedef struct __WIZCHIP -{ - uint16_t if_mode; ///< host interface mode - uint8_t id[6]; ///< @b WIZCHIP ID such as @b 5100, @b 5200, @b 5500, and so on. - /** - * The set of critical section callback func. - */ - struct _CRIS - { - void (*_enter) (void); ///< crtical section enter - void (*_exit) (void); ///< critial section exit - }CRIS; - /** - * The set of @ref\_WIZCHIP_ select control callback func. - */ - struct _CS - { - void (*_select) (void); ///< @ref \_WIZCHIP_ selected - void (*_deselect)(void); ///< @ref \_WIZCHIP_ deselected - }CS; - /** - * The set of interface IO callback func. - */ - union _IF - { - /** - * For BUS interface IO - */ - struct - { - uint8_t (*_read_byte) (uint32_t AddrSel); - void (*_write_byte) (uint32_t AddrSel, uint8_t wb); - }BUS; - /** - * For SPI interface IO - */ - struct - { - void (*_read_bytes) (uint8_t *buf, uint32_t len); - void (*_write_bytes) (const uint8_t *buf, uint32_t len); - }SPI; - // To be added - // - }IF; -}_WIZCHIP; - -extern _WIZCHIP WIZCHIP; - -/** - * @ingroup DATA_TYPE - * WIZCHIP control type enumration used in @ref ctlwizchip(). - */ -typedef enum -{ - CW_RESET_WIZCHIP, ///< Resets WIZCHIP by softly - CW_INIT_WIZCHIP, ///< Inializes to WIZCHIP with SOCKET buffer size 2 or 1 dimension array typed uint8_t. - CW_GET_INTERRUPT, ///< Get Interrupt status of WIZCHIP - CW_CLR_INTERRUPT, ///< Clears interrupt - CW_SET_INTRMASK, ///< Masks interrupt - CW_GET_INTRMASK, ///< Get interrupt mask - CW_SET_INTRTIME, ///< Set interval time between the current and next interrupt. - CW_GET_INTRTIME, ///< Set interval time between the current and next interrupt. - CW_GET_ID, ///< Gets WIZCHIP name. - -#if _WIZCHIP_ == 5500 - CW_RESET_PHY, ///< Resets internal PHY. Valid Only W5000 - CW_SET_PHYCONF, ///< When PHY configured by interal register, PHY operation mode (Manual/Auto, 10/100, Half/Full). Valid Only W5000 - CW_GET_PHYCONF, ///< Get PHY operation mode in interal register. Valid Only W5000 - CW_GET_PHYSTATUS, ///< Get real PHY status on operating. Valid Only W5000 - CW_SET_PHYPOWMODE, ///< Set PHY power mode as noraml and down when PHYSTATUS.OPMD == 1. Valid Only W5000 -#endif - CW_GET_PHYPOWMODE, ///< Get PHY Power mode as down or normal - CW_GET_PHYLINK ///< Get PHY Link status -}ctlwizchip_type; - -/** - * @ingroup DATA_TYPE - * Network control type enumration used in @ref ctlnetwork(). - */ -typedef enum -{ - CN_SET_NETINFO, ///< Set Network with @ref wiz_NetInfo - CN_GET_NETINFO, ///< Get Network with @ref wiz_NetInfo - CN_SET_NETMODE, ///< Set network mode as WOL, PPPoE, Ping Block, and Force ARP mode - CN_GET_NETMODE, ///< Get network mode as WOL, PPPoE, Ping Block, and Force ARP mode - CN_SET_TIMEOUT, ///< Set network timeout as retry count and time. - CN_GET_TIMEOUT, ///< Get network timeout as retry count and time. -}ctlnetwork_type; - -/** - * @ingroup DATA_TYPE - * Interrupt kind when CW_SET_INTRRUPT, CW_GET_INTERRUPT, CW_SET_INTRMASK - * and CW_GET_INTRMASK is used in @ref ctlnetwork(). - * It can be used with OR operation. - */ -typedef enum -{ -#if _WIZCHIP_ > 5200 - IK_WOL = (1 << 4), ///< Wake On Lan by receiving the magic packet. Valid in W500. -#endif - - IK_PPPOE_TERMINATED = (1 << 5), ///< PPPoE Disconnected - -#if _WIZCHIP_ != 5200 - IK_DEST_UNREACH = (1 << 6), ///< Destination IP & Port Unreable, No use in W5200 -#endif - - IK_IP_CONFLICT = (1 << 7), ///< IP conflict occurred - - IK_SOCK_0 = (1 << 8), ///< Socket 0 interrupt - IK_SOCK_1 = (1 << 9), ///< Socket 1 interrupt - IK_SOCK_2 = (1 << 10), ///< Socket 2 interrupt - IK_SOCK_3 = (1 << 11), ///< Socket 3 interrupt -#if _WIZCHIP_ > 5100 - IK_SOCK_4 = (1 << 12), ///< Socket 4 interrupt, No use in 5100 - IK_SOCK_5 = (1 << 13), ///< Socket 5 interrupt, No use in 5100 - IK_SOCK_6 = (1 << 14), ///< Socket 6 interrupt, No use in 5100 - IK_SOCK_7 = (1 << 15), ///< Socket 7 interrupt, No use in 5100 -#endif - -#if _WIZCHIP_ > 5100 - IK_SOCK_ALL = (0xFF << 8) ///< All Socket interrpt -#else - IK_SOCK_ALL = (0x0F << 8) ///< All Socket interrpt -#endif -}intr_kind; - -#define PHY_CONFBY_HW 0 ///< Configured PHY operation mode by HW pin -#define PHY_CONFBY_SW 1 ///< Configured PHY operation mode by SW register -#define PHY_MODE_MANUAL 0 ///< Configured PHY operation mode with user setting. -#define PHY_MODE_AUTONEGO 1 ///< Configured PHY operation mode with auto-negotiation -#define PHY_SPEED_10 0 ///< Link Speed 10 -#define PHY_SPEED_100 1 ///< Link Speed 100 -#define PHY_DUPLEX_HALF 0 ///< Link Half-Duplex -#define PHY_DUPLEX_FULL 1 ///< Link Full-Duplex -#define PHY_LINK_OFF 0 ///< Link Off -#define PHY_LINK_ON 1 ///< Link On -#define PHY_POWER_NORM 0 ///< PHY power normal mode -#define PHY_POWER_DOWN 1 ///< PHY power down mode - - -#if _WIZCHIP_ == 5500 -/** - * @ingroup DATA_TYPE - * It configures PHY configuration when CW_SET PHYCONF or CW_GET_PHYCONF in W5500, - * and it indicates the real PHY status configured by HW or SW in all WIZCHIP. \n - * Valid only in W5500. - */ -typedef struct wiz_PhyConf_t -{ - uint8_t by; ///< set by @ref PHY_CONFBY_HW or @ref PHY_CONFBY_SW - uint8_t mode; ///< set by @ref PHY_MODE_MANUAL or @ref PHY_MODE_AUTONEGO - uint8_t speed; ///< set by @ref PHY_SPEED_10 or @ref PHY_SPEED_100 - uint8_t duplex; ///< set by @ref PHY_DUPLEX_HALF @ref PHY_DUPLEX_FULL - //uint8_t power; ///< set by @ref PHY_POWER_NORM or @ref PHY_POWER_DOWN - //uint8_t link; ///< Valid only in CW_GET_PHYSTATUS. set by @ref PHY_LINK_ON or PHY_DUPLEX_OFF - }wiz_PhyConf; -#endif - -/** - * @ingroup DATA_TYPE - * It used in setting dhcp_mode of @ref wiz_NetInfo. - */ -typedef enum -{ - NETINFO_STATIC = 1, ///< Static IP configuration by manually. - NETINFO_DHCP ///< Dynamic IP configruation from a DHCP sever -}dhcp_mode; - -/** - * @ingroup DATA_TYPE - * Network Information for WIZCHIP - */ -typedef struct wiz_NetInfo_t -{ - uint8_t mac[6]; ///< Source Mac Address - uint8_t ip[4]; ///< Source IP Address - uint8_t sn[4]; ///< Subnet Mask - uint8_t gw[4]; ///< Gateway IP Address - uint8_t dns[4]; ///< DNS server IP Address - dhcp_mode dhcp; ///< 1 - Static, 2 - DHCP -}wiz_NetInfo; - -/** - * @ingroup DATA_TYPE - * Network mode - */ -typedef enum -{ -#if _WIZCHIP_ == 5500 - NM_FORCEARP = (1<<1), ///< Force to APP send whenever udp data is sent. Valid only in W5500 -#endif - NM_WAKEONLAN = (1<<5), ///< Wake On Lan - NM_PINGBLOCK = (1<<4), ///< Block ping-request - NM_PPPOE = (1<<3), ///< PPPoE mode -}netmode_type; - -/** - * @ingroup DATA_TYPE - * Used in CN_SET_TIMEOUT or CN_GET_TIMEOUT of @ref ctlwizchip() for timeout configruation. - */ -typedef struct wiz_NetTimeout_t -{ - uint8_t retry_cnt; ///< retry count - uint16_t time_100us; ///< time unit 100us -}wiz_NetTimeout; - -/** - *@brief Registers call back function for critical section of I/O functions such as - *\ref WIZCHIP_READ, @ref WIZCHIP_WRITE, @ref WIZCHIP_READ_BUF and @ref WIZCHIP_WRITE_BUF. - *@param cris_en : callback function for critical section enter. - *@param cris_ex : callback function for critical section exit. - *@todo Describe @ref WIZCHIP_CRITICAL_ENTER and @ref WIZCHIP_CRITICAL_EXIT marco or register your functions. - *@note If you do not describe or register, default functions(@ref wizchip_cris_enter & @ref wizchip_cris_exit) is called. - */ -void reg_wizchip_cris_cbfunc(void(*cris_en)(void), void(*cris_ex)(void)); - - -/** - *@brief Registers call back function for WIZCHIP select & deselect. - *@param cs_sel : callback function for WIZCHIP select - *@param cs_desel : callback fucntion for WIZCHIP deselect - *@todo Describe @ref wizchip_cs_select and @ref wizchip_cs_deselect function or register your functions. - *@note If you do not describe or register, null function is called. - */ -void reg_wizchip_cs_cbfunc(void(*cs_sel)(void), void(*cs_desel)(void)); - -/** - *@brief Registers call back function for bus interface. - *@param bus_rb : callback function to read byte data using system bus - *@param bus_wb : callback function to write byte data using system bus - *@todo Describe @ref wizchip_bus_readbyte and @ref wizchip_bus_writebyte function - *or register your functions. - *@note If you do not describe or register, null function is called. - */ -void reg_wizchip_bus_cbfunc(uint8_t (*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, uint8_t wb)); - -/** - *@brief Registers call back function for SPI interface. - *@param spi_rb : callback function to read byte usig SPI - *@param spi_wb : callback function to write byte usig SPI - *@todo Describe \ref wizchip_spi_readbyte and \ref wizchip_spi_writebyte function - *or register your functions. - *@note If you do not describe or register, null function is called. - */ -void reg_wizchip_spi_cbfunc(void (*spi_rb)(uint8_t *, uint32_t), void (*spi_wb)(const uint8_t *, uint32_t)); - -/** - * @ingroup extra_functions - * @brief Controls to the WIZCHIP. - * @details Resets WIZCHIP & internal PHY, Configures PHY mode, Monitor PHY(Link,Speed,Half/Full/Auto), - * controls interrupt & mask and so on. - * @param cwtype : Decides to the control type - * @param arg : arg type is dependent on cwtype. - * @return 0 : Success \n - * -1 : Fail because of invalid \ref ctlwizchip_type or unsupported \ref ctlwizchip_type in WIZCHIP - */ -int8_t ctlwizchip(ctlwizchip_type cwtype, void* arg); - -/** - * @ingroup extra_functions - * @brief Controls to network. - * @details Controls to network environment, mode, timeout and so on. - * @param cntype : Input. Decides to the control type - * @param arg : Inout. arg type is dependent on cntype. - * @return -1 : Fail because of invalid \ref ctlnetwork_type or unsupported \ref ctlnetwork_type in WIZCHIP \n - * 0 : Success - */ -int8_t ctlnetwork(ctlnetwork_type cntype, void* arg); - - -/* - * The following functions are implemented for internal use. - * but You can call these functions for code size reduction instead of ctlwizchip() and ctlnetwork(). - */ - -/** - * @ingroup extra_functions - * @brief Reset WIZCHIP by softly. - */ -void wizchip_sw_reset(void); - -/** - * @ingroup extra_functions - * @brief Initializes WIZCHIP with socket buffer size - * @param txsize Socket tx buffer sizes. If null, initialized the default size 2KB. - * @param rxsize Socket rx buffer sizes. If null, initialized the default size 2KB. - * @return 0 : succcess \n - * -1 : fail. Invalid buffer size - */ -int8_t wizchip_init(uint8_t* txsize, uint8_t* rxsize); - -/** - * @ingroup extra_functions - * @brief Clear Interrupt of WIZCHIP. - * @param intr : @ref intr_kind value operated OR. It can type-cast to uint16_t. - */ -void wizchip_clrinterrupt(intr_kind intr); - -/** - * @ingroup extra_functions - * @brief Get Interrupt of WIZCHIP. - * @return @ref intr_kind value operated OR. It can type-cast to uint16_t. - */ -intr_kind wizchip_getinterrupt(void); - -/** - * @ingroup extra_functions - * @brief Mask or Unmask Interrupt of WIZCHIP. - * @param intr : @ref intr_kind value operated OR. It can type-cast to uint16_t. - */ -void wizchip_setinterruptmask(intr_kind intr); - -/** - * @ingroup extra_functions - * @brief Get Interrupt mask of WIZCHIP. - * @return : The operated OR vaule of @ref intr_kind. It can type-cast to uint16_t. - */ -intr_kind wizchip_getinterruptmask(void); - -#if _WIZCHIP_ > 5100 - int8_t wizphy_getphylink(void); ///< get the link status of phy in WIZCHIP. No use in W5100 - int8_t wizphy_getphypmode(void); ///< get the power mode of PHY in WIZCHIP. No use in W5100 -#endif - -#if _WIZCHIP_ == 5500 - void wizphy_reset(void); ///< Reset phy. Vailid only in W5500 -/** - * @ingroup extra_functions - * @brief Set the phy information for WIZCHIP without power mode - * @param phyconf : @ref wiz_PhyConf - */ - void wizphy_setphyconf(wiz_PhyConf* phyconf); - /** - * @ingroup extra_functions - * @brief Get phy configuration information. - * @param phyconf : @ref wiz_PhyConf - */ - void wizphy_getphyconf(wiz_PhyConf* phyconf); - /** - * @ingroup extra_functions - * @brief Get phy status. - * @param phyconf : @ref wiz_PhyConf - */ - void wizphy_getphystat(wiz_PhyConf* phyconf); - /** - * @ingroup extra_functions - * @brief set the power mode of phy inside WIZCHIP. Refer to @ref PHYCFGR in W5500, @ref PHYSTATUS in W5200 - * @param pmode Settig value of power down mode. - */ - int8_t wizphy_setphypmode(uint8_t pmode); -#endif - -/** -* @ingroup extra_functions - * @brief Set the network information for WIZCHIP - * @param pnetinfo : @ref wizNetInfo - */ -void wizchip_setnetinfo(wiz_NetInfo* pnetinfo); - -/** - * @ingroup extra_functions - * @brief Get the network information for WIZCHIP - * @param pnetinfo : @ref wizNetInfo - */ -void wizchip_getnetinfo(wiz_NetInfo* pnetinfo); - -#if _WIZCHIP_ == 5200 // for W5200 ARP errata -uint8_t *wizchip_getsubn(void); -#endif - -/** - * @ingroup extra_functions - * @brief Set the network mode such WOL, PPPoE, Ping Block, and etc. - * @param pnetinfo Value of network mode. Refer to @ref netmode_type. - */ -int8_t wizchip_setnetmode(netmode_type netmode); - -/** - * @ingroup extra_functions - * @brief Get the network mode such WOL, PPPoE, Ping Block, and etc. - * @return Value of network mode. Refer to @ref netmode_type. - */ -netmode_type wizchip_getnetmode(void); - -/** - * @ingroup extra_functions - * @brief Set retry time value(@ref RTR) and retry count(@ref RCR). - * @details @ref RTR configures the retransmission timeout period and @ref RCR configures the number of time of retransmission. - * @param nettime @ref RTR value and @ref RCR value. Refer to @ref wiz_NetTimeout. - */ -void wizchip_settimeout(wiz_NetTimeout* nettime); - -/** - * @ingroup extra_functions - * @brief Get retry time value(@ref RTR) and retry count(@ref RCR). - * @details @ref RTR configures the retransmission timeout period and @ref RCR configures the number of time of retransmission. - * @param nettime @ref RTR value and @ref RCR value. Refer to @ref wiz_NetTimeout. - */ -void wizchip_gettimeout(wiz_NetTimeout* nettime); - -#endif // _WIZCHIP_CONF_H_ diff --git a/drivers/wiznet5k/internet/dhcp/dhcp.c b/drivers/wiznet5k/internet/dhcp/dhcp.c deleted file mode 100644 index 5747582599..0000000000 --- a/drivers/wiznet5k/internet/dhcp/dhcp.c +++ /dev/null @@ -1,978 +0,0 @@ -//***************************************************************************** -// -//! \file dhcp.c -//! \brief DHCP APIs implement file. -//! \details Processig DHCP protocol as DISCOVER, OFFER, REQUEST, ACK, NACK and DECLINE. -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2013/11/18> 1st Release -//! <2012/12/20> V1.1.0 -//! 1. Optimize code -//! 2. Add reg_dhcp_cbfunc() -//! 3. Add DHCP_stop() -//! 4. Integrate check_DHCP_state() & DHCP_run() to DHCP_run() -//! 5. Don't care system endian -//! 6. Add comments -//! <2012/12/26> V1.1.1 -//! 1. Modify variable declaration: dhcp_tick_1s is declared volatile for code optimization -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -//#include "Ethernet/socket.h" -//#include "Internet/DHCP/dhcp.h" -#include "../../Ethernet/socket.h" -#include "dhcp.h" - -/* If you want to display debug & processing message, Define _DHCP_DEBUG_ in dhcp.h */ - -#ifdef _DHCP_DEBUG_ - #include -#endif - -/* DHCP state machine. */ -#define STATE_DHCP_INIT 0 ///< Initialize -#define STATE_DHCP_DISCOVER 1 ///< send DISCOVER and wait OFFER -#define STATE_DHCP_REQUEST 2 ///< send REQEUST and wait ACK or NACK -#define STATE_DHCP_LEASED 3 ///< ReceiveD ACK and IP leased -#define STATE_DHCP_REREQUEST 4 ///< send REQUEST for maintaining leased IP -#define STATE_DHCP_RELEASE 5 ///< No use -#define STATE_DHCP_STOP 6 ///< Stop processing DHCP - -#define DHCP_FLAGSBROADCAST 0x8000 ///< The broadcast value of flags in @ref RIP_MSG -#define DHCP_FLAGSUNICAST 0x0000 ///< The unicast value of flags in @ref RIP_MSG - -/* DHCP message OP code */ -#define DHCP_BOOTREQUEST 1 ///< Request Message used in op of @ref RIP_MSG -#define DHCP_BOOTREPLY 2 ///< Reply Message used i op of @ref RIP_MSG - -/* DHCP message type */ -#define DHCP_DISCOVER 1 ///< DISCOVER message in OPT of @ref RIP_MSG -#define DHCP_OFFER 2 ///< OFFER message in OPT of @ref RIP_MSG -#define DHCP_REQUEST 3 ///< REQUEST message in OPT of @ref RIP_MSG -#define DHCP_DECLINE 4 ///< DECLINE message in OPT of @ref RIP_MSG -#define DHCP_ACK 5 ///< ACK message in OPT of @ref RIP_MSG -#define DHCP_NAK 6 ///< NACK message in OPT of @ref RIP_MSG -#define DHCP_RELEASE 7 ///< RELEASE message in OPT of @ref RIP_MSG. No use -#define DHCP_INFORM 8 ///< INFORM message in OPT of @ref RIP_MSG. No use - -#define DHCP_HTYPE10MB 1 ///< Used in type of @ref RIP_MSG -#define DHCP_HTYPE100MB 2 ///< Used in type of @ref RIP_MSG - -#define DHCP_HLENETHERNET 6 ///< Used in hlen of @ref RIP_MSG -#define DHCP_HOPS 0 ///< Used in hops of @ref RIP_MSG -#define DHCP_SECS 0 ///< Used in secs of @ref RIP_MSG - -#define INFINITE_LEASETIME 0xffffffff ///< Infinite lease time - -#define OPT_SIZE 312 /// Max OPT size of @ref RIP_MSG -#define RIP_MSG_SIZE (236+OPT_SIZE) /// Max size of @ref RIP_MSG - -/* - * @brief DHCP option and value (cf. RFC1533) - */ -enum -{ - padOption = 0, - subnetMask = 1, - timerOffset = 2, - routersOnSubnet = 3, - timeServer = 4, - nameServer = 5, - dns = 6, - logServer = 7, - cookieServer = 8, - lprServer = 9, - impressServer = 10, - resourceLocationServer = 11, - hostName = 12, - bootFileSize = 13, - meritDumpFile = 14, - domainName = 15, - swapServer = 16, - rootPath = 17, - extentionsPath = 18, - IPforwarding = 19, - nonLocalSourceRouting = 20, - policyFilter = 21, - maxDgramReasmSize = 22, - defaultIPTTL = 23, - pathMTUagingTimeout = 24, - pathMTUplateauTable = 25, - ifMTU = 26, - allSubnetsLocal = 27, - broadcastAddr = 28, - performMaskDiscovery = 29, - maskSupplier = 30, - performRouterDiscovery = 31, - routerSolicitationAddr = 32, - staticRoute = 33, - trailerEncapsulation = 34, - arpCacheTimeout = 35, - ethernetEncapsulation = 36, - tcpDefaultTTL = 37, - tcpKeepaliveInterval = 38, - tcpKeepaliveGarbage = 39, - nisDomainName = 40, - nisServers = 41, - ntpServers = 42, - vendorSpecificInfo = 43, - netBIOSnameServer = 44, - netBIOSdgramDistServer = 45, - netBIOSnodeType = 46, - netBIOSscope = 47, - xFontServer = 48, - xDisplayManager = 49, - dhcpRequestedIPaddr = 50, - dhcpIPaddrLeaseTime = 51, - dhcpOptionOverload = 52, - dhcpMessageType = 53, - dhcpServerIdentifier = 54, - dhcpParamRequest = 55, - dhcpMsg = 56, - dhcpMaxMsgSize = 57, - dhcpT1value = 58, - dhcpT2value = 59, - dhcpClassIdentifier = 60, - dhcpClientIdentifier = 61, - endOption = 255 -}; - -/* - * @brief DHCP message format - */ -typedef struct { - uint8_t op; ///< @ref DHCP_BOOTREQUEST or @ref DHCP_BOOTREPLY - uint8_t htype; ///< @ref DHCP_HTYPE10MB or @ref DHCP_HTYPE100MB - uint8_t hlen; ///< @ref DHCP_HLENETHERNET - uint8_t hops; ///< @ref DHCP_HOPS - uint32_t xid; ///< @ref DHCP_XID This increase one every DHCP transaction. - uint16_t secs; ///< @ref DHCP_SECS - uint16_t flags; ///< @ref DHCP_FLAGSBROADCAST or @ref DHCP_FLAGSUNICAST - uint8_t ciaddr[4]; ///< @ref Request IP to DHCP sever - uint8_t yiaddr[4]; ///< @ref Offered IP from DHCP server - uint8_t siaddr[4]; ///< No use - uint8_t giaddr[4]; ///< No use - uint8_t chaddr[16]; ///< DHCP client 6bytes MAC address. Others is filled to zero - uint8_t sname[64]; ///< No use - uint8_t file[128]; ///< No use - uint8_t OPT[OPT_SIZE]; ///< Option -} RIP_MSG; - - - -uint8_t DHCP_SOCKET; // Socket number for DHCP - -uint8_t DHCP_SIP[4]; // DHCP Server IP address - -// Network information from DHCP Server -uint8_t OLD_allocated_ip[4] = {0, }; // Previous IP address -uint8_t DHCP_allocated_ip[4] = {0, }; // IP address from DHCP -uint8_t DHCP_allocated_gw[4] = {0, }; // Gateway address from DHCP -uint8_t DHCP_allocated_sn[4] = {0, }; // Subnet mask from DHCP -uint8_t DHCP_allocated_dns[4] = {0, }; // DNS address from DHCP - - -int8_t dhcp_state = STATE_DHCP_INIT; // DHCP state -int8_t dhcp_retry_count = 0; - -uint32_t dhcp_lease_time = INFINITE_LEASETIME; -volatile uint32_t dhcp_tick_1s = 0; // unit 1 second -uint32_t dhcp_tick_next = DHCP_WAIT_TIME ; - -uint32_t DHCP_XID; // Any number - -RIP_MSG* pDHCPMSG; // Buffer pointer for DHCP processing - -uint8_t HOST_NAME[] = DCHP_HOST_NAME; - -uint8_t DHCP_CHADDR[6]; // DHCP Client MAC address. - -/* The default callback function */ -void default_ip_assign(void); -void default_ip_update(void); -void default_ip_conflict(void); - -/* Callback handler */ -void (*dhcp_ip_assign)(void) = default_ip_assign; /* handler to be called when the IP address from DHCP server is first assigned */ -void (*dhcp_ip_update)(void) = default_ip_update; /* handler to be called when the IP address from DHCP server is updated */ -void (*dhcp_ip_conflict)(void) = default_ip_conflict; /* handler to be called when the IP address from DHCP server is conflict */ - -void reg_dhcp_cbfunc(void(*ip_assign)(void), void(*ip_update)(void), void(*ip_conflict)(void)); - - -/* send DISCOVER message to DHCP server */ -void send_DHCP_DISCOVER(void); - -/* send REQEUST message to DHCP server */ -void send_DHCP_REQUEST(void); - -/* send DECLINE message to DHCP server */ -void send_DHCP_DECLINE(void); - -/* IP conflict check by sending ARP-request to leased IP and wait ARP-response. */ -int8_t check_DHCP_leasedIP(void); - -/* check the timeout in DHCP process */ -uint8_t check_DHCP_timeout(void); - -/* Intialize to timeout process. */ -void reset_DHCP_timeout(void); - -/* Parse message as OFFER and ACK and NACK from DHCP server.*/ -int8_t parseDHCPCMSG(void); - -/* The default handler of ip assign first */ -void default_ip_assign(void) -{ - setSIPR(DHCP_allocated_ip); - setSUBR(DHCP_allocated_sn); - setGAR (DHCP_allocated_gw); -} - -/* The default handler of ip changed */ -void default_ip_update(void) -{ - /* WIZchip Software Reset */ - setMR(MR_RST); - getMR(); // for delay - default_ip_assign(); - setSHAR(DHCP_CHADDR); -} - -/* The default handler of ip changed */ -void default_ip_conflict(void) -{ - // WIZchip Software Reset - setMR(MR_RST); - getMR(); // for delay - setSHAR(DHCP_CHADDR); -} - -/* register the call back func. */ -void reg_dhcp_cbfunc(void(*ip_assign)(void), void(*ip_update)(void), void(*ip_conflict)(void)) -{ - dhcp_ip_assign = default_ip_assign; - dhcp_ip_update = default_ip_update; - dhcp_ip_conflict = default_ip_conflict; - if(ip_assign) dhcp_ip_assign = ip_assign; - if(ip_update) dhcp_ip_update = ip_update; - if(ip_conflict) dhcp_ip_conflict = ip_conflict; -} - -/* make the common DHCP message */ -void makeDHCPMSG(void) -{ - uint8_t bk_mac[6]; - uint8_t* ptmp; - uint8_t i; - getSHAR(bk_mac); - pDHCPMSG->op = DHCP_BOOTREQUEST; - pDHCPMSG->htype = DHCP_HTYPE10MB; - pDHCPMSG->hlen = DHCP_HLENETHERNET; - pDHCPMSG->hops = DHCP_HOPS; - ptmp = (uint8_t*)(&pDHCPMSG->xid); - *(ptmp+0) = (uint8_t)((DHCP_XID & 0xFF000000) >> 24); - *(ptmp+1) = (uint8_t)((DHCP_XID & 0x00FF0000) >> 16); - *(ptmp+2) = (uint8_t)((DHCP_XID & 0x0000FF00) >> 8); - *(ptmp+3) = (uint8_t)((DHCP_XID & 0x000000FF) >> 0); - pDHCPMSG->secs = DHCP_SECS; - ptmp = (uint8_t*)(&pDHCPMSG->flags); - *(ptmp+0) = (uint8_t)((DHCP_FLAGSBROADCAST & 0xFF00) >> 8); - *(ptmp+1) = (uint8_t)((DHCP_FLAGSBROADCAST & 0x00FF) >> 0); - - pDHCPMSG->ciaddr[0] = 0; - pDHCPMSG->ciaddr[1] = 0; - pDHCPMSG->ciaddr[2] = 0; - pDHCPMSG->ciaddr[3] = 0; - - pDHCPMSG->yiaddr[0] = 0; - pDHCPMSG->yiaddr[1] = 0; - pDHCPMSG->yiaddr[2] = 0; - pDHCPMSG->yiaddr[3] = 0; - - pDHCPMSG->siaddr[0] = 0; - pDHCPMSG->siaddr[1] = 0; - pDHCPMSG->siaddr[2] = 0; - pDHCPMSG->siaddr[3] = 0; - - pDHCPMSG->giaddr[0] = 0; - pDHCPMSG->giaddr[1] = 0; - pDHCPMSG->giaddr[2] = 0; - pDHCPMSG->giaddr[3] = 0; - - pDHCPMSG->chaddr[0] = DHCP_CHADDR[0]; - pDHCPMSG->chaddr[1] = DHCP_CHADDR[1]; - pDHCPMSG->chaddr[2] = DHCP_CHADDR[2]; - pDHCPMSG->chaddr[3] = DHCP_CHADDR[3]; - pDHCPMSG->chaddr[4] = DHCP_CHADDR[4]; - pDHCPMSG->chaddr[5] = DHCP_CHADDR[5]; - - for (i = 6; i < 16; i++) pDHCPMSG->chaddr[i] = 0; - for (i = 0; i < 64; i++) pDHCPMSG->sname[i] = 0; - for (i = 0; i < 128; i++) pDHCPMSG->file[i] = 0; - - // MAGIC_COOKIE - pDHCPMSG->OPT[0] = (uint8_t)((MAGIC_COOKIE & 0xFF000000) >> 24); - pDHCPMSG->OPT[1] = (uint8_t)((MAGIC_COOKIE & 0x00FF0000) >> 16); - pDHCPMSG->OPT[2] = (uint8_t)((MAGIC_COOKIE & 0x0000FF00) >> 8); - pDHCPMSG->OPT[3] = (uint8_t) (MAGIC_COOKIE & 0x000000FF) >> 0; -} - -/* SEND DHCP DISCOVER */ -void send_DHCP_DISCOVER(void) -{ - uint16_t i; - uint8_t ip[4]; - uint16_t k = 0; - - makeDHCPMSG(); - - k = 4; // because MAGIC_COOKIE already made by makeDHCPMSG() - - // Option Request Param - pDHCPMSG->OPT[k++] = dhcpMessageType; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_DISCOVER; - - // Client identifier - pDHCPMSG->OPT[k++] = dhcpClientIdentifier; - pDHCPMSG->OPT[k++] = 0x07; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[0]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[1]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[2]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - - // host name - pDHCPMSG->OPT[k++] = hostName; - pDHCPMSG->OPT[k++] = 0; // fill zero length of hostname - for(i = 0 ; HOST_NAME[i] != 0; i++) - pDHCPMSG->OPT[k++] = HOST_NAME[i]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - pDHCPMSG->OPT[k - (i+3+1)] = i+3; // length of hostname - - pDHCPMSG->OPT[k++] = dhcpParamRequest; - pDHCPMSG->OPT[k++] = 0x06; // length of request - pDHCPMSG->OPT[k++] = subnetMask; - pDHCPMSG->OPT[k++] = routersOnSubnet; - pDHCPMSG->OPT[k++] = dns; - pDHCPMSG->OPT[k++] = domainName; - pDHCPMSG->OPT[k++] = dhcpT1value; - pDHCPMSG->OPT[k++] = dhcpT2value; - pDHCPMSG->OPT[k++] = endOption; - - for (i = k; i < OPT_SIZE; i++) pDHCPMSG->OPT[i] = 0; - - // send broadcasting packet - ip[0] = 255; - ip[1] = 255; - ip[2] = 255; - ip[3] = 255; - -#ifdef _DHCP_DEBUG_ - printf("> Send DHCP_DISCOVER\r\n"); -#endif - - sendto(DHCP_SOCKET, (uint8_t *)pDHCPMSG, RIP_MSG_SIZE, ip, DHCP_SERVER_PORT); -} - -/* SEND DHCP REQUEST */ -void send_DHCP_REQUEST(void) -{ - int i; - uint8_t ip[4]; - uint16_t k = 0; - - makeDHCPMSG(); - - if(dhcp_state == STATE_DHCP_LEASED || dhcp_state == STATE_DHCP_REREQUEST) - { - *((uint8_t*)(&pDHCPMSG->flags)) = ((DHCP_FLAGSUNICAST & 0xFF00)>> 8); - *((uint8_t*)(&pDHCPMSG->flags)+1) = (DHCP_FLAGSUNICAST & 0x00FF); - pDHCPMSG->ciaddr[0] = DHCP_allocated_ip[0]; - pDHCPMSG->ciaddr[1] = DHCP_allocated_ip[1]; - pDHCPMSG->ciaddr[2] = DHCP_allocated_ip[2]; - pDHCPMSG->ciaddr[3] = DHCP_allocated_ip[3]; - ip[0] = DHCP_SIP[0]; - ip[1] = DHCP_SIP[1]; - ip[2] = DHCP_SIP[2]; - ip[3] = DHCP_SIP[3]; - } - else - { - ip[0] = 255; - ip[1] = 255; - ip[2] = 255; - ip[3] = 255; - } - - k = 4; // because MAGIC_COOKIE already made by makeDHCPMSG() - - // Option Request Param. - pDHCPMSG->OPT[k++] = dhcpMessageType; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_REQUEST; - - pDHCPMSG->OPT[k++] = dhcpClientIdentifier; - pDHCPMSG->OPT[k++] = 0x07; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[0]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[1]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[2]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - - if(ip[3] == 255) // if(dchp_state == STATE_DHCP_LEASED || dchp_state == DHCP_REREQUEST_STATE) - { - pDHCPMSG->OPT[k++] = dhcpRequestedIPaddr; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[0]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[1]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[2]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[3]; - - pDHCPMSG->OPT[k++] = dhcpServerIdentifier; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_SIP[0]; - pDHCPMSG->OPT[k++] = DHCP_SIP[1]; - pDHCPMSG->OPT[k++] = DHCP_SIP[2]; - pDHCPMSG->OPT[k++] = DHCP_SIP[3]; - } - - // host name - pDHCPMSG->OPT[k++] = hostName; - pDHCPMSG->OPT[k++] = 0; // length of hostname - for(i = 0 ; HOST_NAME[i] != 0; i++) - pDHCPMSG->OPT[k++] = HOST_NAME[i]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - pDHCPMSG->OPT[k - (i+3+1)] = i+3; // length of hostname - - pDHCPMSG->OPT[k++] = dhcpParamRequest; - pDHCPMSG->OPT[k++] = 0x08; - pDHCPMSG->OPT[k++] = subnetMask; - pDHCPMSG->OPT[k++] = routersOnSubnet; - pDHCPMSG->OPT[k++] = dns; - pDHCPMSG->OPT[k++] = domainName; - pDHCPMSG->OPT[k++] = dhcpT1value; - pDHCPMSG->OPT[k++] = dhcpT2value; - pDHCPMSG->OPT[k++] = performRouterDiscovery; - pDHCPMSG->OPT[k++] = staticRoute; - pDHCPMSG->OPT[k++] = endOption; - - for (i = k; i < OPT_SIZE; i++) pDHCPMSG->OPT[i] = 0; - -#ifdef _DHCP_DEBUG_ - printf("> Send DHCP_REQUEST\r\n"); -#endif - - sendto(DHCP_SOCKET, (uint8_t *)pDHCPMSG, RIP_MSG_SIZE, ip, DHCP_SERVER_PORT); - -} - -/* SEND DHCP DHCPDECLINE */ -void send_DHCP_DECLINE(void) -{ - int i; - uint8_t ip[4]; - uint16_t k = 0; - - makeDHCPMSG(); - - k = 4; // because MAGIC_COOKIE already made by makeDHCPMSG() - - *((uint8_t*)(&pDHCPMSG->flags)) = ((DHCP_FLAGSUNICAST & 0xFF00)>> 8); - *((uint8_t*)(&pDHCPMSG->flags)+1) = (DHCP_FLAGSUNICAST & 0x00FF); - - // Option Request Param. - pDHCPMSG->OPT[k++] = dhcpMessageType; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_DECLINE; - - pDHCPMSG->OPT[k++] = dhcpClientIdentifier; - pDHCPMSG->OPT[k++] = 0x07; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[0]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[1]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[2]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - - pDHCPMSG->OPT[k++] = dhcpRequestedIPaddr; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[0]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[1]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[2]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[3]; - - pDHCPMSG->OPT[k++] = dhcpServerIdentifier; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_SIP[0]; - pDHCPMSG->OPT[k++] = DHCP_SIP[1]; - pDHCPMSG->OPT[k++] = DHCP_SIP[2]; - pDHCPMSG->OPT[k++] = DHCP_SIP[3]; - - pDHCPMSG->OPT[k++] = endOption; - - for (i = k; i < OPT_SIZE; i++) pDHCPMSG->OPT[i] = 0; - - //send broadcasting packet - ip[0] = 0xFF; - ip[1] = 0xFF; - ip[2] = 0xFF; - ip[3] = 0xFF; - -#ifdef _DHCP_DEBUG_ - printf("\r\n> Send DHCP_DECLINE\r\n"); -#endif - - sendto(DHCP_SOCKET, (uint8_t *)pDHCPMSG, RIP_MSG_SIZE, ip, DHCP_SERVER_PORT); -} - -/* PARSE REPLY pDHCPMSG */ -int8_t parseDHCPMSG(void) -{ - uint8_t svr_addr[6]; - uint16_t svr_port; - uint16_t len; - - uint8_t * p; - uint8_t * e; - uint8_t type; - uint8_t opt_len; - - if((len = getSn_RX_RSR(DHCP_SOCKET)) > 0) - { - len = recvfrom(DHCP_SOCKET, (uint8_t *)pDHCPMSG, len, svr_addr, &svr_port); - #ifdef _DHCP_DEBUG_ - printf("DHCP message : %d.%d.%d.%d(%d) %d received. \r\n",svr_addr[0],svr_addr[1],svr_addr[2], svr_addr[3],svr_port, len); - #endif - } - else return 0; - if (svr_port == DHCP_SERVER_PORT) { - // compare mac address - if ( (pDHCPMSG->chaddr[0] != DHCP_CHADDR[0]) || (pDHCPMSG->chaddr[1] != DHCP_CHADDR[1]) || - (pDHCPMSG->chaddr[2] != DHCP_CHADDR[2]) || (pDHCPMSG->chaddr[3] != DHCP_CHADDR[3]) || - (pDHCPMSG->chaddr[4] != DHCP_CHADDR[4]) || (pDHCPMSG->chaddr[5] != DHCP_CHADDR[5]) ) - return 0; - type = 0; - p = (uint8_t *)(&pDHCPMSG->op); - p = p + 240; // 240 = sizeof(RIP_MSG) + MAGIC_COOKIE size in RIP_MSG.opt - sizeof(RIP_MSG.opt) - e = p + (len - 240); - - while ( p < e ) { - - switch ( *p ) { - - case endOption : - p = e; // for break while(p < e) - break; - case padOption : - p++; - break; - case dhcpMessageType : - p++; - p++; - type = *p++; - break; - case subnetMask : - p++; - p++; - DHCP_allocated_sn[0] = *p++; - DHCP_allocated_sn[1] = *p++; - DHCP_allocated_sn[2] = *p++; - DHCP_allocated_sn[3] = *p++; - break; - case routersOnSubnet : - p++; - opt_len = *p++; - DHCP_allocated_gw[0] = *p++; - DHCP_allocated_gw[1] = *p++; - DHCP_allocated_gw[2] = *p++; - DHCP_allocated_gw[3] = *p++; - p = p + (opt_len - 4); - break; - case dns : - p++; - opt_len = *p++; - DHCP_allocated_dns[0] = *p++; - DHCP_allocated_dns[1] = *p++; - DHCP_allocated_dns[2] = *p++; - DHCP_allocated_dns[3] = *p++; - p = p + (opt_len - 4); - break; - case dhcpIPaddrLeaseTime : - p++; - opt_len = *p++; - dhcp_lease_time = *p++; - dhcp_lease_time = (dhcp_lease_time << 8) + *p++; - dhcp_lease_time = (dhcp_lease_time << 8) + *p++; - dhcp_lease_time = (dhcp_lease_time << 8) + *p++; - #ifdef _DHCP_DEBUG_ - dhcp_lease_time = 10; - #endif - break; - case dhcpServerIdentifier : - p++; - opt_len = *p++; - DHCP_SIP[0] = *p++; - DHCP_SIP[1] = *p++; - DHCP_SIP[2] = *p++; - DHCP_SIP[3] = *p++; - break; - default : - p++; - opt_len = *p++; - p += opt_len; - break; - } // switch - } // while - } // if - return type; -} - -uint8_t DHCP_run(void) -{ - uint8_t type; - uint8_t ret; - - if(dhcp_state == STATE_DHCP_STOP) return DHCP_STOPPED; - - if(getSn_SR(DHCP_SOCKET) != SOCK_UDP) - socket(DHCP_SOCKET, Sn_MR_UDP, DHCP_CLIENT_PORT, 0x00); - - ret = DHCP_RUNNING; - type = parseDHCPMSG(); - - switch ( dhcp_state ) { - case STATE_DHCP_INIT : - DHCP_allocated_ip[0] = 0; - DHCP_allocated_ip[1] = 0; - DHCP_allocated_ip[2] = 0; - DHCP_allocated_ip[3] = 0; - send_DHCP_DISCOVER(); - dhcp_state = STATE_DHCP_DISCOVER; - break; - case STATE_DHCP_DISCOVER : - if (type == DHCP_OFFER){ -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_OFFER\r\n"); -#endif - DHCP_allocated_ip[0] = pDHCPMSG->yiaddr[0]; - DHCP_allocated_ip[1] = pDHCPMSG->yiaddr[1]; - DHCP_allocated_ip[2] = pDHCPMSG->yiaddr[2]; - DHCP_allocated_ip[3] = pDHCPMSG->yiaddr[3]; - - send_DHCP_REQUEST(); - dhcp_state = STATE_DHCP_REQUEST; - } else ret = check_DHCP_timeout(); - break; - - case STATE_DHCP_REQUEST : - if (type == DHCP_ACK) { - -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_ACK\r\n"); -#endif - if (check_DHCP_leasedIP()) { - // Network info assignment from DHCP - dhcp_ip_assign(); - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_LEASED; - } else { - // IP address conflict occurred - reset_DHCP_timeout(); - dhcp_ip_conflict(); - dhcp_state = STATE_DHCP_INIT; - } - } else if (type == DHCP_NAK) { - -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_NACK\r\n"); -#endif - - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_DISCOVER; - } else ret = check_DHCP_timeout(); - break; - - case STATE_DHCP_LEASED : - ret = DHCP_IP_LEASED; - if ((dhcp_lease_time != INFINITE_LEASETIME) && ((dhcp_lease_time/2) < dhcp_tick_1s)) { - -#ifdef _DHCP_DEBUG_ - printf("> Maintains the IP address \r\n"); -#endif - - type = 0; - OLD_allocated_ip[0] = DHCP_allocated_ip[0]; - OLD_allocated_ip[1] = DHCP_allocated_ip[1]; - OLD_allocated_ip[2] = DHCP_allocated_ip[2]; - OLD_allocated_ip[3] = DHCP_allocated_ip[3]; - - DHCP_XID++; - - send_DHCP_REQUEST(); - - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_REREQUEST; - } - break; - - case STATE_DHCP_REREQUEST : - ret = DHCP_IP_LEASED; - if (type == DHCP_ACK) { - dhcp_retry_count = 0; - if (OLD_allocated_ip[0] != DHCP_allocated_ip[0] || - OLD_allocated_ip[1] != DHCP_allocated_ip[1] || - OLD_allocated_ip[2] != DHCP_allocated_ip[2] || - OLD_allocated_ip[3] != DHCP_allocated_ip[3]) - { - ret = DHCP_IP_CHANGED; - dhcp_ip_update(); - #ifdef _DHCP_DEBUG_ - printf(">IP changed.\r\n"); - #endif - - } - #ifdef _DHCP_DEBUG_ - else printf(">IP is continued.\r\n"); - #endif - reset_DHCP_timeout(); - dhcp_state = STATE_DHCP_LEASED; - } else if (type == DHCP_NAK) { - -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_NACK, Failed to maintain ip\r\n"); -#endif - - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_DISCOVER; - } else ret = check_DHCP_timeout(); - break; - default : - break; - } - - return ret; -} - -void DHCP_stop(void) -{ - close(DHCP_SOCKET); - dhcp_state = STATE_DHCP_STOP; -} - -uint8_t check_DHCP_timeout(void) -{ - uint8_t ret = DHCP_RUNNING; - - if (dhcp_retry_count < MAX_DHCP_RETRY) { - if (dhcp_tick_next < dhcp_tick_1s) { - - switch ( dhcp_state ) { - case STATE_DHCP_DISCOVER : -// printf("<> state : STATE_DHCP_DISCOVER\r\n"); - send_DHCP_DISCOVER(); - break; - - case STATE_DHCP_REQUEST : -// printf("<> state : STATE_DHCP_REQUEST\r\n"); - - send_DHCP_REQUEST(); - break; - - case STATE_DHCP_REREQUEST : -// printf("<> state : STATE_DHCP_REREQUEST\r\n"); - - send_DHCP_REQUEST(); - break; - - default : - break; - } - - dhcp_tick_1s = 0; - dhcp_tick_next = dhcp_tick_1s + DHCP_WAIT_TIME; - dhcp_retry_count++; - } - } else { // timeout occurred - - switch(dhcp_state) { - case STATE_DHCP_DISCOVER: - dhcp_state = STATE_DHCP_INIT; - ret = DHCP_FAILED; - break; - case STATE_DHCP_REQUEST: - case STATE_DHCP_REREQUEST: - send_DHCP_DISCOVER(); - dhcp_state = STATE_DHCP_DISCOVER; - break; - default : - break; - } - reset_DHCP_timeout(); - } - return ret; -} - -int8_t check_DHCP_leasedIP(void) -{ - uint8_t tmp; - int32_t ret; - - //WIZchip RCR value changed for ARP Timeout count control - tmp = getRCR(); - setRCR(0x03); - - // IP conflict detection : ARP request - ARP reply - // Broadcasting ARP Request for check the IP conflict using UDP sendto() function - ret = sendto(DHCP_SOCKET, (uint8_t *)"CHECK_IP_CONFLICT", 17, DHCP_allocated_ip, 5000); - - // RCR value restore - setRCR(tmp); - - if(ret == SOCKERR_TIMEOUT) { - // UDP send Timeout occurred : allocated IP address is unique, DHCP Success - -#ifdef _DHCP_DEBUG_ - printf("\r\n> Check leased IP - OK\r\n"); -#endif - - return 1; - } else { - // Received ARP reply or etc : IP address conflict occur, DHCP Failed - send_DHCP_DECLINE(); - - ret = dhcp_tick_1s; - while((dhcp_tick_1s - ret) < 2) ; // wait for 1s over; wait to complete to send DECLINE message; - - return 0; - } -} - -void DHCP_init(uint8_t s, uint8_t * buf) -{ - uint8_t zeroip[4] = {0,0,0,0}; - getSHAR(DHCP_CHADDR); - if((DHCP_CHADDR[0] | DHCP_CHADDR[1] | DHCP_CHADDR[2] | DHCP_CHADDR[3] | DHCP_CHADDR[4] | DHCP_CHADDR[5]) == 0x00) - { - // assign temporary mac address, you should be set SHAR before call this function. - DHCP_CHADDR[0] = 0x00; - DHCP_CHADDR[1] = 0x08; - DHCP_CHADDR[2] = 0xdc; - DHCP_CHADDR[3] = 0x00; - DHCP_CHADDR[4] = 0x00; - DHCP_CHADDR[5] = 0x00; - setSHAR(DHCP_CHADDR); - } - - DHCP_SOCKET = s; // SOCK_DHCP - pDHCPMSG = (RIP_MSG*)buf; - DHCP_XID = 0x12345678; - - // WIZchip Netinfo Clear - setSIPR(zeroip); - setSIPR(zeroip); - setGAR(zeroip); - - reset_DHCP_timeout(); - dhcp_state = STATE_DHCP_INIT; -} - - -/* Rset the DHCP timeout count and retry count. */ -void reset_DHCP_timeout(void) -{ - dhcp_tick_1s = 0; - dhcp_tick_next = DHCP_WAIT_TIME; - dhcp_retry_count = 0; -} - -void DHCP_time_handler(void) -{ - dhcp_tick_1s++; -} - -void getIPfromDHCP(uint8_t* ip) -{ - ip[0] = DHCP_allocated_ip[0]; - ip[1] = DHCP_allocated_ip[1]; - ip[2] = DHCP_allocated_ip[2]; - ip[3] = DHCP_allocated_ip[3]; -} - -void getGWfromDHCP(uint8_t* ip) -{ - ip[0] =DHCP_allocated_gw[0]; - ip[1] =DHCP_allocated_gw[1]; - ip[2] =DHCP_allocated_gw[2]; - ip[3] =DHCP_allocated_gw[3]; -} - -void getSNfromDHCP(uint8_t* ip) -{ - ip[0] = DHCP_allocated_sn[0]; - ip[1] = DHCP_allocated_sn[1]; - ip[2] = DHCP_allocated_sn[2]; - ip[3] = DHCP_allocated_sn[3]; -} - -void getDNSfromDHCP(uint8_t* ip) -{ - ip[0] = DHCP_allocated_dns[0]; - ip[1] = DHCP_allocated_dns[1]; - ip[2] = DHCP_allocated_dns[2]; - ip[3] = DHCP_allocated_dns[3]; -} - -uint32_t getDHCPLeasetime(void) -{ - return dhcp_lease_time; -} - - - - diff --git a/drivers/wiznet5k/internet/dhcp/dhcp.h b/drivers/wiznet5k/internet/dhcp/dhcp.h deleted file mode 100644 index ee154d506a..0000000000 --- a/drivers/wiznet5k/internet/dhcp/dhcp.h +++ /dev/null @@ -1,150 +0,0 @@ -//***************************************************************************** -// -//! \file dhcp.h -//! \brief DHCP APIs Header file. -//! \details Processig DHCP protocol as DISCOVER, OFFER, REQUEST, ACK, NACK and DECLINE. -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2013/11/18> 1st Release -//! <2012/12/20> V1.1.0 -//! 1. Move unreferenced DEFINE to dhcp.c -//! <2012/12/26> V1.1.1 -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** -#ifndef _DHCP_H_ -#define _DHCP_H_ - -/* - * @brief - * @details If you want to display debug & processing message, Define _DHCP_DEBUG_ - * @note If defined, it depends on - */ - -//#define _DHCP_DEBUG_ - -/* Retry to processing DHCP */ -#define MAX_DHCP_RETRY 2 ///< Maximum retry count -#define DHCP_WAIT_TIME 10 ///< Wait Time 10s - -/* UDP port numbers for DHCP */ -#define DHCP_SERVER_PORT 67 ///< DHCP server port number -#define DHCP_CLIENT_PORT 68 ///< DHCP client port number - -#define MAGIC_COOKIE 0x63825363 ///< Any number. You can be modified it any number - -#define DCHP_HOST_NAME "WIZnet\0" - -/* - * @brief return value of @ref DHCP_run() - */ -enum -{ - DHCP_FAILED = 0, ///< Processing Fail - DHCP_RUNNING, ///< Processing DHCP protocol - DHCP_IP_ASSIGN, ///< First Occupy IP from DHPC server (if cbfunc == null, act as default default_ip_assign) - DHCP_IP_CHANGED, ///< Change IP address by new IP address from DHCP (if cbfunc == null, act as default default_ip_update) - DHCP_IP_LEASED, ///< Stand by - DHCP_STOPPED ///< Stop processing DHCP protocol -}; - -/* - * @brief DHCP client initialization (outside of the main loop) - * @param s - socket number - * @param buf - buffer for processing DHCP message - */ -void DHCP_init(uint8_t s, uint8_t * buf); - -/* - * @brief DHCP 1s Tick Timer handler - * @note SHOULD BE register to your system 1s Tick timer handler - */ -void DHCP_time_handler(void); - -/* - * @brief Register call back function - * @param ip_assign - callback func when IP is assigned from DHCP server first - * @param ip_update - callback func when IP is changed - * @prarm ip_conflict - callback func when the assigned IP is conflict with others. - */ -void reg_dhcp_cbfunc(void(*ip_assign)(void), void(*ip_update)(void), void(*ip_conflict)(void)); - -/* - * @brief DHCP client in the main loop - * @return The value is as the follow \n - * @ref DHCP_FAILED \n - * @ref DHCP_RUNNING \n - * @ref DHCP_IP_ASSIGN \n - * @ref DHCP_IP_CHANGED \n - * @ref DHCP_IP_LEASED \n - * @ref DHCP_STOPPED \n - * - * @note This function is always called by you main task. - */ -uint8_t DHCP_run(void); - -/* - * @brief Stop DHCP processing - * @note If you want to restart. call DHCP_init() and DHCP_run() - */ -void DHCP_stop(void); - -/* Get Network information assigned from DHCP server */ -/* - * @brief Get IP address - * @param ip - IP address to be returned - */ -void getIPfromDHCP(uint8_t* ip); -/* - * @brief Get Gateway address - * @param ip - Gateway address to be returned - */ -void getGWfromDHCP(uint8_t* ip); -/* - * @brief Get Subnet mask value - * @param ip - Subnet mask to be returned - */ -void getSNfromDHCP(uint8_t* ip); -/* - * @brief Get DNS address - * @param ip - DNS address to be returned - */ -void getDNSfromDHCP(uint8_t* ip); - -/* - * @brief Get the leased time by DHCP sever - * @return unit 1s - */ -uint32_t getDHCPLeasetime(void); - -#endif /* _DHCP_H_ */ diff --git a/drivers/wiznet5k/internet/dns/dns.c b/drivers/wiznet5k/internet/dns/dns.c deleted file mode 100644 index c0ad570c00..0000000000 --- a/drivers/wiznet5k/internet/dns/dns.c +++ /dev/null @@ -1,566 +0,0 @@ -//***************************************************************************** -// -//! \file dns.c -//! \brief DNS APIs Implement file. -//! \details Send DNS query & Receive DNS reponse. \n -//! It depends on stdlib.h & string.h in ansi-c library -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.1.0 -//! 1. Remove secondary DNS server in DNS_run -//! If 1st DNS_run failed, call DNS_run with 2nd DNS again -//! 2. DNS_timerHandler -> DNS_time_handler -//! 3. Remove the unused define -//! 4. Integrated dns.h dns.c & dns_parse.h dns_parse.c into dns.h & dns.c -//! <2013/12/20> V1.1.0 -//! -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#include -#include - -//#include "Ethernet/socket.h" -//#include "Internet/DNS/dns.h" -#include "../../ethernet/socket.h" -#include "dns.h" - -#ifdef _DNS_DEBUG_ - #include -#endif - -#define INITRTT 2000L /* Initial smoothed response time */ -#define MAXCNAME (MAX_DOMAIN_NAME + (MAX_DOMAIN_NAME>>1)) /* Maximum amount of cname recursion */ - -#define TYPE_A 1 /* Host address */ -#define TYPE_NS 2 /* Name server */ -#define TYPE_MD 3 /* Mail destination (obsolete) */ -#define TYPE_MF 4 /* Mail forwarder (obsolete) */ -#define TYPE_CNAME 5 /* Canonical name */ -#define TYPE_SOA 6 /* Start of Authority */ -#define TYPE_MB 7 /* Mailbox name (experimental) */ -#define TYPE_MG 8 /* Mail group member (experimental) */ -#define TYPE_MR 9 /* Mail rename name (experimental) */ -#define TYPE_NULL 10 /* Null (experimental) */ -#define TYPE_WKS 11 /* Well-known sockets */ -#define TYPE_PTR 12 /* Pointer record */ -#define TYPE_HINFO 13 /* Host information */ -#define TYPE_MINFO 14 /* Mailbox information (experimental)*/ -#define TYPE_MX 15 /* Mail exchanger */ -#define TYPE_TXT 16 /* Text strings */ -#define TYPE_ANY 255 /* Matches any type */ - -#define CLASS_IN 1 /* The ARPA Internet */ - -/* Round trip timing parameters */ -#define AGAIN 8 /* Average RTT gain = 1/8 */ -#define LAGAIN 3 /* Log2(AGAIN) */ -#define DGAIN 4 /* Mean deviation gain = 1/4 */ -#define LDGAIN 2 /* log2(DGAIN) */ - -/* Header for all domain messages */ -struct dhdr -{ - uint16_t id; /* Identification */ - uint8_t qr; /* Query/Response */ -#define QUERY 0 -#define RESPONSE 1 - uint8_t opcode; -#define IQUERY 1 - uint8_t aa; /* Authoratative answer */ - uint8_t tc; /* Truncation */ - uint8_t rd; /* Recursion desired */ - uint8_t ra; /* Recursion available */ - uint8_t rcode; /* Response code */ -#define NO_ERROR 0 -#define FORMAT_ERROR 1 -#define SERVER_FAIL 2 -#define NAME_ERROR 3 -#define NOT_IMPL 4 -#define REFUSED 5 - uint16_t qdcount; /* Question count */ - uint16_t ancount; /* Answer count */ - uint16_t nscount; /* Authority (name server) count */ - uint16_t arcount; /* Additional record count */ -}; - - -uint8_t* pDNSMSG; // DNS message buffer -uint8_t DNS_SOCKET; // SOCKET number for DNS -uint16_t DNS_MSGID; // DNS message ID - -extern uint32_t HAL_GetTick(void); -uint32_t hal_sys_tick; - -/* converts uint16_t from network buffer to a host byte order integer. */ -uint16_t get16(uint8_t * s) -{ - uint16_t i; - i = *s++ << 8; - i = i + *s; - return i; -} - -/* copies uint16_t to the network buffer with network byte order. */ -uint8_t * put16(uint8_t * s, uint16_t i) -{ - *s++ = i >> 8; - *s++ = i; - return s; -} - - -/* - * CONVERT A DOMAIN NAME TO THE HUMAN-READABLE FORM - * - * Description : This function converts a compressed domain name to the human-readable form - * Arguments : msg - is a pointer to the reply message - * compressed - is a pointer to the domain name in reply message. - * buf - is a pointer to the buffer for the human-readable form name. - * len - is the MAX. size of buffer. - * Returns : the length of compressed message - */ -int parse_name(uint8_t * msg, uint8_t * compressed, char * buf, int16_t len) -{ - uint16_t slen; /* Length of current segment */ - uint8_t * cp; - int clen = 0; /* Total length of compressed name */ - int indirect = 0; /* Set if indirection encountered */ - int nseg = 0; /* Total number of segments in name */ - - cp = compressed; - - for (;;) - { - slen = *cp++; /* Length of this segment */ - - if (!indirect) clen++; - - if ((slen & 0xc0) == 0xc0) - { - if (!indirect) - clen++; - indirect = 1; - /* Follow indirection */ - cp = &msg[((slen & 0x3f)<<8) + *cp]; - slen = *cp++; - } - - if (slen == 0) /* zero length == all done */ - break; - - len -= slen + 1; - - if (len < 0) return -1; - - if (!indirect) clen += slen; - - while (slen-- != 0) *buf++ = (char)*cp++; - *buf++ = '.'; - nseg++; - } - - if (nseg == 0) - { - /* Root name; represent as single dot */ - *buf++ = '.'; - len--; - } - - *buf++ = '\0'; - len--; - - return clen; /* Length of compressed message */ -} - -/* - * PARSE QUESTION SECTION - * - * Description : This function parses the question record of the reply message. - * Arguments : msg - is a pointer to the reply message - * cp - is a pointer to the question record. - * Returns : a pointer the to next record. - */ -uint8_t * dns_question(uint8_t * msg, uint8_t * cp) -{ - int len; - char name[MAXCNAME]; - - len = parse_name(msg, cp, name, MAXCNAME); - - - if (len == -1) return 0; - - cp += len; - cp += 2; /* type */ - cp += 2; /* class */ - - return cp; -} - - -/* - * PARSE ANSER SECTION - * - * Description : This function parses the answer record of the reply message. - * Arguments : msg - is a pointer to the reply message - * cp - is a pointer to the answer record. - * Returns : a pointer the to next record. - */ -uint8_t * dns_answer(uint8_t * msg, uint8_t * cp, uint8_t * ip_from_dns) -{ - int len, type; - char name[MAXCNAME]; - - len = parse_name(msg, cp, name, MAXCNAME); - - if (len == -1) return 0; - - cp += len; - type = get16(cp); - cp += 2; /* type */ - cp += 2; /* class */ - cp += 4; /* ttl */ - cp += 2; /* len */ - - - switch (type) - { - case TYPE_A: - /* Just read the address directly into the structure */ - ip_from_dns[0] = *cp++; - ip_from_dns[1] = *cp++; - ip_from_dns[2] = *cp++; - ip_from_dns[3] = *cp++; - break; - case TYPE_CNAME: - case TYPE_MB: - case TYPE_MG: - case TYPE_MR: - case TYPE_NS: - case TYPE_PTR: - /* These types all consist of a single domain name */ - /* convert it to ASCII format */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - break; - case TYPE_HINFO: - len = *cp++; - cp += len; - - len = *cp++; - cp += len; - break; - case TYPE_MX: - cp += 2; - /* Get domain name of exchanger */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - break; - case TYPE_SOA: - /* Get domain name of name server */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - - /* Get domain name of responsible person */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - - cp += 4; - cp += 4; - cp += 4; - cp += 4; - cp += 4; - break; - case TYPE_TXT: - /* Just stash */ - break; - default: - /* Ignore */ - break; - } - - return cp; -} - -/* - * PARSE THE DNS REPLY - * - * Description : This function parses the reply message from DNS server. - * Arguments : dhdr - is a pointer to the header for DNS message - * buf - is a pointer to the reply message. - * len - is the size of reply message. - * Returns : -1 - Domain name length is too big - * 0 - Fail (Timeout or parse error) - * 1 - Success, - */ -int8_t parseDNSMSG(struct dhdr * pdhdr, uint8_t * pbuf, uint8_t * ip_from_dns) -{ - uint16_t tmp; - uint16_t i; - uint8_t * msg; - uint8_t * cp; - - msg = pbuf; - memset(pdhdr, 0, sizeof(*pdhdr)); - - pdhdr->id = get16(&msg[0]); - tmp = get16(&msg[2]); - if (tmp & 0x8000) pdhdr->qr = 1; - - pdhdr->opcode = (tmp >> 11) & 0xf; - - if (tmp & 0x0400) pdhdr->aa = 1; - if (tmp & 0x0200) pdhdr->tc = 1; - if (tmp & 0x0100) pdhdr->rd = 1; - if (tmp & 0x0080) pdhdr->ra = 1; - - pdhdr->rcode = tmp & 0xf; - pdhdr->qdcount = get16(&msg[4]); - pdhdr->ancount = get16(&msg[6]); - pdhdr->nscount = get16(&msg[8]); - pdhdr->arcount = get16(&msg[10]); - - - /* Now parse the variable length sections */ - cp = &msg[12]; - - /* Question section */ - for (i = 0; i < pdhdr->qdcount; i++) - { - cp = dns_question(msg, cp); - if(!cp) - { -#ifdef _DNS_DEBUG_ - printf("MAX_DOMAIN_NAME is too small, it should be redefined in dns.h\r\n"); -#endif - return -1; - } - } - - /* Answer section */ - for (i = 0; i < pdhdr->ancount; i++) - { - cp = dns_answer(msg, cp, ip_from_dns); - if(!cp) - { -#ifdef _DNS_DEBUG_ - printf("MAX_DOMAIN_NAME is too small, it should be redefined in dns.h\r\n"); -#endif - return -1; - } - - } - - /* Name server (authority) section */ - for (i = 0; i < pdhdr->nscount; i++) - { - ; - } - - /* Additional section */ - for (i = 0; i < pdhdr->arcount; i++) - { - ; - } - - if(pdhdr->rcode == 0) return 1; // No error - else return 0; -} - - -/* - * MAKE DNS QUERY MESSAGE - * - * Description : This function makes DNS query message. - * Arguments : op - Recursion desired - * name - is a pointer to the domain name. - * buf - is a pointer to the buffer for DNS message. - * len - is the MAX. size of buffer. - * Returns : the pointer to the DNS message. - */ -int16_t dns_makequery(uint16_t op, char * name, uint8_t * buf, uint16_t len) -{ - uint8_t *cp; - char *cp1; - char sname[MAXCNAME]; - char *dname; - uint16_t p; - uint16_t dlen; - - cp = buf; - - DNS_MSGID++; - cp = put16(cp, DNS_MSGID); - p = (op << 11) | 0x0100; /* Recursion desired */ - cp = put16(cp, p); - cp = put16(cp, 1); - cp = put16(cp, 0); - cp = put16(cp, 0); - cp = put16(cp, 0); - - strcpy(sname, name); - dname = sname; - dlen = strlen(dname); - for (;;) - { - /* Look for next dot */ - cp1 = strchr(dname, '.'); - - if (cp1 != NULL) len = cp1 - dname; /* More to come */ - else len = dlen; /* Last component */ - - *cp++ = len; /* Write length of component */ - if (len == 0) break; - - /* Copy component up to (but not including) dot */ - memcpy(cp, dname, len); - cp += len; - if (cp1 == NULL) - { - *cp++ = 0; /* Last one; write null and finish */ - break; - } - dname += len+1; - dlen -= len+1; - } - - cp = put16(cp, 0x0001); /* type */ - cp = put16(cp, 0x0001); /* class */ - - return ((int16_t)((uint32_t)(cp) - (uint32_t)(buf))); -} - -/* - * CHECK DNS TIMEOUT - * - * Description : This function check the DNS timeout - * Arguments : None. - * Returns : -1 - timeout occurred, 0 - timer over, but no timeout, 1 - no timer over, no timeout occur - * Note : timeout : retry count and timer both over. - */ - -int8_t check_DNS_timeout(void) -{ - static uint8_t retry_count; - - uint32_t tick = HAL_GetTick(); - if(tick - hal_sys_tick >= DNS_WAIT_TIME * 1000) - { - hal_sys_tick = tick; - if(retry_count >= MAX_DNS_RETRY) { - retry_count = 0; - return -1; // timeout occurred - } - retry_count++; - return 0; // timer over, but no timeout - } - - return 1; // no timer over, no timeout occur -} - - - -/* DNS CLIENT INIT */ -void DNS_init(uint8_t s, uint8_t * buf) -{ - DNS_SOCKET = s; // SOCK_DNS - pDNSMSG = buf; // User's shared buffer - DNS_MSGID = DNS_MSG_ID; -} - -/* DNS CLIENT RUN */ -int8_t DNS_run(uint8_t * dns_ip, uint8_t * name, uint8_t * ip_from_dns) -{ - int8_t ret; - struct dhdr dhp; - uint8_t ip[4]; - uint16_t len, port; - int8_t ret_check_timeout; - - hal_sys_tick = HAL_GetTick(); - - // Socket open - WIZCHIP_EXPORT(socket)(DNS_SOCKET, Sn_MR_UDP, 0, 0); - -#ifdef _DNS_DEBUG_ - printf("> DNS Query to DNS Server : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]); -#endif - - len = dns_makequery(0, (char *)name, pDNSMSG, MAX_DNS_BUF_SIZE); - WIZCHIP_EXPORT(sendto)(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN); - - while (1) - { - if ((len = getSn_RX_RSR(DNS_SOCKET)) > 0) - { - if (len > MAX_DNS_BUF_SIZE) len = MAX_DNS_BUF_SIZE; - len = WIZCHIP_EXPORT(recvfrom)(DNS_SOCKET, pDNSMSG, len, ip, &port); - #ifdef _DNS_DEBUG_ - printf("> Receive DNS message from %d.%d.%d.%d(%d). len = %d\r\n", ip[0], ip[1], ip[2], ip[3],port,len); - #endif - ret = parseDNSMSG(&dhp, pDNSMSG, ip_from_dns); - break; - } - // Check Timeout - ret_check_timeout = check_DNS_timeout(); - if (ret_check_timeout < 0) { - -#ifdef _DNS_DEBUG_ - printf("> DNS Server is not responding : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]); -#endif - return 0; // timeout occurred - } - else if (ret_check_timeout == 0) { - -#ifdef _DNS_DEBUG_ - printf("> DNS Timeout\r\n"); -#endif - WIZCHIP_EXPORT(sendto)(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN); - } - } - WIZCHIP_EXPORT(close)(DNS_SOCKET); - // Return value - // 0 > : failed / 1 - success - return ret; -} diff --git a/drivers/wiznet5k/internet/dns/dns.h b/drivers/wiznet5k/internet/dns/dns.h deleted file mode 100644 index de0039515e..0000000000 --- a/drivers/wiznet5k/internet/dns/dns.h +++ /dev/null @@ -1,96 +0,0 @@ -//***************************************************************************** -// -//! \file dns.h -//! \brief DNS APIs Header file. -//! \details Send DNS query & Receive DNS reponse. -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.1.0 -//! 1. Remove secondary DNS server in DNS_run -//! If 1st DNS_run failed, call DNS_run with 2nd DNS again -//! 2. DNS_timerHandler -> DNS_time_handler -//! 3. Move the no reference define to dns.c -//! 4. Integrated dns.h dns.c & dns_parse.h dns_parse.c into dns.h & dns.c -//! <2013/12/20> V1.1.0 -//! -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#ifndef _DNS_H_ -#define _DNS_H_ - -#include -/* - * @brief Define it for Debug & Monitor DNS processing. - * @note If defined, it depends on - */ - -//#define _DNS_DEBUG_ - -#define MAX_DNS_BUF_SIZE 256 ///< maximum size of DNS buffer. */ -/* - * @brief Maximum length of your queried Domain name - * @todo SHOULD BE defined it equal as or greater than your Domain name length + null character(1) - * @note SHOULD BE careful to stack overflow because it is allocated 1.5 times as MAX_DOMAIN_NAME in stack. - */ -#define MAX_DOMAIN_NAME 32 // for example "www.google.com" - -#define MAX_DNS_RETRY 2 ///< Requery Count -#define DNS_WAIT_TIME 4 ///< Wait response time. unit 1s. - -#define IPPORT_DOMAIN 53 ///< DNS server port number - -#define DNS_MSG_ID 0x1122 ///< ID for DNS message. You can be modified it any number -/* - * @brief DNS process initialize - * @param s : Socket number for DNS - * @param buf : Buffer for DNS message - */ -void DNS_init(uint8_t s, uint8_t * buf); - -/* - * @brief DNS process - * @details Send DNS query and receive DNS response - * @param dns_ip : DNS server ip address - * @param name : Domain name to be queried - * @param ip_from_dns : IP address from DNS server - * @return -1 : failed. @ref MAX_DOMIN_NAME is too small \n - * 0 : failed (Timeout or Parse error)\n - * 1 : success - * @note This function blocks until success or fail. max time = @ref MAX_DNS_RETRY * @ref DNS_WAIT_TIME - */ -int8_t DNS_run(uint8_t * dns_ip, uint8_t * name, uint8_t * ip_from_dns); - -#endif /* _DNS_H_ */ diff --git a/examples/SDdatalogger/README.md b/examples/SDdatalogger/README.md deleted file mode 100644 index 24e69c87e0..0000000000 --- a/examples/SDdatalogger/README.md +++ /dev/null @@ -1,4 +0,0 @@ -This is a SDdatalogger, to log data from the accelerometer to the SD-card. It also functions as card reader, so you can easily get the data on your PC. - -To run, put the boot.py, cardreader.py and datalogger.py files on either the flash or the SD-card of your pyboard. -Upon reset, the datalogger script is run and logs the data. If you press the user button after reset and hold it until the orange LED goes out, you enter the cardreader mode and the filesystem is mounted to your PC. diff --git a/examples/SDdatalogger/boot.py b/examples/SDdatalogger/boot.py deleted file mode 100644 index 4ac94bbaa4..0000000000 --- a/examples/SDdatalogger/boot.py +++ /dev/null @@ -1,25 +0,0 @@ -# boot.py -- runs on boot-up -# Let's you choose which script to run. -# > To run 'datalogger.py': -# * press reset and do nothing else -# > To run 'cardreader.py': -# * press reset -# * press user switch and hold until orange LED goes out - -import pyb - -pyb.LED(3).on() # indicate we are waiting for switch press -pyb.delay(2000) # wait for user to maybe press the switch -switch_value = pyb.Switch()() # sample the switch at end of delay -pyb.LED(3).off() # indicate that we finished waiting for the switch - -pyb.LED(4).on() # indicate that we are selecting the mode - -if switch_value: - pyb.usb_mode('VCP+MSC') - pyb.main('cardreader.py') # if switch was pressed, run this -else: - pyb.usb_mode('VCP+HID') - pyb.main('datalogger.py') # if switch wasn't pressed, run this - -pyb.LED(4).off() # indicate that we finished selecting the mode diff --git a/examples/SDdatalogger/cardreader.py b/examples/SDdatalogger/cardreader.py deleted file mode 100644 index 98d7a37925..0000000000 --- a/examples/SDdatalogger/cardreader.py +++ /dev/null @@ -1,2 +0,0 @@ -# cardread.py -# This is called when the user enters cardreader mode. It does nothing. diff --git a/examples/SDdatalogger/datalogger.py b/examples/SDdatalogger/datalogger.py deleted file mode 100644 index 0690c20bb9..0000000000 --- a/examples/SDdatalogger/datalogger.py +++ /dev/null @@ -1,33 +0,0 @@ -# datalogger.py -# Logs the data from the acceleromter to a file on the SD-card - -import pyb - -# creating objects -accel = pyb.Accel() -blue = pyb.LED(4) -switch = pyb.Switch() - -# loop -while True: - - # wait for interrupt - # this reduces power consumption while waiting for switch press - pyb.wfi() - - # start if switch is pressed - if switch(): - pyb.delay(200) # delay avoids detection of multiple presses - blue.on() # blue LED indicates file open - log = open('/sd/log.csv', 'w') # open file on SD (SD: '/sd/', flash: '/flash/) - - # until switch is pressed again - while not switch(): - t = pyb.millis() # get time - x, y, z = accel.filtered_xyz() # get acceleration data - log.write('{},{},{},{}\n'.format(t,x,y,z)) # write data to file - - # end after switch is pressed again - log.close() # close file - blue.off() # blue LED indicates file closed - pyb.delay(200) # delay avoids detection of multiple presses diff --git a/examples/accel_i2c.py b/examples/accel_i2c.py deleted file mode 100644 index d635e3ccc1..0000000000 --- a/examples/accel_i2c.py +++ /dev/null @@ -1,34 +0,0 @@ -# This is an example on how to access accelerometer on -# PyBoard directly using I2C bus. As such, it's more -# intended to be an I2C example, rather than accelerometer -# example. For the latter, using pyb.Accel class is -# much easier. - -from machine import Pin -from machine import I2C -import time - -# Accelerometer needs to be powered on first. Even -# though signal is called "AVDD", and there's separate -# "DVDD", without AVDD, it won't event talk on I2C bus. -accel_pwr = Pin("MMA_AVDD") -accel_pwr.value(1) - -i2c = I2C(1, baudrate=100000) -addrs = i2c.scan() -print("Scanning devices:", [hex(x) for x in addrs]) -if 0x4c not in addrs: - print("Accelerometer is not detected") - -ACCEL_ADDR = 0x4c -ACCEL_AXIS_X_REG = 0 -ACCEL_MODE_REG = 7 - -# Now activate measurements -i2c.mem_write(b"\x01", ACCEL_ADDR, ACCEL_MODE_REG) - -print("Try to move accelerometer and watch the values") -while True: - val = i2c.mem_read(1, ACCEL_ADDR, ACCEL_AXIS_X_REG) - print(val[0]) - time.sleep(1) diff --git a/examples/accellog.py b/examples/accellog.py deleted file mode 100644 index b1f289f8ad..0000000000 --- a/examples/accellog.py +++ /dev/null @@ -1,17 +0,0 @@ -# log the accelerometer values to a .csv-file on the SD-card - -import pyb - -accel = pyb.Accel() # create object of accelerometer -blue = pyb.LED(4) # create object of blue LED - -log = open('/sd/log.csv', 'w') # open file to write data - /sd/ is the SD-card, /flash/ the internal memory -blue.on() # turn on blue LED - -for i in range(100): # do 100 times (if the board is connected via USB, you can't write longer because the PC tries to open the filesystem which messes up your file.) - t = pyb.millis() # get time since reset - x, y, z = accel.filtered_xyz() # get acceleration data - log.write('{},{},{},{}\n'.format(t,x,y,z)) # write data to file - -log.close() # close file -blue.off() # turn off LED diff --git a/examples/asmled.py b/examples/asmled.py deleted file mode 100644 index 917d9ba03c..0000000000 --- a/examples/asmled.py +++ /dev/null @@ -1,85 +0,0 @@ -# flash LED #1 using inline assembler -# this version is overly verbose and uses word stores -@micropython.asm_thumb -def flash_led(r0): - movw(r1, (stm.GPIOA + stm.GPIO_BSRRL) & 0xffff) - movt(r1, ((stm.GPIOA + stm.GPIO_BSRRL) >> 16) & 0x7fff) - movw(r2, 1 << 13) - movt(r2, 0) - movw(r3, 0) - movt(r3, 1 << 13) - - b(loop_entry) - - label(loop1) - - # turn LED on - str(r2, [r1, 0]) - - # delay for a bit - movw(r4, 5599900 & 0xffff) - movt(r4, (5599900 >> 16) & 0xffff) - label(delay_on) - sub(r4, r4, 1) - cmp(r4, 0) - bgt(delay_on) - - # turn LED off - str(r3, [r1, 0]) - - # delay for a bit - movw(r4, 5599900 & 0xffff) - movt(r4, (5599900 >> 16) & 0xffff) - label(delay_off) - sub(r4, r4, 1) - cmp(r4, 0) - bgt(delay_off) - - # loop r0 times - sub(r0, r0, 1) - label(loop_entry) - cmp(r0, 0) - bgt(loop1) - -# flash LED #2 using inline assembler -# this version uses half-word sortes, and the convenience assembler operation 'movwt' -@micropython.asm_thumb -def flash_led_v2(r0): - # get the GPIOA address in r1 - movwt(r1, stm.GPIOA) - - # get the bit mask for PA14 (the pin LED #2 is on) - movw(r2, 1 << 14) - - b(loop_entry) - - label(loop1) - - # turn LED on - strh(r2, [r1, stm.GPIO_BSRRL]) - - # delay for a bit - movwt(r4, 5599900) - label(delay_on) - sub(r4, r4, 1) - cmp(r4, 0) - bgt(delay_on) - - # turn LED off - strh(r2, [r1, stm.GPIO_BSRRH]) - - # delay for a bit - movwt(r4, 5599900) - label(delay_off) - sub(r4, r4, 1) - cmp(r4, 0) - bgt(delay_off) - - # loop r0 times - sub(r0, r0, 1) - label(loop_entry) - cmp(r0, 0) - bgt(loop1) - -flash_led(5) -flash_led_v2(5) diff --git a/examples/asmsum.py b/examples/asmsum.py deleted file mode 100644 index 07e71c7384..0000000000 --- a/examples/asmsum.py +++ /dev/null @@ -1,57 +0,0 @@ -@micropython.asm_thumb -def asm_sum_words(r0, r1): - - # r0 = len - # r1 = ptr - # r2 = sum - # r3 = dummy - mov(r2, 0) - - b(loop_entry) - - label(loop1) - ldr(r3, [r1, 0]) - add(r2, r2, r3) - - add(r1, r1, 4) - sub(r0, r0, 1) - - label(loop_entry) - cmp(r0, 0) - bgt(loop1) - - mov(r0, r2) - -@micropython.asm_thumb -def asm_sum_bytes(r0, r1): - - # r0 = len - # r1 = ptr - # r2 = sum - # r3 = dummy - mov(r2, 0) - - b(loop_entry) - - label(loop1) - ldrb(r3, [r1, 0]) - add(r2, r2, r3) - - add(r1, r1, 1) - sub(r0, r0, 1) - - label(loop_entry) - cmp(r0, 0) - bgt(loop1) - - mov(r0, r2) - -import array - -b = array.array('l', (100, 200, 300, 400)) -n = asm_sum_words(len(b), b) -print(b, n) - -b = array.array('b', (10, 20, 30, 40, 50, 60, 70, 80)) -n = asm_sum_bytes(len(b), b) -print(b, n) diff --git a/examples/conwaylife.py b/examples/conwaylife.py deleted file mode 100644 index 323f42e850..0000000000 --- a/examples/conwaylife.py +++ /dev/null @@ -1,46 +0,0 @@ -#import essential libraries -import pyb - -lcd = pyb.LCD('x') -lcd.light(1) - -# do 1 iteration of Conway's Game of Life -def conway_step(): - for x in range(128): # loop over x coordinates - for y in range(32): # loop over y coordinates - # count number of neighbours - num_neighbours = (lcd.get(x - 1, y - 1) + - lcd.get(x, y - 1) + - lcd.get(x + 1, y - 1) + - lcd.get(x - 1, y) + - lcd.get(x + 1, y) + - lcd.get(x + 1, y + 1) + - lcd.get(x, y + 1) + - lcd.get(x - 1, y + 1)) - - # check if the centre cell is alive or not - self = lcd.get(x, y) - - # apply the rules of life - if self and not (2 <= num_neighbours <= 3): - lcd.pixel(x, y, 0) # not enough, or too many neighbours: cell dies - elif not self and num_neighbours == 3: - lcd.pixel(x, y, 1) # exactly 3 neighbours around an empty cell: cell is born - -# randomise the start -def conway_rand(): - lcd.fill(0) # clear the LCD - for x in range(128): # loop over x coordinates - for y in range(32): # loop over y coordinates - lcd.pixel(x, y, pyb.rng() & 1) # set the pixel randomly - -# loop for a certain number of frames, doing iterations of Conway's Game of Life -def conway_go(num_frames): - for i in range(num_frames): - conway_step() # do 1 iteration - lcd.show() # update the LCD - pyb.delay(50) - -# testing -conway_rand() -conway_go(100) diff --git a/examples/embedding/Makefile b/examples/embedding/Makefile deleted file mode 100644 index 99f239a7c5..0000000000 --- a/examples/embedding/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -MPTOP = ../.. -CFLAGS = -std=c99 -I. -I$(MPTOP) -DNO_QSTR -LDFLAGS = -L. - -hello-embed: hello-embed.o -lmicropython - --lmicropython: - $(MAKE) -f $(MPTOP)/examples/embedding/Makefile.upylib MPTOP=$(MPTOP) diff --git a/examples/embedding/Makefile.upylib b/examples/embedding/Makefile.upylib deleted file mode 100644 index a9b6535170..0000000000 --- a/examples/embedding/Makefile.upylib +++ /dev/null @@ -1,199 +0,0 @@ -MPTOP = ../.. --include mpconfigport.mk -include $(MPTOP)/py/mkenv.mk - -all: lib - -# OS name, for simple autoconfig -UNAME_S := $(shell uname -s) - -# include py core make definitions -include $(MPTOP)/py/py.mk - -INC += -I. -INC += -I.. -INC += -I$(MPTOP) -INC += -I$(MPTOP)/unix -INC += -I$(BUILD) - -# compiler settings -CWARN = -Wall -Werror -CWARN += -Wpointer-arith -Wuninitialized -CFLAGS = $(INC) $(CWARN) -std=gnu99 -DUNIX $(CFLAGS_MOD) $(COPT) $(CFLAGS_EXTRA) - -# Debugging/Optimization -ifdef DEBUG -CFLAGS += -g -COPT = -O0 -else -COPT = -Os #-DNDEBUG -# _FORTIFY_SOURCE is a feature in gcc/glibc which is intended to provide extra -# security for detecting buffer overflows. Some distros (Ubuntu at the very least) -# have it enabled by default. -# -# gcc already optimizes some printf calls to call puts and/or putchar. When -# _FORTIFY_SOURCE is enabled and compiling with -O1 or greater, then some -# printf calls will also be optimized to call __printf_chk (in glibc). Any -# printfs which get redirected to __printf_chk are then no longer synchronized -# with printfs that go through mp_printf. -# -# In MicroPython, we don't want to use the runtime library's printf but rather -# go through mp_printf, so that stdout is properly tied into streams, etc. -# This means that we either need to turn off _FORTIFY_SOURCE or provide our -# own implementation of __printf_chk. We've chosen to turn off _FORTIFY_SOURCE. -# It should also be noted that the use of printf in MicroPython is typically -# quite limited anyways (primarily for debug and some error reporting, etc -# in the unix version). -# -# Information about _FORTIFY_SOURCE seems to be rather scarce. The best I could -# find was this: https://securityblog.redhat.com/2014/03/26/fortify-and-you/ -# Original patchset was introduced by -# https://gcc.gnu.org/ml/gcc-patches/2004-09/msg02055.html . -# -# Turning off _FORTIFY_SOURCE is only required when compiling with -O1 or greater -CFLAGS += -U _FORTIFY_SOURCE -endif - -# On OSX, 'gcc' is a symlink to clang unless a real gcc is installed. -# The unix port of MicroPython on OSX must be compiled with clang, -# while cross-compile ports require gcc, so we test here for OSX and -# if necessary override the value of 'CC' set in py/mkenv.mk -ifeq ($(UNAME_S),Darwin) -CC = clang -# Use clang syntax for map file -LDFLAGS_ARCH = -Wl,-map,$@.map -else -# Use gcc syntax for map file -LDFLAGS_ARCH = -Wl,-Map=$@.map,--cref -endif -LDFLAGS = $(LDFLAGS_MOD) $(LDFLAGS_ARCH) -lm $(LDFLAGS_EXTRA) - -ifeq ($(MICROPY_FORCE_32BIT),1) -# Note: you may need to install i386 versions of dependency packages, -# starting with linux-libc-dev:i386 -ifeq ($(MICROPY_PY_FFI),1) -ifeq ($(UNAME_S),Linux) -CFLAGS_MOD += -I/usr/include/i686-linux-gnu -endif -endif -endif - -ifeq ($(MICROPY_USE_READLINE),1) -INC += -I../lib/mp-readline -CFLAGS_MOD += -DMICROPY_USE_READLINE=1 -LIB_SRC_C_EXTRA += mp-readline/readline.c -endif -ifeq ($(MICROPY_USE_READLINE),2) -CFLAGS_MOD += -DMICROPY_USE_READLINE=2 -LDFLAGS_MOD += -lreadline -# the following is needed for BSD -#LDFLAGS_MOD += -ltermcap -endif -ifeq ($(MICROPY_PY_TIME),1) -CFLAGS_MOD += -DMICROPY_PY_TIME=1 -SRC_MOD += modtime.c -endif -ifeq ($(MICROPY_PY_TERMIOS),1) -CFLAGS_MOD += -DMICROPY_PY_TERMIOS=1 -SRC_MOD += modtermios.c -endif -ifeq ($(MICROPY_PY_SOCKET),1) -CFLAGS_MOD += -DMICROPY_PY_SOCKET=1 -SRC_MOD += modsocket.c -endif - -ifeq ($(MICROPY_PY_FFI),1) - -ifeq ($(MICROPY_STANDALONE),1) -LIBFFI_CFLAGS_MOD := -I$(shell ls -1d ../lib/libffi/build_dir/out/lib/libffi-*/include) - ifeq ($(MICROPY_FORCE_32BIT),1) - LIBFFI_LDFLAGS_MOD = ../lib/libffi/build_dir/out/lib32/libffi.a - else - LIBFFI_LDFLAGS_MOD = ../lib/libffi/build_dir/out/lib/libffi.a - endif -else -LIBFFI_CFLAGS_MOD := $(shell pkg-config --cflags libffi) -LIBFFI_LDFLAGS_MOD := $(shell pkg-config --libs libffi) -endif - -ifeq ($(UNAME_S),Linux) -LIBFFI_LDFLAGS_MOD += -ldl -endif - -CFLAGS_MOD += $(LIBFFI_CFLAGS_MOD) -DMICROPY_PY_FFI=1 -LDFLAGS_MOD += $(LIBFFI_LDFLAGS_MOD) -SRC_MOD += modffi.c -endif - -MAIN_C = main.c - -# source files -SRC_C = $(addprefix $(MPTOP)/unix/,\ - $(MAIN_C) \ - gccollect.c \ - unix_mphal.c \ - input.c \ - file.c \ - modmachine.c \ - modos.c \ - moduselect.c \ - alloc.c \ - coverage.c \ - fatfs_port.c \ - $(SRC_MOD) \ - ) - -LIB_SRC_C = $(addprefix lib/,\ - $(LIB_SRC_C_EXTRA) \ - utils/printf.c \ - timeutils/timeutils.c \ - ) - -ifeq ($(MICROPY_FATFS),1) -LIB_SRC_C += $(addprefix lib/,\ - fatfs/ff.c \ - fatfs/option/ccsbcs.c \ - ) -endif - -OBJ = $(PY_O) -OBJ += $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(LIB_SRC_C:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(STMHAL_SRC_C:.c=.o)) - -# List of sources for qstr extraction -SRC_QSTR += $(SRC_C) $(LIB_SRC_C) -# Append any auto-generated sources that are needed by sources listed in -# SRC_QSTR -SRC_QSTR_AUTO_DEPS += - -include $(MPTOP)/py/mkrules.mk - -# Value of configure's --host= option (required for cross-compilation). -# Deduce it from CROSS_COMPILE by default, but can be overridden. -ifneq ($(CROSS_COMPILE),) -CROSS_COMPILE_HOST = --host=$(patsubst %-,%,$(CROSS_COMPILE)) -else -CROSS_COMPILE_HOST = -endif - -deplibs: libffi axtls - -# install-exec-recursive & install-data-am targets are used to avoid building -# docs and depending on makeinfo -libffi: - cd ../lib/libffi; git clean -d -x -f - cd ../lib/libffi; ./autogen.sh - mkdir -p ../lib/libffi/build_dir; cd ../lib/libffi/build_dir; \ - ../configure $(CROSS_COMPILE_HOST) --prefix=$$PWD/out CC="$(CC)" CXX="$(CXX)" LD="$(LD)"; \ - make install-exec-recursive; make -C include install-data-am - -axtls: ../lib/axtls/README - cd ../lib/axtls; cp config/upyconfig config/.config - cd ../lib/axtls; make oldconfig -B - cd ../lib/axtls; make clean - cd ../lib/axtls; make all CC="$(CC)" LD="$(LD)" - -../lib/axtls/README: - @echo "You cloned without --recursive, fetching submodules for you." - (cd ..; git submodule update --init --recursive) diff --git a/examples/embedding/README.md b/examples/embedding/README.md deleted file mode 100644 index 804dfede6f..0000000000 --- a/examples/embedding/README.md +++ /dev/null @@ -1,67 +0,0 @@ -Example of embedding MicroPython in a standlone C application -============================================================= - -This directory contains a (very simple!) example of how to embed a MicroPython -in an existing C application. - -A C application is represented by the file hello-embed.c. It executes a simple -Python statement which prints to the standard output. - - -Building the example --------------------- - -Building the example is as simple as running: - - make - -It's worth to trace what's happening behind the scenes though: - -1. As a first step, a MicroPython library is built. This is handled by a -separate makefile, Makefile.upylib. It is more or less complex, but the -good news is that you won't need to change anything in it, just use it -as is, the main Makefile shows how. What may require editing though is -a MicroPython configuration file. MicroPython is highly configurable, so -you would need to build a library suiting your application well, while -not bloating its size. Check the options in the file "mpconfigport.h". -Included is a copy of the "minimal" Unix port, which should be a good start -for minimal embedding. For the list of all available options, see -py/mpconfig.h. - -2. Once the MicroPython library is built, your application is compiled -and linked it. The main Makefile is very simple and shows that the changes -you would need to do to your application's Makefile (or other build -configuration) are also simple: - -a) You would need to use C99 standard (you're using this 15+ years old -standard already, not a 25+ years old one, right?). - -b) You need to provide a path to MicroPython's top-level dir, for includes. - -c) You need to include -DNO_QSTR compile-time flag. - -d) Otherwise, just link with the MicroPython library produced in step 1. - - -Out of tree build ------------------ - -This example is set up to work out of the box, being part of the MicroPython -tree. Your application of course will be outside of its tree, but the -only thing you need to do is to pass MPTOP variable pointing to -MicroPython directory to both Makefiles (in this example, the main Makefile -automatically passes it to Makefile.upylib; in your own Makefile, don't forget -to use a suitable value). - -A practical way to embed MicroPython in your application is to include it -as a git submodule. Suppose you included it as libs/micropython. Then in -your main Makefile you would have something like: - -~~~ -MPTOP = libs/micropython - -my_app: $(MY_OBJS) -lmicropython - --lmicropython: - $(MAKE) -f $(MPTOP)/examples/embedding/Makefile.upylib MPTOP=$(MPTOP) -~~~ diff --git a/examples/embedding/hello-embed.c b/examples/embedding/hello-embed.c deleted file mode 100644 index 3473e5bcd8..0000000000 --- a/examples/embedding/hello-embed.c +++ /dev/null @@ -1,74 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2016 Paul Sokolovsky - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include -#include -#include - -#include "py/compile.h" -#include "py/runtime.h" -#include "py/gc.h" -#include "py/stackctrl.h" - -static char heap[16384]; - -mp_obj_t execute_from_str(const char *str) { - nlr_buf_t nlr; - if (nlr_push(&nlr) == 0) { - mp_lexer_t *lex = mp_lexer_new_from_str_len(0/*MP_QSTR_*/, str, strlen(str), false); - mp_parse_tree_t pt = mp_parse(lex, MP_PARSE_FILE_INPUT); - mp_obj_t module_fun = mp_compile(&pt, lex->source_name, MP_EMIT_OPT_NONE, false); - mp_call_function_0(module_fun); - nlr_pop(); - return 0; - } else { - // uncaught exception - return (mp_obj_t)nlr.ret_val; - } -} - -int main() { - // Initialized stack limit - mp_stack_set_limit(40000 * (BYTES_PER_WORD / 4)); - // Initialize heap - gc_init(heap, heap + sizeof(heap)); - // Initialize interpreter - mp_init(); - - const char str[] = "print('Hello world of easy embedding!')"; - if (execute_from_str(str)) { - printf("Error\n"); - } -} - -uint mp_import_stat(const char *path) { - return MP_IMPORT_STAT_NO_EXIST; -} - -void nlr_jump_fail(void *val) { - printf("FATAL: uncaught NLR %p\n", val); - exit(1); -} diff --git a/examples/embedding/mpconfigport.h b/examples/embedding/mpconfigport.h deleted file mode 120000 index 142e5d6f43..0000000000 --- a/examples/embedding/mpconfigport.h +++ /dev/null @@ -1 +0,0 @@ -mpconfigport_minimal.h \ No newline at end of file diff --git a/examples/embedding/mpconfigport_minimal.h b/examples/embedding/mpconfigport_minimal.h deleted file mode 100644 index fa52be4ad7..0000000000 --- a/examples/embedding/mpconfigport_minimal.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2015 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -// options to control how MicroPython is built - -#define MICROPY_ALLOC_PATH_MAX (PATH_MAX) -#define MICROPY_ENABLE_GC (1) -#define MICROPY_ENABLE_FINALISER (0) -#define MICROPY_STACK_CHECK (0) -#define MICROPY_COMP_CONST (0) -#define MICROPY_MEM_STATS (0) -#define MICROPY_DEBUG_PRINTERS (0) -#define MICROPY_READER_POSIX (1) -#define MICROPY_KBD_EXCEPTION (1) -#define MICROPY_HELPER_REPL (1) -#define MICROPY_HELPER_LEXER_UNIX (1) -#define MICROPY_ENABLE_SOURCE_LINE (0) -#define MICROPY_ERROR_REPORTING (MICROPY_ERROR_REPORTING_TERSE) -#define MICROPY_WARNINGS (0) -#define MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF (0) -#define MICROPY_FLOAT_IMPL (MICROPY_FLOAT_IMPL_NONE) -#define MICROPY_LONGINT_IMPL (MICROPY_LONGINT_IMPL_NONE) -#define MICROPY_STREAMS_NON_BLOCK (0) -#define MICROPY_OPT_COMPUTED_GOTO (0) -#define MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE (0) -#define MICROPY_CAN_OVERRIDE_BUILTINS (0) -#define MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG (0) -#define MICROPY_CPYTHON_COMPAT (0) -#define MICROPY_PY_BUILTINS_BYTEARRAY (0) -#define MICROPY_PY_BUILTINS_MEMORYVIEW (0) -#define MICROPY_PY_BUILTINS_COMPILE (0) -#define MICROPY_PY_BUILTINS_ENUMERATE (0) -#define MICROPY_PY_BUILTINS_FILTER (0) -#define MICROPY_PY_BUILTINS_FROZENSET (0) -#define MICROPY_PY_BUILTINS_REVERSED (0) -#define MICROPY_PY_BUILTINS_SET (0) -#define MICROPY_PY_BUILTINS_SLICE (0) -#define MICROPY_PY_BUILTINS_STR_UNICODE (0) -#define MICROPY_PY_BUILTINS_PROPERTY (0) -#define MICROPY_PY_BUILTINS_MIN_MAX (0) -#define MICROPY_PY___FILE__ (0) -#define MICROPY_PY_MICROPYTHON_MEM_INFO (0) -#define MICROPY_PY_GC (0) -#define MICROPY_PY_GC_COLLECT_RETVAL (0) -#define MICROPY_PY_ARRAY (0) -#define MICROPY_PY_COLLECTIONS (0) -#define MICROPY_PY_MATH (0) -#define MICROPY_PY_CMATH (0) -#define MICROPY_PY_IO (0) -#define MICROPY_PY_IO_FILEIO (0) -#define MICROPY_PY_STRUCT (0) -#define MICROPY_PY_SYS (1) -#define MICROPY_PY_SYS_EXIT (0) -#define MICROPY_PY_SYS_PLATFORM "linux" -#define MICROPY_PY_SYS_MAXSIZE (0) -#define MICROPY_PY_SYS_STDFILES (0) -#define MICROPY_PY_CMATH (0) -#define MICROPY_PY_UCTYPES (0) -#define MICROPY_PY_UZLIB (0) -#define MICROPY_PY_UJSON (0) -#define MICROPY_PY_URE (0) -#define MICROPY_PY_UHEAPQ (0) -#define MICROPY_PY_UHASHLIB (0) -#define MICROPY_PY_UBINASCII (0) - -extern const struct _mp_obj_module_t mp_module_os; - -#define MICROPY_PORT_BUILTIN_MODULES \ - { MP_ROM_QSTR(MP_QSTR_uos), MP_ROM_PTR(&mp_module_os) }, \ - -#define MICROPY_PORT_ROOT_POINTERS \ - -////////////////////////////////////////// -// Do not change anything beyond this line -////////////////////////////////////////// - -// Define to 1 to use undertested inefficient GC helper implementation -// (if more efficient arch-specific one is not available). -#ifndef MICROPY_GCREGS_SETJMP - #ifdef __mips__ - #define MICROPY_GCREGS_SETJMP (1) - #else - #define MICROPY_GCREGS_SETJMP (0) - #endif -#endif - -// type definitions for the specific machine - -#ifdef __LP64__ -typedef long mp_int_t; // must be pointer size -typedef unsigned long mp_uint_t; // must be pointer size -#else -// These are definitions for machines where sizeof(int) == sizeof(void*), -// regardless for actual size. -typedef int mp_int_t; // must be pointer size -typedef unsigned int mp_uint_t; // must be pointer size -#endif - -// Cannot include , as it may lead to symbol name clashes -#if _FILE_OFFSET_BITS == 64 && !defined(__LP64__) -typedef long long mp_off_t; -#else -typedef long mp_off_t; -#endif - -// We need to provide a declaration/definition of alloca() -#ifdef __FreeBSD__ -#include -#else -#include -#endif diff --git a/examples/hwapi/README.md b/examples/hwapi/README.md deleted file mode 100644 index 1992eb6609..0000000000 --- a/examples/hwapi/README.md +++ /dev/null @@ -1,126 +0,0 @@ -This directory shows the best practices for using MicroPython hardware API -(`machine` module). `machine` module strives to provide consistent API -across various boards, with the aim to enable writing portable applications, -which would work from a board to board, from a system to another systems. -This is inherently a hard problem, because hardware is different from one -board type to another, and even from examplar of board to another. For -example, if your app requires an external LED, one user may connect it -to one GPIO pin, while another user may find it much more convinient to -use another pin. This of course applies to relays, buzzers, sensors, etc. - -With complications above in mind, it's still possible to write portable -applications by using "low[est] denominator" subset of hardware API and -following simple rules outlined below. The applications won't be able -to rely on advanced hardware capabilities of a particular board and -will be limited to generic capabilities, but it's still possible to -write many useful applications in such a way, with the obvious benefit of -"write once - run everywhere" approach (only configuration for a particular -board is required). - -The key to this approach is splitting your application into (at least) -2 parts: - -* main application logic -* hardware configuration - -The key point is that hardware configuration should be a separate file -(module in Python terms). A good name would be `hwconfig.py`, and that's -how we'll call it from now on. Another key point is that main application -should never instantiate (construct) hardware objects directly. Instead, -they should be defined in `hwconfig.py`, and main application should -import and reference hardware objects via this module. The simplest -application of this idea would look like: - -`hwconfig.py`: - - from machine import Pin - - LED = Pin("A3", Pin.OUT) - -`app.py`: - - from hwconfig import * - import utime - - while True: - LED.value(1) - utime.sleep_ms(500) - LED.value(0) - utime.sleep_ms(500) - - -To deploy this application to a particular board, a user will need: - -1. Edit `hwconfig.py` to adjust Pin and other hardware peripheral - parameters and locations. -2. Actually deploy `hwconfig.py` and `app.py` to a board (e.g. copy to - board's filesystem, or build new firmware with these modules frozen - into it). - -Note that there's no need to edit the main application code! (Which may -be complex, while `hwconfig.py` should usually remain short enough, and -focused solely on hardware configuration). - -An obvious improvement to this approach is the following. There're few -well-known boards which run MicroPython, and most of them include an -onboard LED. So, to help users of these boards to do configuration -quickly (that's especially important for novice users, for who may -be stumped by the need to reach out to a board reference to find LED -pin assignments), `hwconfig.py` your application ships may include -commented out sections with working configurations for different -boards. The step 1 above then will be: - -1. Look thru `hwconfig.py` to find a section which either exactly - matches your board, or the closest to it. Uncomment, and if any - adjustments required, apply them. - -It's important to keep in mind that adjustments may be always required, -and that there may be users whose configuration doesn't match any of -the available. So, always include a section or instructions for them. -Consider for example that even on a supported board, user may want to -blink not an on-board LED, but the one they connected externally. -MicroPython's Hardware API offers portability not just among "supported" -boards, but to any board at all, so make sure users can enjoy it. - -There's next step of improvement to make. While having one `hwconfig.py` -with many sections would work for smaller projects with few hardware -objects, it may become more cumbersome to maintain both on programmer's -and user's sides for larger projects. Then instead of single -`hwconfig.py` file, you can provide few "template" ones for well-known -boards: - -* `hwconfig_pyboard.py` -* `hwconfig_wipy.py` -* `hwconfig_esp8266.py` -* etc. - -Then step 1 above will be: - -1. Look thru available `hwconfig_*.py` files and find one which matches - your board the best, then rename to `hwconfig.py` and make adjustments, - if any. - -Again, please keep in mind that there may be users whose hardware will be -completely unlike you heard of. Give them some helpful hints too, perhaps -provide `hwconfig_custom.py` with some instructions. - -That's where we stop with improvements to the "separate file for hardware -configuration" idea, as it is already pretty flexible and viable. An -application in this directory shows it in practice, using slightly less -trivial example than just a blinking LED: `soft_pwm.py` implements a -software PWM (pulse width modulation) to produce an LED fade-in/fade-out -effect - without any dependence on hardware PWM availability. - -Note that improvements to board configuration handling may continue further. -For example, one may invent a "configuration manager" helper module which will -try to detect current board (among well-known ones), and load appropriate -`hwconfig_*.py` - this assumes that a user would lazily deploy them all -(or that application will be automatically installed, e.g. using MicroPython's -`upip` package manager). The key point in this case remains the same as -elaborated above - always assume there can, and will be a custom configuration, -and it should be well supported. So, any automatic detection should be -overridable by a user, and instructions how to do so are among the most -important you may provide for your application. - -By following these best practices, you will use MicroPython at its full -potential, and let users enjoy it too. Good luck! diff --git a/examples/hwapi/button_led.py b/examples/hwapi/button_led.py deleted file mode 100644 index bd6fe01729..0000000000 --- a/examples/hwapi/button_led.py +++ /dev/null @@ -1,9 +0,0 @@ -import utime -from hwconfig import LED, BUTTON - -# Light LED when (and while) a BUTTON is pressed - -while 1: - LED.value(BUTTON.value()) - # Don't burn CPU - utime.sleep_ms(10) diff --git a/examples/hwapi/button_reaction.py b/examples/hwapi/button_reaction.py deleted file mode 100644 index b72e813e4c..0000000000 --- a/examples/hwapi/button_reaction.py +++ /dev/null @@ -1,19 +0,0 @@ -import utime -import machine -from hwconfig import LED, BUTTON - -# machine.time_pulse_us() function demo - -print("""\ -Let's play an interesting game: -You click button as fast as you can, and I tell you how slow you are. -Ready? Cliiiiick! -""") - -while 1: - delay = machine.time_pulse_us(BUTTON, 1, 10*1000*1000) - if delay < 0: - print("Well, you're *really* slow") - else: - print("You are as slow as %d microseconds!" % delay) - utime.sleep_ms(10) diff --git a/examples/hwapi/hwconfig_console.py b/examples/hwapi/hwconfig_console.py deleted file mode 100644 index bbcc0e816e..0000000000 --- a/examples/hwapi/hwconfig_console.py +++ /dev/null @@ -1,19 +0,0 @@ -# This is hwconfig for "emulation" for cases when there's no real hardware. -# It just prints information to console. -class LEDClass: - - def __init__(self, id): - self.id = "LED(%d):" % id - - def value(self, v): - print(self.id, v) - - def on(self): - self.value(1) - - def off(self): - self.value(0) - - -LED = LEDClass(1) -LED2 = LEDClass(12) diff --git a/examples/hwapi/hwconfig_dragonboard410c.py b/examples/hwapi/hwconfig_dragonboard410c.py deleted file mode 100644 index eec3582039..0000000000 --- a/examples/hwapi/hwconfig_dragonboard410c.py +++ /dev/null @@ -1,22 +0,0 @@ -from machine import Pin, Signal - -# 96Boards/Qualcomm DragonBoard 410c -# -# By default, on-board LEDs are controlled by kernel LED driver. -# To make corresponding pins be available as normal GPIO, -# corresponding driver needs to be unbound first (as root): -# echo -n "soc:leds" >/sys/class/leds/apq8016-sbc:green:user1/device/driver/unbind -# Note that application also either should be run as root, or -# /sys/class/gpio ownership needs to be changed. -# Likewise, onboard buttons are controlled by gpio_keys driver. -# To release corresponding GPIOs: -# echo -n "gpio_keys" >/sys/class/input/input1/device/driver/unbind - -# User LED 1 on gpio21 -LED = Signal(Pin(21, Pin.OUT)) - -# User LED 2 on gpio120 -LED2 = Signal(Pin(120, Pin.OUT)) - -# Button S3 on gpio107 -BUTTON = Pin(107, Pin.IN) diff --git a/examples/hwapi/hwconfig_esp8266_esp12.py b/examples/hwapi/hwconfig_esp8266_esp12.py deleted file mode 100644 index 2e855ee3d3..0000000000 --- a/examples/hwapi/hwconfig_esp8266_esp12.py +++ /dev/null @@ -1,5 +0,0 @@ -from machine import Pin, Signal - -# ESP12 module as used by many boards -# Blue LED on pin 2, active low (inverted) -LED = Signal(2, Pin.OUT, invert=True) diff --git a/examples/hwapi/hwconfig_pyboard.py b/examples/hwapi/hwconfig_pyboard.py deleted file mode 100644 index fb260033e5..0000000000 --- a/examples/hwapi/hwconfig_pyboard.py +++ /dev/null @@ -1,13 +0,0 @@ -from machine import Pin, Signal - -# Red LED on pin LED_RED also kown as A13 -LED = Signal('LED_RED', Pin.OUT) - -# Green LED on pin LED_GREEN also known as A14 -LED2 = Signal('LED_GREEN', Pin.OUT) - -# Yellow LED on pin LED_YELLOW also known as A15 -LED3 = Signal('LED_YELLOW', Pin.OUT) - -# Blue LED on pin LED_BLUE also known as B4 -LED4 = Signal('LED_BLUE', Pin.OUT) diff --git a/examples/hwapi/hwconfig_z_96b_carbon.py b/examples/hwapi/hwconfig_z_96b_carbon.py deleted file mode 100644 index 97fd57a07f..0000000000 --- a/examples/hwapi/hwconfig_z_96b_carbon.py +++ /dev/null @@ -1,9 +0,0 @@ -from machine import Signal - -# 96Boards Carbon board -# USR1 - User controlled led, connected to PD2 -# USR2 - User controlled led, connected to PA15 -# BT - Bluetooth indicator, connected to PB5. -# Note - 96b_carbon uses (at the time of writing) non-standard -# for Zephyr port device naming convention. -LED = Signal(("GPIOA", 15), Pin.OUT) diff --git a/examples/hwapi/hwconfig_z_frdm_k64f.py b/examples/hwapi/hwconfig_z_frdm_k64f.py deleted file mode 100644 index 377c638787..0000000000 --- a/examples/hwapi/hwconfig_z_frdm_k64f.py +++ /dev/null @@ -1,5 +0,0 @@ -from machine import Pin, Signal - -# Freescale/NXP FRDM-K64F board -# Blue LED on port B, pin 21 -LED = Signal(("GPIO_1", 21), Pin.OUT) diff --git a/examples/hwapi/soft_pwm.py b/examples/hwapi/soft_pwm.py deleted file mode 100644 index 72291b0ecd..0000000000 --- a/examples/hwapi/soft_pwm.py +++ /dev/null @@ -1,38 +0,0 @@ -import utime -from hwconfig import LED - - -# Using sleep_ms() gives pretty poor PWM resolution and -# brightness control, but we use it in the attempt to -# make this demo portable to even more boards (e.g. to -# those which don't provide sleep_us(), or provide, but -# it's not precise, like would be on non realtime OSes). -# We otherwise use 20ms period, to make frequency not less -# than 50Hz to avoid visible flickering (you may still see -# if you're unlucky). -def pwm_cycle(led, duty, cycles): - duty_off = 20 - duty - for i in range(cycles): - if duty: - led.on() - utime.sleep_ms(duty) - if duty_off: - led.off() - utime.sleep_ms(duty_off) - - -# At the duty setting of 1, an LED is still pretty bright, then -# at duty 0, it's off. This makes rather unsmooth transition, and -# breaks fade effect. So, we avoid value of 0 and oscillate between -# 1 and 20. Actually, highest values like 19 and 20 are also -# barely distinguishible (like, both of them too bright and burn -# your eye). So, improvement to the visible effect would be to use -# more steps (at least 10x), and then higher frequency, and use -# range which includes 1 but excludes values at the top. -while True: - # Fade in - for i in range(1, 21): - pwm_cycle(LED, i, 2) - # Fade out - for i in range(20, 0, -1): - pwm_cycle(LED, i, 2) diff --git a/examples/hwapi/soft_pwm2_uasyncio.py b/examples/hwapi/soft_pwm2_uasyncio.py deleted file mode 100644 index 908ef2d8ac..0000000000 --- a/examples/hwapi/soft_pwm2_uasyncio.py +++ /dev/null @@ -1,31 +0,0 @@ -# Like soft_pwm_uasyncio.py, but fading 2 LEDs with different phase. -# Also see original soft_pwm.py. -import uasyncio -from hwconfig import LED, LED2 - - -async def pwm_cycle(led, duty, cycles): - duty_off = 20 - duty - for i in range(cycles): - if duty: - led.value(1) - await uasyncio.sleep_ms(duty) - if duty_off: - led.value(0) - await uasyncio.sleep_ms(duty_off) - - -async def fade_in_out(LED): - while True: - # Fade in - for i in range(1, 21): - await pwm_cycle(LED, i, 2) - # Fade out - for i in range(20, 0, -1): - await pwm_cycle(LED, i, 2) - - -loop = uasyncio.get_event_loop() -loop.create_task(fade_in_out(LED)) -loop.call_later_ms(800, fade_in_out(LED2)) -loop.run_forever() diff --git a/examples/hwapi/soft_pwm_uasyncio.py b/examples/hwapi/soft_pwm_uasyncio.py deleted file mode 100644 index 8d7ad8c9e0..0000000000 --- a/examples/hwapi/soft_pwm_uasyncio.py +++ /dev/null @@ -1,28 +0,0 @@ -# See original soft_pwm.py for detailed comments. -import uasyncio -from hwconfig import LED - - -async def pwm_cycle(led, duty, cycles): - duty_off = 20 - duty - for i in range(cycles): - if duty: - led.value(1) - await uasyncio.sleep_ms(duty) - if duty_off: - led.value(0) - await uasyncio.sleep_ms(duty_off) - - -async def fade_in_out(LED): - while True: - # Fade in - for i in range(1, 21): - await pwm_cycle(LED, i, 2) - # Fade out - for i in range(20, 0, -1): - await pwm_cycle(LED, i, 2) - - -loop = uasyncio.get_event_loop() -loop.run_until_complete(fade_in_out(LED)) diff --git a/examples/ledangle.py b/examples/ledangle.py deleted file mode 100644 index 8c8d9e99d9..0000000000 --- a/examples/ledangle.py +++ /dev/null @@ -1,25 +0,0 @@ -import pyb - -def led_angle(seconds_to_run_for): - # make LED objects - l1 = pyb.LED(1) - l2 = pyb.LED(2) - accel = pyb.Accel() - - for i in range(20 * seconds_to_run_for): - # get x-axis - x = accel.x() - - # turn on LEDs depending on angle - if x < -10: - l1.on() - l2.off() - elif x > 10: - l1.off() - l2.on() - else: - l1.off() - l2.off() - - # delay so that loop runs at at 1/50ms = 20Hz - pyb.delay(50) diff --git a/examples/mandel.py b/examples/mandel.py deleted file mode 100644 index bbb8086470..0000000000 --- a/examples/mandel.py +++ /dev/null @@ -1,27 +0,0 @@ -try: - import micropython -except: - pass - -def mandelbrot(): - # returns True if c, complex, is in the Mandelbrot set - #@micropython.native - def in_set(c): - z = 0 - for i in range(40): - z = z*z + c - if abs(z) > 60: - return False - return True - - lcd.clear() - for u in range(91): - for v in range(31): - if in_set((u / 30 - 2) + (v / 15 - 1) * 1j): - lcd.set(u, v) - lcd.show() - -# PC testing -import lcd -lcd = lcd.LCD(128, 32) -mandelbrot() diff --git a/examples/micropython.py b/examples/micropython.py deleted file mode 100644 index f91da94f41..0000000000 --- a/examples/micropython.py +++ /dev/null @@ -1,8 +0,0 @@ -# micropython module placeholder for CPython - -# Dummy function decorators - -def nodecor(x): - return x - -bytecode = native = viper = nodecor diff --git a/examples/network/http_client.py b/examples/network/http_client.py deleted file mode 100644 index 0791c8066b..0000000000 --- a/examples/network/http_client.py +++ /dev/null @@ -1,30 +0,0 @@ -try: - import usocket as socket -except: - import socket - - -def main(use_stream=False): - s = socket.socket() - - ai = socket.getaddrinfo("google.com", 80) - print("Address infos:", ai) - addr = ai[0][-1] - - print("Connect address:", addr) - s.connect(addr) - - if use_stream: - # MicroPython socket objects support stream (aka file) interface - # directly, but the line below is needed for CPython. - s = s.makefile("rwb", 0) - s.write(b"GET / HTTP/1.0\r\n\r\n") - print(s.read()) - else: - s.send(b"GET / HTTP/1.0\r\n\r\n") - print(s.recv(4096)) - - s.close() - - -main() diff --git a/examples/network/http_client_ssl.py b/examples/network/http_client_ssl.py deleted file mode 100644 index 83f685fdf3..0000000000 --- a/examples/network/http_client_ssl.py +++ /dev/null @@ -1,38 +0,0 @@ -try: - import usocket as _socket -except: - import _socket -try: - import ussl as ssl -except: - import ssl - - -def main(use_stream=True): - s = _socket.socket() - - ai = _socket.getaddrinfo("google.com", 443) - print("Address infos:", ai) - addr = ai[0][-1] - - print("Connect address:", addr) - s.connect(addr) - - s = ssl.wrap_socket(s) - print(s) - - if use_stream: - # Both CPython and MicroPython SSLSocket objects support read() and - # write() methods. - s.write(b"GET / HTTP/1.0\r\n\r\n") - print(s.read(4096)) - else: - # MicroPython SSLSocket objects implement only stream interface, not - # socket interface - s.send(b"GET / HTTP/1.0\r\n\r\n") - print(s.recv(4096)) - - s.close() - - -main() diff --git a/examples/network/http_server.py b/examples/network/http_server.py deleted file mode 100644 index e3a66e8283..0000000000 --- a/examples/network/http_server.py +++ /dev/null @@ -1,64 +0,0 @@ -try: - import usocket as socket -except: - import socket - - -CONTENT = b"""\ -HTTP/1.0 200 OK - -Hello #%d from MicroPython! -""" - -def main(micropython_optimize=False): - s = socket.socket() - - # Binding to all interfaces - server will be accessible to other hosts! - ai = socket.getaddrinfo("0.0.0.0", 8080) - print("Bind address info:", ai) - addr = ai[0][-1] - - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - s.bind(addr) - s.listen(5) - print("Listening, connect your browser to http://:8080/") - - counter = 0 - while True: - res = s.accept() - client_sock = res[0] - client_addr = res[1] - print("Client address:", client_addr) - print("Client socket:", client_sock) - - if not micropython_optimize: - # To read line-oriented protocol (like HTTP) from a socket (and - # avoid short read problem), it must be wrapped in a stream (aka - # file-like) object. That's how you do it in CPython: - client_stream = client_sock.makefile("rwb") - else: - # .. but MicroPython socket objects support stream interface - # directly, so calling .makefile() method is not required. If - # you develop application which will run only on MicroPython, - # especially on a resource-constrained embedded device, you - # may take this shortcut to save resources. - client_stream = client_sock - - print("Request:") - req = client_stream.readline() - print(req) - while True: - h = client_stream.readline() - if h == b"" or h == b"\r\n": - break - print(h) - client_stream.write(CONTENT % counter) - - client_stream.close() - if not micropython_optimize: - client_sock.close() - counter += 1 - print() - - -main() diff --git a/examples/network/http_server_simplistic.py b/examples/network/http_server_simplistic.py deleted file mode 100644 index 67ecb1ad7a..0000000000 --- a/examples/network/http_server_simplistic.py +++ /dev/null @@ -1,40 +0,0 @@ -# Do not use this code in real projects! Read -# http_server_simplistic_commented.py for details. -try: - import usocket as socket -except: - import socket - - -CONTENT = b"""\ -HTTP/1.0 200 OK - -Hello #%d from MicroPython! -""" - -def main(): - s = socket.socket() - ai = socket.getaddrinfo("0.0.0.0", 8080) - addr = ai[0][-1] - - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - - s.bind(addr) - s.listen(5) - print("Listening, connect your browser to http://:8080/") - - counter = 0 - while True: - res = s.accept() - client_s = res[0] - client_addr = res[1] - req = client_s.recv(4096) - print("Request:") - print(req) - client_s.send(CONTENT % counter) - client_s.close() - counter += 1 - print() - - -main() diff --git a/examples/network/http_server_simplistic_commented.py b/examples/network/http_server_simplistic_commented.py deleted file mode 100644 index b58e9eeb60..0000000000 --- a/examples/network/http_server_simplistic_commented.py +++ /dev/null @@ -1,76 +0,0 @@ -# -# MicroPython http_server_simplistic.py example -# -# This example shows how to write the smallest possible HTTP -# server in MicroPython. With comments and convenience code -# removed, this example can be compressed literally to ten -# lines. There's a catch though - read comments below for -# details, and use this code only for quick hacks, preferring -# http_server.py for "real thing". -# -try: - import usocket as socket -except: - import socket - - -CONTENT = b"""\ -HTTP/1.0 200 OK - -Hello #%d from MicroPython! -""" - -def main(): - s = socket.socket() - - # Bind to (allow to be connected on ) all interfaces. This means - # this server will be accessible to other hosts on your local - # network, and if your server has direct (non-firewalled) connection - # to the Internet, then to anyone on the Internet. We bind to all - # interfaces to let this example work easily on embedded MicroPython - # targets, which you will likely access from another machine on your - # local network. Take care when running this on an Internet-connected - # machine though! Replace "0.0.0.0" with "127.0.0.1" if in doubt, to - # make the server accessible only on the machine it runs on. - ai = socket.getaddrinfo("0.0.0.0", 8080) - print("Bind address info:", ai) - addr = ai[0][-1] - - # A port on which a socket listened remains inactive during some time. - # This means that if you run this sample, terminate it, and run again - # you will likely get an error. To avoid this timeout, set SO_REUSEADDR - # socket option. - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - - s.bind(addr) - s.listen(5) - print("Listening, connect your browser to http://:8080/") - - counter = 0 - while True: - res = s.accept() - client_s = res[0] - client_addr = res[1] - print("Client address:", client_addr) - print("Client socket:", client_s) - # We assume here that .recv() call will read entire HTTP request - # from client. This is usually true, at least on "big OS" systems - # like Linux/MacOS/Windows. But that doesn't have to be true in - # all cases, in particular on embedded systems, when there can - # easily be "short recv", where it returns much less than requested - # data size. That's why this example is called "simplistic" - it - # shows that writing a web server in Python that *usually works* is - # ten lines of code, and you can use this technique for quick hacks - # and experimentation. But don't do it like that in production - # applications - instead, parse HTTP request properly, as shown - # by http_server.py example. - req = client_s.recv(4096) - print("Request:") - print(req) - client_s.send(CONTENT % counter) - client_s.close() - counter += 1 - print() - - -main() diff --git a/examples/network/http_server_ssl.py b/examples/network/http_server_ssl.py deleted file mode 100644 index 9a69ca9d41..0000000000 --- a/examples/network/http_server_ssl.py +++ /dev/null @@ -1,64 +0,0 @@ -try: - import usocket as socket -except: - import socket -import ussl as ssl - - -CONTENT = b"""\ -HTTP/1.0 200 OK - -Hello #%d from MicroPython! -""" - -def main(use_stream=True): - s = socket.socket() - - # Binding to all interfaces - server will be accessible to other hosts! - ai = socket.getaddrinfo("0.0.0.0", 8443) - print("Bind address info:", ai) - addr = ai[0][-1] - - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - s.bind(addr) - s.listen(5) - print("Listening, connect your browser to https://:8443/") - - counter = 0 - while True: - res = s.accept() - client_s = res[0] - client_addr = res[1] - print("Client address:", client_addr) - print("Client socket:", client_s) - client_s = ssl.wrap_socket(client_s, server_side=True) - print(client_s) - print("Request:") - if use_stream: - # Both CPython and MicroPython SSLSocket objects support read() and - # write() methods. - # Browsers are prone to terminate SSL connection abruptly if they - # see unknown certificate, etc. We must continue in such case - - # next request they issue will likely be more well-behaving and - # will succeed. - try: - req = client_s.readline() - print(req) - while True: - h = client_s.readline() - if h == b"" or h == b"\r\n": - break - print(h) - if req: - client_s.write(CONTENT % counter) - except Exception as e: - print("Exception serving request:", e) - else: - print(client_s.recv(4096)) - client_s.send(CONTENT % counter) - client_s.close() - counter += 1 - print() - - -main() diff --git a/examples/pins.py b/examples/pins.py deleted file mode 100644 index aafdb48133..0000000000 --- a/examples/pins.py +++ /dev/null @@ -1,58 +0,0 @@ -# Print a nice list of pins, their current settings, and available afs. -# Requires pins_af.py from ports/stm32/build-PYBV10/ directory. - -import pyb -import pins_af - -def af(): - max_name_width = 0 - max_af_width = 0 - for pin_entry in pins_af.PINS_AF: - max_name_width = max(max_name_width, len(pin_entry[0])) - for af_entry in pin_entry[1:]: - max_af_width = max(max_af_width, len(af_entry[1])) - for pin_entry in pins_af.PINS_AF: - pin_name = pin_entry[0] - print('%-*s ' % (max_name_width, pin_name), end='') - for af_entry in pin_entry[1:]: - print('%2d: %-*s ' % (af_entry[0], max_af_width, af_entry[1]), end='') - print('') - -def pins(): - mode_str = { pyb.Pin.IN : 'IN', - pyb.Pin.OUT_PP : 'OUT_PP', - pyb.Pin.OUT_OD : 'OUT_OD', - pyb.Pin.AF_PP : 'AF_PP', - pyb.Pin.AF_OD : 'AF_OD', - pyb.Pin.ANALOG : 'ANALOG' } - pull_str = { pyb.Pin.PULL_NONE : '', - pyb.Pin.PULL_UP : 'PULL_UP', - pyb.Pin.PULL_DOWN : 'PULL_DOWN' } - width = [0, 0, 0, 0] - rows = [] - for pin_entry in pins_af.PINS_AF: - row = [] - pin_name = pin_entry[0] - pin = pyb.Pin(pin_name) - pin_mode = pin.mode() - row.append(pin_name) - row.append(mode_str[pin_mode]) - row.append(pull_str[pin.pull()]) - if pin_mode == pyb.Pin.AF_PP or pin_mode == pyb.Pin.AF_OD: - pin_af = pin.af() - for af_entry in pin_entry[1:]: - if pin_af == af_entry[0]: - af_str = '%d: %s' % (pin_af, af_entry[1]) - break - else: - af_str = '%d' % pin_af - else: - af_str = '' - row.append(af_str) - for col in range(len(width)): - width[col] = max(width[col], len(row[col])) - rows.append(row) - for row in rows: - for col in range(len(width)): - print('%-*s ' % (width[col], row[col]), end='') - print('') diff --git a/examples/pyb.py b/examples/pyb.py deleted file mode 100644 index b303777e5a..0000000000 --- a/examples/pyb.py +++ /dev/null @@ -1,49 +0,0 @@ -# pyboard testing functions for CPython -import time - -def delay(n): - #time.sleep(float(n) / 1000) - pass - -rand_seed = 1 -def rng(): - global rand_seed - # for these choice of numbers, see P L'Ecuyer, "Tables of linear congruential generators of different sizes and good lattice structure" - rand_seed = (rand_seed * 653276) % 8388593 - return rand_seed - -# LCD testing object for PC -# uses double buffering -class LCD: - def __init__(self, port): - self.width = 128 - self.height = 32 - self.buf1 = [[0 for x in range(self.width)] for y in range(self.height)] - self.buf2 = [[0 for x in range(self.width)] for y in range(self.height)] - - def light(self, value): - pass - - def fill(self, value): - for y in range(self.height): - for x in range(self.width): - self.buf1[y][x] = self.buf2[y][x] = value - - def show(self): - print('') # blank line to separate frames - for y in range(self.height): - for x in range(self.width): - self.buf1[y][x] = self.buf2[y][x] - for y in range(self.height): - row = ''.join(['*' if self.buf1[y][x] else ' ' for x in range(self.width)]) - print(row) - - def get(self, x, y): - if 0 <= x < self.width and 0 <= y < self.height: - return self.buf1[y][x] - else: - return 0 - - def pixel(self, x, y, value): - if 0 <= x < self.width and 0 <= y < self.height: - self.buf2[y][x] = value diff --git a/examples/switch.py b/examples/switch.py deleted file mode 100644 index 0efaf22675..0000000000 --- a/examples/switch.py +++ /dev/null @@ -1,45 +0,0 @@ -""" -switch.py -========= - -Light up some leds when the USR switch on the pyboard is pressed. - -Example Usage:: - - Micro Python v1.0.1 on 2014-05-12; PYBv1.0 with STM32F405RG - Type "help()" for more information. - >>> import switch - >>> switch.run_loop() - Loop started. - Press Ctrl+C to break out of the loop. - -""" - -import pyb - -switch = pyb.Switch() -red_led = pyb.LED(1) -green_led = pyb.LED(2) -orange_led = pyb.LED(3) -blue_led = pyb.LED(4) -all_leds = (red_led, green_led, orange_led, blue_led) - -def run_loop(leds=all_leds): - """ - Start the loop. - - :param `leds`: Which LEDs to light up upon switch press. - :type `leds`: sequence of LED objects - """ - print('Loop started.\nPress Ctrl+C to break out of the loop.') - while 1: - try: - if switch(): - [led.on() for led in leds] - else: - [led.off() for led in leds] - except OSError: # VCPInterrupt # Ctrl+C in interpreter mode. - break - -if __name__ == '__main__': - run_loop() diff --git a/examples/unix/ffi_example.py b/examples/unix/ffi_example.py deleted file mode 100644 index f650e33708..0000000000 --- a/examples/unix/ffi_example.py +++ /dev/null @@ -1,38 +0,0 @@ -import ffi - -libc = ffi.open("libc.so.6") -print("libc:", libc) -print() - -# Declare few functions -perror = libc.func("v", "perror", "s") -time = libc.func("i", "time", "p") -open = libc.func("i", "open", "si") -qsort = libc.func("v", "qsort", "piip") -# And one variable -errno = libc.var("i", "errno") - -print("time:", time) -print("UNIX time is:", time(None)) -print() - -perror("ffi before error") -open("somethingnonexistent__", 0) -print("errno object:", errno) -print("errno value:", errno.get()) -perror("ffi after error") -print() - -def cmp(pa, pb): - a = ffi.as_bytearray(pa, 1) - b = ffi.as_bytearray(pb, 1) - print("cmp:", a, b) - return a[0] - b[0] - -cmp_c = ffi.callback("i", cmp, "pp") -print("callback:", cmp_c) - -s = bytearray(b"foobar") -print("org string:", s) -qsort(s, len(s), 1, cmp_c) -print("qsort'ed string:", s) diff --git a/examples/unix/machine_bios.py b/examples/unix/machine_bios.py deleted file mode 100644 index f62e4dbdb4..0000000000 --- a/examples/unix/machine_bios.py +++ /dev/null @@ -1,9 +0,0 @@ -# This example shows how to access Video BIOS memory area via machine.mem -# It requires root privilege and x86 legacy harfware (which has mentioned -# Video BIOS at all). -# It is expected to print 0xaa55, which is a signature at the start of -# Video BIOS. - -import umachine as machine - -print(hex(machine.mem16[0xc0000])) diff --git a/index.rst b/index.rst deleted file mode 100644 index 48b89583a7..0000000000 --- a/index.rst +++ /dev/null @@ -1,92 +0,0 @@ -Adafruit CircuitPython API Reference -==================================== - -.. image:: https://travis-ci.org/adafruit/circuitpython.svg?branch=master - :target: https://travis-ci.org/adafruit/circuitpython - :alt: Build Status - -.. image:: https://readthedocs.org/projects/circuitpython/badge/?version=latest - :target: http://circuitpython.readthedocs.io/ - :alt: Doc Status - -.. image:: https://badges.gitter.im/adafruit/circuitpython.svg - :target: https://gitter.im/adafruit/circuitpython?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge - :alt: Gitter - -.. image:: https://img.shields.io/discord/327254708534116352.svg - :target: https://adafru.it/discord - :alt: Discord - -Welcome to the API reference documentation for Adafruit CircuitPython. -This contains low-level API reference docs which may link out to separate -*"getting started"* guides. `Adafruit `_ has many -excellent tutorials available through the -`Adafruit Learning System `_. - -What is CircuitPython? ----------------------- - -**CircuitPython** is an *education friendly* open source derivative of -`MicroPython `_. CircuitPython supports use on -educational development boards designed and sold by -`Adafruit `_. Adafruit CircuitPython features unified -Python core APIs and a growing list of Adafruit libraries and drivers of -that work with it. - -What boards use CircuitPython? ------------------------------- - -The Adafruit Express line of boards is specifically -designed for use with CircuitPython. This line includes: -`CircuitPlayground Express `_; -`Feather M0 Express `_; and -`Metro M0 Express `_ - -Other supported boards include: -`Arduino Zero `_; -`Adafruit Feather M0 Basic `_; -`Adafruit Feather HUZZAH `_; and -`Adafruit Feather M0 Bluefruit LE `_. - -.. _contents: - -Full Table of Contents ----------------------- - -.. toctree:: - :maxdepth: 3 - :caption: API and Usage - - shared-bindings/index.rst - docs/supported_ports.rst - docs/troubleshooting.rst - docs/drivers.rst - -.. toctree:: - :maxdepth: 1 - :caption: Design and porting reference - - docs/design_guide - docs/common_hal - -.. toctree:: - :maxdepth: 2 - :caption: MicroPython specific - - docs/library/index.rst - -.. toctree:: - :maxdepth: 1 - :caption: About the project - - README - CONTRIBUTING - CODE_OF_CONDUCT - license.rst - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/ports/atmel-samd/README.rst b/ports/atmel-samd/README.rst index 8915189bdc..8785ccada9 100644 --- a/ports/atmel-samd/README.rst +++ b/ports/atmel-samd/README.rst @@ -15,39 +15,39 @@ different names. The table below matches the pin order in and omits the pins only available on the largest package because all supported boards use smaller version. -===================== =============== =========================== ==================== ================ ================== ========================= ================ ================ +===================== =============== =========================== ====================== ================ ================== ========================= ================ ================ `microcontroller.pin` `board` ---------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- -Datasheet arduino_zero circuitplayground_express feather_m0_adalogger feather_m0_basic feather_m0_express gemma_m0 metro_m0_express trinket_m0 -===================== =============== =========================== ==================== ================ ================== ========================= ================ ================ -PA00 ``ACCELEROMETER_SDA`` ``APA102_MOSI`` ``APA102_MOSI`` -PA01 ``ACCELEROMETER_SCL`` ``APA102_SCK`` ``APA102_SCK`` -PA02 ``A0`` ``A0`` / ``SPEAKER`` ``A0`` ``A0`` ``A0`` ``A0`` / ``D1`` ``A0`` ``D1`` / ``A0`` +--------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +Datasheet arduino_zero circuitplayground_express feather_m0_adalogger feather_m0_basic feather_m0_express gemma_m0 metro_m0_express trinket_m0 +===================== =============== =========================== ====================== ================ ================== ========================= ================ ================ +PA00 ``ACCELEROMETER_SDA`` ``APA102_MOSI`` ``APA102_MOSI`` +PA01 ``ACCELEROMETER_SCL`` ``APA102_SCK`` ``APA102_SCK`` +PA02 ``A0`` ``A0`` / ``SPEAKER`` ``A0`` ``A0`` ``A0`` ``A0`` / ``D1`` ``A0`` ``D1`` / ``A0`` PA03 -PB08 ``A1`` ``A7`` / ``TX`` ``A1`` ``A1`` ``A1`` ``A1`` -PB09 ``A2`` ``A6`` / ``RX`` ``A2`` ``A2`` ``A2`` ``A2`` -PA04 ``A3`` ``IR_PROXIMITY`` ``A3`` ``A3`` ``A3`` ``D0`` / ``TX`` / ``SDA`` ``A3`` -PA05 ``A4`` ``A1`` ``A4`` ``A4`` ``A4`` ``D2`` / ``RX`` / ``SCL`` ``A4`` -PA06 ``D8`` ``A2`` ``D8`` / ``GREEN_LED`` ``NEOPIXEL`` ``D8`` ``D4`` / ``TX`` -PA07 ``D9`` ``A3`` ``D9`` ``D9`` ``D9`` ``D9`` ``D3`` / ``RX`` -PA08 ``D4`` ``MICROPHONE_DO`` ``D4`` / ``SD_CS`` ``D4`` ``D0`` / ``SDA`` -PA09 ``D3`` ``TEMPERATURE`` / ``A9`` ``D3`` ``D2`` / ``SCL`` -PA10 ``D1`` / ``TX`` ``MICROPHONE_SCK`` ``D1`` / ``TX`` ``D1`` / ``TX`` ``D1`` / ``TX`` ``D1`` / ``TX`` ``D13`` -PA11 ``D0`` / ``RX`` ``LIGHT`` / ``A8`` ``D0`` / ``RX`` ``D0`` / ``RX`` ``D0`` / ``RX`` ``D0`` / ``RX`` -PB10 ``MOSI`` ``MOSI`` ``MOSI`` ``MOSI`` ``MOSI`` -PB11 ``SCK`` ``SCK`` ``SCK`` ``SCK`` ``SCK`` -PA12 ``MISO`` ``REMOTEIN`` / ``IR_RX`` ``MISO`` ``MISO`` ``MISO`` ``MISO`` -PA13 ``ACCELEROMETER_INTERRUPT`` ``FLASH_CS`` -PA14 ``D2`` ``BUTTON_B`` / ``D5`` ``D2`` -PA15 ``D5`` ``SLIDE_SWITCH`` / ``D7`` ``D5`` ``D5`` ``D5`` ``D5`` -PA16 ``D11`` ``MISO`` ``D11`` ``D11`` ``D11`` ``D11`` -PA17 ``D13`` ``D13`` ``D13`` / ``RED_LED`` ``D13`` ``D13`` ``D13`` -PA18 ``D10`` ``D10`` ``D10`` ``D10`` ``D10`` -PA19 ``D12`` ``D12`` ``D12`` ``D12`` ``D12`` -PA20 ``D6`` ``MOSI`` ``D6`` ``D6`` ``D6`` ``D6`` -PA21 ``D7`` ``SCK`` ``D7`` / ``SD_CD`` ``D7`` -PA22 ``SDA`` ``SDA`` ``SDA`` ``SDA`` ``SDA`` -PA23 ``SCL`` ``REMOTEOUT`` / ``IR_TX`` ``SCL`` ``SCL`` ``SCL`` ``L`` / ``D13`` ``SCL`` +PB08 ``A1`` ``A7`` / ``TX`` ``A1`` ``A1`` ``A1`` ``A1`` +PB09 ``A2`` ``A6`` / ``RX`` ``A2`` ``A2`` ``A2`` ``A2`` +PA04 ``A3`` ``IR_PROXIMITY`` ``A3`` ``A3`` ``A3`` ``D0`` / ``TX`` / ``SDA`` ``A3`` +PA05 ``A4`` ``A1`` ``A4`` ``A4`` ``A4`` ``D2`` / ``RX`` / ``SCL`` ``A4`` +PA06 ``D8`` ``A2`` ``D8`` / ``GREEN_LED`` ``NEOPIXEL`` ``D8`` ``D4`` / ``TX`` +PA07 ``D9`` ``A3`` ``D9`` ``D9`` ``D9`` ``D9`` ``D3`` / ``RX`` +PA08 ``D4`` ``MICROPHONE_DO`` ``D4`` / ``SD_CS`` ``D4`` ``D0`` / ``SDA`` +PA09 ``D3`` ``TEMPERATURE`` / ``A9`` ``D3`` ``D2`` / ``SCL`` +PA10 ``D1`` / ``TX`` ``MICROPHONE_SCK`` ``D1`` / ``TX`` ``D1`` / ``TX`` ``D1`` / ``TX`` ``D1`` / ``TX`` ``D13`` +PA11 ``D0`` / ``RX`` ``LIGHT`` / ``A8`` ``D0`` / ``RX`` ``D0`` / ``RX`` ``D0`` / ``RX`` ``D0`` / ``RX`` +PB10 ``MOSI`` ``MOSI`` ``MOSI`` ``MOSI`` ``MOSI`` +PB11 ``SCK`` ``SCK`` ``SCK`` ``SCK`` ``SCK`` +PA12 ``MISO`` ``REMOTEIN`` / ``IR_RX`` ``MISO`` ``MISO`` ``MISO`` ``MISO`` +PA13 ``ACCELEROMETER_INTERRUPT`` ``FLASH_CS`` +PA14 ``D2`` ``BUTTON_B`` / ``D5`` ``D2`` +PA15 ``D5`` ``SLIDE_SWITCH`` / ``D7`` ``D5`` ``D5`` ``D5`` ``D5`` +PA16 ``D11`` ``MISO`` ``D11`` ``D11`` ``D11`` ``D11`` +PA17 ``D13`` ``D13`` ``D13`` / ``RED_LED`` ``D13`` ``D13`` ``D13`` +PA18 ``D10`` ``D10`` ``D10`` ``D10`` ``D10`` +PA19 ``D12`` ``D12`` ``D12`` ``D12`` ``D12`` +PA20 ``D6`` ``MOSI`` ``D6`` ``D6`` ``D6`` ``D6`` +PA21 ``D7`` ``SCK`` ``D7`` / ``SD_CD`` ``D7`` +PA22 ``SDA`` ``SDA`` ``SDA`` ``SDA`` ``SDA`` +PA23 ``SCL`` ``REMOTEOUT`` / ``IR_TX`` ``SCL`` ``SCL`` ``SCL`` ``L`` / ``D13`` ``SCL`` PA24 PA25 PB22 ``FLASH_CS`` @@ -55,11 +55,11 @@ PB23 ``NEOPIXEL`` / ``D8`` PA27 PA28 ``BUTTON_A`` / ``D4`` PA29 -PA30 ``SPEAKER_ENABLE`` ``NEOPIXEL`` +PA30 ``SPEAKER_ENABLE`` ``NEOPIXEL`` PA31 -PB02 ``A5`` ``A5`` / ``SDA`` ``A5`` ``A5`` ``A5`` ``A5`` +PB02 ``A5`` ``A5`` / ``SDA`` ``A5`` ``A5`` ``A5`` ``A5`` PB03 ``A4`` / ``SCL`` -===================== =============== =========================== ==================== ================ ================== ========================= ================ ================ +===================== =============== =========================== ====================== ================ ================== ========================= ================ ================ Here is a table about which pins can do what in CircuitPython terms. However, just because something is listed, doesn't mean it will always work. Existing use @@ -193,9 +193,3 @@ Mass storage All boards will also show up as a mass storage device. Make sure to eject it before resetting or disconnecting the board. - -Port Specific modules ---------------------- - -.. toctree:: - bindings/samd/__init__ diff --git a/ports/atmel-samd/boards/itsybitsy_m0_express/mpconfigboard.h b/ports/atmel-samd/boards/itsybitsy_m0_express/mpconfigboard.h index 82c5bbc614..46eb8c8d9e 100644 --- a/ports/atmel-samd/boards/itsybitsy_m0_express/mpconfigboard.h +++ b/ports/atmel-samd/boards/itsybitsy_m0_express/mpconfigboard.h @@ -1,4 +1,4 @@ -#define MICROPY_HW_BOARD_NAME "Adafruit ItsyBitsy M0 Express" +#define MICROPY_HW_BOARD_NAME "Adafruit Itsy Bitsy M0 Express" #define MICROPY_HW_MCU_NAME "samd21g18" #define CIRCUITPY_BITBANG_APA102 @@ -41,6 +41,5 @@ #define CIRCUITPY_INTERNAL_NVM_SIZE 0 #define BOARD_FLASH_SIZE (0x00040000 - 0x2000 - CIRCUITPY_INTERNAL_NVM_SIZE) -//#include "external_flash/devices/S25FL216K.h" -#include "external_flash/devices/W25Q80DV.h" -//#include "external_flash/devices/GD25Q16C.h" +#include "external_flash/devices/GD25Q16C.h" +#include "external_flash/devices/W25Q16FW.h" diff --git a/ports/esp8266/espapa102.h b/ports/atmel-samd/boards/pirkey_m0/board.c similarity index 80% rename from ports/esp8266/espapa102.h rename to ports/atmel-samd/boards/pirkey_m0/board.c index dd7c5ab729..c8e20206a1 100644 --- a/ports/esp8266/espapa102.h +++ b/ports/atmel-samd/boards/pirkey_m0/board.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * Copyright (c) 2016 Robert Foss, Daniel Busch + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -23,9 +23,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef MICROPY_INCLUDED_ESP8266_ESPAPA102_H -#define MICROPY_INCLUDED_ESP8266_ESPAPA102_H -void esp_apa102_write(uint8_t clockPin, uint8_t dataPin, uint8_t *pixels, uint32_t numBytes); +#include "boards/board.h" -#endif // MICROPY_INCLUDED_ESP8266_ESPAPA102_H +void board_init(void) +{ +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/pirkey_m0/mpconfigboard.h b/ports/atmel-samd/boards/pirkey_m0/mpconfigboard.h new file mode 100644 index 0000000000..a26fd7fdd0 --- /dev/null +++ b/ports/atmel-samd/boards/pirkey_m0/mpconfigboard.h @@ -0,0 +1,17 @@ +#define MICROPY_HW_BOARD_NAME "Adafruit pIRKey M0" +#define MICROPY_HW_MCU_NAME "samd21e18" + +// #define MICROPY_HW_APA102_MOSI (&pin_PA00) +// #define MICROPY_HW_APA102_SCK (&pin_PA01) + +// #define CIRCUITPY_BITBANG_APA102 + +#define MICROPY_PORT_A (PORT_PA00 | PORT_PA01 | PORT_PA24 | PORT_PA25) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) + +#define CIRCUITPY_INTERNAL_NVM_SIZE 0 + +#include "internal_flash.h" + +#define BOARD_FLASH_SIZE (0x00040000 - 0x2000 - 0x010000) diff --git a/ports/atmel-samd/boards/pirkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/pirkey_m0/mpconfigboard.mk new file mode 100644 index 0000000000..52dfc14309 --- /dev/null +++ b/ports/atmel-samd/boards/pirkey_m0/mpconfigboard.mk @@ -0,0 +1,10 @@ +LD_FILE = boards/samd21x18-bootloader.ld +USB_VID = 0x239A +USB_PID = 0x8028 +USB_PRODUCT = "pIRKey M0" +USB_MANUFACTURER = "Adafruit Industries LLC" + +INTERNAL_FLASH_FILESYSTEM = 1 + +CHIP_VARIANT = SAMD21E18A +CHIP_FAMILY = samd21 diff --git a/ports/atmel-samd/boards/pirkey_m0/pins.c b/ports/atmel-samd/boards/pirkey_m0/pins.c new file mode 100644 index 0000000000..a1b7db85c8 --- /dev/null +++ b/ports/atmel-samd/boards/pirkey_m0/pins.c @@ -0,0 +1,9 @@ +#include "samd21_pins.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_REMOTEIN), MP_ROM_PTR(&pin_PA28) }, + + { MP_ROM_QSTR(MP_QSTR_APA102_MOSI), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_APA102_SCK), MP_ROM_PTR(&pin_PA01) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/atmel-samd/external_flash/devices/GD25Q16C.h b/ports/atmel-samd/external_flash/devices/GD25Q16C.h index 90ec6de5cd..e123265e29 100644 --- a/ports/atmel-samd/external_flash/devices/GD25Q16C.h +++ b/ports/atmel-samd/external_flash/devices/GD25Q16C.h @@ -44,11 +44,12 @@ // used to confirm we're talking to the flash we expect. #define SPI_FLASH_JEDEC_MANUFACTURER 0xc8 #define SPI_FLASH_SECTOR_PROTECTION true +#define SPI_FLASH_JEDEC_MEMORY_TYPE 0x40 #else #define SPI_FLASH_JEDEC_MANUFACTURER_2 0xc8 #define SPI_FLASH_SECTOR_PROTECTION_2 true +#define SPI_FLASH_JEDEC_MEMORY_TYPE_2 0x40 #endif -#define SPI_FLASH_JEDEC_MEMORY_TYPE 0x40 #define SPI_FLASH_JEDEC_CAPACITY 0x15 diff --git a/ports/atmel-samd/external_flash/devices/S25FL064L.h b/ports/atmel-samd/external_flash/devices/S25FL064L.h index 40cfa4cf0a..5a38836874 100644 --- a/ports/atmel-samd/external_flash/devices/S25FL064L.h +++ b/ports/atmel-samd/external_flash/devices/S25FL064L.h @@ -45,11 +45,12 @@ #ifndef SPI_FLASH_JEDEC_MANUFACTURER #define SPI_FLASH_JEDEC_MANUFACTURER 0x01 #define SPI_FLASH_SECTOR_PROTECTION false +#define SPI_FLASH_JEDEC_MEMORY_TYPE 0x60 #else #define SPI_FLASH_JEDEC_MANUFACTURER_2 0x013 #define SPI_FLASH_SECTOR_PROTECTION_2 false +#define SPI_FLASH_JEDEC_MEMORY_TYPE_2 0x60 #endif -#define SPI_FLASH_JEDEC_MEMORY_TYPE 0x60 #define SPI_FLASH_JEDEC_CAPACITY 0x17 #endif // MICROPY_INCLUDED_ATMEL_SAMD_BOARD_FLASH_S25FL216K_H diff --git a/ports/atmel-samd/external_flash/devices/S25FL116K.h b/ports/atmel-samd/external_flash/devices/S25FL116K.h index 4928bd04e2..0ccb58ed07 100644 --- a/ports/atmel-samd/external_flash/devices/S25FL116K.h +++ b/ports/atmel-samd/external_flash/devices/S25FL116K.h @@ -44,11 +44,12 @@ #ifndef SPI_FLASH_JEDEC_MANUFACTURER #define SPI_FLASH_JEDEC_MANUFACTURER 0x01 #define SPI_FLASH_SECTOR_PROTECTION false +#define SPI_FLASH_JEDEC_MEMORY_TYPE 0x40 #else #define SPI_FLASH_JEDEC_MANUFACTURER_2 0x01 #define SPI_FLASH_SECTOR_PROTECTION_2 false +#define SPI_FLASH_JEDEC_MEMORY_TYPE_2 0x40 #endif -#define SPI_FLASH_JEDEC_MEMORY_TYPE 0x40 #define SPI_FLASH_JEDEC_CAPACITY 0x15 #endif // MICROPY_INCLUDED_ATMEL_SAMD_BOARD_FLASH_S25FL216K_H diff --git a/ports/atmel-samd/external_flash/devices/S25FL216K.h b/ports/atmel-samd/external_flash/devices/S25FL216K.h index 61b6b75146..a6a0a12fa2 100644 --- a/ports/atmel-samd/external_flash/devices/S25FL216K.h +++ b/ports/atmel-samd/external_flash/devices/S25FL216K.h @@ -44,11 +44,12 @@ #ifndef SPI_FLASH_JEDEC_MANUFACTURER #define SPI_FLASH_JEDEC_MANUFACTURER 0x01 #define SPI_FLASH_SECTOR_PROTECTION false +#define SPI_FLASH_JEDEC_MEMORY_TYPE 0x40 #else #define SPI_FLASH_JEDEC_MANUFACTURER_2 0x01 #define SPI_FLASH_SECTOR_PROTECTION_2 false +#define SPI_FLASH_JEDEC_MEMORY_TYPE_2 0x40 #endif -#define SPI_FLASH_JEDEC_MEMORY_TYPE 0x40 #define SPI_FLASH_JEDEC_CAPACITY 0x15 #endif // MICROPY_INCLUDED_ATMEL_SAMD_BOARD_FLASH_S25FL216K_H diff --git a/drivers/memory/spiflash.h b/ports/atmel-samd/external_flash/devices/W25Q16FW.h similarity index 52% rename from drivers/memory/spiflash.h rename to ports/atmel-samd/external_flash/devices/W25Q16FW.h index cd96b16f34..219a7f058f 100644 --- a/drivers/memory/spiflash.h +++ b/ports/atmel-samd/external_flash/devices/W25Q16FW.h @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * Copyright (c) 2016 Damien P. George + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -23,18 +23,31 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef MICROPY_INCLUDED_DRIVERS_MEMORY_SPIFLASH_H -#define MICROPY_INCLUDED_DRIVERS_MEMORY_SPIFLASH_H -#include "extmod/machine_spi.h" +#ifndef MICROPY_INCLUDED_ATMEL_SAMD_BOARD_FLASH_W25Q16FW_H +#define MICROPY_INCLUDED_ATMEL_SAMD_BOARD_FLASH_W25Q16FW_H -typedef struct _mp_spiflash_t { - mp_hal_pin_obj_t cs; - mp_obj_base_t *spi; // object must have protocol pointing to mp_machine_spi_p_t struct -} mp_spiflash_t; +// The total flash size in bytes. +#define SPI_FLASH_TOTAL_SIZE (1 << 21) // 2 MiB -void mp_spiflash_init(mp_spiflash_t *self); -void mp_spiflash_read(mp_spiflash_t *self, uint32_t addr, size_t len, uint8_t *dest); -int mp_spiflash_write(mp_spiflash_t *self, uint32_t addr, size_t len, const uint8_t *src); +// The size of the smallest erase unit thats erased with command 0x20. +#define SPI_FLASH_ERASE_SIZE (1 << 12) // 4 KiB -#endif // MICROPY_INCLUDED_DRIVERS_MEMORY_SPIFLASH_H +// The size of a page that is programmed with page program command 0x02. +#define SPI_FLASH_PAGE_SIZE (256) // 256 bytes + +// These are the first three response bytes to the JEDEC ID command 0x9f that is +// used to confirm we're talking to the flash we expect. +#ifndef SPI_FLASH_JEDEC_MANUFACTURER + #define SPI_FLASH_JEDEC_MANUFACTURER 0xef + #define SPI_FLASH_SECTOR_PROTECTION false + #define SPI_FLASH_JEDEC_MEMORY_TYPE 0x60 +#else + #define SPI_FLASH_JEDEC_MANUFACTURER_2 0xef + #define SPI_FLASH_SECTOR_PROTECTION_2 false + #define SPI_FLASH_JEDEC_MEMORY_TYPE_2 0x60 +#endif + +#define SPI_FLASH_JEDEC_CAPACITY 0x15 + +#endif // MICROPY_INCLUDED_ATMEL_SAMD_BOARD_FLASH_W25Q16BV_H diff --git a/ports/atmel-samd/external_flash/devices/W25Q32BV.h b/ports/atmel-samd/external_flash/devices/W25Q32BV.h index ae730fc6a2..d71771babc 100644 --- a/ports/atmel-samd/external_flash/devices/W25Q32BV.h +++ b/ports/atmel-samd/external_flash/devices/W25Q32BV.h @@ -41,11 +41,12 @@ #ifndef SPI_FLASH_JEDEC_MANUFACTURER #define SPI_FLASH_JEDEC_MANUFACTURER 0xef #define SPI_FLASH_SECTOR_PROTECTION false +#define SPI_FLASH_JEDEC_MEMORY_TYPE 0x40 #else #define SPI_FLASH_JEDEC_MANUFACTURER_2 0xef #define SPI_FLASH_SECTOR_PROTECTION_2 false +#define SPI_FLASH_JEDEC_MEMORY_TYPE_2 0x40 #endif -#define SPI_FLASH_JEDEC_MEMORY_TYPE 0x40 #define SPI_FLASH_JEDEC_CAPACITY 0x16 #endif // MICROPY_INCLUDED_ATMEL_SAMD_BOARD_FLASH_W25Q32BV_H diff --git a/ports/atmel-samd/external_flash/devices/W25Q80DV.h b/ports/atmel-samd/external_flash/devices/W25Q80DV.h index 1e8003867f..de12e3fd44 100644 --- a/ports/atmel-samd/external_flash/devices/W25Q80DV.h +++ b/ports/atmel-samd/external_flash/devices/W25Q80DV.h @@ -41,11 +41,12 @@ #ifndef SPI_FLASH_JEDEC_MANUFACTURER #define SPI_FLASH_JEDEC_MANUFACTURER 0xef #define SPI_FLASH_SECTOR_PROTECTION false +#define SPI_FLASH_JEDEC_MEMORY_TYPE 0x40 #else #define SPI_FLASH_JEDEC_MANUFACTURER_2 0xef #define SPI_FLASH_SECTOR_PROTECTION_2 false +#define SPI_FLASH_JEDEC_MEMORY_TYPE_2 0x40 #endif -#define SPI_FLASH_JEDEC_MEMORY_TYPE 0x40 #define SPI_FLASH_JEDEC_CAPACITY 0x14 #endif // MICROPY_INCLUDED_ATMEL_SAMD_BOARD_FLASH_W25Q80DV_H diff --git a/ports/atmel-samd/external_flash/external_flash.c b/ports/atmel-samd/external_flash/external_flash.c index d3a2b4bae6..b432567ef2 100644 --- a/ports/atmel-samd/external_flash/external_flash.c +++ b/ports/atmel-samd/external_flash/external_flash.c @@ -204,7 +204,11 @@ void external_flash_init(void) { || jedec_id_response[0] == SPI_FLASH_JEDEC_MANUFACTURER_2 #endif ) && - jedec_id_response[1] == SPI_FLASH_JEDEC_MEMORY_TYPE && + (jedec_id_response[1] == SPI_FLASH_JEDEC_MEMORY_TYPE +#ifdef SPI_FLASH_JEDEC_MANUFACTURER_2 + || jedec_id_response[1] == SPI_FLASH_JEDEC_MEMORY_TYPE_2 +#endif + ) && jedec_id_response[2] == SPI_FLASH_JEDEC_CAPACITY) { spi_flash_is_initialised = true; } else { diff --git a/ports/esp8266/Makefile b/ports/esp8266/Makefile index 70c5c96773..4a598b6291 100644 --- a/ports/esp8266/Makefile +++ b/ports/esp8266/Makefile @@ -79,7 +79,6 @@ SRC_C = \ espuart.c \ esppwm.c \ espneopixel.c \ - espapa102.c \ intr.c \ modpyb.c \ modmachine.c \ @@ -193,10 +192,6 @@ LIB_SRC_C += \ lib/oofatfs/option/unicode.c endif -DRIVERS_SRC_C = $(addprefix drivers/,\ - dht/dht.c \ - ) - SRC_S = \ gchelper.s \ @@ -209,7 +204,6 @@ OBJ += $(addprefix $(BUILD)/, $(SRC_SHARED_MODULE_EXPANDED:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(STM_SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(EXTMOD_SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(LIB_SRC_C:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(DRIVERS_SRC_C:.c=.o)) #OBJ += $(BUILD)/pins_$(BOARD).o # List of sources for qstr extraction diff --git a/ports/esp8266/espapa102.c b/ports/esp8266/espapa102.c deleted file mode 100644 index 4295fe42d8..0000000000 --- a/ports/esp8266/espapa102.c +++ /dev/null @@ -1,115 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2016 Robert Foss, Daniel Busch - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include "py/mpconfig.h" -#if MICROPY_ESP8266_APA102 - -#include -#include "c_types.h" -#include "eagle_soc.h" -#include "user_interface.h" -#include "espapa102.h" - -#define NOP asm volatile(" nop \n\t") - -static inline void _esp_apa102_send_byte(uint32_t clockPinMask, uint32_t dataPinMask, uint8_t byte) { - for (uint32_t i = 0; i < 8; i++) { - if (byte & 0x80) { - // set data pin high - GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, dataPinMask); - } else { - // set data pin low - GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, dataPinMask); - } - - // set clock pin high - GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, clockPinMask); - byte <<= 1; - NOP; - NOP; - - // set clock pin low - GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, clockPinMask); - NOP; - NOP; - } -} - -static inline void _esp_apa102_send_colors(uint32_t clockPinMask, uint32_t dataPinMask, uint8_t *pixels, uint32_t numBytes) { - for (uint32_t i = 0; i < numBytes / 4; i++) { - _esp_apa102_send_byte(clockPinMask, dataPinMask, pixels[i * 4 + 3] | 0xE0); - _esp_apa102_send_byte(clockPinMask, dataPinMask, pixels[i * 4 + 2]); - _esp_apa102_send_byte(clockPinMask, dataPinMask, pixels[i * 4 + 1]); - _esp_apa102_send_byte(clockPinMask, dataPinMask, pixels[i * 4]); - } -} - -static inline void _esp_apa102_start_frame(uint32_t clockPinMask, uint32_t dataPinMask) { - for (uint32_t i = 0; i < 4; i++) { - _esp_apa102_send_byte(clockPinMask, dataPinMask, 0x00); - } -} - -static inline void _esp_apa102_append_additionial_cycles(uint32_t clockPinMask, uint32_t dataPinMask, uint32_t numBytes) { - GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, dataPinMask); - - // we need to write some more clock cycles, because each led - // delays the data by one edge after inverting the clock - for (uint32_t i = 0; i < numBytes / 8 + ((numBytes / 4) % 2); i++) { - GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, clockPinMask); - NOP; - NOP; - - GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, clockPinMask); - NOP; - NOP; - } -} - -static inline void _esp_apa102_end_frame(uint32_t clockPinMask, uint32_t dataPinMask) { - for (uint32_t i = 0; i < 4; i++) { - _esp_apa102_send_byte(clockPinMask, dataPinMask, 0xFF); - } -} - -void esp_apa102_write(uint8_t clockPin, uint8_t dataPin, uint8_t *pixels, uint32_t numBytes) { - uint32_t clockPinMask, dataPinMask; - - clockPinMask = 1 << clockPin; - dataPinMask = 1 << dataPin; - - // start the frame - _esp_apa102_start_frame(clockPinMask, dataPinMask); - - // write pixels - _esp_apa102_send_colors(clockPinMask, dataPinMask, pixels, numBytes); - - // end the frame - _esp_apa102_append_additionial_cycles(clockPinMask, dataPinMask, numBytes); - _esp_apa102_end_frame(clockPinMask, dataPinMask); -} - -#endif diff --git a/ports/esp8266/modesp.c b/ports/esp8266/modesp.c index b57f7de586..ec4e735035 100644 --- a/ports/esp8266/modesp.c +++ b/ports/esp8266/modesp.c @@ -30,12 +30,9 @@ #include "py/runtime.h" #include "py/mperrno.h" #include "py/mphal.h" -#include "drivers/dht/dht.h" #include "espuart.h" #include "user_interface.h" #include "mem.h" -#include "espneopixel.h" -#include "espapa102.h" #include "modmachine.h" #define MODESP_INCLUDE_CONSTANTS (1) @@ -193,31 +190,6 @@ STATIC mp_obj_t esp_check_fw(void) { } STATIC MP_DEFINE_CONST_FUN_OBJ_0(esp_check_fw_obj, esp_check_fw); - -STATIC mp_obj_t esp_neopixel_write_(mp_obj_t pin, mp_obj_t buf, mp_obj_t is800k) { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ); - if (!mp_obj_is_true(is800k)) { - nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Only 800khz neopixels are supported.")); - } - esp_neopixel_write(mp_obj_get_pin_obj(pin)->phys_port, - (uint8_t*)bufinfo.buf, bufinfo.len); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp_neopixel_write_obj, esp_neopixel_write_); - -#if MICROPY_ESP8266_APA102 -STATIC mp_obj_t esp_apa102_write_(mp_obj_t clockPin, mp_obj_t dataPin, mp_obj_t buf) { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ); - esp_apa102_write(mp_obj_get_pin_obj(clockPin)->phys_port, - mp_obj_get_pin_obj(dataPin)->phys_port, - (uint8_t*)bufinfo.buf, bufinfo.len); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp_apa102_write_obj, esp_apa102_write_); -#endif - STATIC mp_obj_t esp_freemem() { return MP_OBJ_NEW_SMALL_INT(system_get_free_heap_size()); } @@ -362,13 +334,6 @@ STATIC const mp_rom_map_elem_t esp_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_flash_erase), MP_ROM_PTR(&esp_flash_erase_obj) }, { MP_ROM_QSTR(MP_QSTR_flash_size), MP_ROM_PTR(&esp_flash_size_obj) }, { MP_ROM_QSTR(MP_QSTR_flash_user_start), MP_ROM_PTR(&esp_flash_user_start_obj) }, - #if MICROPY_ESP8266_NEOPIXEL - { MP_ROM_QSTR(MP_QSTR_neopixel_write), MP_ROM_PTR(&esp_neopixel_write_obj) }, - #endif - #if MICROPY_ESP8266_APA102 - { MP_ROM_QSTR(MP_QSTR_apa102_write), MP_ROM_PTR(&esp_apa102_write_obj) }, - #endif - { MP_ROM_QSTR(MP_QSTR_dht_readinto), MP_ROM_PTR(&dht_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_freemem), MP_ROM_PTR(&esp_freemem_obj) }, { MP_ROM_QSTR(MP_QSTR_meminfo), MP_ROM_PTR(&esp_meminfo_obj) }, { MP_ROM_QSTR(MP_QSTR_check_fw), MP_ROM_PTR(&esp_check_fw_obj) }, diff --git a/ports/esp8266/modules/apa102.py b/ports/esp8266/modules/apa102.py deleted file mode 100644 index 41b7c0485c..0000000000 --- a/ports/esp8266/modules/apa102.py +++ /dev/null @@ -1,17 +0,0 @@ -# APA102 driver for MicroPython on ESP8266 -# MIT license; Copyright (c) 2016 Robert Foss, Daniel Busch - -from esp import apa102_write -from neopixel import NeoPixel - - -class APA102(NeoPixel): - ORDER = (0, 1, 2, 3) - - def __init__(self, clock_pin, data_pin, n, bpp=4): - super().__init__(data_pin, n, bpp) - self.clock_pin = clock_pin - self.clock_pin.init(clock_pin.OUT) - - def write(self): - apa102_write(self.clock_pin, self.pin, self.buf) diff --git a/ports/esp8266/modules/dht.py b/ports/esp8266/modules/dht.py deleted file mode 100644 index 9a69e7e07e..0000000000 --- a/ports/esp8266/modules/dht.py +++ /dev/null @@ -1,32 +0,0 @@ -# DHT11/DHT22 driver for MicroPython on ESP8266 -# MIT license; Copyright (c) 2016 Damien P. George - -import esp - -class DHTBase: - def __init__(self, pin): - self.pin = pin - self.buf = bytearray(5) - - def measure(self): - buf = self.buf - esp.dht_readinto(self.pin, buf) - if (buf[0] + buf[1] + buf[2] + buf[3]) & 0xff != buf[4]: - raise Exception("checksum error") - -class DHT11(DHTBase): - def humidity(self): - return self.buf[0] - - def temperature(self): - return self.buf[2] - -class DHT22(DHTBase): - def humidity(self): - return (self.buf[0] << 8 | self.buf[1]) * 0.1 - - def temperature(self): - t = ((self.buf[2] & 0x7f) << 8 | self.buf[3]) * 0.1 - if self.buf[2] & 0x80: - t = -t - return t diff --git a/ports/esp8266/modules/ds18x20.py b/ports/esp8266/modules/ds18x20.py deleted file mode 120000 index 1ec92d1c99..0000000000 --- a/ports/esp8266/modules/ds18x20.py +++ /dev/null @@ -1 +0,0 @@ -../../../drivers/onewire/ds18x20.py \ No newline at end of file diff --git a/ports/esp8266/modules/onewire.py b/ports/esp8266/modules/onewire.py deleted file mode 120000 index 33f30e84f1..0000000000 --- a/ports/esp8266/modules/onewire.py +++ /dev/null @@ -1 +0,0 @@ -../../../drivers/onewire/onewire.py \ No newline at end of file diff --git a/ports/esp8266/mpconfigport.h b/ports/esp8266/mpconfigport.h index 479484a43e..cdf06450c6 100644 --- a/ports/esp8266/mpconfigport.h +++ b/ports/esp8266/mpconfigport.h @@ -106,7 +106,6 @@ #define MICROPY_FATFS_MAX_SS (4096) #define MICROPY_FATFS_LFN_CODE_PAGE (437) /* 1=SFN/ANSI 437=LFN/U.S.(OEM) */ #define MICROPY_VFS_FAT (1) -#define MICROPY_ESP8266_APA102 (1) #define MICROPY_ESP8266_NEOPIXEL (1) extern void ets_event_poll(void); diff --git a/shared-bindings/_stage/__init__.c b/shared-bindings/_stage/__init__.c index 16e0b58d94..832b287716 100644 --- a/shared-bindings/_stage/__init__.c +++ b/shared-bindings/_stage/__init__.c @@ -32,7 +32,22 @@ #include "Layer.h" #include "Text.h" -//| .. currentmodule:: _stage +//| :mod:`_stage` --- C-level helpers for animation of sprites on a stage +//| ===================================================================== +//| +//| .. module:: _stage +//| :synopsis: C-level helpers for animation of sprites on a stage +//| :platform: SAMD21 +//| +//| The `_stage` module contains native code to speed-up the ```stage`` Library +//| `_. +//| Libraries +//| +//| .. toctree:: +//| :maxdepth: 3 +//| +//| Layer +//| Text //| //| .. function:: render(x0, y0, x1, y1, layers, buffer, spi) //| @@ -42,9 +57,9 @@ //| :param int y0: Top edge of the fragment. //| :param int x1: Right edge of the fragment. //| :param int y1: Bottom edge of the fragment. -//| :param list layers: A list of the `Layer` objects. +//| :param list layers: A list of the :py:class:`~_stage.Layer` objects. //| :param bytearray buffer: A buffer to use for rendering. -//| :param SPI spi: The SPI device to use. +//| :param ~busio.SPI spi: The SPI bus to use. //| //| Note that this function only sends the raw pixel data. Setting up //| the display for receiving it and handling the chip-select and diff --git a/shared-bindings/audiobusio/PDMIn.c b/shared-bindings/audiobusio/PDMIn.c index bd89ab1793..6f0a130e83 100644 --- a/shared-bindings/audiobusio/PDMIn.c +++ b/shared-bindings/audiobusio/PDMIn.c @@ -47,13 +47,13 @@ //| Create a PDMIn object associated with the given pins. This allows you to //| record audio signals from the given pins. Individual ports may put further //| restrictions on the recording parameters. The overall frequency is -//| determined by `frequency` x `oversample`, and the total must be 1MHz or +//| determined by `frequency` x ``oversample``, and the total must be 1MHz or //| higher, so `frequency` must be a minimum of 16000. //| //| :param ~microcontroller.Pin clock_pin: The pin to output the clock to //| :param ~microcontroller.Pin data_pin: The pin to read the data from //| :param int frequency: Target frequency of the resulting samples. Check `frequency` for actual value. -//| Minimum frequency is about 16000 Hz. +//| Minimum frequency is about 16000 Hz. //| :param int bit_depth: Final number of bits per sample. Must be divisible by 8 //| :param bool mono: True when capturing a single channel of audio, captures two channels otherwise //| :param int oversample: Number of single bit samples to decimate into a final sample. Must be divisible by 8 @@ -182,8 +182,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(audiobusio_pdmin___exit___obj, 4, 4, //| audio at the given rate. For internal flash, writing all 1s to the file //| before recording is recommended to speed up writes. //| -//| :return: The number of samples recorded. If this is less than `destination_length`, -//| some samples were missed due to processing time. +//| :return: The number of samples recorded. If this is less than ``destination_length``, +//| some samples were missed due to processing time. //| STATIC mp_obj_t audiobusio_pdmin_obj_record(mp_obj_t self_obj, mp_obj_t destination, mp_obj_t destination_length) { audiobusio_pdmin_obj_t *self = MP_OBJ_TO_PTR(self_obj); diff --git a/shared-bindings/audiobusio/__init__.c b/shared-bindings/audiobusio/__init__.c index 70606e4964..bdd999b044 100644 --- a/shared-bindings/audiobusio/__init__.c +++ b/shared-bindings/audiobusio/__init__.c @@ -34,7 +34,7 @@ #include "shared-bindings/audiobusio/PDMIn.h" //| :mod:`audiobusio` --- Support for audio input and output over digital bus -//| ================================================= +//| ========================================================================= //| //| .. module:: audiobusio //| :synopsis: Support for audio input and output over digital bus diff --git a/shared-bindings/busio/SPI.c b/shared-bindings/busio/SPI.c index c2889bb129..52c145d6de 100644 --- a/shared-bindings/busio/SPI.c +++ b/shared-bindings/busio/SPI.c @@ -258,7 +258,7 @@ MP_DEFINE_CONST_FUN_OBJ_KW(busio_spi_write_obj, 2, busio_spi_write); //| //| :param bytearray buffer: Read data into this buffer //| :param int start: Start of the slice of ``buffer`` to read into: ``buffer[start:end]`` -//| :param int end: End of the slice; this index is not included +//| :param int end: End of the slice; this index is not included //| :param int write_value: Value to write while reading. (Usually ignored.) //| STATIC mp_obj_t busio_spi_readinto(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { @@ -304,7 +304,7 @@ MP_DEFINE_CONST_FUN_OBJ_KW(busio_spi_readinto_obj, 2, busio_spi_readinto); //| :param bytearray buffer_out: Write out the data in this buffer //| :param bytearray buffer_in: Read data into this buffer //| :param int out_start: Start of the slice of buffer_out to write out: ``buffer_out[out_start:out_end]`` -//| :param int out_end: End of the slice; this index is not included +//| :param int out_end: End of the slice; this index is not included //| :param int in_start: Start of the slice of ``buffer_in`` to read into: ``buffer_in[in_start:in_end]`` //| :param int in_end: End of the slice; this index is not included //| diff --git a/shared-bindings/gamepad/GamePad.c b/shared-bindings/gamepad/GamePad.c index bdc3359fb6..a03b9318d8 100644 --- a/shared-bindings/gamepad/GamePad.c +++ b/shared-bindings/gamepad/GamePad.c @@ -49,8 +49,8 @@ gamepad_obj_t* gamepad_singleton = NULL; //| //| //| pad = gamepad.GamePad( -//| digitalio.DigitalInOut(board.D0), -//| digitalio.DigitalInOut(board.D1), +//| digitalio.DigitalInOut(board.D10), +//| digitalio.DigitalInOut(board.D11), //| ) //| //| y = 0 @@ -63,8 +63,9 @@ gamepad_obj_t* gamepad_singleton = NULL; //| y += 1 //| print(y) //| time.sleep(0.1) -//| while pad.get_pressed(): +//| while buttons: //| # Wait for all buttons to be released. +//| buttons = pad.get_pressed() //| time.sleep(0.1) //| diff --git a/shared-bindings/help.c b/shared-bindings/help.c index a3ae947975..cdd9a4a937 100644 --- a/shared-bindings/help.c +++ b/shared-bindings/help.c @@ -26,6 +26,15 @@ #include "genhdr/mpversion.h" +//| :func:`help` - Built-in method to provide helpful information +//| ============================================================== +//| +//| .. method:: help(object=None) +//| +//| Prints a help method about the given object. When ``object`` is none, +//| prints general port information. +//| + const char *circuitpython_help_text = "Welcome to Adafruit CircuitPython " MICROPY_GIT_TAG "!\r\n" "\r\n" diff --git a/shared-bindings/index.rst b/shared-bindings/index.rst index 1813d5699e..a43270e150 100644 --- a/shared-bindings/index.rst +++ b/shared-bindings/index.rst @@ -17,9 +17,9 @@ SAMD51, SAMD51 Express, and ESP8266. NOTE 2: **SAMD** and/or **SAMD Express** without additional numbers, means both SAMD21 & SAMD51 versions are supported. -================= =============== -Module Supported Ports -================= =============== +================= ============================== +Module Supported Ports +================= ============================== `analogio` **All Supported** `audiobusio` **SAMD/SAMD Express** `audioio` **SAMD Express** @@ -43,7 +43,7 @@ Module Supported Ports `touchio` **SAMD/SAMD Express** `uheap` **Debug (All)** `usb_hid` **SAMD/SAMD Express** -================= =============== +================= ============================== Modules --------- diff --git a/shared-bindings/math/__init__.c b/shared-bindings/math/__init__.c index 76ba80c95b..84827842f8 100644 --- a/shared-bindings/math/__init__.c +++ b/shared-bindings/math/__init__.c @@ -176,7 +176,7 @@ STATIC NORETURN void math_error(void) { //| //| .. function:: pow(x, y) //| - //| Returns `x` to the power of `y`. + //| Returns ``x`` to the power of ``y``. //| //| .. function:: radians(x) //| @@ -188,7 +188,7 @@ STATIC NORETURN void math_error(void) { //| //| .. function:: sqrt(x) //| - //| Returns the square root of `x`. + //| Returns the square root of ``x``. //| //| .. function:: tan(x) //| @@ -299,25 +299,25 @@ MATH_FUN_2(ldexp, ldexp) // .. function:: erf(x) // -// Return the error function of `x`. +// Return the error function of ``x``. // MATH_FUN_1(erf, erf) // .. function:: erfc(x) // -// Return the complementary error function of `x`. +// Return the complementary error function of ``x``. // MATH_FUN_1(erfc, erfc) // .. function:: gamma(x) // -// Return the gamma function of `x`. +// Return the gamma function of ``x``. // MATH_FUN_1(gamma, tgamma) // .. function:: lgamma(x) // -// Return the natural logarithm of the gamma function of `x`. +// Return the natural logarithm of the gamma function of ``x``. // MATH_FUN_1(lgamma, lgamma) #endif diff --git a/shared-bindings/microcontroller/Processor.c b/shared-bindings/microcontroller/Processor.c index a311f1866d..be685b0a82 100644 --- a/shared-bindings/microcontroller/Processor.c +++ b/shared-bindings/microcontroller/Processor.c @@ -37,7 +37,7 @@ //| .. currentmodule:: microcontroller //| //| :class:`Processor` --- Microcontroller CPU information and control -//| -------------------------------------------------------- +//| ------------------------------------------------------------------ //| //| Get information about the microcontroller CPU and control it. //| diff --git a/shared-bindings/microcontroller/__init__.c b/shared-bindings/microcontroller/__init__.c index f261178f0e..0c627cdf9e 100644 --- a/shared-bindings/microcontroller/__init__.c +++ b/shared-bindings/microcontroller/__init__.c @@ -59,11 +59,12 @@ //| //| Pin //| Processor +//| RunMode //| //| .. attribute:: cpu //| -//| CPU information and control, such as `cpu.temperature` and `cpu.frequency` +//| CPU information and control, such as ``cpu.temperature`` and ``cpu.frequency`` //| (clock frequency). //| This object is the sole instance of `microcontroller.Processor`. //| @@ -74,7 +75,7 @@ //| because this stops all other functions from completing. Think of this as an empty //| ``while`` loop that runs for the specified ``(delay)`` time. If you have other //| code or peripherals (e.g audio recording) that require specific timing or -//| processing while you are waiting, explore a different avenue such as using +//| processing while you are waiting, explore a different avenue such as using //| `time.sleep()`. //| STATIC mp_obj_t mcu_delay_us(mp_obj_t delay_obj) { @@ -134,7 +135,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mcu_on_next_reset_obj, mcu_on_next_reset); //| .. method:: reset() //| //| Reset the microcontroller. After reset, the microcontroller will enter the -//| run mode last set by `one_next_reset`. +//| run mode last set by `on_next_reset`. //| //| .. warning:: This may result in file system corruption when connected to a //| host computer. Be very careful when calling this! Make sure the device diff --git a/shared-bindings/random/__init__.c b/shared-bindings/random/__init__.c index fe52c1fc05..cea437e98d 100644 --- a/shared-bindings/random/__init__.c +++ b/shared-bindings/random/__init__.c @@ -79,7 +79,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(random_getrandbits_obj, random_getrandbits); //| .. function:: randrange(stop) //| randrange(start, stop, step=1) //| -//| Returns a randomly selected integer from `range(start, stop, step)`. +//| Returns a randomly selected integer from ``range(start, stop, step)``. //| STATIC mp_obj_t random_randrange(size_t n_args, const mp_obj_t *args) { mp_int_t start = 0; @@ -122,7 +122,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(random_randrange_obj, 1, 3, random_ra //| .. function:: randint(a, b) //| //| Returns a randomly selected integer between a and b inclusive. Equivalent -//| to `randrange(a, b + 1, 1)` +//| to ``randrange(a, b + 1, 1)`` //| STATIC mp_obj_t random_randint(mp_obj_t a_in, mp_obj_t b_in) { mp_int_t a = mp_obj_get_int(a_in); diff --git a/shared-bindings/storage/__init__.c b/shared-bindings/storage/__init__.c index 9c186a0519..6f6a30da6d 100644 --- a/shared-bindings/storage/__init__.c +++ b/shared-bindings/storage/__init__.c @@ -43,9 +43,7 @@ //| The `storage` provides storage management functionality such as mounting and //| unmounting which is typically handled by the operating system hosting Python. //| CircuitPython does not have an OS, so this module provides this functionality -//| directly. Its based on MicroPython's `uos` module but deliberately separates -//| CPython compatible functionality (in `os`) from incompatible functionality -//| (in `storage`). +//| directly. //| //| .. function:: mount(filesystem, mount_path, \*, readonly=False) diff --git a/supervisor/shared/rgb_led_colors.h b/supervisor/shared/rgb_led_colors.h index 12f5cc3d9d..cab7029811 100644 --- a/supervisor/shared/rgb_led_colors.h +++ b/supervisor/shared/rgb_led_colors.h @@ -1,12 +1,12 @@ #define BLACK 0x000000 -#define GREEN 0x001000 -#define BLUE 0x000010 -#define CYAN 0x001010 -#define RED 0x100000 -#define ORANGE 0x100800 -#define YELLOW 0x101000 -#define PURPLE 0x100010 -#define WHITE 0x101010 +#define GREEN 0x003000 +#define BLUE 0x000030 +#define CYAN 0x003030 +#define RED 0x300000 +#define ORANGE 0x302000 +#define YELLOW 0x303000 +#define PURPLE 0x300030 +#define WHITE 0x303030 #define BOOT_RUNNING BLUE #define MAIN_RUNNING GREEN diff --git a/supervisor/shared/rgb_led_status.c b/supervisor/shared/rgb_led_status.c index 4ea0900421..2899c1f5d8 100644 --- a/supervisor/shared/rgb_led_status.c +++ b/supervisor/shared/rgb_led_status.c @@ -29,8 +29,8 @@ #include "rgb_led_status.h" #include "pins.h" -uint8_t rgb_status_brightness = 255; #ifdef MICROPY_HW_NEOPIXEL +uint8_t rgb_status_brightness = 63; #include "shared-bindings/digitalio/DigitalInOut.h" #include "shared-bindings/neopixel_write/__init__.h" static uint8_t status_neopixel_color[3]; @@ -39,7 +39,7 @@ static digitalio_digitalinout_obj_t status_neopixel; #if defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK) - +uint8_t rgb_status_brightness = 255; static uint8_t status_apa102_color[12] = {0, 0, 0, 0, 0xff, 0, 0, 0}; #ifdef CIRCUITPY_BITBANG_APA102 #include "shared-bindings/bitbangio/SPI.h" @@ -196,7 +196,9 @@ uint32_t color_brightness(uint32_t color, uint8_t brightness) { } void set_rgb_status_brightness(uint8_t level){ - rgb_status_brightness = level; + #if defined(MICROPY_HW_NEOPIXEL) || (defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK)) + rgb_status_brightness = level; + #endif } void prep_rgb_status_animation(const pyexec_result_t* result, diff --git a/tools/build_adafruit_bins.sh b/tools/build_adafruit_bins.sh index 6f5175c5d3..0bc3d45515 100755 --- a/tools/build_adafruit_bins.sh +++ b/tools/build_adafruit_bins.sh @@ -2,7 +2,7 @@ rm -rf ports/atmel-samd/build* rm -rf ports/esp8266/build* rm -rf ports/nrf/build* -ATMEL_BOARDS="arduino_zero circuitplayground_express feather_m0_basic feather_m0_adalogger itsybitsy_m0 feather_m0_rfm69 feather_m0_rfm9x feather_m0_express metro_m0_express metro_m4_express trinket_m0 gemma_m0 feather52" +ATMEL_BOARDS="arduino_zero circuitplayground_express feather_m0_basic feather_m0_adalogger itsybitsy_m0_express feather_m0_rfm69 feather_m0_rfm9x feather_m0_express metro_m0_express metro_m4_express pirkey_m0 trinket_m0 gemma_m0 feather52" ROSIE_SETUPS="rosie-ci" PARALLEL="-j 5"