Compare commits

..

574 Commits
v1.3 ... v1.3.8

Author SHA1 Message Date
Paul Sokolovsky
361909e3ca py: Add MP_LIKELY(), MP_UNLIKELY() macros to help branch prediction. 2014-12-29 00:51:24 +02:00
Paul Sokolovsky
1ee1785bed showbc: Print operation mnemonic in BINARY_OP. 2014-12-28 21:43:44 +02:00
Paul Sokolovsky
df103462dc showbc: Make code object start pointer semi-public.
This allows to pring either absolute addresses or relative offsets in jumps
and code references.
2014-12-28 21:37:17 +02:00
Paul Sokolovsky
749575097f vm: Record exception ip only for instructions where exceptions may happen.
Mirroring ip to a volatile memory variable for each opcode is an expensive
operation. For quite a lot of often executed opcodes like stack manipulation
or jumps, exceptions cannot actually happen. So, record ip only for opcode
where that's possible.
2014-12-28 07:37:04 +02:00
Damien George
1570eaf0e3 drivers: Add SD card driver, controlled via SPI bus. 2014-12-27 20:23:14 +00:00
Damien George
7690b13953 stmhal: Add ability to mount custom block device. 2014-12-27 20:20:51 +00:00
Damien George
e2745b307b lib/fatfs: Allow a smaller minimum sector count for fatfs to be created. 2014-12-27 20:20:08 +00:00
Damien George
20236a8a99 stmhal: Upgrade to latest fatfs driver. 2014-12-27 17:36:16 +00:00
Damien George
6b755d827a lib/fatfs: Support our volume names; make some funcs static. 2014-12-27 17:36:16 +00:00
Damien George
c546b66bab lib/fatfs: Upgrade to new FatFs driver, put in lib/ for common use.
Patches to fatfs for our use will follow.
2014-12-27 17:36:16 +00:00
Damien George
83204f3406 py: Allow to properly disable builtin slice operation.
This patch makes the MICROPY_PY_BUILTINS_SLICE compile-time option
fully disable the builtin slice operation (when set to 0).  This
includes removing the slice sytanx from the grammar.  Now, enabling
slice costs 4228 bytes on unix x64, and 1816 bytes on stmhal.
2014-12-27 17:33:30 +00:00
Damien George
e37dcaafb4 py: Allow to properly disable builtin "set" object.
This patch makes MICROPY_PY_BUILTINS_SET compile-time option fully
disable the builtin set object (when set to 0).  This includes removing
set constructor/comprehension from the grammar, the compiler and the
emitters.  Now, enabling set costs 8168 bytes on unix x64, and 3576
bytes on stmhal.
2014-12-27 17:33:30 +00:00
Paul Sokolovsky
3b74c91684 Makefiles: Support py/*.h includes per #1022. 2014-12-27 16:32:52 +02:00
Paul Sokolovsky
8ab6f90674 py: Move to guarded includes for compile.h and related headers. 2014-12-27 16:12:17 +02:00
Paul Sokolovsky
343266ea51 showbc: Refactor to allow inline instruction printing. 2014-12-27 05:01:21 +02:00
Damien George
c55a4d82cf py: Make bytes objs work with more str methods; add tests. 2014-12-24 20:28:30 +00:00
Paul Sokolovsky
7fdb8d78a4 tests: Add run-tests-exp.py, simple MicroPython-based test runner.
This script is rewrite of run-tests-exp.sh, and tries to achieve self-hosted
testsuite running in environments where neither CPython nor unix shell is
available. As run-tests-exp.sh, it requires complete set of .exp files
pre-generated with ./run-test --write-exp.
2014-12-24 16:34:05 +00:00
Damien George
f3a1d673de stmhal: Enable ubinascii module, weak link to binascii. 2014-12-24 16:24:42 +00:00
Dave Hylands
90cd6cd987 docs: Add mention about using USB charger when resetting the filesystem.
It seems the Mac will happily wipe out at least some of the data on
a freshly reset filesytem, if the filesystem was reset while plugged
into the Mac.
2014-12-23 13:22:32 +00:00
Paul Sokolovsky
9c658b6afc unix, windows: Add _os.system() call.
system() is the basic function to support automation of tasks, so have it
available builtin, for example, for bootstrapping rest of micropython
environment.
2014-12-23 12:56:24 +00:00
Damien George
a37656c132 docs: Make admonition for CPy-difference use "attention" class.
This renders it in yellow/orange box on RTD server.
2014-12-22 13:42:30 +00:00
Damien George
74eb44c392 py: Reduce size of VM exception stack element by 1 machine word.
This optimisation reduces the VM exception stack element (mp_exc_stack_t)
by 1 word, by using bit 1 of a pointer to store whether the opcode was a
FINALLY or WITH opcode.  This optimisation was pending, waiting for
maturity of the exception handling code, which has now proven itself.

Saves 1 machine word RAM for each exception (4->3 words per exception).
Increases stmhal code by 4 bytes, and decreases unix x64 code by 32
bytes.
2014-12-22 12:49:57 +00:00
Damien George
81836c28b3 py: Use str_to_int function in more places to reduce code size. 2014-12-21 21:07:03 +00:00
Damien George
01039b5bd8 py: Remove last uses of printf from compile; use proper SyntaxError. 2014-12-21 17:44:27 +00:00
Damien George
584ba6762f py: Move global/nonlocal decl code to compiler for proper SyntaxError.
This patch gives proper SyntaxError exceptions for bad global/nonlocal
declarations.  It also reduces code size: 304 bytes on unix x64, 132
bytes on stmhal.
2014-12-21 17:26:45 +00:00
Damien George
b063b9b36d py: Fix iteration over map in 2 places. 2014-12-21 16:24:09 +00:00
Damien George
7b80d908bf docs: Add RTD local_settings file, to add custom templates. 2014-12-21 11:21:06 +00:00
Damien George
9b561a7c0d docs: Add custom CSS file, with code for admonition. 2014-12-21 00:22:49 +00:00
Paul Sokolovsky
4b60b45bfc stmhal: gccollect.h is superfluous in many places. 2014-12-21 00:58:06 +02:00
Paul Sokolovsky
6aaccc484c stmhal: Use gc_dump_info() function instead of adhoc code. 2014-12-21 00:26:10 +02:00
Paul Sokolovsky
bf19586c53 stmhal: Include MICROPY_HAL_H only if defined.
Helps other ports.
2014-12-20 20:47:35 +02:00
Damien George
6efa66f125 py: Remove unnecessary RULE_none and PN_none from parser. 2014-12-20 18:41:59 +00:00
Damien George
b47ea4eadd py: Add blank and ident flags to grammar rules to simplify parser.
This saves around 100 bytes code space on stmhal, more on unix.
2014-12-20 18:37:50 +00:00
Damien George
4fd7c1a2ac tools, pyboard.py: Write data to pyboard in chunks of 256 bytes.
This speeds up writes significantly.
2014-12-20 18:09:04 +00:00
Damien George
2870d85a11 py: Save a few code bytes in parser; make vars local where possible. 2014-12-20 18:06:08 +00:00
Paul Sokolovsky
978f4ca2e1 run-tests: Allow to run testuite against Windows build on Linux (using Wine).
Just adjust line-endings of micropython.exe output, the rest should be
handled by Wine (automagically on properly configured distro).

To run:

MICROPY_MICROPYTHON=../windows/micropython.exe ./run-tests
2014-12-20 16:53:46 +02:00
stijn
f5efefd5a0 windows: Correctly interpret skipped tests, enable uhashlib and ubinascii 2014-12-20 16:52:22 +02:00
Damien George
6d3ae569cf docs: Add CPy diff note for print_exception; embellish sys.platform. 2014-12-19 22:10:38 +00:00
Damien George
2a3e2b9033 py: Add execfile function (from Python 2); enable in stmhal port.
Adds just 60 bytes to stmhal binary.  Addresses issue #362.
2014-12-19 13:36:17 +00:00
Paul Sokolovsky
8427c5b76c unix/windows: Make sure that process exit code is portable 8-bit value.
This fixes FORCED_EXIT internal flag leaking into Windows exit code.
2014-12-19 00:01:49 +02:00
Damien George
f04329e93b lib/libm: Add acosh, asinh, atanh, tan; get working with stmhal.
acoshf, asinhf, atanhf were added from musl.  mathsincos.c was
split up into its original, separate files (from newlibe-nano-2).
tan was added.

All of the important missing float functions are now implemented,
and pyboard now passes tests/float/math_fun.py (finally!).
2014-12-18 14:44:02 +00:00
Damien George
6936f4626c tests: Get misc/print_exception and pyb/spi working on pyboard. 2014-12-18 13:37:56 +00:00
Paul Sokolovsky
c8b0229bc7 tests: sha256: skip test if uhashlib module is not available. 2014-12-18 00:32:15 +02:00
Gregory
5cf7ac7309 Fix leds.rst
N (mod 4) is 0..3
2014-12-18 00:06:48 +03:00
Paul Sokolovsky
9d944c7fb2 unix: Rename "time" module to "utime" to allow extensibility.
Name choosen per latest conventions and for compatibiity with stmhal port.
2014-12-17 00:13:32 +02:00
Damien George
9642846d71 docs: Define more clearly the behaviour of LED methods.
Addresses issue #1006.
2014-12-16 11:55:46 +00:00
Paul Sokolovsky
0078561303 modffi: Support void (None) return value for Python callback functions. 2014-12-16 00:28:12 +02:00
Paul Sokolovsky
7a4765dbeb tests: Add testcase for ffi callbacks. 2014-12-15 02:18:54 +02:00
Paul Sokolovsky
b62371e8fb modffi: 64-bit cleanness (fixes actual bug in callback arg handling). 2014-12-15 02:18:49 +02:00
Paul Sokolovsky
c0bc3bd736 asmarm: Fix bug with encoding small negative ints using MVN instruction. 2014-12-14 03:24:17 +02:00
Paul Sokolovsky
83d27b0f0b unix: Enable Thumb2 and ARM emitters by default on corresponding archs. 2014-12-14 03:24:17 +02:00
Paul Sokolovsky
138562ccd9 run-tests: Skip native/viper tests based on prefix.
Otherwise, new tests are forgotten to be added to explicit lists. Issue
found running on Debian/ARM.
2014-12-13 00:51:24 +02:00
Damien George
e181c0dc07 py: Fix optimised for-loop compiler so it follows proper semantics.
You can now assign to the range end variable and the for-loop still
works correctly.  This fully addresses issue #565.

Also fixed a bug with the stack not being fully popped when breaking out
of an optimised for-loop (and it's actually impossible to write a test
for this case!).
2014-12-12 17:19:56 +00:00
Damien George
7764f163fa py: Fix label printing in showbc; print sp in vm trace. 2014-12-12 17:18:56 +00:00
Paul Sokolovsky
1ca28bd570 run-tests: Reset MICROPYPATH, to make sure tests use only builtin modules. 2014-12-12 00:58:07 +02:00
Paul Sokolovsky
dbc7854355 run-tests: PEP8 fix. 2014-12-12 00:58:07 +02:00
Paul Sokolovsky
f42b3c7599 tests: Activate recursive_data.py test, now that io.StringIO is available. 2014-12-12 00:58:07 +02:00
Damien George
5fba93a26b tests: Add test for semantics of for-loop that optimisation can break. 2014-12-11 17:40:41 +00:00
Damien George
c33ce606cf py: Fix a semantic issue with range optimisation.
Now you can assign to the range variable within the for loop and it will
still work.

Partially addresses issue #565.
2014-12-11 17:35:23 +00:00
Damien George
f905145c6d tests: Disable print_exception test when using native emitter. 2014-12-11 17:34:55 +00:00
Damien George
184182d14c tests: Fix print_exception test and re-enable it on Travis CI.
Issue was with uPy: on local machine with micropython-lib installed, io
module is available.  Not the case on Travis CI, where only _io module
is available in uPy.
2014-12-11 17:10:25 +00:00
Paul Sokolovsky
66a6caa307 run-tests: Skip print_exception.py on TravisCI, as it irreproducibly fails.
TODO: Figure out what's wrong on Travis.
2014-12-11 15:03:29 +02:00
Damien George
5318cc028a py: Tidy up a few function declarations. 2014-12-10 22:37:07 +00:00
Damien George
7eb2317fa2 py: Remove static from definition of pfenv_printf.
It's used by stmhal, but not unix.
2014-12-10 22:11:01 +00:00
Damien George
969a6b37bf py: Make functions static where appropriate. 2014-12-10 22:08:14 +00:00
Nikita Nazarenko
d51107927d unix: add unlink function to os module 2014-12-10 21:49:24 +00:00
Damien George
4140e19c8a tests: Fix print_exception.py to work on Travis CI. 2014-12-10 21:45:51 +00:00
Paul Sokolovsky
e8487ea1be tests: Add test for print_exception() function. 2014-12-10 20:48:53 +00:00
Paul Sokolovsky
6c3fc74656 docs: Add sys.print_exception(). 2014-12-10 20:31:38 +02:00
Damien George
b4fe6e28eb py: Fix function type: () -> (void). 2014-12-10 18:05:42 +00:00
Damien George
78d702c300 py: Allow builtins to be overridden.
This patch adds a configuration option (MICROPY_CAN_OVERRIDE_BUILTINS)
which, when enabled, allows to override all names within the builtins
module.  A builtins override dict is created the first time the user
assigns to a name in the builtins model, and then that dict is searched
first on subsequent lookups.  Note that this implementation doesn't
allow deleting of names.

This patch also does some refactoring of builtins code, creating the
modbuiltins.c file.

Addresses issue #959.
2014-12-09 16:19:48 +00:00
adminpete
e6e8ad8ab2 drivers, nrf24: Nonblocking send now uses send_start and send_done. 2014-12-09 02:30:22 +00:00
adminpete
706955976c drivers, nrf24: Nonblocking send now done by generator. 2014-12-09 02:29:56 +00:00
Peter Hinch
5deceb842d drivers, nrf24: Add nonblocking send option etc. 2014-12-09 02:29:35 +00:00
Damien George
b66a31c42c stmhal: Allow SPI.init to specify prescaler directly; improve SPI docs. 2014-12-08 21:34:07 +00:00
Damien George
008251180d stmhal: Enhance pyb.freq to configure bus (AHB, APB1, APB2) freqs.
This is useful if you need precise control over the speed of
peripherals (eg SPI clock).
2014-12-08 21:32:55 +00:00
Paul Sokolovsky
46c3ab2004 modsys: Add sys.print_exception(exc, file=sys.stdout) function.
The function is modeled after traceback.print_exception(), but unbloated,
and put into existing module to save overhead on adding another module.
Compliant traceback.print_exception() is intended to be implemented in
micropython-lib in terms of sys.print_exception().

This change required refactoring mp_obj_print_exception() to take pfenv_t
interface arguments.

Addresses #751.
2014-12-08 20:25:49 +00:00
Damien George
d0caaadaee stmhal: Allow network, uselect, usocket mods to be used by other ports.
Remove include of stm32f4xx_hal.h, replace by include of MICROPY_HAL_H
where needed, and make it compile without float support.  This makes
these 3 modules much more generic and usable by other ports.
2014-12-07 17:03:47 +00:00
Damien George
1f8a2f6623 windows: define __USE_MINGW_ANSI_STDIO for all Windows compilers. 2014-12-06 19:51:30 +00:00
Damien George
9de6773237 stmhal: Make SPI bus use DMA for transfers.
Uses DMA if interrupts are enabled, polling if they are disabled.
2014-12-06 17:41:17 +00:00
Paul Sokolovsky
d4f80f58b8 esp8266/README: Fix typos. 2014-12-06 13:34:18 +02:00
Damien George
be6d8be91e py: Rename mp_obj_int_get to mp_obj_int_get_truncated; fix struct.pack.
mp_obj_int_get_truncated is used as a "fast path" int accessor that
doesn't check for overflow and returns the int truncated to the machine
word size, ie mp_int_t.

Use mp_obj_int_get_truncated to fix struct.pack when packing maximum word
sized values.

Addresses issues #779 and #998.
2014-12-05 23:13:52 +00:00
Damien George
451a087075 py: Fix printing of size_t entity; fix qemu-arm for changes to lexer. 2014-12-05 22:50:16 +00:00
Damien George
759cc9bcc8 unix-cpy: Fix build due to change in lexer API. 2014-12-05 21:42:28 +00:00
Damien George
a4c52c5a3d py: Optimise lexer by exposing lexer type.
mp_lexer_t type is exposed, mp_token_t type is removed, and simple lexer
functions (like checking current token kind) are now inlined.

This saves 784 bytes ROM on 32-bit unix, 348 bytes on stmhal, and 460
bytes on bare-arm.  It also saves a tiny bit of RAM since mp_lexer_t
is a bit smaller.  Also will run a bit more efficiently.
2014-12-05 19:35:18 +00:00
Paul Sokolovsky
41c07d5b80 docs: uzlib: Typo fix. 2014-12-05 02:08:30 +02:00
Paul Sokolovsky
adf4c4cea8 docs: Add quick docs for uzlib. 2014-12-05 00:40:35 +02:00
Damien George
c0b3d4540b docs: Update network docs to reflect changes to code. 2014-12-04 19:43:56 +00:00
Damien George
29a1ec1bd6 stmhal: Overhaul network drivers; has generic network protocol in C.
This patch overhauls the network driver interface.  A generic NIC must
provide a set of C-level functions to implement low-level socket control
(eg socket, bind, connect, send, recv).  Doing this, the network and
usocket modules can then use such a NIC to implement proper socket
control at the Python level.

This patch also updates the CC3K and WIZNET5K drivers to conform to the
new interface, and fixes some bugs in the drivers.  They now work
reasonably well.
2014-12-04 18:57:57 +00:00
Damien George
d8f239263d drivers, wiznet5k: Add socket_reset; fix orderly shutdown in recv. 2014-12-04 18:57:18 +00:00
Damien George
32ef3a3517 py: Allow bytes/bytearray/array to be init'd by buffer protocol objects.
Behaviour of array initialisation is subtly different for bytes,
bytearray and array.array when argument has buffer protocol.  This patch
gets us CPython conformant (except we allow initialisation of
array.array by buffer with length not a multiple of typecode).
2014-12-04 15:46:14 +00:00
Paul Sokolovsky
3a5352b483 docs: Add skeleton docs for ure module. 2014-12-04 00:07:00 +02:00
Damien George
cd97a43f8d py, vm: Make unum a local variable for each opcode that uses it.
This makes no change to the generated code, but it's now easier to
understand since unum is not a "global" variable anymore.
2014-12-02 19:25:10 +00:00
Damien George
57c70d6073 stmhal: Move RTC HAL init functions to rtc.c, where they belong.
So can remove unnecessary stm32f4xx_hal_msp.c file.
2014-12-02 12:40:37 +00:00
Damien George
578ea6d4a5 docs: Add links to LCD and AMP skin schematics. 2014-12-02 12:32:39 +00:00
Paul Sokolovsky
d8fd3103fa docs: Add quick docs for ubinascii. 2014-12-02 01:51:56 +02:00
Paul Sokolovsky
d96a916405 docs: Add quick docs for uhashlib. 2014-12-02 00:53:19 +02:00
Paul Sokolovsky
7f0699eedf docs: Sort "micro-library" module list alphabetically. 2014-12-01 20:42:38 +02:00
Paul Sokolovsky
6e8ff9cd68 modmicropython: Move mem_info() and qstr_info() functions from unix port.
TODO: Merge useful functionality from modpyb too.
2014-12-01 20:42:24 +02:00
Damien George
17c5ce3727 tools: Make pyboard.py have infinite timeout when running script.
This makes pyboard.py much more useful for long running scripts.  When
running a script via pyboard.py, it now waits until the script finishes,
with no timeout.  CTRL-C can be used to break out of the waiting if
needed.
2014-11-30 21:30:53 +00:00
Damien George
1960475ed7 stmhal: Make pyb.[u]delay use systick with IRQs, busy loop otherwise.
pyb.delay and pyb.udelay now use systick if IRQs are enabled, otherwise
they use a busy loop.  Thus they work correctly when IRQs are disabled.
The busy loop is computed from the current CPU frequency, so works no
matter the CPU frequency.
2014-11-30 21:23:25 +00:00
Damien George
c7ca01ad96 py: Generalise and reduce code size of array +, += and .extend().
By using the buffer protocol for these array operations, we now allow
addition of memoryview objects, and objects with "incompatible"
typecodes (in this case it just adds bytes naively).  This is an
extension to CPython which seems sensible.  It also reduces the code
size.
2014-11-30 14:01:33 +00:00
Henrik Sölver
d8c2b2a1c4 Update documentation for the CAN class 2014-11-30 01:04:56 +00:00
Damien George
b2e731177e py: Implement +, += and .extend for bytearray and array objs.
Addresses issue #994.
2014-11-30 00:00:55 +00:00
Damien George
19fb1b4dd7 stmhal: Add USB_VCP.setinterrupt method, to disable CTRL-C. 2014-11-29 15:23:21 +00:00
Damien George
b395220ef0 esp8266: Add README.md. 2014-11-29 15:06:20 +00:00
Damien George
7288403b9b tests: Split out float test from builtin_round.py. 2014-11-29 14:47:54 +00:00
Damien George
3b603f29ec Use MP_DEFINE_CONST_DICT macro to define module dicts.
This is just a clean-up of the code.  Generated code is exactly the
same.
2014-11-29 14:39:27 +00:00
Damien George
e636279fe0 esp8266: Move more rodata to irom section.
rodata can only go in iram/irom if it's accessed only using word loads
(ie no byte or half-word access).
2014-11-29 14:36:18 +00:00
Paul Sokolovsky
bfdc205934 modubinascii: Add, with hexlify() implementation. 2014-11-29 13:52:47 +00:00
Damien George
d96e6b14c9 esp8266: Make default ESP_SDK variable work correctly.
When esp-open-sdk is built with STANDALONE=y (the default) then ESP_SDK
is set to the correct value, so that "make" just works.
2014-11-28 18:05:25 +00:00
Damien George
722fab7c2a docs: Bump version to 1.3.7. 2014-11-28 17:48:48 +00:00
inaugurator
9aae41121b Update uheapq.rst
Erratum in froh.
2014-11-28 17:32:29 +00:00
Damien George
fbea810043 esp8266: Change bignum from mpz to longlong; move some rodata to iram.
Some rodata items can go in iram/irom segment, but not others.  With
this patch ESP now has 24256 bytes of heap ram.  It passes 228 out of
248 tests from tests/basics directory.
2014-11-28 14:58:25 +00:00
Damien George
5f10065718 esp8266: Provide sensible default ESP_SDK; deploy 2 the images together. 2014-11-28 10:22:01 +00:00
Paul Sokolovsky
1bbc389d67 esp8266: Allow to override serial port. 2014-11-28 01:54:46 +02:00
Damien George
075d597464 esp8266: New port of Micro Python to ESP8266 wifi module. 2014-11-27 20:30:33 +00:00
Damien George
2399aa03b8 py: Add NLR support for xtensa CPU. 2014-11-27 20:29:33 +00:00
Damien George
92f1ed8f40 stmhal: Enable uhashlib module; add heapq, hashlib weak links.
hashlib test passes on pyboard.
2014-11-27 17:54:37 +00:00
Paul Sokolovsky
df732bb01b pfenv_printf: Properly implement %p format specifier.
Previously, it truncated pointer value to 32 bits on 64-bit systems.
2014-11-27 17:38:03 +00:00
Paul Sokolovsky
1eca32836d builtin: Reimplement __repl_print__() in terms of print().
Before, __repl_print__() used libc printf(), while print() used uPy streams
and own printf() implementation. This led to subtle, but confusing
differences in output when just doing "foo" vs "print(foo)" on interactive
prompt.
2014-11-27 17:38:03 +00:00
Paul Sokolovsky
e5dbe1e283 map: Add empty fixed map.
Useful when need to call kw-receiving functions  without any keywords
from C, etc.
2014-11-27 17:37:07 +00:00
Damien George
317cf18486 stmhal: Remove unnecessary HAL_Delay in readline loop.
The reason for having this delay is to reduce power consumption at the
REPL (HAL_Delay calls __WFI to idle the CPU).  But stdin_rx_chr has a
__WFI in it anyway, so this delay call is not needed.

By removing this call, the readline input can consume characters much
more quickly (before was limited to 1000 chrs/s), and has much reduced
dependency on the specific port.
2014-11-27 17:04:09 +00:00
Damien George
5cbc9e0db0 stmhal: Reduce coupling between USB driver and readline.
This makes it easier to re-use readline.c and pyexec.c from stmhal in
other ports.
2014-11-27 16:58:31 +00:00
Damien George
6f5eb84c19 py: #if guard str_make_new when not needed. 2014-11-27 16:55:47 +00:00
Henrik Sölver
acb92c186c Adding CAN filter management 2014-11-26 18:52:33 +00:00
Damien George
20d239cb28 stmhal: Enable DAC on STM32F4DISC.
Addresses issue #987.
2014-11-25 11:42:26 +00:00
Paul Sokolovsky
4a1c80c293 tests: Add test for hashlib.sha256 . 2014-11-22 14:54:02 +02:00
Paul Sokolovsky
a944183b35 moduhashlib: Integrate sha256 implementation. 2014-11-22 14:48:17 +02:00
Paul Sokolovsky
63e02e8cc0 moduhashlib: Add sha256 implementation from "crypto-algorithms" project.
https://github.com/B-Con/crypto-algorithms revision 100f4ff
2014-11-22 14:47:52 +02:00
Paul Sokolovsky
f4b19c873f moduhashlib: Initial module skeleton. 2014-11-22 14:47:46 +02:00
Damien George
df242facdc drivers, cc3000: Cleaning up, make local functions static. 2014-11-21 19:46:24 +00:00
stijn
b89eaaa2e2 windows: Update config with latest features
- update mpconfigport.h to reflect latest unix version
- fix compilation error in modure due to msvc not allowing dynamic arrays
2014-11-21 19:38:33 +00:00
Damien George
c9f8f653ad py: Add support for float/double arrays in array module.
Addresses issue #981.
2014-11-21 18:16:25 +00:00
blmorris
9d1ca65b59 Set PYTHONIOENCODING='utf-8' so that unicode tests can pass on CPython on
systems where another encoding is set in the locale
2014-11-19 10:44:31 -05:00
Damien George
3bdb23d4d3 README: Update link to logo. 2014-11-17 00:41:54 +00:00
Damien George
5694cc5490 py: Make stream seek correctly check for ioctl fn; add seek for textio. 2014-11-16 23:56:37 +00:00
Paul Sokolovsky
91386eee26 ports: Define mp_off_t. 2014-11-17 00:16:14 +02:00
Paul Sokolovsky
fa2edabc5c stmhal: Switch to file.seek() implementation using stream ioctl. 2014-11-17 00:16:14 +02:00
Paul Sokolovsky
c7d5500142 tests: Add test for file.seek(). 2014-11-17 00:16:14 +02:00
Paul Sokolovsky
838eb1fa2d stream: Implement seek operation support via ioctl, wrapped in generic method.
Also, implement for unix port.
2014-11-17 00:16:14 +02:00
Paul Sokolovsky
f4a6a577ab stream: Convert .ioctl() to take fixed number of args.
This is more efficient, as allows to use register calling convention.
If needed, a structure pointer can be passed as argument to pass more
data.
2014-11-17 00:16:14 +02:00
Damien George
5228854f0e docs: Fix RTD build configuration.
ReadTheDocs needs the root directory in its search path so it finds
topindex.html.
2014-11-15 21:33:07 +00:00
Damien George
d1b42d7b51 stmhal: Improve CAN init so that it can take sjw, bs1, bs2 args.
Also update docs to explain how CAN baudrate is determined.
2014-11-15 21:28:14 +00:00
Damien George
224fee0e10 stmhal: Fix HAL error raising; make test for it.
Addresses issue #968.
2014-11-15 20:39:44 +00:00
evildmp
aec189a5ba docs: Add optional sphinx_rtd_theme; add docs build instructions.
The sphinx_rtd_theme is used by ReadTheDocs to render a pretty looking
documentation.  If you have this theme installed locally then your
locally-compiled docs will look exactly like the published
documentation.   Otherwise it falls back to the default theme.
2014-11-15 19:01:19 +00:00
Matthias
ca0b0cb83f Document parameter "data" of i2c.mem_read() more clear
Hi,

i would like to add a little clarification to the parameter "data" of i2c.mem_read(): I misunderstood 

        ``data`` can be an integer or a buffer to read into

as "i can give a integer variable to read a integer into" .  This pull-request adds the following clarification:

         ``data`` can be an integer (number of bytes to read) or a buffer to read into

Thanks for your great work!

Best wishes,
Matthias
2014-11-15 18:31:37 +00:00
Damien George
4df85e49d4 tests: Add test for hash of user defined class. 2014-11-15 18:30:01 +00:00
stijn
e00eeaf4cd py: Use __hash__ method if a type defines it 2014-11-15 18:24:22 +00:00
Paul Sokolovsky
d8474d3617 docs: select: Describe extra details. 2014-11-09 01:48:05 +02:00
Sven Wegener
b98c162c52 py: Fix order-only dependencies in mkrules.mk and py.mk.
Currently compilation sporadically fails, because the automatic
dependency gets created *during* the compilation of objects.

OBJ is a auperset of PY_O and the dependencies apply to all objects.

Signed-off-by: Sven Wegener <sven.wegener@stealer.net>
2014-11-06 18:48:38 +00:00
Damien George
1e9a92f84f py: Use shorter, static error msgs when ERROR_REPORTING_TERSE enabled.
Going from MICROPY_ERROR_REPORTING_NORMAL to
MICROPY_ERROR_REPORTING_TERSE now saves 2020 bytes ROM for ARM Thumb2,
and 2200 bytes ROM for 32-bit x86.

This is about a 2.5% code size reduction for bare-arm.
2014-11-06 17:36:16 +00:00
Damien George
b6b34cd3f6 py: Remove obsolute function declaration. 2014-11-06 17:31:18 +00:00
Sven Wegener
bfb18a714b py: Add order-only dependency for py-version.h
Else the directory might not exist.

Signed-off-by: Sven Wegener <sven.wegener@stealer.net>
2014-11-05 22:52:51 +00:00
Sven Wegener
0e0ae97975 stmhal: Declare variables extern in include files
Else we end up with several instances of the variable.

Signed-off-by: Sven Wegener <sven.wegener@stealer.net>
2014-11-05 22:52:51 +00:00
Sven Wegener
1a5a6d1403 bare-arm: Add dummy __assert_func and __fatal_error
Required to build bare-arm with debugging.

Signed-off-by: Sven Wegener <sven.wegener@stealer.net>
2014-11-05 22:52:51 +00:00
Sven Wegener
238ab5013b py: Deactivate more code without MICROPY_PY_SYS
When compiler optimization has been turned on, gcc knows that this code
block is not going to be executed. But with -O0 it complains about
path_items being used uninitialized.

Signed-off-by: Sven Wegener <sven.wegener@stealer.net>
2014-11-05 22:52:51 +00:00
Paul Sokolovsky
98d8d59c33 unix: Allow -X heapsize number take 'w' specifier for word size adjustment.
The specifier should go after the number, before size suffix like 'k' or 'm'.
E.g.: "-X heapsize=100wk" will use 100K heap on 32-bit system and 200K - on
64-bit.
2014-11-05 22:47:30 +00:00
Damien George
7860c2a68a py: Fix some macros defines; cleanup some includes. 2014-11-05 21:16:41 +00:00
Damien George
be8e99c7d4 py: Allow bytes object as argument to some str methods.
This turns failing assertions to type exceptions for things like
b"123".find(...).  We still don't support operations like this on bytes
objects (unlike CPython), but at least it no longer crashes.
2014-11-05 16:45:54 +00:00
Damien George
a65c03c6c0 py: Allow +, in, and compare ops between bytes and bytearray/array.
Eg b"123" + bytearray(2) now works.  This patch actually decreases code
size while adding functionality: 32-bit unix down by 128 bytes, stmhal
down by 84 bytes.
2014-11-05 16:30:34 +00:00
Paul Sokolovsky
346aacf27f unix: fast: Set initial module dict size big to have high pystone score.
For this, introduce MICROPY_MODULE_DICT_SIZE config setting.
2014-11-05 00:30:21 +02:00
Damien George
ff8d0e071c docs: Bump version to 1.3.6.
This needs to be done before actually tagging the new version.
2014-11-04 19:04:12 +00:00
Damien George
0e3722137f docs: Update front page to display date of last update. 2014-11-04 18:51:29 +00:00
Damien George
8e701604d5 docs: Add links from quickref to pyb classes. 2014-11-04 18:25:20 +00:00
Damien George
bc0bc764fc docs: Add debounce tutorial; order Pin methods; add pull resistor info. 2014-11-04 18:07:06 +00:00
Damien George
183ac71dc8 docs: Add pdf size info to datasheet links. 2014-11-03 22:21:25 +00:00
Damien George
1e3fde0a10 docs: Add skin imgs; change external links to micropython.org/resources. 2014-11-03 22:14:23 +00:00
Damien George
72165c01f0 docs: Adjust table spacing in topindex page. 2014-11-03 20:48:43 +00:00
Damien George
ff319dffad py: Explicitly set uninitialised struct member to false.
Uninitialised struct members get a default value of 0/false, so this is
not strictly needed.  But it actually decreases code size because when
all members are initialised the compiler doesn't need to insert a call
to memset to clear everything.  In other words, setting 1 extra member
to 0 uses less code than calling memset.

ROM savings in bytes: 32-bit unix: 100; bare-arm: 44; stmhal: 52.
2014-11-03 16:18:51 +00:00
Damien George
0344fa1ddf py: Fix builtin callable so it checks user-defined instances correctly.
Addresses issue #953.
2014-11-03 16:09:39 +00:00
Damien George
2cd79fa924 Merge branch 'szinya-master' 2014-11-03 10:22:59 +00:00
Márton Szinovszki
bfd11a35db docs: Fix typo in Fading LEDs 2014-11-03 09:42:38 +01:00
Damien George
f6e825b42e docs: Disable logo and add spacing to top index. 2014-11-02 23:45:29 +00:00
Damien George
6e6dfdc56b docs: Make custom index page; add more docs. 2014-11-02 23:37:02 +00:00
Paul Sokolovsky
1060baa2c2 unix: Provide "fast" target to build interpreter for benchmarking.
This build is primarily intended for benchmarking, and may have random
features enabled/disabled to get high scores in synthetic benchmarks.
The intent is to show/prove that MicroPython codebase can compete with
CPython, when configured appropriately. But the main MicroPython aim
still remains to optimize for memory usage (which inevitibly leads to
performance degradation in some areas on some workloads).
2014-11-02 18:17:43 +02:00
Damien George
38bd762121 stmhal: Improve pyb.freq to allow 8 and 16MHz (not usable with USB).
Also restrict higher frequencies to have a VCO_OUT frequency below
432MHz, as specified in the datasheet.

Docs improved to list allowed frequencies, and explain about USB
stability.
2014-11-02 15:10:15 +00:00
Paul Sokolovsky
039887a0ac py: Fix bug with right-shifting small ints by large amounts.
Undefined behavior in C, needs explicit check.
2014-11-02 02:41:30 +02:00
Damien George
a58713a899 docs: Cleanup and update some docs. 2014-10-31 22:21:37 +00:00
Damien George
c7da7838ba tests: Add heapalloc.py.exp, since CPython can't generate it. 2014-10-31 22:09:40 +00:00
Damien George
109c1de015 py: Make gc.enable/disable just control auto-GC; alloc is still allowed.
gc.enable/disable are now the same as CPython: they just control whether
automatic garbage collection is enabled or not.  If disabled, you can
still allocate heap memory, and initiate a manual collection.
2014-10-31 21:30:46 +00:00
Damien George
4029f51842 stmhal: Fix UART so bits counts number of data bits, not incl parity.
Addresses issue #950.
2014-10-31 20:28:10 +00:00
Damien George
1559a97810 py: Add builtin round function.
Addresses issue #934.
2014-10-31 11:28:50 +00:00
Damien George
fa73c9cb25 docs: Add 2 images for tutorials. 2014-10-31 01:43:37 +00:00
Damien George
88d3054ac0 docs: Import documentation from source-code inline comments.
The inline docs (prefixed with /// in .c files) have been converted to
RST format and put in the docs subdirectory.
2014-10-31 01:37:19 +00:00
Damien George
7c4445afe1 tools: Make gendoc.py able to output RST format. 2014-10-31 01:36:11 +00:00
Damien George
1a8573ed0e stmhal: Update some inlined docs for network and CAN. 2014-10-31 01:12:54 +00:00
Damien George
47f349e7de docs: Fix links to images and other parts of the docs. 2014-10-31 00:58:23 +00:00
Shuning Bian
c92ef361c7 docs: Add tutorial for fading LED using PWM, with fritzing image 2014-10-31 00:49:17 +00:00
Damien George
4ef67d30f1 stmhal: Implement support for RTS/CTS hardware flow control in UART.
This is experimental support.  API is subject to changes.  RTS/CTS
available on UART(2) and UART(3) only.  Use as:

    uart = pyb.UART(2, 9600, flow=pyb.UART.RTS | pyb.UART.CTS)
2014-10-31 00:40:57 +00:00
Damien George
9a41b32b3f stmhal: Add ioctl to USB_VCP object, so it works with select.
This patch also enables non-blocking streams on stmhal port.

One can now make a USB-UART pass-through function:

def pass_through(usb, uart):
    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))
2014-10-31 00:12:02 +00:00
Damien George
efc49c5591 stmhal: Improve CAN print function. 2014-10-30 23:16:05 +00:00
Henrik Sölver
6a15ac80dc tests: Added and adapted CAN tests for extended messages 2014-10-30 23:16:01 +00:00
Henrik Sölver
504636815e stmhal: Added support for extended CAN frames. 2014-10-30 23:16:01 +00:00
stijn
0e557facb9 mpz: Fix 64bit msvc build
msvc does not treat 1L a 64bit integer hence all occurences of shifting it left or right
result in undefined behaviour since the maximum allowed shift count for 32bit ints is 31.
Forcing the correct type explicitely, stored in MPZ_LONG_1, solves this.
2014-10-30 23:00:24 +00:00
Paul Sokolovsky
e62a0fe367 objstr: Allow to convert any buffer proto object to str.
Original motivation is to support converting bytearrays, but easier to just
support buffer protocol at all.
2014-10-31 00:03:53 +02:00
Paul Sokolovsky
31619cc589 py: mp_obj_str_get_str(): Work with bytes too.
It should be fair to say that almost in all cases where some API call
expects string, it should be also possible to pass byte string. For example,
it should be open/delete/rename file with name as bytestring. Note that
similar change was done quite a long ago to mp_obj_str_get_data().
2014-10-31 00:00:39 +02:00
Damien George
11aa91615e stmhal: Fix ptr arith in CC3000 code; enable network build in travis. 2014-10-30 15:28:15 +00:00
Paul Sokolovsky
8bb71f0b06 moductypes: Make .sizeof() work with bytearrays. 2014-10-30 03:50:37 +02:00
Paul Sokolovsky
66d08eb4fe moductypes: Add test for accessing UINT8 array. 2014-10-30 03:50:37 +02:00
Paul Sokolovsky
6d287a6a02 moductypes: When dereferencing a field which is array of uint8, use bytearray.
Because bytearrays are much friendlier to work with, e.g. they can be printed
easily.
2014-10-30 03:50:34 +02:00
Paul Sokolovsky
2559e13957 moductypes: Make sure we can apply .sizeof() to all aggregate types.
Before, sizeof() could be applied to a structure field only if that field
was itself a structure. Now it can be applied to PTR and ARRAY fields too.
It's not possible to apply it to scalar fields though, because as soon as
scalar field (int or float) is dereferenced, its value is converted into
Python int/float value, and all original type info is lost. Moreover, we
allow sizeof of type definitions too, and there int is used to represent
(scalar) types. So, we have ambiguity what int may be - either dereferenced
scalar structure field, or encoded scalar type. So, rather throw an error
if user tries to apply sizeof() to int.
2014-10-30 03:50:23 +02:00
Paul Sokolovsky
b1422de12f py: Allow to override port config file and thus have >1 configs per port.
Use it like:

make CFLAGS_EXTRA='-DMP_CONFIGFILE="<mpconfigport_my.h>"'
2014-10-29 23:37:45 +00:00
stijn
49c47da804 Fix errors after enabling -Wpointer-arith 2014-10-29 15:42:38 +00:00
stijn
4e54c876a7 Add -Wpointer-arith flag to prevent problems with pointer arithmetic on void* 2014-10-29 10:29:09 +01:00
Damien George
ccedf000ed docs: Increase size of pyboard pinout. 2014-10-26 22:58:18 +00:00
Paul Sokolovsky
429e3f077e unix: Make -v dump memory info at exit.
Also, move bytecode dumps to -v -v, because they're too verbose for just -v.
2014-10-26 22:36:56 +00:00
Damien George
8768f8ad4b docs: Add quick reference page, with pinout and short example code. 2014-10-26 22:11:34 +00:00
Damien George
e4e52f5370 stmhal: Allow DAC object to be initialised from a pin.
Eg: dac = DAC(Pin.board.X5)
2014-10-26 21:46:06 +00:00
Paul Sokolovsky
e503512f83 unix: Implement -m option (execute module from stdlib).
Support for packages as argument not implemented, but otherwise error and
exit handling should be correct. This for example will allow to do:

pip-micropython install micropython-test.pystone
micropython -m test.pystone
2014-10-26 15:54:19 +00:00
Damien George
bc1488a05f stmhal: Improve REPL control codes; improve pyboard.py script.
Improvements are:

2 ctrl-C's are now needed to truly kill running script on pyboard, so
make CDC interface allow multiple ctrl-C's through at once (ie sending
b'\x03\x03' to pyboard now counts as 2 ctrl-C's).

ctrl-C in friendly-repl can now stop multi-line input.

In raw-repl mode, use ctrl-D to indicate end of running script, and also
end of any error message.  Thus, output of raw-repl is always at least 2
ctrl-D's and it's much easier to parse.

pyboard.py is now a bit faster, handles exceptions from pyboard better
(prints them and exits with exit code 1), prints out the pyboard output
while the script is running (instead of waiting till the end), and
allows to follow the output of a previous script when run with no
arguments.
2014-10-26 15:39:22 +00:00
Damien George
b2f19b8d34 tests: Get builtin_compile to skin properly on pyboard. 2014-10-26 15:38:28 +00:00
Damien George
480a7ce58f stmhal: Change SPI phase spec to 0,1 to match standard conventions.
Was 1 or 2, now 0 or 1 (respectively).  0 means sample MISO on first
edge, 1 means sample on second edge.

Addresses issue #936.
2014-10-26 13:54:31 +00:00
Damien George
de3c806965 py: Fix memoryview referencing so it retains ptr to original buffer.
This way, if original parent object is GC'd, the memoryview still points
to the underlying buffer data so that buffer is not GC'd.
2014-10-26 13:20:50 +00:00
Damien George
c76af32575 unix/windows: Disable sigaction on windows port. 2014-10-26 00:42:41 +01:00
Damien George
b0b0012fd8 py: Fix VM dispatch following a pending exception check. 2014-10-26 00:33:23 +01:00
Sebastian Plamauer
91bd4e8a23 changed file paths to new names 2014-10-25 23:59:33 +01:00
Damien George
124df6f8d0 py: Add mp_pending_exception global variable, for VM soft interrupt.
This allows to implement KeyboardInterrupt on unix, and a much safer
ctrl-C in stmhal port.  First ctrl-C is a soft one, with hope that VM
will notice it; second ctrl-C is a hard one that kills anything (for
both unix and stmhal).

One needs to check for a pending exception in the VM only for jump
opcodes.  Others can't produce an infinite loop (infinite recursion is
caught by stack check).
2014-10-25 23:37:57 +01:00
Damien George
d7353fe6fe stmhal: Change USB PID when in CDC+HID mode.
This gets CDC+HID working on Windows, since it needs a different PID for
a different USB configuration.

Thanks to tmbinc and dhylands.
2014-10-25 22:55:07 +01:00
Damien George
627852019b tests: Add test for compile builtin. 2014-10-25 22:07:25 +01:00
Damien George
c9fc620723 py: Implement compile builtin, enabled only on unix port.
This should be pretty compliant with CPython, except perhaps for some
corner cases to do with globals/locals context.

Addresses issue #879.
2014-10-25 22:07:25 +01:00
Paul Sokolovsky
e5a3759ff5 py: Factor out mp_obj_is_package() function. 2014-10-25 22:31:33 +03:00
Paul Sokolovsky
8becca7c82 py: mp_builtin___import__(): Add const to arg type. 2014-10-25 22:31:26 +03:00
Damien George
8456cc017b py: Compress load-int, load-fast, store-fast, unop, binop bytecodes.
There is a lot potential in compress bytecodes and make more use of the
coding space.  This patch introduces "multi" bytecodes which have their
argument included in the bytecode (by addition).

UNARY_OP and BINARY_OP now no longer take a 1 byte argument for the
opcode.  Rather, the opcode is included in the first byte itself.

LOAD_FAST_[0,1,2] and STORE_FAST_[0,1,2] are removed in favour of their
multi versions, which can take an argument between 0 and 15 inclusive.
The majority of LOAD_FAST/STORE_FAST codes fit in this range and so this
saves a byte for each of these.

LOAD_CONST_SMALL_INT_MULTI is used to load small ints between -16 and 47
inclusive.  Such ints are quite common and now only need 1 byte to
store, and now have much faster decoding.

In all this patch saves about 2% RAM for typically bytecode (1.8% on
64-bit test, 2.5% on pyboard test).  It also reduces the binary size
(because bytecodes are simplified) and doesn't harm performance.
2014-10-25 20:23:13 +01:00
Damien George
1084b0f9c2 py: Store bytecode arg names in bytecode (were in own array).
This saves a lot of RAM for 2 reasons:

1. For functions that don't have default values, var args or var kw
args (which is a large number of functions in the general case), the
mp_obj_fun_bc_t type now fits in 1 GC block (previously needed 2 because
of the extra pointer to point to the arg_names array).  So this saves 16
bytes per function (32 bytes on 64-bit machines).

2. Combining separate memory regions generally saves RAM because the
unused bytes at the end of the GC block are saved for 1 of the blocks
(since that block doesn't exist on its own anymore).  So generally this
saves 8 bytes per function.

Tested by importing lots of modules:

- 64-bit Linux gave about an 8% RAM saving for 86k of used RAM.
- pyboard gave about a 6% RAM saving for 31k of used RAM.
2014-10-25 20:23:13 +01:00
Paul Sokolovsky
fcff4663dd unix: Allow -X heapsize= option take numbers with K & M suffixes.
For kilobytes and megabytes respectively.
2014-10-25 17:00:55 +01:00
Damien George
8204db6831 stmhal: Change fresh boot.py and main.py to use \r\n newlines.
This is so it's compatible with Windows.
2014-10-25 01:14:39 +01:00
Damien George
21dfd207ca stmhal: Fill in USB class/subclass/proto for CDC+HID device.
Also change HID device from keyboard to mouse (should have been mouse
all along).
2014-10-25 01:14:39 +01:00
Felix Domke
a64d5d67b5 USB CDC ACM: populate bFunction{Class,SubClass,Protocol} in the interface association descriptor 2014-10-25 01:14:39 +01:00
Damien George
0b13f3e026 py: Improve memory usage debugging; better GC AT dumping.
In unix port, mem_info(1) now prints pretty GC alloc table.
2014-10-24 23:12:25 +01:00
Damien George
564963a170 py: Fix debug-printing of bytecode line numbers.
Also move the raw bytecode printing code from emitglue to mp_bytecode_print.
2014-10-24 14:42:50 +00:00
Damien George
d00d8ac95c py: Use mp_uint_t where appropriate in stream functions. 2014-10-24 11:26:12 +00:00
Damien George
e294bee45b stmhal: Use stream's readinto. 2014-10-24 11:19:01 +00:00
Damien George
e5b1b7348a stmhal: Fix pin af definition: TIM2_CH1_ETR -> TIM2_CH1/TIM2_ETR. 2014-10-23 22:07:24 +01:00
Paul Sokolovsky
e2f8d98525 stream: Add optional 2nd "length" arg to .readinto() - extension to CPython.
While extension to file.readinto() definition of CPython, the additional arg
is similar to what in CPython available in socket.recv_into().
2014-10-23 21:43:59 +03:00
Damien George
185cb0d943 stmhal: Use OSError with POSIX error code for HAL errors.
Addresses issue #921.
2014-10-23 14:25:32 +01:00
Damien George
e7bb0443cd py: Properly free string parse-node; add assertion to gc_free. 2014-10-23 14:13:05 +01:00
Damien George
dd4f4530ab py: Add builtin memoryview object (mostly using array code). 2014-10-23 13:34:35 +01:00
Damien George
3aa09f5784 py: Use MP_OBJ_NULL instead of NULL in a few places. 2014-10-23 12:06:53 +01:00
Damien George
37378f8a9d py: Clean up edge cases of malloc/realloc/free. 2014-10-23 12:02:00 +01:00
Damien George
f5d69794a8 extmod: Add uheapq module. 2014-10-22 23:20:15 +01:00
Damien George
e72be1b999 py: Fix smallint modulo with negative arguments.
Addresses issue #927.
2014-10-22 23:05:50 +01:00
Damien George
5fc42a6c97 tools, pydfu: Some fixes to support Python 3. 2014-10-22 20:27:43 +01:00
Dave Hylands
842210f53a Add pydfu.py to the micropython tree. Use dfu_util bgy default
You can do:

make USE_PYDFU=1 deploy

to use pydfu.py
2014-10-22 20:18:38 +01:00
Damien George
e7a478204a py: Remove unused and unneeded SystemError exception.
It's purpose is for internal errors that are not catastrophic (ie not as
bad as RuntimeError).  Since we don't use it, we don't need it.
2014-10-22 19:42:55 +01:00
Damien George
efa04eafd3 stmhal: Add MMA_INT/PB2 to available pins on PYBV10.
This allows you to register ExtInt on the MMA interrupt pin.
2014-10-22 19:31:27 +01:00
Dave Hylands
d46a822262 Fixed TIM2_CH1 definition.
TIM2_CH1_ETR is really bundling 2 functions to the same pin:
TIM2_CH1 (where its used as a channel)
TIM2_ETR (where iss used as an external trigger).

I fixed most of these a while back, but it looks like I missed this one.
2014-10-22 19:16:51 +01:00
Damien George
3be6984b8f stmhal: Don't return SystemExit value from parse_compile_execute.
There is no need, since we don't (currently) use the value.
2014-10-22 19:14:20 +01:00
Dave Hylands
8d62bbd46a Add pyb.hard_reset, and make sys.exit() or raise SystemExit do a soft reset. 2014-10-22 19:14:20 +01:00
Damien George
3e42570538 stmhal: Change cc3k.recv to only make 1 call to underlying recv().
Also make cc3k.send and cc3k.recv independent functions (not wrapped by
stream write/read).  Also make wiznet5k.recv more memory efficient.

This might address issue #920.
2014-10-22 01:10:53 +01:00
Damien George
481d714bd5 stmhal: Overhaul UART class to use read/write, and improve it.
UART object now uses a stream-like interface: read, readall, readline,
readinto, readchar, write, writechar.

Timeouts are configured when the UART object is initialised, using
timeout and timeout_char keyword args.

The object includes optional read buffering, using interrupts.  You can set
the buffer size dynamically using read_buf_len keyword arg.  A size of 0
disables buffering.
2014-10-21 22:15:20 +01:00
Damien George
20f59e182e py: Make mp_const_empty_bytes globally available. 2014-10-21 21:02:56 +01:00
Damien George
b1e217222e Merge pull request #922 from swegener/for-upstream
stmhal: Set entry point for ELF binary debugging
2014-10-21 20:58:29 +01:00
stijn
a3efe04dce Use mode/encoding kwargs in io and unicode tests
mode argument is used to assert it works
encoding argument is used to make sure CPython uses the correct encoding
as it does not automatically use utf-8
2014-10-21 22:10:38 +03:00
stijn
2fe4cf7761 Implement kwargs for builtin open() and _io.FileIO
This makes open() and _io.FileIO() more CPython compliant.
The mode kwarg is fully iplemented.
The encoding kwarg is allowed but not implemented; mainly to allow
the tests to specify encoding for CPython, see #874
2014-10-21 22:10:01 +03:00
Sven Wegener
abf0f07a5a stmhal: Set entry point for ELF binary debugging
When loading the ELF binary to the board with a debugger, the debugger
needs to know at which point to start executing the code. Currently the
entry point defaults to the start of the .text section.

Signed-off-by: Sven Wegener <sven.wegener@stealer.net>
2014-10-21 16:48:32 +02:00
Damien George
072bd07f17 stmhal: Add retry to SD card init.
This fixed an issue with a certain SD card sometimes not initialising
first time round.  See issue #822 for related, and thanks to
@iabdalkader for the idea.
2014-10-20 00:04:27 +01:00
Damien George
0c3955b506 examples: Update conwaylife to work with new LCD API. 2014-10-19 19:02:34 +01:00
Damien George
21ca2d76a2 py: Partially fix viper multi-comparison; add test for it. 2014-10-19 19:00:51 +01:00
Damien George
9c9db3a7a1 tools, pyboard.py: Allow exec argument to be bytes or str. 2014-10-19 14:54:52 +01:00
Paul Sokolovsky
1a55b6a787 unix, stmhal: Implement file.readinto() method.
Also, usocket.readinto(). Known issue is that .readinto() should be available
only for binary files, but micropython uses single method table for both
binary and text files.
2014-10-18 22:44:07 +03:00
Damien George
c92672d7f8 unix: Make -c option parse input script as a file, as per CPython.
Addresses issue #915.
2014-10-17 23:51:39 +01:00
Damien George
b7a4b0f86f py: Improve stream_read so it doesn't need to alloc 2 bits of heap. 2014-10-17 23:34:06 +01:00
Paul Sokolovsky
297d8469b8 modure: Update to re1.5 v0.6.1, fixed and extended character class support. 2014-10-17 22:25:18 +03:00
Damien George
391db8669b py: Add more compiler optimisations for constant if/while conditions. 2014-10-17 17:57:33 +00:00
Damien George
235f9b33c8 py: Simplify compilation of elif blocks. 2014-10-17 17:30:16 +00:00
Damien George
9870fdd4b0 tests: Add test for nested while with exc and break. 2014-10-17 17:28:25 +00:00
Damien George
c30595eb1b py: Add more debug printing code in gc_dump_alloc_table. 2014-10-17 14:12:57 +00:00
Damien George
090c9236e8 py: Fix compiling of nested while/for and exception handler.
Addresses issue #912.
2014-10-17 14:08:49 +00:00
Damien George
37ada236b3 py: Take gc_pool_start out of bss section, to reclaim 1st block of heap. 2014-10-16 21:50:39 +01:00
Paul Sokolovsky
923a8a8320 stream: Handle non-blocking errors in readline() properly.
Just like they handled in other read*(). Note that behavior of readline()
in case there's no data when it's called is underspecified in Python lib
spec, implemented to behave as read() - return None.
2014-10-16 12:22:52 +03:00
Paul Sokolovsky
0c7b26c0f8 stream: Return errno value as first arg of OSError exception.
This is CPython-compatible convention established yet in acb13886fc.
2014-10-16 02:58:52 +03:00
Paul Sokolovsky
067ae1269d objclosure: Fix printing of generator closures.
The code previously assumed that only functions can be closed over.
2014-10-16 00:14:01 +03:00
Damien George
9b0b373e5e py: Fix GC realloc issue, where memory chunks were never shrunk.
Previously, a realloc to a smaller memory chunk size would not free the
unused blocks in the tail of the chunk.
2014-10-15 18:24:47 +00:00
Damien George
4859edb95b py: Fix dummy definition of BEGIN/END_ATOMIC_SECTION. 2014-10-15 17:33:24 +00:00
Paul Sokolovsky
95908b0f50 modure: Update to re1.5 v0.6, support for char sets/classes ([a-c]). 2014-10-15 04:44:07 +03:00
Damien George
d27c0bb3aa Merge pull request #905 from pfalcon/remove-zlibd
Remove zlibd, superceded by uzlib
2014-10-13 18:04:16 +01:00
Paul Sokolovsky
911c00bbc5 modzlibd: Remove, superceded by moduzlib. 2014-10-13 14:13:22 +03:00
Paul Sokolovsky
e6c5a63fab windows: Enable moduzlib instead of modzlibd. 2014-10-13 14:12:32 +03:00
Damien George
4b71c056ef moduzlib: Fix fn prototype and some code style; use it in stmhal port. 2014-10-12 23:35:38 +01:00
Damien George
29f5682621 Merge pull request #904 from pfalcon/moduzlib
Module "uzlib" - based on similarly named library
2014-10-12 23:25:24 +01:00
Paul Sokolovsky
bfb6af857a moduzlib: Import uzlib v1.1.
https://github.com/pfalcon/uzlib
2014-10-13 00:09:43 +03:00
Paul Sokolovsky
34162872b1 moduzlib: Integrate into the system. 2014-10-13 00:07:44 +03:00
Paul Sokolovsky
426bb58b23 moduzlib: New zlib-like module, based on uzlib. 2014-10-13 00:07:43 +03:00
Damien George
50062587c7 stmhal: Oops: rename mod files in Makefile. 2014-10-12 20:35:21 +01:00
Damien George
136b5cbd76 stmhal: Rename module files to keep consistency with module name. 2014-10-12 20:24:55 +01:00
Damien George
0107e90328 stmhal: Enable module weak links.
os, time, select modules are now prefixed with u, but are still
available (via weak links) as their original names.

ure and ujson now available as re and json via weak links.
2014-10-12 20:23:47 +01:00
Damien George
c14a81662c py: Add module weak link support.
With this patch a port can enable module weak link support and provide
a dict of qstr->module mapping.  This mapping is looked up only if an
import fails to find the requested module in the filesystem.

This allows to have the builtin module named, eg, usocket, and provide
a weak link of "socket" to the same module, but this weak link can be
overridden if a file by the name "socket.py" is found in the import
path.
2014-10-12 20:18:40 +01:00
Damien George
3c34d4140d py: Fix x86 viper code generation, mem8 <-> mem16 for load. 2014-10-12 16:10:25 +00:00
Damien George
91cfd414c0 py: Implement native load for viper.
Viper can now do: ptr8(buf)[0], which loads a byte from a buffer using
machine instructions.
2014-10-12 16:59:29 +01:00
Damien George
1ef2348df0 py: Implement and,or,xor native ops for viper. 2014-10-12 14:21:06 +01:00
Paul Sokolovsky
1606607bd4 modure: Make sure that re1.5 compiled in only of modure itself is enabled.
This is achieved by including re1.5 *.c files straight from modure.c .
2014-10-12 03:40:20 +03:00
Paul Sokolovsky
457c0a606c modure: Upgrade re1.5 to 0.5.1
Changes include:

regexp.h: Add double-include protection.
2014-10-12 03:12:19 +03:00
Damien George
fbf976c9aa Merge pull request #902 from pfalcon/readme-unix
README: Update "unix" section with more info/details.
2014-10-11 18:58:46 +01:00
Damien George
37671c9a97 Merge branch 'pfalcon-modure' 2014-10-11 18:55:44 +01:00
Damien George
dd5ee9ff9c stmhal: Enable ure module (tests pass on pyboard). 2014-10-11 18:55:12 +01:00
Damien George
26fa3e30ec Merge branch 'modure' of https://github.com/pfalcon/micropython into pfalcon-modure 2014-10-11 18:49:02 +01:00
Paul Sokolovsky
945df4e564 README: Update "unix" section with more info/details. 2014-10-11 20:45:32 +03:00
Damien George
1ce916aefd Merge pull request #900 from dhylands/comp-deadtime
Add support for complimentary channel output and deadtime.
2014-10-11 18:44:39 +01:00
Paul Sokolovsky
c36c75c4dc unix: Update comment MICROPY_GCREGS_SETJMP (untested -> undertested). 2014-10-11 20:33:44 +03:00
Paul Sokolovsky
6c2ab5c315 unix: Add comment about needed dependencies for MICROPY_FORCE_32BIT. 2014-10-11 20:33:37 +03:00
Paul Sokolovsky
f7bcce0552 modure: Basic tests. 2014-10-11 14:36:33 +03:00
Paul Sokolovsky
5edbadefc1 modure: Import needed files from re1.5 v0.5.
https://github.com/pfalcon/re1.5
2014-10-11 14:36:32 +03:00
Paul Sokolovsky
c71e045165 modure: Initial module, using re1.5 (which is based on re1 codebase).
https://github.com/pfalcon/re1.5
2014-10-11 14:36:32 +03:00
Dave Hylands
1c795445b3 Add support for complimentary channel output and deadtime.
This patch enables output on the complimentary channels (TIMx_CHyN).
For timers 1 and 8, deadtime can also be inserted when the channels
transition. For the pyboard, TIM8_CH1/CH1N and TIM8_CH2/CH2N can
take advantage of this.
2014-10-10 13:54:03 -07:00
Damien George
9b6617ea8b stmhal: Add pyb.stop() and pyb.standby() functions. 2014-10-09 19:02:47 +01:00
Damien George
cc5b4a2653 Merge pull request #899 from pfalcon/usocket-rename
unix: Rename "microsocket" module to "usocket".
2014-10-09 18:58:24 +01:00
Paul Sokolovsky
23b3b04072 unix: Rename "microsocket" module to "usocket".
Per new conventions, we'd like to consistently use "u*" naming conventions
for modules which don't offer complete CPython compatibility, while offer
subset or similar API.
2014-10-09 20:43:10 +03:00
Paul Sokolovsky
a2d8f98a7e examples: Rename unix socket examples to have more precise naming (http). 2014-10-09 20:35:56 +03:00
Damien George
1e49b151a7 Merge branch 'master' of github.com:micropython/micropython 2014-10-09 16:54:14 +01:00
Damien George
f0f964807e Merge branch 'dhylands-lexer-crash' 2014-10-09 16:54:03 +01:00
Damien George
9bf5f2857d py: Add further checks for failed malloc in lexer init functions. 2014-10-09 16:53:37 +01:00
Damien George
a8202762f0 Merge branch 'lexer-crash' of https://github.com/dhylands/micropython into dhylands-lexer-crash 2014-10-09 16:48:55 +01:00
Damien George
40e4c777a1 Merge pull request #897 from tomvonclef/master
Updating README.md. The Unix build requires pkg-config for FFI.
2014-10-09 16:47:06 +01:00
Damien George
7989b07637 Merge branch 'dhylands-memory-error' 2014-10-09 16:45:15 +01:00
Damien George
4091445612 py: Add #if guard around gc-specific code. 2014-10-09 16:44:43 +01:00
Dave Hylands
e20cbbec73 Make lexer fail gracefully when memory can't be allocated. 2014-10-08 23:17:35 -07:00
Tom von Clef
2090a98e80 Updating README.md to include the fact that the Unix build requires pkg-config to build the FFI module. 2014-10-08 17:26:03 -04:00
Dave Hylands
3556e45711 Allow real memory errors (from locked gc) to be reported with traceback. 2014-10-07 08:07:49 -07:00
Paul Sokolovsky
67f25dfe6f travis: Install realpath, required for teensy build. 2014-10-06 23:49:17 +03:00
Paul Sokolovsky
5d328cbeb9 windows: mingw32 gcc doesn't define endianness macros, so just assume little.
Specifically, at least Ubuntu's i586-mingw32msvc-gcc doesn't supply
__LITTLE_ENDIAN__ and friends. And as it's safe enough to assume that
Windows is only little-endian, then it's defined unconditionally,
instead of duplicating detection logic in py/mpconfig.h (or adding
windows-specific defines to it).
2014-10-06 23:18:59 +03:00
Paul Sokolovsky
5dc8f9b28a tests: Skip ffi_float.py if module ffi is not available. 2014-10-06 22:37:40 +03:00
Paul Sokolovsky
9aeec0e3a3 tests: Add missing "import sys". 2014-10-06 22:30:46 +03:00
Damien George
f53c343363 tests: Force skip of LE test on non-LE arch; improve run-tests-exp.sh. 2014-10-06 17:35:46 +00:00
Damien George
9c6f7378f7 tests: Make run-tests-exp.sh skip tests that fail due to invalid decorator.
Should address issue #856.
2014-10-06 17:06:49 +00:00
Damien George
f32498fe04 py: Extra autodetect for little endianness using __LITTLE_ENDIAN__. 2014-10-06 16:09:31 +00:00
Damien George
fec70ad369 stmhal: Remove long-obsolete pybwlan.[ch] files from old CC3k driver. 2014-10-06 15:40:25 +00:00
Damien George
9336ee320a py: Make mp_binary_set_val work on big endian machine. 2014-10-06 15:05:35 +00:00
Damien George
fcdb239815 py: Make int.to_bytes work on big endian machine.
Partly addresses issue #856.
2014-10-06 13:45:34 +00:00
Damien George
a9bcd51dc7 py: Try to autodetect machine endianness when not defined by port. 2014-10-06 13:44:59 +00:00
Damien George
5a04e2cca8 tests: Add check for micropython.native and then skip relevant tests.
If micropython.native decorator doesn't compile, then we skill all
native/viper tests.

This patch also re-enables the ujson_loads test on NT.

Addresses issue #861, and partially addresses issue #856.
2014-10-05 22:27:12 +01:00
Damien George
854c8c0153 unix: Detect and print compile error. 2014-10-05 22:25:36 +01:00
Damien George
d03c681608 stmhal: Use mp_uint_t where appropriate.
Found these by compiling stmhal with mp_uint_t of type uint32_t instead
of unsigned int.  This actually makes a difference to the code, but just
a curiosity.
2014-10-05 21:51:54 +01:00
Damien George
c4d0868df1 py: Implement proper context save/restore for eval/exec; factor code.
This has benefits all round: code factoring for parse/compile/execute,
proper context save/restore for exec, allow to sepcify globals/locals
for eval, and reduced ROM usage by >100 bytes on stmhal and unix.

Also, the call to mp_parse_compile_execute is tail call optimised for
the import code, so it doesn't increase stack memory usage.
2014-10-05 20:13:34 +01:00
Damien George
a91ac2011f py: Make compiler return a proper exception on SyntaxError. 2014-10-05 19:01:34 +01:00
Damien George
6dba992182 stmhal: Add config option to disable/enable CAN driver. 2014-10-05 18:05:26 +01:00
Damien George
ba0383a8c7 stmhal, timer: Fix timer.chanel so mode can be a keyword. 2014-10-05 17:52:45 +01:00
Damien George
55f68b3ce8 stmhal, timer: Improve accuracy of freq computation. 2014-10-05 17:52:45 +01:00
Damien George
97ef94df83 stmhal, timer: Set freq from float; get timer source freq.
Timers now have the following new features:
- can init freq using floating point; eg tim.init(freq=0.1)
- tim.source_freq() added to get freq of timer clock source
- tim.freq() added to get/set freq
- print(tim) now prints freq
2014-10-05 17:52:44 +01:00
Damien George
c3ab90da46 tests: Make printing of floats hopefully more portable. 2014-10-05 17:50:02 +01:00
Damien George
d112cbfd7c Merge pull request #891 from stinos/windows-tests
windows tests fixes
2014-10-05 17:48:37 +01:00
stijn
dc1ea1156a Exclude some tests which always fail on windows 2014-10-05 09:32:26 +02:00
stijn
a2f9c9445a Enable unicode for Windows port so unicode tests give correct uPy output 2014-10-04 09:16:20 +02:00
Damien George
24119176e7 stmhal: Allow pyb.freq() function to change SYSCLK frequency.
Eg pyb.freq(120000000) sets the CPU to 120MHz.  The frequency can be set
at any point in the code, and can be changed as many times as you like.
Note that any active timers will need to be reconfigured after a freq
change.

Valid range is 24MHz to 168MHz (but not all freqs are supported).  The
code maintains a 48MHz clock for the USB at all times and it's possible
to change the frequency at a USB REPL and keep the REPL alive (well,
most of the time it stays, sometimes it resets the USB for some reason).
Note that USB does not work with pyb.freq of 24MHz.
2014-10-04 01:54:31 +01:00
Damien George
c568a2b443 stmhal: Adjust computation of SYSCLK to retain precision. 2014-10-04 01:54:02 +01:00
Damien George
1f2558d647 Merge pull request #889 from Vogtinator/master
Implement missing ARM emitter functions for viper
2014-10-04 00:26:05 +01:00
Fabian Vogt
e5268963c6 Implement missing ARM emitter functions for viper 2014-10-04 00:57:21 +02:00
Damien George
00be7a849a py: Fix unix-cpy to compile with uint->mp_uint_t changes. 2014-10-03 20:05:44 +01:00
Damien George
39dc145478 py: Change [u]int to mp_[u]int_t in qstr.[ch], and some other places.
This should pretty much resolve issue #50.
2014-10-03 19:52:22 +01:00
Damien George
3eaa0c3833 py: Use UINT_FMT instead of %d. 2014-10-03 17:54:25 +00:00
Damien George
42f3de924b py: Convert [u]int to mp_[u]int_t where appropriate.
Addressing issue #50.
2014-10-03 17:44:14 +00:00
Damien George
877dba3e1a drivers: Add NRF24L01 driver (written in pure Python).
Comes with test script.  Copy both files to pyboard and run
"import nrf24l01test".
2014-10-02 19:36:56 +01:00
Damien George
e535a61983 tests: Add simple CAN test. 2014-10-02 17:32:02 +01:00
Damien George
3550de4ebe stmhal: Add basic CAN bus support. 2014-10-02 17:32:02 +01:00
Damien George
5fc6aa8100 stmhal: Set is_enabled=false when creating UART object; fix doc typo. 2014-10-02 17:31:37 +01:00
Damien George
0bbe4de527 stmhal: Update help text.
Remove reference to pyb.gc; add reference to pyb.millis.

There are lots of functions not listed when you run help(), but it would
be too much to list them all, so we list only some basic, useful ones.

Addresses issue #846.
2014-10-02 14:51:17 +01:00
blmorris
3b064370f8 Enable device keyword option when running pyboard.py --tests and run-tests --pyboard 2014-10-01 23:31:52 +01:00
Damien George
762d57519d unix: Do a proper clean-up on sys.exit/SystemExit.
Addresses issue #859.
2014-10-01 23:18:39 +01:00
Dave Hylands
d368611ea6 Proposed fix for USB Mass Storage. 2014-10-01 22:52:02 +01:00
Damien George
c737086e1c tools: Add network build to auto-build script. 2014-09-30 23:04:08 +00:00
Damien George
de37775a26 stmhal: Enable patch_program in cc3k driver, with key. 2014-09-30 23:43:38 +01:00
Damien George
e5cc4b2503 stmhal: Fix wiznet5k init of SPI bus. 2014-09-30 23:34:18 +01:00
Damien George
8762418d0c drivers, cc3000: Wrap exported functions in a macro for renaming. 2014-09-30 23:25:42 +01:00
Damien George
9d2bf9c405 drivers, wiznet5k: Wrap exported functions in a macro for renaming.
3rd party drivers should not export generic names like "close".
2014-09-30 22:51:47 +01:00
Damien George
3a1c4c5bc6 stmhal: Add network and usocket module.
As per issue #876, the network module is used to configure NICs
(hardware modules) and configure routing.  The usocket module is
supposed to implement the normal Python socket module and selects the
underlying NIC using routing logic.

Right now the routing logic is brain dead: first-initialised,
first-used.  And the routing table is just a list of registered NICs.

cc3k and wiznet5k work, but not at the same time due to C name clashes
(to be fixed).

Note that the usocket module has alias socket, so that one can import
socket and it works as normal.  But you can also override socket with
your own module, using usocket at the backend.
2014-09-30 22:36:47 +01:00
Damien George
bfa7b480a7 stmhal: For spi_init, add argument to select if NSS pin is enabled.
Most of the time you don't use the NSS pin of the SPI bus, and so it
shouldn't be enabled by default (this gave some bugs in the past).
2014-09-30 22:36:47 +01:00
Damien George
8b03d944e2 py: Remove IOError since it's deprecated; use OSError instead.
In CPython IOError (and EnvironmentError) is deprecated and aliased to
OSError.  All modules that used to raise IOError now raise OSError (or a
derived exception).

In Micro Python we never used IOError (except 1 place, incorrectly) and
so don't need to keep it.

See http://legacy.python.org/dev/peps/pep-3151/ for background.
2014-09-30 13:59:30 +00:00
Damien George
1c6a1dc740 py: Allow x86-64 to mov r16 to rm16 with extended src reg.
Fixes bug with x86-64 viper ptr16.
2014-09-29 22:44:18 +01:00
Damien George
dfef4249eb py: Fix viper store on x86; add tests for viper ptr16. 2014-09-29 21:41:41 +00:00
Damien George
e9dac3b4d0 py: Add casting to viper; add native mem stores to viper.
Viper can now do the following:

def store(p:ptr8, c:int):
    p[0] = c

This does a store of c to the memory pointed to by p using a machine
instructions inline in the code.
2014-09-29 22:10:41 +01:00
Damien George
44c96b2314 tests: Add tests for viper binary operations. 2014-09-29 19:42:06 +01:00
Damien George
3112cde900 py: Implement more binary ops for viper emitter.
This included a bit of restructuring of the assembler backends.  Note
that the ARM backend is missing a few functions and won't compile.
2014-09-29 19:42:06 +01:00
Damien George
6f81348fa2 py: Allow viper to use ints as direct conditionals in jumps.
Allows things like: if 1: ...
2014-09-29 19:42:06 +01:00
Damien George
a7329615eb py: Fix types, uint -> mp_uint_t. 2014-09-29 19:42:06 +01:00
Damien George
0b610de017 py: Make macro names in assemblers consistent, and tidy up a bit. 2014-09-29 19:42:06 +01:00
Damien George
d66e48662b py: Add store r8 and store r16 ops to asm_x86 and asm_x64. 2014-09-29 19:42:06 +01:00
Damien George
851f15f34c py: In asmthumb, clean up unit/int types and ite ops. 2014-09-29 19:42:06 +01:00
Damien George
860805aae7 unix: Remove unnecessary #defines from config. 2014-09-29 19:41:49 +01:00
Damien George
41249e17c3 stmhal, fatfs: Use stdlib for string fns; make all private fns static.
We save some code bytes by using builtin string functions.
2014-09-29 15:26:46 +01:00
Damien George
3a2795e200 stmhal: Add label to internal flash drive on creation. 2014-09-29 15:26:11 +01:00
Damien George
f042d7a4d7 stmhal: Fix edge case for timer PWM of 100%.
Also improve precision of calculating PWM percent in integer mode.
Also update teensy with edge case fix.
2014-09-29 14:15:01 +01:00
Damien George
853708738e Merge pull request #881 from dhylands/elapsed
Added pyb.elapsed_millis and pyb.elapsed_micros
2014-09-29 12:42:31 +01:00
Damien George
6e2051377f Merge pull request #880 from dhylands/irq-align
teensy: Enable 8-byte stack alignment for IRQ Handlers.
2014-09-29 12:22:53 +01:00
Damien George
305c4d49be Merge pull request #878 from bvernoux/master
Fix error: unknown type name 'size_t'
2014-09-29 12:22:16 +01:00
Damien George
bf683e6b32 Merge pull request #877 from dhylands/timer-overflow
Fix timer overflow code.
2014-09-29 12:18:48 +01:00
Dave Hylands
a21f56b2d5 Added pyb.elapsed_millis and pyb.elapsed_micros
tested using:
stmhal: https://github.com/dhylands/upy-examples/blob/master/elapsed.py
teensy: https://github.com/dhylands/upy-examples/blob/master/teensy/elapsed.py
2014-09-28 11:24:44 -07:00
Dave Hylands
ada691e704 teensy: Enable 8-byte stack alignment for IRQ Handlers. 2014-09-28 10:17:44 -07:00
bvernoux
f6f248b464 Fix error: unknown type name 'size_t' 2014-09-28 09:54:35 +02:00
Dave Hylands
39296b40d4 Fix timer overflow code.
Teensy doesn't need to worry about overflows since all of
its timers are only 16-bit.

For PWM, the pulse width needs to be able to vary from 0..period+1
(pulse-width == period+1 corresponds to 100% PWM)

I couldn't test the 0xffffffff cases since we can't currently get a
period that big in python. With a prescaler of 0, that corresponds
to a freq of 0.039 (i.e. cycle every 25.56 seconds), and we can't
set that using freq or period.

I also tested both stmhal and teensy with floats disabled, which
required a few other code changes to compile.
2014-09-27 19:40:37 -07:00
Damien George
f90b59e610 stmhal, modcc3k: Add ioctl to cc3k sockets so select works. 2014-09-26 13:52:41 +00:00
Damien George
133b083b89 py: Clean up nlr*.S to make it easier to read; fix clang .bss error.
It seems that newer versions of clang don't like the .bss directive, so
we don't use it for OSX.

Addressing issues #865 and #875.
2014-09-26 13:07:26 +00:00
Damien George
b766e79510 stmhal: Initial implementation of cc3k module and driver.
Pulled in and modified work done by mux/iabdalkader on cc3k driver, from
iabdalkader-cc3k-update branch.  That branch was terribly messy and had
too many conflicts to merge neatly.
2014-09-26 00:57:26 +01:00
Damien George
f996d8854f drivers, cc3k: Move cc3000 driver from stmhal to drivers directory. 2014-09-26 00:56:45 +01:00
Damien George
55a5b80793 docs: Make images and youtube video links work for LCD and AMP docs.
Images are currently served from micropython.org/static.  I don't know
if there is a better way to handle images.
2014-09-25 19:42:27 +01:00
Damien George
cde0ca21bf py: Simplify JSON str printing (while still conforming to JSON spec).
The JSON specs are relatively flexible and allow us to use one function
to print strings, be they ascii, bytes or utf-8 encoded.
2014-09-25 17:35:56 +01:00
Damien George
d19c256656 docs: Imported tutorials from previous documentation system. 2014-09-25 17:23:06 +01:00
Damien George
6162bea5b2 docs: Initial commit of Sphinx documentation framework. 2014-09-25 17:23:06 +01:00
blmorris
4f449120e1 Change allows tests/unix/ffi_float.py to pass on OSX 2014-09-25 16:31:30 +01:00
Damien George
2234c3f23d tests: Add test for exception matching of a tuple of exceptions. 2014-09-25 15:49:26 +01:00
Damien George
4bcd04bcad py: Tidy up exception matching; allow matching of tuple of exceptions.
Addresses issue #864.
2014-09-25 15:49:26 +01:00
Damien George
16ef60fba6 Updated CODECONVENTIONS to clarify use of integer types. 2014-09-25 15:49:26 +01:00
Damien George
b0261341d3 py: For malloc and vstr functions, use size_t exclusively for int type.
It seems most sensible to use size_t for measuring "number of bytes" in
malloc and vstr functions (since that's what size_t is for).  We don't
use mp_uint_t because malloc and vstr are not Micro Python specific.
2014-09-25 15:49:26 +01:00
Damien George
ac04a8a56a stmhal: Enable 8-byte stack alignment for IRQ handlers. 2014-09-25 15:47:53 +01:00
Damien George
e8ea0724da stmhal, timer: Factor code to compute PWM percent; improve 32bit case.
Also do the same for teensy timer code.
2014-09-25 15:44:10 +01:00
Damien George
3fafe730d3 Merge pull request #868 from dhylands/fix-teensy-float
Add pulse_width_percent to teensy.
2014-09-25 14:51:44 +01:00
Dave Hylands
53d5fa641f Add pulse_width_percent to teensy.
Fix stmhal and teensy print routines to report actual prescaler an period.
Fix teensy build to use soft-float
Add USE_ARDUINO_TOOLCHAIN option to teensy build
2014-09-23 23:19:36 -07:00
Damien George
52b5d76a6b py: Free non-interned strings in the parser when not needed.
mp_parse_node_free now frees the memory associated with non-interned
strings.  And the parser calls mp_parse_node_free when discarding a
non-used node (such as a doc string).

Also, the compiler now frees the parse tree explicitly just before it
exits (as opposed to relying on the caller to do this).

Addresses issue #708 as best we can.
2014-09-23 15:31:56 +00:00
Damien George
d6230f62c7 py: Make native emitter handle multi-compare and not/is not/not in ops. 2014-09-23 14:15:45 +00:00
Damien George
96e20c600f tests: Fix uctypes tests to run on 64bit arch; enable more native tests. 2014-09-23 14:15:45 +00:00
Damien George
5a5555e385 Merge pull request #869 from stinos/windows-up
windows: Enable input(), sys.maxsize(), ujson module, emergency exceptio...
2014-09-23 14:58:52 +01:00
Damien George
9f53275042 Merge pull request #871 from blmorris/osx_build_fix
Fix unix/Makefile to build on OSX
2014-09-23 14:57:14 +01:00
blmorris
fa6567a39f Clean up logical flow for setting LDFLAGS to build for Linux and OSX
Add more specific comments describing what is going on.
2014-09-23 09:42:18 -04:00
Damien George
eaaebf3291 stmhal: Initialise stack pointer correctly.
Stack is full descending and must be 8-byte aligned.  It must start off
pointing to just above the last byte of RAM.

Previously, stack started pointed to last byte of RAM (eg 0x2001ffff)
and so was not 8-byte aligned.  This caused a bug in combination with
alloca.

This patch also updates some debug printing code.

Addresses issue #872 (among many other undiscovered issues).
2014-09-23 10:59:05 +01:00
blmorris
8afb9b3863 Incorporate change in assignment logic suggested by dhylands 2014-09-22 23:00:42 -04:00
blmorris
1fae787493 Fix unix/Makefile to build on OSX
Force OSX to compile with clang even if gcc is available
Change LDFLAGS syntax to be compatible with clang
Fix questionable syntax on line 90
Remove extraneous tab character
2014-09-22 15:16:14 -04:00
stijn
8c41920a90 windows: Enable input(), sys.maxsize(), ujson module, emergency exception buf, os module 2014-09-22 11:10:27 +02:00
Damien George
2c180f7ccc extmod, ujson: Add test and comment for loads. 2014-09-21 23:43:03 +01:00
Damien George
df1e92ba3a extmod, ujson: Add \uxxxx parsing in json strings. 2014-09-21 23:43:03 +01:00
Damien George
fa2f1f72e0 extmod, ujson: Slight reduction in code size. 2014-09-21 23:43:03 +01:00
Damien George
89e4657c69 extmod: Add loads to ujson module. 2014-09-21 23:43:03 +01:00
Damien George
c95359ecc6 Merge branch 'dhylands-timer-pwm2' 2014-09-21 22:56:07 +01:00
Damien George
0e58c5810d stmhal: Add pulse_width_ratio to timer channel object.
This allows to set the pulse width (for PWM mode) as a ratio relative to
the period of the timer.  Eg, 0.5 is a 50% duty cycle.  You can set the
ratio in the channel init, or using channel.pulse_width_ratio; the
latter can also read the pulse width as a ratio.
2014-09-21 22:54:02 +01:00
Dave Hylands
becbc87fd7 Add Timer support (PWM, OC, IC) for stmhal and teensy 2014-09-19 09:26:13 -07:00
Damien George
2842945e76 stmhal: Fix bugs in documentation so it compiles. 2014-09-17 23:27:42 +00:00
Damien George
8bb44f69f2 lib: Add basic README. 2014-09-18 00:13:03 +01:00
Damien George
3d61528fe7 py: Add 'builtins' module. 2014-09-17 23:17:26 +01:00
Damien George
612045f53f py: Add native json printing using existing print framework.
Also add start of ujson module with dumps implemented.  Enabled in unix
and stmhal ports.  Test passes on both.
2014-09-17 22:56:34 +01:00
Damien George
8a9b999f1c py: Make dict use a bit less RAM when iterating; properly del values.
Heap RAM was being allocated to print dicts and do some other types of
iterating.  Now these iterations use 1 word of state on the stack.

Deleting elements from a dict was not allowing the value to be reclaimed
by the GC.  This is now fixed.
2014-09-17 15:53:03 +01:00
Damien George
1d7fb82f0a stmhal: Change 64-bit arithmetic to 32-bit for SD card block addressing.
By measuring SD card addresses in blocks and not bytes, one can get away
with using 32-bit numbers.

This patch also uses proper atomic lock/unlock around SD card
read/write, adds SD.info() function, and gives error code for failed
read/writes.
2014-09-15 23:49:57 +01:00
Felix Domke
6ff42c54bb stmhal/sdcard.c: add pyb.SD.write 2014-09-15 22:34:16 +01:00
Felix Domke
09de030651 stmhal/hal/src/stm32f4xx_hal_sd.c: fix SDHC card capacity 2014-09-15 22:34:07 +01:00
Damien George
d4a799f152 py: Make asm_arm_less_op take destination register as first arg.
This gets ARM native emitter working againg and addresses issue #858.
2014-09-15 16:39:24 +01:00
Damien George
b92cbe6129 py: Move definition of mp_sys_exit to core.
sys.exit always raises SystemExit so doesn't need a special
implementation for each port.  If C exit() is really needed, use the
standard os._exit function.

Also initialise mp_sys_path and mp_sys_argv in teensy port.
2014-09-15 15:53:09 +01:00
Damien George
83695596ed py: Fix build error when float disabled; add test for divmod. 2014-09-13 19:58:18 +01:00
Damien George
8594ce2280 py: Implement divmod, % and proper // for floating point.
Tested and working on unix and pyboard.
2014-09-13 18:43:09 +01:00
Damien George
5c6783496d Merge branch 'iabdalkader-memcpy' 2014-09-13 00:13:28 +01:00
Damien George
32781cce6d stmhal: Slightly improved memcpy; memset uses word store when aligned. 2014-09-13 00:12:41 +01:00
Damien George
5792500ccc Merge branch 'memcpy' of github.com:iabdalkader/micropython into iabdalkader-memcpy 2014-09-12 23:23:49 +01:00
Damien George
bb29546868 py: Load strings as objects when compiling viper.
Eventually, viper wants to be able to use raw pointers to strings and
arrays for efficient access.  But for now, let's just load strings as a
Python object so they can be used as normal.  This will anyway be
compatible with eventual intended viper behaviour.

Addresses issue #857.
2014-09-12 23:15:06 +01:00
Damien George
89ab3be0b1 Merge branch 'master' of github.com:micropython/micropython 2014-09-11 22:28:58 +01:00
Damien George
20beff9ae3 py and libm: Add asinf,acosf; print higher precision for float.
Also use less stack space when printing single precision float.

Addition of asinf and acosf addresses issue #851.
2014-09-11 22:24:45 +01:00
Damien George
5f0c18e583 Merge pull request #852 from techno/staccel_LIS3DSH
Add LIS3DSH accelometer support to staccel.py
2014-09-11 20:36:44 +01:00
iabdalkader
d60580eb5e Optimize memcpy more 2014-09-11 19:01:48 +02:00
Hirotaka Kawata
2b4af54992 Add LIS3DSH accelometer support to staccel.py 2014-09-11 16:40:53 +09:00
iabdalkader
81b2ddf5d1 Memcpy: copy words 2014-09-11 07:49:21 +02:00
Damien George
953074315e py: Enable struct/binary-helper to parse q and Q sized ints.
Addresses issue #848.
2014-09-10 22:10:33 +01:00
Damien George
6eae861685 py: Put define of x86 argument registers in asmx86.h. 2014-09-08 22:16:35 +00:00
Damien George
7ff996c237 py: Convert [u]int to mp_[u]int_t in emit.h and associated .c files.
Towards resolving issue #50.
2014-09-08 23:05:16 +01:00
Damien George
377b80b624 py: Print imported module's location (__file__) if available. 2014-09-08 10:45:23 +01:00
Damien George
5c00757a5c stmhal: uart ioctl uses EINVAL, and checks TXE bit for write-ability. 2014-09-07 20:57:18 +01:00
Damien George
013d53c0b4 Remove skeletal modselect from extmod and just put it in stmhal. 2014-09-07 20:42:01 +01:00
Damien George
e2a618615d stmhal: Fix modselect so non-hashable objects can be polled. 2014-09-07 20:41:09 +01:00
Damien George
c7687ad7e6 py: Rename mp_builtin_id to mp_obj_id and make it public. 2014-09-07 20:41:09 +01:00
Damien George
a2f55fe12b stmhal: Add polling ability to UART object. 2014-09-07 20:40:32 +01:00
Damien George
6c9c7bc75a stmhal: Implement generic select.select and select.poll. 2014-09-07 20:40:32 +01:00
Damien George
c8c44a4c2e py: Add ioctl method to stream protocol; add initial modselect. 2014-09-07 20:40:10 +01:00
Damien George
8105736982 py: Clean up x86-64 native assembler; allow use of extended regs.
Native x86-64 now has 3 locals in registers.
2014-09-07 01:06:19 +01:00
Damien George
25d904105c py: Adjust regs for x86 so that 1 more local can live in a reg. 2014-09-06 23:24:32 +00:00
Damien George
91fe0d4880 unix: Fix modffi to be able to return double on x86 machines. 2014-09-06 23:04:42 +00:00
Damien George
03281b3850 py: Allow x86 native functions to take arguments.
Fix some bugs with x86 stack and saving registers correctly.
2014-09-06 22:38:50 +00:00
Damien George
c90f59ec3a py: Add support for emitting native x86 machine code. 2014-09-06 23:06:36 +01:00
Damien George
33b50a0217 Merge branch 'master' of github.com:micropython/micropython 2014-09-06 18:39:39 +01:00
Damien George
c7a79284bb tests: Enable misc tests on pyboard; output 4 sig figs in rge_sm. 2014-09-06 18:38:55 +01:00
Damien George
e6ce10a3e7 py: Native emitter now supports delete name & global, and end finally. 2014-09-06 18:38:20 +01:00
Paul Sokolovsky
78fde4819c modstruct: Implement 'O', 'P', 's' types for packed structs.
This is required to deal with, well, packed C structs containing pointers.
2014-09-06 20:22:06 +03:00
Paul Sokolovsky
722e562736 py: Correctly set sys.maxsize value for 64-bit.
Type representing signed size doesn't have to be int, so use special value
which defaults to SSIZE_MAX, but as it's not defined by C standard (but rather
by POSIX), allow ports to set it.
2014-09-06 20:22:06 +03:00
Damien George
17598d49e1 unix: Don't use -Wno-error=cpp or #warning; fix strict alias warning.
For the sake of older versions of gcc (and other compilers), don't use
the #warning CPP directive, nor the -Wno-error=cpp option.

Also, fix a strict alias warning in modffi.c for older compilers, and
add a test for ffi module.

Addresses issue #847.
2014-09-06 17:46:52 +01:00
Damien George
8002d5d2b9 py: Fix definition of sys.maxsize with mpz changes. 2014-09-06 17:37:29 +01:00
Damien George
9a21d2e070 py: Make mpz able to use 16 bits per digit; and 32 on 64-bit arch.
Previously, mpz was restricted to using at most 15 bits in each digit,
where a digit was a uint16_t.

With this patch, mpz can use all 16 bits in the uint16_t (improvement
to mpn_div was required).  This gives small inprovements in speed and
RAM usage.  It also yields savings in ROM code size because all of the
digit masking operations become no-ops.

Also, mpz can now use a uint32_t as the digit type, and hence use 32
bits per digit.  This will give decent improvements in mpz speed on
64-bit machines.

Test for big integer division added.
2014-09-06 17:15:34 +01:00
Damien George
afb1cf75dd py: Convert (u)int to mp_(u)int_t in mpz, and remove unused function. 2014-09-05 20:37:06 +01:00
Damien George
e191d42188 py: Use % str formatting instead of {} in makeqstrdata.py.
Script is equivalent, but now also runs under ancient Python 2.6.
Goes part way to addressing issue #847.
2014-09-05 13:16:19 +01:00
Damien George
b534e1b9f1 py: Use variable length encoded uints in more places in bytecode.
Code-info size, block name, source name, n_state and n_exc_stack now use
variable length encoded uints.  This saves 7-9 bytes per bytecode
function for most functions.
2014-09-04 14:44:01 +01:00
Damien George
dda46460ff Code style/whitespace cleanup; remove obsolete headers.
And move the MAP_ANON redefinition from py/asmx64.c to unix/alloc.c.
2014-09-03 22:47:23 +01:00
Damien George
a669cbc690 unix: Auto-detect MICROPY_EMIT_X64 and MICROPY_GCREGS_SETJMP.
If not set, MICROPY_EMIT_X64 is set only if on x86-64 machine.

If not set, MICROPY_GCREGS_SETJMP is set when on MIPS.
2014-09-03 22:40:15 +01:00
Damien George
91fbea2c1e Merge pull request #845 from Vogtinator/master
Add allocation macros (per platform) and ARM cache flush
2014-09-03 22:31:08 +01:00
Fabian Vogt
b7235b8412 Add cache flush in py/asmarm.c and add new MP_PLAT_ALLOC_EXEC and MP_PLAT_FREE_EXEC macros
Fixes issue #840
2014-09-03 23:07:42 +02:00
Damien George
fc54250d31 Merge pull request #844 from chrisdearman/do_str
Declare do_str() function before the implementation
2014-09-03 21:53:48 +01:00
Damien George
27dd910c44 Merge branch 'stinos-msvc-extmod' 2014-09-02 11:39:12 +01:00
Damien George
e875e3882d extmod: Fix type-punned-ptr error. 2014-09-02 11:38:45 +01:00
Damien George
bc9f34860b Merge branch 'msvc-extmod' of github.com:stinos/micropython into stinos-msvc-extmod 2014-09-02 11:37:47 +01:00
stijn
759138caee msvc: Exclude modtermios, include extmod and fix compilation error 2014-09-02 09:00:20 +02:00
Chris Dearman
8c56241c82 Declare do_str() function before the implementation
This ensures that GCC does not discard the do_str implementation in
some cases eg when compiling tests with debug enabled:
  make RUN_TESTS=1 DEBUG=1
2014-09-01 19:51:12 -07:00
Damien George
bad2df3e95 stmhal, modwiznet5k: Add very minimal documentation. 2014-09-01 22:58:22 +01:00
Damien George
bcf041f1a3 stmhal: Add wiznet5k module, to control WIZnet ethernet adaptor.
Allows to create socket objects that support TCP and UDP in server and
client mode.  Interface is very close to standard Python socket class,
except bind and accept do not work the same (due to hardware not
supporting them in the usual way).

Not compiled by default.  To compile this module, use:
make MICROPY_PY_WIZNET5K=1
2014-09-01 22:52:38 +01:00
Damien George
cdd40f149a drivers, wiznet5k: Make DNS service use HAL sys tick. 2014-09-01 22:52:38 +01:00
Damien George
9091e84454 drivers, wiznet5k: Add HAL_Delay(1) to "infinite" loops. 2014-09-01 22:52:38 +01:00
Damien George
7da9145e47 drivers, wiznet5k: Properly fix ARP bug with W5200 chipset. 2014-09-01 22:52:37 +01:00
Damien George
0c0550bff0 drivers, wiznet5k: Add W5200 support. 2014-09-01 22:52:37 +01:00
Damien George
79d17e3e7d drivers, wiznet5k: Change SPI interface to read/write multiple bytes. 2014-09-01 22:52:37 +01:00
Damien George
812cf62f43 drivers, wiznet5k: Fix IP addr verification. 2014-09-01 22:52:37 +01:00
Damien George
71224cb8db drivers: Initial import of WIZnet5x000 driver. 2014-09-01 22:52:37 +01:00
Damien George
e07737d202 Added 'drivers' directory, intended to hold code for specific hardware. 2014-09-01 22:52:37 +01:00
Damien George
90fad65d2f Merge pull request #841 from dhylands/teensy-README
Update teensy README.md file
2014-08-31 00:36:54 +01:00
Dave Hylands
76dd7e180f Update teensy README.md file
Thanks to Artur Wroblewski for some suggested changes.
I also added the TIPs section at the end while I was updating.
2014-08-30 12:21:08 -07:00
Damien George
ca6d75f16d py: Small simplifications in tuple and list accessors. 2014-08-30 15:17:47 +01:00
Damien George
4abff7500f py: Change uint to mp_uint_t in runtime.h, stackctrl.h, binary.h.
Part of code cleanup, working towards resolving issue #50.
2014-08-30 14:59:21 +01:00
Damien George
4d91723587 py: Remove use of int type in obj.h.
Part of code cleanup, working towards resolving issue #50.
2014-08-30 14:28:06 +01:00
Damien George
d182b98a37 py: Change all uint to mp_uint_t in obj.h.
Part of code cleanup, working towards resolving issue #50.
2014-08-30 14:19:41 +01:00
Damien George
9c4cbe2ac0 py: Make tuple and list use mp_int_t/mp_uint_t.
Part of code cleanup, to resolve issue #50.
2014-08-30 14:04:14 +01:00
Damien George
93965e726f py: Make map, dict, set use mp_int_t/mp_uint_t exclusively.
Part of code cleanup, towards resolving issue #50.
2014-08-30 13:23:35 +01:00
Damien George
1c70cbf151 py: Save about 200 bytes of ROM by using smaller type for static table. 2014-08-30 00:38:16 +01:00
Damien George
ecc88e949c Change some parts of the core API to use mp_uint_t instead of uint/int.
Addressing issue #50, still some way to go yet.
2014-08-30 00:35:11 +01:00
Damien George
4d3fc46326 lib, libm: Add back dummy definition of tanf. 2014-08-29 23:24:00 +01:00
Damien George
8707ea3421 lib: Add lib and libm, moving current files from stmhal.
Top-level lib directory is for standard C libraries that we want to
provide our own versions of (for efficiency and stand-alone reasons).
It currently has libm in it for math functions.

Also add atanf and atan2f, which addresses issue #837.
2014-08-29 22:42:26 +01:00
Damien George
17ae2395c2 py: Use memmove instead of memcpy when appropriate.
Found this bug by running unix/ tests with DEBUG=1 enabled when
compiling.
2014-08-29 21:07:54 +01:00
Damien George
02d95d7ce9 py: Fix 2 bugs in native emitter: jump_or_pop and stack settling.
Addresses issue #838.
2014-08-29 20:05:32 +01:00
Damien George
eb4e18f057 py: Add compiler optimisation for conditions in parenthesis.
Optimises:
    if () -> if False
    if (x,...) -> if True
    if (a and b) -> if a and b
2014-08-29 20:04:01 +01:00
Damien George
15d2fe8da4 tests: Add option to run-tests to enable native emitter. 2014-08-29 19:47:10 +01:00
Damien George
110ba35980 py: Move native glue code from runtime.c to new file nativeglue.c.
This way, the native glue code is only compiled if native code is
enabled (which makes complete sense; thanks to Paul Sokolovsky for
the idea).

Should fix issue #834.
2014-08-28 23:37:02 +01:00
Damien George
1ac6faa732 Merge pull request #833 from Vogtinator/arm-native
Basic native ARM emitter
2014-08-28 23:24:43 +01:00
Damien George
516b09efc3 py, gc: Further reduce heap fragmentation with new, faster gc alloc.
The heap allocation is now exactly as it was before the "faster gc
alloc" patch, but it's still nearly as fast.  It is fixed by being
careful to always update the "last free block" pointer whenever the heap
changes (eg free or realloc).

Tested on all tests by enabling EXTENSIVE_HEAP_PROFILING in py/gc.c:
old and new allocator have exactly the same behaviour, just the new one
is much faster.
2014-08-28 23:06:38 +01:00
Damien George
b796e3d848 py: Reduce fragmentation of GC heap.
Recent speed up of GC allocation made the GC have a fragmented heap.
This patch restores "original fragmentation behaviour" whilst still
retaining relatively fast allocation.  This patch works because there is
always going to be a single block allocated now and then, which advances
the gc_last_free_atb_index pointer often enough so that the whole heap
doesn't need scanning.

Should address issue #836.
2014-08-28 10:18:40 +01:00
Fabian Vogt
16ee30c6fa Clarify copyright on asmarm files 2014-08-28 01:18:56 +02:00
Fabian Vogt
fe3d16e8c2 Basic native ARM emitter 2014-08-27 18:18:50 +02:00
Damien George
a97e091d4e Merge branch 'dhylands-int-bytes' 2014-08-27 09:21:41 +01:00
Damien George
a75b02ea9b py: Improve efficiency of MP_OBJ_IS_STR_OR_BYTES.
Saves ROM (16 on stmhal, 240 on 64-bit unix) and should be quicker since
there is 1 less branch.
2014-08-27 09:20:30 +01:00
Damien George
ad4c014d46 Merge branch 'int-bytes' of https://github.com/dhylands/micropython into dhylands-int-bytes 2014-08-27 09:13:15 +01:00
Dave Hylands
b7f7c655ed Make int(b'123') work properly. 2014-08-26 19:15:04 -07:00
Paul Sokolovsky
f3c3010ffc pip-micropython: Revert to using PIP_MICROPY_DEST environment var.
-t/--target is a pip option. Trying to use pip options for different meanings
in pip-micropython may lead to big confusion. That's why the original passed
any extra parameters using environment variables. "All options belong to pip."
2014-08-27 02:53:06 +03:00
Damien George
b427d6ae86 py: Fix line number printing for file with 1 line.
With a file with 1 line (and an error on that line), used to show the
line as number 0.  Now shows it correctly as line number 1.

But, when line numbers are disabled, it now prints line number 1 for any
line that has an error (instead of 0 as previously).  This might end up
being confusing, but requires extra RAM and/or hack logic to make it
print something special in the case of no line numbers.
2014-08-26 23:35:57 +01:00
Damien George
f05b87bd63 Merge pull request #824 from dhylands/sdcard-power
Fix sdcard_power_on to not do anything if the card is already powered on...
2014-08-26 22:58:54 +01:00
Damien George
3b72da674e stmhal, STM32F4DISC: Small changes to ST accel driver. 2014-08-26 22:41:27 +01:00
Damien George
6cf8dd4f51 Merge branch 'siorpaes-master' 2014-08-26 17:31:21 +01:00
Damien George
e00fb08f99 stmhal, staccel.py: Style cleanup. 2014-08-26 17:30:48 +01:00
David Siorpaes
f4ce26de5c Added LIS302DL ID check 2014-08-26 18:23:00 +02:00
Damien George
db63660c19 Add pip-micropython to unix make install.
Also add -t/--target option to pip-micropython to allowing installing to
the pyboard.

Thanks to turbinenreiter/Sebastian Plamauer for the patch.
2014-08-26 16:03:57 +01:00
Damien George
3bb7efc943 stmhal: Hookup USB_VCP.any().
Thanks to Dave Hylands for this patch.
2014-08-26 14:18:22 +01:00
Damien George
cd021bfe56 stmhal: Fix build issues with (old) CC3000 driver.
Addresses issue #825.
2014-08-26 14:13:53 +01:00
Damien George
779794a680 py: Add dispatch for user defined ==, >, <=, >=.
Addresses issue #827.
2014-08-26 09:31:26 +01:00
Damien George
fa1a9bc9fd tests: Add test for pyb.disable_irq and pyb.enable_irq. 2014-08-25 18:44:10 +01:00
Dave Hylands
994bb4a839 Fix sdcard_power_on to not do anything if the card is already powered on. 2014-08-25 10:16:52 -07:00
Damien George
34e43c7ee9 stmhal: Improve efficiency of SysTick IRQ and HAL_Delay.
SysTick IRQ now increases millisecond counter directly (ie without
calling HAL_IncTick).  Provide our own version of HAL_Delay that does a
wfi while waiting.  This more than halves power consumption when running
a loop containing a pyb.delay call.  It used to be like this, but new
version of HAL library regressed this feature.
2014-08-25 18:12:44 +01:00
Damien George
3475b04101 teensy: Fix multiple definition of irq functions. 2014-08-25 18:12:23 +01:00
Damien George
29c92a407c stmhal: Use MP_OBJ_NEW_SMALL_INT directly in pyb.micros/millis.
Also some whitespace cleanup.
2014-08-25 17:38:55 +01:00
Dave Hylands
2bf044442e Add support for pyb.micros() by using the systick timer.
I also removed trailing spaces from modpyb.c which affected a couple
of lines technically not part of this patch.

Tested using: https://github.com/dhylands/upy-examples/blob/master/micros_test.py

which eventually fails due to wraparound issues (I could fix the test to compensate
but didn't bother)
2014-08-25 17:38:55 +01:00
Dave Hylands
8c0add4eee Add save/restore_irq
Factored irq functions into a separate file.
2014-08-25 17:38:55 +01:00
Damien George
e5cbb70328 stmhal: Make enable_irq and disable_irq inline functions.
These functions are generally 1 machine instruction, and are used in
critical code, so makes sense to have them inline.

Also leave these functions uninverted (ie 0 means enable, 1 means
disable) and provide macro constants if you really need to distinguish
the states.  This makes for smaller code as well (combined with
inlining).

Applied to teensy port as well.
2014-08-25 13:24:33 +01:00
Dave Hylands
9480138f0c Add save/restore_irq
Factored irq functions into a separate file.
2014-08-25 12:22:11 +01:00
Damien George
7310fd469a py: Consolidate min/max functions into one, and add key= argument.
Addresses issue #811.
2014-08-24 19:14:09 +01:00
Damien George
1d8a06406a examples: Added pins.py example script to list pin config/af.
Script is due to Dave Hylands.
2014-08-24 18:34:38 +01:00
Damien George
2c4e67e32d stmhal, pin: Update documentation. 2014-08-24 18:30:22 +01:00
Dave Hylands
3d945559d4 Added python script to map AF to a pin name
Added some functions to Pin class to query mode, pull, and af
2014-08-24 18:21:08 +01:00
Damien George
c668d51b08 Merge branch 'dhylands-localtime' 2014-08-24 17:41:31 +01:00
Damien George
8ba832456e stmhal, modtime: Small changes, reduced code size by around 80 bytes.
Also added test for modtime.
2014-08-24 17:40:24 +01:00
Dave Hylands
6678595e7e Add time.mktime and enhance time.localtime (for stmhal)
Now you can use time.localtime on the timestamps presented by os.stat
2014-08-24 17:00:03 +01:00
Damien George
3c658a4e75 py: Fix bug where GC collected native/viper/asm function data.
Because (for Thumb) a function pointer has the LSB set, pointers to
dynamic functions in RAM (eg native, viper or asm functions) were not
being traced by the GC.  This patch is a comprehensive fix for this.

Addresses issue #820.
2014-08-24 16:28:17 +01:00
Damien George
25fc41dd31 unix, modtermios: Make it properly configurable; fix spelling mistake. 2014-08-24 13:19:22 +01:00
Paul Sokolovsky
4f9ebade60 modtermios: Add "termios" unix module, subset of CPython's.
Also provides setraw() function from "tty" module (which in CPython is
implemented in Python). The idea here is that 95% of "termios" module usage
is to set raw mode to allow access to normal serial devices. Then, instead
of exporting gazillion termios symbols, it's better to implement it in C,
and export minimal number of symbols (mostly baud rates and drain values).
2014-08-23 06:09:46 +03:00
Damien George
72b115cbaa extmod, zlibd: Make some simple ROM and RAM savings.
ROM down by 320 bytes on stmhal.  RAM down by 5.5k for a decompression
object.
2014-08-22 18:38:16 +01:00
Damien George
26a0d4f4f1 py: Change hash and len members of str from 16 bit to full word.
This allows to make strings longer than 64k.  It doesn't use any more
RAM with current GC because a str object still fits in a GC block.
2014-08-22 18:34:28 +01:00
Damien George
69b7dae362 py: Small cleanup in stream.c. 2014-08-22 18:30:02 +01:00
Damien George
d5e7f6e37e py: Speed up GC allocation.
This simple patch gives a very significant speed up for memory allocation
with the GC.

Eg, on PYBv1.0:
tests/basics/dict_del.py: 3.55 seconds -> 1.19 seconds
tests/misc/rge_sm.py:     15.3 seconds -> 2.48 seconds
2014-08-22 18:17:02 +01:00
Paul Sokolovsky
13ec400f28 Merge pull request #796 from turbinenreiter/makeinstall
unix: Added install/uninstall
2014-08-18 22:29:37 +03:00
Damien George
7fe2191c9b py: Code clean-up in native emitter; improve thumb native calls. 2014-08-16 22:31:57 +01:00
Damien George
86de21b810 py: Viper can call functions with native types, and raise exceptions. 2014-08-16 22:06:11 +01:00
Damien George
339bdccc58 Merge pull request #803 from dhylands/ld-opt
Put some code into the first 16K of flash
2014-08-16 16:09:39 +01:00
Dave Hylands
3688414d9d Put some code into the first 16K of flash
This basically shrinks the remaining size of flash in the portion
that goes after the internal flash drive.
2014-08-16 08:00:12 -07:00
Damien George
8f81b5cb4b py: Put SystemExit in builtin namespace.
Also fix unix port so that SystemExit with no arg exits with value 0.
2014-08-16 14:32:06 +01:00
Damien George
b63be37be1 stmhal: In safe mode, still mount SD card and present as MSD over USB.
It's still "safe" because no scripts are run.  Remove the SD card if you
want to access the internal flash filesystem.  Addresses issue #616.

Also: remove obsolete pyb.source_dir setting, and reset pyb.main and
pyb.usb_mode settings on soft-reset.
2014-08-16 14:23:22 +01:00
Damien George
b0accc8571 stmhal: Fix printing of pin name in error message. 2014-08-16 13:56:19 +01:00
Damien George
d779b9642f tests: Wait for just over 1 sec when testing RTC.
Waiting for 1000ms between seconds of RTC is sometimes too quick.
Waiting for 1001ms is enough for the RTC to pass 1 second.
2014-08-16 13:39:14 +01:00
Damien George
244476e3e6 stmhal: For non-debug compile, enable CC/LD opt to remove dead code.
Saves over 35k ROM due to elimination of unused HAL functions.  All
tests pass.

Addresses issue #702.
2014-08-16 13:37:05 +01:00
Damien George
c84aa41990 Merge branch 'danpeirce-master' 2014-08-16 11:56:16 +01:00
Dan Peirce
f0c3a7e781 teensy/README.md (corrected typo) 2014-08-16 11:54:36 +01:00
Dan Peirce
6009309c33 modified: teensy/README.md
Updated teensy/README.md to reflect change in build process (teensyduino is no
longer required for build).
2014-08-16 11:54:36 +01:00
Damien George
e6c0dff967 py: Viper can now store to global. 2014-08-15 23:47:59 +01:00
Damien George
a5190a7dac py: Fix typing of viper locals; allow default types in annotation. 2014-08-15 22:39:08 +01:00
Damien George
2ac4af6946 py: Allow viper to have type annotations.
Viper functions can now be annotated with the type of their arguments
and return value.  Eg:

@micropython.viper
def f(x:int) -> int:
    return x + 1
2014-08-15 16:45:41 +01:00
Damien George
6be0b0a8ec py: Clean up and simplify functions in scope; add STATIC in compiler.
Some small code clean-ups that result in about 80 bytes ROM saving for
stmhal.
2014-08-15 14:30:52 +01:00
Damien George
bf133f7737 stmhal: Resolve question in comment about timer clock. 2014-08-14 00:30:14 +01:00
Damien George
2c781eabbd Merge pull request #798 from stinos/msvc-alignof
msvc: Use built-in alignof
2014-08-13 13:34:41 +01:00
Damien George
9b7a8ee8f1 py: Fix mult by negative number of tuple, list, str, bytes.
Multiplication of a tuple, list, str or bytes now yields an empty
sequence (instead of crashing).  Addresses issue #799

Also added ability to mult bytes on LHS by integer.
2014-08-13 13:22:24 +01:00
stijn
8cce8b7c4c msvc: Use built-in alignof
This also fixes a 'unnamed type definition in parentheses' warning on the
alignof implementation define in binary.c
2014-08-13 10:19:56 +02:00
Sebastian Plamauer
2eeeafcba5 added install/uninstall 2014-08-11 19:47:00 +02:00
738 changed files with 46992 additions and 22380 deletions

View File

@@ -8,6 +8,8 @@ before_script:
- sudo add-apt-repository -y ppa:terry.guo/gcc-arm-embedded
- sudo apt-get update -qq
- sudo apt-get install -y python3.3 python3 gcc-4.7 gcc-arm-none-eabi qemu-system mingw32
# For teensy build
- sudo apt-get install realpath
script:
- make -C unix CC=gcc-4.7
@@ -15,11 +17,13 @@ script:
- make -C bare-arm
- make -C qemu-arm
- make -C stmhal
- make -C stmhal -B MICROPY_PY_WIZNET5K=1 MICROPY_PY_CC3K=1
- make -C stmhal BOARD=STM32F4DISC
- make -C teensy
- make -C windows CROSS_COMPILE=i586-mingw32msvc-
- (cd tests && MICROPY_CPYTHON3=python3.3 ./run-tests)
- (cd tests && MICROPY_CPYTHON3=python3.3 ./run-tests --emit native)
after_failure:
- (cd tests && for exp in *.exp; do testbase=$(basename $exp .exp); echo -e "\nFAILURE $testbase"; diff -u $testbase.exp $testbase.out; done)

View File

@@ -40,6 +40,17 @@ Header files:
Type names and declarations:
- When defining a type, put '_t' after it.
Integer types: Micro Python runs on 32 and 64 bit machines (and one day
maybe 16 bit), 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 Micro Python 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.
Examples
--------

View File

@@ -5,7 +5,7 @@
The Micro Python project
========================
<p align="center">
<img src="https://raw2.github.com/micropython/micropython/master/logo/upython-with-micro.jpg" alt="MicroPython Logo"/>
<img src="https://raw.githubusercontent.com/micropython/micropython/master/logo/upython-with-micro.jpg" alt="MicroPython Logo"/>
</p>
This is the Micro Python project, which aims to put an implementation
@@ -49,23 +49,28 @@ The Unix version
The "unix" port requires a standard Unix environment with gcc and GNU make.
x86 and x64 architectures are supported (i.e. x86 32- and 64-bit), as well
as ARMv7. Porting to other architectures require writing some assembly code
for the exception handling.
as ARM and MIPS. Making full-featured port to another architecture requires
writing some assembly code for the exception handling and garbage collection.
Alternatively, fallback implementation based on setjmp/longjmp can be used.
To build:
$ cd unix
$ make
Then to test it:
Then to give it a try:
$ ./micropython
>>> list(5 * x + y for x in range(10) for y in [4, 2, 1])
Run complete testsuite:
$ make test
Debian/Ubuntu/Mint derivative Linux distros will require build-essentials and
libreadline-dev packages installed. To build FFI (Foreign Function Interface)
module, libffi-dev package is required. If you have problems with some
dependencies, they can be disabled in unix/mpconfigport.mk .
module, libffi-dev and pkg-config packages are required. If you have problems
with some dependencies, they can be disabled in unix/mpconfigport.mk .
The STM version
---------------
@@ -93,3 +98,18 @@ AUR. If the above does not work it may be because you don't have the
correct permissions. Try then:
$ sudo dfu-util -a 0 -d 0483:df11 -D build-PYBV10/firmware.dfu
Building the documentation locally
----------------------------------
Install Sphinx, and optionally (for the RTD-styling), sphinx_rtd_theme,
preferably in a virtualenv:
pip install sphinx
pip install sphinx_rtd_theme
In `micropython/docs`, build the docs:
make html
You'll find the index page at `micropython/docs/build/html/index.html`.

View File

@@ -9,6 +9,7 @@ include ../py/py.mk
CROSS_COMPILE = arm-none-eabi-
INC = -I.
INC += -I..
INC += -I$(PY_SRC)
INC += -I$(BUILD)

View File

@@ -14,6 +14,7 @@
#include "runtime0.h"
#include "runtime.h"
#include "repl.h"
#include "pfenv.h"
void do_str(const char *src) {
mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, src, strlen(src), 0);
@@ -32,13 +33,13 @@ void do_str(const char *src) {
}
// parse okay
qstr source_name = mp_lexer_source_name(lex);
qstr source_name = lex->source_name;
mp_lexer_free(lex);
mp_obj_t module_fun = mp_compile(pn, source_name, MP_EMIT_OPT_NONE, true);
mp_parse_node_free(pn);
if (module_fun == mp_const_none) {
if (mp_obj_is_exception_instance(module_fun)) {
// compile error
mp_obj_print_exception(printf_wrapper, NULL, module_fun);
return;
}
@@ -48,7 +49,7 @@ void do_str(const char *src) {
nlr_pop();
} else {
// uncaught exception
mp_obj_print_exception((mp_obj_t)nlr.ret_val);
mp_obj_print_exception(printf_wrapper, NULL, (mp_obj_t)nlr.ret_val);
}
}
@@ -70,14 +71,25 @@ mp_import_stat_t mp_import_stat(const char *path) {
return MP_IMPORT_STAT_NO_EXIST;
}
mp_obj_t mp_builtin_open(uint n_args, const mp_obj_t *args) {
mp_obj_t mp_builtin_open(uint n_args, const mp_obj_t *args, mp_map_t *kwargs) {
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_open_obj, 1, 2, mp_builtin_open);
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
void nlr_jump_fail(void *val) {
}
void NORETURN __fatal_error(const char *msg) {
while (1);
}
#ifndef NDEBUG
void MP_WEAK __assert_func(const char *file, int line, const char *func, const char *expr) {
printf("Assertion '%s' failed, at file %s:%d\n", expr, file, line);
__fatal_error("Assertion failed");
}
#endif
/*
int _lseek() {return 0;}
int _read() {return 0;}

View File

@@ -12,11 +12,15 @@
#define MICROPY_HELPER_REPL (0)
#define MICROPY_HELPER_LEXER_UNIX (0)
#define MICROPY_ENABLE_SOURCE_LINE (0)
#define MICROPY_ENABLE_DOC_STRING (0)
#define MICROPY_ERROR_REPORTING (MICROPY_ERROR_REPORTING_TERSE)
#define MICROPY_PY_BUILTINS_BYTEARRAY (0)
#define MICROPY_PY_BUILTINS_MEMORYVIEW (0)
#define MICROPY_PY_BUILTINS_FROZENSET (0)
#define MICROPY_PY_BUILTINS_SET (0)
#define MICROPY_PY_BUILTINS_SLICE (0)
#define MICROPY_PY_BUILTINS_PROPERTY (0)
#define MICROPY_PY___FILE__ (0)
#define MICROPY_PY_GC (0)
#define MICROPY_PY_ARRAY (0)
#define MICROPY_PY_COLLECTIONS (0)
@@ -29,12 +33,12 @@
#define MICROPY_LONGINT_IMPL (MICROPY_LONGINT_IMPL_NONE)
#define MICROPY_FLOAT_IMPL (MICROPY_FLOAT_IMPL_NONE)
//#define MICROPY_ERROR_REPORTING (MICROPY_ERROR_REPORTING_TERSE)
// type definitions for the specific machine
#define BYTES_PER_WORD (4)
#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1))
#define UINT_FMT "%lu"
#define INT_FMT "%ld"
@@ -42,9 +46,10 @@ typedef int32_t mp_int_t; // must be pointer size
typedef uint32_t mp_uint_t; // must be pointer size
typedef void *machine_ptr_t; // must be of pointer size
typedef const void *machine_const_ptr_t; // must be of pointer size
typedef long mp_off_t;
// extra built in names to add to the global namespace
extern const struct _mp_obj_fun_native_t mp_builtin_open_obj;
extern const struct _mp_obj_fun_builtin_t mp_builtin_open_obj;
#define MICROPY_PORT_BUILTINS \
{ MP_OBJ_NEW_QSTR(MP_QSTR_open), (mp_obj_t)&mp_builtin_open_obj },

177
docs/Makefile Normal file
View File

@@ -0,0 +1,177 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/MicroPython.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/MicroPython.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/MicroPython"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/MicroPython"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."

279
docs/conf.py Executable file
View File

@@ -0,0 +1,279 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Micro Python documentation build configuration file, created by
# sphinx-quickstart on Sun Sep 21 11:42:03 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'Micro Python'
copyright = '2014, Damien P. George'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.3'
# The full version, including alpha/beta/rc tags.
release = '1.3.7'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# on_rtd is whether we are on readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
try:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.']
except:
html_theme = 'default'
html_theme_path = ['.']
else:
html_theme_path = ['.']
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = ['.']
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = '../logo/trans-logo.png'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%d %b %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
html_additional_pages = {"index": "topindex.html"}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'MicroPythondoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'MicroPython.tex', 'Micro Python Documentation',
'Damien P. George', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'micropython', 'Micro Python Documentation',
['Damien P. George'], 1),
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'MicroPython', 'Micro Python Documentation',
'Damien P. George', 'MicroPython', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}

11
docs/contents.rst Normal file
View File

@@ -0,0 +1,11 @@
Micro Python documentation contents
===================================
.. toctree::
quickref.rst
general.rst
tutorial/index.rst
library/index.rst
hardware/index.rst
license.rst

62
docs/general.rst Normal file
View File

@@ -0,0 +1,62 @@
General information about the pyboard
=====================================
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``.
(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.

29
docs/hardware/index.rst Normal file
View File

@@ -0,0 +1,29 @@
.. _hardware_index:
The pyboard hardware
====================
For the pyboard:
* `PYBv1.0 schematics and layout <http://micropython.org/resources/PYBv10b.pdf>`_ (2.4MiB PDF)
* `PYBv1.0 metric dimensions <http://micropython.org/resources/PYBv10b-metric-dimensions.pdf>`_ (360KiB PDF)
* `PYBv1.0 imperial dimensions <http://micropython.org/resources/PYBv10b-imperial-dimensions.pdf>`_ (360KiB PDF)
For the official skin modules:
* `LCD32MKv1.0 schematics <http://micropython.org/resources/LCD32MKv10-schematics.pdf>`_ (194KiB PDF)
* `AMPv1.0 schematics <http://micropython.org/resources/AMPv10-schematics.pdf>`_ (209KiB PDF)
Datasheets for the components on the pyboard
============================================
* The microcontroller: `STM32F405RGT6 <http://www.st.com/web/catalog/mmc/FM141/SC1169/SS1577/LN1035/PF252144>`_ (link to manufacturer's site)
* The accelerometer: `Freescale MMA7660 <http://micropython.org/resources/datasheets/MMA7660FC.pdf>`_ (800kiB PDF)
* The LDO voltage regulator: `Microchip MCP1802 <http://micropython.org/resources/datasheets/MCP1802-22053C.pdf>`_ (400kiB PDF)
Datasheets for other components
===============================
* The LCD display on the LCD touch-sensor skin: `Newhaven Display NHD-C12832A1Z-FSW-FBW-3V3 <http://micropython.org/resources/datasheets/NHD-C12832A1Z-FSW-FBW-3V3.pdf>`_ (460KiB PDF)
* The touch sensor chip on the LCD touch-sensor skin: `Freescale MPR121 <http://micropython.org/resources/datasheets/MPR121.pdf>`_ (280KiB PDF)
* The digital potentiometer on the audio skin: `Microchip MCP4541 <http://micropython.org/resources/datasheets/MCP4541-22107B.pdf>`_ (2.7MiB PDF)

19
docs/index.rst Normal file
View File

@@ -0,0 +1,19 @@
Micro Python documentation and references
=========================================
.. toctree::
quickref.rst
general.rst
tutorial/index.rst
library/index.rst
hardware/index.rst
license.rst
contents.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

58
docs/library/cmath.rst Normal file
View File

@@ -0,0 +1,58 @@
:mod:`cmath` -- mathematical functions for complex numbers
==========================================================
.. module:: cmath
:synopsis: mathematical functions for complex numbers
The ``cmath`` module provides some basic mathematical funtions for
working with complex numbers.
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

29
docs/library/gc.rst Normal file
View File

@@ -0,0 +1,29 @@
:mod:`gc` -- control the garbage collector
==========================================
.. module:: gc
:synopsis: control the garbage collector
Functions
---------
.. function:: enable()
Enable automatic garbage collection.
.. function:: disable()
Disable automatic garbage collection. Heap memory can still be allocated,
and garbage collection can still be initiated manually using :meth:`gc.collect`.
.. function:: collect()
Run a garbage collection.
.. function:: mem_alloc()
Return the number of bytes of heap RAM that are allocated.
.. function:: mem_free()
Return the number of bytes of available heap RAM.

58
docs/library/index.rst Normal file
View File

@@ -0,0 +1,58 @@
Micro Python libraries
======================
Python standard libraries
-------------------------
The following standard Python libraries are built in to Micro Python.
For additional libraries, please download them from the `micropython-lib repository
<https://github.com/micropython/micropython-lib>`_.
.. toctree::
:maxdepth: 1
cmath.rst
gc.rst
math.rst
os.rst
select.rst
struct.rst
sys.rst
time.rst
Python micro-libraries
----------------------
The following standard Python libraries have been "micro-ified" to fit in with
the philosophy of Micro Python. They provide the core functionality of that
module and are intended to be a drop-in replacement for the standard Python
library.
The modules are available 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
ubinascii.rst
uhashlib.rst
uheapq.rst
ujson.rst
ure.rst
usocket.rst
uzlib.rst
Libraries specific to the pyboard
---------------------------------
The following libraries are specific to the pyboard.
.. toctree::
:maxdepth: 2
pyb.rst
network.rst

177
docs/library/math.rst Normal file
View File

@@ -0,0 +1,177 @@
:mod:`math` -- mathematical functions
=====================================
.. module:: math
:synopsis: mathematical functions
The ``math`` module provides some basic mathematical funtions for
working with floating-point numbers.
*Note:* On the pyboard, floating-point numbers have 32-bit precision.
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)
Converts a floating-point number to fractional and integral components.
.. 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

177
docs/library/network.rst Normal file
View File

@@ -0,0 +1,177 @@
****************************************
:mod:`network` --- network configuration
****************************************
.. module:: network
:synopsis: network configuration
This module provides network drivers and routing configuration. Network
drivers for specific hardware are available within this module and are
used to configure a hardware network interface. Configured interfaces
are then available for use via the :mod:`socket` module.
For example::
# configure a specific network interface
# see below for examples of specific drivers
import network
nic = network.Driver(...)
print(nic.ifconfig())
# now use socket as usual
import socket
addr = socket.getaddrinfo('micropython.org', 80)[0][-1]
s = socket.socket()
s.connect(addr)
s.send(b'GET / HTTP/1.1\r\nHost: micropython.org\r\n\r\n')
data = s.recv(1000)
s.close()
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 <pyb.SPI>` which is the SPI bus that the CC3000 is
connected to (the MOSI, MISO and CLK pins).
- ``pin_cs`` is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 CS pin.
- ``pin_en`` is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 VBEN pin.
- ``pin_irq`` is a :ref:`Pin object <pyb.Pin>` 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 (only W5200 tested).
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 <pyb.SPI>` which is the SPI bus that the WIZnet5x00 is
connected to (the MOSI, MISO and SCLK pins).
- ``pin_cs`` is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nSS pin.
- ``pin_rst`` is a :ref:`Pin object <pyb.Pin>` 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.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.

67
docs/library/os.rst Normal file
View File

@@ -0,0 +1,67 @@
:mod:`os` -- basic "operating system" services
==============================================
.. module:: os
:synopsis: basic "operating system" services
The ``os`` module contains functions for filesystem access and ``urandom``.
Pyboard specifics
-----------------
The filesystem on the pyboard has ``/`` as the root directory and the
available physical drives are accessible from here. They are currently:
``/flash`` -- the internal flash filesystem
``/sd`` -- the SD card (if it exists)
On boot up, the current directory is ``/flash`` if no SD card is inserted,
otherwise it is ``/sd``.
Functions
---------
.. function:: chdir(path)
Change current directory.
.. function:: getcwd()
Get the current directory.
.. 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:: stat(path)
Get the status of a file or directory.
.. function:: sync()
Sync all filesystems.
.. function:: urandom(n)
Return a bytes object with n random bytes, generated by the hardware
random number generator.
Constants
---------
.. data:: sep
separation character used in paths

52
docs/library/pyb.ADC.rst Normal file
View File

@@ -0,0 +1,52 @@
.. _pyb.ADC:
class ADC -- analog to digital conversion: read analog values on a pin
======================================================================
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) # creale 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
------------
.. 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
-------
.. 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, freq)
Read analog values into the given buffer at the given frequency. Buffer
can be bytearray or array.array for example. If a buffer with 8-bit elements
is used, sample resolution will be reduced to 8 bits.
Example::
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.

View File

@@ -0,0 +1,51 @@
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.
Note: if you read accelerometer values immediately after creating this object
you will get 0. It takes around 20ms for the first sample to be ready, so,
unless you have some other code between creating this object and reading its
values, you should put a ``pyb.delay(20)`` after creating it. For example::
accel = pyb.Accel()
pyb.delay(20)
print(accel.x())
Methods
-------
.. method:: accel.filtered_xyz()
Get a 3-tuple of filtered x, y and z values.
.. 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.

154
docs/library/pyb.CAN.rst Normal file
View File

@@ -0,0 +1,154 @@
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
-------------
.. method:: 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)
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.|
+-----------+---------------------------------------------------------+
.. 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: buffer of data bytes.
.. method:: can.send(send, addr, \*, timeout=5000)
Send a message on the bus:
- ``send`` is the data to send (an integer to send, or a buffer object).
- ``addr`` is the address to send to
- ``timeout`` is the timeout in milliseconds to wait for the send.
Return value: ``None``.
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

69
docs/library/pyb.DAC.rst Normal file
View File

@@ -0,0 +1,69 @@
.. _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)
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)
Constructors
------------
.. class:: pyb.DAC(port)
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.
Methods
-------
.. 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 frequence of the repeating triangle wave
itself is 256 (or 1024, need to check) times smaller.
.. method:: dac.write(value)
Direct access to the DAC output (8 bit only at the moment).
.. 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 (8 bit data).
``mode`` can be ``DAC.NORMAL`` or ``DAC.CIRCULAR``.
TIM6 is used to control the frequency of the transfer.

113
docs/library/pyb.ExtInt.rst Normal file
View File

@@ -0,0 +1,113 @@
.. _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 thru 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 thru 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
-------------
.. method:: 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

153
docs/library/pyb.I2C.rst Normal file
View File

@@ -0,0 +1,153 @@
.. _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::
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.
Basic methods for slave 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) # timout 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)
Constructors
------------
.. class:: pyb.I2C(bus, ...)
Construct an I2C object on the given bus. ``bus`` can be 1 or 2.
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 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)``
Methods
-------
.. method:: i2c.deinit()
Turn off the I2C bus.
.. method:: i2c.init(mode, \*, addr=0x12, baudrate=400000, gencall=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
.. 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.scan()
Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond.
Only valid when in master mode.
.. 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``.
Constants
---------
.. data:: I2C.MASTER
for initialising the bus to master mode
.. data:: I2C.SLAVE
for initialising the bus to slave mode

94
docs/library/pyb.LCD.rst Normal file
View File

@@ -0,0 +1,94 @@
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.

39
docs/library/pyb.LED.rst Normal file
View File

@@ -0,0 +1,39 @@
.. _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``.
.. 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.

266
docs/library/pyb.Pin.rst Normal file
View File

@@ -0,0 +1,266 @@
.. _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:
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.B6`` 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).
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`.
Class methods
-------------
.. method:: Pin.af_list()
Returns an array of alternate functions available for this pin.
.. method:: Pin.debug([state])
Get or set the debugging state (``True`` or ``False`` for on or off).
.. method:: Pin.dict([dict])
Get or set the pin mapper dictionary.
.. method:: Pin.mapper([fun])
Get or set the pin mapper function.
Methods
-------
.. 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.high()
Set the pin to a high logic level.
.. method:: pin.low()
Set the pin to a low logic level.
.. 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.
.. 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.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
---------
.. 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
class PinAF -- Pin Alternate Functions
======================================
A Pin represents a physical pin on the microcprocessor. 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 availble 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

48
docs/library/pyb.RTC.rst Normal file
View File

@@ -0,0 +1,48 @@
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.
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
.. 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

123
docs/library/pyb.SPI.rst Normal file
View File

@@ -0,0 +1,123 @@
.. _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.
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 method 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
------------
.. class:: pyb.SPI(bus, ...)
Construct an SPI object on the given bus. ``bus`` can be 1 or 2.
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.
.. 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.
- ``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.
.. 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
---------
.. 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

View File

@@ -0,0 +1,38 @@
class Servo -- 3-wire hobby servo driver
========================================
Servo controls standard hobby servos with 3-wires (ground, power, signal).
Constructors
------------
.. class:: pyb.Servo(id)
Create a servo object. ``id`` is 1-4.
Methods
-------
.. method:: servo.angle([angle, time=0])
Get or set 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.
.. method:: servo.calibration([pulse_min, pulse_max, pulse_centre, [pulse_angle_90, pulse_speed_100]])
Get or set the calibration of the servo timing.
.. method:: servo.pulse_width([value])
Get or set the pulse width in milliseconds.
.. method:: servo.speed([speed, time=0])
Get or set the speed of a continuous rotation servo.
- ``speed`` is the speed to move to change to, between -100 and 100.
- ``time`` is the number of milliseconds to take to get to the specified speed.

View File

@@ -0,0 +1,37 @@
class Switch -- switch object
=============================
A Switch object is used to control a push-button switch.
Usage::
sw = pyb.Switch() # create a switch object
sw() # get state (True if pressed, False otherwise)
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()
Return the switch state: ``True`` if pressed down, ``False`` otherwise.
.. 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.

234
docs/library/pyb.Timer.rst Normal file
View File

@@ -0,0 +1,234 @@
.. _pyb.Timer:
class Timer -- control internal timers
======================================
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())
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 3 is reserved for internal use. 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.
Constructors
------------
.. class:: pyb.Timer(id, ...)
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, excluding 3.
Methods
-------
.. 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.
.. 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).
Othwerwise, 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.
- ``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 acive 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.
PWM Example::
timer = pyb.Timer(2, freq=1000)
ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=210000)
ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=420000)
.. method:: timer.counter([value])
Get or set the timer counter.
.. method:: timer.deinit()
Deinitialises the timer.
Disables the callback (and the associated irq).
Disables any channel callbacks (and the associated irq).
Stops the timer, and disables the timer peripheral.
.. method:: timer.freq([value])
Get or set the frequency for the timer (changes prescaler and period if set).
.. 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 migh 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`` - confgures 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. ``deadime``
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.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
-------
.. 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.
.. 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%.

136
docs/library/pyb.UART.rst Normal file
View File

@@ -0,0 +1,136 @@
.. _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
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.readall() # 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
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 True if any characters waiting
*Note:* The stream functions ``read``, ``write`` etc Are new in Micro Python since v1.3.4.
Earlier versions use ``uart.send`` and ``uart.recv``.
Constructors
------------
.. 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)``
Methods
-------
.. method:: uart.init(baudrate, bits=8, parity=None, stop=1, \*, timeout=1000, 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.
- ``timeout`` is the timeout in milliseconds to wait for the first character.
- ``timeout_char`` is the timeout in milliseconds to wait between characters.
- ``read_buf_len`` is the character length of the read buffer (0 to disable).
*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.
.. method:: uart.any()
Return ``True`` if any characters waiting, else ``False``.
.. method:: uart.read([nbytes])
Read characters. If ``nbytes`` is specified then read at most that many bytes.
*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 ``b''``
on timeout.
.. method:: uart.readall()
Read as much data as possible.
Return value: a bytes object.
.. 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``.
.. method:: uart.readline()
Read a line, ending in a newline character.
Return value: the line read.
.. method:: uart.write(buf)
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.
.. method:: uart.writechar(char)
Write a single character on the bus. ``char`` is an integer to write.
Return value: ``None``.

View File

@@ -0,0 +1,66 @@
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.any()
Return ``True`` if any characters waiting, else ``False``.
.. method:: usb_vcp.close()
.. method:: usb_vcp.read([nbytes])
.. method:: usb_vcp.readall()
.. method:: usb_vcp.readline()
.. 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.
.. method:: usb_vcp.write(buf)

225
docs/library/pyb.rst Normal file
View File

@@ -0,0 +1,225 @@
:mod:`pyb` --- functions related to the pyboard
===============================================
.. module:: pyb
:synopsis: functions related to the pyboard
The ``pyb`` module contains specific functions related to the pyboard.
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.
.. 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.
.. 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 upto 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 upto 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.
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
-----------------------
.. 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 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 interrupt.
This executies a ``wfi`` instruction which reduces power consumption
of the MCU until an interrupt occurs, at which point execution continues.
.. function:: standby()
.. function:: stop()
Miscellaneous functions
-----------------------
.. function:: have_cdc()
Return True if USB is connected as a serial device, False otherwise.
.. 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.
.. function:: info([dump_alloc_table])
Print out lots of information about the board.
.. 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 that the REPL is repeated on.
.. function:: rng()
Return a 30-bit hardware generated random number.
.. function:: sync()
Sync all file systems.
.. function:: unique_id()
Returns a string of 12 bytes (96 bits), which is the unique ID for the MCU.
Classes
-------
.. 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_VCP.rst

57
docs/library/select.rst Normal file
View File

@@ -0,0 +1,57 @@
:mod:`select` -- wait for events on a set of streams
========================================================================
.. module:: select
:synopsis: wait for events on a set of streams
This module provides functions to wait for events on streams (select streams
which are ready for operations).
Pyboard specifics
-----------------
Polling is an efficient way of waiting for read/write activity on multiple
objects. Current objects that support polling are: :class:`pyb.UART`,
:class:`pyb.USB_VCP`.
Functions
---------
.. function:: poll()
Create an instance of the Poll class.
.. function:: select(rlist, wlist, xlist[, timeout])
Wait for activity on a set of objects.
This function is provided for compatibility and is not efficient. Usage
of :class:`Poll` is recommended instead.
.. _class: Poll
class ``Poll``
--------------
Methods
~~~~~~~
.. method:: poll.register(obj[, eventmask])
Register ``obj`` for polling. ``eventmask`` is 1 for read, 2 for
write, 3 for read-write.
.. method:: poll.unregister(obj)
Unregister ``obj`` from polling.
.. method:: poll.modify(obj, eventmask)
Modify the ``eventmask`` for ``obj``.
.. method:: poll.poll([timeout])
Wait for at least one of the registered objects to become ready. Returns
list of ready objects, or empty list on timeout.
Timeout is in milliseconds.

25
docs/library/struct.rst Normal file
View File

@@ -0,0 +1,25 @@
:mod:`struct` -- pack and unpack primitive data types
=====================================================
.. module:: struct
:synopsis: pack and unpack primitive data types
See `Python struct <https://docs.python.org/3/library/struct.html>`_ for more
information.
Functions
---------
.. function:: calcsize(fmt)
Return the number of bytes needed to store the given ``fmt``.
.. function:: pack(fmt, v1, v2, ...)
Pack the values ``v1``, ``v2``, ... according to the format string ``fmt``.
The return value is a bytes object encoding the values.
.. function:: unpack(fmt, data)
Unpack from the ``data`` according to the format string ``fmt``.
The return value is a tuple of the unpacked values.

64
docs/library/sys.rst Normal file
View File

@@ -0,0 +1,64 @@
:mod:`sys` -- system specific functions
=======================================
.. module:: sys
:synopsis: system specific functions
Functions
---------
.. function:: exit([retval])
Raise a ``SystemExit`` exception. If an argument is given, it is the
value given to ``SystemExit``.
.. function:: print_exception(exc, [file])
Print exception with a traceback to a file-like object ``file`` (or
``sys.stdout`` by default).
.. admonition:: Difference to CPython
:class: attention
This function appears in the ``traceback`` module in CPython.
Constants
---------
.. data:: argv
a mutable list of arguments this program started with
.. data:: byteorder
the byte order of the system ("little" or "big")
.. data:: path
a mutable list of directories to search for imported modules
.. data:: platform
The platform that Micro Python is running on. This is "pyboard" on the
pyboard and provides a robust way of determining if a script is running
on the pyboard or not.
.. data:: stderr
standard error (connected to USB VCP, and optional UART object)
.. data:: stdin
standard input (connected to USB VCP, and optional UART object)
.. data:: stdout
standard output (connected to USB VCP, and optional UART object)
.. data:: version
Python language version that this implementation conforms to, as a string
.. data:: version_info
Python language version that this implementation conforms to, as a tuple of ints

41
docs/library/time.rst Normal file
View File

@@ -0,0 +1,41 @@
:mod:`time` -- time related functions
=====================================
.. module:: time
:synopsis: time related functions
The ``time`` module provides functions for getting the current time and date,
and for sleeping.
Functions
---------
.. function:: localtime([secs])
Convert a time expressed in seconds since Jan 1, 2000 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. Seconds can be a floating-point number to
sleep for a fractional number of seconds.
.. function:: time()
Returns the number of seconds, as an integer, since 1/1/2000.

View File

@@ -0,0 +1,15 @@
:mod:`ubinascii` -- binary/ASCII conversions
============================================
.. module:: ubinascii
:synopsis: binary/ASCII conversions
This module implements conversions between binary data and various
encodings of it in ASCII form (in both directions).
Functions
---------
.. function:: hexlify(data)
Convert binary data to hexadecimal representation. Return bytes string.

37
docs/library/uhashlib.rst Normal file
View File

@@ -0,0 +1,37 @@
:mod:`uhashlib` -- hashing algorithm
====================================
.. module:: uhashlib
:synopsis: hashing algorithm
This module implements binary data hashing algorithms. Currently, it
implements SHA256 algorithm. Choosing SHA256 was a deliberate choice,
as a modern, cryptographically secure algorithm. This means that a
single algorithm can cover both usecases of "any hash algorithm" and
security-related usage, and thus save space omitting legacy algorithms
like MD5 or SHA1.
Constructors
------------
.. class:: uhashlib.sha256([data])
Create a hasher object and optionally feed ``data`` into it.
Methods
-------
.. method:: sha256.update(data)
Feed more binary data into hash.
.. method:: sha256.digest()
Return hash for all data passed thru hash, as a bytes object. After this
method is called, more data cannot be fed into hash any longer.
.. method:: sha256.hexdigest()
This method is NOT implemented. Use ``ubinascii.hexlify(sha256.digest())``
to achieve similar effect.

25
docs/library/uheapq.rst Normal file
View File

@@ -0,0 +1,25 @@
:mod:`uheapq` -- heap queue algorithm
=====================================
.. module:: uheapq
:synopsis: heap queue algorithm
This module implements the heap queue algorithm.
A heap queue is simply a list that has its elements stored in a certain way.
Functions
---------
.. function:: heappush(heap, item)
Push the ``item`` onto the ``heap``.
.. function:: heappop(heap)
Pop the first item from the ``heap``, and return it. Raises IndexError if
heap is empty.
.. function:: heapify(x)
Convert the list ``x`` into a heap. This is an in-place operation.

20
docs/library/ujson.rst Normal file
View File

@@ -0,0 +1,20 @@
:mod:`ujson` -- JSON encoding and decoding
==========================================
.. module:: ujson
:synopsis: JSON encoding and decoding
This modules allows to convert between Python objects and the JSON
data format.
Functions
---------
.. function:: dumps(obj)
Return ``obj`` represented as a JSON string.
.. function:: loads(str)
Parse the JSON ``str`` and return an object. Raises ValueError if the
string is not correctly formed.

82
docs/library/ure.rst Normal file
View File

@@ -0,0 +1,82 @@
:mod:`ure` -- regular expressions
=================================
.. module:: ure
:synopsis: regular expressions
This module implements regular expression operations. Regular expression
syntax supported is a subset of CPython ``re`` module (and actually is
a subset of POSIX extended regular expressions).
Supported operators are:
``'.'``
Match any character.
``'[]'``
Match set of characters. Individual characters and ranges are supported.
``'^'``
``'$'``
``'?'``
``'*'``
``'+'``
``'??'``
``'*?'``
``'+?'``
Counted repetitions (``{m,n}``), more advanced assertions, names groups,
etc. are not supported.
Functions
---------
.. function:: compile(regex)
Compile regular expression, return ``regex`` object.
.. function:: match(regex, string)
Match ``regex`` against ``string``. Match always happens from starting
position in a string.
.. function:: search(regex, string)
Search ``regex`` in a ``string``. Unlike ``match``, this will search
string for first position which matches regex (which still may be
0 if regex is anchored).
.. data:: DEBUG
Flag value, display debug information about compiled expression.
Regex objects
-------------
Compiled regular expression. Instances of this class are created using
``ure.compile()``.
.. method:: regex.match(string)
.. method:: regex.search(string)
.. method:: regex.split(string, max_split=-1)
Match objects
-------------
Match objects as returned by ``match()`` and ``search()`` methods.
.. method:: match.group([index])
Only numeric groups are supported.

17
docs/library/usocket.rst Normal file
View File

@@ -0,0 +1,17 @@
:mod:`usocket` -- socket module
===============================
.. module:: usocket
:synopsis: socket module
Socket functionality.
Functions
---------
.. function:: getaddrinfo(host, port)
.. function:: socket(family=AF_INET, type=SOCK_STREAM, fileno=-1)
Create a socket.

16
docs/library/uzlib.rst Normal file
View File

@@ -0,0 +1,16 @@
:mod:`uzlib` -- zlib decompression
==================================
.. module:: uzlib
:synopsis: zlib decompression
This modules allows to decompress binary data compressed with DEFLATE
algorithm (commonly used in zlib library and gzip archiver). Compression
is not yet implemented.
Functions
---------
.. function:: decompress(data)
Return decompressed data as bytes.

24
docs/license.rst Normal file
View File

@@ -0,0 +1,24 @@
Micro Python license information
================================
The MIT License (MIT)
Copyright (c) 2013, 2014 Damien P. George, and others
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.

242
docs/make.bat Normal file
View File

@@ -0,0 +1,242 @@
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. xml to make Docutils-native XML files
echo. pseudoxml to make pseudoxml-XML files for display purposes
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
%SPHINXBUILD% 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\MicroPython.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\MicroPython.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdf" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdfja" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf-ja
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
if "%1" == "xml" (
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The XML files are in %BUILDDIR%/xml.
goto end
)
if "%1" == "pseudoxml" (
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
goto end
)
:end

140
docs/quickref.rst Normal file
View File

@@ -0,0 +1,140 @@
.. _quickref:
Quick reference for the pyboard
===============================
.. image:: http://micropython.org/resources/pybv10-pinout.jpg
:alt: PYBv1.0 pinout
:width: 700px
General board control
---------------------
See :mod:`pyb`. ::
import pyb
pyb.delay(50) # wait 50 milliseconds
pyb.millis() # number of milliseconds since bootup
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
LEDs
----
See :ref:`pyb.LED <pyb.LED>`. ::
from pyb import LED
led = LED(1) # red led
led.toggle()
led.on()
led.off()
Pins and GPIO
-------------
See :ref:`pyb.Pin <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
External interrupts
-------------------
See :ref:`pyb.ExtInt <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 <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())
PWM (pulse width modulation)
----------------------------
See :ref:`pyb.Pin <pyb.Pin>` and :ref:`pyb.Timer <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 <pyb.Pin>` and :ref:`pyb.ADC <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 <pyb.Pin>` and :ref:`pyb.DAC <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 <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 <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 a receive 5 bytes
I2C bus
-------
See :ref:`pyb.I2C <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

View File

@@ -0,0 +1,9 @@
import os
# Directory that the project lives in, aka ../..
SITE_ROOT = '/'.join(os.path.dirname(__file__).split('/')[0:-2])
TEMPLATE_DIRS = (
"%s/templates/" % SITE_ROOT, # Your custom template directory, before the RTD one to override it.
"%s/readthedocs/templates/" % SITE_ROOT, # Default RTD template dir
)

10
docs/static/customstyle.css vendored Normal file
View File

@@ -0,0 +1,10 @@
/* custom CSS for Micro Python docs
*/
.admonition-difference-to-cpython {
border: 1px solid black;
}
.admonition-difference-to-cpython .admonition-title {
margin: 4px;
}

2
docs/templates/layout.html vendored Normal file
View File

@@ -0,0 +1,2 @@
{% extends "!layout.html" %}
{% set css_files = css_files + ["_static/customstyle.css"] %}

93
docs/topindex.html Normal file
View File

@@ -0,0 +1,93 @@
{% extends "defindex.html" %}
{% block body %}
<h1>Micro Python documentation</h1>
<p>
{{ _('Welcome! This is the documentation for Micro Python') }}
v{{ release|e }}{% if last_updated %}, {{ _('last updated') }} {{ last_updated|e }}{% endif %}.
</p>
<p><strong>Documentation for Micro Python and the pyboard:</strong></p>
<table class="contentstable"><tr>
<td width="40%" style="padding-left:2em;">
<p class="biglink">
<a class="biglink" href="{{ pathto("quickref") }}">Quick reference for the pyboard</a><br/>
<span class="linkdescr">pinout for the pyboard and snippets of useful code</span>
</p>
<p class="biglink">
<a class="biglink" href="{{ pathto("general") }}">General information about the pyboard</a><br/>
<span class="linkdescr">read this first for a quick overview</span>
</p>
<p class="biglink">
<a class="biglink" href="{{ pathto("tutorial/index") }}">Tutorials and code examples</a><br/>
<span class="linkdescr">start here</span>
</p>
<p class="biglink">
<a class="biglink" href="{{ pathto("library/index") }}">Library Reference</a><br/>
<span class="linkdescr">Micro Python libraries, including the <a href="{{ pathto("library/pyb") }}">pyb module</a></span>
</p>
</td>
<td width="40%" style="padding-left:2em;">
<p class="biglink">
<a class="biglink" href="{{ pathto("hardware/index") }}">The pyboard hardware</a><br/>
<span class="linkdescr">schematics, dimensions and component datasheets</span>
</p>
<p class="biglink">
<a class="biglink" href="http://micropython.org/resources/Micro-Python-Windows-setup.pdf">Guide for pyboard on Windows (PDF)</a><br/>
<span class="linkdescr">including DFU programming</span>
</p>
<p class="biglink">
<a class="biglink" href="{{ pathto("license") }}">License</a><br/>
<span class="linkdescr">Micro Python license information</span>
</p>
</td>
</tr></table>
<p><strong>Indices and tables:</strong></p>
<table class="contentstable"><tr>
<td width="40%" style="padding-left:2em;">
<p class="biglink">
<a class="biglink" href="{{ pathto("py-modindex") }}">Module index</a><br/>
<span class="linkdescr">quick access to all modules</span>
</p>
<p class="biglink">
<a class="biglink" href="{{ pathto("genindex") }}">Full index</a><br/>
<span class="linkdescr">all functions, classes, constants</span>
</p>
</td>
<td width="40%" style="padding-left:2em;">
<p class="biglink">
<a class="biglink" href="{{ pathto("contents") }}">Table of contents</a><br/>
<span class="linkdescr">a list of all sections and subsections</span>
</p>
<p class="biglink">
<a class="biglink" href="{{ pathto("search") }}">Search page</a><br/>
<span class="linkdescr">search this documentation</span>
</p>
</td></tr>
</table>
<p><strong>External links:</strong></p>
<table class="contentstable"><tr>
<td width="40%" style="padding-left:2em;">
<p class="biglink">
<a class="biglink" href="http://micropython.org">Micro Python homepage</a><br/>
<span class="linkdescr">the official Micro Python site</span>
</p>
<p class="biglink">
<a class="biglink" href="http://forum.micropython.org">Micro Python forum</a><br/>
<span class="linkdescr">community discussion for all things related to Micro Python</span>
</p>
</td>
<td width="40%" style="padding-left:2em;">
<p class="biglink">
<a class="biglink" href="https://github.com/micropython">Micro Python on GitHub</a><br/>
<span class="linkdescr">contribute to the source code on GitHub</span>
</p>
</td>
</tr></table>
{% endblock %}

92
docs/tutorial/accel.rst Normal file
View File

@@ -0,0 +1,92 @@
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.

View File

@@ -0,0 +1,68 @@
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
<iframe style="margin-left:3em;" width="560" height="315" src="http://www.youtube.com/embed/fjB1DuZRveo?rel=0" frameborder="0" allowfullscreen></iframe>
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 <http://micropython.org/resources/examples/wave.py>`_ and you will also need
the chunk module available `here <http://micropython.org/resources/examples/chunk.py>`_. 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 <http://micropython.org/resources/examples/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.

123
docs/tutorial/assembler.rst Normal file
View File

@@ -0,0 +1,123 @@
Inline assembler
================
Here you will learn how to write inline assembler in Micro Python.
**Note**: this is an advanced tutorial, intended for those who already
know a bit about microcontrollers and assembly language.
Micro Python 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.
Micro Python 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 3 arguments. If they are
used, they must be named ``r0``, ``r1`` and ``r2`` 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)

View File

@@ -0,0 +1,37 @@
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()

View File

@@ -0,0 +1,89 @@
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) <http://en.wikipedia.org/wiki/Pulse-width_modulation>`_, 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 <http://en.wikipedia.org/wiki/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 <http://www.telescope-optics.net/eye_intensity_response.htm>`_
), 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.

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

47
docs/tutorial/index.rst Normal file
View File

@@ -0,0 +1,47 @@
.. _tutorial-index:
Micro Python tutorial
=====================
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
Tips, tricks and useful things to know
--------------------------------------
.. toctree::
:maxdepth: 1
:numbered:
debounce.rst
pass_through.rst

54
docs/tutorial/intro.rst Normal file
View File

@@ -0,0 +1,54 @@
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
Micro Python 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.**

View File

@@ -0,0 +1,86 @@
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
<iframe style="margin-left:3em;" width="560" height="315" src="http://www.youtube.com/embed/PowCzdLYbFM?rel=0" frameborder="0" allowfullscreen></iframe>
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 Micro Python 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 <http://micropython.org/resources/examples/mpr121.py>`_
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 <http://micropython.org/resources/examples/lcddemo.py>`_.

75
docs/tutorial/leds.rst Normal file
View File

@@ -0,0 +1,75 @@
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, Micro Python 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 Micro Python 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 Fourth Special LED
----------------------
The blue LED is special. As well as turning it on and off, you can control the 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 the other LEDs but they can only be off or on. 0 sets them off and any other number up to 255 turns them on.

View File

@@ -0,0 +1,18 @@
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))

View File

@@ -0,0 +1,13 @@
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

107
docs/tutorial/repl.rst Normal file
View File

@@ -0,0 +1,107 @@
Getting a Micro Python REPL prompt
==================================
REPL stands for Read Evaluate Print Loop, and is the name given to the
interactive Micro Python 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).
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 <http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html>`_.
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 Micro Python 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
Micro Python 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 Micro Python 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.

60
docs/tutorial/reset.rst Normal file
View File

@@ -0,0 +1,60 @@
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.

105
docs/tutorial/script.rst Normal file
View File

@@ -0,0 +1,105 @@
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 <http://micropython.org/resources/fresh-pyboard/boot.py>`_ -- this script is executed when the pyboard boots up. It sets
up various configuration options for the pyboard.
* `main.py <http://micropython.org/resources/fresh-pyboard/main.py>`_ -- this is the main script that will contain your Python program.
It is executed after ``boot.py``.
* `README.txt <http://micropython.org/resources/fresh-pyboard/README.txt>`_ -- this contains some very basic information about getting
started with the pyboard.
* `pybcdc.inf <http://micropython.org/resources/fresh-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 Micro Python
program!

146
docs/tutorial/servo.rst Normal file
View File

@@ -0,0 +1,146 @@
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.

101
docs/tutorial/switch.rst Normal file
View File

@@ -0,0 +1,101 @@
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()
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.
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.

112
docs/tutorial/timer.rst Normal file
View File

@@ -0,0 +1,112 @@
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=255, period=32811, mode=0, div=0)
The information means that this timer is set to run at the peripheral
clock speed divided by 255, and it will count up to 32811, 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.
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 freqency 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()

129
docs/tutorial/usb_mouse.rst Normal file
View File

@@ -0,0 +1,129 @@
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('CDC+MSC') # act as a serial and a storage device
#pyb.usb_mode('CDC+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('CDC+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('CDC+HID')
This tells the pyboard to configure itself as a CDC (serial) 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::
>>> pyb.hid((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):
... pyb.hid((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.
**Excercise: 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 editting ``main.py``.)
In ``main.py`` put the following code::
import pyb
switch = pyb.Switch()
accel = pyb.Accel()
while not switch():
pyb.hid((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 ``pyb.hid()`` 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
``CDC+HID`` setting, so it looks like::
#pyb.usb_mode('CDC+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.

2
drivers/README.md Normal file
View File

@@ -0,0 +1,2 @@
This directory contains drivers for specific hardware. The drivers are
intended to work across multiple ports.

View File

@@ -12,32 +12,41 @@
*
* 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
* 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
* 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
* 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
* 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 __COMMON_H__
#define __COMMON_H__
#ifndef __CC3000_COMMON_H__
#define __CC3000_COMMON_H__
#include "data_types.h"
//******************************************************************************
// Include files
//******************************************************************************
#include <stdlib.h>
#include <stdint.h>
//*****************************************************************************
// Prefix exported names to avoid name clash
//*****************************************************************************
#define CC3000_EXPORT(name) cc3000_ ## name
//*****************************************************************************
//
@@ -49,6 +58,8 @@
extern "C" {
#endif
extern int CC3000_EXPORT(errno);
//*****************************************************************************
// ERROR CODES
//*****************************************************************************
@@ -59,18 +70,16 @@ extern "C" {
//*****************************************************************************
// COMMON DEFINES
//*****************************************************************************
#define ERROR_SOCKET_INACTIVE -57
#define ERROR_SOCKET_INACTIVE -57
#define WLAN_ENABLE (1)
#define WLAN_ENABLE (1)
#define WLAN_DISABLE (0)
#define MAC_ADDR_LEN (6)
#define SP_PORTION_SIZE (32)
// #define CC3000_TINY_DRIVER
/*Defines for minimal and maximal RX buffer size. This size includes the spi
/*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
@@ -78,26 +87,26 @@ extern "C" {
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 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
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:
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,
MAX SSID LEN = 32
MAX SSID LEN = 13 (with add_profile only ascii key setting is supported,
therfore maximum key size is 13)
*/
@@ -106,24 +115,24 @@ extern "C" {
/*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
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 */
The 1 is used for the overrun detection */
#define CC3000_MINIMAL_TX_SIZE (130 + 1)
#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.
@@ -132,64 +141,64 @@ extern "C" {
#define TINY_CC3000_MAXIMAL_TX_SIZE 59
#endif
/*In order to determine your preferred buffer size,
/*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.
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_MINIMAL_RX_SIZE)
#define CC3000_TX_BUFFER_SIZE (CC3000_MINIMAL_TX_SIZE)
#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
#endif
//*****************************************************************************
// Compound Types
//*****************************************************************************
typedef long time_t;
typedef unsigned long clock_t;
typedef long suseconds_t;
typedef INT32 time_t;
typedef UINT32 clock_t;
typedef INT32 suseconds_t;
typedef struct timeval timeval;
struct timeval
struct timeval
{
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
typedef char *(*tFWPatches)(unsigned long *usLength);
typedef CHAR *(*tFWPatches)(UINT32 *usLength);
typedef char *(*tDriverPatches)(unsigned long *usLength);
typedef CHAR *(*tDriverPatches)(UINT32 *usLength);
typedef char *(*tBootLoaderPatches)(unsigned long *usLength);
typedef CHAR *(*tBootLoaderPatches)(UINT32 *usLength);
typedef void (*tWlanCB)(long event_type, char * data, unsigned char length );
typedef void (*tWlanCB)(INT32 event_type, CHAR * data, UINT8 length );
typedef long (*tWlanReadInteruptPin)(void);
typedef INT32 (*tWlanReadInteruptPin)(void);
typedef void (*tWlanInterruptEnable)(void);
typedef void (*tWlanInterruptDisable)(void);
typedef void (*tWriteWlanPin)(unsigned char val);
typedef void (*tWriteWlanPin)(UINT8 val);
typedef struct
{
unsigned short usRxEventOpcode;
unsigned short usEventOrDataReceived;
unsigned char *pucReceivedData;
unsigned char *pucTxCommandBuffer;
UINT16 usRxEventOpcode;
UINT16 usEventOrDataReceived;
UINT8 *pucReceivedData;
UINT8 *pucTxCommandBuffer;
tFWPatches sFWPatches;
tDriverPatches sDriverPatches;
@@ -200,16 +209,16 @@ typedef struct
tWlanInterruptDisable WlanInterruptDisable;
tWriteWlanPin WriteWlanPin;
signed long slTransmitDataError;
unsigned short usNumberOfFreeBuffers;
unsigned short usSlBufferLength;
unsigned short usBufferSize;
unsigned short usRxDataPending;
INT32 slTransmitDataError;
UINT16 usNumberOfFreeBuffers;
UINT16 usSlBufferLength;
UINT16 usBufferSize;
UINT16 usRxDataPending;
unsigned long NumberOfSentPackets;
unsigned long NumberOfReleasedPackets;
UINT32 NumberOfSentPackets;
UINT32 NumberOfReleasedPackets;
unsigned char InformHostOnTxComplete;
UINT8 InformHostOnTxComplete;
}sSimplLinkInformation;
extern volatile sSimplLinkInformation tSLInformation;
@@ -235,7 +244,7 @@ extern volatile sSimplLinkInformation tSLInformation;
//
//*****************************************************************************
extern void SimpleLinkWaitEvent(unsigned short usOpcode, void *pRetParams);
extern void SimpleLinkWaitEvent(UINT16 usOpcode, void *pRetParams);
//*****************************************************************************
//
@@ -248,12 +257,12 @@ extern void SimpleLinkWaitEvent(unsigned short usOpcode, void *pRetParams);
//! @return none
//!
//! @brief Wait for data, pass it to the hci_event_handler
//! and update in a global variable that there is
//! and update in a global variable that there is
//! data to read.
//
//*****************************************************************************
extern void SimpleLinkWaitData(unsigned char *pBuf, unsigned char *from, unsigned char *fromlen);
extern void SimpleLinkWaitData(UINT8 *pBuf, UINT8 *from, UINT8 *fromlen);
//*****************************************************************************
//
@@ -269,7 +278,7 @@ extern void SimpleLinkWaitData(unsigned char *pBuf, unsigned char *from, unsigne
//
//*****************************************************************************
extern unsigned char* UINT32_TO_STREAM_f (unsigned char *p, unsigned long u32);
extern UINT8* UINT32_TO_STREAM_f (UINT8 *p, UINT32 u32);
//*****************************************************************************
//
@@ -280,12 +289,12 @@ extern unsigned char* UINT32_TO_STREAM_f (unsigned char *p, unsigned long u32);
//!
//! \return pointer to the new stream
//!
//! \brief This function is used for copying 16 bit to stream
//! \brief This function is used for copying 16 bit to stream
//! while converting to little endian format.
//
//*****************************************************************************
extern unsigned char* UINT16_TO_STREAM_f (unsigned char *p, unsigned short u16);
extern UINT8* UINT16_TO_STREAM_f (UINT8 *p, UINT16 u16);
//*****************************************************************************
//
@@ -296,12 +305,12 @@ extern unsigned char* UINT16_TO_STREAM_f (unsigned char *p, unsigned short u16);
//!
//! \return pointer to the new 16 bit
//!
//! \brief This function is used for copying received stream to
//! \brief This function is used for copying received stream to
//! 16 bit in little endian format.
//
//*****************************************************************************
extern unsigned short STREAM_TO_UINT16_f(char* p, unsigned short offset);
extern UINT16 STREAM_TO_UINT16_f(CHAR* p, UINT16 offset);
//*****************************************************************************
//
@@ -317,21 +326,7 @@ extern unsigned short STREAM_TO_UINT16_f(char* p, unsigned short offset);
//
//*****************************************************************************
extern unsigned long STREAM_TO_UINT32_f(char* p, unsigned short offset);
//*****************************************************************************
//
//! cc3k_int_poll
//!
//! \brief checks if the interrupt pin is low
//! just in case the hardware missed a falling edge
//! function is in ccspi.cpp
//
//*****************************************************************************
extern void cc3k_int_poll();
extern UINT32 STREAM_TO_UINT32_f(CHAR* p, UINT16 offset);
//*****************************************************************************
@@ -346,14 +341,14 @@ extern void cc3k_int_poll();
//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 short _i; for (_i = 0; _i < l; _i++) *(p)++ = ((unsigned char *) a)[_i];}
#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 = (unsigned char)(*(_p + _offset));}
#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 short _i; for (_i = 0; _i < l; _i++) *(a)++= ((unsigned char *) p)[_i];}
#define STREAM_TO_STREAM(p, a, l) {register INT16 _i; for (_i = 0; _i < l; _i++) *(a)++= ((UINT8 *) p)[_i];}
@@ -367,4 +362,4 @@ extern void cc3k_int_poll();
}
#endif // __cplusplus
#endif // __COMMON_H__
#endif // __CC3000_COMMON_H__

View File

@@ -3,14 +3,6 @@
* spi.h - CC3000 Host Driver Implementation.
* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/
*
* Adapted for use with the Arduino/AVR by KTOWN (Kevin Townsend)
* & Limor Fried for Adafruit Industries
* This library works with the Adafruit CC3000 breakout
* ----> https://www.adafruit.com/products/1469
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
@@ -20,40 +12,43 @@
*
* 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
* 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
* 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
* 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
* 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 __SPI_H__
#define __SPI_H__
#ifndef __CC3000_SPI_H__
#define __CC3000_SPI_H__
//#include <string.h>
//#include <stdlib.h>
//#include <stdio.h>
//#include "wlan.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[];
//*****************************************************************************
@@ -61,23 +56,29 @@ extern unsigned char wlan_tx_buffer[];
// Prototypes for the APIs.
//
//*****************************************************************************
extern void SpiInit(void);
// 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 long SpiWrite(unsigned char *pUserBuffer, unsigned short usLength);
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 long TXBufferIsEmpty(void);
extern long RXBufferIsEmpty(void);
extern void CC3000_UsynchCallback(long lEventType, char * data, unsigned char length);
extern void WriteWlanPin( unsigned char val );
extern void SSIConfigure(unsigned long ulSSIFreq, unsigned long bForceGpioConfiguration, unsigned long uiReconfigureSysClock);
extern int init_spi(void);
extern long ReadWlanInterruptPin(void);
extern void WlanInterruptEnable();
extern void WlanInterruptDisable();
extern char *sendDriverPatch(unsigned long *Length);
extern char *sendBootLoaderPatch(unsigned long *Length);
extern char *sendWLFWPatch(unsigned long *Length);
extern void SpiIntGPIOHandler(void);
extern void WriteWlanPin(unsigned char val);
//*****************************************************************************
//
// Mark the end of the C bindings section for C++ compilers.
//
//*****************************************************************************
#ifdef __cplusplus
}
#endif // __cplusplus
#endif

View File

@@ -0,0 +1,107 @@
/*****************************************************************************
*
* 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__ */

View File

@@ -12,28 +12,28 @@
*
* 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
* 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
* 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
* 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
* 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 __EVENT_HANDLER_H__
#define __EVENT_HANDLER_H__
#ifndef __CC3000_EVENT_HANDLER_H__
#define __CC3000_EVENT_HANDLER_H__
#include "hci.h"
#include "socket.h"
@@ -67,7 +67,7 @@ extern "C" {
//! event handler from global array of handlers pointers
//
//*****************************************************************************
extern unsigned char *hci_event_handler(void *pRetParams, unsigned char *from, unsigned char *fromlen);
extern UINT8 *hci_event_handler(void *pRetParams, UINT8 *from, UINT8 *fromlen);
//*****************************************************************************
//
@@ -81,7 +81,7 @@ extern unsigned char *hci_event_handler(void *pRetParams, unsigned char *from, u
//! @brief Handle unsolicited events
//
//*****************************************************************************
extern long hci_unsol_event_handler(char *event_hdr);
extern INT32 hci_unsol_event_handler(CHAR *event_hdr);
//*****************************************************************************
//
@@ -91,13 +91,13 @@ extern long hci_unsol_event_handler(char *event_hdr);
//!
//! @return ESUCCESS if successful, EFAIL if an error occurred
//!
//! @brief Parse the incoming unsolicited event packets and issues
//! @brief Parse the incoming unsolicited event packets and issues
//! corresponding event handler.
//
//*****************************************************************************
extern long hci_unsolicited_event_handler(void);
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 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
@@ -107,25 +107,25 @@ extern long hci_unsolicited_event_handler(void);
#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 unsigned long socket_active_status;
extern UINT32 socket_active_status;
extern void set_socket_active_status(long Sd, long Status);
extern long get_socket_active_status(long Sd);
extern void set_socket_active_status(INT32 Sd, INT32 Status);
extern INT32 get_socket_active_status(INT32 Sd);
typedef struct _bsd_accept_return_t
{
long iSocketDescriptor;
long iStatus;
INT32 iSocketDescriptor;
INT32 iStatus;
sockaddr tSocketAddress;
} tBsdReturnParams;
typedef struct _bsd_read_return_t
{
long iSocketDescriptor;
long iNumberOfBytes;
unsigned long uiFlags;
INT32 iSocketDescriptor;
INT32 iNumberOfBytes;
UINT32 uiFlags;
} tBsdReadReturnParams;
#define BSD_RECV_FROM_FROMLEN_OFFSET (4)
@@ -134,23 +134,23 @@ typedef struct _bsd_read_return_t
typedef struct _bsd_select_return_t
{
long iStatus;
unsigned long uiRdfd;
unsigned long uiWrfd;
unsigned long uiExfd;
INT32 iStatus;
UINT32 uiRdfd;
UINT32 uiWrfd;
UINT32 uiExfd;
} tBsdSelectRecvParams;
typedef struct _bsd_getsockopt_return_t
{
unsigned char ucOptValue[4];
char iStatus;
UINT8 ucOptValue[4];
CHAR iStatus;
} tBsdGetSockOptReturnParams;
typedef struct _bsd_gethostbyname_return_t
{
long retVal;
long outputAddress;
INT32 retVal;
INT32 outputAddress;
} tBsdGethostbynameParams;
//*****************************************************************************
@@ -162,5 +162,5 @@ typedef struct _bsd_gethostbyname_return_t
}
#endif // __cplusplus
#endif // __EVENT_HANDLER_H__
#endif // __CC3000_EVENT_HANDLER_H__

View File

@@ -12,28 +12,28 @@
*
* 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
* 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
* 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
* 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
* 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 __HCI_H__
#define __HCI_H__
#ifndef __CC3000_HCI_H__
#define __CC3000_HCI_H__
#include "cc3000_common.h"
@@ -102,6 +102,7 @@ extern "C" {
#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
@@ -167,6 +168,7 @@ extern "C" {
#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
@@ -230,8 +232,8 @@ extern "C" {
#define HCI_EVENT_LENGTH_OFFSET (3)
#define HCI_EVENT_STATUS_OFFSET (4)
#define HCI_DATA_LENGTH_OFFSET (3)
//*****************************************************************************
@@ -253,10 +255,10 @@ extern "C" {
//! @brief Initiate an HCI command.
//
//*****************************************************************************
extern unsigned short hci_command_send(unsigned short usOpcode,
unsigned char *ucArgs,
unsigned char ucArgsLength);
extern UINT16 hci_command_send(UINT16 usOpcode,
UINT8 *ucArgs,
UINT8 ucArgsLength);
//*****************************************************************************
//
@@ -273,12 +275,12 @@ extern unsigned short hci_command_send(unsigned short usOpcode,
//! @brief Initiate an HCI data write operation
//
//*****************************************************************************
extern long hci_data_send(unsigned char ucOpcode,
unsigned char *ucArgs,
unsigned short usArgsLength,
unsigned short usDataLength,
const unsigned char *ucTail,
unsigned short usTailLength);
extern INT32 hci_data_send(UINT8 ucOpcode,
UINT8 *ucArgs,
UINT16 usArgsLength,
UINT16 usDataLength,
const UINT8 *ucTail,
UINT16 usTailLength);
//*****************************************************************************
@@ -295,8 +297,8 @@ extern long hci_data_send(unsigned char ucOpcode,
//! @brief Prepare HCI header and initiate an HCI data write operation
//
//*****************************************************************************
extern void hci_data_command_send(unsigned short usOpcode, unsigned char *pucBuff,
unsigned char ucArgsLength, unsigned short ucDataLength);
extern void hci_data_command_send(UINT16 usOpcode, UINT8 *pucBuff,
UINT8 ucArgsLength, UINT16 ucDataLength);
//*****************************************************************************
//
@@ -304,7 +306,7 @@ extern void hci_data_command_send(unsigned short usOpcode, unsigned char *pucBuf
//!
//! @param usOpcode command operation code
//! @param pucBuff pointer to the command's arguments buffer
//! @param patch pointer to patch content buffer
//! @param patch pointer to patch content buffer
//! @param usDataLength data length
//!
//! @return none
@@ -312,7 +314,7 @@ extern void hci_data_command_send(unsigned short usOpcode, unsigned char *pucBuf
//! @brief Prepare HCI header and initiate an HCI patch write operation
//
//*****************************************************************************
extern void hci_patch_send(unsigned char ucOpcode, unsigned char *pucBuff, char *patch, unsigned short usDataLength);
extern void hci_patch_send(UINT8 ucOpcode, UINT8 *pucBuff, CHAR *patch, UINT16 usDataLength);
@@ -325,4 +327,4 @@ extern void hci_patch_send(unsigned char ucOpcode, unsigned char *pucBuff, char
}
#endif // __cplusplus
#endif // __HCI_H__
#endif // __CC3000_HCI_H__

View File

@@ -12,44 +12,29 @@
*
* 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
* 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
* 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
* 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
* 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 __HOST_DRIVER_VERSION_H__
#define __HOST_DRIVER_VERSION_H__
#define DRIVER_VERSION_NUMBER 14
#endif // __VERSION_H__
#ifndef __CC3000_HOST_DRIVER_VERSION_H__
#define __CC3000_HOST_DRIVER_VERSION_H__
#define DRIVER_VERSION_NUMBER 15
#endif // __CC3000_HOST_DRIVER_VERSION_H__

View File

@@ -0,0 +1,4 @@
#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 */

View File

@@ -0,0 +1,4 @@
#ifndef __INET_PTON_H
#define __INET_PTON_H
int inet_pton(int, const char *, void *);
#endif /* __INET_PTON_H */

View File

@@ -12,29 +12,30 @@
*
* 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
* 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
* 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
* 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
* 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 __NETAPP_H__
#define __NETAPP_H__
#ifndef __CC3000_NETAPP_H__
#define __CC3000_NETAPP_H__
#include "data_types.h"
//*****************************************************************************
//
@@ -55,33 +56,33 @@ extern "C" {
typedef struct _netapp_dhcp_ret_args_t
{
unsigned char aucIP[4];
unsigned char aucSubnetMask[4];
unsigned char aucDefaultGateway[4];
unsigned char aucDHCPServer[4];
unsigned char aucDNSServer[4];
UINT8 aucIP[4];
UINT8 aucSubnetMask[4];
UINT8 aucDefaultGateway[4];
UINT8 aucDHCPServer[4];
UINT8 aucDNSServer[4];
}tNetappDhcpParams;
typedef struct _netapp_ipconfig_ret_args_t
{
unsigned char aucIP[4];
unsigned char aucSubnetMask[4];
unsigned char aucDefaultGateway[4];
unsigned char aucDHCPServer[4];
unsigned char aucDNSServer[4];
unsigned char uaMacAddr[6];
unsigned char uaSSID[32];
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
{
unsigned long packets_sent;
unsigned long packets_received;
unsigned long min_round_time;
unsigned long max_round_time;
unsigned long avg_round_time;
UINT32 packets_sent;
UINT32 packets_received;
UINT32 min_round_time;
UINT32 max_round_time;
UINT32 avg_round_time;
} netapp_pingreport_args_t;
@@ -89,45 +90,45 @@ typedef struct _netapp_pingreport_args
//
//! netapp_config_mac_adrress
//!
//! @param mac device mac address, 6 bytes. Saved: yes
//! @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.
//! @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
//! be stored in CC3000 non volatile memory, thus preserved
//! over resets.
//
//*****************************************************************************
extern long netapp_config_mac_adrress( unsigned char *mac );
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
//! @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,
//! @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.
//!
//! @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 long netapp_dhcp(unsigned long *aucIP, unsigned long *aucSubnetMask,unsigned long *aucDefaultGateway, unsigned long *aucDNSServer);
extern INT32 netapp_dhcp(UINT32 *aucIP, UINT32 *aucSubnetMask,UINT32 *aucDefaultGateway, UINT32 *aucDNSServer);
@@ -135,30 +136,30 @@ extern long netapp_dhcp(unsigned long *aucIP, unsigned long *aucSubnetMask,unsi
//
//! netapp_timeout_values
//!
//! @param aucDHCP DHCP lease time request, also impact
//! @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 - 20 seconds.
//! The parameter is saved into the CC3000 NVMEM.
//! 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.
//! 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 - 20 seconds
//! The parameter is saved into the CC3000 NVMEM.
//! 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 - 20 sec
//! The parameter is saved into the CC3000 NVMEM.
//! 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
@@ -166,22 +167,22 @@ extern long netapp_dhcp(unsigned long *aucIP, unsigned long *aucSubnetMask,unsi
//! 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 - 20 sec
//! The parameter is saved into the CC3000 NVMEM.
//! 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 20s,
//! it will be set automatically to 20s.
//! @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 long netapp_timeout_values(unsigned long *aucDHCP, unsigned long *aucARP,unsigned long *aucKeepalive, unsigned long *aucInactivity);
#ifndef CC3000_TINY_DRIVER
extern INT32 netapp_timeout_values(UINT32 *aucDHCP, UINT32 *aucARP, UINT32 *aucKeepalive, UINT32 *aucInactivity);
#endif
//*****************************************************************************
@@ -190,23 +191,23 @@ extern long netapp_timeout_values(unsigned long *aucDHCP, unsigned long *aucARP,
//!
//! @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 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
//! @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
//! @warning Calling this function while a previous Ping Requests are in
//! progress will stop the previous ping request.
//*****************************************************************************
#ifndef CC3000_TINY_DRIVER
extern long netapp_ping_send(unsigned long *ip, unsigned long ulPingAttempts, unsigned long ulPingSize, unsigned long ulPingTimeout);
extern INT32 netapp_ping_send(UINT32 *ip, UINT32 ulPingAttempts, UINT32 ulPingSize, UINT32 ulPingTimeout);
#endif
//*****************************************************************************
@@ -215,15 +216,15 @@ extern long netapp_ping_send(unsigned long *ip, unsigned long ulPingAttempts, un
//!
//! @param none
//!
//! @return On success, zero is returned. On error, -1 is returned.
//! @return On success, zero is returned. On error, -1 is returned.
//!
//! @brief Stop any ping request.
//!
//!
//!
//*****************************************************************************
#ifndef CC3000_TINY_DRIVER
extern long netapp_ping_stop();
extern INT32 netapp_ping_stop();
#endif
//*****************************************************************************
//
@@ -233,7 +234,7 @@ extern long netapp_ping_stop();
//!
//! @return none
//!
//! @brief Request for ping status. This API triggers the CC3000 to send
//! @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
@@ -242,8 +243,8 @@ extern long netapp_ping_stop();
//! 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
//!
//! @note When a ping operation is not active, the returned structure
//! fields are 0.
//!
//*****************************************************************************
@@ -256,7 +257,7 @@ extern void netapp_ping_report();
//
//! netapp_ipconfig
//!
//! @param[out] ipconfig This argument is a pointer to a
//! @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,
@@ -271,7 +272,7 @@ extern void netapp_ping_report();
//! 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.
@@ -294,7 +295,7 @@ extern void netapp_ipconfig( tNetappIpconfigRetArgs * ipconfig );
//*****************************************************************************
#ifndef CC3000_TINY_DRIVER
extern long netapp_arp_flush();
extern INT32 netapp_arp_flush();
#endif
@@ -318,7 +319,7 @@ extern long netapp_arp_flush();
#ifndef CC3000_TINY_DRIVER
long netapp_set_debug_level(unsigned long ulLevel);
INT32 netapp_set_debug_level(UINT32 ulLevel);
#endif
//*****************************************************************************
//
@@ -338,5 +339,5 @@ long netapp_set_debug_level(unsigned long ulLevel);
}
#endif // __cplusplus
#endif // __NETAPP_H__
#endif // __CC3000_NETAPP_H__

View File

@@ -12,28 +12,28 @@
*
* 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
* 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
* 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
* 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
* 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 __NVRAM_H__
#define __NVRAM_H__
#ifndef __CC3000_NVRAM_H__
#define __CC3000_NVRAM_H__
#include "cc3000_common.h"
@@ -59,7 +59,7 @@ extern "C" {
/****************************************************************************
**
** Definitions for File IDs
**
**
****************************************************************************/
/* NVMEM file ID - system files*/
#define NVMEM_NVS_FILEID (0)
@@ -95,19 +95,19 @@ extern "C" {
//! 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 ulLength number of bytes to read
//! @param ulOffset ulOffset in file from where to read
//! @param buff output buffer pointer
//!
//! @return number of bytes read, otherwise error.
//! @return on success 0, error otherwise.
//!
//! @brief Reads data from the file referred by the ulFileId parameter.
//! @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.
//!
//! be used, is invalid, or if the read is out of bounds.
//!
//*****************************************************************************
extern signed long nvmem_read(unsigned long file_id, unsigned long length, unsigned long offset, unsigned char *buff);
extern INT32 nvmem_read(UINT32 file_id, UINT32 length, UINT32 offset, UINT8 *buff);
//*****************************************************************************
//
@@ -117,21 +117,21 @@ extern signed long nvmem_read(unsigned long file_id, unsigned long length, unsig
//! 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 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
//! 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 signed long nvmem_write(unsigned long ulFileId, unsigned long ulLength, unsigned long ulEntryOffset, unsigned char *buff);
extern INT32 nvmem_write(UINT32 ulFileId, UINT32 ulLength, UINT32 ulEntryOffset, UINT8 *buff);
//*****************************************************************************
@@ -142,26 +142,26 @@ extern signed long nvmem_write(unsigned long ulFileId, unsigned long ulLength, u
//!
//! @return on success 0, error otherwise.
//!
//! @brief Write MAC address to EEPROM.
//! @brief Write MAC address to EEPROM.
//! mac address as appears over the air (OUI first)
//!
//!
//*****************************************************************************
extern unsigned char nvmem_set_mac_address(unsigned char *mac);
extern UINT8 nvmem_set_mac_address(UINT8 *mac);
//*****************************************************************************
//
//! nvmem_get_mac_address
//!
//! @param[out] mac mac address
//! @param[out] mac mac address
//!
//! @return on success 0, error otherwise.
//!
//! @brief Read MAC address from EEPROM.
//! @brief Read MAC address from EEPROM.
//! mac address as appears over the air (OUI first)
//!
//!
//*****************************************************************************
extern unsigned char nvmem_get_mac_address(unsigned char *mac);
extern UINT8 nvmem_get_mac_address(UINT8 *mac);
//*****************************************************************************
@@ -170,35 +170,35 @@ extern unsigned char nvmem_get_mac_address(unsigned char *mac);
//!
//! @param ulFileId nvmem file id:\n
//! NVMEM_WLAN_DRIVER_SP_FILEID, NVMEM_WLAN_FW_SP_FILEID,
//! @param spLength number of bytes to write
//! @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.
//! @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
//! Each line is SP_PORTION_SIZE bytes long. Actual programming is
//! applied in SP_PORTION_SIZE bytes portions.
//!
//!
//*****************************************************************************
extern unsigned char nvmem_write_patch(unsigned long ulFileId, unsigned long spLength, const unsigned char *spData);
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
//! @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,
//! @brief Read patch version. read package version (WiFi FW patch,
//! driver-supplicant-NS patch, bootloader patch)
//!
//!
//*****************************************************************************
#ifndef CC3000_TINY_DRIVER
extern unsigned char nvmem_read_sp_version(unsigned char* patchVer);
#ifndef CC3000_TINY_DRIVER
extern UINT8 nvmem_read_sp_version(UINT8* patchVer);
#endif
//*****************************************************************************
@@ -209,21 +209,21 @@ extern unsigned char nvmem_read_sp_version(unsigned char* patchVer);
//! * NVMEM_AES128_KEY_FILEID: 12
//! * NVMEM_SHARED_MEM_FILEID: 13
//! * and fileIDs 14 and 15
//! @param ulNewLen entry ulLength
//! @param ulNewLen entry ulLength
//!
//! @return on success 0, error otherwise.
//!
//! @brief Create new file entry and allocate space on the NVMEM.
//! @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
//! 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 -
//! To just mark the file as invalid without resizing -
//! set ulNewLen=0.
//!
//!
//*****************************************************************************
extern signed long nvmem_create_entry(unsigned long file_id, unsigned long newlen);
extern INT32 nvmem_create_entry(UINT32 file_id, UINT32 newlen);
//*****************************************************************************
@@ -245,4 +245,4 @@ extern signed long nvmem_create_entry(unsigned long file_id, unsigned long newle
}
#endif // __cplusplus
#endif // __NVRAM_H__
#endif // __CC3000_NVRAM_H__

View File

@@ -0,0 +1,11 @@
#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__

View File

@@ -12,28 +12,28 @@
*
* 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
* 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
* 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
* 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
* 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 __SECURITY__
#define __SECURITY__
#ifndef __CC3000_SECURITY__
#define __CC3000_SECURITY__
#include "nvmem.h"
@@ -64,12 +64,12 @@ extern "C" {
//!
//! @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).
//!
//! is computed. The AES implementation is in mode ECB (Electronic
//! Code Book).
//!
//!
//*****************************************************************************
extern void aes_encrypt(unsigned char *state, unsigned char *key);
extern void aes_encrypt(UINT8 *state, UINT8 *key);
//*****************************************************************************
//
@@ -82,12 +82,12 @@ extern void aes_encrypt(unsigned char *state, unsigned char *key);
//!
//! @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
//! is computed The AES implementation is in mode ECB
//! (Electronic Code Book).
//!
//!
//!
//*****************************************************************************
extern void aes_decrypt(unsigned char *state, unsigned char *key);
extern void aes_decrypt(UINT8 *state, UINT8 *key);
//*****************************************************************************
@@ -100,11 +100,11 @@ extern void aes_decrypt(unsigned char *state, unsigned char *key);
//!
//! @brief Reads AES128 key from EEPROM
//! Reads the AES128 key from fileID #12 in EEPROM
//! returns an error if the key does not exist.
//!
//! returns an error if the key does not exist.
//!
//!
//*****************************************************************************
extern signed long aes_read_key(unsigned char *key);
extern INT32 aes_read_key(UINT8 *key);
//*****************************************************************************
//
@@ -116,18 +116,13 @@ extern signed long aes_read_key(unsigned char *key);
//!
//! @brief writes AES128 key from EEPROM
//! Writes the AES128 key to fileID #12 in EEPROM
//!
//!
//!
//*****************************************************************************
extern signed long aes_write_key(unsigned char *key);
extern INT32 aes_write_key(UINT8 *key);
#endif //CC3000_UNENCRYPTED_SMART_CONFIG
//*****************************************************************************
//
// Mark the end of the C bindings section for C++ compilers.
//
//*****************************************************************************
#ifdef __cplusplus
}
#endif // __cplusplus

View File

@@ -12,29 +12,30 @@
*
* 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
* 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
* 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
* 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
* 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 __SOCKET_H__
#define __SOCKET_H__
#ifndef __CC3000_SOCKET_H__
#define __CC3000_SOCKET_H__
#include "cc3000_common.h"
//*****************************************************************************
//
@@ -83,7 +84,7 @@ extern "C" {
//----------- Socket retunr codes -----------
#define SOC_ERROR (-1) // error
#define SOC_ERROR (-1) // error
#define SOC_IN_PROGRESS (-2) // socket in progress
//----------- Socket Options -----------
@@ -91,7 +92,7 @@ extern "C" {
#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_ON 0 // socket non-blocking mode is enabled
#define SOCK_OFF 1 // socket blocking mode is enabled
#define MAX_PACKET_SIZE 1500
@@ -99,51 +100,44 @@ extern "C" {
#define IOCTL_SOCKET_EVENTMASK
#ifdef ENOBUFS
#undef ENOBUFS
#endif
#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
{
unsigned long s_addr; // load with inet_aton()
UINT32 s_addr; // load with inet_aton()
} in_addr;
typedef struct _sockaddr_t
{
unsigned short int sa_family;
unsigned char sa_data[14];
UINT16 sa_family;
UINT8 sa_data[14];
} sockaddr;
typedef struct _sockaddr_in_t
{
short sin_family; // e.g. AF_INET
unsigned short sin_port; // e.g. htons(3490)
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
CHAR sin_zero[8]; // zero this if you want to
} sockaddr_in;
typedef unsigned long socklen_t;
typedef UINT32 socklen_t;
// The fd_set member is required to be an array of longs.
typedef long int __fd_mask;
// 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))
#ifdef fd_set
#undef fd_set // for compatibility with newlib, which defines fd_set
#endif
// fd_set for select and pselect.
typedef struct
{
@@ -155,7 +149,7 @@ typedef struct
// the array isn't too big.
#define __FD_ZERO(set) \
do { \
unsigned int __i; \
UINT16 __i; \
fd_set *__arr = (set); \
for (__i = 0; __i < sizeof (fd_set) / sizeof (__fd_mask); ++__i) \
__FDS_BITS (__arr)[__i] = 0; \
@@ -165,46 +159,34 @@ typedef struct
#define __FD_ISSET(d, set) (__FDS_BITS (set)[__FDELT (d)] & __FDMASK (d))
// Access macros for 'fd_set'.
#ifdef FD_SET
#undef FD_SET
#endif
#ifdef FD_CLR
#undef FD_CLR
#endif
#ifdef FD_ISSET
#undef FD_ISSET
#endif
#ifdef FD_ZERO
#undef FD_ZERO
#endif
#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) ((((unsigned long)(A) & 0xff000000) >> 24) | \
(((unsigned long)(A) & 0x00ff0000) >> 8) | \
(((unsigned long)(A) & 0x0000ff00) << 8) | \
(((unsigned long)(A) & 0x000000ff) << 24))
#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) ((((unsigned long)(A) & 0xff00) >> 8) | \
(((unsigned long)(A) & 0x00ff) << 8))
#define htons(A) ((((UINT32)(A) & 0xff00) >> 8) | \
(((UINT32)(A) & 0x00ff) << 8))
#define ntohs htons
// mDNS port - 5353 mDNS multicast address - 224.0.0.251
// 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;
sockaddr.sa_data[5] = 0xfb;
//*****************************************************************************
@@ -217,24 +199,24 @@ typedef struct
//
//! socket
//!
//! @param domain selects the protocol family which will be used for
//! @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
//! @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
//! @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
//! @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
//! 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 int socket(long domain, long type, long protocol);
extern INT16 CC3000_EXPORT(socket)(INT32 domain, INT32 type, INT32 protocol);
//*****************************************************************************
//
@@ -247,21 +229,21 @@ extern int socket(long domain, long type, long protocol);
//! @brief The socket function closes a created socket.
//
//*****************************************************************************
extern long closesocket(long sd);
extern INT32 CC3000_EXPORT(closesocket)(INT32 sd);
//*****************************************************************************
//
//! accept
//!
//! @param[in] sd socket descriptor (handle)
//! @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.
//! 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:
//! @param[out] addrlen the addrlen argument is a value-result argument:
//! it should initially contain the size of the structure
//! pointed to by addr.
//!
@@ -273,34 +255,34 @@ extern long closesocket(long sd);
//! - 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
//! 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 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
//! 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
//! 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
//! pointed to by addr, on return it will contain the actual
//! length (in bytes) of the address returned.
//!
//! @sa socket ; bind ; listen
//
//*****************************************************************************
extern long accept(long sd, sockaddr *addr, socklen_t *addrlen);
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
//! @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.
//!
@@ -308,8 +290,8 @@ extern long accept(long sd, sockaddr *addr, socklen_t *addrlen);
//!
//! @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
//! 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.
@@ -317,13 +299,13 @@ extern long accept(long sd, sockaddr *addr, socklen_t *addrlen);
//! @sa socket ; accept ; listen
//
//*****************************************************************************
extern long bind(long sd, const sockaddr *addr, long addrlen);
extern INT32 CC3000_EXPORT(bind)(INT32 sd, const sockaddr *addr, INT32 addrlen);
//*****************************************************************************
//
//! listen
//!
//! @param[in] sd socket descriptor (handle)
//! @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.
@@ -334,35 +316,35 @@ extern long bind(long sd, const sockaddr *addr, long addrlen);
//! 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.
//! pending connections may grow to.
//!
//! @sa socket ; accept ; bind
//!
//! @note On this version, backlog is not supported
//
//*****************************************************************************
extern long listen(long sd, long backlog);
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.
//! @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,
//! @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 int gethostbyname(const char* hostname, unsigned short usNameLen, unsigned long* out_ip_addr);
#ifndef CC3000_TINY_DRIVER
extern INT16 CC3000_EXPORT(gethostbyname)(CHAR * hostname, UINT16 usNameLen, UINT32* out_ip_addr);
#endif
@@ -370,43 +352,43 @@ extern int gethostbyname(const char* hostname, unsigned short usNameLen, unsigne
//
//! connect
//!
//! @param[in] sd socket descriptor (handle)
//! @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
//! @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
//! @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
//! 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
//! 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 long connect(long sd, const sockaddr *addr, long addrlen);
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.
//! three sets, plus 1.
//! @param[out] writesds socket descriptors list for write monitoring
//! @param[out] readsds socket descriptors list for read 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
//! before select() returns. Null means infinity
//! timeout. The minimum timeout is 5 milliseconds,
//! less than 5 milliseconds will be set
//! automatically to 5 milliseconds.
@@ -418,14 +400,14 @@ extern long connect(long sd, const sockaddr *addr, long addrlen);
//! 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
//! *writesds - return the sockets on which Write request
//! will return without delay.
//! *exceptsds - return the sockets which closed recently.
//!
//! @brief Monitor socket activity
//! @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
//! 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
@@ -433,7 +415,7 @@ extern long connect(long sd, const sockaddr *addr, long addrlen);
//! @sa socket
//
//*****************************************************************************
extern int select(long nfds, fd_set *readsds, fd_set *writesds,
extern INT16 CC3000_EXPORT(select)(INT32 nfds, fd_set *readsds, fd_set *writesds,
fd_set *exceptsds, struct timeval *timeout);
//*****************************************************************************
@@ -451,39 +433,39 @@ extern int select(long nfds, fd_set *readsds, fd_set *writesds,
//! 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 -
//! 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
//! 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
//! SOCKOPT_RECV_TIMEOUT configures recv and recvfrom timeout
//! in milliseconds.
//! In that case optval should be pointer to unsigned long.
//! 2. SOCKOPT_NONBLOCK (optname). sets the socket non-blocking mode on
//! 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 int setsockopt(long sd, long level, long optname, const void *optval,
#ifndef CC3000_TINY_DRIVER
extern INT16 CC3000_EXPORT(setsockopt)(INT32 sd, INT32 level, INT32 optname, const void *optval,
socklen_t optlen);
#endif
//*****************************************************************************
@@ -501,38 +483,38 @@ extern int setsockopt(long sd, long level, long optname, const void *optval,
//! 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 -
//! 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
//! 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
//! SOCKOPT_RECV_TIMEOUT configures recv and recvfrom timeout
//! in milliseconds.
//! In that case optval should be pointer to unsigned long.
//! 2. SOCKOPT_NONBLOCK (optname). sets the socket non-blocking mode on
//! 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 int getsockopt(long sd, long level, long optname, void *optval,
extern INT16 CC3000_EXPORT(getsockopt)(INT32 sd, INT32 level, INT32 optname, void *optval,
socklen_t *optlen);
//*****************************************************************************
@@ -541,9 +523,9 @@ extern int getsockopt(long sd, long level, long optname, void *optval,
//!
//! @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
//! @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.
//! @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
@@ -556,7 +538,7 @@ extern int getsockopt(long sd, long level, long optname, void *optval,
//! @Note On this version, only blocking mode is supported.
//
//*****************************************************************************
extern int recv(long sd, void *buf, long len, long flags);
extern INT16 CC3000_EXPORT(recv)(INT32 sd, void *buf, INT32 len, INT32 flags);
//*****************************************************************************
//
@@ -564,9 +546,9 @@ extern int recv(long sd, void *buf, long len, long flags);
//!
//! @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
//! @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.
//! @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
@@ -586,7 +568,7 @@ extern int recv(long sd, void *buf, long len, long flags);
//! @Note On this version, only blocking mode is supported.
//
//*****************************************************************************
extern int recvfrom(long sd, void *buf, long len, long flags, sockaddr *from,
extern INT16 CC3000_EXPORT(recvfrom)(INT32 sd, void *buf, INT32 len, INT32 flags, sockaddr *from,
socklen_t *fromlen);
//*****************************************************************************
@@ -602,7 +584,7 @@ extern int recvfrom(long sd, void *buf, long len, long flags, sockaddr *from,
//! error occurred
//!
//! @brief Write data to TCP socket
//! This function is used to transmit a message to another
//! This function is used to transmit a message to another
//! socket.
//!
//! @Note On this version, only blocking mode is supported.
@@ -611,7 +593,7 @@ extern int recvfrom(long sd, void *buf, long len, long flags, sockaddr *from,
//
//*****************************************************************************
extern int send(long sd, const void *buf, long len, long flags);
extern INT16 CC3000_EXPORT(send)(INT32 sd, const void *buf, INT32 len, INT32 flags);
//*****************************************************************************
//
@@ -630,7 +612,7 @@ extern int send(long sd, const void *buf, long len, long flags);
//! error occurred
//!
//! @brief Write data to TCP socket
//! This function is used to transmit a message to another
//! This function is used to transmit a message to another
//! socket.
//!
//! @Note On this version, only blocking mode is supported.
@@ -639,7 +621,7 @@ extern int send(long sd, const void *buf, long len, long flags);
//
//*****************************************************************************
extern int sendto(long sd, const void *buf, long len, long flags,
extern INT16 CC3000_EXPORT(sendto)(INT32 sd, const void *buf, INT32 len, INT32 flags,
const sockaddr *to, socklen_t tolen);
//*****************************************************************************
@@ -649,16 +631,30 @@ extern int sendto(long sd, const void *buf, long len, long flags,
//! @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
//! @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
//! @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 int mdnsAdvertiser(unsigned short mdnsEnabled, char * deviceServiceName, unsigned short deviceServiceNameLength);
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);
//*****************************************************************************
//

View File

@@ -12,28 +12,28 @@
*
* 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
* 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
* 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
* 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
* 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 __WLAN_H__
#define __WLAN_H__
#ifndef __CC3000_WLAN_H__
#define __CC3000_WLAN_H__
#include "cc3000_common.h"
@@ -63,41 +63,41 @@ extern "C" {
//
//! wlan_init
//!
//! @param sWlanCB Asynchronous events callback.
//! @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_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,
//! 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,
//! 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 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
//! @param sReadWlanInterruptPin init callback. the callback read wlan
//! interrupt status.
//! @param sWlanInterruptEnable init callback. the callback enable wlan
//! @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.
//! @param sWriteWlanPin init callback. the callback write value
//! to device pin.
//!
//! @return none
//!
//! @sa wlan_set_event_mask , wlan_start , wlan_stop
//! @sa wlan_set_event_mask , wlan_start , wlan_stop
//!
//! @brief Initialize wlan driver
//!
@@ -120,28 +120,28 @@ extern void wlan_init( tWlanCB sWlanCB,
//! wlan_start
//!
//! @param usPatchesAvailableAtHost - flag to indicate if patches available
//! from host or from EEPROM. Due to the
//! from host or from EEPROM. Due to the
//! fact the patches are burn to the EEPROM
//! using the patch programmer utility, the
//! 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
//! @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)
//! 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
//! @Warning This function must be called after wlan_init and before any
//! other wlan API
//! @sa wlan_init , wlan_stop
//!
//
//*****************************************************************************
extern void wlan_start(unsigned short usPatchesAvailableAtHost);
extern int wlan_start(UINT16 usPatchesAvailableAtHost);
//*****************************************************************************
//
@@ -163,23 +163,23 @@ extern void wlan_stop(void);
//! wlan_connect
//!
//! @param sec_type security options:
//! WLAN_SEC_UNSEC,
//! 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
//! @param key_len key length
//!
//! @return On success, zero is returned. On error, negative is returned.
//! @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
//! 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
//! 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
@@ -189,10 +189,10 @@ extern void wlan_stop(void);
//
//*****************************************************************************
#ifndef CC3000_TINY_DRIVER
extern long wlan_connect(unsigned long ulSecType, const char *ssid, long ssid_len,
unsigned char *bssid, unsigned char *key, long key_len);
extern INT32 wlan_connect(UINT32 ulSecType, CHAR *ssid, INT32 ssid_len,
UINT8 *bssid, UINT8 *key, INT32 key_len);
#else
extern long wlan_connect(const char *ssid, long ssid_len);
extern INT32 wlan_connect(CHAR *ssid, INT32 ssid_len);
#endif
@@ -200,15 +200,15 @@ extern long wlan_connect(const char *ssid, long ssid_len);
//
//! wlan_disconnect
//!
//! @return 0 disconnected done, other CC3000 already disconnected
//! @return 0 disconnected done, other CC3000 already disconnected
//!
//! @brief Disconnect connection from AP.
//! @brief Disconnect connection from AP.
//!
//! @sa wlan_connect
//
//*****************************************************************************
extern long wlan_disconnect(void);
extern INT32 wlan_disconnect(void);
//*****************************************************************************
//
@@ -221,32 +221,33 @@ extern long wlan_disconnect(void);
//! @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 ulKeyMgmt KEY management
//! @param ucPf_OrKey security key
//! @param ulPassPhraseLen security key length for WPA\WPA2
//!
//! @return On success, zero is returned. On error, -1 is returned
//! @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
//! 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
//! @sa wlan_ioctl_del_profile
//
//*****************************************************************************
extern long wlan_add_profile(unsigned long ulSecType, unsigned char* ucSsid,
unsigned long ulSsidLen,
unsigned char *ucBssid,
unsigned long ulPriority,
unsigned long ulPairwiseCipher_Or_Key,
unsigned long ulGroupCipher_TxKeyLen,
unsigned long ulKeyMgmt,
unsigned char* ucPf_OrKey,
unsigned long ulPassPhraseLen);
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);
@@ -256,16 +257,16 @@ extern long wlan_add_profile(unsigned long ulSecType, unsigned char* ucSsid,
//!
//! @param index number of profile to delete
//!
//! @return On success, zero is returned. On error, -1 is returned
//! @return On success, zero is returned. On error, -1 is returned
//!
//! @brief Delete WLAN profile
//! @brief Delete WLAN profile
//!
//! @Note In order to delete all stored profile, set index to 255.
//!
//! @sa wlan_add_profile
//! @sa wlan_add_profile
//
//*****************************************************************************
extern long wlan_ioctl_del_profile(unsigned long ulIndex);
extern INT32 wlan_ioctl_del_profile(UINT32 ulIndex);
//*****************************************************************************
//
@@ -282,64 +283,64 @@ extern long wlan_ioctl_del_profile(unsigned long ulIndex);
//! HCI_EVNT_WLAN_TX_COMPLETE - disable information on end of transmission
//! Saved: no.
//!
//! @return On success, zero is returned. On error, -1 is returned
//! @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.
//! @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 long wlan_set_event_mask(unsigned long ulMask);
extern INT32 wlan_set_event_mask(UINT32 ulMask);
//*****************************************************************************
//
//! wlan_ioctl_statusget
//!
//! @param none
//! @param none
//!
//! @return WLAN_STATUS_DISCONNECTED, WLAN_STATUS_SCANING,
//! STATUS_CONNECTING or WLAN_STATUS_CONNECTED
//! @return WLAN_STATUS_DISCONNECTED, WLAN_STATUS_SCANING,
//! STATUS_CONNECTING or WLAN_STATUS_CONNECTED
//!
//! @brief get wlan status: disconnected, scanning, connecting or connected
//
//*****************************************************************************
extern long wlan_ioctl_statusget(void);
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
//! @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
//! @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
//! @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
//! @return On success, zero is returned. On error, -1 is returned
//!
//! @brief When auto is enabled, the device tries to connect according
//! @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
//! 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
//! 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
//! @sa wlan_add_profile , wlan_ioctl_del_profile
//
//*****************************************************************************
extern long wlan_ioctl_set_connection_policy(
unsigned long should_connect_to_open_ap,
unsigned long should_use_fast_connect,
unsigned long ulUseProfiles);
extern INT32 wlan_ioctl_set_connection_policy(
UINT32 should_connect_to_open_ap,
UINT32 should_use_fast_connect,
UINT32 ulUseProfiles);
//*****************************************************************************
//
@@ -348,94 +349,94 @@ extern long wlan_ioctl_set_connection_policy(
//! @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
//! @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:
//! 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;
//! - 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
//! - 2 bytes: the time at which the entry has entered into
//! scans result table
//! - 32 bytes: SSID name
//! - 6 bytes: BSSID
//! - 6 bytes: BSSID
//!
//! @Note scan_timeout, is not supported on this version.
//!
//! @sa wlan_ioctl_set_scan_params
//! @sa wlan_ioctl_set_scan_params
//
//*****************************************************************************
extern long wlan_ioctl_get_scan_results(unsigned long ulScanTimeout,
unsigned char *ucResults);
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
//! @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
//! @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.
//! @param uiNumOfProbeRequests max probe request between dwell time.
//! Saved: yes. Recommended Value: 5 (Default:2)
//! @param uiChannelMask bitwise, up to 13 channels (0x1fff).
//! @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 (unsigned long) holds timeout between periodic scan
//! @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
//! @return On success, zero is returned. On error, -1 is returned
//!
//! @brief start and stop scan procedure. Set scan parameters.
//! @brief start and stop scan procedure. Set scan parameters.
//!
//! @Note uiDefaultTxPower, is not supported on this version.
//!
//! @sa wlan_ioctl_get_scan_results
//! @sa wlan_ioctl_get_scan_results
//
//*****************************************************************************
extern long wlan_ioctl_set_scan_params(unsigned long uiEnable, unsigned long
uiMinDwellTime,unsigned long uiMaxDwellTime,
unsigned long uiNumOfProbeRequests,
unsigned long uiChannelMask,
long iRSSIThreshold,unsigned long uiSNRThreshold,
unsigned long uiDefaultTxPower,
unsigned long *aiIntervalList);
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
//! @return On success, zero is returned. On error, -1 is returned
//!
//! @brief Start to acquire device profile. The device acquire its own
//! @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
//! 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
@@ -443,8 +444,8 @@ extern long wlan_ioctl_set_scan_params(unsigned long uiEnable, unsigned long
//!
//! @sa wlan_smart_config_set_prefix , wlan_smart_config_stop
//
//*****************************************************************************
extern long wlan_smart_config_start(unsigned long algoEncryptedFlag);
//*****************************************************************************
extern INT32 wlan_smart_config_start(UINT32 algoEncryptedFlag);
//*****************************************************************************
@@ -453,24 +454,24 @@ extern long wlan_smart_config_start(unsigned long algoEncryptedFlag);
//!
//! @param algoEncryptedFlag indicates whether the information is encrypted
//!
//! @return On success, zero is returned. On error, -1 is returned
//! @return On success, zero is returned. On error, -1 is returned
//!
//! @brief Stop the acquire profile procedure
//! @brief Stop the acquire profile procedure
//!
//! @sa wlan_smart_config_start , wlan_smart_config_set_prefix
//
//*****************************************************************************
extern long wlan_smart_config_stop(void);
extern INT32 wlan_smart_config_stop(void);
//*****************************************************************************
//
//! wlan_smart_config_set_prefix
//!
//! @param newPrefix 3 bytes identify the SSID prefix for the Smart Config.
//! @param newPrefix 3 bytes identify the SSID prefix for the Smart Config.
//!
//! @return On success, zero is returned. On error, -1 is returned
//! @return On success, zero is returned. On error, -1 is returned
//!
//! @brief Configure station ssid prefix. The prefix is used internally
//! @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
@@ -478,23 +479,23 @@ extern long wlan_smart_config_stop(void);
//! @sa wlan_smart_config_start , wlan_smart_config_stop
//
//*****************************************************************************
extern long wlan_smart_config_set_prefix(char* cNewPrefix);
extern INT32 wlan_smart_config_set_prefix(CHAR* cNewPrefix);
//*****************************************************************************
//
//! wlan_smart_config_process
//!
//! @param none
//! @param none
//!
//! @return On success, zero is returned. On error, -1 is returned
//! @return On success, zero is returned. On error, -1 is returned
//!
//! @brief process the acquired data and store it as a profile. The acquired
//! @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 long wlan_smart_config_process(void);
extern INT32 wlan_smart_config_process(void);
//*****************************************************************************
//
@@ -514,4 +515,4 @@ extern long wlan_smart_config_process(void);
}
#endif // __cplusplus
#endif // __WLAN_H__
#endif // __CC3000_WLAN_H__

View File

@@ -12,23 +12,23 @@
*
* 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
* 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
* 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
* 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
* 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.
*
*****************************************************************************/
@@ -39,14 +39,10 @@
//
//*****************************************************************************
/******************************************************************************
*
* Include files
*
*****************************************************************************/
#include <stdint.h>
#include "mpconfigport.h"
#if MICROPY_HW_ENABLE_CC3K
*
* Include files
*
*****************************************************************************/
#include "cc3000_common.h"
#include "socket.h"
@@ -65,10 +61,9 @@
//! @brief stub function for ASSERT macro
//
//*****************************************************************************
void
__error__(char *pcFilename, unsigned long ulLine)
void __error__(CHAR *pcFilename, UINT32 ulLine)
{
//TODO full up function
//TODO full up function
}
@@ -87,12 +82,12 @@ __error__(char *pcFilename, unsigned long ulLine)
//
//*****************************************************************************
unsigned char* UINT32_TO_STREAM_f (unsigned char *p, unsigned long u32)
UINT8* UINT32_TO_STREAM_f (UINT8 *p, UINT32 u32)
{
*(p)++ = (unsigned char)(u32);
*(p)++ = (unsigned char)((u32) >> 8);
*(p)++ = (unsigned char)((u32) >> 16);
*(p)++ = (unsigned char)((u32) >> 24);
*(p)++ = (UINT8)(u32);
*(p)++ = (UINT8)((u32) >> 8);
*(p)++ = (UINT8)((u32) >> 16);
*(p)++ = (UINT8)((u32) >> 24);
return p;
}
@@ -110,10 +105,10 @@ unsigned char* UINT32_TO_STREAM_f (unsigned char *p, unsigned long u32)
//
//*****************************************************************************
unsigned char* UINT16_TO_STREAM_f (unsigned char *p, unsigned short u16)
UINT8* UINT16_TO_STREAM_f (UINT8 *p, UINT16 u16)
{
*(p)++ = (unsigned char)(u16);
*(p)++ = (unsigned char)((u16) >> 8);
*(p)++ = (UINT8)(u16);
*(p)++ = (UINT8)((u16) >> 8);
return p;
}
@@ -131,10 +126,10 @@ unsigned char* UINT16_TO_STREAM_f (unsigned char *p, unsigned short u16)
//
//*****************************************************************************
unsigned short STREAM_TO_UINT16_f(char* p, unsigned short offset)
UINT16 STREAM_TO_UINT16_f(CHAR* p, UINT16 offset)
{
return (unsigned short)((unsigned short)((unsigned short)
(*(p + offset + 1)) << 8) + (unsigned short)(*(p + offset)));
return (UINT16)((UINT16)((UINT16)
(*(p + offset + 1)) << 8) + (UINT16)(*(p + offset)));
}
//*****************************************************************************
@@ -151,12 +146,12 @@ unsigned short STREAM_TO_UINT16_f(char* p, unsigned short offset)
//
//*****************************************************************************
unsigned long STREAM_TO_UINT32_f(char* p, unsigned short offset)
UINT32 STREAM_TO_UINT32_f(CHAR* p, UINT16 offset)
{
return (unsigned long)((unsigned long)((unsigned long)
(*(p + offset + 3)) << 24) + (unsigned long)((unsigned long)
(*(p + offset + 2)) << 16) + (unsigned long)((unsigned long)
(*(p + offset + 1)) << 8) + (unsigned long)(*(p + offset)));
return (UINT32)((UINT32)((UINT32)
(*(p + offset + 3)) << 24) + (UINT32)((UINT32)
(*(p + offset + 2)) << 16) + (UINT32)((UINT32)
(*(p + offset + 1)) << 8) + (UINT32)(*(p + offset)));
}
@@ -167,5 +162,3 @@ unsigned long STREAM_TO_UINT32_f(char* p, unsigned short offset)
//! @}
//
//*****************************************************************************
#endif // MICROPY_HW_ENABLE_CC3K

460
drivers/cc3000/src/ccspi.c Normal file
View File

@@ -0,0 +1,460 @@
/*****************************************************************************
*
* 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 <string.h>
#include "stm32f4xx_hal.h"
#include "mpconfig.h"
#include "nlr.h"
#include "misc.h"
#include "qstr.h"
#include "obj.h"
#include "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 <stdio.h>
#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_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, NULL);
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);
}

View File

@@ -12,23 +12,23 @@
*
* 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
* 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
* 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
* 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
* 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.
*
*****************************************************************************/
@@ -43,11 +43,6 @@
// INCLUDE FILES
//******************************************************************************
#include <stdint.h>
#include "mpconfigport.h"
#if MICROPY_HW_ENABLE_CC3K
#include "cc3000_common.h"
#include "string.h"
#include "hci.h"
@@ -114,22 +109,22 @@
#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
//*****************************************************************************
unsigned long socket_active_status = SOCKET_STATUS_INIT_VAL;
UINT32 socket_active_status = SOCKET_STATUS_INIT_VAL;
//*****************************************************************************
// Prototypes for the static functions
//*****************************************************************************
static long hci_event_unsol_flowcontrol_handler(char *pEvent);
static INT32 hci_event_unsol_flowcontrol_handler(CHAR *pEvent);
static void update_socket_active_status(char *resp_params);
static void update_socket_active_status(CHAR *resp_params);
//*****************************************************************************
@@ -143,11 +138,11 @@ static void update_socket_active_status(char *resp_params);
//! @brief Handle unsolicited event from type patch request
//
//*****************************************************************************
void hci_unsol_handle_patch_request(char *event_hdr)
void hci_unsol_handle_patch_request(CHAR *event_hdr)
{
char *params = (char *)(event_hdr) + HCI_EVENT_HEADER_SIZE;
unsigned long ucLength = 0;
char *patch;
CHAR *params = (CHAR *)(event_hdr) + HCI_EVENT_HEADER_SIZE;
UINT32 ucLength = 0;
CHAR *patch;
switch (*params)
{
@@ -159,15 +154,15 @@ void hci_unsol_handle_patch_request(char *event_hdr)
if (patch)
{
hci_patch_send(HCI_EVENT_PATCHES_DRV_REQ,
tSLInformation.pucTxCommandBuffer, patch, ucLength);
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);
hci_patch_send(HCI_EVENT_PATCHES_DRV_REQ,
tSLInformation.pucTxCommandBuffer, 0, 0);
break;
case HCI_EVENT_PATCHES_FW_REQ:
@@ -179,15 +174,15 @@ void hci_unsol_handle_patch_request(char *event_hdr)
// Build and send a patch
if (patch)
{
hci_patch_send(HCI_EVENT_PATCHES_FW_REQ,
tSLInformation.pucTxCommandBuffer, patch, ucLength);
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);
hci_patch_send(HCI_EVENT_PATCHES_FW_REQ,
tSLInformation.pucTxCommandBuffer, 0, 0);
break;
case HCI_EVENT_PATCHES_BOOTLOAD_REQ:
@@ -198,15 +193,15 @@ void hci_unsol_handle_patch_request(char *event_hdr)
if (patch)
{
hci_patch_send(HCI_EVENT_PATCHES_BOOTLOAD_REQ,
tSLInformation.pucTxCommandBuffer, patch, ucLength);
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);
hci_patch_send(HCI_EVENT_PATCHES_BOOTLOAD_REQ,
tSLInformation.pucTxCommandBuffer, 0, 0);
break;
}
}
@@ -229,42 +224,45 @@ void hci_unsol_handle_patch_request(char *event_hdr)
//*****************************************************************************
unsigned char *
hci_event_handler(void *pRetParams, unsigned char *from, unsigned char *fromlen)
UINT8 * hci_event_handler(void *pRetParams, UINT8 *from, UINT8 *fromlen)
{
unsigned char *pucReceivedData, ucArgsize;
unsigned short usLength;
unsigned char *pucReceivedParams;
unsigned short usReceivedEventOpcode = 0;
unsigned long retValue32;
unsigned char * RecvParams;
unsigned char *RetParams;
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;
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)
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);
STREAM_TO_UINT8((CHAR *)pucReceivedParams, 0,
tSLInformation.usNumberOfFreeBuffers);
STREAM_TO_UINT16((CHAR *)pucReceivedParams, 1,
tSLInformation.usSlBufferLength);
}
break;
@@ -281,7 +279,8 @@ hci_event_handler(void *pRetParams, unsigned char *from, unsigned char *fromlen)
case HCI_NETAPP_PING_REPORT:
case HCI_EVNT_MDNS_ADVERTISE:
STREAM_TO_UINT8(pucReceivedData, HCI_EVENT_STATUS_OFFSET ,*(unsigned char *)pRetParams);
STREAM_TO_UINT8(pucReceivedData, HCI_EVENT_STATUS_OFFSET
,*(UINT8 *)pRetParams);
break;
case HCI_CMND_SETSOCKOPT:
@@ -303,49 +302,58 @@ hci_event_handler(void *pRetParams, unsigned char *from, unsigned char *fromlen)
case HCI_EVNT_CONNECT:
case HCI_EVNT_NVMEM_WRITE:
STREAM_TO_UINT32((char *)pucReceivedParams,0 ,*(unsigned long *)pRetParams);
STREAM_TO_UINT32((CHAR *)pucReceivedParams,0
,*(UINT32 *)pRetParams);
break;
case HCI_EVNT_READ_SP_VERSION:
STREAM_TO_UINT8(pucReceivedData, HCI_EVENT_STATUS_OFFSET ,*(unsigned char *)pRetParams);
pRetParams = ((char *)pRetParams) + 1;
STREAM_TO_UINT32((char *)pucReceivedParams, 0, retValue32);
UINT32_TO_STREAM((unsigned char *)pRetParams, retValue32);
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,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 4;
STREAM_TO_UINT32((char *)pucReceivedParams
,GET_HOST_BY_NAME_ADDR_OFFSET,*(unsigned long *)pRetParams);
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
,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 4;
STREAM_TO_UINT32((char *)pucReceivedParams
,ACCEPT_RETURN_STATUS_OFFSET,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 4;
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((unsigned char *)pRetParams,
pucReceivedParams + ACCEPT_ADDRESS__OFFSET, sizeof(sockaddr));
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 ,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 4;
STREAM_TO_UINT32((char *)pucReceivedParams,SL_RECEIVE_NUM_BYTES_OFFSET,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 4;
STREAM_TO_UINT32((char *)pucReceivedParams,SL_RECEIVE__FLAGS__OFFSET,*(unsigned long *)pRetParams);
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)
{
@@ -354,26 +362,26 @@ hci_event_handler(void *pRetParams, unsigned char *from, unsigned char *fromlen)
break;
}
case HCI_EVNT_SEND:
case HCI_EVNT_SEND:
case HCI_EVNT_SENDTO:
{
STREAM_TO_UINT32((char *)pucReceivedParams,SL_RECEIVE_SD_OFFSET ,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 4;
STREAM_TO_UINT32((char *)pucReceivedParams,SL_RECEIVE_NUM_BYTES_OFFSET,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 4;
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,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 4;
STREAM_TO_UINT32((char *)pucReceivedParams,SELECT_READFD_OFFSET,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 4;
STREAM_TO_UINT32((char *)pucReceivedParams,SELECT_WRITEFD_OFFSET,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 4;
STREAM_TO_UINT32((char *)pucReceivedParams,SELECT_EXFD_OFFSET,*(unsigned long *)pRetParams);
{
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;
}
@@ -381,20 +389,20 @@ hci_event_handler(void *pRetParams, unsigned char *from, unsigned char *fromlen)
STREAM_TO_UINT8(pucReceivedData, HCI_EVENT_STATUS_OFFSET,((tBsdGetSockOptReturnParams *)pRetParams)->iStatus);
//This argument returns in network order
memcpy((unsigned char *)pRetParams, pucReceivedParams, 4);
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,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 4;
STREAM_TO_UINT32((char *)pucReceivedParams,GET_SCAN_RESULTS_SCANRESULT_STATUS_OFFSET,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 4;
STREAM_TO_UINT16((char *)pucReceivedParams,GET_SCAN_RESULTS_ISVALID_TO_SSIDLEN_OFFSET,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 2;
STREAM_TO_UINT16((char *)pucReceivedParams,GET_SCAN_RESULTS_FRAME_TIME_OFFSET,*(unsigned long *)pRetParams);
pRetParams = ((char *)pRetParams) + 2;
memcpy((unsigned char *)pRetParams, (char *)(pucReceivedParams + GET_SCAN_RESULTS_FRAME_TIME_OFFSET + 2), GET_SCAN_RESULTS_SSID_MAC_LENGTH);
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:
@@ -414,21 +422,21 @@ hci_event_handler(void *pRetParams, unsigned char *from, unsigned char *fromlen)
STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_IP_LENGTH);
RecvParams += 4;
//Read DHCP server
//Read DHCP server
STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_IP_LENGTH);
RecvParams += 4;
//Read DNS server
//Read DNS server
STREAM_TO_STREAM(RecvParams,RetParams,NETAPP_IPCONFIG_IP_LENGTH);
RecvParams += 4;
//Read Mac address
//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);
break;
}
}
@@ -438,22 +446,22 @@ hci_event_handler(void *pRetParams, unsigned char *from, unsigned char *fromlen)
}
}
else
{
{
pucReceivedParams = pucReceivedData;
STREAM_TO_UINT8((char *)pucReceivedData, HCI_PACKET_ARGSIZE_OFFSET, ucArgsize);
STREAM_TO_UINT8((CHAR *)pucReceivedData, HCI_PACKET_ARGSIZE_OFFSET, ucArgsize);
STREAM_TO_UINT16((char *)pucReceivedData, HCI_PACKET_LENGTH_OFFSET, usLength);
STREAM_TO_UINT16((CHAR *)pucReceivedData, HCI_PACKET_LENGTH_OFFSET, usLength);
// Data received: note that the only case where from and from length
// 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, *(unsigned long *)fromlen);
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);
usLength - ucArgsize);
tSLInformation.usRxDataPending = 0;
}
@@ -462,18 +470,18 @@ hci_event_handler(void *pRetParams, unsigned char *from, unsigned char *fromlen)
SpiResumeSpi();
// Since we are going to TX - we need to handle this event after the
// 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))
(usReceivedEventOpcode == HCI_EVNT_PATCHES_REQ))
{
hci_unsol_handle_patch_request((char *)pucReceivedData);
hci_unsol_handle_patch_request((CHAR *)pucReceivedData);
}
if ((tSLInformation.usRxEventOpcode == 0) && (tSLInformation.usRxDataPending == 0))
{
return NULL;
}
}
}
}
@@ -491,13 +499,12 @@ hci_event_handler(void *pRetParams, unsigned char *from, unsigned char *fromlen)
//! @brief Handle unsolicited events
//
//*****************************************************************************
long
hci_unsol_event_handler(char *event_hdr)
INT32 hci_unsol_event_handler(CHAR *event_hdr)
{
char * data = NULL;
long event_type;
unsigned long NumberOfReleasedPackets;
unsigned long NumberOfSentPackets;
CHAR * data = NULL;
INT32 event_type;
UINT32 NumberOfReleasedPackets;
UINT32 NumberOfSentPackets;
STREAM_TO_UINT16(event_hdr, HCI_EVENT_OPCODE_OFFSET,event_type);
@@ -519,7 +526,7 @@ hci_unsol_event_handler(char *event_hdr)
{
tSLInformation.sWlanCB(HCI_EVENT_CC3000_CAN_SHUT_DOWN, NULL, 0);
}
}
}
return 1;
}
@@ -527,7 +534,7 @@ hci_unsol_event_handler(char *event_hdr)
}
if(event_type & HCI_EVNT_WLAN_UNSOL_BASE)
{
{
switch(event_type)
{
case HCI_EVNT_WLAN_KEEPALIVE:
@@ -544,10 +551,10 @@ hci_unsol_event_handler(char *event_hdr)
case HCI_EVNT_WLAN_UNSOL_DHCP:
{
unsigned char params[NETAPP_IPCONFIG_MAC_OFFSET + 1]; // extra byte is for the status
unsigned char *recParams = params;
UINT8 params[NETAPP_IPCONFIG_MAC_OFFSET + 1]; // extra byte is for the status
UINT8 *recParams = params;
data = (char*)(event_hdr) + HCI_EVENT_HEADER_SIZE;
data = (CHAR*)(event_hdr) + HCI_EVENT_HEADER_SIZE;
//Read IP address
STREAM_TO_STREAM(data,recParams,NETAPP_IPCONFIG_IP_LENGTH);
@@ -556,81 +563,81 @@ hci_unsol_event_handler(char *event_hdr)
STREAM_TO_STREAM(data,recParams,NETAPP_IPCONFIG_IP_LENGTH);
data += 4;
//Read default GW
STREAM_TO_STREAM(data,recParams,NETAPP_IPCONFIG_IP_LENGTH);
STREAM_TO_STREAM(data,recParams,NETAPP_IPCONFIG_IP_LENGTH);
data += 4;
//Read DHCP server
STREAM_TO_STREAM(data,recParams,NETAPP_IPCONFIG_IP_LENGTH);
//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 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));
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);
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 *)&params, sizeof(params));
tSLInformation.sWlanCB(event_type, (CHAR *)&params, sizeof(params));
}
}
break;
case HCI_EVNT_BSD_TCP_CLOSE_WAIT:
{
data = (char *)(event_hdr) + HCI_EVENT_HEADER_SIZE;
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
//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:
//'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))
|| (event_type == HCI_EVNT_WRITE))
{
char *pArg;
long status;
CHAR *pArg;
INT32 status;
pArg = M_BSD_RESP_PARAMS_OFFSET(event_hdr);
STREAM_TO_UINT32(pArg, BSD_RSP_PARAMS_STATUS_OFFSET,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));
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);
return (1);
}
else
return (0);
}
//handle a case where unsolicited event arrived, but was not handled by any of the cases above
@@ -650,29 +657,28 @@ hci_unsol_event_handler(char *event_hdr)
//!
//! @return ESUCCESS if successful, EFAIL if an error occurred
//!
//! @brief Parse the incoming unsolicited event packets and issues
//! @brief Parse the incoming unsolicited event packets and issues
//! corresponding event handler.
//
//*****************************************************************************
long
hci_unsolicited_event_handler(void)
INT32 hci_unsolicited_event_handler(void)
{
unsigned long res = 0;
unsigned char *pucReceivedData;
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)
if (hci_unsol_event_handler((CHAR *)pucReceivedData) == 1)
{
// There was an unsolicited event received - we can release the buffer
// and clean the event received
// and clean the event received
tSLInformation.usEventOrDataReceived = 0;
res = 1;
@@ -692,11 +698,11 @@ hci_unsolicited_event_handler(void)
//! @param Status
//! @return none
//!
//! @brief Check if the socket ID and status are valid and set
//! @brief Check if the socket ID and status are valid and set
//! accordingly the global socket status
//
//*****************************************************************************
void set_socket_active_status(long Sd, long Status)
void set_socket_active_status(INT32 Sd, INT32 Status)
{
if(M_IS_VALID_SD(Sd) && M_IS_VALID_STATUS(Status))
{
@@ -719,25 +725,24 @@ void set_socket_active_status(long Sd, long Status)
//! number of free buffer in the SL device.
//
//*****************************************************************************
long
hci_event_unsol_flowcontrol_handler(char *pEvent)
INT32 hci_event_unsol_flowcontrol_handler(CHAR *pEvent)
{
long temp, value;
unsigned short i;
unsigned short pusNumberOfHandles=0;
char *pReadPayload;
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));
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;
pReadPayload += FLOW_CONTROL_EVENT_SIZE;
}
tSLInformation.usNumberOfFreeBuffers += temp;
@@ -751,14 +756,13 @@ hci_event_unsol_flowcontrol_handler(char *pEvent)
//! get_socket_active_status
//!
//! @param Sd Socket IS
//! @return Current status of the socket.
//! @return Current status of the socket.
//!
//! @brief Retrieve socket status
//
//*****************************************************************************
long
get_socket_active_status(long Sd)
INT32 get_socket_active_status(INT32 Sd)
{
if(M_IS_VALID_SD(Sd))
{
@@ -772,15 +776,14 @@ get_socket_active_status(long Sd)
//! update_socket_active_status
//!
//! @param resp_params Socket IS
//! @return Current status of the socket.
//! @return Current status of the socket.
//!
//! @brief Retrieve socket status
//
//*****************************************************************************
void
update_socket_active_status(char *resp_params)
void update_socket_active_status(CHAR *resp_params)
{
long status, sd;
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);
@@ -806,10 +809,9 @@ update_socket_active_status(char *resp_params)
//
//*****************************************************************************
void
SimpleLinkWaitEvent(unsigned short usOpcode, void *pRetParams)
void SimpleLinkWaitEvent(UINT16 usOpcode, void *pRetParams)
{
// In the blocking implementation the control to caller will be returned only
// 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);
@@ -826,16 +828,14 @@ SimpleLinkWaitEvent(unsigned short usOpcode, void *pRetParams)
//! @return none
//!
//! @brief Wait for data, pass it to the hci_event_handler
//! and update in a global variable that there is
//! and update in a global variable that there is
//! data to read.
//
//*****************************************************************************
void
SimpleLinkWaitData(unsigned char *pBuf, unsigned char *from,
unsigned char *fromlen)
void SimpleLinkWaitData(UINT8 *pBuf, UINT8 *from, UINT8 *fromlen)
{
// In the blocking implementation the control to caller will be returned only
// 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);
@@ -847,5 +847,3 @@ SimpleLinkWaitData(unsigned char *pBuf, unsigned char *from,
//! @}
//
//*****************************************************************************
#endif // MICROPY_HW_ENABLE_CC3K

View File

@@ -12,23 +12,23 @@
*
* 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
* 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
* 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
* 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
* 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.
*
*****************************************************************************/
@@ -40,12 +40,7 @@
//
//*****************************************************************************
#include <stdint.h>
#include <string.h> // for memcpy
#include "mpconfigport.h"
#if MICROPY_HW_ENABLE_CC3K
#include <string.h>
#include "cc3000_common.h"
#include "hci.h"
#include "ccspi.h"
@@ -68,11 +63,9 @@
//! @brief Initiate an HCI command.
//
//*****************************************************************************
unsigned short
hci_command_send(unsigned short usOpcode, unsigned char *pucBuff,
unsigned char ucArgsLength)
{
unsigned char *stream;
UINT16 hci_command_send(UINT16 usOpcode, UINT8 *pucBuff, UINT8 ucArgsLength)
{
UINT8 *stream;
stream = (pucBuff + SPI_HEADER_SIZE);
@@ -101,15 +94,14 @@ hci_command_send(unsigned short usOpcode, unsigned char *pucBuff,
//! @brief Initiate an HCI data write operation
//
//*****************************************************************************
long
hci_data_send(unsigned char ucOpcode,
unsigned char *ucArgs,
unsigned short usArgsLength,
unsigned short usDataLength,
const unsigned char *ucTail,
unsigned short usTailLength)
INT32 hci_data_send(UINT8 ucOpcode,
UINT8 *ucArgs,
UINT16 usArgsLength,
UINT16 usDataLength,
const UINT8 *ucTail,
UINT16 usTailLength)
{
unsigned char *stream;
UINT8 *stream;
stream = ((ucArgs) + SPI_HEADER_SIZE);
@@ -139,10 +131,9 @@ hci_data_send(unsigned char ucOpcode,
//! @brief Prepeare HCI header and initiate an HCI data write operation
//
//*****************************************************************************
void hci_data_command_send(unsigned short usOpcode, unsigned char *pucBuff,
unsigned char ucArgsLength,unsigned short ucDataLength)
{
unsigned char *stream = (pucBuff + SPI_HEADER_SIZE);
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);
@@ -161,7 +152,7 @@ void hci_data_command_send(unsigned short usOpcode, unsigned char *pucBuff,
//!
//! @param usOpcode command operation code
//! @param pucBuff pointer to the command's arguments buffer
//! @param patch pointer to patch content buffer
//! @param patch pointer to patch content buffer
//! @param usDataLength data length
//!
//! @return none
@@ -169,12 +160,11 @@ void hci_data_command_send(unsigned short usOpcode, unsigned char *pucBuff,
//! @brief Prepeare HCI header and initiate an HCI patch write operation
//
//*****************************************************************************
void
hci_patch_send(unsigned char ucOpcode, unsigned char *pucBuff, char *patch, unsigned short usDataLength)
{
unsigned char *data_ptr = (pucBuff + SPI_HEADER_SIZE);
unsigned short usTransLength;
unsigned char *stream = (pucBuff + SPI_HEADER_SIZE);
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);
@@ -216,12 +206,12 @@ hci_patch_send(unsigned char ucOpcode, unsigned char *pucBuff, char *patch, unsi
usDataLength -= usTransLength;
}
*(unsigned short *)data_ptr = 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((unsigned char *)data_ptr, usTransLength + sizeof(usTransLength));
SpiWrite((UINT8 *)data_ptr, usTransLength + sizeof(usTransLength));
}
}
}
@@ -233,5 +223,3 @@ hci_patch_send(unsigned char ucOpcode, unsigned char *pucBuff, char *patch, unsi
//
//
//*****************************************************************************
#endif // MICROPY_HW_ENABLE_CC3K

View File

@@ -0,0 +1,196 @@
/*
* 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 <std.h>
#include <string.h>
#include "cc3000_common.h"
#include "socket.h"
#include "inet_ntop.h"
#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;
}
}

View File

@@ -0,0 +1,216 @@
/* 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 <string.h>
#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 */

View File

@@ -12,42 +12,39 @@
*
* 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
* 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
* 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
* 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
* 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 <stdint.h>
#include "mpconfigport.h"
#if MICROPY_HW_ENABLE_CC3K
#include <string.h>
#include "netapp.h"
#include "hci.h"
#include "socket.h"
#include "evnt_handler.h"
#include "nvmem.h"
#define MIN_TIMER_VAL_SECONDS 20
#define MIN_TIMER_VAL_SECONDS 10
#define MIN_TIMER_SET(t) if ((0 != t) && (t < MIN_TIMER_VAL_SECONDS)) \
{ \
t = MIN_TIMER_VAL_SECONDS; \
}
{ \
t = MIN_TIMER_VAL_SECONDS; \
}
#define NETAPP_DHCP_PARAMS_LEN (20)
@@ -60,17 +57,17 @@
//
//! netapp_config_mac_adrress
//!
//! @param mac device mac address, 6 bytes. Saved: yes
//! @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.
//! @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
//! be stored in CC3000 non volatile memory, thus preserved
//! over resets.
//
//*****************************************************************************
long netapp_config_mac_adrress(unsigned char * mac)
INT32 netapp_config_mac_adrress(UINT8 * mac)
{
return nvmem_set_mac_address(mac);
}
@@ -79,33 +76,33 @@ long netapp_config_mac_adrress(unsigned char * 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
//! @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,
//! @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.
//!
//! @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.
//!
//*****************************************************************************
long netapp_dhcp(unsigned long *aucIP, unsigned long *aucSubnetMask,unsigned long *aucDefaultGateway, unsigned long *aucDNSServer)
INT32 netapp_dhcp(UINT32 *aucIP, UINT32 *aucSubnetMask,UINT32 *aucDefaultGateway, UINT32 *aucDNSServer)
{
signed char scRet;
unsigned char *ptr;
unsigned char *args;
INT8 scRet;
UINT8 *ptr;
UINT8 *args;
scRet = EFAIL;
ptr = tSLInformation.pucTxCommandBuffer;
@@ -132,30 +129,30 @@ long netapp_dhcp(unsigned long *aucIP, unsigned long *aucSubnetMask,unsigned lon
//
//! netapp_timeout_values
//!
//! @param aucDHCP DHCP lease time request, also impact
//! @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 - 20 seconds.
//! The parameter is saved into the CC3000 NVMEM.
//! 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.
//! 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 - 20 seconds
//! The parameter is saved into the CC3000 NVMEM.
//! 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 - 20 sec
//! The parameter is saved into the CC3000 NVMEM.
//! 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
@@ -163,41 +160,40 @@ long netapp_dhcp(unsigned long *aucIP, unsigned long *aucSubnetMask,unsigned lon
//! 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 - 20 sec
//! The parameter is saved into the CC3000 NVMEM.
//! 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 20s,
//! it will be set automatically to 20s.
//! @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
long
netapp_timeout_values(unsigned long *aucDHCP, unsigned long *aucARP,unsigned long *aucKeepalive, unsigned long *aucInactivity)
INT32 netapp_timeout_values(UINT32 *aucDHCP, UINT32 *aucARP,UINT32 *aucKeepalive, UINT32 *aucInactivity)
{
signed char scRet;
unsigned char *ptr;
unsigned char *args;
INT8 scRet;
UINT8 *ptr;
UINT8 *args;
scRet = EFAIL;
ptr = tSLInformation.pucTxCommandBuffer;
args = (ptr + HEADERS_SIZE_CMD);
// Set minimal values of timers
// Set minimal values of timers
MIN_TIMER_SET(*aucDHCP)
MIN_TIMER_SET(*aucARP)
MIN_TIMER_SET(*aucKeepalive)
MIN_TIMER_SET(*aucInactivity)
MIN_TIMER_SET(*aucARP)
MIN_TIMER_SET(*aucKeepalive)
MIN_TIMER_SET(*aucInactivity)
// Fill in temporary command buffer
args = UINT32_TO_STREAM(args, *aucDHCP);
// 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);
@@ -219,27 +215,27 @@ netapp_timeout_values(unsigned long *aucDHCP, unsigned long *aucARP,unsigned lon
//!
//! @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 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
//! @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
//! @warning Calling this function while a previous Ping Requests are in
//! progress will stop the previous ping request.
//*****************************************************************************
#ifndef CC3000_TINY_DRIVER
long
netapp_ping_send(unsigned long *ip, unsigned long ulPingAttempts, unsigned long ulPingSize, unsigned long ulPingTimeout)
INT32
netapp_ping_send(UINT32 *ip, UINT32 ulPingAttempts, UINT32 ulPingSize, UINT32 ulPingTimeout)
{
signed char scRet;
unsigned char *ptr, *args;
INT8 scRet;
UINT8 *ptr, *args;
scRet = EFAIL;
ptr = tSLInformation.pucTxCommandBuffer;
@@ -269,7 +265,7 @@ netapp_ping_send(unsigned long *ip, unsigned long ulPingAttempts, unsigned long
//!
//! @return none
//!
//! @brief Request for ping status. This API triggers the CC3000 to send
//! @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
@@ -278,8 +274,8 @@ netapp_ping_send(unsigned long *ip, unsigned long ulPingAttempts, unsigned long
//! 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
//!
//! @note When a ping operation is not active, the returned structure
//! fields are 0.
//!
//*****************************************************************************
@@ -288,9 +284,9 @@ netapp_ping_send(unsigned long *ip, unsigned long ulPingAttempts, unsigned long
#ifndef CC3000_TINY_DRIVER
void netapp_ping_report()
{
unsigned char *ptr;
UINT8 *ptr;
ptr = tSLInformation.pucTxCommandBuffer;
signed char scRet;
INT8 scRet;
scRet = EFAIL;
@@ -298,7 +294,7 @@ void netapp_ping_report()
hci_command_send(HCI_NETAPP_PING_REPORT, ptr, 0);
// Wait for command complete event
SimpleLinkWaitEvent(HCI_NETAPP_PING_REPORT, &scRet);
SimpleLinkWaitEvent(HCI_NETAPP_PING_REPORT, &scRet);
}
#endif
@@ -308,18 +304,18 @@ void netapp_ping_report()
//!
//! @param none
//!
//! @return On success, zero is returned. On error, -1 is returned.
//! @return On success, zero is returned. On error, -1 is returned.
//!
//! @brief Stop any ping request.
//!
//!
//!
//*****************************************************************************
#ifndef CC3000_TINY_DRIVER
long netapp_ping_stop()
INT32 netapp_ping_stop()
{
signed char scRet;
unsigned char *ptr;
INT8 scRet;
UINT8 *ptr;
scRet = EFAIL;
ptr = tSLInformation.pucTxCommandBuffer;
@@ -338,7 +334,7 @@ long netapp_ping_stop()
//
//! netapp_ipconfig
//!
//! @param[out] ipconfig This argument is a pointer to a
//! @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,
@@ -353,7 +349,7 @@ long netapp_ping_stop()
//! 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.
@@ -363,7 +359,7 @@ long netapp_ping_stop()
#ifndef CC3000_TINY_DRIVER
void netapp_ipconfig( tNetappIpconfigRetArgs * ipconfig )
{
unsigned char *ptr;
UINT8 *ptr;
ptr = tSLInformation.pucTxCommandBuffer;
@@ -394,10 +390,10 @@ void netapp_ipconfig( tNetappIpconfigRetArgs * ipconfig )
//*****************************************************************************
#ifndef CC3000_TINY_DRIVER
long netapp_arp_flush(void)
INT32 netapp_arp_flush(void)
{
signed char scRet;
unsigned char *ptr;
INT8 scRet;
UINT8 *ptr;
scRet = EFAIL;
ptr = tSLInformation.pucTxCommandBuffer;
@@ -432,34 +428,32 @@ long netapp_arp_flush(void)
#ifndef CC3000_TINY_DRIVER
long netapp_set_debug_level(unsigned long ulLevel)
INT32 netapp_set_debug_level(UINT32 ulLevel)
{
signed char scRet;
unsigned char *ptr, *args;
INT8 scRet;
UINT8 *ptr, *args;
scRet = EFAIL;
ptr = tSLInformation.pucTxCommandBuffer;
args = (ptr + HEADERS_SIZE_CMD);
scRet = EFAIL;
ptr = tSLInformation.pucTxCommandBuffer;
args = (ptr + HEADERS_SIZE_CMD);
//
// Fill in temporary command buffer
//
args = UINT32_TO_STREAM(args, ulLevel);
//
// 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);
//
// 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);
return(scRet);
}
#endif
#endif // MICROPY_HW_ENABLE_CC3K

Some files were not shown because too many files have changed in this diff Show More