diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 74f911b6f4..cb65a9cd63 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -178,8 +178,13 @@ jobs: - "TG-Watch" - "adafruit_feather_rp2040" - "adafruit_itsybitsy_rp2040" + - "adafruit_neokey_trinkey_m0" + - "adafruit_proxlight_trinkey_m0" - "adafruit_qtpy_rp2040" + - "adafruit_rotary_trinkey_m0" + - "adafruit_slide_trinkey_m0" - "aloriumtech_evo_m51" + - "aramcon2_badge" - "aramcon_badge_2019" - "arduino_mkr1300" - "arduino_mkrzero" @@ -190,6 +195,7 @@ jobs: - "bastble" - "bdmicro_vina_d21" - "bdmicro_vina_d51" + - "bdmicro_vina_d51_pcb7" - "bless_dev_board_multi_sensor" - "blm_badge" - "capablerobot_usbhub" @@ -284,6 +290,8 @@ jobs: - "pewpew_m4" - "picoplanet" - "pimoroni_keybow2040" + - "pimoroni_picolipo_16mb" + - "pimoroni_picolipo_4mb" - "pimoroni_picosystem" - "pimoroni_tiny2040" - "pirkey_m0" @@ -304,17 +312,18 @@ jobs: - "raspberry_pi_pico" - "raytac_mdbt50q-db-40" - "robohatmm1_m4" - - "rotary_trinkey_m0" - "sam32" - "same54_xplained" - "seeeduino_wio_terminal" - "seeeduino_xiao" + - "sensebox_mcu" - "serpente" - "shirtty" - "silicognition-m4-shim" - "simmel" - "snekboard" - "sparkfun_lumidrive" + - "sparkfun_micromod_rp2040" - "sparkfun_nrf52840_micromod" - "sparkfun_nrf52840_mini" - "sparkfun_pro_micro_rp2040" @@ -374,6 +383,8 @@ jobs: python3 --version - name: mpy-cross run: make -C mpy-cross -j2 + - name: Setup build failure matcher + run: echo "::add-matcher::$GITHUB_WORKSPACE/.github/workflows/match-build-fail.json" - name: build run: python3 -u build_release_files.py working-directory: tools @@ -423,6 +434,8 @@ jobs: python3 --version - name: mpy-cross run: make -C mpy-cross -j2 + - name: Setup build failure matcher + run: echo "::add-matcher::$GITHUB_WORKSPACE/.github/workflows/match-build-fail.json" - name: build run: python3 -u build_release_files.py working-directory: tools @@ -452,6 +465,7 @@ jobs: - "adafruit_magtag_2.9_grayscale" - "adafruit_metro_esp32s2" - "artisense_rd00" + - "atmegazero_esp32s2" - "electroniccats_bastwifi" - "espressif_kaluga_1" - "espressif_saola_1_wroom" @@ -484,7 +498,7 @@ jobs: id: idf-cache with: path: ${{ github.workspace }}/.idf_tools - key: ${{ runner.os }}-idf-tools-${{ hashFiles('.git/modules/ports/esp32s2/esp-idf/HEAD') }}-20210304 + key: ${{ runner.os }}-idf-tools-${{ hashFiles('.git/modules/ports/esp32s2/esp-idf/HEAD') }}-20210422 - name: Clone IDF submodules run: | (cd $IDF_PATH && git submodule update --init) @@ -521,6 +535,8 @@ jobs: IDF_TOOLS_PATH: ${{ github.workspace }}/.idf_tools - name: mpy-cross run: make -C mpy-cross -j2 + - name: Setup build failure matcher + run: echo "::add-matcher::$GITHUB_WORKSPACE/.github/workflows/match-build-fail.json" - name: build run: | source $IDF_PATH/export.sh diff --git a/.github/workflows/match-build-fail.json b/.github/workflows/match-build-fail.json new file mode 100644 index 0000000000..938c484f26 --- /dev/null +++ b/.github/workflows/match-build-fail.json @@ -0,0 +1,14 @@ +{ + "problemMatcher": [ + { + "severity": "error", + "pattern": [ + { + "regexp": "^(Build .+ and \\x1b\\[31mfailed\\x1b\\[0m)$", + "message": 1 + } + ], + "owner": "build-failed" + } + ] +} diff --git a/.gitmodules b/.gitmodules index 52abb02a99..da5b5835a6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -171,6 +171,9 @@ [submodule "frozen/Adafruit_CircuitPython_LC709203F"] path = frozen/Adafruit_CircuitPython_LC709203F url = https://github.com/adafruit/Adafruit_CircuitPython_LC709203F +[submodule "frozen/Adafruit_CircuitPython_SimpleMath"] + path = frozen/Adafruit_CircuitPython_SimpleMath + url = https://github.com/adafruit/Adafruit_CircuitPython_SimpleMath [submodule "ports/raspberrypi/sdk"] path = ports/raspberrypi/sdk url = https://github.com/adafruit/pico-sdk.git @@ -178,3 +181,6 @@ path = data/nvm.toml url = https://github.com/adafruit/nvm.toml.git branch = main +[submodule "frozen/Adafruit_CircuitPython_MIDI"] + path = frozen/Adafruit_CircuitPython_MIDI + url = https://github.com/adafruit/Adafruit_CircuitPython_MIDI diff --git a/conf.py b/conf.py index 43ff72d1a2..2625ad63c1 100644 --- a/conf.py +++ b/conf.py @@ -284,7 +284,7 @@ html_static_path = ['docs/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 = ["docs/robots.txt"] +#html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. @@ -489,6 +489,8 @@ class CoreModuleTransform(SphinxTransform): def setup(app): app.add_css_file("customstyle.css") + app.add_css_file("filter.css") + app.add_js_file("filter.js") app.add_config_value('redirects_file', 'redirects', 'env') app.connect('builder-inited', generate_redirects) app.add_transform(CoreModuleTransform) diff --git a/devices/ble_hci/common-hal/_bleio/Characteristic.c b/devices/ble_hci/common-hal/_bleio/Characteristic.c index 7255661576..db1317f4c8 100644 --- a/devices/ble_hci/common-hal/_bleio/Characteristic.c +++ b/devices/ble_hci/common-hal/_bleio/Characteristic.c @@ -78,6 +78,10 @@ bleio_service_obj_t *common_hal_bleio_characteristic_get_service(bleio_character return self->service; } +size_t common_hal_bleio_characteristic_get_max_length(bleio_characteristic_obj_t *self) { + return self->max_length; +} + size_t common_hal_bleio_characteristic_get_value(bleio_characteristic_obj_t *self, uint8_t *buf, size_t len) { // Do GATT operations only if this characteristic has been added to a registered service. if (self->handle != BLE_GATT_HANDLE_INVALID) { diff --git a/devices/ble_hci/common-hal/_bleio/PacketBuffer.c b/devices/ble_hci/common-hal/_bleio/PacketBuffer.c index 9d8a21601d..cb14f4044b 100644 --- a/devices/ble_hci/common-hal/_bleio/PacketBuffer.c +++ b/devices/ble_hci/common-hal/_bleio/PacketBuffer.c @@ -81,7 +81,7 @@ void bleio_packet_buffer_update(bleio_packet_buffer_obj_t *self, mp_buffer_info_ void common_hal_bleio_packet_buffer_construct( bleio_packet_buffer_obj_t *self, bleio_characteristic_obj_t *characteristic, - size_t buffer_size) { + size_t buffer_size, size_t max_packet_size) { self->characteristic = characteristic; self->client = self->characteristic->service->is_remote; @@ -101,7 +101,7 @@ void common_hal_bleio_packet_buffer_construct( } if (incoming) { - if (!ringbuf_alloc(&self->ringbuf, buffer_size * (sizeof(uint16_t) + characteristic->max_length), false)) { + if (!ringbuf_alloc(&self->ringbuf, buffer_size * (sizeof(uint16_t) + max_packet_size), false)) { mp_raise_ValueError(translate("Buffer too large and unable to allocate")); } } @@ -110,12 +110,13 @@ void common_hal_bleio_packet_buffer_construct( self->packet_queued = false; self->pending_index = 0; self->pending_size = 0; - self->outgoing[0] = m_malloc(characteristic->max_length, false); - self->outgoing[1] = m_malloc(characteristic->max_length, false); + self->outgoing[0] = m_malloc(max_packet_size, false); + self->outgoing[1] = m_malloc(max_packet_size, false); } else { self->outgoing[0] = NULL; self->outgoing[1] = NULL; } + self->max_packet_size = max_packet_size; bleio_characteristic_set_observer(self->characteristic, self); } @@ -243,15 +244,16 @@ mp_int_t common_hal_bleio_packet_buffer_get_outgoing_packet_length(bleio_packet_ if (self->conn_handle != BLE_CONN_HANDLE_INVALID) { bleio_connection_internal_t *connection = bleio_conn_handle_to_connection(self->conn_handle); if (connection) { - return MIN(common_hal_bleio_connection_get_max_packet_length(connection), - self->characteristic->max_length); + return MIN(MIN(common_hal_bleio_connection_get_max_packet_length(connection), + self->max_packet_size), + self->characteristic->max_length); } } // There's no current connection, so we don't know the MTU, and // we can't tell what the largest outgoing packet length would be. return -1; } - return self->characteristic->max_length; + return MIN(self->characteristic->max_length, self->max_packet_size); } bool common_hal_bleio_packet_buffer_deinited(bleio_packet_buffer_obj_t *self) { diff --git a/devices/ble_hci/common-hal/_bleio/PacketBuffer.h b/devices/ble_hci/common-hal/_bleio/PacketBuffer.h index 7f351929d5..34471741fe 100644 --- a/devices/ble_hci/common-hal/_bleio/PacketBuffer.h +++ b/devices/ble_hci/common-hal/_bleio/PacketBuffer.h @@ -42,6 +42,7 @@ typedef struct { // We remember the conn_handle so we can do a NOTIFY/INDICATE to a client. // We can find out the conn_handle on a Characteristic write or a CCCD write (but not a read). volatile uint16_t conn_handle; + uint16_t max_packet_size; uint8_t pending_index; uint8_t write_type; bool client; diff --git a/docs/design_guide.rst b/docs/design_guide.rst index 3317570347..1bac4df61b 100644 --- a/docs/design_guide.rst +++ b/docs/design_guide.rst @@ -18,7 +18,7 @@ Start libraries with the cookiecutter Cookiecutter is a tool that lets you bootstrap a new repo based on another repo. We've made one `here `_ for CircuitPython libraries that include configs for Travis CI and ReadTheDocs -along with a setup.py, license, code of conduct and readme. +along with a setup.py, license, code of conduct, readme among other files. .. code-block::sh @@ -252,7 +252,7 @@ At the class level document what class does and how to initialize it:: """DS3231 real-time clock. :param ~busio.I2C i2c_bus: The I2C bus the DS3231 is connected to. - :param int address: The I2C address of the device. + :param int address: The I2C address of the device. Defaults to :const:`0x40` """ def __init__(self, i2c_bus, address=0x40): @@ -267,7 +267,7 @@ Renders as: DS3231 real-time clock. :param ~busio.I2C i2c_bus: The I2C bus the DS3231 is connected to. - :param int address: The I2C address of the device. + :param int address: The I2C address of the device. Defaults to :const:`0x40` Attributes ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -516,6 +516,15 @@ when using ``const()``, keep in mind these general guide lines: - If user will not need access to variable, prefix name with a leading underscore, ex: ``_SOME_CONST``. +Libraries Examples +------------------ +When adding examples, cookiecutter will add a ``_simpletest.py`` file in the examples directory for you. +Be sure to include code with the library minimal functionalities to work on a device. +You could other examples if needed featuring different +functionalities of the library. +If you add additional examples, be sure to include them in the ``examples.rst``. Naming of the examples +files should use the name of the library followed by a description, using underscore to separate them. + Sensor properties and units -------------------------------------------------------------------------------- @@ -536,7 +545,7 @@ properties. +-----------------------+-----------------------+-------------------------------------------------------------------------+ | ``gyro`` | (float, float, float) | x, y, z radians per second | +-----------------------+-----------------------+-------------------------------------------------------------------------+ -| ``temperature`` | float | degrees centigrade | +| ``temperature`` | float | degrees Celsius | +-----------------------+-----------------------+-------------------------------------------------------------------------+ | ``CO2`` | float | measured CO2 in ppm | +-----------------------+-----------------------+-------------------------------------------------------------------------+ @@ -544,9 +553,9 @@ properties. +-----------------------+-----------------------+-------------------------------------------------------------------------+ | ``TVOC`` | float | Total Volatile Organic Compounds in ppb | +-----------------------+-----------------------+-------------------------------------------------------------------------+ -| ``distance`` | float | centimeters | +| ``distance`` | float | centimeters (cm) | +-----------------------+-----------------------+-------------------------------------------------------------------------+ -| ``proximity`` | int | non-unit-specifc proximity values (monotonic but not actual distance) | +| ``proximity`` | int | non-unit-specific proximity values (monotonic but not actual distance) | +-----------------------+-----------------------+-------------------------------------------------------------------------+ | ``light`` | float | non-unit-specific light levels (should be monotonic but is not lux) | +-----------------------+-----------------------+-------------------------------------------------------------------------+ @@ -568,7 +577,7 @@ properties. +-----------------------+-----------------------+-------------------------------------------------------------------------+ | ``duty_cycle`` | int | 16-bit PWM duty cycle (regardless of output resolution) | +-----------------------+-----------------------+-------------------------------------------------------------------------+ -| ``frequency`` | int | Hertz | +| ``frequency`` | int | Hertz (Hz) | +-----------------------+-----------------------+-------------------------------------------------------------------------+ | ``value`` | bool | Digital logic | +-----------------------+-----------------------+-------------------------------------------------------------------------+ @@ -592,9 +601,8 @@ mimic the structure in ``shared-bindings``. To test your native modules or core enhancements, follow these Adafruit Learning Guides for building local firmware to flash onto your device(s): -`SAMD21 - Build Firmware Learning Guide `_ +`Build CircuitPython `_ -`ESP8266 - Build Firmware Learning Guide `_ MicroPython compatibility -------------------------------------------------------------------------------- diff --git a/docs/library/collections.rst b/docs/library/collections.rst index 849e8b6944..b7a5fb1765 100644 --- a/docs/library/collections.rst +++ b/docs/library/collections.rst @@ -14,6 +14,33 @@ hold/accumulate various objects. Classes ------- +.. function:: deque(iterable, maxlen[, flags]) + + Deques (double-ended queues) are a list-like container that support O(1) + appends and pops from either side of the deque. New deques are created + using the following arguments: + + - *iterable* must be the empty tuple, and the new deque is created empty. + + - *maxlen* must be specified and the deque will be bounded to this + maximum length. Once the deque is full, any new items added will + discard items from the opposite end. + + - The optional *flags* can be 1 to check for overflow when adding items. + + As well as supporting `bool` and `len`, deque objects have the following + methods: + + .. method:: deque.append(x) + + Add *x* to the right side of the deque. + Raises IndexError if overflow checking is enabled and there is no more room left. + + .. method:: deque.popleft() + + Remove and return an item from the left side of the deque. + Raises IndexError if no items are present. + .. function:: namedtuple(name, fields) This is factory function to create a new namedtuple type with a specific diff --git a/docs/library/index.rst b/docs/library/index.rst index 181ff0109a..d490ae2277 100644 --- a/docs/library/index.rst +++ b/docs/library/index.rst @@ -39,8 +39,6 @@ with the ``u`` prefix dropped: sys.rst uctypes.rst uselect.rst - usocket.rst - ussl.rst uzlib.rst Omitted functions in the ``string`` library diff --git a/docs/library/micropython.rst b/docs/library/micropython.rst index 31065fbe55..6e39a24c64 100644 --- a/docs/library/micropython.rst +++ b/docs/library/micropython.rst @@ -81,6 +81,9 @@ Functions in a row and the lock-depth will increase, and then `heap_unlock()` must be called the same number of times to make the heap available again. + If the REPL becomes active with the heap locked then it will be forcefully + unlocked. + .. function:: kbd_intr(chr) Set the character that will raise a `KeyboardInterrupt` exception. By diff --git a/docs/library/re.rst b/docs/library/re.rst index bdcc9f52c1..9c266a6d8f 100644 --- a/docs/library/re.rst +++ b/docs/library/re.rst @@ -10,41 +10,101 @@ 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: +Supported operators and special sequences are: -``'.'`` +``.`` Match any character. -``'[...]'`` +``[...]`` Match set of characters. Individual characters and ranges are supported, including negated sets (e.g. ``[^a-c]``). -``'^'`` +``^`` + Match the start of the string. -``'$'`` +``$`` + Match the end of the string. -``'?'`` +``?`` + Match zero or one of the previous sub-pattern. -``'*'`` +``*`` + Match zero or more of the previous sub-pattern. -``'+'`` +``+`` + Match one or more of the previous sub-pattern. -``'??'`` +``??`` + Non-greedy version of ``?``, match zero or one, with the preference + for zero. -``'*?'`` +``*?`` + Non-greedy version of ``*``, match zero or more, with the preference + for the shortest match. -``'+?'`` +``+?`` + Non-greedy version of ``+``, match one or more, with the preference + for the shortest match. -``'|'`` +``|`` + Match either the left-hand side or the right-hand side sub-patterns of + this operator. -``'(...)'`` +``(...)`` Grouping. Each group is capturing (a substring it captures can be accessed with `match.group()` method). -**NOT SUPPORTED**: Counted repetitions (``{m,n}``), more advanced assertions -(``\b``, ``\B``), named groups (``(?P...)``), non-capturing groups -(``(?:...)``), etc. +``\d`` + Matches digit. Equivalent to ``[0-9]``. +``\D`` + Matches non-digit. Equivalent to ``[^0-9]``. + +``\s`` + Matches whitespace. Equivalent to ``[ \t-\r]``. + +``\S`` + Matches non-whitespace. Equivalent to ``[^ \t-\r]``. + +``\w`` + Matches "word characters" (ASCII only). Equivalent to ``[A-Za-z0-9_]``. + +``\W`` + Matches non "word characters" (ASCII only). Equivalent to ``[^A-Za-z0-9_]``. + +``\`` + Escape character. Any other character following the backslash, except + for those listed above, is taken literally. For example, ``\*`` is + equivalent to literal ``*`` (not treated as the ``*`` operator). + Note that ``\r``, ``\n``, etc. are not handled specially, and will be + equivalent to literal letters ``r``, ``n``, etc. Due to this, it's + not recommended to use raw Python strings (``r""``) for regular + expressions. For example, ``r"\r\n"`` when used as the regular + expression is equivalent to ``"rn"``. To match CR character followed + by LF, use ``"\r\n"``. + +**NOT SUPPORTED**: + +* counted repetitions (``{m,n}``) +* named groups (``(?P...)``) +* non-capturing groups (``(?:...)``) +* more advanced assertions (``\b``, ``\B``) +* special character escapes like ``\r``, ``\n`` - use Python's own escaping + instead +* etc. + +Example:: + + import ure + + # As ure doesn't support escapes itself, use of r"" strings is not + # recommended. + regex = ure.compile("[\r\n]") + + regex.split("line1\rline2\nline3\r\n") + + # Result: + # ['line1', 'line2', 'line3', '', ''] Functions --------- @@ -64,6 +124,22 @@ Functions string for first position which matches regex (which still may be 0 if regex is anchored). +.. function:: sub(regex_str, replace, string, count=0, flags=0) + + Compile *regex_str* and search for it in *string*, replacing all matches + with *replace*, and returning the new string. + + *replace* can be a string or a function. If it is a string then escape + sequences of the form ``\`` and ``\g`` can be used to + expand to the corresponding group (or an empty string for unmatched groups). + If *replace* is a function then it must take a single argument (the match) + and should return a replacement string. + + If *count* is specified and non-zero then substitution will stop after + this many substitutions are made. The *flags* argument is ignored. + + Note: availability of this function depends on MicroPython port. + .. data:: DEBUG Flag value, display debug information about compiled expression. @@ -79,8 +155,10 @@ Compiled regular expression. Instances of this class are created using .. method:: regex.match(string) regex.search(string) + regex.sub(replace, string, count=0, flags=0) - Similar to the module-level functions :meth:`match` and :meth:`search`. + Similar to the module-level functions :meth:`match`, :meth:`search` + and :meth:`sub`. Using methods is (much) more efficient if the same regex is applied to multiple strings. @@ -93,9 +171,31 @@ Compiled regular expression. Instances of this class are created using Match objects ------------- -Match objects as returned by `match()` and `search()` methods. +Match objects as returned by `match()` and `search()` methods, and passed +to the replacement function in `sub()`. .. method:: match.group([index]) Return matching (sub)string. *index* is 0 for entire match, 1 and above for each capturing group. Only numeric groups are supported. + +.. method:: match.groups() + + Return a tuple containing all the substrings of the groups of the match. + + Note: availability of this method depends on MicroPython port. + +.. method:: match.start([index]) + match.end([index]) + + Return the index in the original string of the start or end of the + substring group that was matched. *index* defaults to the entire + group, otherwise it will select a group. + + Note: availability of these methods depends on MicroPython port. + +.. method:: match.span([index]) + + Returns the 2-tuple ``(match.start(index), match.end(index))``. + + Note: availability of this method depends on MicroPython port. diff --git a/docs/library/uctypes.rst b/docs/library/uctypes.rst index f71b00c1e4..fb81e3377e 100644 --- a/docs/library/uctypes.rst +++ b/docs/library/uctypes.rst @@ -13,19 +13,91 @@ module is to define data structure layout with about the same power as the C language allows, and then access it using familiar dot-syntax to reference sub-fields. +.. warning:: + + ``uctypes`` module allows access to arbitrary memory addresses of the + machine (including I/O and control registers). Uncareful usage of it + may lead to crashes, data loss, and even hardware malfunction. + .. seealso:: Module :mod:`struct` Standard Python way to access binary data structures (doesn't scale well to large and complex structures). +Usage examples:: + + import uctypes + + # Example 1: Subset of ELF file header + # https://wikipedia.org/wiki/Executable_and_Linkable_Format#File_header + ELF_HEADER = { + "EI_MAG": (0x0 | uctypes.ARRAY, 4 | uctypes.UINT8), + "EI_DATA": 0x5 | uctypes.UINT8, + "e_machine": 0x12 | uctypes.UINT16, + } + + # "f" is an ELF file opened in binary mode + buf = f.read(uctypes.sizeof(ELF_HEADER, uctypes.LITTLE_ENDIAN)) + header = uctypes.struct(uctypes.addressof(buf), ELF_HEADER, uctypes.LITTLE_ENDIAN) + assert header.EI_MAG == b"\x7fELF" + assert header.EI_DATA == 1, "Oops, wrong endianness. Could retry with uctypes.BIG_ENDIAN." + print("machine:", hex(header.e_machine)) + + + # Example 2: In-memory data structure, with pointers + COORD = { + "x": 0 | uctypes.FLOAT32, + "y": 4 | uctypes.FLOAT32, + } + + STRUCT1 = { + "data1": 0 | uctypes.UINT8, + "data2": 4 | uctypes.UINT32, + "ptr": (8 | uctypes.PTR, COORD), + } + + # Suppose you have address of a structure of type STRUCT1 in "addr" + # uctypes.NATIVE is optional (used by default) + struct1 = uctypes.struct(addr, STRUCT1, uctypes.NATIVE) + print("x:", struct1.ptr[0].x) + + + # Example 3: Access to CPU registers. Subset of STM32F4xx WWDG block + WWDG_LAYOUT = { + "WWDG_CR": (0, { + # BFUINT32 here means size of the WWDG_CR register + "WDGA": 7 << uctypes.BF_POS | 1 << uctypes.BF_LEN | uctypes.BFUINT32, + "T": 0 << uctypes.BF_POS | 7 << uctypes.BF_LEN | uctypes.BFUINT32, + }), + "WWDG_CFR": (4, { + "EWI": 9 << uctypes.BF_POS | 1 << uctypes.BF_LEN | uctypes.BFUINT32, + "WDGTB": 7 << uctypes.BF_POS | 2 << uctypes.BF_LEN | uctypes.BFUINT32, + "W": 0 << uctypes.BF_POS | 7 << uctypes.BF_LEN | uctypes.BFUINT32, + }), + } + + WWDG = uctypes.struct(0x40002c00, WWDG_LAYOUT) + + WWDG.WWDG_CFR.WDGTB = 0b10 + WWDG.WWDG_CR.WDGA = 1 + print("Current counter:", WWDG.WWDG_CR.T) + Defining structure layout ------------------------- Structure layout is defined by a "descriptor" - a Python dictionary which encodes field names as keys and other properties required to access them as -associated values. Currently, uctypes requires explicit specification of -offsets for each field. Offset are given in bytes from a structure start. +associated values:: + + { + "field1": , + "field2": , + ... + } + +Currently, ``uctypes`` requires explicit specification of offsets for each +field. Offset are given in bytes from the structure start. Following are encoding examples for various field types: @@ -33,7 +105,7 @@ Following are encoding examples for various field types: "field_name": offset | uctypes.UINT32 - in other words, value is scalar type identifier ORed with field offset + in other words, the value is a scalar type identifier ORed with a field offset (in bytes) from the start of the structure. * Recursive structures:: @@ -43,9 +115,11 @@ Following are encoding examples for various field types: "b1": 1 | uctypes.UINT8, }) - i.e. value is a 2-tuple, first element of which is offset, and second is + i.e. value is a 2-tuple, first element of which is an offset, and second is a structure descriptor dictionary (note: offsets in recursive descriptors - are relative to the structure it defines). + are relative to the structure it defines). Of course, recursive structures + can be specified not just by a literal dictionary, but by referring to a + structure descriptor dictionary (defined earlier) by name. * Arrays of primitive types:: @@ -53,42 +127,42 @@ Following are encoding examples for various field types: i.e. value is a 2-tuple, first element of which is ARRAY flag ORed with offset, and second is scalar element type ORed number of elements - in array. + in the array. * Arrays of aggregate types:: "arr2": (offset | uctypes.ARRAY, size, {"b": 0 | uctypes.UINT8}), i.e. value is a 3-tuple, first element of which is ARRAY flag ORed - with offset, second is a number of elements in array, and third is - descriptor of element type. + with offset, second is a number of elements in the array, and third is + a descriptor of element type. * Pointer to a primitive type:: "ptr": (offset | uctypes.PTR, uctypes.UINT8), i.e. value is a 2-tuple, first element of which is PTR flag ORed - with offset, and second is scalar element type. + with offset, and second is a scalar element type. * Pointer to an aggregate type:: "ptr2": (offset | uctypes.PTR, {"b": 0 | uctypes.UINT8}), i.e. value is a 2-tuple, first element of which is PTR flag ORed - with offset, second is descriptor of type pointed to. + with offset, second is a descriptor of type pointed to. * Bitfields:: "bitf0": offset | uctypes.BFUINT16 | lsbit << uctypes.BF_POS | bitsize << uctypes.BF_LEN, - i.e. value is type of scalar value containing given bitfield (typenames are - similar to scalar types, but prefixes with "BF"), ORed with offset for + i.e. value is a type of scalar value containing given bitfield (typenames are + similar to scalar types, but prefixes with ``BF``), ORed with offset for scalar value containing the bitfield, and further ORed with values for - bit offset and bit length of the bitfield within scalar value, shifted by - BF_POS and BF_LEN positions, respectively. Bitfield position is counted - from the least significant bit, and is the number of right-most bit of a - field (in other words, it's a number of bits a scalar needs to be shifted - right to extract the bitfield). + bit position and bit length of the bitfield within the scalar value, shifted by + BF_POS and BF_LEN bits, respectively. A bitfield position is counted + from the least significant bit of the scalar (having position of 0), and + is the number of right-most bit of a field (in other words, it's a number + of bits a scalar needs to be shifted right to extract the bitfield). In the example above, first a UINT16 value will be extracted at offset 0 (this detail may be important when accessing hardware registers, where @@ -128,10 +202,11 @@ Module contents Layout type for a native structure - with data endianness and alignment conforming to the ABI of the system on which MicroPython runs. -.. function:: sizeof(struct) +.. function:: sizeof(struct, layout_type=NATIVE) - Return size of data structure in bytes. Argument can be either structure - class or specific instantiated structure object (or its aggregate field). + Return size of data structure in bytes. The *struct* argument can be + either a structure class or a specific instantiated structure object + (or its aggregate field). .. function:: addressof(obj) @@ -153,6 +228,35 @@ Module contents so it can be both written too, and you will access current value at the given memory address. +.. data:: UINT8 + INT8 + UINT16 + INT16 + UINT32 + INT32 + UINT64 + INT64 + + Integer types for structure descriptors. Constants for 8, 16, 32, + and 64 bit types are provided, both signed and unsigned. + +.. data:: FLOAT32 + FLOAT64 + + Floating-point types for structure descriptors. + +.. data:: VOID + + ``VOID`` is an alias for ``UINT8``, and is provided to conviniently define + C's void pointers: ``(uctypes.PTR, uctypes.VOID)``. + +.. data:: PTR + ARRAY + + Type constants for pointers and arrays. Note that there is no explicit + constant for structures, it's implicit: an aggregate type without ``PTR`` + or ``ARRAY`` flags is a structure. + Structure descriptors and instantiating structure objects --------------------------------------------------------- @@ -165,7 +269,7 @@ following sources: system. Lookup these addresses in datasheet for a particular MCU/SoC. * As a return value from a call to some FFI (Foreign Function Interface) function. -* From uctypes.addressof(), when you want to pass arguments to an FFI +* From `uctypes.addressof()`, when you want to pass arguments to an FFI function, or alternatively, to access some data for I/O (for example, data read from a file or network socket). @@ -183,30 +287,41 @@ the standard subscript operator ``[]`` - both read and assigned to. If a field is a pointer, it can be dereferenced using ``[0]`` syntax (corresponding to C ``*`` operator, though ``[0]`` works in C too). -Subscripting a pointer with other integer values but 0 are supported too, +Subscripting a pointer with other integer values but 0 are also supported, with the same semantics as in C. -Summing up, accessing structure fields generally follows C syntax, +Summing up, accessing structure fields generally follows the C syntax, except for pointer dereference, when you need to use ``[0]`` operator instead of ``*``. Limitations ----------- -Accessing non-scalar fields leads to allocation of intermediate objects +1. Accessing non-scalar fields leads to allocation of intermediate objects to represent them. This means that special care should be taken to layout a structure which needs to be accessed when memory allocation is disabled (e.g. from an interrupt). The recommendations are: -* Avoid nested structures. For example, instead of +* Avoid accessing nested structures. For example, instead of ``mcu_registers.peripheral_a.register1``, define separate layout descriptors for each peripheral, to be accessed as - ``peripheral_a.register1``. -* Avoid other non-scalar data, like array. For example, instead of - ``peripheral_a.register[0]`` use ``peripheral_a.register0``. + ``peripheral_a.register1``. Or just cache a particular peripheral: + ``peripheral_a = mcu_registers.peripheral_a``. If a register + consists of multiple bitfields, you would need to cache references + to a particular register: ``reg_a = mcu_registers.peripheral_a.reg_a``. +* Avoid other non-scalar data, like arrays. For example, instead of + ``peripheral_a.register[0]`` use ``peripheral_a.register0``. Again, + an alternative is to cache intermediate values, e.g. + ``register0 = peripheral_a.register[0]``. -Note that these recommendations will lead to decreased readability -and conciseness of layouts, so they should be used only if the need -to access structure fields without allocation is anticipated (it's -even possible to define 2 parallel layouts - one for normal usage, -and a restricted one to use when memory allocation is prohibited). +2. Range of offsets supported by the ``uctypes`` module is limited. +The exact range supported is considered an implementation detail, +and the general suggestion is to split structure definitions to +cover from a few kilobytes to a few dozen of kilobytes maximum. +In most cases, this is a natural situation anyway, e.g. it doesn't make +sense to define all registers of an MCU (spread over 32-bit address +space) in one structure, but rather a peripheral block by peripheral +block. In some extreme cases, you may need to split a structure in +several parts artificially (e.g. if accessing native data structure +with multi-megabyte array in the middle, though that would be a very +synthetic case). diff --git a/docs/library/uselect.rst b/docs/library/uselect.rst index a2b408b206..cdf12fac26 100644 --- a/docs/library/uselect.rst +++ b/docs/library/uselect.rst @@ -47,13 +47,18 @@ Methods *eventmask* defaults to ``uselect.POLLIN | uselect.POLLOUT``. + It is OK to call this function multiple times for the same *obj*. + Successive calls will update *obj*'s eventmask to the value of + *eventmask* (i.e. will behave as `modify()`). + .. method:: poll.unregister(obj) Unregister *obj* from polling. .. method:: poll.modify(obj, eventmask) - Modify the *eventmask* for *obj*. + Modify the *eventmask* for *obj*. If *obj* is not registered, `OSError` + is raised with error of ENOENT. .. method:: poll.poll(timeout=-1) diff --git a/docs/library/usocket.rst b/docs/library/usocket.rst deleted file mode 100644 index 2115085a31..0000000000 --- a/docs/library/usocket.rst +++ /dev/null @@ -1,336 +0,0 @@ -******************************* -:mod:`usocket` -- socket module -******************************* - -.. include:: ../templates/unsupported_in_circuitpython.inc - -.. module:: usocket - :synopsis: socket module - -|see_cpython_module| :mod:`cpython:socket`. - -This module provides access to the BSD socket interface. - -.. admonition:: Difference to CPython - :class: attention - - For efficiency and consistency, socket objects in MicroPython implement a ``stream`` - (file-like) interface directly. In CPython, you need to convert a socket to - a file-like object using `makefile()` method. This method is still supported - by MicroPython (but is a no-op), so where compatibility with CPython matters, - be sure to use it. - -Socket address format(s) ------------------------- - -The native socket address format of the ``usocket`` module is an opaque data type -returned by `getaddrinfo` function, which must be used to resolve textual address -(including numeric addresses):: - - sockaddr = usocket.getaddrinfo('www.micropython.org', 80)[0][-1] - # You must use getaddrinfo() even for numeric addresses - sockaddr = usocket.getaddrinfo('127.0.0.1', 80)[0][-1] - # Now you can use that address - sock.connect(addr) - -Using `getaddrinfo` is the most efficient (both in terms of memory and processing -power) and portable way to work with addresses. - -However, ``socket`` module (note the difference with native MicroPython -``usocket`` module described here) provides CPython-compatible way to specify -addresses using tuples, as described below. - -Summing up: - -* Always use `getaddrinfo` when writing portable applications. -* Tuple addresses described below can be used as a shortcut for - quick hacks and interactive use, if your port supports them. - -Tuple address format for ``socket`` module: - -* IPv4: *(ipv4_address, port)*, where *ipv4_address* is a string with - dot-notation numeric IPv4 address, e.g. ``"8.8.8.8"``, and *port* is and - integer port number in the range 1-65535. Note the domain names are not - accepted as *ipv4_address*, they should be resolved first using - `usocket.getaddrinfo()`. -* IPv6: *(ipv6_address, port, flowinfo, scopeid)*, where *ipv6_address* - is a string with colon-notation numeric IPv6 address, e.g. ``"2001:db8::1"``, - and *port* is an integer port number in the range 1-65535. *flowinfo* - must be 0. *scopeid* is the interface scope identifier for link-local - addresses. Note the domain names are not accepted as *ipv6_address*, - they should be resolved first using `usocket.getaddrinfo()`. - -Functions ---------- - -.. function:: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP) - - Create a new socket using the given address family, socket type and - protocol number. Note that specifying *proto* in most cases is not - required (and not recommended, as some MicroPython ports may omit - ``IPPROTO_*`` constants). Instead, *type* argument will select needed - protocol automatically:: - - # Create STREAM TCP socket - socket(AF_INET, SOCK_STREAM) - # Create DGRAM UDP socket - socket(AF_INET, SOCK_DGRAM) - -.. function:: getaddrinfo(host, port) - - Translate the host/port argument into a sequence of 5-tuples that contain all the - necessary arguments for creating a socket connected to that service. The list of - 5-tuples has following structure:: - - (family, type, proto, canonname, sockaddr) - - The following example shows how to connect to a given url:: - - s = usocket.socket() - s.connect(usocket.getaddrinfo('www.micropython.org', 80)[0][-1]) - - .. admonition:: Difference to CPython - :class: attention - - CPython raises a ``socket.gaierror`` exception (`OSError` subclass) in case - of error in this function. MicroPython doesn't have ``socket.gaierror`` - and raises OSError directly. Note that error numbers of `getaddrinfo()` - form a separate namespace and may not match error numbers from - :py:mod:`uerrno` module. To distinguish `getaddrinfo()` errors, they are - represented by negative numbers, whereas standard system errors are - positive numbers (error numbers are accessible using ``e.args[0]`` property - from an exception object). The use of negative values is a provisional - detail which may change in the future. - -.. function:: inet_ntop(af, bin_addr) - - Convert a binary network address *bin_addr* of the given address family *af* - to a textual representation:: - - >>> usocket.inet_ntop(usocket.AF_INET, b"\x7f\0\0\1") - '127.0.0.1' - -.. function:: inet_pton(af, txt_addr) - - Convert a textual network address *txt_addr* of the given address family *af* - to a binary representation:: - - >>> usocket.inet_pton(usocket.AF_INET, "1.2.3.4") - b'\x01\x02\x03\x04' - -Constants ---------- - -.. data:: AF_INET - AF_INET6 - - Address family types. Availability depends on a particular ``MicroPython port``. - -.. data:: SOCK_STREAM - SOCK_DGRAM - - Socket types. - -.. data:: IPPROTO_UDP - IPPROTO_TCP - - IP protocol numbers. Availability depends on a particular ``MicroPython port``. - Note that you don't need to specify these in a call to `usocket.socket()`, - because `SOCK_STREAM` socket type automatically selects `IPPROTO_TCP`, and - `SOCK_DGRAM` - `IPPROTO_UDP`. Thus, the only real use of these constants - is as an argument to `usocket.socket.setsockopt()`. - -.. data:: usocket.SOL_* - - Socket option levels (an argument to `usocket.socket.setsockopt()`). The exact - inventory depends on a ``MicroPython port``. - -.. data:: usocket.SO_* - - Socket options (an argument to `usocket.socket.setsockopt()`). The exact - inventory depends on a ``MicroPython port``. - -Constants specific to WiPy: - -.. data:: IPPROTO_SEC - - Special protocol value to create SSL-compatible socket. - -class socket -============ - -Methods -------- - -.. method:: socket.close() - - Mark the socket closed and release all resources. Once that happens, all future operations - on the socket object will fail. The remote end will receive EOF indication if - supported by protocol. - - Sockets are automatically closed when they are garbage-collected, but it is recommended - to `close()` them explicitly as soon you finished working with them. - -.. method:: socket.bind(address) - - Bind the socket to *address*. The socket must not already be bound. - -.. method:: socket.listen([backlog]) - - Enable a server to accept connections. If *backlog* is specified, it must be at least 0 - (if it's lower, it will be set to 0); and specifies the number of unaccepted connections - that the system will allow before refusing new connections. If not specified, a default - reasonable value is chosen. - -.. method:: socket.accept() - - Accept a connection. The socket must be bound to an address and listening for connections. - The return value is a pair (conn, address) where conn is a new socket object usable to send - and receive data on the connection, and address is the address bound to the socket on the - other end of the connection. - -.. method:: socket.connect(address) - - Connect to a remote socket at *address*. - -.. method:: socket.send(bytes) - - Send data to the socket. The socket must be connected to a remote socket. - Returns number of bytes sent, which may be smaller than the length of data - ("short write"). - -.. method:: socket.sendall(bytes) - - Send all data to the socket. The socket must be connected to a remote socket. - Unlike `send()`, this method will try to send all of data, by sending data - chunk by chunk consecutively. - - The behavior of this method on non-blocking sockets is undefined. Due to this, - on MicroPython, it's recommended to use `write()` method instead, which - has the same "no short writes" policy for blocking sockets, and will return - number of bytes sent on non-blocking sockets. - -.. method:: socket.recv(bufsize) - - Receive data from the socket. The return value is a bytes object representing the data - received. The maximum amount of data to be received at once is specified by bufsize. - -.. method:: socket.sendto(bytes, address) - - Send data to the socket. The socket should not be connected to a remote socket, since the - destination socket is specified by *address*. - -.. method:: socket.recvfrom(bufsize) - - Receive data from the socket. The return value is a pair *(bytes, address)* where *bytes* is a - bytes object representing the data received and *address* is the address of the socket sending - the data. - -.. method:: socket.setsockopt(level, optname, value) - - Set the value of the given socket option. The needed symbolic constants are defined in the - socket module (SO_* etc.). The *value* can be an integer or a bytes-like object representing - a buffer. - -.. method:: socket.settimeout(value) - - **Note**: Not every port supports this method, see below. - - Set a timeout on blocking socket operations. The value argument can be a nonnegative floating - point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations - will raise an `OSError` exception if the timeout period value has elapsed before the operation has - completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket - is put in blocking mode. - - Not every ``MicroPython port`` supports this method. A more portable and - generic solution is to use `uselect.poll` object. This allows to wait on - multiple objects at the same time (and not just on sockets, but on generic - ``stream`` objects which support polling). Example:: - - # Instead of: - s.settimeout(1.0) # time in seconds - s.read(10) # may timeout - - # Use: - poller = uselect.poll() - poller.register(s, uselect.POLLIN) - res = poller.poll(1000) # time in milliseconds - if not res: - # s is still not ready for input, i.e. operation timed out - - .. admonition:: Difference to CPython - :class: attention - - CPython raises a ``socket.timeout`` exception in case of timeout, - which is an `OSError` subclass. MicroPython raises an OSError directly - instead. If you use ``except OSError:`` to catch the exception, - your code will work both in MicroPython and CPython. - -.. method:: socket.setblocking(flag) - - Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, - else to blocking mode. - - This method is a shorthand for certain `settimeout()` calls: - - * ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)`` - * ``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0)`` - -.. method:: socket.makefile(mode='rb', buffering=0) - - Return a file object associated with the socket. The exact returned type depends on the arguments - given to makefile(). The support is limited to binary modes only ('rb', 'wb', and 'rwb'). - CPython's arguments: *encoding*, *errors* and *newline* are not supported. - - .. admonition:: Difference to CPython - :class: attention - - As MicroPython doesn't support buffered streams, values of *buffering* - parameter is ignored and treated as if it was 0 (unbuffered). - - .. admonition:: Difference to CPython - :class: attention - - Closing the file object returned by makefile() WILL close the - original socket as well. - -.. method:: socket.read([size]) - - Read up to size bytes from the socket. Return a bytes object. If *size* is not given, it - reads all data available from the socket until EOF; as such the method will not return until - the socket is closed. This function tries to read as much data as - requested (no "short reads"). This may be not possible with - non-blocking socket though, and then less data will be returned. - -.. method:: socket.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. Just as - `read()`, this method follows "no short reads" policy. - - Return value: number of bytes read and stored into *buf*. - -.. method:: socket.readline() - - Read a line, ending in a newline character. - - Return value: the line read. - -.. method:: socket.write(buf) - - Write the buffer of bytes to the socket. This function will try to - write all data to a socket (no "short writes"). This may be not possible - with a non-blocking socket though, and returned value will be less than - the length of *buf*. - - Return value: number of bytes written. - -.. exception:: usocket.error - - MicroPython does NOT have this exception. - - .. admonition:: Difference to CPython - :class: attention - - CPython used to have a ``socket.error`` exception which is now deprecated, - and is an alias of `OSError`. In MicroPython, use `OSError` directly. diff --git a/docs/library/ussl.rst b/docs/library/ussl.rst deleted file mode 100644 index 91a64b025f..0000000000 --- a/docs/library/ussl.rst +++ /dev/null @@ -1,50 +0,0 @@ -:mod:`ussl` -- SSL/TLS module -============================= - -.. include:: ../templates/unsupported_in_circuitpython.inc - -.. module:: ussl - :synopsis: TLS/SSL wrapper for socket objects - -|see_cpython_module| :mod:`cpython:ssl`. - -This module provides access to Transport Layer Security (previously and -widely known as “Secure Sockets Layer”) encryption and peer authentication -facilities for network sockets, both client-side and server-side. - -Functions ---------- - -.. function:: ussl.wrap_socket(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=CERT_NONE, ca_certs=None) - - Takes a ``stream`` *sock* (usually usocket.socket instance of ``SOCK_STREAM`` type), - and returns an instance of ssl.SSLSocket, which wraps the underlying stream in - an SSL context. Returned object has the usual ``stream`` interface methods like - ``read()``, ``write()``, etc. In MicroPython, the returned object does not expose - socket interface and methods like ``recv()``, ``send()``. In particular, a - server-side SSL socket should be created from a normal socket returned from - :meth:`~usocket.socket.accept()` on a non-SSL listening server socket. - - Depending on the underlying module implementation in a particular - ``MicroPython port``, some or all keyword arguments above may be not supported. - -.. warning:: - - Some implementations of ``ussl`` module do NOT validate server certificates, - which makes an SSL connection established prone to man-in-the-middle attacks. - -Exceptions ----------- - -.. data:: ssl.SSLError - - This exception does NOT exist. Instead its base class, OSError, is used. - -Constants ---------- - -.. data:: ussl.CERT_NONE - ussl.CERT_OPTIONAL - ussl.CERT_REQUIRED - - Supported values for *cert_reqs* parameter. diff --git a/docs/robots.txt b/docs/robots.txt deleted file mode 100644 index ad3189d42c..0000000000 --- a/docs/robots.txt +++ /dev/null @@ -1,6 +0,0 @@ -User-agent: * -Allow: /*/latest/ -Allow: /en/latest/ # Fallback for bots that don't understand wildcards -Allow: /*/6.0.x/ -Allow: /en/6.0.x/ # Fallback for bots that don't understand wildcards -Disallow: / diff --git a/docs/static/filter.css b/docs/static/filter.css new file mode 100644 index 0000000000..12efe14a40 --- /dev/null +++ b/docs/static/filter.css @@ -0,0 +1,17 @@ +#support-matrix-filter-block { position: relative; } +#support-matrix-filter { + width: 100%; +} +#support-matrix-filter-num { + position: absolute; + right: 10px; + top: 4px; +} +.support-matrix-table .this_module code, +.support-matrix-table .this_module span { + background: black; + color: white; +} +.support-matrix-table .board_hidden { + display: none; +} diff --git a/docs/static/filter.js b/docs/static/filter.js new file mode 100644 index 0000000000..9dc46a9eed --- /dev/null +++ b/docs/static/filter.js @@ -0,0 +1,86 @@ +$(() => { + var urlTimeout = null; + function setURL(query, value) { + clearTimeout(urlTimeout); + + urlTimeout = setTimeout(function() { + var url = new URL(window.location.href); + console.log(query,value,value.length,!value.length); + if (!value.length) { + console.log + url.searchParams.delete(query); + } else if (Array.isArray(value)) { + url.searchParams.delete(query); + value.forEach(function(v) { + url.searchParams.append(query, v); + }) + } else { + url.searchParams.set(query, value); + } + + window.history.pushState(null, document.title, url.href); + }, 1000); + } + + function handlePageLoad() { + var url = new URL(window.location.href); + //get values from URL + var filters = url.searchParams.getAll('filter'); + search_terms = filters.join(" "); + $("#support-matrix-filter").val(search_terms); + run_filter(); + } + + function filter_boards(search_string) { + $(".board_hidden").removeClass("board_hidden"); + $(".this_module").removeClass("this_module"); + var nboards = $(".support-matrix-table tbody tr").length; + if(search_string.trim() == "") { + $("#support-matrix-filter-num").html("(all)"); + setURL("filter",[]); + return; + } + var list_search = search_string.split(" ").filter(i => i); + var nvisible = 0; + $(".support-matrix-table tbody tr").each( (index,item) => { + var name = $(item).find("td:first-child p").html(); + var modules = $(item).find("a.reference.internal"); + var matching_all = true; + // + list_search.forEach((sstring) => { + var matching = (sstring[0] == "-"); + for(var modi = 0; modi < modules.length; ++modi) { + module = modules[modi]; + var mod_name = module.firstChild.firstChild.textContent; + if(sstring[0] == "-") { + if(mod_name.match(sstring.substr(1))) { + matching = false; + break; + } + } else { + if(mod_name.match(sstring)) { + $(module).addClass("this_module"); + matching = true; + } + } + } + matching_all = matching_all && matching; + }); + if(!matching_all) { + $(item).addClass("board_hidden"); + } else { + nvisible += 1; + } + }); + $("#support-matrix-filter-num").html(`(${nvisible}/${nboards})`); + setURL("filter",list_search); + } + + function run_filter() { + var search_string = $("#support-matrix-filter").val(); + filter_boards(search_string); + } + $("#support-matrix-filter").on("keyup", run_filter); + // $(document).on("keyup", "#support-matrix-filter", run_filter); + handlePageLoad(); +}); diff --git a/drivers/bus/softqspi.c b/drivers/bus/softqspi.c deleted file mode 100644 index c0aecf87d2..0000000000 --- a/drivers/bus/softqspi.c +++ /dev/null @@ -1,203 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * SPDX-FileCopyrightText: Copyright (c) 2017-2018 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include "drivers/bus/qspi.h" - -#define CS_LOW(self) mp_hal_pin_write(self->cs, 0) -#define CS_HIGH(self) mp_hal_pin_write(self->cs, 1) - -#ifdef MICROPY_HW_SOFTQSPI_SCK_LOW - -// Use externally provided functions for SCK control and IO reading -#define SCK_LOW(self) MICROPY_HW_SOFTQSPI_SCK_LOW(self) -#define SCK_HIGH(self) MICROPY_HW_SOFTQSPI_SCK_HIGH(self) -#define NIBBLE_READ(self) MICROPY_HW_SOFTQSPI_NIBBLE_READ(self) - -#else - -// Use generic pin functions for SCK control and IO reading -#define SCK_LOW(self) mp_hal_pin_write(self->clk, 0) -#define SCK_HIGH(self) mp_hal_pin_write(self->clk, 1) -#define NIBBLE_READ(self) ( \ - mp_hal_pin_read(self->io0) \ - | (mp_hal_pin_read(self->io1) << 1) \ - | (mp_hal_pin_read(self->io2) << 2) \ - | (mp_hal_pin_read(self->io3) << 3)) - -#endif - -STATIC void nibble_write(mp_soft_qspi_obj_t *self, uint8_t v) { - mp_hal_pin_write(self->io0, v & 1); - mp_hal_pin_write(self->io1, (v >> 1) & 1); - mp_hal_pin_write(self->io2, (v >> 2) & 1); - mp_hal_pin_write(self->io3, (v >> 3) & 1); -} - -STATIC int mp_soft_qspi_ioctl(void *self_in, uint32_t cmd) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; - - switch (cmd) { - case MP_QSPI_IOCTL_INIT: - mp_hal_pin_high(self->cs); - mp_hal_pin_output(self->cs); - - // Configure pins - mp_hal_pin_write(self->clk, 0); - mp_hal_pin_output(self->clk); - // mp_hal_pin_write(self->clk, 1); - mp_hal_pin_output(self->io0); - mp_hal_pin_input(self->io1); - mp_hal_pin_write(self->io2, 1); - mp_hal_pin_output(self->io2); - mp_hal_pin_write(self->io3, 1); - mp_hal_pin_output(self->io3); - break; - } - - return 0; // success -} - -STATIC void mp_soft_qspi_transfer(mp_soft_qspi_obj_t *self, size_t len, const uint8_t *src, uint8_t *dest) { - // Will run as fast as possible, limited only by CPU speed and GPIO time - mp_hal_pin_input(self->io1); - mp_hal_pin_output(self->io0); - if (self->io3) { - mp_hal_pin_write(self->io2, 1); - mp_hal_pin_output(self->io2); - mp_hal_pin_write(self->io3, 1); - mp_hal_pin_output(self->io3); - } - if (src) { - for (size_t i = 0; i < len; ++i) { - uint8_t data_out = src[i]; - uint8_t data_in = 0; - for (int j = 0; j < 8; ++j, data_out <<= 1) { - mp_hal_pin_write(self->io0, (data_out >> 7) & 1); - mp_hal_pin_write(self->clk, 1); - data_in = (data_in << 1) | mp_hal_pin_read(self->io1); - mp_hal_pin_write(self->clk, 0); - } - if (dest != NULL) { - dest[i] = data_in; - } - } - } else { - for (size_t i = 0; i < len; ++i) { - uint8_t data_in = 0; - for (int j = 0; j < 8; ++j) { - mp_hal_pin_write(self->clk, 1); - data_in = (data_in << 1) | mp_hal_pin_read(self->io1); - mp_hal_pin_write(self->clk, 0); - } - if (dest != NULL) { - dest[i] = data_in; - } - } - } -} - -STATIC void mp_soft_qspi_qread(mp_soft_qspi_obj_t *self, size_t len, uint8_t *buf) { - // Make all IO lines input - mp_hal_pin_input(self->io2); - mp_hal_pin_input(self->io3); - mp_hal_pin_input(self->io0); - mp_hal_pin_input(self->io1); - - // Will run as fast as possible, limited only by CPU speed and GPIO time - while (len--) { - SCK_HIGH(self); - uint8_t data_in = NIBBLE_READ(self); - SCK_LOW(self); - SCK_HIGH(self); - *buf++ = (data_in << 4) | NIBBLE_READ(self); - SCK_LOW(self); - } -} - -STATIC void mp_soft_qspi_qwrite(mp_soft_qspi_obj_t *self, size_t len, const uint8_t *buf) { - // Make all IO lines output - mp_hal_pin_output(self->io2); - mp_hal_pin_output(self->io3); - mp_hal_pin_output(self->io0); - mp_hal_pin_output(self->io1); - - // Will run as fast as possible, limited only by CPU speed and GPIO time - for (size_t i = 0; i < len; ++i) { - nibble_write(self, buf[i] >> 4); - SCK_HIGH(self); - SCK_LOW(self); - - nibble_write(self, buf[i]); - SCK_HIGH(self); - SCK_LOW(self); - } - - // mp_hal_pin_input(self->io1); -} - -STATIC void mp_soft_qspi_write_cmd_data(void *self_in, uint8_t cmd, size_t len, uint32_t data) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; - uint32_t cmd_buf = cmd | data << 8; - CS_LOW(self); - mp_soft_qspi_transfer(self, 1 + len, (uint8_t *)&cmd_buf, NULL); - CS_HIGH(self); -} - -STATIC void mp_soft_qspi_write_cmd_addr_data(void *self_in, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; - uint8_t cmd_buf[4] = {cmd, addr >> 16, addr >> 8, addr}; - CS_LOW(self); - mp_soft_qspi_transfer(self, 4, cmd_buf, NULL); - mp_soft_qspi_transfer(self, len, src, NULL); - CS_HIGH(self); -} - -STATIC uint32_t mp_soft_qspi_read_cmd(void *self_in, uint8_t cmd, size_t len) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; - uint32_t cmd_buf = cmd; - CS_LOW(self); - mp_soft_qspi_transfer(self, 1 + len, (uint8_t *)&cmd_buf, (uint8_t *)&cmd_buf); - CS_HIGH(self); - return cmd_buf >> 8; -} - -STATIC void mp_soft_qspi_read_cmd_qaddr_qdata(void *self_in, uint8_t cmd, uint32_t addr, size_t len, uint8_t *dest) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; - uint8_t cmd_buf[7] = {cmd, addr >> 16, addr >> 8, addr}; - CS_LOW(self); - mp_soft_qspi_transfer(self, 1, cmd_buf, NULL); - mp_soft_qspi_qwrite(self, 6, &cmd_buf[1]); // 3 addr bytes, 1 extra byte (0), 2 dummy bytes (4 dummy cycles) - mp_soft_qspi_qread(self, len, dest); - CS_HIGH(self); -} - -const mp_qspi_proto_t mp_soft_qspi_proto = { - .ioctl = mp_soft_qspi_ioctl, - .write_cmd_data = mp_soft_qspi_write_cmd_data, - .write_cmd_addr_data = mp_soft_qspi_write_cmd_addr_data, - .read_cmd = mp_soft_qspi_read_cmd, - .read_cmd_qaddr_qdata = mp_soft_qspi_read_cmd_qaddr_qdata, -}; diff --git a/drivers/bus/softspi.c b/drivers/bus/softspi.c deleted file mode 100644 index b0b1accd99..0000000000 --- a/drivers/bus/softspi.c +++ /dev/null @@ -1,105 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * SPDX-FileCopyrightText: Copyright (c) 2016-2018 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include "drivers/bus/spi.h" - -int mp_soft_spi_ioctl(void *self_in, uint32_t cmd) { - mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t *)self_in; - - switch (cmd) { - case MP_SPI_IOCTL_INIT: - mp_hal_pin_write(self->sck, self->polarity); - mp_hal_pin_output(self->sck); - mp_hal_pin_output(self->mosi); - mp_hal_pin_input(self->miso); - break; - - case MP_SPI_IOCTL_DEINIT: - break; - } - - return 0; -} - -void mp_soft_spi_transfer(void *self_in, size_t len, const uint8_t *src, uint8_t *dest) { - mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t *)self_in; - uint32_t delay_half = self->delay_half; - - // only MSB transfer is implemented - - // If a port defines MICROPY_HW_SOFTSPI_MIN_DELAY, and the configured - // delay_half is equal to this value, then the software SPI implementation - // will run as fast as possible, limited only by CPU speed and GPIO time. - #ifdef MICROPY_HW_SOFTSPI_MIN_DELAY - if (delay_half == MICROPY_HW_SOFTSPI_MIN_DELAY) { - for (size_t i = 0; i < len; ++i) { - uint8_t data_out = src[i]; - uint8_t data_in = 0; - for (int j = 0; j < 8; ++j, data_out <<= 1) { - mp_hal_pin_write(self->mosi, (data_out >> 7) & 1); - mp_hal_pin_write(self->sck, 1 - self->polarity); - data_in = (data_in << 1) | mp_hal_pin_read(self->miso); - mp_hal_pin_write(self->sck, self->polarity); - } - if (dest != NULL) { - dest[i] = data_in; - } - } - return; - } - #endif - - for (size_t i = 0; i < len; ++i) { - uint8_t data_out = src[i]; - uint8_t data_in = 0; - for (int j = 0; j < 8; ++j, data_out <<= 1) { - mp_hal_pin_write(self->mosi, (data_out >> 7) & 1); - if (self->phase == 0) { - mp_hal_delay_us_fast(delay_half); - mp_hal_pin_write(self->sck, 1 - self->polarity); - } else { - mp_hal_pin_write(self->sck, 1 - self->polarity); - mp_hal_delay_us_fast(delay_half); - } - data_in = (data_in << 1) | mp_hal_pin_read(self->miso); - if (self->phase == 0) { - mp_hal_delay_us_fast(delay_half); - mp_hal_pin_write(self->sck, self->polarity); - } else { - mp_hal_pin_write(self->sck, self->polarity); - mp_hal_delay_us_fast(delay_half); - } - } - if (dest != NULL) { - dest[i] = data_in; - } - } -} - -const mp_spi_proto_t mp_soft_spi_proto = { - .ioctl = mp_soft_spi_ioctl, - .transfer = mp_soft_spi_transfer, -}; diff --git a/drivers/wiznet5k/README.md b/drivers/wiznet5k/README.md deleted file mode 100644 index 88f25a2b8d..0000000000 --- a/drivers/wiznet5k/README.md +++ /dev/null @@ -1,6 +0,0 @@ -This is the driver for the WIZnet5x00 series of Ethernet controllers. - -Adapted for MicroPython. - -Original source: https://github.com/Wiznet/W5500_EVB/tree/master/ioLibrary -Taken on: 30 August 2014 diff --git a/drivers/wiznet5k/ethernet/socket.c b/drivers/wiznet5k/ethernet/socket.c deleted file mode 100644 index 7a114aa1bc..0000000000 --- a/drivers/wiznet5k/ethernet/socket.c +++ /dev/null @@ -1,718 +0,0 @@ -//***************************************************************************** -// -//! \file socket.c -//! \brief SOCKET APIs Implements file. -//! \details SOCKET APIs like as Berkeley Socket APIs. -//! \version 1.0.3 -//! \date 2013/10/21 -//! \par Revision history -//! <2018/10/09> Nick Moore fixes for CircuitPython -//! <2014/05/01> V1.0.3. Refer to M20140501 -//! 1. Implicit type casting -> Explicit type casting. -//! 2. replace 0x01 with PACK_REMAINED in recvfrom() -//! 3. Validation a destination ip in connect() & sendto(): -//! It occurs a fatal error on converting unint32 address if uint8* addr parameter is not aligned by 4byte address. -//! Copy 4 byte addr value into temporary uint32 variable and then compares it. -//! <2013/12/20> V1.0.2 Refer to M20131220 -//! Remove Warning. -//! <2013/11/04> V1.0.1 2nd Release. Refer to "20131104". -//! In sendto(), Add to clear timeout interrupt status (Sn_IR_TIMEOUT) -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#include - -#include "py/mpthread.h" -#include "socket.h" - -#define SOCK_ANY_PORT_NUM 0xC000; - -static uint16_t sock_any_port = SOCK_ANY_PORT_NUM; -static uint16_t sock_io_mode = 0; -static uint16_t sock_is_sending = 0; -static uint16_t sock_remained_size[_WIZCHIP_SOCK_NUM_] = {0,0,}; -static uint8_t sock_pack_info[_WIZCHIP_SOCK_NUM_] = {0,}; - -#if _WIZCHIP_ == 5200 - static uint16_t sock_next_rd[_WIZCHIP_SOCK_NUM_] ={0,}; -#endif - -#define CHECK_SOCKNUM() \ - do{ \ - if(sn > _WIZCHIP_SOCK_NUM_) return SOCKERR_SOCKNUM; \ - }while(0); \ - -#define CHECK_SOCKMODE(mode) \ - do{ \ - if((getSn_MR(sn) & 0x0F) != mode) return SOCKERR_SOCKMODE; \ - }while(0); \ - -#define CHECK_SOCKINIT() \ - do{ \ - if((getSn_SR(sn) != SOCK_INIT)) return SOCKERR_SOCKINIT; \ - }while(0); \ - -#define CHECK_SOCKDATA() \ - do{ \ - if(len == 0) return SOCKERR_DATALEN; \ - }while(0); \ - -void WIZCHIP_EXPORT(socket_reset)(void) { - sock_any_port = SOCK_ANY_PORT_NUM; - sock_io_mode = 0; - sock_is_sending = 0; - /* - memset(sock_remained_size, 0, _WIZCHIP_SOCK_NUM_ * sizeof(uint16_t)); - memset(sock_pack_info, 0, _WIZCHIP_SOCK_NUM_ * sizeof(uint8_t)); - */ - -#if _WIZCHIP_ == 5200 - memset(sock_next_rd, 0, _WIZCHIP_SOCK_NUM_ * sizeof(uint16_t)); -#endif -} - -int8_t WIZCHIP_EXPORT(socket)(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag) -{ - CHECK_SOCKNUM(); - switch(protocol) - { - case Sn_MR_TCP : - case Sn_MR_UDP : - case Sn_MR_MACRAW : - break; - #if ( _WIZCHIP_ < 5200 ) - case Sn_MR_IPRAW : - case Sn_MR_PPPoE : - break; - #endif - default : - return SOCKERR_SOCKMODE; - } - if((flag & 0x06) != 0) return SOCKERR_SOCKFLAG; -#if _WIZCHIP_ == 5200 - if(flag & 0x10) return SOCKERR_SOCKFLAG; -#endif - - if(flag != 0) - { - switch(protocol) - { - case Sn_MR_TCP: - if((flag & (SF_TCP_NODELAY|SF_IO_NONBLOCK))==0) return SOCKERR_SOCKFLAG; - break; - case Sn_MR_UDP: - if(flag & SF_IGMP_VER2) - { - if((flag & SF_MULTI_ENABLE)==0) return SOCKERR_SOCKFLAG; - } - #if _WIZCHIP_ == 5500 - if(flag & SF_UNI_BLOCK) - { - if((flag & SF_MULTI_ENABLE) == 0) return SOCKERR_SOCKFLAG; - } - #endif - break; - default: - break; - } - } - WIZCHIP_EXPORT(close)(sn); - setSn_MR(sn, (protocol | (flag & 0xF0))); - if(!port) - { - port = sock_any_port++; - if(sock_any_port == 0xFFF0) sock_any_port = SOCK_ANY_PORT_NUM; - } - setSn_PORT(sn,port); - setSn_CR(sn,Sn_CR_OPEN); - while(getSn_CR(sn)); - sock_io_mode |= ((flag & SF_IO_NONBLOCK) << sn); - sock_is_sending &= ~(1< freesize) len = freesize; // check size not to exceed MAX size. - while(1) - { - freesize = getSn_TX_FSR(sn); - tmp = getSn_SR(sn); - if ((tmp != SOCK_ESTABLISHED) && (tmp != SOCK_CLOSE_WAIT)) - { - WIZCHIP_EXPORT(close)(sn); - return SOCKERR_SOCKSTATUS; - } - if( (sock_io_mode & (1< freesize) ) return SOCK_BUSY; - if(len <= freesize) break; - MICROPY_THREAD_YIELD(); - } - wiz_send_data(sn, buf, len); - #if _WIZCHIP_ == 5200 - sock_next_rd[sn] = getSn_TX_RD(sn) + len; - #endif - setSn_CR(sn,Sn_CR_SEND); - /* wait to process the command... */ - while(getSn_CR(sn)); - sock_is_sending |= (1 << sn); - return len; -} - - -int32_t WIZCHIP_EXPORT(recv)(uint8_t sn, uint8_t * buf, uint16_t len) -{ - uint8_t tmp = 0; - uint16_t recvsize = 0; - CHECK_SOCKNUM(); - CHECK_SOCKMODE(Sn_MR_TCP); - CHECK_SOCKDATA(); - - recvsize = getSn_RxMAX(sn); - if(recvsize < len) len = recvsize; - while(1) - { - recvsize = getSn_RX_RSR(sn); - tmp = getSn_SR(sn); - if (tmp != SOCK_ESTABLISHED) - { - if(tmp == SOCK_CLOSE_WAIT) - { - if(recvsize != 0) break; - else if(getSn_TX_FSR(sn) == getSn_TxMAX(sn)) - { - // dpgeorge: Getting here seems to be an orderly shutdown of the - // socket, and trying to get POSIX behaviour we return 0 because: - // "If no messages are available to be received and the peer has per‐ - // formed an orderly shutdown, recv() shall return 0". - // TODO this return value clashes with SOCK_BUSY in non-blocking mode. - WIZCHIP_EXPORT(close)(sn); - return 0; - } - } - else - { - WIZCHIP_EXPORT(close)(sn); - return SOCKERR_SOCKSTATUS; - } - } - if((sock_io_mode & (1< freesize) len = freesize; // check size not to exceed MAX size. - while(1) - { - freesize = getSn_TX_FSR(sn); - if(getSn_SR(sn) == SOCK_CLOSED) return SOCKERR_SOCKCLOSED; - if( (sock_io_mode & (1< freesize) ) return SOCK_BUSY; - if(len <= freesize) break; - MICROPY_THREAD_YIELD(); - }; - wiz_send_data(sn, buf, len); - - #if _WIZCHIP_ == 5200 // for W5200 ARP errata - setSUBR(wizchip_getsubn()); - #endif - - setSn_CR(sn,Sn_CR_SEND); - /* wait to process the command... */ - while(getSn_CR(sn)); - while(1) - { - tmp = getSn_IR(sn); - if(tmp & Sn_IR_SENDOK) - { - setSn_IR(sn, Sn_IR_SENDOK); - break; - } - //M:20131104 - //else if(tmp & Sn_IR_TIMEOUT) return SOCKERR_TIMEOUT; - else if(tmp & Sn_IR_TIMEOUT) - { - setSn_IR(sn, Sn_IR_TIMEOUT); - #if _WIZCHIP_ == 5200 // for W5200 ARP errata - setSUBR((uint8_t*)"\x00\x00\x00\x00"); - #endif - return SOCKERR_TIMEOUT; - } - //////////// - MICROPY_THREAD_YIELD(); - } - #if _WIZCHIP_ == 5200 // for W5200 ARP errata - setSUBR((uint8_t*)"\x00\x00\x00\x00"); - #endif - return len; -} - - - -int32_t WIZCHIP_EXPORT(recvfrom)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t *port) -{ - uint8_t mr; - uint8_t head[8]; - uint16_t pack_len=0; - - CHECK_SOCKNUM(); - //CHECK_SOCKMODE(Sn_MR_UDP); - switch((mr=getSn_MR(sn)) & 0x0F) - { - case Sn_MR_UDP: - case Sn_MR_MACRAW: - break; - #if ( _WIZCHIP_ < 5200 ) - case Sn_MR_IPRAW: - case Sn_MR_PPPoE: - break; - #endif - default: - return SOCKERR_SOCKMODE; - } - CHECK_SOCKDATA(); - if(sock_remained_size[sn] == 0) - { - while(1) - { - pack_len = getSn_RX_RSR(sn); - if(getSn_SR(sn) == SOCK_CLOSED) return SOCKERR_SOCKCLOSED; - if( (sock_io_mode & (1< 1514) - { - WIZCHIP_EXPORT(close)(sn); - return SOCKFATAL_PACKLEN; - } - sock_pack_info[sn] = PACK_FIRST; - } - if(len < sock_remained_size[sn]) pack_len = len; - else pack_len = sock_remained_size[sn]; - wiz_recv_data(sn,buf,pack_len); - break; - #if ( _WIZCHIP_ < 5200 ) - case Sn_MR_IPRAW: - if(sock_remained_size[sn] == 0) - { - wiz_recv_data(sn, head, 6); - setSn_CR(sn,Sn_CR_RECV); - while(getSn_CR(sn)); - addr[0] = head[0]; - addr[1] = head[1]; - addr[2] = head[2]; - addr[3] = head[3]; - sock_remained_size[sn] = head[4]; - sock_remaiend_size[sn] = (sock_remained_size[sn] << 8) + head[5]; - sock_pack_info[sn] = PACK_FIRST; - } - // - // Need to packet length check - // - if(len < sock_remained_size[sn]) pack_len = len; - else pack_len = sock_remained_size[sn]; - wiz_recv_data(sn, buf, pack_len); // data copy. - break; - #endif - default: - wiz_recv_ignore(sn, pack_len); // data copy. - sock_remained_size[sn] = pack_len; - break; - } - setSn_CR(sn,Sn_CR_RECV); - /* wait to process the command... */ - while(getSn_CR(sn)) ; - sock_remained_size[sn] -= pack_len; - //M20140501 : replace 0x01 with PACK_REMAINED - //if(sock_remained_size[sn] != 0) sock_pack_info[sn] |= 0x01; - if(sock_remained_size[sn] != 0) sock_pack_info[sn] |= PACK_REMAINED; - // - return pack_len; -} - - -int8_t WIZCHIP_EXPORT(ctlsocket)(uint8_t sn, ctlsock_type cstype, void* arg) -{ - uint8_t tmp = 0; - CHECK_SOCKNUM(); - switch(cstype) - { - case CS_SET_IOMODE: - tmp = *((uint8_t*)arg); - if(tmp == SOCK_IO_NONBLOCK) sock_io_mode |= (1< explict type casting - //*((uint8_t*)arg) = (sock_io_mode >> sn) & 0x0001; - *((uint8_t*)arg) = (uint8_t)((sock_io_mode >> sn) & 0x0001); - // - break; - case CS_GET_MAXTXBUF: - *((uint16_t*)arg) = getSn_TxMAX(sn); - break; - case CS_GET_MAXRXBUF: - *((uint16_t*)arg) = getSn_RxMAX(sn); - break; - case CS_CLR_INTERRUPT: - if( (*(uint8_t*)arg) > SIK_ALL) return SOCKERR_ARG; - setSn_IR(sn,*(uint8_t*)arg); - break; - case CS_GET_INTERRUPT: - *((uint8_t*)arg) = getSn_IR(sn); - break; - case CS_SET_INTMASK: - if( (*(uint8_t*)arg) > SIK_ALL) return SOCKERR_ARG; - setSn_IMR(sn,*(uint8_t*)arg); - break; - case CS_GET_INTMASK: - *((uint8_t*)arg) = getSn_IMR(sn); - default: - return SOCKERR_ARG; - } - return SOCK_OK; -} - -int8_t WIZCHIP_EXPORT(setsockopt)(uint8_t sn, sockopt_type sotype, void* arg) -{ - // M20131220 : Remove warning - //uint8_t tmp; - CHECK_SOCKNUM(); - switch(sotype) - { - case SO_TTL: - setSn_TTL(sn,*(uint8_t*)arg); - break; - case SO_TOS: - setSn_TOS(sn,*(uint8_t*)arg); - break; - case SO_MSS: - setSn_MSSR(sn,*(uint16_t*)arg); - break; - case SO_DESTIP: - setSn_DIPR(sn, (uint8_t*)arg); - break; - case SO_DESTPORT: - setSn_DPORT(sn, *(uint16_t*)arg); - break; -#if _WIZCHIP_ != 5100 - case SO_KEEPALIVESEND: - CHECK_SOCKMODE(Sn_MR_TCP); - #if _WIZCHIP_ > 5200 - if(getSn_KPALVTR(sn) != 0) return SOCKERR_SOCKOPT; - #endif - setSn_CR(sn,Sn_CR_SEND_KEEP); - while(getSn_CR(sn) != 0) - { - // M20131220 - //if ((tmp = getSn_IR(sn)) & Sn_IR_TIMEOUT) - if (getSn_IR(sn) & Sn_IR_TIMEOUT) - { - setSn_IR(sn, Sn_IR_TIMEOUT); - return SOCKERR_TIMEOUT; - } - } - break; - #if _WIZCHIP_ > 5200 - case SO_KEEPALIVEAUTO: - CHECK_SOCKMODE(Sn_MR_TCP); - setSn_KPALVTR(sn,*(uint8_t*)arg); - break; - #endif -#endif - default: - return SOCKERR_ARG; - } - return SOCK_OK; -} - -int8_t WIZCHIP_EXPORT(getsockopt)(uint8_t sn, sockopt_type sotype, void* arg) -{ - CHECK_SOCKNUM(); - switch(sotype) - { - case SO_FLAG: - *(uint8_t*)arg = getSn_MR(sn) & 0xF0; - break; - case SO_TTL: - *(uint8_t*) arg = getSn_TTL(sn); - break; - case SO_TOS: - *(uint8_t*) arg = getSn_TOS(sn); - break; - case SO_MSS: - *(uint8_t*) arg = getSn_MSSR(sn); - case SO_DESTIP: - getSn_DIPR(sn, (uint8_t*)arg); - break; - case SO_DESTPORT: - *(uint16_t*) arg = getSn_DPORT(sn); - break; - #if _WIZCHIP_ > 5200 - case SO_KEEPALIVEAUTO: - CHECK_SOCKMODE(Sn_MR_TCP); - *(uint16_t*) arg = getSn_KPALVTR(sn); - break; - #endif - case SO_SENDBUF: - *(uint16_t*) arg = getSn_TX_FSR(sn); - case SO_RECVBUF: - *(uint16_t*) arg = getSn_RX_RSR(sn); - case SO_STATUS: - *(uint8_t*) arg = getSn_SR(sn); - break; - case SO_REMAINSIZE: - if(getSn_MR(sn) == Sn_MR_TCP) - *(uint16_t*)arg = getSn_RX_RSR(sn); - else - *(uint16_t*)arg = sock_remained_size[sn]; - break; - case SO_PACKINFO: - CHECK_SOCKMODE(Sn_MR_TCP); - *(uint8_t*)arg = sock_pack_info[sn]; - break; - default: - return SOCKERR_SOCKOPT; - } - return SOCK_OK; -} diff --git a/drivers/wiznet5k/ethernet/socket.h b/drivers/wiznet5k/ethernet/socket.h deleted file mode 100644 index 4f602e429c..0000000000 --- a/drivers/wiznet5k/ethernet/socket.h +++ /dev/null @@ -1,472 +0,0 @@ -//***************************************************************************** -// -//! \file socket.h -//! \brief SOCKET APIs Header file. -//! \details SOCKET APIs like as berkeley socket api. -//! \version 1.0.2 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.2. Refer to M20140501 -//! 1. Modify the comment : SO_REMAINED -> PACK_REMAINED -//! 2. Add the comment as zero byte udp data reception in getsockopt(). -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** -/** - * @defgroup WIZnet_socket_APIs 1. WIZnet socket APIs - * @brief WIZnet socket APIs are based on Berkeley socket APIs, thus it has much similar name and interface. - * But there is a little bit of difference. - * @details - * Comparison between WIZnet and Berkeley SOCKET APIs - * - * - * - * - * - * - * - * - * - * - * - * - *
API WIZnet Berkeley
socket() O O
bind() X O
listen() O O
connect() O O
accept() X O
recv() O O
send() O O
recvfrom() O O
sendto() O O
closesocket() O
close() & disconnect()
O
- * There are @b bind() and @b accept() functions in @b Berkeley SOCKET API but, - * not in @b WIZnet SOCKET API. Because socket() of WIZnet is not only creating a SOCKET but also binding a local port number, - * and listen() of WIZnet is not only listening to connection request from client but also accepting the connection request. \n - * When you program "TCP SERVER" with Berkeley SOCKET API, you can use only one listen port. - * When the listen SOCKET accepts a connection request from a client, it keeps listening. - * After accepting the connection request, a new SOCKET is created and the new SOCKET is used in communication with the client. \n - * Following figure shows network flow diagram by Berkeley SOCKET API. - * @image html Berkeley_SOCKET.jpg "" - * But, When you program "TCP SERVER" with WIZnet SOCKET API, you can use as many as 8 listen SOCKET with same port number. \n - * Because there's no accept() in WIZnet SOCKET APIs, when the listen SOCKET accepts a connection request from a client, - * it is changed in order to communicate with the client. - * And the changed SOCKET is not listening any more and is dedicated for communicating with the client. \n - * If there're many listen SOCKET with same listen port number and a client requests a connection, - * the SOCKET which has the smallest SOCKET number accepts the request and is changed as communication SOCKET. \n - * Following figure shows network flow diagram by WIZnet SOCKET API. - * @image html WIZnet_SOCKET.jpg "" - */ -#ifndef _WIZCHIP_SOCKET_H_ -#define _WIZCHIP_SOCKET_H_ - -// use this macro for exported names to avoid name clashes -#define WIZCHIP_EXPORT(name) wizchip_ ## name - -#include "wizchip_conf.h" - -#define SOCKET uint8_t ///< SOCKET type define for legacy driver - -#define SOCK_OK 1 ///< Result is OK about socket process. -#define SOCK_BUSY 0 ///< Socket is busy on processing the operation. Valid only Non-block IO Mode. -#define SOCK_FATAL -1000 ///< Result is fatal error about socket process. - -#define SOCK_ERROR 0 -#define SOCKERR_SOCKNUM (SOCK_ERROR - 1) ///< Invalid socket number -#define SOCKERR_SOCKOPT (SOCK_ERROR - 2) ///< Invalid socket option -#define SOCKERR_SOCKINIT (SOCK_ERROR - 3) ///< Socket is not initialized -#define SOCKERR_SOCKCLOSED (SOCK_ERROR - 4) ///< Socket unexpectedly closed. -#define SOCKERR_SOCKMODE (SOCK_ERROR - 5) ///< Invalid socket mode for socket operation. -#define SOCKERR_SOCKFLAG (SOCK_ERROR - 6) ///< Invalid socket flag -#define SOCKERR_SOCKSTATUS (SOCK_ERROR - 7) ///< Invalid socket status for socket operation. -#define SOCKERR_ARG (SOCK_ERROR - 10) ///< Invalid argument. -#define SOCKERR_PORTZERO (SOCK_ERROR - 11) ///< Port number is zero -#define SOCKERR_IPINVALID (SOCK_ERROR - 12) ///< Invalid IP address -#define SOCKERR_TIMEOUT (SOCK_ERROR - 13) ///< Timeout occurred -#define SOCKERR_DATALEN (SOCK_ERROR - 14) ///< Data length is zero or greater than buffer max size. -#define SOCKERR_BUFFER (SOCK_ERROR - 15) ///< Socket buffer is not enough for data communication. - -#define SOCKFATAL_PACKLEN (SOCK_FATAL - 1) ///< Invalid packet length. Fatal Error. - -/* - * SOCKET FLAG - */ -#define SF_ETHER_OWN (Sn_MR_MFEN) ///< In \ref Sn_MR_MACRAW, Receive only the packet as broadcast, multicast and own packet -#define SF_IGMP_VER2 (Sn_MR_MC) ///< In \ref Sn_MR_UDP with \ref SF_MULTI_ENABLE, Select IGMP version 2. -#define SF_TCP_NODELAY (Sn_MR_ND) ///< In \ref Sn_MR_TCP, Use to nodelayed ack. -#define SF_MULTI_ENABLE (Sn_MR_MULTI) ///< In \ref Sn_MR_UDP, Enable multicast mode. - -#if _WIZCHIP_ == 5500 - #define SF_BROAD_BLOCK (Sn_MR_BCASTB) ///< In \ref Sn_MR_UDP or \ref Sn_MR_MACRAW, Block broadcast packet. Valid only in W5500 - #define SF_MULTI_BLOCK (Sn_MR_MMB) ///< In \ref Sn_MR_MACRAW, Block multicast packet. Valid only in W5500 - #define SF_IPv6_BLOCK (Sn_MR_MIP6B) ///< In \ref Sn_MR_MACRAW, Block IPv6 packet. Valid only in W5500 - #define SF_UNI_BLOCK (Sn_MR_UCASTB) ///< In \ref Sn_MR_UDP with \ref SF_MULTI_ENABLE. Valid only in W5500 -#endif - -#define SF_IO_NONBLOCK 0x01 ///< Socket nonblock io mode. It used parameter in \ref socket(). - -/* - * UDP & MACRAW Packet Infomation - */ -#define PACK_FIRST 0x80 ///< In Non-TCP packet, It indicates to start receiving a packet. -#define PACK_REMAINED 0x01 ///< In Non-TCP packet, It indicates to remain a packet to be received. -#define PACK_COMPLETED 0x00 ///< In Non-TCP packet, It indicates to complete to receive a packet. - -// resets all global state associated with the socket interface -void WIZCHIP_EXPORT(socket_reset)(void); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Open a socket. - * @details Initializes the socket with 'sn' passed as parameter and open. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param protocol Protocol type to operate such as TCP, UDP and MACRAW. - * @param port Port number to be bined. - * @param flag Socket flags as \ref SF_ETHER_OWN, \ref SF_IGMP_VER2, \ref SF_TCP_NODELAY, \ref SF_MULTI_ENABLE, \ref SF_IO_NONBLOCK and so on.\n - * Valid flags only in W5500 : @ref SF_BROAD_BLOCK, @ref SF_MULTI_BLOCK, @ref SF_IPv6_BLOCK, and @ref SF_UNI_BLOCK. - * @sa Sn_MR - * - * @return @b Success : The socket number @b 'sn' passed as parameter\n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number\n - * @ref SOCKERR_SOCKMODE - Not support socket mode as TCP, UDP, and so on. \n - * @ref SOCKERR_SOCKFLAG - Invaild socket flag. - */ -int8_t WIZCHIP_EXPORT(socket)(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Close a socket. - * @details It closes the socket with @b'sn' passed as parameter. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * - * @return @b Success : @ref SOCK_OK \n - * @b Fail : @ref SOCKERR_SOCKNUM - Invalid socket number - */ -int8_t WIZCHIP_EXPORT(close)(uint8_t sn); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Listen to a connection request from a client. - * @details It is listening to a connection request from a client. - * If connection request is accepted successfully, the connection is established. Socket sn is used in passive(server) mode. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @return @b Success : @ref SOCK_OK \n - * @b Fail :\n @ref SOCKERR_SOCKINIT - Socket is not initialized \n - * @ref SOCKERR_SOCKCLOSED - Socket closed unexpectedly. - */ -int8_t WIZCHIP_EXPORT(listen)(uint8_t sn); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Try to connect a server. - * @details It requests connection to the server with destination IP address and port number passed as parameter.\n - * @note It is valid only in TCP client mode. - * In block io mode, it does not return until connection is completed. - * In Non-block io mode, it return @ref SOCK_BUSY immediately. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param addr Pointer variable of destination IP address. It should be allocated 4 bytes. - * @param port Destination port number. - * - * @return @b Success : @ref SOCK_OK \n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number\n - * @ref SOCKERR_SOCKMODE - Invalid socket mode\n - * @ref SOCKERR_SOCKINIT - Socket is not initialized\n - * @ref SOCKERR_IPINVALID - Wrong server IP address\n - * @ref SOCKERR_PORTZERO - Server port zero\n - * @ref SOCKERR_TIMEOUT - Timeout occurred during request connection\n - * @ref SOCK_BUSY - In non-block io mode, it returned immediately\n - */ -int8_t WIZCHIP_EXPORT(connect)(uint8_t sn, uint8_t * addr, uint16_t port); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Try to disconnect a connection socket. - * @details It sends request message to disconnect the TCP socket 'sn' passed as parameter to the server or client. - * @note It is valid only in TCP server or client mode. \n - * In block io mode, it does not return until disconnection is completed. \n - * In Non-block io mode, it return @ref SOCK_BUSY immediately. \n - - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @return @b Success : @ref SOCK_OK \n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_TIMEOUT - Timeout occurred \n - * @ref SOCK_BUSY - Socket is busy. - */ -int8_t WIZCHIP_EXPORT(disconnect)(uint8_t sn); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Send data to the connected peer in TCP socket. - * @details It is used to send outgoing data to the connected socket. - * @note It is valid only in TCP server or client mode. It can't send data greater than socket buffer size. \n - * In block io mode, It doesn't return until data send is completed - socket buffer size is greater than data. \n - * In non-block io mode, It return @ref SOCK_BUSY immediately when socket buffer is not enough. \n - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer containing data to be sent. - * @param len The byte length of data in buf. - * @return @b Success : The sent data size \n - * @b Fail : \n @ref SOCKERR_SOCKSTATUS - Invalid socket status for socket operation \n - * @ref SOCKERR_TIMEOUT - Timeout occurred \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCK_BUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(send)(uint8_t sn, uint8_t * buf, uint16_t len); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Receive data from the connected peer. - * @details It is used to read incoming data from the connected socket.\n - * It waits for data as much as the application wants to receive. - * @note It is valid only in TCP server or client mode. It can't receive data greater than socket buffer size. \n - * In block io mode, it doesn't return until data reception is completed - data is filled as len in socket buffer. \n - * In non-block io mode, it return @ref SOCK_BUSY immediately when len is greater than data size in socket buffer. \n - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer to read incoming data. - * @param len The max data length of data in buf. - * @return @b Success : The real received data size \n - * @b Fail :\n - * @ref SOCKERR_SOCKSTATUS - Invalid socket status for socket operation \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCK_BUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(recv)(uint8_t sn, uint8_t * buf, uint16_t len); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Sends datagram to the peer with destination IP address and port number passed as parameter. - * @details It sends datagram of UDP or MACRAW to the peer with destination IP address and port number passed as parameter.\n - * Even if the connectionless socket has been previously connected to a specific address, - * the address and port number parameters override the destination address for that particular datagram only. - * @note In block io mode, It doesn't return until data send is completed - socket buffer size is greater than len. - * In non-block io mode, It return @ref SOCK_BUSY immediately when socket buffer is not enough. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer to send outgoing data. - * @param len The byte length of data in buf. - * @param addr Pointer variable of destination IP address. It should be allocated 4 bytes. - * @param port Destination port number. - * - * @return @b Success : The sent data size \n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKSTATUS - Invalid socket status for socket operation \n - * @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCKERR_IPINVALID - Wrong server IP address\n - * @ref SOCKERR_PORTZERO - Server port zero\n - * @ref SOCKERR_SOCKCLOSED - Socket unexpectedly closed \n - * @ref SOCKERR_TIMEOUT - Timeout occurred \n - * @ref SOCK_BUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(sendto)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t port); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Receive datagram of UDP or MACRAW - * @details This function is an application I/F function which is used to receive the data in other then TCP mode. \n - * This function is used to receive UDP and MAC_RAW mode, and handle the header as well. - * This function can divide to received the packet data. - * On the MACRAW SOCKET, the addr and port parameters are ignored. - * @note In block io mode, it doesn't return until data reception is completed - data is filled as len in socket buffer - * In non-block io mode, it return @ref SOCK_BUSY immediately when len is greater than data size in socket buffer. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer to read incoming data. - * @param len The max data length of data in buf. - * When the received packet size <= len, receives data as packet sized. - * When others, receives data as len. - * @param addr Pointer variable of destination IP address. It should be allocated 4 bytes. - * It is valid only when the first call recvfrom for receiving the packet. - * When it is valid, @ref packinfo[7] should be set as '1' after call @ref getsockopt(sn, SO_PACKINFO, &packinfo). - * @param port Pointer variable of destination port number. - * It is valid only when the first call recvform for receiving the packet. -* When it is valid, @ref packinfo[7] should be set as '1' after call @ref getsockopt(sn, SO_PACKINFO, &packinfo). - * - * @return @b Success : This function return real received data size for success.\n - * @b Fail : @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKBUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(recvfrom)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t *port); - - -///////////////////////////// -// SOCKET CONTROL & OPTION // -///////////////////////////// -#define SOCK_IO_BLOCK 0 ///< Socket Block IO Mode in @ref setsockopt(). -#define SOCK_IO_NONBLOCK 1 ///< Socket Non-block IO Mode in @ref setsockopt(). - -/** - * @defgroup DATA_TYPE DATA TYPE - */ - -/** - * @ingroup DATA_TYPE - * @brief The kind of Socket Interrupt. - * @sa Sn_IR, Sn_IMR, setSn_IR(), getSn_IR(), setSn_IMR(), getSn_IMR() - */ -typedef enum -{ - SIK_CONNECTED = (1 << 0), ///< connected - SIK_DISCONNECTED = (1 << 1), ///< disconnected - SIK_RECEIVED = (1 << 2), ///< data received - SIK_TIMEOUT = (1 << 3), ///< timeout occurred - SIK_SENT = (1 << 4), ///< send ok - SIK_ALL = 0x1F, ///< all interrupt -}sockint_kind; - -/** - * @ingroup DATA_TYPE - * @brief The type of @ref ctlsocket(). - */ -typedef enum -{ - CS_SET_IOMODE, ///< set socket IO mode with @ref SOCK_IO_BLOCK or @ref SOCK_IO_NONBLOCK - CS_GET_IOMODE, ///< get socket IO mode - CS_GET_MAXTXBUF, ///< get the size of socket buffer allocated in TX memory - CS_GET_MAXRXBUF, ///< get the size of socket buffer allocated in RX memory - CS_CLR_INTERRUPT, ///< clear the interrupt of socket with @ref sockint_kind - CS_GET_INTERRUPT, ///< get the socket interrupt. refer to @ref sockint_kind - CS_SET_INTMASK, ///< set the interrupt mask of socket with @ref sockint_kind - CS_GET_INTMASK ///< get the masked interrupt of socket. refer to @ref sockint_kind -}ctlsock_type; - - -/** - * @ingroup DATA_TYPE - * @brief The type of socket option in @ref setsockopt() or @ref getsockopt() - */ -typedef enum -{ - SO_FLAG, ///< Valid only in getsockopt(), For set flag of socket refer to flag in @ref socket(). - SO_TTL, ///< Set/Get TTL. @ref Sn_TTL ( @ref setSn_TTL(), @ref getSn_TTL() ) - SO_TOS, ///< Set/Get TOS. @ref Sn_TOS ( @ref setSn_TOS(), @ref getSn_TOS() ) - SO_MSS, ///< Set/Get MSS. @ref Sn_MSSR ( @ref setSn_MSSR(), @ref getSn_MSSR() ) - SO_DESTIP, ///< Set/Get the destination IP address. @ref Sn_DIPR ( @ref setSn_DIPR(), @ref getSn_DIPR() ) - SO_DESTPORT, ///< Set/Get the destination Port number. @ref Sn_DPORT ( @ref setSn_DPORT(), @ref getSn_DPORT() ) -#if _WIZCHIP_ != 5100 - SO_KEEPALIVESEND, ///< Valid only in setsockopt. Manually send keep-alive packet in TCP mode - #if _WIZCHIP_ > 5200 - SO_KEEPALIVEAUTO, ///< Set/Get keep-alive auto transmission timer in TCP mode - #endif -#endif - SO_SENDBUF, ///< Valid only in getsockopt. Get the free data size of Socekt TX buffer. @ref Sn_TX_FSR, @ref getSn_TX_FSR() - SO_RECVBUF, ///< Valid only in getsockopt. Get the received data size in socket RX buffer. @ref Sn_RX_RSR, @ref getSn_RX_RSR() - SO_STATUS, ///< Valid only in getsockopt. Get the socket status. @ref Sn_SR, @ref getSn_SR() - SO_REMAINSIZE, ///< Valid only in getsockopt. Get the remained packet size in other then TCP mode. - SO_PACKINFO ///< Valid only in getsockopt. Get the packet information as @ref PACK_FIRST, @ref PACK_REMAINED, and @ref PACK_COMPLETED in other then TCP mode. -}sockopt_type; - -/** - * @ingroup WIZnet_socket_APIs - * @brief Control socket. - * @details Control IO mode, Interrupt & Mask of socket and get the socket buffer information. - * Refer to @ref ctlsock_type. - * @param sn socket number - * @param cstype type of control socket. refer to @ref ctlsock_type. - * @param arg Data type and value is determined according to @ref ctlsock_type. \n - * - * - * - * - * - *
@b cstype @b data type@b value
@ref CS_SET_IOMODE \n @ref CS_GET_IOMODE uint8_t @ref SOCK_IO_BLOCK @ref SOCK_IO_NONBLOCK
@ref CS_GET_MAXTXBUF \n @ref CS_GET_MAXRXBUF uint16_t 0 ~ 16K
@ref CS_CLR_INTERRUPT \n @ref CS_GET_INTERRUPT \n @ref CS_SET_INTMASK \n @ref CS_GET_INTMASK @ref sockint_kind @ref SIK_CONNECTED, etc.
- * @return @b Success @ref SOCK_OK \n - * @b fail @ref SOCKERR_ARG - Invalid argument\n - */ -int8_t WIZCHIP_EXPORT(ctlsocket)(uint8_t sn, ctlsock_type cstype, void* arg); - -/** - * @ingroup WIZnet_socket_APIs - * @brief set socket options - * @details Set socket option like as TTL, MSS, TOS, and so on. Refer to @ref sockopt_type. - * - * @param sn socket number - * @param sotype socket option type. refer to @ref sockopt_type - * @param arg Data type and value is determined according to sotype. \n - * - * - * - * - * - * - * - * - * - *
@b sotype @b data type@b value
@ref SO_TTL uint8_t 0 ~ 255
@ref SO_TOS uint8_t 0 ~ 255
@ref SO_MSS uint16_t 0 ~ 65535
@ref SO_DESTIP uint8_t[4]
@ref SO_DESTPORT uint16_t 0 ~ 65535
@ref SO_KEEPALIVESEND null null
@ref SO_KEEPALIVEAUTO uint8_t 0 ~ 255
- * @return - * - @b Success : @ref SOCK_OK \n - * - @b Fail - * - @ref SOCKERR_SOCKNUM - Invalid Socket number \n - * - @ref SOCKERR_SOCKMODE - Invalid socket mode \n - * - @ref SOCKERR_SOCKOPT - Invalid socket option or its value \n - * - @ref SOCKERR_TIMEOUT - Timeout occurred when sending keep-alive packet \n - */ -int8_t WIZCHIP_EXPORT(setsockopt)(uint8_t sn, sockopt_type sotype, void* arg); - -/** - * @ingroup WIZnet_socket_APIs - * @brief get socket options - * @details Get socket option like as FLAG, TTL, MSS, and so on. Refer to @ref sockopt_type - * @param sn socket number - * @param sotype socket option type. refer to @ref sockopt_type - * @param arg Data type and value is determined according to sotype. \n - * - * - * - * - * - * - * - * - * - * - * - * - * - *
@b sotype @b data type@b value
@ref SO_FLAG uint8_t @ref SF_ETHER_OWN, etc...
@ref SO_TOS uint8_t 0 ~ 255
@ref SO_MSS uint16_t 0 ~ 65535
@ref SO_DESTIP uint8_t[4]
@ref SO_DESTPORT uint16_t
@ref SO_KEEPALIVEAUTO uint8_t 0 ~ 255
@ref SO_SENDBUF uint16_t 0 ~ 65535
@ref SO_RECVBUF uint16_t 0 ~ 65535
@ref SO_STATUS uint8_t @ref SOCK_ESTABLISHED, etc..
@ref SO_REMAINSIZE uint16_t 0~ 65535
@ref SO_PACKINFO uint8_t @ref PACK_FIRST, etc...
- * @return - * - @b Success : @ref SOCK_OK \n - * - @b Fail - * - @ref SOCKERR_SOCKNUM - Invalid Socket number \n - * - @ref SOCKERR_SOCKOPT - Invalid socket option or its value \n - * - @ref SOCKERR_SOCKMODE - Invalid socket mode \n - * @note - * The option as PACK_REMAINED and SO_PACKINFO is valid only in NON-TCP mode and after call @ref recvfrom(). \n - * When SO_PACKINFO value is PACK_FIRST and the return value of recvfrom() is zero, - * This means the zero byte UDP data(UDP Header only) received. - */ -int8_t WIZCHIP_EXPORT(getsockopt)(uint8_t sn, sockopt_type sotype, void* arg); - -#endif // _WIZCHIP_SOCKET_H_ diff --git a/drivers/wiznet5k/ethernet/w5200/w5200.c b/drivers/wiznet5k/ethernet/w5200/w5200.c deleted file mode 100644 index cbcb136091..0000000000 --- a/drivers/wiznet5k/ethernet/w5200/w5200.c +++ /dev/null @@ -1,206 +0,0 @@ -// dpgeorge: this file taken from w5500/w5500.c and adapted to W5200 - -//***************************************************************************** -// -//! \file w5500.c -//! \brief W5500 HAL Interface. -//! \version 1.0.1 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.2 -//! 1. Implicit type casting -> Explicit type casting. Refer to M20140501 -//! Fixed the problem on porting into under 32bit MCU -//! Issued by Mathias ClauBen, wizwiki forum ID Think01 and bobh -//! Thank for your interesting and serious advices. -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.0.1 -//! 1. Remove warning -//! 2. WIZCHIP_READ_BUF WIZCHIP_WRITE_BUF in case _WIZCHIP_IO_MODE_SPI_FDM_ -//! for loop optimized(removed). refer to M20131220 -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#include "w5200.h" - -#define SMASK (0x7ff) /* tx buffer mask */ -#define RMASK (0x7ff) /* rx buffer mask */ -#define SSIZE (2048) /* max tx buffer size */ -#define RSIZE (2048) /* max rx buffer size */ - -#define TXBUF_BASE (0x8000) -#define RXBUF_BASE (0xc000) -#define SBASE(sn) (TXBUF_BASE + SSIZE * (sn)) /* tx buffer base for socket sn */ -#define RBASE(sn) (RXBUF_BASE + RSIZE * (sn)) /* rx buffer base for socket sn */ - -uint8_t WIZCHIP_READ(uint32_t AddrSel) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[4] = { - AddrSel >> 8, - AddrSel, - 0x00, - 0x01, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 4); - uint8_t ret; - WIZCHIP.IF.SPI._read_bytes(&ret, 1); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); - - return ret; -} - -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[5] = { - AddrSel >> 8, - AddrSel, - 0x80, - 0x01, - wb, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 5); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_READ_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[4] = { - AddrSel >> 8, - AddrSel, - 0x00 | ((len >> 8) & 0x7f), - len & 0xff, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 4); - WIZCHIP.IF.SPI._read_bytes(pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[4] = { - AddrSel >> 8, - AddrSel, - 0x80 | ((len >> 8) & 0x7f), - len & 0xff, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 4); - WIZCHIP.IF.SPI._write_bytes(pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -uint16_t getSn_TX_FSR(uint8_t sn) { - uint16_t val = 0, val1 = 0; - do { - val1 = (WIZCHIP_READ(Sn_TX_FSR(sn)) << 8) | WIZCHIP_READ(Sn_TX_FSR(sn) + 1); - if (val1 != 0) { - val = (WIZCHIP_READ(Sn_TX_FSR(sn)) << 8) | WIZCHIP_READ(Sn_TX_FSR(sn) + 1); - } - } while (val != val1); - return val; -} - -uint16_t getSn_RX_RSR(uint8_t sn) { - uint16_t val = 0, val1 = 0; - do { - val1 = (WIZCHIP_READ(Sn_RX_RSR(sn)) << 8) | WIZCHIP_READ(Sn_RX_RSR(sn) + 1); - if (val1 != 0) { - val = (WIZCHIP_READ(Sn_RX_RSR(sn)) << 8) | WIZCHIP_READ(Sn_RX_RSR(sn) + 1); - } - } while (val != val1); - return val; -} - -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len) { - if (len == 0) { - return; - } - - uint16_t ptr = getSn_TX_WR(sn); - uint16_t offset = ptr & SMASK; - uint32_t addr = offset + SBASE(sn); - - if (offset + len > SSIZE) { - // implement wrap-around circular buffer - uint16_t size = SSIZE - offset; - WIZCHIP_WRITE_BUF(addr, wizdata, size); - WIZCHIP_WRITE_BUF(SBASE(sn), wizdata + size, len - size); - } else { - WIZCHIP_WRITE_BUF(addr, wizdata, len); - } - - ptr += len; - setSn_TX_WR(sn, ptr); -} - -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len) { - if (len == 0) { - return; - } - - uint16_t ptr = getSn_RX_RD(sn); - uint16_t offset = ptr & RMASK; - uint16_t addr = RBASE(sn) + offset; - - if (offset + len > RSIZE) { - // implement wrap-around circular buffer - uint16_t size = RSIZE - offset; - WIZCHIP_READ_BUF(addr, wizdata, size); - WIZCHIP_READ_BUF(RBASE(sn), wizdata + size, len - size); - } else { - WIZCHIP_READ_BUF(addr, wizdata, len); - } - - ptr += len; - setSn_RX_RD(sn, ptr); -} - -void wiz_recv_ignore(uint8_t sn, uint16_t len) { - uint16_t ptr = getSn_RX_RD(sn); - ptr += len; - setSn_RX_RD(sn, ptr); -} diff --git a/drivers/wiznet5k/ethernet/w5200/w5200.h b/drivers/wiznet5k/ethernet/w5200/w5200.h deleted file mode 100644 index 988c8827fc..0000000000 --- a/drivers/wiznet5k/ethernet/w5200/w5200.h +++ /dev/null @@ -1,2092 +0,0 @@ -// dpgeorge: this file taken from w5500/w5500.h and adapted to W5200 - -//***************************************************************************** -// -//! \file w5500.h -//! \brief W5500 HAL Header File. -//! \version 1.0.0 -//! \date 2013/10/21 -//! \par Revision history -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#ifndef _W5200_H_ -#define _W5200_H_ - -#include -#include "../wizchip_conf.h" -//#include "board.h" - -#define _W5200_IO_BASE_ 0x00000000 - -#define WIZCHIP_CREG_ADDR(addr) (_W5200_IO_BASE_ + (addr)) - -#define WIZCHIP_CH_BASE (0x4000) -#define WIZCHIP_CH_SIZE (0x100) -#define WIZCHIP_SREG_ADDR(sn, addr) (_W5200_IO_BASE_ + WIZCHIP_CH_BASE + (sn) * WIZCHIP_CH_SIZE + (addr)) - -////////////////////////////// -//-------------------------- defgroup --------------------------------- -/** - * @defgroup W5500 W5500 - * - * @brief WHIZCHIP register defines and I/O functions of @b W5500. - * - * - @ref WIZCHIP_register : @ref Common_register_group and @ref Socket_register_group - * - @ref WIZCHIP_IO_Functions : @ref Basic_IO_function, @ref Common_register_access_function and @ref Socket_register_access_function - */ - - -/** - * @defgroup WIZCHIP_register WIZCHIP register - * @ingroup W5500 - * - * @brief WHIZCHIP register defines register group of @b W5500. - * - * - @ref Common_register_group : Common register group - * - @ref Socket_register_group : \c SOCKET n register group - */ - - -/** - * @defgroup WIZCHIP_IO_Functions WIZCHIP I/O functions - * @ingroup W5500 - * - * @brief This supports the basic I/O functions for @ref WIZCHIP_register. - * - * - Basic I/O function \n - * WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() \n\n - * - * - @ref Common_register_group access functions \n - * -# @b Mode \n - * getMR(), setMR() - * -# @b Interrupt \n - * getIR(), setIR(), getIMR(), setIMR(), getSIR(), setSIR(), getSIMR(), setSIMR(), getINTLEVEL(), setINTLEVEL() - * -# Network Information \n - * getSHAR(), setSHAR(), getGAR(), setGAR(), getSUBR(), setSUBR(), getSIPR(), setSIPR() - * -# @b Retransmission \n - * getRCR(), setRCR(), getRTR(), setRTR() - * -# @b PPPoE \n - * getPTIMER(), setPTIMER(), getPMAGIC(), getPMAGIC(), getPSID(), setPSID(), getPHAR(), setPHAR(), getPMRU(), setPMRU() - * -# ICMP packet \n - * getUIPR(), getUPORTR() - * -# @b etc. \n - * getPHYCFGR(), setPHYCFGR(), getVERSIONR() \n\n - * - * - \ref Socket_register_group access functions \n - * -# SOCKET control \n - * getSn_MR(), setSn_MR(), getSn_CR(), setSn_CR(), getSn_IMR(), setSn_IMR(), getSn_IR(), setSn_IR() - * -# SOCKET information \n - * getSn_SR(), getSn_DHAR(), setSn_DHAR(), getSn_PORT(), setSn_PORT(), getSn_DIPR(), setSn_DIPR(), getSn_DPORT(), setSn_DPORT() - * getSn_MSSR(), setSn_MSSR() - * -# SOCKET communication \n - * getSn_RXBUF_SIZE(), setSn_RXBUF_SIZE(), getSn_TXBUF_SIZE(), setSn_TXBUF_SIZE() \n - * getSn_TX_RD(), getSn_TX_WR(), setSn_TX_WR() \n - * getSn_RX_RD(), setSn_RX_RD(), getSn_RX_WR() \n - * getSn_TX_FSR(), getSn_RX_RSR(), getSn_KPALVTR(), setSn_KPALVTR() - * -# IP header field \n - * getSn_FRAG(), setSn_FRAG(), getSn_TOS(), setSn_TOS() \n - * getSn_TTL(), setSn_TTL() - */ - - - -/** - * @defgroup Common_register_group Common register - * @ingroup WIZCHIP_register - * - * @brief Common register group\n - * It set the basic for the networking\n - * It set the configuration such as interrupt, network information, ICMP, etc. - * @details - * @sa MR : Mode register. - * @sa GAR, SUBR, SHAR, SIPR - * @sa INTLEVEL, IR, IMR, SIR, SIMR : Interrupt. - * @sa RTR, RCR : Data retransmission. - * @sa PTIMER, PMAGIC, PHAR, PSID, PMRU : PPPoE. - * @sa UIPR, UPORTR : ICMP message. - * @sa PHYCFGR, VERSIONR : etc. - */ - - - -/** - * @defgroup Socket_register_group Socket register - * @ingroup WIZCHIP_register - * - * @brief Socket register group.\n - * Socket register configures and control SOCKETn which is necessary to data communication. - * @details - * @sa Sn_MR, Sn_CR, Sn_IR, Sn_IMR : SOCKETn Control - * @sa Sn_SR, Sn_PORT, Sn_DHAR, Sn_DIPR, Sn_DPORT : SOCKETn Information - * @sa Sn_MSSR, Sn_TOS, Sn_TTL, Sn_KPALVTR, Sn_FRAG : Internet protocol. - * @sa Sn_RXBUF_SIZE, Sn_TXBUF_SIZE, Sn_TX_FSR, Sn_TX_RD, Sn_TX_WR, Sn_RX_RSR, Sn_RX_RD, Sn_RX_WR : Data communication - */ - - - - /** - * @defgroup Basic_IO_function Basic I/O function - * @ingroup WIZCHIP_IO_Functions - * @brief These are basic input/output functions to read values from register or write values to register. - */ - -/** - * @defgroup Common_register_access_function Common register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access common registers. - */ - -/** - * @defgroup Socket_register_access_function Socket register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access socket registers. - */ - -//------------------------------- defgroup end -------------------------------------------- -//----------------------------- W5500 Common Registers IOMAP ----------------------------- -/** - * @ingroup Common_register_group - * @brief Mode Register address(R/W)\n - * @ref MR is used for S/W reset, ping block mode, PPPoE mode and etc. - * @details Each bit of @ref MR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
RST Reserved WOL PB PPPoE Reserved FARP Reserved
- * - \ref MR_RST : Reset - * - \ref MR_WOL : Wake on LAN - * - \ref MR_PB : Ping block - * - \ref MR_PPPOE : PPPoE mode - * - \ref MR_FARP : Force ARP mode - */ -#define MR WIZCHIP_CREG_ADDR(0x0000) - -/** - * @ingroup Common_register_group - * @brief Gateway IP Register address(R/W) - * @details @ref GAR configures the default gateway address. - */ -#define GAR WIZCHIP_CREG_ADDR(0x0001) - -/** - * @ingroup Common_register_group - * @brief Subnet mask Register address(R/W) - * @details @ref SUBR configures the subnet mask address. - */ -#define SUBR WIZCHIP_CREG_ADDR(0x0005) - -/** - * @ingroup Common_register_group - * @brief Source MAC Register address(R/W) - * @details @ref SHAR configures the source hardware address. - */ -#define SHAR WIZCHIP_CREG_ADDR(0x0009) - -/** - * @ingroup Common_register_group - * @brief Source IP Register address(R/W) - * @details @ref SIPR configures the source IP address. - */ -#define SIPR WIZCHIP_CREG_ADDR(0x000f) - -/** - * @ingroup Common_register_group - * @brief Set Interrupt low level timer register address(R/W) - * @details @ref INTLEVEL configures the Interrupt Assert Time. - */ -//#define INTLEVEL (_W5500_IO_BASE_ + (0x0013 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Interrupt Register(R/W) - * @details @ref IR indicates the interrupt status. Each bit of @ref IR will be still until the bit will be written to by the host. - * If @ref IR is not equal to x00 INTn PIN is asserted to low until it is x00\n\n - * Each bit of @ref IR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
CONFLICT UNREACH PPPoE MP Reserved Reserved Reserved Reserved
- * - \ref IR_CONFLICT : IP conflict - * - \ref IR_UNREACH : Destination unreachable - * - \ref IR_PPPoE : PPPoE connection close - * - \ref IR_MP : Magic packet - */ -#define IR WIZCHIP_CREG_ADDR(0x0015) - -/** - * @ingroup Common_register_group - * @brief Interrupt mask register(R/W) - * @details @ref IMR is used to mask interrupts. Each bit of @ref IMR corresponds to each bit of @ref IR. - * When a bit of @ref IMR is and the corresponding bit of @ref IR is an interrupt will be issued. In other words, - * if a bit of @ref IMR is an interrupt will not be issued even if the corresponding bit of @ref IR is \n\n - * Each bit of @ref IMR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
IM_IR7 IM_IR6 IM_IR5 IM_IR4 Reserved Reserved Reserved Reserved
- * - \ref IM_IR7 : IP Conflict Interrupt Mask - * - \ref IM_IR6 : Destination unreachable Interrupt Mask - * - \ref IM_IR5 : PPPoE Close Interrupt Mask - * - \ref IM_IR4 : Magic Packet Interrupt Mask - */ -#define IMR WIZCHIP_CREG_ADDR(0x0016) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Register(R/W) - * @details @ref SIR indicates the interrupt status of Socket.\n - * Each bit of @ref SIR be still until @ref Sn_IR is cleared by the host.\n - * If @ref Sn_IR is not equal to x00 the n-th bit of @ref SIR is and INTn PIN is asserted until @ref SIR is x00 */ -//#define SIR (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Mask Register(R/W) - * @details Each bit of @ref SIMR corresponds to each bit of @ref SIR. - * When a bit of @ref SIMR is and the corresponding bit of @ref SIR is Interrupt will be issued. - * In other words, if a bit of @ref SIMR is an interrupt will be not issued even if the corresponding bit of @ref SIR is - */ -//#define SIMR (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Timeout register address( 1 is 100us )(R/W) - * @details @ref RTR configures the retransmission timeout period. The unit of timeout period is 100us and the default of @ref RTR is x07D0or 000 - * And so the default timeout period is 200ms(100us X 2000). During the time configured by @ref RTR, W5500 waits for the peer response - * to the packet that is transmitted by \ref Sn_CR (CONNECT, DISCON, CLOSE, SEND, SEND_MAC, SEND_KEEP command). - * If the peer does not respond within the @ref RTR time, W5500 retransmits the packet or issues timeout. - */ -#define RTR WIZCHIP_CREG_ADDR(0x0017) - -/** - * @ingroup Common_register_group - * @brief Retry count register(R/W) - * @details @ref RCR configures the number of time of retransmission. - * When retransmission occurs as many as ref RCR+1 Timeout interrupt is issued (@ref Sn_IR[TIMEOUT] = . - */ -#define RCR WIZCHIP_CREG_ADDR(0x0019) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Request Timer register in PPPoE mode(R/W) - * @details @ref PTIMER configures the time for sending LCP echo request. The unit of time is 25ms. - */ -#define PTIMER WIZCHIP_CREG_ADDR(0x0028) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Magic number register in PPPoE mode(R/W) - * @details @ref PMAGIC configures the 4bytes magic number to be used in LCP negotiation. - */ -#define PMAGIC WIZCHIP_CREG_ADDR(0x0029) - -/** - * @ingroup Common_register_group - * @brief PPP Destination MAC Register address(R/W) - * @details @ref PHAR configures the PPPoE server hardware address that is acquired during PPPoE connection process. - */ -//#define PHAR (_W5500_IO_BASE_ + (0x001E << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Session Identification Register(R/W) - * @details @ref PSID configures the PPPoE sever session ID acquired during PPPoE connection process. - */ -//#define PSID (_W5500_IO_BASE_ + (0x0024 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Maximum Segment Size(MSS) register(R/W) - * @details @ref PMRU configures the maximum receive unit of PPPoE. - */ -//#define PMRU (_W5500_IO_BASE_ + (0x0026 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable IP register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR indicates - * the destination IP address & port number respectively. - */ -//#define UIPR (_W5500_IO_BASE_ + (0x002a << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable Port register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR - * indicates the destination IP address & port number respectively. - */ -//#define UPORTR (_W5500_IO_BASE_ + (0x002e << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PHY Status Register(R/W) - * @details @ref PHYCFGR configures PHY operation mode and resets PHY. In addition, @ref PHYCFGR indicates the status of PHY such as duplex, Speed, Link. - */ -//#define PHYCFGR (_W5500_IO_BASE_ + (0x002E << 8) + (WIZCHIP_CREG_BLOCK << 3)) -#define PHYSTATUS WIZCHIP_CREG_ADDR(0x0035) - -// Reserved (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0031 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0032 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0033 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0034 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0035 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0036 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0037 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0038 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief chip version register address(R) - * @details @ref VERSIONR always indicates the W5500 version as @b 0x04. - */ -//#define VERSIONR (_W5200_IO_BASE_ + (0x0039 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - - -//----------------------------- W5500 Socket Registers IOMAP ----------------------------- -/** - * @ingroup Socket_register_group - * @brief socket Mode register(R/W) - * @details @ref Sn_MR configures the option or protocol type of Socket n.\n\n - * Each bit of @ref Sn_MR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
MULTI/MFEN BCASTB ND/MC/MMB UCASTB/MIP6B Protocol[3] Protocol[2] Protocol[1] Protocol[0]
- * - @ref Sn_MR_MULTI : Support UDP Multicasting - * - @ref Sn_MR_BCASTB : Broadcast block in UDP Multicasting - * - @ref Sn_MR_ND : No Delayed Ack(TCP) flag - * - @ref Sn_MR_MC : IGMP version used in UDP mulitcasting - * - @ref Sn_MR_MMB : Multicast Blocking in @ref Sn_MR_MACRAW mode - * - @ref Sn_MR_UCASTB : Unicast Block in UDP Multicating - * - @ref Sn_MR_MIP6B : IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * - Protocol - * - * - * - * - * - * - *
Protocol[3] Protocol[2] Protocol[1] Protocol[0] @b Meaning
0 0 0 0 Closed
0 0 0 1 TCP
0 0 1 0 UDP
0 1 0 0 MACRAW
- * - @ref Sn_MR_MACRAW : MAC LAYER RAW SOCK \n - * - @ref Sn_MR_UDP : UDP - * - @ref Sn_MR_TCP : TCP - * - @ref Sn_MR_CLOSE : Unused socket - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR(N) WIZCHIP_SREG_ADDR(N, 0x0000) - -/** - * @ingroup Socket_register_group - * @brief Socket command register(R/W) - * @details This is used to set the command for Socket n such as OPEN, CLOSE, CONNECT, LISTEN, SEND, and RECEIVE.\n - * After W5500 accepts the command, the @ref Sn_CR register is automatically cleared to 0x00. - * Even though @ref Sn_CR is cleared to 0x00, the command is still being processed.\n - * To check whether the command is completed or not, please check the @ref Sn_IR or @ref Sn_SR. - * - @ref Sn_CR_OPEN : Initialize or open socket. - * - @ref Sn_CR_LISTEN : Wait connection request in TCP mode(Server mode) - * - @ref Sn_CR_CONNECT : Send connection request in TCP mode(Client mode) - * - @ref Sn_CR_DISCON : Send closing request in TCP mode. - * - @ref Sn_CR_CLOSE : Close socket. - * - @ref Sn_CR_SEND : Update TX buffer pointer and send data. - * - @ref Sn_CR_SEND_MAC : Send data with MAC address, so without ARP process. - * - @ref Sn_CR_SEND_KEEP : Send keep alive message. - * - @ref Sn_CR_RECV : Update RX buffer pointer and receive data. - */ -#define Sn_CR(N) WIZCHIP_SREG_ADDR(N, 0x0001) - -/** - * @ingroup Socket_register_group - * @brief Socket interrupt register(R) - * @details @ref Sn_IR indicates the status of Socket Interrupt such as establishment, termination, receiving data, timeout).\n - * When an interrupt occurs and the corresponding bit of @ref Sn_IMR is the corresponding bit of @ref Sn_IR becomes \n - * In order to clear the @ref Sn_IR bit, the host should write the bit to \n - * - * - * - *
7 6 5 4 3 2 1 0
Reserved Reserved Reserved SEND_OK TIMEOUT RECV DISCON CON
- * - \ref Sn_IR_SENDOK : SEND_OK Interrupt - * - \ref Sn_IR_TIMEOUT : TIMEOUT Interrupt - * - \ref Sn_IR_RECV : RECV Interrupt - * - \ref Sn_IR_DISCON : DISCON Interrupt - * - \ref Sn_IR_CON : CON Interrupt - */ -#define Sn_IR(N) WIZCHIP_SREG_ADDR(N, 0x0002) - -/** - * @ingroup Socket_register_group - * @brief Socket status register(R) - * @details @ref Sn_SR indicates the status of Socket n.\n - * The status of Socket n is changed by @ref Sn_CR or some special control packet as SYN, FIN packet in TCP. - * @par Normal status - * - @ref SOCK_CLOSED : Closed - * - @ref SOCK_INIT : Initiate state - * - @ref SOCK_LISTEN : Listen state - * - @ref SOCK_ESTABLISHED : Success to connect - * - @ref SOCK_CLOSE_WAIT : Closing state - * - @ref SOCK_UDP : UDP socket - * - @ref SOCK_MACRAW : MAC raw mode socket - *@par Temporary status during changing the status of Socket n. - * - @ref SOCK_SYNSENT : This indicates Socket n sent the connect-request packet (SYN packet) to a peer. - * - @ref SOCK_SYNRECV : It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer. - * - @ref SOCK_FIN_WAIT : Connection state - * - @ref SOCK_CLOSING : Closing state - * - @ref SOCK_TIME_WAIT : Closing state - * - @ref SOCK_LAST_ACK : Closing state - */ -#define Sn_SR(N) WIZCHIP_SREG_ADDR(N, 0x0003) - -/** - * @ingroup Socket_register_group - * @brief source port register(R/W) - * @details @ref Sn_PORT configures the source port number of Socket n. - * It is valid when Socket n is used in TCP/UPD mode. It should be set before OPEN command is ordered. - */ -#define Sn_PORT(N) WIZCHIP_SREG_ADDR(N, 0x0004) - -/** - * @ingroup Socket_register_group - * @brief Peer MAC register address(R/W) - * @details @ref Sn_DHAR configures the destination hardware address of Socket n when using SEND_MAC command in UDP mode or - * it indicates that it is acquired in ARP-process by CONNECT/SEND command. - */ -#define Sn_DHAR(N) WIZCHIP_SREG_ADDR(N, 0x0006) - -/** - * @ingroup Socket_register_group - * @brief Peer IP register address(R/W) - * @details @ref Sn_DIPR configures or indicates the destination IP address of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In TCP client mode, it configures an IP address of �TCP serverbefore CONNECT command. - * In TCP server mode, it indicates an IP address of �TCP clientafter successfully establishing connection. - * In UDP mode, it configures an IP address of peer to be received the UDP packet by SEND or SEND_MAC command. - */ -#define Sn_DIPR(N) WIZCHIP_SREG_ADDR(N, 0x000c) - -/** - * @ingroup Socket_register_group - * @brief Peer port register address(R/W) - * @details @ref Sn_DPORT configures or indicates the destination port number of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In �TCP clientmode, it configures the listen port number of �TCP serverbefore CONNECT command. - * In �TCP Servermode, it indicates the port number of TCP client after successfully establishing connection. - * In UDP mode, it configures the port number of peer to be transmitted the UDP packet by SEND/SEND_MAC command. - */ -#define Sn_DPORT(N) WIZCHIP_SREG_ADDR(N, 0x0010) - -/** - * @ingroup Socket_register_group - * @brief Maximum Segment Size(Sn_MSSR0) register address(R/W) - * @details @ref Sn_MSSR configures or indicates the MTU(Maximum Transfer Unit) of Socket n. - */ -#define Sn_MSSR(N) WIZCHIP_SREG_ADDR(N, 0x0012) - -// Reserved (_W5500_IO_BASE_ + (0x0014 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief IP Type of Service(TOS) Register(R/W) - * @details @ref Sn_TOS configures the TOS(Type Of Service field in IP Header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TOS(N) WIZCHIP_SREG_ADDR(N, 0x0015) -/** - * @ingroup Socket_register_group - * @brief IP Time to live(TTL) Register(R/W) - * @details @ref Sn_TTL configures the TTL(Time To Live field in IP header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TTL(N) WIZCHIP_SREG_ADDR(N, 0x0016) -// Reserved (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001A << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Receive memory size register(R/W) - * @details @ref Sn_RXBUF_SIZE configures the RX buffer block size of Socket n. - * Socket n RX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data cannot be normally received from a peer. - * Although Socket n RX Buffer Block size is initially configured to 2Kbytes, - * user can re-configure its size using @ref Sn_RXBUF_SIZE. The total sum of @ref Sn_RXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data reception error is occurred. - */ -#define Sn_RXBUF_SIZE(N) WIZCHIP_SREG_ADDR(N, 0x001e) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory size register(R/W) - * @details @ref Sn_TXBUF_SIZE configures the TX buffer block size of Socket n. Socket n TX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data can�t be normally transmitted to a peer. - * Although Socket n TX Buffer Block size is initially configured to 2Kbytes, - * user can be re-configure its size using @ref Sn_TXBUF_SIZE. The total sum of @ref Sn_TXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data transmission error is occurred. - */ -#define Sn_TXBUF_SIZE(N) WIZCHIP_SREG_ADDR(N, 0x001f) - -/** - * @ingroup Socket_register_group - * @brief Transmit free memory size register(R) - * @details @ref Sn_TX_FSR indicates the free size of Socket n TX Buffer Block. It is initialized to the configured size by @ref Sn_TXBUF_SIZE. - * Data bigger than @ref Sn_TX_FSR should not be saved in the Socket n TX Buffer because the bigger data overwrites the previous saved data not yet sent. - * Therefore, check before saving the data to the Socket n TX Buffer, and if data is equal or smaller than its checked size, - * transmit the data with SEND/SEND_MAC command after saving the data in Socket n TX buffer. But, if data is bigger than its checked size, - * transmit the data after dividing into the checked size and saving in the Socket n TX buffer. - */ -#define Sn_TX_FSR(N) WIZCHIP_SREG_ADDR(N, 0x0020) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory read pointer register address(R) - * @details @ref Sn_TX_RD is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP. - * After its initialization, it is auto-increased by SEND command. - * SEND command transmits the saved data from the current @ref Sn_TX_RD to the @ref Sn_TX_WR in the Socket n TX Buffer. - * After transmitting the saved data, the SEND command increases the @ref Sn_TX_RD as same as the @ref Sn_TX_WR. - * If its increment value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_TX_RD(N) WIZCHIP_SREG_ADDR(N, 0x0022) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory write pointer register address(R/W) - * @details @ref Sn_TX_WR is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP.\n - * It should be read or be updated like as follows.\n - * 1. Read the starting address for saving the transmitting data.\n - * 2. Save the transmitting data from the starting address of Socket n TX buffer.\n - * 3. After saving the transmitting data, update @ref Sn_TX_WR to the increased value as many as transmitting data size. - * If the increment value exceeds the maximum value 0xFFFF(greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value.\n - * 4. Transmit the saved data in Socket n TX Buffer by using SEND/SEND command - */ -#define Sn_TX_WR(N) WIZCHIP_SREG_ADDR(N, 0x0024) - -/** - * @ingroup Socket_register_group - * @brief Received data size register(R) - * @details @ref Sn_RX_RSR indicates the data size received and saved in Socket n RX Buffer. - * @ref Sn_RX_RSR does not exceed the @ref Sn_RXBUF_SIZE and is calculated as the difference between - * �Socket n RX Write Pointer (@ref Sn_RX_WR)and �Socket n RX Read Pointer (@ref Sn_RX_RD) - */ -#define Sn_RX_RSR(N) WIZCHIP_SREG_ADDR(N, 0x0026) - -/** - * @ingroup Socket_register_group - * @brief Read point of Receive memory(R/W) - * @details @ref Sn_RX_RD is initialized by OPEN command. Make sure to be read or updated as follows.\n - * 1. Read the starting save address of the received data.\n - * 2. Read data from the starting address of Socket n RX Buffer.\n - * 3. After reading the received data, Update @ref Sn_RX_RD to the increased value as many as the reading size. - * If the increment value exceeds the maximum value 0xFFFF, that is, is greater than 0x10000 and the carry bit occurs, - * update with the lower 16bits value ignored the carry bit.\n - * 4. Order RECV command is for notifying the updated @ref Sn_RX_RD to W5500. - */ -#define Sn_RX_RD(N) WIZCHIP_SREG_ADDR(N, 0x0028) - -/** - * @ingroup Socket_register_group - * @brief Write point of Receive memory(R) - * @details @ref Sn_RX_WR is initialized by OPEN command and it is auto-increased by the data reception. - * If the increased value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_RX_WR(N) WIZCHIP_SREG_ADDR(N, 0x002a) - -/** - * @ingroup Socket_register_group - * @brief socket interrupt mask register(R) - * @details @ref Sn_IMR masks the interrupt of Socket n. - * Each bit corresponds to each bit of @ref Sn_IR. When a Socket n Interrupt is occurred and the corresponding bit of @ref Sn_IMR is - * the corresponding bit of @ref Sn_IR becomes When both the corresponding bit of @ref Sn_IMR and @ref Sn_IR are and the n-th bit of @ref IR is - * Host is interrupted by asserted INTn PIN to low. - */ -//#define Sn_IMR(N) (_W5500_IO_BASE_ + (0x002C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Fragment field value in IP header register(R/W) - * @details @ref Sn_FRAG configures the FRAG(Fragment field in IP header). - */ -//#define Sn_FRAG(N) (_W5500_IO_BASE_ + (0x002D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Keep Alive Timer register(R/W) - * @details @ref Sn_KPALVTR configures the transmitting timer of �KEEP ALIVE(KA)packet of SOCKETn. It is valid only in TCP mode, - * and ignored in other modes. The time unit is 5s. - * KA packet is transmittable after @ref Sn_SR is changed to SOCK_ESTABLISHED and after the data is transmitted or received to/from a peer at least once. - * In case of '@ref Sn_KPALVTR > 0', W5500 automatically transmits KA packet after time-period for checking the TCP connection (Auto-keepalive-process). - * In case of '@ref Sn_KPALVTR = 0', Auto-keep-alive-process will not operate, - * and KA packet can be transmitted by SEND_KEEP command by the host (Manual-keep-alive-process). - * Manual-keep-alive-process is ignored in case of '@ref Sn_KPALVTR > 0'. - */ -//#define Sn_KPALVTR(N) (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -//#define Sn_TSR(N) (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - - -//----------------------------- W5500 Register values ----------------------------- - -/* MODE register values */ -/** - * @brief Reset - * @details If this bit is All internal registers will be initialized. It will be automatically cleared as after S/W reset. - */ -#define MR_RST 0x80 - -/** - * @brief Wake on LAN - * @details 0 : Disable WOL mode\n - * 1 : Enable WOL mode\n - * If WOL mode is enabled and the received magic packet over UDP has been normally processed, the Interrupt PIN (INTn) asserts to low. - * When using WOL mode, the UDP Socket should be opened with any source port number. (Refer to Socket n Mode Register (@ref Sn_MR) for opening Socket.) - * @note The magic packet over UDP supported by W5500 consists of 6 bytes synchronization stream (xFFFFFFFFFFFF and - * 16 times Target MAC address stream in UDP payload. The options such like password are ignored. You can use any UDP source port number for WOL mode. - */ -#define MR_WOL 0x20 - -/** - * @brief Ping block - * @details 0 : Disable Ping block\n - * 1 : Enable Ping block\n - * If the bit is it blocks the response to a ping request. - */ -#define MR_PB 0x10 - -/** - * @brief Enable PPPoE - * @details 0 : DisablePPPoE mode\n - * 1 : EnablePPPoE mode\n - * If you use ADSL, this bit should be - */ -#define MR_PPPOE 0x08 - -/** - * @brief Enable UDP_FORCE_ARP CHECHK - * @details 0 : Disable Force ARP mode\n - * 1 : Enable Force ARP mode\n - * In Force ARP mode, It forces on sending ARP Request whenever data is sent. - */ -#define MR_FARP 0x02 - -/* IR register values */ -/** - * @brief Check IP conflict. - * @details Bit is set as when own source IP address is same with the sender IP address in the received ARP request. - */ -#define IR_CONFLICT 0x80 - -/** - * @brief Get the destination unreachable message in UDP sending. - * @details When receiving the ICMP (Destination port unreachable) packet, this bit is set as - * When this bit is Destination Information such as IP address and Port number may be checked with the corresponding @ref UIPR & @ref UPORTR. - */ -#define IR_UNREACH 0x40 - -/** - * @brief Get the PPPoE close message. - * @details When PPPoE is disconnected during PPPoE mode, this bit is set. - */ -#define IR_PPPoE 0x20 - -/** - * @brief Get the magic packet interrupt. - * @details When WOL mode is enabled and receives the magic packet over UDP, this bit is set. - */ -#define IR_MP 0x10 - - -/* PHYCFGR register value */ -#define PHYCFGR_RST ~(1<<7) //< For PHY reset, must operate AND mask. -#define PHYCFGR_OPMD (1<<6) // Configre PHY with OPMDC value -#define PHYCFGR_OPMDC_ALLA (7<<3) -#define PHYCFGR_OPMDC_PDOWN (6<<3) -#define PHYCFGR_OPMDC_NA (5<<3) -#define PHYCFGR_OPMDC_100FA (4<<3) -#define PHYCFGR_OPMDC_100F (3<<3) -#define PHYCFGR_OPMDC_100H (2<<3) -#define PHYCFGR_OPMDC_10F (1<<3) -#define PHYCFGR_OPMDC_10H (0<<3) -#define PHYCFGR_DPX_FULL (1<<2) -#define PHYCFGR_DPX_HALF (0<<2) -#define PHYCFGR_SPD_100 (1<<1) -#define PHYCFGR_SPD_10 (0<<1) -#define PHYCFGR_LNK_ON (1<<0) -#define PHYCFGR_LNK_OFF (0<<0) - -// PHYSTATUS register -#define PHYSTATUS_POWERDOWN (0x08) -#define PHYSTATUS_LINK (0x20) - -/* IMR register values */ -/** - * @brief IP Conflict Interrupt Mask. - * @details 0: Disable IP Conflict Interrupt\n - * 1: Enable IP Conflict Interrupt - */ -#define IM_IR7 0x80 - -/** - * @brief Destination unreachable Interrupt Mask. - * @details 0: Disable Destination unreachable Interrupt\n - * 1: Enable Destination unreachable Interrupt - */ -#define IM_IR6 0x40 - -/** - * @brief PPPoE Close Interrupt Mask. - * @details 0: Disable PPPoE Close Interrupt\n - * 1: Enable PPPoE Close Interrupt - */ -#define IM_IR5 0x20 - -/** - * @brief Magic Packet Interrupt Mask. - * @details 0: Disable Magic Packet Interrupt\n - * 1: Enable Magic Packet Interrupt - */ -#define IM_IR4 0x10 - -/* Sn_MR Default values */ -/** - * @brief Support UDP Multicasting - * @details 0 : disable Multicasting\n - * 1 : enable Multicasting\n - * This bit is applied only during UDP mode(P[3:0] = 010.\n - * To use multicasting, @ref Sn_DIPR & @ref Sn_DPORT should be respectively configured with the multicast group IP address & port number - * before Socket n is opened by OPEN command of @ref Sn_CR. - */ -#define Sn_MR_MULTI 0x80 - -/** - * @brief Broadcast block in UDP Multicasting. - * @details 0 : disable Broadcast Blocking\n - * 1 : enable Broadcast Blocking\n - * This bit blocks to receive broadcasting packet during UDP mode(P[3:0] = 010.\m - * In addition, This bit does when MACRAW mode(P[3:0] = 100 - */ -//#define Sn_MR_BCASTB 0x40 - -/** - * @brief No Delayed Ack(TCP), Multicast flag - * @details 0 : Disable No Delayed ACK option\n - * 1 : Enable No Delayed ACK option\n - * This bit is applied only during TCP mode (P[3:0] = 001.\n - * When this bit is It sends the ACK packet without delay as soon as a Data packet is received from a peer.\n - * When this bit is It sends the ACK packet after waiting for the timeout time configured by @ref RTR. - */ -#define Sn_MR_ND 0x20 - -/** - * @brief Unicast Block in UDP Multicasting - * @details 0 : disable Unicast Blocking\n - * 1 : enable Unicast Blocking\n - * This bit blocks receiving the unicast packet during UDP mode(P[3:0] = 010 and MULTI = - */ -//#define Sn_MR_UCASTB 0x10 - -/** - * @brief MAC LAYER RAW SOCK - * @details This configures the protocol mode of Socket n. - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR_MACRAW 0x04 - -#define Sn_MR_IPRAW 0x03 /**< IP LAYER RAW SOCK */ - -/** - * @brief UDP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_UDP 0x02 - -/** - * @brief TCP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_TCP 0x01 - -/** - * @brief Unused socket - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_CLOSE 0x00 - -/* Sn_MR values used with Sn_MR_MACRAW */ -/** - * @brief MAC filter enable in @ref Sn_MR_MACRAW mode - * @details 0 : disable MAC Filtering\n - * 1 : enable MAC Filtering\n - * This bit is applied only during MACRAW mode(P[3:0] = 100.\n - * When set as W5500 can only receive broadcasting packet or packet sent to itself. - * When this bit is W5500 can receive all packets on Ethernet. - * If user wants to implement Hybrid TCP/IP stack, - * it is recommended that this bit is set as for reducing host overhead to process the all received packets. - */ -#define Sn_MR_MFEN Sn_MR_MULTI - -/** - * @brief Multicast Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : using IGMP version 2\n - * 1 : using IGMP version 1\n - * This bit is applied only during UDP mode(P[3:0] = 010 and MULTI = - * It configures the version for IGMP messages (Join/Leave/Report). - */ -#define Sn_MR_MMB Sn_MR_ND - -/** - * @brief IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : disable IPv6 Blocking\n - * 1 : enable IPv6 Blocking\n - * This bit is applied only during MACRAW mode (P[3:0] = 100. It blocks to receiving the IPv6 packet. - */ -#define Sn_MR_MIP6B Sn_MR_UCASTB - -/* Sn_MR value used with Sn_MR_UDP & Sn_MR_MULTI */ -/** - * @brief IGMP version used in UDP mulitcasting - * @details 0 : disable Multicast Blocking\n - * 1 : enable Multicast Blocking\n - * This bit is applied only when MACRAW mode(P[3:0] = 100. It blocks to receive the packet with multicast MAC address. - */ -#define Sn_MR_MC Sn_MR_ND - -/* Sn_MR alternate values */ -/** - * @brief For Berkeley Socket API - */ -#define SOCK_STREAM Sn_MR_TCP - -/** - * @brief For Berkeley Socket API - */ -#define SOCK_DGRAM Sn_MR_UDP - - -/* Sn_CR values */ -/** - * @brief Initialize or open socket - * @details Socket n is initialized and opened according to the protocol selected in Sn_MR(P3:P0). - * The table below shows the value of @ref Sn_SR corresponding to @ref Sn_MR.\n - * - * - * - * - * - * - *
\b Sn_MR (P[3:0]) \b Sn_SR
Sn_MR_CLOSE (000
Sn_MR_TCP (001 SOCK_INIT (0x13)
Sn_MR_UDP (010 SOCK_UDP (0x22)
S0_MR_MACRAW (100 SOCK_MACRAW (0x02)
- */ -#define Sn_CR_OPEN 0x01 - -/** - * @brief Wait connection request in TCP mode(Server mode) - * @details This is valid only in TCP mode (Sn_MR(P3:P0) = Sn_MR_TCP). - * In this mode, Socket n operates as a �TCP serverand waits for connection-request (SYN packet) from any �TCP client - * The @ref Sn_SR changes the state from SOCK_INIT to SOCKET_LISTEN. - * When a �TCP clientconnection request is successfully established, - * the @ref Sn_SR changes from SOCK_LISTEN to SOCK_ESTABLISHED and the Sn_IR(0) becomes - * But when a �TCP clientconnection request is failed, Sn_IR(3) becomes and the status of @ref Sn_SR changes to SOCK_CLOSED. - */ -#define Sn_CR_LISTEN 0x02 - -/** - * @brief Send connection request in TCP mode(Client mode) - * @details To connect, a connect-request (SYN packet) is sent to b>TCP serverconfigured by @ref Sn_DIPR & Sn_DPORT(destination address & port). - * If the connect-request is successful, the @ref Sn_SR is changed to @ref SOCK_ESTABLISHED and the Sn_IR(0) becomes \n\n - * The connect-request fails in the following three cases.\n - * 1. When a @b ARPTO occurs (@ref Sn_IR[3] = ) because destination hardware address is not acquired through the ARP-process.\n - * 2. When a @b SYN/ACK packet is not received and @b TCPTO (Sn_IR(3) = )\n - * 3. When a @b RST packet is received instead of a @b SYN/ACK packet. In these cases, @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note This is valid only in TCP mode and operates when Socket n acts as b>TCP client - */ -#define Sn_CR_CONNECT 0x04 - -/** - * @brief Send closing request in TCP mode - * @details Regardless of b>TCP serveror b>TCP client the DISCON command processes the disconnect-process (b>Active closeor b>Passive close.\n - * @par Active close - * it transmits disconnect-request(FIN packet) to the connected peer\n - * @par Passive close - * When FIN packet is received from peer, a FIN packet is replied back to the peer.\n - * @details When the disconnect-process is successful (that is, FIN/ACK packet is received successfully), @ref Sn_SR is changed to @ref SOCK_CLOSED.\n - * Otherwise, TCPTO occurs (Sn_IR(3)=)= and then @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note Valid only in TCP mode. - */ -#define Sn_CR_DISCON 0x08 - -/** - * @brief Close socket - * @details Sn_SR is changed to @ref SOCK_CLOSED. - */ -#define Sn_CR_CLOSE 0x10 - -/** - * @brief Update TX buffer pointer and send data - * @details SEND transmits all the data in the Socket n TX buffer.\n - * For more details, please refer to Socket n TX Free Size Register (@ref Sn_TX_FSR), Socket n, - * TX Write Pointer Register(@ref Sn_TX_WR), and Socket n TX Read Pointer Register(@ref Sn_TX_RD). - */ -#define Sn_CR_SEND 0x20 - -/** - * @brief Send data with MAC address, so without ARP process - * @details The basic operation is same as SEND.\n - * Normally SEND transmits data after destination hardware address is acquired by the automatic ARP-process(Address Resolution Protocol).\n - * But SEND_MAC transmits data without the automatic ARP-process.\n - * In this case, the destination hardware address is acquired from @ref Sn_DHAR configured by host, instead of APR-process. - * @note Valid only in UDP mode. - */ -#define Sn_CR_SEND_MAC 0x21 - -/** - * @brief Send keep alive message - * @details It checks the connection status by sending 1byte keep-alive packet.\n - * If the peer can not respond to the keep-alive packet during timeout time, the connection is terminated and the timeout interrupt will occur. - * @note Valid only in TCP mode. - */ -#define Sn_CR_SEND_KEEP 0x22 - -/** - * @brief Update RX buffer pointer and receive data - * @details RECV completes the processing of the received data in Socket n RX Buffer by using a RX read pointer register (@ref Sn_RX_RD).\n - * For more details, refer to Socket n RX Received Size Register (@ref Sn_RX_RSR), Socket n RX Write Pointer Register (@ref Sn_RX_WR), - * and Socket n RX Read Pointer Register (@ref Sn_RX_RD). - */ -#define Sn_CR_RECV 0x40 - -/* Sn_IR values */ -/** - * @brief SEND_OK Interrupt - * @details This is issued when SEND command is completed. - */ -#define Sn_IR_SENDOK 0x10 - -/** - * @brief TIMEOUT Interrupt - * @details This is issued when ARPTO or TCPTO occurs. - */ -#define Sn_IR_TIMEOUT 0x08 - -/** - * @brief RECV Interrupt - * @details This is issued whenever data is received from a peer. - */ -#define Sn_IR_RECV 0x04 - -/** - * @brief DISCON Interrupt - * @details This is issued when FIN or FIN/ACK packet is received from a peer. - */ -#define Sn_IR_DISCON 0x02 - -/** - * @brief CON Interrupt - * @details This is issued one time when the connection with peer is successful and then @ref Sn_SR is changed to @ref SOCK_ESTABLISHED. - */ -#define Sn_IR_CON 0x01 - -/* Sn_SR values */ -/** - * @brief Closed - * @details This indicates that Socket n is released.\N - * When DICON, CLOSE command is ordered, or when a timeout occurs, it is changed to @ref SOCK_CLOSED regardless of previous status. - */ -#define SOCK_CLOSED 0x00 - -/** - * @brief Initiate state - * @details This indicates Socket n is opened with TCP mode.\N - * It is changed to @ref SOCK_INIT when Sn_MR(P[3:0]) = 001and OPEN command is ordered.\N - * After @ref SOCK_INIT, user can use LISTEN /CONNECT command. - */ -#define SOCK_INIT 0x13 - -/** - * @brief Listen state - * @details This indicates Socket n is operating as b>TCP servermode and waiting for connection-request (SYN packet) from a peer (b>TCP client.\n - * It will change to @ref SOCK_ESTALBLISHED when the connection-request is successfully accepted.\n - * Otherwise it will change to @ref SOCK_CLOSED after TCPTO occurred (Sn_IR(TIMEOUT) = . - */ -#define SOCK_LISTEN 0x14 - -/** - * @brief Connection state - * @details This indicates Socket n sent the connect-request packet (SYN packet) to a peer.\n - * It is temporarily shown when @ref Sn_SR is changed from @ref SOCK_INIT to @ref SOCK_ESTABLISHED by CONNECT command.\n - * If connect-accept(SYN/ACK packet) is received from the peer at SOCK_SYNSENT, it changes to @ref SOCK_ESTABLISHED.\n - * Otherwise, it changes to @ref SOCK_CLOSED after TCPTO (@ref Sn_IR[TIMEOUT] = is occurred. - */ -#define SOCK_SYNSENT 0x15 - -/** - * @brief Connection state - * @details It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer.\n - * If socket n sends the response (SYN/ACK packet) to the peer successfully, it changes to @ref SOCK_ESTABLISHED. \n - * If not, it changes to @ref SOCK_CLOSED after timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_SYNRECV 0x16 - -/** - * @brief Success to connect - * @details This indicates the status of the connection of Socket n.\n - * It changes to @ref SOCK_ESTABLISHED when the b>TCP SERVERprocessed the SYN packet from the b>TCP CLIENTduring @ref SOCK_LISTEN, or - * when the CONNECT command is successful.\n - * During @ref SOCK_ESTABLISHED, DATA packet can be transferred using SEND or RECV command. - */ -#define SOCK_ESTABLISHED 0x17 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_FIN_WAIT 0x18 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_CLOSING 0x1A - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_TIME_WAIT 0x1B - -/** - * @brief Closing state - * @details This indicates Socket n received the disconnect-request (FIN packet) from the connected peer.\n - * This is half-closing status, and data can be transferred.\n - * For full-closing, DISCON command is used. But For just-closing, CLOSE command is used. - */ -#define SOCK_CLOSE_WAIT 0x1C - -/** - * @brief Closing state - * @details This indicates Socket n is waiting for the response (FIN/ACK packet) to the disconnect-request (FIN packet) by passive-close.\n - * It changes to @ref SOCK_CLOSED when Socket n received the response successfully, or when timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_LAST_ACK 0x1D - -/** - * @brief UDP socket - * @details This indicates Socket n is opened in UDP mode(Sn_MR(P[3:0]) = 010.\n - * It changes to SOCK_UPD when Sn_MR(P[3:0]) = 010 and OPEN command is ordered.\n - * Unlike TCP mode, data can be transfered without the connection-process. - */ -#define SOCK_UDP 0x22 - -//#define SOCK_IPRAW 0x32 /**< IP raw mode socket */ - -/** - * @brief MAC raw mode socket - * @details This indicates Socket 0 is opened in MACRAW mode (S0_MR(P[3:0]) = 100and is valid only in Socket 0.\n - * It changes to SOCK_MACRAW when S0_MR(P[3:0] = 100and OPEN command is ordered.\n - * Like UDP mode socket, MACRAW mode Socket 0 can transfer a MAC packet (Ethernet frame) without the connection-process. - */ -#define SOCK_MACRAW 0x42 - -//#define SOCK_PPPOE 0x5F - -/* IP PROTOCOL */ -#define IPPROTO_IP 0 //< Dummy for IP -#define IPPROTO_ICMP 1 //< Control message protocol -#define IPPROTO_IGMP 2 //< Internet group management protocol -#define IPPROTO_GGP 3 //< Gateway^2 (deprecated) -#define IPPROTO_TCP 6 //< TCP -#define IPPROTO_PUP 12 //< PUP -#define IPPROTO_UDP 17 //< UDP -#define IPPROTO_IDP 22 //< XNS idp -#define IPPROTO_ND 77 //< UNOFFICIAL net disk protocol -#define IPPROTO_RAW 255 //< Raw IP packet - - -/** - * @brief Enter a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n \n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt.\n - * In OS environment, You can replace it to critical section api supported by OS. - * - * \sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * \sa WIZCHIP_CRITICAL_EXIT() - */ -#define WIZCHIP_CRITICAL_ENTER() WIZCHIP.CRIS._enter() - -/** - * @brief Exit a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n\n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt. \n - * In OS environment, You can replace it to critical section api supported by OS. - * - * @sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * @sa WIZCHIP_CRITICAL_ENTER() - */ -#ifdef _exit -#undef _exit -#endif -#define WIZCHIP_CRITICAL_EXIT() WIZCHIP.CRIS._exit() - - - -//////////////////////// -// Basic I/O Function // -//////////////////////// - -/** - * @ingroup Basic_IO_function - * @brief It reads 1 byte value from a register. - * @param AddrSel Register address - * @return The value of register - */ -uint8_t WIZCHIP_READ (uint32_t AddrSel); - -/** - * @ingroup Basic_IO_function - * @brief It writes 1 byte value to a register. - * @param AddrSel Register address - * @param wb Write data - * @return void - */ -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb ); - -/** - * @ingroup Basic_IO_function - * @brief It reads sequence data from registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to read data - * @param len Data length - */ -void WIZCHIP_READ_BUF (uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It writes sequence data to registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to write data - * @param len Data length - */ -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -///////////////////////////////// -// Common Register I/O function // -///////////////////////////////// -/** - * @ingroup Common_register_access_function - * @brief Set Mode Register - * @param (uint8_t)mr The value to be set. - * @sa getMR() - */ -#define setMR(mr) \ - WIZCHIP_WRITE(MR,mr) - - -/** - * @ingroup Common_register_access_function - * @brief Get Mode Register - * @return uint8_t. The value of Mode register. - * @sa setMR() - */ -#define getMR() \ - WIZCHIP_READ(MR) - -/** - * @ingroup Common_register_access_function - * @brief Set gateway IP address - * @param (uint8_t*)gar Pointer variable to set gateway IP address. It should be allocated 4 bytes. - * @sa getGAR() - */ -#define setGAR(gar) \ - WIZCHIP_WRITE_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Get gateway IP address - * @param (uint8_t*)gar Pointer variable to get gateway IP address. It should be allocated 4 bytes. - * @sa setGAR() - */ -#define getGAR(gar) \ - WIZCHIP_READ_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Set subnet mask address - * @param (uint8_t*)subr Pointer variable to set subnet mask address. It should be allocated 4 bytes. - * @sa getSUBR() - */ -#define setSUBR(subr) \ - WIZCHIP_WRITE_BUF(SUBR, subr,4) - - -/** - * @ingroup Common_register_access_function - * @brief Get subnet mask address - * @param (uint8_t*)subr Pointer variable to get subnet mask address. It should be allocated 4 bytes. - * @sa setSUBR() - */ -#define getSUBR(subr) \ - WIZCHIP_READ_BUF(SUBR, subr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set local MAC address - * @param (uint8_t*)shar Pointer variable to set local MAC address. It should be allocated 6 bytes. - * @sa getSHAR() - */ -#define setSHAR(shar) \ - WIZCHIP_WRITE_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local MAC address - * @param (uint8_t*)shar Pointer variable to get local MAC address. It should be allocated 6 bytes. - * @sa setSHAR() - */ -#define getSHAR(shar) \ - WIZCHIP_READ_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set local IP address - * @param (uint8_t*)sipr Pointer variable to set local IP address. It should be allocated 4 bytes. - * @sa getSIPR() - */ -#define setSIPR(sipr) \ - WIZCHIP_WRITE_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)sipr Pointer variable to get local IP address. It should be allocated 4 bytes. - * @sa setSIPR() - */ -#define getSIPR(sipr) \ - WIZCHIP_READ_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set INTLEVEL register - * @param (uint16_t)intlevel Value to set @ref INTLEVEL register. - * @sa getINTLEVEL() - */ -// dpgeorge: not yet implemented -#define setINTLEVEL(intlevel) (void)intlevel -#if 0 -#define setINTLEVEL(intlevel) {\ - WIZCHIP_WRITE(INTLEVEL, (uint8_t)(intlevel >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(INTLEVEL,1), (uint8_t) intlevel); \ - } -#endif - - -/** - * @ingroup Common_register_access_function - * @brief Get INTLEVEL register - * @return uint16_t. Value of @ref INTLEVEL register. - * @sa setINTLEVEL() - */ -// dpgeorge: not yet implemented -#define getINTLEVEL() (0) -#if 0 -#define getINTLEVEL() \ - ((WIZCHIP_READ(INTLEVEL) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(INTLEVEL,1))) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Set @ref IR register - * @param (uint8_t)ir Value to set @ref IR register. - * @sa getIR() - */ -#define setIR(ir) \ - WIZCHIP_WRITE(IR, (ir & 0xF0)) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IR register - * @return uint8_t. Value of @ref IR register. - * @sa setIR() - */ -#define getIR() \ - (WIZCHIP_READ(IR) & 0xF0) -/** - * @ingroup Common_register_access_function - * @brief Set @ref IMR register - * @param (uint8_t)imr Value to set @ref IMR register. - * @sa getIMR() - */ -#define setIMR(imr) \ - WIZCHIP_WRITE(IMR, imr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IMR register - * @return uint8_t. Value of @ref IMR register. - * @sa setIMR() - */ -#define getIMR() \ - WIZCHIP_READ(IMR) - - -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIR register - * @param (uint8_t)sir Value to set @ref SIR register. - * @sa getSIR() - */ -// dpgeorge: not yet implemented -#define setSIR(sir) ((void)sir) -#if 0 -#define setSIR(sir) \ - WIZCHIP_WRITE(SIR, sir) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIR register - * @return uint8_t. Value of @ref SIR register. - * @sa setSIR() - */ -// dpgeorge: not yet implemented -#define getSIR() (0) -#if 0 -#define getSIR() \ - WIZCHIP_READ(SIR) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIMR register - * @param (uint8_t)simr Value to set @ref SIMR register. - * @sa getSIMR() - */ -// dpgeorge: not yet implemented -#define setSIMR(simr) ((void)simr) -#if 0 -#define setSIMR(simr) \ - WIZCHIP_WRITE(SIMR, simr) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIMR register - * @return uint8_t. Value of @ref SIMR register. - * @sa setSIMR() - */ -// dpgeorge: not yet implemented -#define getSIMR() (0) -#if 0 -#define getSIMR() \ - WIZCHIP_READ(SIMR) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RTR register - * @param (uint16_t)rtr Value to set @ref RTR register. - * @sa getRTR() - */ -#define setRTR(rtr) {\ - WIZCHIP_WRITE(RTR, (uint8_t)(rtr >> 8)); \ - WIZCHIP_WRITE(RTR + 1, (uint8_t) rtr); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RTR register - * @return uint16_t. Value of @ref RTR register. - * @sa setRTR() - */ -#define getRTR() \ - ((WIZCHIP_READ(RTR) << 8) + WIZCHIP_READ(RTR + 1)) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RCR register - * @param (uint8_t)rcr Value to set @ref RCR register. - * @sa getRCR() - */ -#define setRCR(rcr) \ - WIZCHIP_WRITE(RCR, rcr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RCR register - * @return uint8_t. Value of @ref RCR register. - * @sa setRCR() - */ -#define getRCR() \ - WIZCHIP_READ(RCR) - -//================================================== test done =========================================================== - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PTIMER register - * @param (uint8_t)ptimer Value to set @ref PTIMER register. - * @sa getPTIMER() - */ -#define setPTIMER(ptimer) \ - WIZCHIP_WRITE(PTIMER, ptimer) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PTIMER register - * @return uint8_t. Value of @ref PTIMER register. - * @sa setPTIMER() - */ -#define getPTIMER() \ - WIZCHIP_READ(PTIMER) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMAGIC register - * @param (uint8_t)pmagic Value to set @ref PMAGIC register. - * @sa getPMAGIC() - */ -#define setPMAGIC(pmagic) \ - WIZCHIP_WRITE(PMAGIC, pmagic) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMAGIC register - * @return uint8_t. Value of @ref PMAGIC register. - * @sa setPMAGIC() - */ -#define getPMAGIC() \ - WIZCHIP_READ(PMAGIC) - -/** - * @ingroup Common_register_access_function - * @brief Set PHAR address - * @param (uint8_t*)phar Pointer variable to set PPP destination MAC register address. It should be allocated 6 bytes. - * @sa getPHAR() - */ -#if 0 -#define setPHAR(phar) \ - WIZCHIP_WRITE_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)phar Pointer variable to PPP destination MAC register address. It should be allocated 6 bytes. - * @sa setPHAR() - */ -#define getPHAR(phar) \ - WIZCHIP_READ_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PSID register - * @param (uint16_t)psid Value to set @ref PSID register. - * @sa getPSID() - */ -#define setPSID(psid) {\ - WIZCHIP_WRITE(PSID, (uint8_t)(psid >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PSID,1), (uint8_t) psid); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PSID register - * @return uint16_t. Value of @ref PSID register. - * @sa setPSID() - */ -//uint16_t getPSID(void); -#define getPSID() \ - ((WIZCHIP_READ(PSID) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PSID,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMRU register - * @param (uint16_t)pmru Value to set @ref PMRU register. - * @sa getPMRU() - */ -#define setPMRU(pmru) { \ - WIZCHIP_WRITE(PMRU, (uint8_t)(pmru>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PMRU,1), (uint8_t) pmru); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMRU register - * @return uint16_t. Value of @ref PMRU register. - * @sa setPMRU() - */ -#define getPMRU() \ - ((WIZCHIP_READ(PMRU) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PMRU,1))) - -/** - * @ingroup Common_register_access_function - * @brief Get unreachable IP address - * @param (uint8_t*)uipr Pointer variable to get unreachable IP address. It should be allocated 4 bytes. - */ -#define getUIPR(uipr) \ - WIZCHIP_READ_BUF(UIPR,uipr,6) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref UPORTR register - * @return uint16_t. Value of @ref UPORTR register. - */ -#define getUPORTR() \ - ((WIZCHIP_READ(UPORTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(UPORTR,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PHYCFGR register - * @param (uint8_t)phycfgr Value to set @ref PHYCFGR register. - * @sa getPHYCFGR() - */ -#define setPHYCFGR(phycfgr) \ - WIZCHIP_WRITE(PHYCFGR, phycfgr) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PHYCFGR register - * @return uint8_t. Value of @ref PHYCFGR register. - * @sa setPHYCFGR() - */ -#define getPHYSTATUS() \ - WIZCHIP_READ(PHYSTATUS) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref VERSIONR register - * @return uint8_t. Value of @ref VERSIONR register. - */ -/* -#define getVERSIONR() \ - WIZCHIP_READ(VERSIONR) - */ -///////////////////////////////////// - -/////////////////////////////////// -// Socket N register I/O function // -/////////////////////////////////// -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)mr Value to set @ref Sn_MR - * @sa getSn_MR() - */ -#define setSn_MR(sn, mr) \ - WIZCHIP_WRITE(Sn_MR(sn),mr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_MR. - * @sa setSn_MR() - */ -#define getSn_MR(sn) \ - WIZCHIP_READ(Sn_MR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)cr Value to set @ref Sn_CR - * @sa getSn_CR() - */ -#define setSn_CR(sn, cr) \ - WIZCHIP_WRITE(Sn_CR(sn), cr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_CR. - * @sa setSn_CR() - */ -#define getSn_CR(sn) \ - WIZCHIP_READ(Sn_CR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ir Value to set @ref Sn_IR - * @sa getSn_IR() - */ -#define setSn_IR(sn, ir) \ - WIZCHIP_WRITE(Sn_IR(sn), (ir & 0x1F)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IR. - * @sa setSn_IR() - */ -#define getSn_IR(sn) \ - (WIZCHIP_READ(Sn_IR(sn)) & 0x1F) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)imr Value to set @ref Sn_IMR - * @sa getSn_IMR() - */ -// dpgeorge: not yet implemented -#define setSn_IMR(sn, imr) (void)sn; (void)imr -#if 0 -#define setSn_IMR(sn, imr) \ - WIZCHIP_WRITE(Sn_IMR(sn), (imr & 0x1F)) -#endif - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IMR. - * @sa setSn_IMR() - */ -// dpgeorge: not yet implemented -#define getSn_IMR(sn) (0) -#if 0 -#define getSn_IMR(sn) \ - (WIZCHIP_READ(Sn_IMR(sn)) & 0x1F) -#endif - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_SR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_SR. - */ -#define getSn_SR(sn) \ - WIZCHIP_READ(Sn_SR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)port Value to set @ref Sn_PORT. - * @sa getSn_PORT() - */ -#define setSn_PORT(sn, port) { \ - WIZCHIP_WRITE(Sn_PORT(sn), (uint8_t)(port >> 8)); \ - WIZCHIP_WRITE(Sn_PORT(sn) + 1, (uint8_t) port); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_PORT. - * @sa setSn_PORT() - */ -#define getSn_PORT(sn) \ - ((WIZCHIP_READ(Sn_PORT(sn)) << 8) | WIZCHIP_READ(Sn_PORT(sn) + 1)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DHAR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to set socket n destination hardware address. It should be allocated 6 bytes. - * @sa getSn_DHAR() - */ -#define setSn_DHAR(sn, dhar) \ - WIZCHIP_WRITE_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to get socket n destination hardware address. It should be allocated 6 bytes. - * @sa setSn_DHAR() - */ -#define getSn_DHAR(sn, dhar) \ - WIZCHIP_READ_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to set socket n destination IP address. It should be allocated 4 bytes. - * @sa getSn_DIPR() - */ -#define setSn_DIPR(sn, dipr) \ - WIZCHIP_WRITE_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to get socket n destination IP address. It should be allocated 4 bytes. - * @sa SetSn_DIPR() - */ -#define getSn_DIPR(sn, dipr) \ - WIZCHIP_READ_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)dport Value to set @ref Sn_DPORT - * @sa getSn_DPORT() - */ -#define setSn_DPORT(sn, dport) { \ - WIZCHIP_WRITE(Sn_DPORT(sn), (uint8_t) (dport>>8)); \ - WIZCHIP_WRITE(Sn_DPORT(sn) + 1, (uint8_t) dport); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_DPORT. - * @sa setSn_DPORT() - */ -#define getSn_DPORT(sn) \ - ((WIZCHIP_READ(Sn_DPORT(sn)) << 8) + WIZCHIP_READ((Sn_DPORT(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)mss Value to set @ref Sn_MSSR - * @sa setSn_MSSR() - */ -#define setSn_MSSR(sn, mss) { \ - WIZCHIP_WRITE(Sn_MSSR(sn), (uint8_t)(mss>>8)); \ - WIZCHIP_WRITE((Sn_MSSR(sn)+1), (uint8_t) mss); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_MSSR. - * @sa setSn_MSSR() - */ -#define getSn_MSSR(sn) \ - ((WIZCHIP_READ(Sn_MSSR(sn)) << 8) + WIZCHIP_READ((Sn_MSSR(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)tos Value to set @ref Sn_TOS - * @sa getSn_TOS() - */ -#define setSn_TOS(sn, tos) \ - WIZCHIP_WRITE(Sn_TOS(sn), tos) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of Sn_TOS. - * @sa setSn_TOS() - */ -#define getSn_TOS(sn) \ - WIZCHIP_READ(Sn_TOS(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ttl Value to set @ref Sn_TTL - * @sa getSn_TTL() - */ -#define setSn_TTL(sn, ttl) \ - WIZCHIP_WRITE(Sn_TTL(sn), ttl) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TTL. - * @sa setSn_TTL() - */ -#define getSn_TTL(sn) \ - WIZCHIP_READ(Sn_TTL(sn)) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)rxbufsize Value to set @ref Sn_RXBUF_SIZE - * @sa getSn_RXBUF_SIZE() - */ -#define setSn_RXBUF_SIZE(sn, rxbufsize) \ - WIZCHIP_WRITE(Sn_RXBUF_SIZE(sn),rxbufsize) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_RXBUF_SIZE. - * @sa setSn_RXBUF_SIZE() - */ -#define getSn_RXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_RXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)txbufsize Value to set @ref Sn_TXBUF_SIZE - * @sa getSn_TXBUF_SIZE() - */ -#define setSn_TXBUF_SIZE(sn, txbufsize) \ - WIZCHIP_WRITE(Sn_TXBUF_SIZE(sn), txbufsize) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TXBUF_SIZE. - * @sa setSn_TXBUF_SIZE() - */ -#define getSn_TXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_TXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_FSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_FSR. - */ -uint16_t getSn_TX_FSR(uint8_t sn); - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_RD. - */ -#define getSn_TX_RD(sn) \ - ((WIZCHIP_READ(Sn_TX_RD(sn)) << 8) + WIZCHIP_READ((Sn_TX_RD(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)txwr Value to set @ref Sn_TX_WR - * @sa GetSn_TX_WR() - */ -#define setSn_TX_WR(sn, txwr) { \ - WIZCHIP_WRITE(Sn_TX_WR(sn), (uint8_t)(txwr>>8)); \ - WIZCHIP_WRITE((Sn_TX_WR(sn)+1), (uint8_t) txwr); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_WR. - * @sa setSn_TX_WR() - */ -#define getSn_TX_WR(sn) \ - ((WIZCHIP_READ(Sn_TX_WR(sn)) << 8) + WIZCHIP_READ((Sn_TX_WR(sn)+1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_RSR. - */ -uint16_t getSn_RX_RSR(uint8_t sn); - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)rxrd Value to set @ref Sn_RX_RD - * @sa getSn_RX_RD() - */ -#define setSn_RX_RD(sn, rxrd) { \ - WIZCHIP_WRITE(Sn_RX_RD(sn), (uint8_t)(rxrd>>8)); \ - WIZCHIP_WRITE((Sn_RX_RD(sn)+1), (uint8_t) rxrd); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @regurn uint16_t. Value of @ref Sn_RX_RD. - * @sa setSn_RX_RD() - */ -#define getSn_RX_RD(sn) \ - ((WIZCHIP_READ(Sn_RX_RD(sn)) << 8) + WIZCHIP_READ((Sn_RX_RD(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_WR. - */ -#define getSn_RX_WR(sn) \ - ((WIZCHIP_READ(Sn_RX_WR(sn)) << 8) + WIZCHIP_READ((Sn_RX_WR(sn)+1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)frag Value to set @ref Sn_FRAG - * @sa getSn_FRAD() - */ -#if 0 // dpgeorge -#define setSn_FRAG(sn, frag) { \ - WIZCHIP_WRITE(Sn_FRAG(sn), (uint8_t)(frag >>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1), (uint8_t) frag); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_FRAG. - * @sa setSn_FRAG() - */ -#define getSn_FRAG(sn) \ - ((WIZCHIP_READ(Sn_FRAG(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)kpalvt Value to set @ref Sn_KPALVTR - * @sa getSn_KPALVTR() - */ -#define setSn_KPALVTR(sn, kpalvt) \ - WIZCHIP_WRITE(Sn_KPALVTR(sn), kpalvt) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_KPALVTR. - * @sa setSn_KPALVTR() - */ -#define getSn_KPALVTR(sn) \ - WIZCHIP_READ(Sn_KPALVTR(sn)) - -////////////////////////////////////// -#endif - -///////////////////////////////////// -// Sn_TXBUF & Sn_RXBUF IO function // -///////////////////////////////////// -/** - * @brief Gets the max buffer size of socket sn passed as parameter. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n RX max buffer size. - */ -#define getSn_RxMAX(sn) \ - (getSn_RXBUF_SIZE(sn) << 10) - -/** - * @brief Gets the max buffer size of socket sn passed as parameters. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n TX max buffer size. - */ -//uint16_t getSn_TxMAX(uint8_t sn); -#define getSn_TxMAX(sn) \ - (getSn_TXBUF_SIZE(sn) << 10) - -void wiz_init(void); - -/** - * @ingroup Basic_IO_function - * @brief It copies data to internal TX memory - * - * @details This function reads the Tx write pointer register and after that, - * it copies the wizdata(pointer buffer) of the length of len(variable) bytes to internal TX memory - * and updates the Tx write pointer register. - * This function is being called by send() and sendto() function also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to write data - * @param len Data length - * @sa wiz_recv_data() - */ -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It copies data to your buffer from internal RX memory - * - * @details This function read the Rx read pointer register and after that, - * it copies the received data from internal RX memory - * to wizdata(pointer variable) of the length of len(variable) bytes. - * This function is being called by recv() also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to read data - * @param len Data length - * @sa wiz_send_data() - */ -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It discard the received data in RX memory. - * @details It discards the data of the length of len(variable) bytes in internal RX memory. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param len Data length - */ -void wiz_recv_ignore(uint8_t sn, uint16_t len); - -#endif // _W5500_H_ diff --git a/drivers/wiznet5k/ethernet/w5500/w5500.c b/drivers/wiznet5k/ethernet/w5500/w5500.c deleted file mode 100644 index fef08e2e3e..0000000000 --- a/drivers/wiznet5k/ethernet/w5500/w5500.c +++ /dev/null @@ -1,246 +0,0 @@ -//***************************************************************************** -// -//! \file w5500.c -//! \brief W5500 HAL Interface. -//! \version 1.0.1 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.2 -//! 1. Implicit type casting -> Explicit type casting. Refer to M20140501 -//! Fixed the problem on porting into under 32bit MCU -//! Issued by Mathias ClauBen, wizwiki forum ID Think01 and bobh -//! Thank for your interesting and serious advices. -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.0.1 -//! 1. Remove warning -//! 2. WIZCHIP_READ_BUF WIZCHIP_WRITE_BUF in case _WIZCHIP_IO_MODE_SPI_FDM_ -//! for loop optimized(removed). refer to M20131220 -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** -//#include -#include "w5500.h" - -#define _W5500_SPI_VDM_OP_ 0x00 -#define _W5500_SPI_FDM_OP_LEN1_ 0x01 -#define _W5500_SPI_FDM_OP_LEN2_ 0x02 -#define _W5500_SPI_FDM_OP_LEN4_ 0x03 - -//////////////////////////////////////////////////// - -#define LPC_SSP0 (0) - -static void Chip_SSP_ReadFrames_Blocking(int dummy, uint8_t *buf, uint32_t len) { - WIZCHIP.IF.SPI._read_bytes(buf, len); -} - -static void Chip_SSP_WriteFrames_Blocking(int dummy, const uint8_t *buf, uint32_t len) { - WIZCHIP.IF.SPI._write_bytes(buf, len); -} - -uint8_t WIZCHIP_READ(uint32_t AddrSel) -{ - uint8_t ret; - uint8_t spi_data[3]; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_READ_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //ret = WIZCHIP.IF.SPI._read_byte(); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 3); - Chip_SSP_ReadFrames_Blocking(LPC_SSP0, &ret, 1); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); - return ret; -} - -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb ) -{ - uint8_t spi_data[4]; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_WRITE_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //WIZCHIP.IF.SPI._write_byte(wb); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - spi_data[3] = wb; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 4); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_READ_BUF (uint32_t AddrSel, uint8_t* pBuf, uint16_t len) -{ - uint8_t spi_data[3]; - //uint16_t i; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_READ_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //for(i = 0; i < len; i++) - // pBuf[i] = WIZCHIP.IF.SPI._read_byte(); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 3); - Chip_SSP_ReadFrames_Blocking(LPC_SSP0, pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len) -{ - uint8_t spi_data[3]; - //uint16_t i; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_WRITE_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //for(i = 0; i < len; i++) - // WIZCHIP.IF.SPI._write_byte(pBuf[i]); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 3); - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - - -uint16_t getSn_TX_FSR(uint8_t sn) -{ - uint16_t val=0,val1=0; - - do - { - val1 = WIZCHIP_READ(Sn_TX_FSR(sn)); - val1 = (val1 << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_FSR(sn),1)); - if (val1 != 0) - { - val = WIZCHIP_READ(Sn_TX_FSR(sn)); - val = (val << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_FSR(sn),1)); - } - }while (val != val1); - return val; -} - - -uint16_t getSn_RX_RSR(uint8_t sn) -{ - uint16_t val=0,val1=0; - - do - { - val1 = WIZCHIP_READ(Sn_RX_RSR(sn)); - val1 = (val1 << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RSR(sn),1)); - if (val1 != 0) - { - val = WIZCHIP_READ(Sn_RX_RSR(sn)); - val = (val << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RSR(sn),1)); - } - }while (val != val1); - return val; -} - -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len) -{ - uint16_t ptr = 0; - uint32_t addrsel = 0; - - if(len == 0) return; - ptr = getSn_TX_WR(sn); - //M20140501 : implict type casting -> explict type casting - //addrsel = (ptr << 8) + (WIZCHIP_TXBUF_BLOCK(sn) << 3); - addrsel = ((uint32_t)ptr << 8) + (WIZCHIP_TXBUF_BLOCK(sn) << 3); - // - WIZCHIP_WRITE_BUF(addrsel,wizdata, len); - - ptr += len; - setSn_TX_WR(sn,ptr); -} - -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len) -{ - uint16_t ptr = 0; - uint32_t addrsel = 0; - - if(len == 0) return; - ptr = getSn_RX_RD(sn); - //M20140501 : implict type casting -> explict type casting - //addrsel = ((ptr << 8) + (WIZCHIP_RXBUF_BLOCK(sn) << 3); - addrsel = ((uint32_t)ptr << 8) + (WIZCHIP_RXBUF_BLOCK(sn) << 3); - // - WIZCHIP_READ_BUF(addrsel, wizdata, len); - ptr += len; - - setSn_RX_RD(sn,ptr); -} - - -void wiz_recv_ignore(uint8_t sn, uint16_t len) -{ - uint16_t ptr = 0; - - ptr = getSn_RX_RD(sn); - ptr += len; - setSn_RX_RD(sn,ptr); -} diff --git a/drivers/wiznet5k/ethernet/w5500/w5500.h b/drivers/wiznet5k/ethernet/w5500/w5500.h deleted file mode 100644 index f94eed3aff..0000000000 --- a/drivers/wiznet5k/ethernet/w5500/w5500.h +++ /dev/null @@ -1,2057 +0,0 @@ -//***************************************************************************** -// -//! \file w5500.h -//! \brief W5500 HAL Header File. -//! \version 1.0.0 -//! \date 2013/10/21 -//! \par Revision history -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#ifndef _W5500_H_ -#define _W5500_H_ - -#include -#include "../wizchip_conf.h" - -#define _W5500_IO_BASE_ 0x00000000 - -#define _W5500_SPI_READ_ (0x00 << 2) //< SPI interface Read operation in Control Phase -#define _W5500_SPI_WRITE_ (0x01 << 2) //< SPI interface Write operation in Control Phase - -#define WIZCHIP_CREG_BLOCK 0x00 //< Common register block -#define WIZCHIP_SREG_BLOCK(N) (1+4*N) //< Socket N register block -#define WIZCHIP_TXBUF_BLOCK(N) (2+4*N) //< Socket N Tx buffer address block -#define WIZCHIP_RXBUF_BLOCK(N) (3+4*N) //< Socket N Rx buffer address block - -#define WIZCHIP_OFFSET_INC(ADDR, N) (ADDR + (N<<8)) //< Increase offset address - - -/////////////////////////////////////// -// Definition For Legacy Chip Driver // -/////////////////////////////////////// -#define IINCHIP_READ(ADDR) WIZCHIP_READ(ADDR) ///< The defined for legacy chip driver -#define IINCHIP_WRITE(ADDR,VAL) WIZCHIP_WRITE(ADDR,VAL) ///< The defined for legacy chip driver -#define IINCHIP_READ_BUF(ADDR,BUF,LEN) WIZCHIP_READ_BUF(ADDR,BUF,LEN) ///< The defined for legacy chip driver -#define IINCHIP_WRITE_BUF(ADDR,BUF,LEN) WIZCHIP_WRITE(ADDR,BUF,LEN) ///< The defined for legacy chip driver - -////////////////////////////// -//-------------------------- defgroup --------------------------------- -/** - * @defgroup W5500 W5500 - * - * @brief WHIZCHIP register defines and I/O functions of @b W5500. - * - * - @ref WIZCHIP_register : @ref Common_register_group and @ref Socket_register_group - * - @ref WIZCHIP_IO_Functions : @ref Basic_IO_function, @ref Common_register_access_function and @ref Socket_register_access_function - */ - - -/** - * @defgroup WIZCHIP_register WIZCHIP register - * @ingroup W5500 - * - * @brief WHIZCHIP register defines register group of @b W5500. - * - * - @ref Common_register_group : Common register group - * - @ref Socket_register_group : \c SOCKET n register group - */ - - -/** - * @defgroup WIZCHIP_IO_Functions WIZCHIP I/O functions - * @ingroup W5500 - * - * @brief This supports the basic I/O functions for @ref WIZCHIP_register. - * - * - Basic I/O function \n - * WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() \n\n - * - * - @ref Common_register_group access functions \n - * -# @b Mode \n - * getMR(), setMR() - * -# @b Interrupt \n - * getIR(), setIR(), getIMR(), setIMR(), getSIR(), setSIR(), getSIMR(), setSIMR(), getINTLEVEL(), setINTLEVEL() - * -# Network Information \n - * getSHAR(), setSHAR(), getGAR(), setGAR(), getSUBR(), setSUBR(), getSIPR(), setSIPR() - * -# @b Retransmission \n - * getRCR(), setRCR(), getRTR(), setRTR() - * -# @b PPPoE \n - * getPTIMER(), setPTIMER(), getPMAGIC(), getPMAGIC(), getPSID(), setPSID(), getPHAR(), setPHAR(), getPMRU(), setPMRU() - * -# ICMP packet \n - * getUIPR(), getUPORTR() - * -# @b etc. \n - * getPHYCFGR(), setPHYCFGR(), getVERSIONR() \n\n - * - * - \ref Socket_register_group access functions \n - * -# SOCKET control \n - * getSn_MR(), setSn_MR(), getSn_CR(), setSn_CR(), getSn_IMR(), setSn_IMR(), getSn_IR(), setSn_IR() - * -# SOCKET information \n - * getSn_SR(), getSn_DHAR(), setSn_DHAR(), getSn_PORT(), setSn_PORT(), getSn_DIPR(), setSn_DIPR(), getSn_DPORT(), setSn_DPORT() - * getSn_MSSR(), setSn_MSSR() - * -# SOCKET communication \n - * getSn_RXBUF_SIZE(), setSn_RXBUF_SIZE(), getSn_TXBUF_SIZE(), setSn_TXBUF_SIZE() \n - * getSn_TX_RD(), getSn_TX_WR(), setSn_TX_WR() \n - * getSn_RX_RD(), setSn_RX_RD(), getSn_RX_WR() \n - * getSn_TX_FSR(), getSn_RX_RSR(), getSn_KPALVTR(), setSn_KPALVTR() - * -# IP header field \n - * getSn_FRAG(), setSn_FRAG(), getSn_TOS(), setSn_TOS() \n - * getSn_TTL(), setSn_TTL() - */ - - - -/** - * @defgroup Common_register_group Common register - * @ingroup WIZCHIP_register - * - * @brief Common register group\n - * It set the basic for the networking\n - * It set the configuration such as interrupt, network information, ICMP, etc. - * @details - * @sa MR : Mode register. - * @sa GAR, SUBR, SHAR, SIPR - * @sa INTLEVEL, IR, IMR, SIR, SIMR : Interrupt. - * @sa RTR, RCR : Data retransmission. - * @sa PTIMER, PMAGIC, PHAR, PSID, PMRU : PPPoE. - * @sa UIPR, UPORTR : ICMP message. - * @sa PHYCFGR, VERSIONR : etc. - */ - - - -/** - * @defgroup Socket_register_group Socket register - * @ingroup WIZCHIP_register - * - * @brief Socket register group.\n - * Socket register configures and control SOCKETn which is necessary to data communication. - * @details - * @sa Sn_MR, Sn_CR, Sn_IR, Sn_IMR : SOCKETn Control - * @sa Sn_SR, Sn_PORT, Sn_DHAR, Sn_DIPR, Sn_DPORT : SOCKETn Information - * @sa Sn_MSSR, Sn_TOS, Sn_TTL, Sn_KPALVTR, Sn_FRAG : Internet protocol. - * @sa Sn_RXBUF_SIZE, Sn_TXBUF_SIZE, Sn_TX_FSR, Sn_TX_RD, Sn_TX_WR, Sn_RX_RSR, Sn_RX_RD, Sn_RX_WR : Data communication - */ - - - - /** - * @defgroup Basic_IO_function Basic I/O function - * @ingroup WIZCHIP_IO_Functions - * @brief These are basic input/output functions to read values from register or write values to register. - */ - -/** - * @defgroup Common_register_access_function Common register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access common registers. - */ - -/** - * @defgroup Socket_register_access_function Socket register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access socket registers. - */ - -//------------------------------- defgroup end -------------------------------------------- -//----------------------------- W5500 Common Registers IOMAP ----------------------------- -/** - * @ingroup Common_register_group - * @brief Mode Register address(R/W)\n - * @ref MR is used for S/W reset, ping block mode, PPPoE mode and etc. - * @details Each bit of @ref MR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
RST Reserved WOL PB PPPoE Reserved FARP Reserved
- * - \ref MR_RST : Reset - * - \ref MR_WOL : Wake on LAN - * - \ref MR_PB : Ping block - * - \ref MR_PPPOE : PPPoE mode - * - \ref MR_FARP : Force ARP mode - */ -#define MR (_W5500_IO_BASE_ + (0x0000 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Gateway IP Register address(R/W) - * @details @ref GAR configures the default gateway address. - */ -#define GAR (_W5500_IO_BASE_ + (0x0001 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Subnet mask Register address(R/W) - * @details @ref SUBR configures the subnet mask address. - */ -#define SUBR (_W5500_IO_BASE_ + (0x0005 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Source MAC Register address(R/W) - * @details @ref SHAR configures the source hardware address. - */ -#define SHAR (_W5500_IO_BASE_ + (0x0009 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Source IP Register address(R/W) - * @details @ref SIPR configures the source IP address. - */ -#define SIPR (_W5500_IO_BASE_ + (0x000F << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Set Interrupt low level timer register address(R/W) - * @details @ref INTLEVEL configures the Interrupt Assert Time. - */ -#define INTLEVEL (_W5500_IO_BASE_ + (0x0013 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Interrupt Register(R/W) - * @details @ref IR indicates the interrupt status. Each bit of @ref IR will be still until the bit will be written to by the host. - * If @ref IR is not equal to x00 INTn PIN is asserted to low until it is x00\n\n - * Each bit of @ref IR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
CONFLICT UNREACH PPPoE MP Reserved Reserved Reserved Reserved
- * - \ref IR_CONFLICT : IP conflict - * - \ref IR_UNREACH : Destination unreachable - * - \ref IR_PPPoE : PPPoE connection close - * - \ref IR_MP : Magic packet - */ -#define IR (_W5500_IO_BASE_ + (0x0015 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Interrupt mask register(R/W) - * @details @ref IMR is used to mask interrupts. Each bit of @ref IMR corresponds to each bit of @ref IR. - * When a bit of @ref IMR is and the corresponding bit of @ref IR is an interrupt will be issued. In other words, - * if a bit of @ref IMR is an interrupt will not be issued even if the corresponding bit of @ref IR is \n\n - * Each bit of @ref IMR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
IM_IR7 IM_IR6 IM_IR5 IM_IR4 Reserved Reserved Reserved Reserved
- * - \ref IM_IR7 : IP Conflict Interrupt Mask - * - \ref IM_IR6 : Destination unreachable Interrupt Mask - * - \ref IM_IR5 : PPPoE Close Interrupt Mask - * - \ref IM_IR4 : Magic Packet Interrupt Mask - */ -#define IMR (_W5500_IO_BASE_ + (0x0016 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Register(R/W) - * @details @ref SIR indicates the interrupt status of Socket.\n - * Each bit of @ref SIR be still until @ref Sn_IR is cleared by the host.\n - * If @ref Sn_IR is not equal to x00 the n-th bit of @ref SIR is and INTn PIN is asserted until @ref SIR is x00 */ -#define SIR (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Mask Register(R/W) - * @details Each bit of @ref SIMR corresponds to each bit of @ref SIR. - * When a bit of @ref SIMR is and the corresponding bit of @ref SIR is Interrupt will be issued. - * In other words, if a bit of @ref SIMR is an interrupt will be not issued even if the corresponding bit of @ref SIR is - */ -#define SIMR (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Timeout register address( 1 is 100us )(R/W) - * @details @ref RTR configures the retransmission timeout period. The unit of timeout period is 100us and the default of @ref RTR is x07D0or 000 - * And so the default timeout period is 200ms(100us X 2000). During the time configured by @ref RTR, W5500 waits for the peer response - * to the packet that is transmitted by \ref Sn_CR (CONNECT, DISCON, CLOSE, SEND, SEND_MAC, SEND_KEEP command). - * If the peer does not respond within the @ref RTR time, W5500 retransmits the packet or issues timeout. - */ -#define RTR (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Retry count register(R/W) - * @details @ref RCR configures the number of time of retransmission. - * When retransmission occurs as many as ref RCR+1 Timeout interrupt is issued (@ref Sn_IR[TIMEOUT] = . - */ -#define RCR (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Request Timer register in PPPoE mode(R/W) - * @details @ref PTIMER configures the time for sending LCP echo request. The unit of time is 25ms. - */ -#define PTIMER (_W5500_IO_BASE_ + (0x001C << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Magic number register in PPPoE mode(R/W) - * @details @ref PMAGIC configures the 4bytes magic number to be used in LCP negotiation. - */ -#define PMAGIC (_W5500_IO_BASE_ + (0x001D << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Destination MAC Register address(R/W) - * @details @ref PHAR configures the PPPoE server hardware address that is acquired during PPPoE connection process. - */ -#define PHAR (_W5500_IO_BASE_ + (0x001E << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Session Identification Register(R/W) - * @details @ref PSID configures the PPPoE sever session ID acquired during PPPoE connection process. - */ -#define PSID (_W5500_IO_BASE_ + (0x0024 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Maximum Segment Size(MSS) register(R/W) - * @details @ref PMRU configures the maximum receive unit of PPPoE. - */ -#define PMRU (_W5500_IO_BASE_ + (0x0026 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable IP register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR indicates - * the destination IP address & port number respectively. - */ -#define UIPR (_W5500_IO_BASE_ + (0x0028 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable Port register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR - * indicates the destination IP address & port number respectively. - */ -#define UPORTR (_W5500_IO_BASE_ + (0x002C << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PHY Status Register(R/W) - * @details @ref PHYCFGR configures PHY operation mode and resets PHY. In addition, @ref PHYCFGR indicates the status of PHY such as duplex, Speed, Link. - */ -#define PHYCFGR (_W5500_IO_BASE_ + (0x002E << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -// Reserved (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0031 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0032 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0033 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0034 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0035 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0036 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0037 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0038 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief chip version register address(R) - * @details @ref VERSIONR always indicates the W5500 version as @b 0x04. - */ -#define VERSIONR (_W5500_IO_BASE_ + (0x0039 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - - -//----------------------------- W5500 Socket Registers IOMAP ----------------------------- -/** - * @ingroup Socket_register_group - * @brief socket Mode register(R/W) - * @details @ref Sn_MR configures the option or protocol type of Socket n.\n\n - * Each bit of @ref Sn_MR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
MULTI/MFEN BCASTB ND/MC/MMB UCASTB/MIP6B Protocol[3] Protocol[2] Protocol[1] Protocol[0]
- * - @ref Sn_MR_MULTI : Support UDP Multicasting - * - @ref Sn_MR_BCASTB : Broadcast block in UDP Multicasting - * - @ref Sn_MR_ND : No Delayed Ack(TCP) flag - * - @ref Sn_MR_MC : IGMP version used in UDP mulitcasting - * - @ref Sn_MR_MMB : Multicast Blocking in @ref Sn_MR_MACRAW mode - * - @ref Sn_MR_UCASTB : Unicast Block in UDP Multicating - * - @ref Sn_MR_MIP6B : IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * - Protocol - * - * - * - * - * - * - *
Protocol[3] Protocol[2] Protocol[1] Protocol[0] @b Meaning
0 0 0 0 Closed
0 0 0 1 TCP
0 0 1 0 UDP
0 1 0 0 MACRAW
- * - @ref Sn_MR_MACRAW : MAC LAYER RAW SOCK \n - * - @ref Sn_MR_UDP : UDP - * - @ref Sn_MR_TCP : TCP - * - @ref Sn_MR_CLOSE : Unused socket - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR(N) (_W5500_IO_BASE_ + (0x0000 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Socket command register(R/W) - * @details This is used to set the command for Socket n such as OPEN, CLOSE, CONNECT, LISTEN, SEND, and RECEIVE.\n - * After W5500 accepts the command, the @ref Sn_CR register is automatically cleared to 0x00. - * Even though @ref Sn_CR is cleared to 0x00, the command is still being processed.\n - * To check whether the command is completed or not, please check the @ref Sn_IR or @ref Sn_SR. - * - @ref Sn_CR_OPEN : Initialize or open socket. - * - @ref Sn_CR_LISTEN : Wait connection request in TCP mode(Server mode) - * - @ref Sn_CR_CONNECT : Send connection request in TCP mode(Client mode) - * - @ref Sn_CR_DISCON : Send closing request in TCP mode. - * - @ref Sn_CR_CLOSE : Close socket. - * - @ref Sn_CR_SEND : Update TX buffer pointer and send data. - * - @ref Sn_CR_SEND_MAC : Send data with MAC address, so without ARP process. - * - @ref Sn_CR_SEND_KEEP : Send keep alive message. - * - @ref Sn_CR_RECV : Update RX buffer pointer and receive data. - */ -#define Sn_CR(N) (_W5500_IO_BASE_ + (0x0001 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Socket interrupt register(R) - * @details @ref Sn_IR indicates the status of Socket Interrupt such as establishment, termination, receiving data, timeout).\n - * When an interrupt occurs and the corresponding bit of @ref Sn_IMR is the corresponding bit of @ref Sn_IR becomes \n - * In order to clear the @ref Sn_IR bit, the host should write the bit to \n - * - * - * - *
7 6 5 4 3 2 1 0
Reserved Reserved Reserved SEND_OK TIMEOUT RECV DISCON CON
- * - \ref Sn_IR_SENDOK : SEND_OK Interrupt - * - \ref Sn_IR_TIMEOUT : TIMEOUT Interrupt - * - \ref Sn_IR_RECV : RECV Interrupt - * - \ref Sn_IR_DISCON : DISCON Interrupt - * - \ref Sn_IR_CON : CON Interrupt - */ -#define Sn_IR(N) (_W5500_IO_BASE_ + (0x0002 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Socket status register(R) - * @details @ref Sn_SR indicates the status of Socket n.\n - * The status of Socket n is changed by @ref Sn_CR or some special control packet as SYN, FIN packet in TCP. - * @par Normal status - * - @ref SOCK_CLOSED : Closed - * - @ref SOCK_INIT : Initiate state - * - @ref SOCK_LISTEN : Listen state - * - @ref SOCK_ESTABLISHED : Success to connect - * - @ref SOCK_CLOSE_WAIT : Closing state - * - @ref SOCK_UDP : UDP socket - * - @ref SOCK_MACRAW : MAC raw mode socket - *@par Temporary status during changing the status of Socket n. - * - @ref SOCK_SYNSENT : This indicates Socket n sent the connect-request packet (SYN packet) to a peer. - * - @ref SOCK_SYNRECV : It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer. - * - @ref SOCK_FIN_WAIT : Connection state - * - @ref SOCK_CLOSING : Closing state - * - @ref SOCK_TIME_WAIT : Closing state - * - @ref SOCK_LAST_ACK : Closing state - */ -#define Sn_SR(N) (_W5500_IO_BASE_ + (0x0003 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief source port register(R/W) - * @details @ref Sn_PORT configures the source port number of Socket n. - * It is valid when Socket n is used in TCP/UPD mode. It should be set before OPEN command is ordered. - */ -#define Sn_PORT(N) (_W5500_IO_BASE_ + (0x0004 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Peer MAC register address(R/W) - * @details @ref Sn_DHAR configures the destination hardware address of Socket n when using SEND_MAC command in UDP mode or - * it indicates that it is acquired in ARP-process by CONNECT/SEND command. - */ -#define Sn_DHAR(N) (_W5500_IO_BASE_ + (0x0006 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Peer IP register address(R/W) - * @details @ref Sn_DIPR configures or indicates the destination IP address of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In TCP client mode, it configures an IP address of �TCP serverbefore CONNECT command. - * In TCP server mode, it indicates an IP address of �TCP clientafter successfully establishing connection. - * In UDP mode, it configures an IP address of peer to be received the UDP packet by SEND or SEND_MAC command. - */ -#define Sn_DIPR(N) (_W5500_IO_BASE_ + (0x000C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Peer port register address(R/W) - * @details @ref Sn_DPORT configures or indicates the destination port number of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In �TCP clientmode, it configures the listen port number of �TCP serverbefore CONNECT command. - * In �TCP Servermode, it indicates the port number of TCP client after successfully establishing connection. - * In UDP mode, it configures the port number of peer to be transmitted the UDP packet by SEND/SEND_MAC command. - */ -#define Sn_DPORT(N) (_W5500_IO_BASE_ + (0x0010 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Maximum Segment Size(Sn_MSSR0) register address(R/W) - * @details @ref Sn_MSSR configures or indicates the MTU(Maximum Transfer Unit) of Socket n. - */ -#define Sn_MSSR(N) (_W5500_IO_BASE_ + (0x0012 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -// Reserved (_W5500_IO_BASE_ + (0x0014 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief IP Type of Service(TOS) Register(R/W) - * @details @ref Sn_TOS configures the TOS(Type Of Service field in IP Header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TOS(N) (_W5500_IO_BASE_ + (0x0015 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -/** - * @ingroup Socket_register_group - * @brief IP Time to live(TTL) Register(R/W) - * @details @ref Sn_TTL configures the TTL(Time To Live field in IP header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TTL(N) (_W5500_IO_BASE_ + (0x0016 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001A << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Receive memory size register(R/W) - * @details @ref Sn_RXBUF_SIZE configures the RX buffer block size of Socket n. - * Socket n RX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data cannot be normally received from a peer. - * Although Socket n RX Buffer Block size is initially configured to 2Kbytes, - * user can re-configure its size using @ref Sn_RXBUF_SIZE. The total sum of @ref Sn_RXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data reception error is occurred. - */ -#define Sn_RXBUF_SIZE(N) (_W5500_IO_BASE_ + (0x001E << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory size register(R/W) - * @details @ref Sn_TXBUF_SIZE configures the TX buffer block size of Socket n. Socket n TX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data can�t be normally transmitted to a peer. - * Although Socket n TX Buffer Block size is initially configured to 2Kbytes, - * user can be re-configure its size using @ref Sn_TXBUF_SIZE. The total sum of @ref Sn_TXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data transmission error is occurred. - */ -#define Sn_TXBUF_SIZE(N) (_W5500_IO_BASE_ + (0x001F << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit free memory size register(R) - * @details @ref Sn_TX_FSR indicates the free size of Socket n TX Buffer Block. It is initialized to the configured size by @ref Sn_TXBUF_SIZE. - * Data bigger than @ref Sn_TX_FSR should not be saved in the Socket n TX Buffer because the bigger data overwrites the previous saved data not yet sent. - * Therefore, check before saving the data to the Socket n TX Buffer, and if data is equal or smaller than its checked size, - * transmit the data with SEND/SEND_MAC command after saving the data in Socket n TX buffer. But, if data is bigger than its checked size, - * transmit the data after dividing into the checked size and saving in the Socket n TX buffer. - */ -#define Sn_TX_FSR(N) (_W5500_IO_BASE_ + (0x0020 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory read pointer register address(R) - * @details @ref Sn_TX_RD is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP. - * After its initialization, it is auto-increased by SEND command. - * SEND command transmits the saved data from the current @ref Sn_TX_RD to the @ref Sn_TX_WR in the Socket n TX Buffer. - * After transmitting the saved data, the SEND command increases the @ref Sn_TX_RD as same as the @ref Sn_TX_WR. - * If its increment value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_TX_RD(N) (_W5500_IO_BASE_ + (0x0022 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory write pointer register address(R/W) - * @details @ref Sn_TX_WR is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP.\n - * It should be read or be updated like as follows.\n - * 1. Read the starting address for saving the transmitting data.\n - * 2. Save the transmitting data from the starting address of Socket n TX buffer.\n - * 3. After saving the transmitting data, update @ref Sn_TX_WR to the increased value as many as transmitting data size. - * If the increment value exceeds the maximum value 0xFFFF(greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value.\n - * 4. Transmit the saved data in Socket n TX Buffer by using SEND/SEND command - */ -#define Sn_TX_WR(N) (_W5500_IO_BASE_ + (0x0024 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Received data size register(R) - * @details @ref Sn_RX_RSR indicates the data size received and saved in Socket n RX Buffer. - * @ref Sn_RX_RSR does not exceed the @ref Sn_RXBUF_SIZE and is calculated as the difference between - * �Socket n RX Write Pointer (@ref Sn_RX_WR)and �Socket n RX Read Pointer (@ref Sn_RX_RD) - */ -#define Sn_RX_RSR(N) (_W5500_IO_BASE_ + (0x0026 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Read point of Receive memory(R/W) - * @details @ref Sn_RX_RD is initialized by OPEN command. Make sure to be read or updated as follows.\n - * 1. Read the starting save address of the received data.\n - * 2. Read data from the starting address of Socket n RX Buffer.\n - * 3. After reading the received data, Update @ref Sn_RX_RD to the increased value as many as the reading size. - * If the increment value exceeds the maximum value 0xFFFF, that is, is greater than 0x10000 and the carry bit occurs, - * update with the lower 16bits value ignored the carry bit.\n - * 4. Order RECV command is for notifying the updated @ref Sn_RX_RD to W5500. - */ -#define Sn_RX_RD(N) (_W5500_IO_BASE_ + (0x0028 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Write point of Receive memory(R) - * @details @ref Sn_RX_WR is initialized by OPEN command and it is auto-increased by the data reception. - * If the increased value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_RX_WR(N) (_W5500_IO_BASE_ + (0x002A << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief socket interrupt mask register(R) - * @details @ref Sn_IMR masks the interrupt of Socket n. - * Each bit corresponds to each bit of @ref Sn_IR. When a Socket n Interrupt is occurred and the corresponding bit of @ref Sn_IMR is - * the corresponding bit of @ref Sn_IR becomes When both the corresponding bit of @ref Sn_IMR and @ref Sn_IR are and the n-th bit of @ref IR is - * Host is interrupted by asserted INTn PIN to low. - */ -#define Sn_IMR(N) (_W5500_IO_BASE_ + (0x002C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Fragment field value in IP header register(R/W) - * @details @ref Sn_FRAG configures the FRAG(Fragment field in IP header). - */ -#define Sn_FRAG(N) (_W5500_IO_BASE_ + (0x002D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Keep Alive Timer register(R/W) - * @details @ref Sn_KPALVTR configures the transmitting timer of �KEEP ALIVE(KA)packet of SOCKETn. It is valid only in TCP mode, - * and ignored in other modes. The time unit is 5s. - * KA packet is transmittable after @ref Sn_SR is changed to SOCK_ESTABLISHED and after the data is transmitted or received to/from a peer at least once. - * In case of '@ref Sn_KPALVTR > 0', W5500 automatically transmits KA packet after time-period for checking the TCP connection (Auto-keepalive-process). - * In case of '@ref Sn_KPALVTR = 0', Auto-keep-alive-process will not operate, - * and KA packet can be transmitted by SEND_KEEP command by the host (Manual-keep-alive-process). - * Manual-keep-alive-process is ignored in case of '@ref Sn_KPALVTR > 0'. - */ -#define Sn_KPALVTR(N) (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -//#define Sn_TSR(N) (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - - -//----------------------------- W5500 Register values ----------------------------- - -/* MODE register values */ -/** - * @brief Reset - * @details If this bit is All internal registers will be initialized. It will be automatically cleared as after S/W reset. - */ -#define MR_RST 0x80 - -/** - * @brief Wake on LAN - * @details 0 : Disable WOL mode\n - * 1 : Enable WOL mode\n - * If WOL mode is enabled and the received magic packet over UDP has been normally processed, the Interrupt PIN (INTn) asserts to low. - * When using WOL mode, the UDP Socket should be opened with any source port number. (Refer to Socket n Mode Register (@ref Sn_MR) for opening Socket.) - * @note The magic packet over UDP supported by W5500 consists of 6 bytes synchronization stream (xFFFFFFFFFFFF and - * 16 times Target MAC address stream in UDP payload. The options such like password are ignored. You can use any UDP source port number for WOL mode. - */ -#define MR_WOL 0x20 - -/** - * @brief Ping block - * @details 0 : Disable Ping block\n - * 1 : Enable Ping block\n - * If the bit is it blocks the response to a ping request. - */ -#define MR_PB 0x10 - -/** - * @brief Enable PPPoE - * @details 0 : DisablePPPoE mode\n - * 1 : EnablePPPoE mode\n - * If you use ADSL, this bit should be - */ -#define MR_PPPOE 0x08 - -/** - * @brief Enable UDP_FORCE_ARP CHECHK - * @details 0 : Disable Force ARP mode\n - * 1 : Enable Force ARP mode\n - * In Force ARP mode, It forces on sending ARP Request whenever data is sent. - */ -#define MR_FARP 0x02 - -/* IR register values */ -/** - * @brief Check IP conflict. - * @details Bit is set as when own source IP address is same with the sender IP address in the received ARP request. - */ -#define IR_CONFLICT 0x80 - -/** - * @brief Get the destination unreachable message in UDP sending. - * @details When receiving the ICMP (Destination port unreachable) packet, this bit is set as - * When this bit is Destination Information such as IP address and Port number may be checked with the corresponding @ref UIPR & @ref UPORTR. - */ -#define IR_UNREACH 0x40 - -/** - * @brief Get the PPPoE close message. - * @details When PPPoE is disconnected during PPPoE mode, this bit is set. - */ -#define IR_PPPoE 0x20 - -/** - * @brief Get the magic packet interrupt. - * @details When WOL mode is enabled and receives the magic packet over UDP, this bit is set. - */ -#define IR_MP 0x10 - - -/* PHYCFGR register value */ -#define PHYCFGR_RST ~(1<<7) //< For PHY reset, must operate AND mask. -#define PHYCFGR_OPMD (1<<6) // Configre PHY with OPMDC value -#define PHYCFGR_OPMDC_ALLA (7<<3) -#define PHYCFGR_OPMDC_PDOWN (6<<3) -#define PHYCFGR_OPMDC_NA (5<<3) -#define PHYCFGR_OPMDC_100FA (4<<3) -#define PHYCFGR_OPMDC_100F (3<<3) -#define PHYCFGR_OPMDC_100H (2<<3) -#define PHYCFGR_OPMDC_10F (1<<3) -#define PHYCFGR_OPMDC_10H (0<<3) -#define PHYCFGR_DPX_FULL (1<<2) -#define PHYCFGR_DPX_HALF (0<<2) -#define PHYCFGR_SPD_100 (1<<1) -#define PHYCFGR_SPD_10 (0<<1) -#define PHYCFGR_LNK_ON (1<<0) -#define PHYCFGR_LNK_OFF (0<<0) - -/* IMR register values */ -/** - * @brief IP Conflict Interrupt Mask. - * @details 0: Disable IP Conflict Interrupt\n - * 1: Enable IP Conflict Interrupt - */ -#define IM_IR7 0x80 - -/** - * @brief Destination unreachable Interrupt Mask. - * @details 0: Disable Destination unreachable Interrupt\n - * 1: Enable Destination unreachable Interrupt - */ -#define IM_IR6 0x40 - -/** - * @brief PPPoE Close Interrupt Mask. - * @details 0: Disable PPPoE Close Interrupt\n - * 1: Enable PPPoE Close Interrupt - */ -#define IM_IR5 0x20 - -/** - * @brief Magic Packet Interrupt Mask. - * @details 0: Disable Magic Packet Interrupt\n - * 1: Enable Magic Packet Interrupt - */ -#define IM_IR4 0x10 - -/* Sn_MR Default values */ -/** - * @brief Support UDP Multicasting - * @details 0 : disable Multicasting\n - * 1 : enable Multicasting\n - * This bit is applied only during UDP mode(P[3:0] = 010.\n - * To use multicasting, @ref Sn_DIPR & @ref Sn_DPORT should be respectively configured with the multicast group IP address & port number - * before Socket n is opened by OPEN command of @ref Sn_CR. - */ -#define Sn_MR_MULTI 0x80 - -/** - * @brief Broadcast block in UDP Multicasting. - * @details 0 : disable Broadcast Blocking\n - * 1 : enable Broadcast Blocking\n - * This bit blocks to receive broadcasting packet during UDP mode(P[3:0] = 010.\m - * In addition, This bit does when MACRAW mode(P[3:0] = 100 - */ -#define Sn_MR_BCASTB 0x40 - -/** - * @brief No Delayed Ack(TCP), Multicast flag - * @details 0 : Disable No Delayed ACK option\n - * 1 : Enable No Delayed ACK option\n - * This bit is applied only during TCP mode (P[3:0] = 001.\n - * When this bit is It sends the ACK packet without delay as soon as a Data packet is received from a peer.\n - * When this bit is It sends the ACK packet after waiting for the timeout time configured by @ref RTR. - */ -#define Sn_MR_ND 0x20 - -/** - * @brief Unicast Block in UDP Multicasting - * @details 0 : disable Unicast Blocking\n - * 1 : enable Unicast Blocking\n - * This bit blocks receiving the unicast packet during UDP mode(P[3:0] = 010 and MULTI = - */ -#define Sn_MR_UCASTB 0x10 - -/** - * @brief MAC LAYER RAW SOCK - * @details This configures the protocol mode of Socket n. - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR_MACRAW 0x04 - -//#define Sn_MR_IPRAW 0x03 /**< IP LAYER RAW SOCK */ - -/** - * @brief UDP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_UDP 0x02 - -/** - * @brief TCP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_TCP 0x01 - -/** - * @brief Unused socket - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_CLOSE 0x00 - -/* Sn_MR values used with Sn_MR_MACRAW */ -/** - * @brief MAC filter enable in @ref Sn_MR_MACRAW mode - * @details 0 : disable MAC Filtering\n - * 1 : enable MAC Filtering\n - * This bit is applied only during MACRAW mode(P[3:0] = 100.\n - * When set as W5500 can only receive broadcasting packet or packet sent to itself. - * When this bit is W5500 can receive all packets on Ethernet. - * If user wants to implement Hybrid TCP/IP stack, - * it is recommended that this bit is set as for reducing host overhead to process the all received packets. - */ -#define Sn_MR_MFEN Sn_MR_MULTI - -/** - * @brief Multicast Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : using IGMP version 2\n - * 1 : using IGMP version 1\n - * This bit is applied only during UDP mode(P[3:0] = 010 and MULTI = - * It configures the version for IGMP messages (Join/Leave/Report). - */ -#define Sn_MR_MMB Sn_MR_ND - -/** - * @brief IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : disable IPv6 Blocking\n - * 1 : enable IPv6 Blocking\n - * This bit is applied only during MACRAW mode (P[3:0] = 100. It blocks to receiving the IPv6 packet. - */ -#define Sn_MR_MIP6B Sn_MR_UCASTB - -/* Sn_MR value used with Sn_MR_UDP & Sn_MR_MULTI */ -/** - * @brief IGMP version used in UDP mulitcasting - * @details 0 : disable Multicast Blocking\n - * 1 : enable Multicast Blocking\n - * This bit is applied only when MACRAW mode(P[3:0] = 100. It blocks to receive the packet with multicast MAC address. - */ -#define Sn_MR_MC Sn_MR_ND - -/* Sn_MR alternate values */ -/** - * @brief For Berkeley Socket API - */ -#define SOCK_STREAM Sn_MR_TCP - -/** - * @brief For Berkeley Socket API - */ -#define SOCK_DGRAM Sn_MR_UDP - - -/* Sn_CR values */ -/** - * @brief Initialize or open socket - * @details Socket n is initialized and opened according to the protocol selected in Sn_MR(P3:P0). - * The table below shows the value of @ref Sn_SR corresponding to @ref Sn_MR.\n - * - * - * - * - * - * - *
\b Sn_MR (P[3:0]) \b Sn_SR
Sn_MR_CLOSE (000
Sn_MR_TCP (001 SOCK_INIT (0x13)
Sn_MR_UDP (010 SOCK_UDP (0x22)
S0_MR_MACRAW (100 SOCK_MACRAW (0x02)
- */ -#define Sn_CR_OPEN 0x01 - -/** - * @brief Wait connection request in TCP mode(Server mode) - * @details This is valid only in TCP mode (Sn_MR(P3:P0) = Sn_MR_TCP). - * In this mode, Socket n operates as a �TCP serverand waits for connection-request (SYN packet) from any �TCP client - * The @ref Sn_SR changes the state from SOCK_INIT to SOCKET_LISTEN. - * When a �TCP clientconnection request is successfully established, - * the @ref Sn_SR changes from SOCK_LISTEN to SOCK_ESTABLISHED and the Sn_IR(0) becomes - * But when a �TCP clientconnection request is failed, Sn_IR(3) becomes and the status of @ref Sn_SR changes to SOCK_CLOSED. - */ -#define Sn_CR_LISTEN 0x02 - -/** - * @brief Send connection request in TCP mode(Client mode) - * @details To connect, a connect-request (SYN packet) is sent to b>TCP serverconfigured by @ref Sn_DIPR & Sn_DPORT(destination address & port). - * If the connect-request is successful, the @ref Sn_SR is changed to @ref SOCK_ESTABLISHED and the Sn_IR(0) becomes \n\n - * The connect-request fails in the following three cases.\n - * 1. When a @b ARPTO occurs (@ref Sn_IR[3] = ) because destination hardware address is not acquired through the ARP-process.\n - * 2. When a @b SYN/ACK packet is not received and @b TCPTO (Sn_IR(3) = )\n - * 3. When a @b RST packet is received instead of a @b SYN/ACK packet. In these cases, @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note This is valid only in TCP mode and operates when Socket n acts as b>TCP client - */ -#define Sn_CR_CONNECT 0x04 - -/** - * @brief Send closing request in TCP mode - * @details Regardless of b>TCP serveror b>TCP client the DISCON command processes the disconnect-process (b>Active closeor b>Passive close.\n - * @par Active close - * it transmits disconnect-request(FIN packet) to the connected peer\n - * @par Passive close - * When FIN packet is received from peer, a FIN packet is replied back to the peer.\n - * @details When the disconnect-process is successful (that is, FIN/ACK packet is received successfully), @ref Sn_SR is changed to @ref SOCK_CLOSED.\n - * Otherwise, TCPTO occurs (Sn_IR(3)=)= and then @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note Valid only in TCP mode. - */ -#define Sn_CR_DISCON 0x08 - -/** - * @brief Close socket - * @details Sn_SR is changed to @ref SOCK_CLOSED. - */ -#define Sn_CR_CLOSE 0x10 - -/** - * @brief Update TX buffer pointer and send data - * @details SEND transmits all the data in the Socket n TX buffer.\n - * For more details, please refer to Socket n TX Free Size Register (@ref Sn_TX_FSR), Socket n, - * TX Write Pointer Register(@ref Sn_TX_WR), and Socket n TX Read Pointer Register(@ref Sn_TX_RD). - */ -#define Sn_CR_SEND 0x20 - -/** - * @brief Send data with MAC address, so without ARP process - * @details The basic operation is same as SEND.\n - * Normally SEND transmits data after destination hardware address is acquired by the automatic ARP-process(Address Resolution Protocol).\n - * But SEND_MAC transmits data without the automatic ARP-process.\n - * In this case, the destination hardware address is acquired from @ref Sn_DHAR configured by host, instead of APR-process. - * @note Valid only in UDP mode. - */ -#define Sn_CR_SEND_MAC 0x21 - -/** - * @brief Send keep alive message - * @details It checks the connection status by sending 1byte keep-alive packet.\n - * If the peer can not respond to the keep-alive packet during timeout time, the connection is terminated and the timeout interrupt will occur. - * @note Valid only in TCP mode. - */ -#define Sn_CR_SEND_KEEP 0x22 - -/** - * @brief Update RX buffer pointer and receive data - * @details RECV completes the processing of the received data in Socket n RX Buffer by using a RX read pointer register (@ref Sn_RX_RD).\n - * For more details, refer to Socket n RX Received Size Register (@ref Sn_RX_RSR), Socket n RX Write Pointer Register (@ref Sn_RX_WR), - * and Socket n RX Read Pointer Register (@ref Sn_RX_RD). - */ -#define Sn_CR_RECV 0x40 - -/* Sn_IR values */ -/** - * @brief SEND_OK Interrupt - * @details This is issued when SEND command is completed. - */ -#define Sn_IR_SENDOK 0x10 - -/** - * @brief TIMEOUT Interrupt - * @details This is issued when ARPTO or TCPTO occurs. - */ -#define Sn_IR_TIMEOUT 0x08 - -/** - * @brief RECV Interrupt - * @details This is issued whenever data is received from a peer. - */ -#define Sn_IR_RECV 0x04 - -/** - * @brief DISCON Interrupt - * @details This is issued when FIN or FIN/ACK packet is received from a peer. - */ -#define Sn_IR_DISCON 0x02 - -/** - * @brief CON Interrupt - * @details This is issued one time when the connection with peer is successful and then @ref Sn_SR is changed to @ref SOCK_ESTABLISHED. - */ -#define Sn_IR_CON 0x01 - -/* Sn_SR values */ -/** - * @brief Closed - * @details This indicates that Socket n is released.\N - * When DICON, CLOSE command is ordered, or when a timeout occurs, it is changed to @ref SOCK_CLOSED regardless of previous status. - */ -#define SOCK_CLOSED 0x00 - -/** - * @brief Initiate state - * @details This indicates Socket n is opened with TCP mode.\N - * It is changed to @ref SOCK_INIT when Sn_MR(P[3:0]) = 001and OPEN command is ordered.\N - * After @ref SOCK_INIT, user can use LISTEN /CONNECT command. - */ -#define SOCK_INIT 0x13 - -/** - * @brief Listen state - * @details This indicates Socket n is operating as b>TCP servermode and waiting for connection-request (SYN packet) from a peer (b>TCP client.\n - * It will change to @ref SOCK_ESTALBLISHED when the connection-request is successfully accepted.\n - * Otherwise it will change to @ref SOCK_CLOSED after TCPTO occurred (Sn_IR(TIMEOUT) = . - */ -#define SOCK_LISTEN 0x14 - -/** - * @brief Connection state - * @details This indicates Socket n sent the connect-request packet (SYN packet) to a peer.\n - * It is temporarily shown when @ref Sn_SR is changed from @ref SOCK_INIT to @ref SOCK_ESTABLISHED by CONNECT command.\n - * If connect-accept(SYN/ACK packet) is received from the peer at SOCK_SYNSENT, it changes to @ref SOCK_ESTABLISHED.\n - * Otherwise, it changes to @ref SOCK_CLOSED after TCPTO (@ref Sn_IR[TIMEOUT] = is occurred. - */ -#define SOCK_SYNSENT 0x15 - -/** - * @brief Connection state - * @details It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer.\n - * If socket n sends the response (SYN/ACK packet) to the peer successfully, it changes to @ref SOCK_ESTABLISHED. \n - * If not, it changes to @ref SOCK_CLOSED after timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_SYNRECV 0x16 - -/** - * @brief Success to connect - * @details This indicates the status of the connection of Socket n.\n - * It changes to @ref SOCK_ESTABLISHED when the b>TCP SERVERprocessed the SYN packet from the b>TCP CLIENTduring @ref SOCK_LISTEN, or - * when the CONNECT command is successful.\n - * During @ref SOCK_ESTABLISHED, DATA packet can be transferred using SEND or RECV command. - */ -#define SOCK_ESTABLISHED 0x17 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_FIN_WAIT 0x18 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_CLOSING 0x1A - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_TIME_WAIT 0x1B - -/** - * @brief Closing state - * @details This indicates Socket n received the disconnect-request (FIN packet) from the connected peer.\n - * This is half-closing status, and data can be transferred.\n - * For full-closing, DISCON command is used. But For just-closing, CLOSE command is used. - */ -#define SOCK_CLOSE_WAIT 0x1C - -/** - * @brief Closing state - * @details This indicates Socket n is waiting for the response (FIN/ACK packet) to the disconnect-request (FIN packet) by passive-close.\n - * It changes to @ref SOCK_CLOSED when Socket n received the response successfully, or when timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_LAST_ACK 0x1D - -/** - * @brief UDP socket - * @details This indicates Socket n is opened in UDP mode(Sn_MR(P[3:0]) = 010.\n - * It changes to SOCK_UPD when Sn_MR(P[3:0]) = 010 and OPEN command is ordered.\n - * Unlike TCP mode, data can be transfered without the connection-process. - */ -#define SOCK_UDP 0x22 - -//#define SOCK_IPRAW 0x32 /**< IP raw mode socket */ - -/** - * @brief MAC raw mode socket - * @details This indicates Socket 0 is opened in MACRAW mode (S0_MR(P[3:0]) = 100and is valid only in Socket 0.\n - * It changes to SOCK_MACRAW when S0_MR(P[3:0] = 100and OPEN command is ordered.\n - * Like UDP mode socket, MACRAW mode Socket 0 can transfer a MAC packet (Ethernet frame) without the connection-process. - */ -#define SOCK_MACRAW 0x42 - -//#define SOCK_PPPOE 0x5F - -/* IP PROTOCOL */ -#define IPPROTO_IP 0 //< Dummy for IP -#define IPPROTO_ICMP 1 //< Control message protocol -#define IPPROTO_IGMP 2 //< Internet group management protocol -#define IPPROTO_GGP 3 //< Gateway^2 (deprecated) -#define IPPROTO_TCP 6 //< TCP -#define IPPROTO_PUP 12 //< PUP -#define IPPROTO_UDP 17 //< UDP -#define IPPROTO_IDP 22 //< XNS idp -#define IPPROTO_ND 77 //< UNOFFICIAL net disk protocol -#define IPPROTO_RAW 255 //< Raw IP packet - - -/** - * @brief Enter a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n \n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt.\n - * In OS environment, You can replace it to critical section api supported by OS. - * - * \sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * \sa WIZCHIP_CRITICAL_EXIT() - */ -#define WIZCHIP_CRITICAL_ENTER() WIZCHIP.CRIS._enter() - -/** - * @brief Exit a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n\n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt. \n - * In OS environment, You can replace it to critical section api supported by OS. - * - * @sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * @sa WIZCHIP_CRITICAL_ENTER() - */ -#ifdef _exit -#undef _exit -#endif -#define WIZCHIP_CRITICAL_EXIT() WIZCHIP.CRIS._exit() - - - -//////////////////////// -// Basic I/O Function // -//////////////////////// - -/** - * @ingroup Basic_IO_function - * @brief It reads 1 byte value from a register. - * @param AddrSel Register address - * @return The value of register - */ -uint8_t WIZCHIP_READ (uint32_t AddrSel); - -/** - * @ingroup Basic_IO_function - * @brief It writes 1 byte value to a register. - * @param AddrSel Register address - * @param wb Write data - * @return void - */ -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb ); - -/** - * @ingroup Basic_IO_function - * @brief It reads sequence data from registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to read data - * @param len Data length - */ -void WIZCHIP_READ_BUF (uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It writes sequence data to registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to write data - * @param len Data length - */ -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -///////////////////////////////// -// Common Register I/O function // -///////////////////////////////// -/** - * @ingroup Common_register_access_function - * @brief Set Mode Register - * @param (uint8_t)mr The value to be set. - * @sa getMR() - */ -#define setMR(mr) \ - WIZCHIP_WRITE(MR,mr) - - -/** - * @ingroup Common_register_access_function - * @brief Get Mode Register - * @return uint8_t. The value of Mode register. - * @sa setMR() - */ -#define getMR() \ - WIZCHIP_READ(MR) - -/** - * @ingroup Common_register_access_function - * @brief Set gateway IP address - * @param (uint8_t*)gar Pointer variable to set gateway IP address. It should be allocated 4 bytes. - * @sa getGAR() - */ -#define setGAR(gar) \ - WIZCHIP_WRITE_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Get gateway IP address - * @param (uint8_t*)gar Pointer variable to get gateway IP address. It should be allocated 4 bytes. - * @sa setGAR() - */ -#define getGAR(gar) \ - WIZCHIP_READ_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Set subnet mask address - * @param (uint8_t*)subr Pointer variable to set subnet mask address. It should be allocated 4 bytes. - * @sa getSUBR() - */ -#define setSUBR(subr) \ - WIZCHIP_WRITE_BUF(SUBR, subr,4) - - -/** - * @ingroup Common_register_access_function - * @brief Get subnet mask address - * @param (uint8_t*)subr Pointer variable to get subnet mask address. It should be allocated 4 bytes. - * @sa setSUBR() - */ -#define getSUBR(subr) \ - WIZCHIP_READ_BUF(SUBR, subr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set local MAC address - * @param (uint8_t*)shar Pointer variable to set local MAC address. It should be allocated 6 bytes. - * @sa getSHAR() - */ -#define setSHAR(shar) \ - WIZCHIP_WRITE_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local MAC address - * @param (uint8_t*)shar Pointer variable to get local MAC address. It should be allocated 6 bytes. - * @sa setSHAR() - */ -#define getSHAR(shar) \ - WIZCHIP_READ_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set local IP address - * @param (uint8_t*)sipr Pointer variable to set local IP address. It should be allocated 4 bytes. - * @sa getSIPR() - */ -#define setSIPR(sipr) \ - WIZCHIP_WRITE_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)sipr Pointer variable to get local IP address. It should be allocated 4 bytes. - * @sa setSIPR() - */ -#define getSIPR(sipr) \ - WIZCHIP_READ_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set INTLEVEL register - * @param (uint16_t)intlevel Value to set @ref INTLEVEL register. - * @sa getINTLEVEL() - */ -#define setINTLEVEL(intlevel) {\ - WIZCHIP_WRITE(INTLEVEL, (uint8_t)(intlevel >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(INTLEVEL,1), (uint8_t) intlevel); \ - } - - -/** - * @ingroup Common_register_access_function - * @brief Get INTLEVEL register - * @return uint16_t. Value of @ref INTLEVEL register. - * @sa setINTLEVEL() - */ -#define getINTLEVEL() \ - ((WIZCHIP_READ(INTLEVEL) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(INTLEVEL,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref IR register - * @param (uint8_t)ir Value to set @ref IR register. - * @sa getIR() - */ -#define setIR(ir) \ - WIZCHIP_WRITE(IR, (ir & 0xF0)) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IR register - * @return uint8_t. Value of @ref IR register. - * @sa setIR() - */ -#define getIR() \ - (WIZCHIP_READ(IR) & 0xF0) -/** - * @ingroup Common_register_access_function - * @brief Set @ref IMR register - * @param (uint8_t)imr Value to set @ref IMR register. - * @sa getIMR() - */ -#define setIMR(imr) \ - WIZCHIP_WRITE(IMR, imr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IMR register - * @return uint8_t. Value of @ref IMR register. - * @sa setIMR() - */ -#define getIMR() \ - WIZCHIP_READ(IMR) - - -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIR register - * @param (uint8_t)sir Value to set @ref SIR register. - * @sa getSIR() - */ -#define setSIR(sir) \ - WIZCHIP_WRITE(SIR, sir) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIR register - * @return uint8_t. Value of @ref SIR register. - * @sa setSIR() - */ -#define getSIR() \ - WIZCHIP_READ(SIR) -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIMR register - * @param (uint8_t)simr Value to set @ref SIMR register. - * @sa getSIMR() - */ -#define setSIMR(simr) \ - WIZCHIP_WRITE(SIMR, simr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIMR register - * @return uint8_t. Value of @ref SIMR register. - * @sa setSIMR() - */ -#define getSIMR() \ - WIZCHIP_READ(SIMR) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RTR register - * @param (uint16_t)rtr Value to set @ref RTR register. - * @sa getRTR() - */ -#define setRTR(rtr) {\ - WIZCHIP_WRITE(RTR, (uint8_t)(rtr >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(RTR,1), (uint8_t) rtr); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RTR register - * @return uint16_t. Value of @ref RTR register. - * @sa setRTR() - */ -#define getRTR() \ - ((WIZCHIP_READ(RTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(RTR,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RCR register - * @param (uint8_t)rcr Value to set @ref RCR register. - * @sa getRCR() - */ -#define setRCR(rcr) \ - WIZCHIP_WRITE(RCR, rcr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RCR register - * @return uint8_t. Value of @ref RCR register. - * @sa setRCR() - */ -#define getRCR() \ - WIZCHIP_READ(RCR) - -//================================================== test done =========================================================== - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PTIMER register - * @param (uint8_t)ptimer Value to set @ref PTIMER register. - * @sa getPTIMER() - */ -#define setPTIMER(ptimer) \ - WIZCHIP_WRITE(PTIMER, ptimer) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PTIMER register - * @return uint8_t. Value of @ref PTIMER register. - * @sa setPTIMER() - */ -#define getPTIMER() \ - WIZCHIP_READ(PTIMER) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMAGIC register - * @param (uint8_t)pmagic Value to set @ref PMAGIC register. - * @sa getPMAGIC() - */ -#define setPMAGIC(pmagic) \ - WIZCHIP_WRITE(PMAGIC, pmagic) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMAGIC register - * @return uint8_t. Value of @ref PMAGIC register. - * @sa setPMAGIC() - */ -#define getPMAGIC() \ - WIZCHIP_READ(PMAGIC) - -/** - * @ingroup Common_register_access_function - * @brief Set PHAR address - * @param (uint8_t*)phar Pointer variable to set PPP destination MAC register address. It should be allocated 6 bytes. - * @sa getPHAR() - */ -#define setPHAR(phar) \ - WIZCHIP_WRITE_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)phar Pointer variable to PPP destination MAC register address. It should be allocated 6 bytes. - * @sa setPHAR() - */ -#define getPHAR(phar) \ - WIZCHIP_READ_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PSID register - * @param (uint16_t)psid Value to set @ref PSID register. - * @sa getPSID() - */ -#define setPSID(psid) {\ - WIZCHIP_WRITE(PSID, (uint8_t)(psid >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PSID,1), (uint8_t) psid); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PSID register - * @return uint16_t. Value of @ref PSID register. - * @sa setPSID() - */ -//uint16_t getPSID(void); -#define getPSID() \ - ((WIZCHIP_READ(PSID) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PSID,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMRU register - * @param (uint16_t)pmru Value to set @ref PMRU register. - * @sa getPMRU() - */ -#define setPMRU(pmru) { \ - WIZCHIP_WRITE(PMRU, (uint8_t)(pmru>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PMRU,1), (uint8_t) pmru); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMRU register - * @return uint16_t. Value of @ref PMRU register. - * @sa setPMRU() - */ -#define getPMRU() \ - ((WIZCHIP_READ(PMRU) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PMRU,1))) - -/** - * @ingroup Common_register_access_function - * @brief Get unreachable IP address - * @param (uint8_t*)uipr Pointer variable to get unreachable IP address. It should be allocated 4 bytes. - */ -#define getUIPR(uipr) \ - WIZCHIP_READ_BUF(UIPR,uipr,6) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref UPORTR register - * @return uint16_t. Value of @ref UPORTR register. - */ -#define getUPORTR() \ - ((WIZCHIP_READ(UPORTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(UPORTR,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PHYCFGR register - * @param (uint8_t)phycfgr Value to set @ref PHYCFGR register. - * @sa getPHYCFGR() - */ -#define setPHYCFGR(phycfgr) \ - WIZCHIP_WRITE(PHYCFGR, phycfgr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PHYCFGR register - * @return uint8_t. Value of @ref PHYCFGR register. - * @sa setPHYCFGR() - */ -#define getPHYCFGR() \ - WIZCHIP_READ(PHYCFGR) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref VERSIONR register - * @return uint8_t. Value of @ref VERSIONR register. - */ -#define getVERSIONR() \ - WIZCHIP_READ(VERSIONR) - -///////////////////////////////////// - -/////////////////////////////////// -// Socket N register I/O function // -/////////////////////////////////// -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)mr Value to set @ref Sn_MR - * @sa getSn_MR() - */ -#define setSn_MR(sn, mr) \ - WIZCHIP_WRITE(Sn_MR(sn),mr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_MR. - * @sa setSn_MR() - */ -#define getSn_MR(sn) \ - WIZCHIP_READ(Sn_MR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)cr Value to set @ref Sn_CR - * @sa getSn_CR() - */ -#define setSn_CR(sn, cr) \ - WIZCHIP_WRITE(Sn_CR(sn), cr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_CR. - * @sa setSn_CR() - */ -#define getSn_CR(sn) \ - WIZCHIP_READ(Sn_CR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ir Value to set @ref Sn_IR - * @sa getSn_IR() - */ -#define setSn_IR(sn, ir) \ - WIZCHIP_WRITE(Sn_IR(sn), (ir & 0x1F)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IR. - * @sa setSn_IR() - */ -#define getSn_IR(sn) \ - (WIZCHIP_READ(Sn_IR(sn)) & 0x1F) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)imr Value to set @ref Sn_IMR - * @sa getSn_IMR() - */ -#define setSn_IMR(sn, imr) \ - WIZCHIP_WRITE(Sn_IMR(sn), (imr & 0x1F)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IMR. - * @sa setSn_IMR() - */ -#define getSn_IMR(sn) \ - (WIZCHIP_READ(Sn_IMR(sn)) & 0x1F) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_SR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_SR. - */ -#define getSn_SR(sn) \ - WIZCHIP_READ(Sn_SR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)port Value to set @ref Sn_PORT. - * @sa getSn_PORT() - */ -#define setSn_PORT(sn, port) { \ - WIZCHIP_WRITE(Sn_PORT(sn), (uint8_t)(port >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_PORT(sn),1), (uint8_t) port); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_PORT. - * @sa setSn_PORT() - */ -#define getSn_PORT(sn) \ - ((WIZCHIP_READ(Sn_PORT(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_PORT(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DHAR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to set socket n destination hardware address. It should be allocated 6 bytes. - * @sa getSn_DHAR() - */ -#define setSn_DHAR(sn, dhar) \ - WIZCHIP_WRITE_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to get socket n destination hardware address. It should be allocated 6 bytes. - * @sa setSn_DHAR() - */ -#define getSn_DHAR(sn, dhar) \ - WIZCHIP_READ_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to set socket n destination IP address. It should be allocated 4 bytes. - * @sa getSn_DIPR() - */ -#define setSn_DIPR(sn, dipr) \ - WIZCHIP_WRITE_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to get socket n destination IP address. It should be allocated 4 bytes. - * @sa SetSn_DIPR() - */ -#define getSn_DIPR(sn, dipr) \ - WIZCHIP_READ_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)dport Value to set @ref Sn_DPORT - * @sa getSn_DPORT() - */ -#define setSn_DPORT(sn, dport) { \ - WIZCHIP_WRITE(Sn_DPORT(sn), (uint8_t) (dport>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_DPORT(sn),1), (uint8_t) dport); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_DPORT. - * @sa setSn_DPORT() - */ -#define getSn_DPORT(sn) \ - ((WIZCHIP_READ(Sn_DPORT(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_DPORT(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)mss Value to set @ref Sn_MSSR - * @sa setSn_MSSR() - */ -#define setSn_MSSR(sn, mss) { \ - WIZCHIP_WRITE(Sn_MSSR(sn), (uint8_t)(mss>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_MSSR(sn),1), (uint8_t) mss); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_MSSR. - * @sa setSn_MSSR() - */ -#define getSn_MSSR(sn) \ - ((WIZCHIP_READ(Sn_MSSR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_MSSR(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)tos Value to set @ref Sn_TOS - * @sa getSn_TOS() - */ -#define setSn_TOS(sn, tos) \ - WIZCHIP_WRITE(Sn_TOS(sn), tos) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of Sn_TOS. - * @sa setSn_TOS() - */ -#define getSn_TOS(sn) \ - WIZCHIP_READ(Sn_TOS(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ttl Value to set @ref Sn_TTL - * @sa getSn_TTL() - */ -#define setSn_TTL(sn, ttl) \ - WIZCHIP_WRITE(Sn_TTL(sn), ttl) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TTL. - * @sa setSn_TTL() - */ -#define getSn_TTL(sn) \ - WIZCHIP_READ(Sn_TTL(sn)) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)rxbufsize Value to set @ref Sn_RXBUF_SIZE - * @sa getSn_RXBUF_SIZE() - */ -#define setSn_RXBUF_SIZE(sn, rxbufsize) \ - WIZCHIP_WRITE(Sn_RXBUF_SIZE(sn),rxbufsize) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_RXBUF_SIZE. - * @sa setSn_RXBUF_SIZE() - */ -#define getSn_RXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_RXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)txbufsize Value to set @ref Sn_TXBUF_SIZE - * @sa getSn_TXBUF_SIZE() - */ -#define setSn_TXBUF_SIZE(sn, txbufsize) \ - WIZCHIP_WRITE(Sn_TXBUF_SIZE(sn), txbufsize) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TXBUF_SIZE. - * @sa setSn_TXBUF_SIZE() - */ -#define getSn_TXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_TXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_FSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_FSR. - */ -uint16_t getSn_TX_FSR(uint8_t sn); - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_RD. - */ -#define getSn_TX_RD(sn) \ - ((WIZCHIP_READ(Sn_TX_RD(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_RD(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)txwr Value to set @ref Sn_TX_WR - * @sa GetSn_TX_WR() - */ -#define setSn_TX_WR(sn, txwr) { \ - WIZCHIP_WRITE(Sn_TX_WR(sn), (uint8_t)(txwr>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_TX_WR(sn),1), (uint8_t) txwr); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_WR. - * @sa setSn_TX_WR() - */ -#define getSn_TX_WR(sn) \ - ((WIZCHIP_READ(Sn_TX_WR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_WR(sn),1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_RSR. - */ -uint16_t getSn_RX_RSR(uint8_t sn); - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)rxrd Value to set @ref Sn_RX_RD - * @sa getSn_RX_RD() - */ -#define setSn_RX_RD(sn, rxrd) { \ - WIZCHIP_WRITE(Sn_RX_RD(sn), (uint8_t)(rxrd>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_RX_RD(sn),1), (uint8_t) rxrd); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @regurn uint16_t. Value of @ref Sn_RX_RD. - * @sa setSn_RX_RD() - */ -#define getSn_RX_RD(sn) \ - ((WIZCHIP_READ(Sn_RX_RD(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RD(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_WR. - */ -#define getSn_RX_WR(sn) \ - ((WIZCHIP_READ(Sn_RX_WR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_WR(sn),1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)frag Value to set @ref Sn_FRAG - * @sa getSn_FRAD() - */ -#define setSn_FRAG(sn, frag) { \ - WIZCHIP_WRITE(Sn_FRAG(sn), (uint8_t)(frag >>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1), (uint8_t) frag); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_FRAG. - * @sa setSn_FRAG() - */ -#define getSn_FRAG(sn) \ - ((WIZCHIP_READ(Sn_FRAG(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)kpalvt Value to set @ref Sn_KPALVTR - * @sa getSn_KPALVTR() - */ -#define setSn_KPALVTR(sn, kpalvt) \ - WIZCHIP_WRITE(Sn_KPALVTR(sn), kpalvt) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_KPALVTR. - * @sa setSn_KPALVTR() - */ -#define getSn_KPALVTR(sn) \ - WIZCHIP_READ(Sn_KPALVTR(sn)) - -////////////////////////////////////// - -///////////////////////////////////// -// Sn_TXBUF & Sn_RXBUF IO function // -///////////////////////////////////// -/** - * @brief Gets the max buffer size of socket sn passed as parameter. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n RX max buffer size. - */ -#define getSn_RxMAX(sn) \ - (getSn_RXBUF_SIZE(sn) << 10) - -/** - * @brief Gets the max buffer size of socket sn passed as parameters. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n TX max buffer size. - */ -//uint16_t getSn_TxMAX(uint8_t sn); -#define getSn_TxMAX(sn) \ - (getSn_TXBUF_SIZE(sn) << 10) - -/** - * @ingroup Basic_IO_function - * @brief It copies data to internal TX memory - * - * @details This function reads the Tx write pointer register and after that, - * it copies the wizdata(pointer buffer) of the length of len(variable) bytes to internal TX memory - * and updates the Tx write pointer register. - * This function is being called by send() and sendto() function also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to write data - * @param len Data length - * @sa wiz_recv_data() - */ -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It copies data to your buffer from internal RX memory - * - * @details This function read the Rx read pointer register and after that, - * it copies the received data from internal RX memory - * to wizdata(pointer variable) of the length of len(variable) bytes. - * This function is being called by recv() also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to read data - * @param len Data length - * @sa wiz_send_data() - */ -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It discard the received data in RX memory. - * @details It discards the data of the length of len(variable) bytes in internal RX memory. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param len Data length - */ -void wiz_recv_ignore(uint8_t sn, uint16_t len); - -#endif // _W5500_H_ diff --git a/drivers/wiznet5k/ethernet/wizchip_conf.c b/drivers/wiznet5k/ethernet/wizchip_conf.c deleted file mode 100644 index c7a2f50f04..0000000000 --- a/drivers/wiznet5k/ethernet/wizchip_conf.c +++ /dev/null @@ -1,662 +0,0 @@ -//****************************************************************************/ -//! -//! \file wizchip_conf.c -//! \brief WIZCHIP Config Header File. -//! \version 1.0.1 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.1 Refer to M20140501 -//! 1. Explicit type casting in wizchip_bus_readbyte() & wizchip_bus_writebyte() -// Issued by Mathias ClauBen. -//! uint32_t type converts into ptrdiff_t first. And then recoverting it into uint8_t* -//! For remove the warning when pointer type size is not 32bit. -//! If ptrdiff_t doesn't support in your complier, You should must replace ptrdiff_t into your suitable pointer type. -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//*****************************************************************************/ -//A20140501 : for use the type - ptrdiff_t -#include -// - -#include "wizchip_conf.h" -#include "socket.h" - -/** - * @brief Default function to enable interrupt. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cris_enter(void) {}; -/** - * @brief Default function to disable interrupt. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cris_exit(void) {}; -/** - * @brief Default function to select chip. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cs_select(void) {}; -/** - * @brief Default function to deselect chip. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cs_deselect(void) {}; -/** - * @brief Default function to read in direct or indirect interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ - //M20140501 : Explict pointer type casting -//uint8_t wizchip_bus_readbyte(uint32_t AddrSel) { return * ((volatile uint8_t *) AddrSel); }; -uint8_t wizchip_bus_readbyte(uint32_t AddrSel) { return * ((volatile uint8_t *)((ptrdiff_t) AddrSel)); }; -/** - * @brief Default function to write in direct or indirect interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ - -//M20140501 : Explict pointer type casting -//void wizchip_bus_writebyte(uint32_t AddrSel, uint8_t wb) { *((volatile uint8_t*) AddrSel) = wb; }; -void wizchip_bus_writebyte(uint32_t AddrSel, uint8_t wb) { *((volatile uint8_t*)((ptrdiff_t)AddrSel)) = wb; }; - -/** - * @brief Default function to read in SPI interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_spi_readbytes(uint8_t *buf, uint32_t len) {} -/** - * @brief Default function to write in SPI interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_spi_writebytes(const uint8_t *buf, uint32_t len) {} - -/** - * @\ref _WIZCHIP instance - */ -_WIZCHIP WIZCHIP = - { - .id = _WIZCHIP_ID_, - .if_mode = _WIZCHIP_IO_MODE_, - .CRIS._enter = wizchip_cris_enter, - .CRIS._exit = wizchip_cris_exit, - .CS._select = wizchip_cs_select, - .CS._deselect = wizchip_cs_deselect, - .IF.BUS._read_byte = wizchip_bus_readbyte, - .IF.BUS._write_byte = wizchip_bus_writebyte -// .IF.SPI._read_byte = wizchip_spi_readbyte, -// .IF.SPI._write_byte = wizchip_spi_writebyte - }; - -#if _WIZCHIP_ == 5200 // for W5200 ARP errata -static uint8_t _SUBN_[4]; // subnet -#endif -static uint8_t _DNS_[4]; // DNS server ip address -static dhcp_mode _DHCP_; // DHCP mode - -void reg_wizchip_cris_cbfunc(void(*cris_en)(void), void(*cris_ex)(void)) -{ - if(!cris_en || !cris_ex) - { - WIZCHIP.CRIS._enter = wizchip_cris_enter; - WIZCHIP.CRIS._exit = wizchip_cris_exit; - } - else - { - WIZCHIP.CRIS._enter = cris_en; - WIZCHIP.CRIS._exit = cris_ex; - } -} - -void reg_wizchip_cs_cbfunc(void(*cs_sel)(void), void(*cs_desel)(void)) -{ - if(!cs_sel || !cs_desel) - { - WIZCHIP.CS._select = wizchip_cs_select; - WIZCHIP.CS._deselect = wizchip_cs_deselect; - } - else - { - WIZCHIP.CS._select = cs_sel; - WIZCHIP.CS._deselect = cs_desel; - } -} - -void reg_wizchip_bus_cbfunc(uint8_t(*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, uint8_t wb)) -{ - while(!(WIZCHIP.if_mode & _WIZCHIP_IO_MODE_BUS_)); - - if(!bus_rb || !bus_wb) - { - WIZCHIP.IF.BUS._read_byte = wizchip_bus_readbyte; - WIZCHIP.IF.BUS._write_byte = wizchip_bus_writebyte; - } - else - { - WIZCHIP.IF.BUS._read_byte = bus_rb; - WIZCHIP.IF.BUS._write_byte = bus_wb; - } -} - -void reg_wizchip_spi_cbfunc(void (*spi_rb)(uint8_t *, uint32_t), void (*spi_wb)(const uint8_t *, uint32_t)) -{ - while(!(WIZCHIP.if_mode & _WIZCHIP_IO_MODE_SPI_)); - - if(!spi_rb || !spi_wb) - { - WIZCHIP.IF.SPI._read_bytes = wizchip_spi_readbytes; - WIZCHIP.IF.SPI._write_bytes = wizchip_spi_writebytes; - } - else - { - WIZCHIP.IF.SPI._read_bytes = spi_rb; - WIZCHIP.IF.SPI._write_bytes = spi_wb; - } -} - -int8_t ctlwizchip(ctlwizchip_type cwtype, void* arg) -{ - uint8_t tmp = 0; - uint8_t* ptmp[2] = {0,0}; - switch(cwtype) - { - case CW_RESET_WIZCHIP: - wizchip_sw_reset(); - break; - case CW_INIT_WIZCHIP: - if(arg != 0) - { - ptmp[0] = (uint8_t*)arg; - ptmp[1] = ptmp[0] + _WIZCHIP_SOCK_NUM_; - } - return wizchip_init(ptmp[0], ptmp[1]); - case CW_CLR_INTERRUPT: - wizchip_clrinterrupt(*((intr_kind*)arg)); - break; - case CW_GET_INTERRUPT: - *((intr_kind*)arg) = wizchip_getinterrupt(); - break; - case CW_SET_INTRMASK: - wizchip_setinterruptmask(*((intr_kind*)arg)); - break; - case CW_GET_INTRMASK: - *((intr_kind*)arg) = wizchip_getinterruptmask(); - break; - #if _WIZCHIP_ > 5100 - case CW_SET_INTRTIME: - setINTLEVEL(*(uint16_t*)arg); - break; - case CW_GET_INTRTIME: - *(uint16_t*)arg = getINTLEVEL(); - break; - #endif - case CW_GET_ID: - ((uint8_t*)arg)[0] = WIZCHIP.id[0]; - ((uint8_t*)arg)[1] = WIZCHIP.id[1]; - ((uint8_t*)arg)[2] = WIZCHIP.id[2]; - ((uint8_t*)arg)[3] = WIZCHIP.id[3]; - ((uint8_t*)arg)[4] = WIZCHIP.id[4]; - ((uint8_t*)arg)[5] = 0; - break; - #if _WIZCHIP_ == 5500 - case CW_RESET_PHY: - wizphy_reset(); - break; - case CW_SET_PHYCONF: - wizphy_setphyconf((wiz_PhyConf*)arg); - break; - case CW_GET_PHYCONF: - wizphy_getphyconf((wiz_PhyConf*)arg); - break; - case CW_GET_PHYSTATUS: - break; - case CW_SET_PHYPOWMODE: - return wizphy_setphypmode(*(uint8_t*)arg); - #endif - case CW_GET_PHYPOWMODE: - tmp = wizphy_getphypmode(); - if((int8_t)tmp == -1) return -1; - *(uint8_t*)arg = tmp; - break; - case CW_GET_PHYLINK: - tmp = wizphy_getphylink(); - if((int8_t)tmp == -1) return -1; - *(uint8_t*)arg = tmp; - break; - default: - return -1; - } - return 0; -} - - -int8_t ctlnetwork(ctlnetwork_type cntype, void* arg) -{ - - switch(cntype) - { - case CN_SET_NETINFO: - wizchip_setnetinfo((wiz_NetInfo*)arg); - break; - case CN_GET_NETINFO: - wizchip_getnetinfo((wiz_NetInfo*)arg); - break; - case CN_SET_NETMODE: - return wizchip_setnetmode(*(netmode_type*)arg); - case CN_GET_NETMODE: - *(netmode_type*)arg = wizchip_getnetmode(); - break; - case CN_SET_TIMEOUT: - wizchip_settimeout((wiz_NetTimeout*)arg); - break; - case CN_GET_TIMEOUT: - wizchip_gettimeout((wiz_NetTimeout*)arg); - break; - default: - return -1; - } - return 0; -} - -void wizchip_sw_reset(void) -{ - uint8_t gw[4], sn[4], sip[4]; - uint8_t mac[6]; - getSHAR(mac); - getGAR(gw); getSUBR(sn); getSIPR(sip); - setMR(MR_RST); - getMR(); // for delay - setSHAR(mac); - setGAR(gw); - setSUBR(sn); - setSIPR(sip); -} - -int8_t wizchip_init(uint8_t* txsize, uint8_t* rxsize) -{ - int8_t i; - int8_t tmp = 0; - wizchip_sw_reset(); - if(txsize) - { - tmp = 0; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - tmp += txsize[i]; - if(tmp > 16) return -1; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - setSn_TXBUF_SIZE(i, txsize[i]); - } - if(rxsize) - { - tmp = 0; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - tmp += rxsize[i]; - if(tmp > 16) return -1; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - setSn_RXBUF_SIZE(i, rxsize[i]); - } - - WIZCHIP_EXPORT(socket_reset)(); - - return 0; -} - -void wizchip_clrinterrupt(intr_kind intr) -{ - uint8_t ir = (uint8_t)intr; - uint8_t sir = (uint8_t)((uint16_t)intr >> 8); -#if _WIZCHIP_ < 5500 - ir |= (1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - ir |= (1 << 6); -#endif - -#if _WIZCHIP_ < 5200 - sir &= 0x0F; -#endif - -#if _WIZCHIP_ == 5100 - ir |= sir; - setIR(ir); -#else - setIR(ir); - setSIR(sir); -#endif -} - -intr_kind wizchip_getinterrupt(void) -{ - uint8_t ir = 0; - uint8_t sir = 0; - uint16_t ret = 0; -#if _WIZCHIP_ == 5100 - ir = getIR(); - sir = ir 0x0F; -#else - ir = getIR(); - sir = getSIR(); -#endif - -#if _WIZCHIP_ < 5500 - ir &= ~(1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - ir &= ~(1 << 6); -#endif - ret = sir; - ret = (ret << 8) + ir; - return (intr_kind)ret; -} - -void wizchip_setinterruptmask(intr_kind intr) -{ - uint8_t imr = (uint8_t)intr; - uint8_t simr = (uint8_t)((uint16_t)intr >> 8); -#if _WIZCHIP_ < 5500 - imr &= ~(1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - imr &= ~(1 << 6); -#endif - -#if _WIZCHIP_ < 5200 - simr &= 0x0F; -#endif - -#if _WIZCHIP_ == 5100 - imr |= simr; - setIMR(imr); -#else - setIMR(imr); - setSIMR(simr); -#endif -} - -intr_kind wizchip_getinterruptmask(void) -{ - uint8_t imr = 0; - uint8_t simr = 0; - uint16_t ret = 0; -#if _WIZCHIP_ == 5100 - imr = getIMR(); - simr = imr 0x0F; -#else - imr = getIMR(); - simr = getSIMR(); -#endif - -#if _WIZCHIP_ < 5500 - imr &= ~(1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - imr &= ~(1 << 6); // IK_DEST_UNREACH -#endif - ret = simr; - ret = (ret << 8) + imr; - return (intr_kind)ret; -} - -int8_t wizphy_getphylink(void) -{ - int8_t tmp; -#if _WIZCHIP_ == 5200 - if(getPHYSTATUS() & PHYSTATUS_LINK) - tmp = PHY_LINK_ON; - else - tmp = PHY_LINK_OFF; -#elif _WIZCHIP_ == 5500 - if(getPHYCFGR() & PHYCFGR_LNK_ON) - tmp = PHY_LINK_ON; - else - tmp = PHY_LINK_OFF; -#else - tmp = -1; -#endif - return tmp; -} - -#if _WIZCHIP_ > 5100 - -int8_t wizphy_getphypmode(void) -{ - int8_t tmp = 0; - #if _WIZCHIP_ == 5200 - if(getPHYSTATUS() & PHYSTATUS_POWERDOWN) - tmp = PHY_POWER_DOWN; - else - tmp = PHY_POWER_NORM; - #elif _WIZCHIP_ == 5500 - if(getPHYCFGR() & PHYCFGR_OPMDC_PDOWN) - tmp = PHY_POWER_DOWN; - else - tmp = PHY_POWER_NORM; - #else - tmp = -1; - #endif - return tmp; -} -#endif - -#if _WIZCHIP_ == 5500 -void wizphy_reset(void) -{ - uint8_t tmp = getPHYCFGR(); - tmp &= PHYCFGR_RST; - setPHYCFGR(tmp); - tmp = getPHYCFGR(); - tmp |= ~PHYCFGR_RST; - setPHYCFGR(tmp); -} - -void wizphy_setphyconf(wiz_PhyConf* phyconf) -{ - uint8_t tmp = 0; - if(phyconf->by == PHY_CONFBY_SW) - tmp |= PHYCFGR_OPMD; - else - tmp &= ~PHYCFGR_OPMD; - if(phyconf->mode == PHY_MODE_AUTONEGO) - tmp |= PHYCFGR_OPMDC_ALLA; - else - { - if(phyconf->duplex == PHY_DUPLEX_FULL) - { - if(phyconf->speed == PHY_SPEED_100) - tmp |= PHYCFGR_OPMDC_100F; - else - tmp |= PHYCFGR_OPMDC_10F; - } - else - { - if(phyconf->speed == PHY_SPEED_100) - tmp |= PHYCFGR_OPMDC_100H; - else - tmp |= PHYCFGR_OPMDC_10H; - } - } - setPHYCFGR(tmp); - wizphy_reset(); -} - -void wizphy_getphyconf(wiz_PhyConf* phyconf) -{ - uint8_t tmp = 0; - tmp = getPHYCFGR(); - phyconf->by = (tmp & PHYCFGR_OPMD) ? PHY_CONFBY_SW : PHY_CONFBY_HW; - switch(tmp & PHYCFGR_OPMDC_ALLA) - { - case PHYCFGR_OPMDC_ALLA: - case PHYCFGR_OPMDC_100FA: - phyconf->mode = PHY_MODE_AUTONEGO; - break; - default: - phyconf->mode = PHY_MODE_MANUAL; - break; - } - switch(tmp & PHYCFGR_OPMDC_ALLA) - { - case PHYCFGR_OPMDC_100FA: - case PHYCFGR_OPMDC_100F: - case PHYCFGR_OPMDC_100H: - phyconf->speed = PHY_SPEED_100; - break; - default: - phyconf->speed = PHY_SPEED_10; - break; - } - switch(tmp & PHYCFGR_OPMDC_ALLA) - { - case PHYCFGR_OPMDC_100FA: - case PHYCFGR_OPMDC_100F: - case PHYCFGR_OPMDC_10F: - phyconf->duplex = PHY_DUPLEX_FULL; - break; - default: - phyconf->duplex = PHY_DUPLEX_HALF; - break; - } -} - -void wizphy_getphystat(wiz_PhyConf* phyconf) -{ - uint8_t tmp = getPHYCFGR(); - phyconf->duplex = (tmp & PHYCFGR_DPX_FULL) ? PHY_DUPLEX_FULL : PHY_DUPLEX_HALF; - phyconf->speed = (tmp & PHYCFGR_SPD_100) ? PHY_SPEED_100 : PHY_SPEED_10; -} - -int8_t wizphy_setphypmode(uint8_t pmode) -{ - uint8_t tmp = 0; - tmp = getPHYCFGR(); - if((tmp & PHYCFGR_OPMD)== 0) return -1; - tmp &= ~PHYCFGR_OPMDC_ALLA; - if( pmode == PHY_POWER_DOWN) - tmp |= PHYCFGR_OPMDC_PDOWN; - else - tmp |= PHYCFGR_OPMDC_ALLA; - setPHYCFGR(tmp); - wizphy_reset(); - tmp = getPHYCFGR(); - if( pmode == PHY_POWER_DOWN) - { - if(tmp & PHYCFGR_OPMDC_PDOWN) return 0; - } - else - { - if(tmp & PHYCFGR_OPMDC_ALLA) return 0; - } - return -1; -} -#endif - - -void wizchip_setnetinfo(wiz_NetInfo* pnetinfo) -{ - setSHAR(pnetinfo->mac); - setGAR(pnetinfo->gw); - setSUBR(pnetinfo->sn); - setSIPR(pnetinfo->ip); -#if _WIZCHIP_ == 5200 // for W5200 ARP errata - _SUBN_[0] = pnetinfo->sn[0]; - _SUBN_[1] = pnetinfo->sn[1]; - _SUBN_[2] = pnetinfo->sn[2]; - _SUBN_[3] = pnetinfo->sn[3]; -#endif - _DNS_[0] = pnetinfo->dns[0]; - _DNS_[1] = pnetinfo->dns[1]; - _DNS_[2] = pnetinfo->dns[2]; - _DNS_[3] = pnetinfo->dns[3]; - _DHCP_ = pnetinfo->dhcp; -} - -void wizchip_getnetinfo(wiz_NetInfo* pnetinfo) -{ - getSHAR(pnetinfo->mac); - getGAR(pnetinfo->gw); - getSUBR(pnetinfo->sn); - getSIPR(pnetinfo->ip); -#if _WIZCHIP_ == 5200 // for W5200 ARP errata - pnetinfo->sn[0] = _SUBN_[0]; - pnetinfo->sn[1] = _SUBN_[1]; - pnetinfo->sn[2] = _SUBN_[2]; - pnetinfo->sn[3] = _SUBN_[3]; -#endif - pnetinfo->dns[0]= _DNS_[0]; - pnetinfo->dns[1]= _DNS_[1]; - pnetinfo->dns[2]= _DNS_[2]; - pnetinfo->dns[3]= _DNS_[3]; - pnetinfo->dhcp = _DHCP_; -} - -#if _WIZCHIP_ == 5200 // for W5200 ARP errata -uint8_t *wizchip_getsubn(void) { - return _SUBN_; -} -#endif - -int8_t wizchip_setnetmode(netmode_type netmode) -{ - uint8_t tmp = 0; -#if _WIZCHIP_ != 5500 - if(netmode & ~(NM_WAKEONLAN | NM_PPPOE | NM_PINGBLOCK)) return -1; -#else - if(netmode & ~(NM_WAKEONLAN | NM_PPPOE | NM_PINGBLOCK | NM_FORCEARP)) return -1; -#endif - tmp = getMR(); - tmp |= (uint8_t)netmode; - setMR(tmp); - return 0; -} - -netmode_type wizchip_getnetmode(void) -{ - return (netmode_type) getMR(); -} - -void wizchip_settimeout(wiz_NetTimeout* nettime) -{ - setRCR(nettime->retry_cnt); - setRTR(nettime->time_100us); -} - -void wizchip_gettimeout(wiz_NetTimeout* nettime) -{ - nettime->retry_cnt = getRCR(); - nettime->time_100us = getRTR(); -} diff --git a/drivers/wiznet5k/ethernet/wizchip_conf.h b/drivers/wiznet5k/ethernet/wizchip_conf.h deleted file mode 100644 index 509ba0668a..0000000000 --- a/drivers/wiznet5k/ethernet/wizchip_conf.h +++ /dev/null @@ -1,554 +0,0 @@ -//***************************************************************************** -// -//! \file wizchip_conf.h -//! \brief WIZCHIP Config Header File. -//! \version 1.0.0 -//! \date 2013/10/21 -//! \par Revision history -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -/** - * @defgroup extra_functions 2. WIZnet Extra Functions - * - * @brief These functions is optional function. It could be replaced at WIZCHIP I/O function because they were made by WIZCHIP I/O functions. - * @details There are functions of configuring WIZCHIP, network, interrupt, phy, network information and timer. \n - * - */ - -#ifndef _WIZCHIP_CONF_H_ -#define _WIZCHIP_CONF_H_ - -#include -/** - * @brief Select WIZCHIP. - * @todo You should select one, \b 5100, \b 5200 ,\b 5500 or etc. \n\n - * ex> #define \_WIZCHIP_ 5500 - */ -#ifndef _WIZCHIP_ -#define _WIZCHIP_ 5200 // 5100, 5200, 5500 -#endif - -#define _WIZCHIP_IO_MODE_NONE_ 0x0000 -#define _WIZCHIP_IO_MODE_BUS_ 0x0100 /**< Bus interface mode */ -#define _WIZCHIP_IO_MODE_SPI_ 0x0200 /**< SPI interface mode */ -//#define _WIZCHIP_IO_MODE_IIC_ 0x0400 -//#define _WIZCHIP_IO_MODE_SDIO_ 0x0800 -// Add to -// - -#define _WIZCHIP_IO_MODE_BUS_DIR_ (_WIZCHIP_IO_MODE_BUS_ + 1) /**< BUS interface mode for direct */ -#define _WIZCHIP_IO_MODE_BUS_INDIR_ (_WIZCHIP_IO_MODE_BUS_ + 2) /**< BUS interface mode for indirect */ - -#define _WIZCHIP_IO_MODE_SPI_VDM_ (_WIZCHIP_IO_MODE_SPI_ + 1) /**< SPI interface mode for variable length data*/ -#define _WIZCHIP_IO_MODE_SPI_FDM_ (_WIZCHIP_IO_MODE_SPI_ + 2) /**< SPI interface mode for fixed length data mode*/ - - -#if (_WIZCHIP_ == 5100) - #define _WIZCHIP_ID_ "W5100\0" -/** - * @brief Define interface mode. - * @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ , @ref \_WIZCHIP_IO_MODE_BUS_DIR_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_ - */ - -// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_DIR_ -// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_ - #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_ - -#elif (_WIZCHIP_ == 5200) - #define _WIZCHIP_ID_ "W5200\0" -/** - * @brief Define interface mode. - * @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_ - */ -// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_ - #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_ - #include "w5200/w5200.h" -#elif (_WIZCHIP_ == 5500) - #define _WIZCHIP_ID_ "W5500\0" - -/** - * @brief Define interface mode. \n - * @todo Should select interface mode as chip. - * - @ref \_WIZCHIP_IO_MODE_SPI_ \n - * -@ref \_WIZCHIP_IO_MODE_SPI_VDM_ : Valid only in @ref \_WIZCHIP_ == 5500 \n - * -@ref \_WIZCHIP_IO_MODE_SPI_FDM_ : Valid only in @ref \_WIZCHIP_ == 5500 \n - * - @ref \_WIZCHIP_IO_MODE_BUS_ \n - * - @ref \_WIZCHIP_IO_MODE_BUS_DIR_ \n - * - @ref \_WIZCHIP_IO_MODE_BUS_INDIR_ \n - * - Others will be defined in future. \n\n - * ex> #define \_WIZCHIP_IO_MODE_ \_WIZCHIP_IO_MODE_SPI_VDM_ - * - */ - //#define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_FDM_ - #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_VDM_ - #include "w5500/w5500.h" -#else - #error "Unknown defined _WIZCHIP_. You should define one of 5100, 5200, and 5500 !!!" -#endif - -#ifndef _WIZCHIP_IO_MODE_ - #error "Undefined _WIZCHIP_IO_MODE_. You should define it !!!" -#endif - -/** - * @brief Define I/O base address when BUS IF mode. - * @todo Should re-define it to fit your system when BUS IF Mode (@ref \_WIZCHIP_IO_MODE_BUS_, - * @ref \_WIZCHIP_IO_MODE_BUS_DIR_, @ref \_WIZCHIP_IO_MODE_BUS_INDIR_). \n\n - * ex> #define \_WIZCHIP_IO_BASE_ 0x00008000 - */ -#define _WIZCHIP_IO_BASE_ 0x00000000 // - -#if _WIZCHIP_IO_MODE_ & _WIZCHIP_IO_MODE_BUS_ - #ifndef _WIZCHIP_IO_BASE_ - #error "You should be define _WIZCHIP_IO_BASE to fit your system memory map." - #endif -#endif - -#if _WIZCHIP_ > 5100 - #define _WIZCHIP_SOCK_NUM_ 8 ///< The count of independant socket of @b WIZCHIP -#else - #define _WIZCHIP_SOCK_NUM_ 4 ///< The count of independant socket of @b WIZCHIP -#endif - - -/******************************************************** -* WIZCHIP BASIC IF functions for SPI, SDIO, I2C , ETC. -*********************************************************/ -/** - * @ingroup DATA_TYPE - * @brief The set of callback functions for W5500:@ref WIZCHIP_IO_Functions W5200:@ref WIZCHIP_IO_Functions_W5200 - */ -typedef struct __WIZCHIP -{ - uint16_t if_mode; ///< host interface mode - uint8_t id[6]; ///< @b WIZCHIP ID such as @b 5100, @b 5200, @b 5500, and so on. - /** - * The set of critical section callback func. - */ - struct _CRIS - { - void (*_enter) (void); ///< crtical section enter - void (*_exit) (void); ///< critial section exit - }CRIS; - /** - * The set of @ref\_WIZCHIP_ select control callback func. - */ - struct _CS - { - void (*_select) (void); ///< @ref \_WIZCHIP_ selected - void (*_deselect)(void); ///< @ref \_WIZCHIP_ deselected - }CS; - /** - * The set of interface IO callback func. - */ - union _IF - { - /** - * For BUS interface IO - */ - struct - { - uint8_t (*_read_byte) (uint32_t AddrSel); - void (*_write_byte) (uint32_t AddrSel, uint8_t wb); - }BUS; - /** - * For SPI interface IO - */ - struct - { - void (*_read_bytes) (uint8_t *buf, uint32_t len); - void (*_write_bytes) (const uint8_t *buf, uint32_t len); - }SPI; - // To be added - // - }IF; -}_WIZCHIP; - -extern _WIZCHIP WIZCHIP; - -/** - * @ingroup DATA_TYPE - * WIZCHIP control type enumration used in @ref ctlwizchip(). - */ -typedef enum -{ - CW_RESET_WIZCHIP, ///< Resets WIZCHIP by softly - CW_INIT_WIZCHIP, ///< Inializes to WIZCHIP with SOCKET buffer size 2 or 1 dimension array typed uint8_t. - CW_GET_INTERRUPT, ///< Get Interrupt status of WIZCHIP - CW_CLR_INTERRUPT, ///< Clears interrupt - CW_SET_INTRMASK, ///< Masks interrupt - CW_GET_INTRMASK, ///< Get interrupt mask - CW_SET_INTRTIME, ///< Set interval time between the current and next interrupt. - CW_GET_INTRTIME, ///< Set interval time between the current and next interrupt. - CW_GET_ID, ///< Gets WIZCHIP name. - -#if _WIZCHIP_ == 5500 - CW_RESET_PHY, ///< Resets internal PHY. Valid Only W5000 - CW_SET_PHYCONF, ///< When PHY configured by interal register, PHY operation mode (Manual/Auto, 10/100, Half/Full). Valid Only W5000 - CW_GET_PHYCONF, ///< Get PHY operation mode in interal register. Valid Only W5000 - CW_GET_PHYSTATUS, ///< Get real PHY status on operating. Valid Only W5000 - CW_SET_PHYPOWMODE, ///< Set PHY power mode as noraml and down when PHYSTATUS.OPMD == 1. Valid Only W5000 -#endif - CW_GET_PHYPOWMODE, ///< Get PHY Power mode as down or normal - CW_GET_PHYLINK ///< Get PHY Link status -}ctlwizchip_type; - -/** - * @ingroup DATA_TYPE - * Network control type enumration used in @ref ctlnetwork(). - */ -typedef enum -{ - CN_SET_NETINFO, ///< Set Network with @ref wiz_NetInfo - CN_GET_NETINFO, ///< Get Network with @ref wiz_NetInfo - CN_SET_NETMODE, ///< Set network mode as WOL, PPPoE, Ping Block, and Force ARP mode - CN_GET_NETMODE, ///< Get network mode as WOL, PPPoE, Ping Block, and Force ARP mode - CN_SET_TIMEOUT, ///< Set network timeout as retry count and time. - CN_GET_TIMEOUT, ///< Get network timeout as retry count and time. -}ctlnetwork_type; - -/** - * @ingroup DATA_TYPE - * Interrupt kind when CW_SET_INTRRUPT, CW_GET_INTERRUPT, CW_SET_INTRMASK - * and CW_GET_INTRMASK is used in @ref ctlnetwork(). - * It can be used with OR operation. - */ -typedef enum -{ -#if _WIZCHIP_ > 5200 - IK_WOL = (1 << 4), ///< Wake On Lan by receiving the magic packet. Valid in W500. -#endif - - IK_PPPOE_TERMINATED = (1 << 5), ///< PPPoE Disconnected - -#if _WIZCHIP_ != 5200 - IK_DEST_UNREACH = (1 << 6), ///< Destination IP & Port Unreable, No use in W5200 -#endif - - IK_IP_CONFLICT = (1 << 7), ///< IP conflict occurred - - IK_SOCK_0 = (1 << 8), ///< Socket 0 interrupt - IK_SOCK_1 = (1 << 9), ///< Socket 1 interrupt - IK_SOCK_2 = (1 << 10), ///< Socket 2 interrupt - IK_SOCK_3 = (1 << 11), ///< Socket 3 interrupt -#if _WIZCHIP_ > 5100 - IK_SOCK_4 = (1 << 12), ///< Socket 4 interrupt, No use in 5100 - IK_SOCK_5 = (1 << 13), ///< Socket 5 interrupt, No use in 5100 - IK_SOCK_6 = (1 << 14), ///< Socket 6 interrupt, No use in 5100 - IK_SOCK_7 = (1 << 15), ///< Socket 7 interrupt, No use in 5100 -#endif - -#if _WIZCHIP_ > 5100 - IK_SOCK_ALL = (0xFF << 8) ///< All Socket interrpt -#else - IK_SOCK_ALL = (0x0F << 8) ///< All Socket interrpt -#endif -}intr_kind; - -#define PHY_CONFBY_HW 0 ///< Configured PHY operation mode by HW pin -#define PHY_CONFBY_SW 1 ///< Configured PHY operation mode by SW register -#define PHY_MODE_MANUAL 0 ///< Configured PHY operation mode with user setting. -#define PHY_MODE_AUTONEGO 1 ///< Configured PHY operation mode with auto-negotiation -#define PHY_SPEED_10 0 ///< Link Speed 10 -#define PHY_SPEED_100 1 ///< Link Speed 100 -#define PHY_DUPLEX_HALF 0 ///< Link Half-Duplex -#define PHY_DUPLEX_FULL 1 ///< Link Full-Duplex -#define PHY_LINK_OFF 0 ///< Link Off -#define PHY_LINK_ON 1 ///< Link On -#define PHY_POWER_NORM 0 ///< PHY power normal mode -#define PHY_POWER_DOWN 1 ///< PHY power down mode - - -#if _WIZCHIP_ == 5500 -/** - * @ingroup DATA_TYPE - * It configures PHY configuration when CW_SET PHYCONF or CW_GET_PHYCONF in W5500, - * and it indicates the real PHY status configured by HW or SW in all WIZCHIP. \n - * Valid only in W5500. - */ -typedef struct wiz_PhyConf_t -{ - uint8_t by; ///< set by @ref PHY_CONFBY_HW or @ref PHY_CONFBY_SW - uint8_t mode; ///< set by @ref PHY_MODE_MANUAL or @ref PHY_MODE_AUTONEGO - uint8_t speed; ///< set by @ref PHY_SPEED_10 or @ref PHY_SPEED_100 - uint8_t duplex; ///< set by @ref PHY_DUPLEX_HALF @ref PHY_DUPLEX_FULL - //uint8_t power; ///< set by @ref PHY_POWER_NORM or @ref PHY_POWER_DOWN - //uint8_t link; ///< Valid only in CW_GET_PHYSTATUS. set by @ref PHY_LINK_ON or PHY_DUPLEX_OFF - }wiz_PhyConf; -#endif - -/** - * @ingroup DATA_TYPE - * It used in setting dhcp_mode of @ref wiz_NetInfo. - */ -typedef enum -{ - NETINFO_STATIC = 1, ///< Static IP configuration by manually. - NETINFO_DHCP ///< Dynamic IP configruation from a DHCP sever -}dhcp_mode; - -/** - * @ingroup DATA_TYPE - * Network Information for WIZCHIP - */ -typedef struct wiz_NetInfo_t -{ - uint8_t mac[6]; ///< Source Mac Address - uint8_t ip[4]; ///< Source IP Address - uint8_t sn[4]; ///< Subnet Mask - uint8_t gw[4]; ///< Gateway IP Address - uint8_t dns[4]; ///< DNS server IP Address - dhcp_mode dhcp; ///< 1 - Static, 2 - DHCP -}wiz_NetInfo; - -/** - * @ingroup DATA_TYPE - * Network mode - */ -typedef enum -{ -#if _WIZCHIP_ == 5500 - NM_FORCEARP = (1<<1), ///< Force to APP send whenever udp data is sent. Valid only in W5500 -#endif - NM_WAKEONLAN = (1<<5), ///< Wake On Lan - NM_PINGBLOCK = (1<<4), ///< Block ping-request - NM_PPPOE = (1<<3), ///< PPPoE mode -}netmode_type; - -/** - * @ingroup DATA_TYPE - * Used in CN_SET_TIMEOUT or CN_GET_TIMEOUT of @ref ctlwizchip() for timeout configruation. - */ -typedef struct wiz_NetTimeout_t -{ - uint8_t retry_cnt; ///< retry count - uint16_t time_100us; ///< time unit 100us -}wiz_NetTimeout; - -/** - *@brief Registers call back function for critical section of I/O functions such as - *\ref WIZCHIP_READ, @ref WIZCHIP_WRITE, @ref WIZCHIP_READ_BUF and @ref WIZCHIP_WRITE_BUF. - *@param cris_en : callback function for critical section enter. - *@param cris_ex : callback function for critical section exit. - *@todo Describe @ref WIZCHIP_CRITICAL_ENTER and @ref WIZCHIP_CRITICAL_EXIT marco or register your functions. - *@note If you do not describe or register, default functions(@ref wizchip_cris_enter & @ref wizchip_cris_exit) is called. - */ -void reg_wizchip_cris_cbfunc(void(*cris_en)(void), void(*cris_ex)(void)); - - -/** - *@brief Registers call back function for WIZCHIP select & deselect. - *@param cs_sel : callback function for WIZCHIP select - *@param cs_desel : callback fucntion for WIZCHIP deselect - *@todo Describe @ref wizchip_cs_select and @ref wizchip_cs_deselect function or register your functions. - *@note If you do not describe or register, null function is called. - */ -void reg_wizchip_cs_cbfunc(void(*cs_sel)(void), void(*cs_desel)(void)); - -/** - *@brief Registers call back function for bus interface. - *@param bus_rb : callback function to read byte data using system bus - *@param bus_wb : callback function to write byte data using system bus - *@todo Describe @ref wizchip_bus_readbyte and @ref wizchip_bus_writebyte function - *or register your functions. - *@note If you do not describe or register, null function is called. - */ -void reg_wizchip_bus_cbfunc(uint8_t (*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, uint8_t wb)); - -/** - *@brief Registers call back function for SPI interface. - *@param spi_rb : callback function to read byte usig SPI - *@param spi_wb : callback function to write byte usig SPI - *@todo Describe \ref wizchip_spi_readbyte and \ref wizchip_spi_writebyte function - *or register your functions. - *@note If you do not describe or register, null function is called. - */ -void reg_wizchip_spi_cbfunc(void (*spi_rb)(uint8_t *, uint32_t), void (*spi_wb)(const uint8_t *, uint32_t)); - -/** - * @ingroup extra_functions - * @brief Controls to the WIZCHIP. - * @details Resets WIZCHIP & internal PHY, Configures PHY mode, Monitor PHY(Link,Speed,Half/Full/Auto), - * controls interrupt & mask and so on. - * @param cwtype : Decides to the control type - * @param arg : arg type is dependent on cwtype. - * @return 0 : Success \n - * -1 : Fail because of invalid \ref ctlwizchip_type or unsupported \ref ctlwizchip_type in WIZCHIP - */ -int8_t ctlwizchip(ctlwizchip_type cwtype, void* arg); - -/** - * @ingroup extra_functions - * @brief Controls to network. - * @details Controls to network environment, mode, timeout and so on. - * @param cntype : Input. Decides to the control type - * @param arg : Inout. arg type is dependent on cntype. - * @return -1 : Fail because of invalid \ref ctlnetwork_type or unsupported \ref ctlnetwork_type in WIZCHIP \n - * 0 : Success - */ -int8_t ctlnetwork(ctlnetwork_type cntype, void* arg); - - -/* - * The following functions are implemented for internal use. - * but You can call these functions for code size reduction instead of ctlwizchip() and ctlnetwork(). - */ - -/** - * @ingroup extra_functions - * @brief Reset WIZCHIP by softly. - */ -void wizchip_sw_reset(void); - -/** - * @ingroup extra_functions - * @brief Initializes WIZCHIP with socket buffer size - * @param txsize Socket tx buffer sizes. If null, initialized the default size 2KB. - * @param rxsize Socket rx buffer sizes. If null, initialized the default size 2KB. - * @return 0 : succcess \n - * -1 : fail. Invalid buffer size - */ -int8_t wizchip_init(uint8_t* txsize, uint8_t* rxsize); - -/** - * @ingroup extra_functions - * @brief Clear Interrupt of WIZCHIP. - * @param intr : @ref intr_kind value operated OR. It can type-cast to uint16_t. - */ -void wizchip_clrinterrupt(intr_kind intr); - -/** - * @ingroup extra_functions - * @brief Get Interrupt of WIZCHIP. - * @return @ref intr_kind value operated OR. It can type-cast to uint16_t. - */ -intr_kind wizchip_getinterrupt(void); - -/** - * @ingroup extra_functions - * @brief Mask or Unmask Interrupt of WIZCHIP. - * @param intr : @ref intr_kind value operated OR. It can type-cast to uint16_t. - */ -void wizchip_setinterruptmask(intr_kind intr); - -/** - * @ingroup extra_functions - * @brief Get Interrupt mask of WIZCHIP. - * @return : The operated OR vaule of @ref intr_kind. It can type-cast to uint16_t. - */ -intr_kind wizchip_getinterruptmask(void); - -#if _WIZCHIP_ > 5100 - int8_t wizphy_getphylink(void); ///< get the link status of phy in WIZCHIP. No use in W5100 - int8_t wizphy_getphypmode(void); ///< get the power mode of PHY in WIZCHIP. No use in W5100 -#endif - -#if _WIZCHIP_ == 5500 - void wizphy_reset(void); ///< Reset phy. Vailid only in W5500 -/** - * @ingroup extra_functions - * @brief Set the phy information for WIZCHIP without power mode - * @param phyconf : @ref wiz_PhyConf - */ - void wizphy_setphyconf(wiz_PhyConf* phyconf); - /** - * @ingroup extra_functions - * @brief Get phy configuration information. - * @param phyconf : @ref wiz_PhyConf - */ - void wizphy_getphyconf(wiz_PhyConf* phyconf); - /** - * @ingroup extra_functions - * @brief Get phy status. - * @param phyconf : @ref wiz_PhyConf - */ - void wizphy_getphystat(wiz_PhyConf* phyconf); - /** - * @ingroup extra_functions - * @brief set the power mode of phy inside WIZCHIP. Refer to @ref PHYCFGR in W5500, @ref PHYSTATUS in W5200 - * @param pmode Settig value of power down mode. - */ - int8_t wizphy_setphypmode(uint8_t pmode); -#endif - -/** -* @ingroup extra_functions - * @brief Set the network information for WIZCHIP - * @param pnetinfo : @ref wizNetInfo - */ -void wizchip_setnetinfo(wiz_NetInfo* pnetinfo); - -/** - * @ingroup extra_functions - * @brief Get the network information for WIZCHIP - * @param pnetinfo : @ref wizNetInfo - */ -void wizchip_getnetinfo(wiz_NetInfo* pnetinfo); - -#if _WIZCHIP_ == 5200 // for W5200 ARP errata -uint8_t *wizchip_getsubn(void); -#endif - -/** - * @ingroup extra_functions - * @brief Set the network mode such WOL, PPPoE, Ping Block, and etc. - * @param pnetinfo Value of network mode. Refer to @ref netmode_type. - */ -int8_t wizchip_setnetmode(netmode_type netmode); - -/** - * @ingroup extra_functions - * @brief Get the network mode such WOL, PPPoE, Ping Block, and etc. - * @return Value of network mode. Refer to @ref netmode_type. - */ -netmode_type wizchip_getnetmode(void); - -/** - * @ingroup extra_functions - * @brief Set retry time value(@ref RTR) and retry count(@ref RCR). - * @details @ref RTR configures the retransmission timeout period and @ref RCR configures the number of time of retransmission. - * @param nettime @ref RTR value and @ref RCR value. Refer to @ref wiz_NetTimeout. - */ -void wizchip_settimeout(wiz_NetTimeout* nettime); - -/** - * @ingroup extra_functions - * @brief Get retry time value(@ref RTR) and retry count(@ref RCR). - * @details @ref RTR configures the retransmission timeout period and @ref RCR configures the number of time of retransmission. - * @param nettime @ref RTR value and @ref RCR value. Refer to @ref wiz_NetTimeout. - */ -void wizchip_gettimeout(wiz_NetTimeout* nettime); - -#endif // _WIZCHIP_CONF_H_ diff --git a/drivers/wiznet5k/internet/dhcp/dhcp.c b/drivers/wiznet5k/internet/dhcp/dhcp.c deleted file mode 100644 index 00f41c3c72..0000000000 --- a/drivers/wiznet5k/internet/dhcp/dhcp.c +++ /dev/null @@ -1,975 +0,0 @@ -//***************************************************************************** -// -//! \file dhcp.c -//! \brief DHCP APIs implement file. -//! \details Processig DHCP protocol as DISCOVER, OFFER, REQUEST, ACK, NACK and DECLINE. -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2018/10/09> Modified by Nick Moore for CircuitPython -//! <2013/11/18> 1st Release -//! <2012/12/20> V1.1.0 -//! 1. Optimize code -//! 2. Add reg_dhcp_cbfunc() -//! 3. Add DHCP_stop() -//! 4. Integrate check_DHCP_state() & DHCP_run() to DHCP_run() -//! 5. Don't care system endian -//! 6. Add comments -//! <2012/12/26> V1.1.1 -//! 1. Modify variable declaration: dhcp_tick_1s is declared volatile for code optimization -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -//#include "Ethernet/socket.h" -//#include "Internet/DHCP/dhcp.h" -#include "../../ethernet/socket.h" -#include "dhcp.h" - -/* If you want to display debug & processing message, Define _DHCP_DEBUG_ in dhcp.h */ - -#ifdef _DHCP_DEBUG_ - #include -#endif - -/* DHCP state machine. */ -#define STATE_DHCP_INIT 0 ///< Initialize -#define STATE_DHCP_DISCOVER 1 ///< send DISCOVER and wait OFFER -#define STATE_DHCP_REQUEST 2 ///< send REQEUST and wait ACK or NACK -#define STATE_DHCP_LEASED 3 ///< ReceiveD ACK and IP leased -#define STATE_DHCP_REREQUEST 4 ///< send REQUEST for maintaining leased IP -#define STATE_DHCP_RELEASE 5 ///< No use -#define STATE_DHCP_STOP 6 ///< Stop processing DHCP - -#define DHCP_FLAGSBROADCAST 0x8000 ///< The broadcast value of flags in @ref RIP_MSG -#define DHCP_FLAGSUNICAST 0x0000 ///< The unicast value of flags in @ref RIP_MSG - -/* DHCP message OP code */ -#define DHCP_BOOTREQUEST 1 ///< Request Message used in op of @ref RIP_MSG -#define DHCP_BOOTREPLY 2 ///< Reply Message used i op of @ref RIP_MSG - -/* DHCP message type */ -#define DHCP_DISCOVER 1 ///< DISCOVER message in OPT of @ref RIP_MSG -#define DHCP_OFFER 2 ///< OFFER message in OPT of @ref RIP_MSG -#define DHCP_REQUEST 3 ///< REQUEST message in OPT of @ref RIP_MSG -#define DHCP_DECLINE 4 ///< DECLINE message in OPT of @ref RIP_MSG -#define DHCP_ACK 5 ///< ACK message in OPT of @ref RIP_MSG -#define DHCP_NAK 6 ///< NACK message in OPT of @ref RIP_MSG -#define DHCP_RELEASE 7 ///< RELEASE message in OPT of @ref RIP_MSG. No use -#define DHCP_INFORM 8 ///< INFORM message in OPT of @ref RIP_MSG. No use - -#define DHCP_HTYPE10MB 1 ///< Used in type of @ref RIP_MSG -#define DHCP_HTYPE100MB 2 ///< Used in type of @ref RIP_MSG - -#define DHCP_HLENETHERNET 6 ///< Used in hlen of @ref RIP_MSG -#define DHCP_HOPS 0 ///< Used in hops of @ref RIP_MSG -#define DHCP_SECS 0 ///< Used in secs of @ref RIP_MSG - -#define INFINITE_LEASETIME 0xffffffff ///< Infinite lease time - -#define OPT_SIZE 312 /// Max OPT size of @ref RIP_MSG -#define RIP_MSG_SIZE (236+OPT_SIZE) /// Max size of @ref RIP_MSG - -/* - * @brief DHCP option and value (cf. RFC1533) - */ -enum -{ - padOption = 0, - subnetMask = 1, - timerOffset = 2, - routersOnSubnet = 3, - timeServer = 4, - nameServer = 5, - dns = 6, - logServer = 7, - cookieServer = 8, - lprServer = 9, - impressServer = 10, - resourceLocationServer = 11, - hostName = 12, - bootFileSize = 13, - meritDumpFile = 14, - domainName = 15, - swapServer = 16, - rootPath = 17, - extentionsPath = 18, - IPforwarding = 19, - nonLocalSourceRouting = 20, - policyFilter = 21, - maxDgramReasmSize = 22, - defaultIPTTL = 23, - pathMTUagingTimeout = 24, - pathMTUplateauTable = 25, - ifMTU = 26, - allSubnetsLocal = 27, - broadcastAddr = 28, - performMaskDiscovery = 29, - maskSupplier = 30, - performRouterDiscovery = 31, - routerSolicitationAddr = 32, - staticRoute = 33, - trailerEncapsulation = 34, - arpCacheTimeout = 35, - ethernetEncapsulation = 36, - tcpDefaultTTL = 37, - tcpKeepaliveInterval = 38, - tcpKeepaliveGarbage = 39, - nisDomainName = 40, - nisServers = 41, - ntpServers = 42, - vendorSpecificInfo = 43, - netBIOSnameServer = 44, - netBIOSdgramDistServer = 45, - netBIOSnodeType = 46, - netBIOSscope = 47, - xFontServer = 48, - xDisplayManager = 49, - dhcpRequestedIPaddr = 50, - dhcpIPaddrLeaseTime = 51, - dhcpOptionOverload = 52, - dhcpMessageType = 53, - dhcpServerIdentifier = 54, - dhcpParamRequest = 55, - dhcpMsg = 56, - dhcpMaxMsgSize = 57, - dhcpT1value = 58, - dhcpT2value = 59, - dhcpClassIdentifier = 60, - dhcpClientIdentifier = 61, - endOption = 255 -}; - -/* - * @brief DHCP message format - */ -typedef struct { - uint8_t op; ///< @ref DHCP_BOOTREQUEST or @ref DHCP_BOOTREPLY - uint8_t htype; ///< @ref DHCP_HTYPE10MB or @ref DHCP_HTYPE100MB - uint8_t hlen; ///< @ref DHCP_HLENETHERNET - uint8_t hops; ///< @ref DHCP_HOPS - uint32_t xid; ///< @ref DHCP_XID This increase one every DHCP transaction. - uint16_t secs; ///< @ref DHCP_SECS - uint16_t flags; ///< @ref DHCP_FLAGSBROADCAST or @ref DHCP_FLAGSUNICAST - uint8_t ciaddr[4]; ///< @ref Request IP to DHCP sever - uint8_t yiaddr[4]; ///< @ref Offered IP from DHCP server - uint8_t siaddr[4]; ///< No use - uint8_t giaddr[4]; ///< No use - uint8_t chaddr[16]; ///< DHCP client 6bytes MAC address. Others is filled to zero - uint8_t sname[64]; ///< No use - uint8_t file[128]; ///< No use - uint8_t OPT[OPT_SIZE]; ///< Option -} RIP_MSG; - - - -uint8_t DHCP_SOCKET; // Socket number for DHCP - -uint8_t DHCP_SIP[4]; // DHCP Server IP address - -// Network information from DHCP Server -uint8_t OLD_allocated_ip[4] = {0, }; // Previous IP address -uint8_t DHCP_allocated_ip[4] = {0, }; // IP address from DHCP -uint8_t DHCP_allocated_gw[4] = {0, }; // Gateway address from DHCP -uint8_t DHCP_allocated_sn[4] = {0, }; // Subnet mask from DHCP -uint8_t DHCP_allocated_dns[4] = {0, }; // DNS address from DHCP - - -int8_t dhcp_state = STATE_DHCP_INIT; // DHCP state -int8_t dhcp_retry_count = 0; - -uint32_t dhcp_lease_time = INFINITE_LEASETIME; -volatile uint32_t dhcp_tick_1s = 0; // unit 1 second -uint32_t dhcp_tick_next = DHCP_WAIT_TIME ; - -uint32_t DHCP_XID; // Any number - -RIP_MSG* pDHCPMSG; // Buffer pointer for DHCP processing - -uint8_t HOST_NAME[] = DCHP_HOST_NAME; - -uint8_t DHCP_CHADDR[6]; // DHCP Client MAC address. - -/* The default callback function */ -void default_ip_assign(void); -void default_ip_update(void); -void default_ip_conflict(void); - -/* Callback handler */ -void (*dhcp_ip_assign)(void) = default_ip_assign; /* handler to be called when the IP address from DHCP server is first assigned */ -void (*dhcp_ip_update)(void) = default_ip_update; /* handler to be called when the IP address from DHCP server is updated */ -void (*dhcp_ip_conflict)(void) = default_ip_conflict; /* handler to be called when the IP address from DHCP server is conflict */ - -void reg_dhcp_cbfunc(void(*ip_assign)(void), void(*ip_update)(void), void(*ip_conflict)(void)); - - -/* send DISCOVER message to DHCP server */ -void send_DHCP_DISCOVER(void); - -/* send REQEUST message to DHCP server */ -void send_DHCP_REQUEST(void); - -/* send DECLINE message to DHCP server */ -void send_DHCP_DECLINE(void); - -/* IP conflict check by sending ARP-request to leased IP and wait ARP-response. */ -int8_t check_DHCP_leasedIP(void); - -/* check the timeout in DHCP process */ -uint8_t check_DHCP_timeout(void); - -/* Intialize to timeout process. */ -void reset_DHCP_timeout(void); - -/* Parse message as OFFER and ACK and NACK from DHCP server.*/ -int8_t parseDHCPCMSG(void); - -/* The default handler of ip assign first */ -void default_ip_assign(void) -{ - setSIPR(DHCP_allocated_ip); - setSUBR(DHCP_allocated_sn); - setGAR (DHCP_allocated_gw); -} - -/* The default handler of ip changed */ -void default_ip_update(void) -{ - /* WIZchip Software Reset */ - setMR(MR_RST); - getMR(); // for delay - default_ip_assign(); - setSHAR(DHCP_CHADDR); -} - -/* The default handler of ip changed */ -void default_ip_conflict(void) -{ - // WIZchip Software Reset - setMR(MR_RST); - getMR(); // for delay - setSHAR(DHCP_CHADDR); -} - -/* register the call back func. */ -void reg_dhcp_cbfunc(void(*ip_assign)(void), void(*ip_update)(void), void(*ip_conflict)(void)) -{ - dhcp_ip_assign = default_ip_assign; - dhcp_ip_update = default_ip_update; - dhcp_ip_conflict = default_ip_conflict; - if(ip_assign) dhcp_ip_assign = ip_assign; - if(ip_update) dhcp_ip_update = ip_update; - if(ip_conflict) dhcp_ip_conflict = ip_conflict; -} - -/* make the common DHCP message */ -void makeDHCPMSG(void) -{ - uint8_t bk_mac[6]; - uint8_t* ptmp; - uint8_t i; - getSHAR(bk_mac); - pDHCPMSG->op = DHCP_BOOTREQUEST; - pDHCPMSG->htype = DHCP_HTYPE10MB; - pDHCPMSG->hlen = DHCP_HLENETHERNET; - pDHCPMSG->hops = DHCP_HOPS; - ptmp = (uint8_t*)(&pDHCPMSG->xid); - *(ptmp+0) = (uint8_t)((DHCP_XID & 0xFF000000) >> 24); - *(ptmp+1) = (uint8_t)((DHCP_XID & 0x00FF0000) >> 16); - *(ptmp+2) = (uint8_t)((DHCP_XID & 0x0000FF00) >> 8); - *(ptmp+3) = (uint8_t)((DHCP_XID & 0x000000FF) >> 0); - pDHCPMSG->secs = DHCP_SECS; - ptmp = (uint8_t*)(&pDHCPMSG->flags); - *(ptmp+0) = (uint8_t)((DHCP_FLAGSBROADCAST & 0xFF00) >> 8); - *(ptmp+1) = (uint8_t)((DHCP_FLAGSBROADCAST & 0x00FF) >> 0); - - pDHCPMSG->ciaddr[0] = 0; - pDHCPMSG->ciaddr[1] = 0; - pDHCPMSG->ciaddr[2] = 0; - pDHCPMSG->ciaddr[3] = 0; - - pDHCPMSG->yiaddr[0] = 0; - pDHCPMSG->yiaddr[1] = 0; - pDHCPMSG->yiaddr[2] = 0; - pDHCPMSG->yiaddr[3] = 0; - - pDHCPMSG->siaddr[0] = 0; - pDHCPMSG->siaddr[1] = 0; - pDHCPMSG->siaddr[2] = 0; - pDHCPMSG->siaddr[3] = 0; - - pDHCPMSG->giaddr[0] = 0; - pDHCPMSG->giaddr[1] = 0; - pDHCPMSG->giaddr[2] = 0; - pDHCPMSG->giaddr[3] = 0; - - pDHCPMSG->chaddr[0] = DHCP_CHADDR[0]; - pDHCPMSG->chaddr[1] = DHCP_CHADDR[1]; - pDHCPMSG->chaddr[2] = DHCP_CHADDR[2]; - pDHCPMSG->chaddr[3] = DHCP_CHADDR[3]; - pDHCPMSG->chaddr[4] = DHCP_CHADDR[4]; - pDHCPMSG->chaddr[5] = DHCP_CHADDR[5]; - - for (i = 6; i < 16; i++) pDHCPMSG->chaddr[i] = 0; - for (i = 0; i < 64; i++) pDHCPMSG->sname[i] = 0; - for (i = 0; i < 128; i++) pDHCPMSG->file[i] = 0; - - // MAGIC_COOKIE - pDHCPMSG->OPT[0] = (uint8_t)((MAGIC_COOKIE & 0xFF000000) >> 24); - pDHCPMSG->OPT[1] = (uint8_t)((MAGIC_COOKIE & 0x00FF0000) >> 16); - pDHCPMSG->OPT[2] = (uint8_t)((MAGIC_COOKIE & 0x0000FF00) >> 8); - pDHCPMSG->OPT[3] = (uint8_t) (MAGIC_COOKIE & 0x000000FF) >> 0; -} - -/* SEND DHCP DISCOVER */ -void send_DHCP_DISCOVER(void) -{ - uint16_t i; - uint8_t ip[4]; - uint16_t k = 0; - - makeDHCPMSG(); - - k = 4; // because MAGIC_COOKIE already made by makeDHCPMSG() - - // Option Request Param - pDHCPMSG->OPT[k++] = dhcpMessageType; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_DISCOVER; - - // Client identifier - pDHCPMSG->OPT[k++] = dhcpClientIdentifier; - pDHCPMSG->OPT[k++] = 0x07; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[0]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[1]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[2]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - - // host name - pDHCPMSG->OPT[k++] = hostName; - pDHCPMSG->OPT[k++] = 0; // fill zero length of hostname - for(i = 0 ; HOST_NAME[i] != 0; i++) - pDHCPMSG->OPT[k++] = HOST_NAME[i]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - pDHCPMSG->OPT[k - (i+3+1)] = i+3; // length of hostname - - pDHCPMSG->OPT[k++] = dhcpParamRequest; - pDHCPMSG->OPT[k++] = 0x06; // length of request - pDHCPMSG->OPT[k++] = subnetMask; - pDHCPMSG->OPT[k++] = routersOnSubnet; - pDHCPMSG->OPT[k++] = dns; - pDHCPMSG->OPT[k++] = domainName; - pDHCPMSG->OPT[k++] = dhcpT1value; - pDHCPMSG->OPT[k++] = dhcpT2value; - pDHCPMSG->OPT[k++] = endOption; - - for (i = k; i < OPT_SIZE; i++) pDHCPMSG->OPT[i] = 0; - - // send broadcasting packet - ip[0] = 255; - ip[1] = 255; - ip[2] = 255; - ip[3] = 255; - -#ifdef _DHCP_DEBUG_ - printf("> Send DHCP_DISCOVER\r\n"); -#endif - - WIZCHIP_EXPORT(sendto)(DHCP_SOCKET, (uint8_t *)pDHCPMSG, RIP_MSG_SIZE, ip, DHCP_SERVER_PORT); -} - -/* SEND DHCP REQUEST */ -void send_DHCP_REQUEST(void) -{ - int i; - uint8_t ip[4]; - uint16_t k = 0; - - makeDHCPMSG(); - - if(dhcp_state == STATE_DHCP_LEASED || dhcp_state == STATE_DHCP_REREQUEST) - { - *((uint8_t*)(&pDHCPMSG->flags)) = ((DHCP_FLAGSUNICAST & 0xFF00)>> 8); - *((uint8_t*)(&pDHCPMSG->flags)+1) = (DHCP_FLAGSUNICAST & 0x00FF); - pDHCPMSG->ciaddr[0] = DHCP_allocated_ip[0]; - pDHCPMSG->ciaddr[1] = DHCP_allocated_ip[1]; - pDHCPMSG->ciaddr[2] = DHCP_allocated_ip[2]; - pDHCPMSG->ciaddr[3] = DHCP_allocated_ip[3]; - ip[0] = DHCP_SIP[0]; - ip[1] = DHCP_SIP[1]; - ip[2] = DHCP_SIP[2]; - ip[3] = DHCP_SIP[3]; - } - else - { - ip[0] = 255; - ip[1] = 255; - ip[2] = 255; - ip[3] = 255; - } - - k = 4; // because MAGIC_COOKIE already made by makeDHCPMSG() - - // Option Request Param. - pDHCPMSG->OPT[k++] = dhcpMessageType; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_REQUEST; - - pDHCPMSG->OPT[k++] = dhcpClientIdentifier; - pDHCPMSG->OPT[k++] = 0x07; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[0]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[1]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[2]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - - if(ip[3] == 255) // if(dchp_state == STATE_DHCP_LEASED || dchp_state == DHCP_REREQUEST_STATE) - { - pDHCPMSG->OPT[k++] = dhcpRequestedIPaddr; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[0]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[1]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[2]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[3]; - - pDHCPMSG->OPT[k++] = dhcpServerIdentifier; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_SIP[0]; - pDHCPMSG->OPT[k++] = DHCP_SIP[1]; - pDHCPMSG->OPT[k++] = DHCP_SIP[2]; - pDHCPMSG->OPT[k++] = DHCP_SIP[3]; - } - - // host name - pDHCPMSG->OPT[k++] = hostName; - pDHCPMSG->OPT[k++] = 0; // length of hostname - for(i = 0 ; HOST_NAME[i] != 0; i++) - pDHCPMSG->OPT[k++] = HOST_NAME[i]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - pDHCPMSG->OPT[k - (i+3+1)] = i+3; // length of hostname - - pDHCPMSG->OPT[k++] = dhcpParamRequest; - pDHCPMSG->OPT[k++] = 0x08; - pDHCPMSG->OPT[k++] = subnetMask; - pDHCPMSG->OPT[k++] = routersOnSubnet; - pDHCPMSG->OPT[k++] = dns; - pDHCPMSG->OPT[k++] = domainName; - pDHCPMSG->OPT[k++] = dhcpT1value; - pDHCPMSG->OPT[k++] = dhcpT2value; - pDHCPMSG->OPT[k++] = performRouterDiscovery; - pDHCPMSG->OPT[k++] = staticRoute; - pDHCPMSG->OPT[k++] = endOption; - - for (i = k; i < OPT_SIZE; i++) pDHCPMSG->OPT[i] = 0; - -#ifdef _DHCP_DEBUG_ - printf("> Send DHCP_REQUEST\r\n"); -#endif - - WIZCHIP_EXPORT(sendto)(DHCP_SOCKET, (uint8_t *)pDHCPMSG, RIP_MSG_SIZE, ip, DHCP_SERVER_PORT); - -} - -/* SEND DHCP DHCPDECLINE */ -void send_DHCP_DECLINE(void) -{ - int i; - uint8_t ip[4]; - uint16_t k = 0; - - makeDHCPMSG(); - - k = 4; // because MAGIC_COOKIE already made by makeDHCPMSG() - - *((uint8_t*)(&pDHCPMSG->flags)) = ((DHCP_FLAGSUNICAST & 0xFF00)>> 8); - *((uint8_t*)(&pDHCPMSG->flags)+1) = (DHCP_FLAGSUNICAST & 0x00FF); - - // Option Request Param. - pDHCPMSG->OPT[k++] = dhcpMessageType; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_DECLINE; - - pDHCPMSG->OPT[k++] = dhcpClientIdentifier; - pDHCPMSG->OPT[k++] = 0x07; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[0]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[1]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[2]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - - pDHCPMSG->OPT[k++] = dhcpRequestedIPaddr; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[0]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[1]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[2]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[3]; - - pDHCPMSG->OPT[k++] = dhcpServerIdentifier; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_SIP[0]; - pDHCPMSG->OPT[k++] = DHCP_SIP[1]; - pDHCPMSG->OPT[k++] = DHCP_SIP[2]; - pDHCPMSG->OPT[k++] = DHCP_SIP[3]; - - pDHCPMSG->OPT[k++] = endOption; - - for (i = k; i < OPT_SIZE; i++) pDHCPMSG->OPT[i] = 0; - - //send broadcasting packet - ip[0] = 0xFF; - ip[1] = 0xFF; - ip[2] = 0xFF; - ip[3] = 0xFF; - -#ifdef _DHCP_DEBUG_ - printf("\r\n> Send DHCP_DECLINE\r\n"); -#endif - - WIZCHIP_EXPORT(sendto)(DHCP_SOCKET, (uint8_t *)pDHCPMSG, RIP_MSG_SIZE, ip, DHCP_SERVER_PORT); -} - -/* PARSE REPLY pDHCPMSG */ -int8_t parseDHCPMSG(void) -{ - uint8_t svr_addr[6]; - uint16_t svr_port; - uint16_t len; - - uint8_t * p; - uint8_t * e; - uint8_t type = 0; - uint8_t opt_len; - - if((len = getSn_RX_RSR(DHCP_SOCKET)) > 0) - { - len = WIZCHIP_EXPORT(recvfrom)(DHCP_SOCKET, (uint8_t *)pDHCPMSG, len, svr_addr, &svr_port); - #ifdef _DHCP_DEBUG_ - printf("DHCP message : %d.%d.%d.%d(%d) %d received. \r\n",svr_addr[0],svr_addr[1],svr_addr[2], svr_addr[3],svr_port, len); - #endif - } - else return 0; - if (svr_port == DHCP_SERVER_PORT) { - // compare mac address - if ( (pDHCPMSG->chaddr[0] != DHCP_CHADDR[0]) || (pDHCPMSG->chaddr[1] != DHCP_CHADDR[1]) || - (pDHCPMSG->chaddr[2] != DHCP_CHADDR[2]) || (pDHCPMSG->chaddr[3] != DHCP_CHADDR[3]) || - (pDHCPMSG->chaddr[4] != DHCP_CHADDR[4]) || (pDHCPMSG->chaddr[5] != DHCP_CHADDR[5]) ) - return 0; - type = 0; - p = (uint8_t *)(&pDHCPMSG->op); - p = p + 240; // 240 = sizeof(RIP_MSG) + MAGIC_COOKIE size in RIP_MSG.opt - sizeof(RIP_MSG.opt) - e = p + (len - 240); - - while ( p < e ) { - - switch ( *p ) { - - case endOption : - p = e; // for break while(p < e) - break; - case padOption : - p++; - break; - case dhcpMessageType : - p++; - p++; - type = *p++; - break; - case subnetMask : - p++; - p++; - DHCP_allocated_sn[0] = *p++; - DHCP_allocated_sn[1] = *p++; - DHCP_allocated_sn[2] = *p++; - DHCP_allocated_sn[3] = *p++; - break; - case routersOnSubnet : - p++; - opt_len = *p++; - DHCP_allocated_gw[0] = *p++; - DHCP_allocated_gw[1] = *p++; - DHCP_allocated_gw[2] = *p++; - DHCP_allocated_gw[3] = *p++; - p = p + (opt_len - 4); - break; - case dns : - p++; - opt_len = *p++; - DHCP_allocated_dns[0] = *p++; - DHCP_allocated_dns[1] = *p++; - DHCP_allocated_dns[2] = *p++; - DHCP_allocated_dns[3] = *p++; - p = p + (opt_len - 4); - break; - case dhcpIPaddrLeaseTime : - p++; - opt_len = *p++; - dhcp_lease_time = *p++; - dhcp_lease_time = (dhcp_lease_time << 8) + *p++; - dhcp_lease_time = (dhcp_lease_time << 8) + *p++; - dhcp_lease_time = (dhcp_lease_time << 8) + *p++; - #ifdef _DHCP_DEBUG_ - dhcp_lease_time = 10; - #endif - break; - case dhcpServerIdentifier : - p++; - opt_len = *p++; - DHCP_SIP[0] = *p++; - DHCP_SIP[1] = *p++; - DHCP_SIP[2] = *p++; - DHCP_SIP[3] = *p++; - break; - default : - p++; - opt_len = *p++; - p += opt_len; - break; - } // switch - } // while - } // if - return type; -} - -uint8_t DHCP_run(void) -{ - uint8_t type; - uint8_t ret; - - if(dhcp_state == STATE_DHCP_STOP) return DHCP_STOPPED; - - if(getSn_SR(DHCP_SOCKET) != SOCK_UDP) - WIZCHIP_EXPORT(socket)(DHCP_SOCKET, Sn_MR_UDP, DHCP_CLIENT_PORT, 0x00); - - ret = DHCP_RUNNING; - type = parseDHCPMSG(); - - switch ( dhcp_state ) { - case STATE_DHCP_INIT : - DHCP_allocated_ip[0] = 0; - DHCP_allocated_ip[1] = 0; - DHCP_allocated_ip[2] = 0; - DHCP_allocated_ip[3] = 0; - send_DHCP_DISCOVER(); - dhcp_state = STATE_DHCP_DISCOVER; - break; - case STATE_DHCP_DISCOVER : - if (type == DHCP_OFFER){ -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_OFFER\r\n"); -#endif - DHCP_allocated_ip[0] = pDHCPMSG->yiaddr[0]; - DHCP_allocated_ip[1] = pDHCPMSG->yiaddr[1]; - DHCP_allocated_ip[2] = pDHCPMSG->yiaddr[2]; - DHCP_allocated_ip[3] = pDHCPMSG->yiaddr[3]; - - send_DHCP_REQUEST(); - dhcp_state = STATE_DHCP_REQUEST; - } else ret = check_DHCP_timeout(); - break; - - case STATE_DHCP_REQUEST : - if (type == DHCP_ACK) { - -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_ACK\r\n"); -#endif - if (check_DHCP_leasedIP()) { - // Network info assignment from DHCP - dhcp_ip_assign(); - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_LEASED; - } else { - // IP address conflict occurred - reset_DHCP_timeout(); - dhcp_ip_conflict(); - dhcp_state = STATE_DHCP_INIT; - } - } else if (type == DHCP_NAK) { - -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_NACK\r\n"); -#endif - - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_DISCOVER; - } else ret = check_DHCP_timeout(); - break; - - case STATE_DHCP_LEASED : - ret = DHCP_IP_LEASED; - if ((dhcp_lease_time != INFINITE_LEASETIME) && ((dhcp_lease_time/2) < dhcp_tick_1s)) { - -#ifdef _DHCP_DEBUG_ - printf("> Maintains the IP address \r\n"); -#endif - - type = 0; - OLD_allocated_ip[0] = DHCP_allocated_ip[0]; - OLD_allocated_ip[1] = DHCP_allocated_ip[1]; - OLD_allocated_ip[2] = DHCP_allocated_ip[2]; - OLD_allocated_ip[3] = DHCP_allocated_ip[3]; - - DHCP_XID++; - - send_DHCP_REQUEST(); - - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_REREQUEST; - } - break; - - case STATE_DHCP_REREQUEST : - ret = DHCP_IP_LEASED; - if (type == DHCP_ACK) { - dhcp_retry_count = 0; - if (OLD_allocated_ip[0] != DHCP_allocated_ip[0] || - OLD_allocated_ip[1] != DHCP_allocated_ip[1] || - OLD_allocated_ip[2] != DHCP_allocated_ip[2] || - OLD_allocated_ip[3] != DHCP_allocated_ip[3]) - { - ret = DHCP_IP_CHANGED; - dhcp_ip_update(); - #ifdef _DHCP_DEBUG_ - printf(">IP changed.\r\n"); - #endif - - } - #ifdef _DHCP_DEBUG_ - else printf(">IP is continued.\r\n"); - #endif - reset_DHCP_timeout(); - dhcp_state = STATE_DHCP_LEASED; - } else if (type == DHCP_NAK) { - -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_NACK, Failed to maintain ip\r\n"); -#endif - - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_DISCOVER; - } else ret = check_DHCP_timeout(); - break; - default : - break; - } - - return ret; -} - -void DHCP_stop(void) -{ - WIZCHIP_EXPORT(close)(DHCP_SOCKET); - dhcp_state = STATE_DHCP_STOP; -} - -uint8_t check_DHCP_timeout(void) -{ - uint8_t ret = DHCP_RUNNING; - - if (dhcp_retry_count < MAX_DHCP_RETRY) { - if (dhcp_tick_next < dhcp_tick_1s) { - - switch ( dhcp_state ) { - case STATE_DHCP_DISCOVER : -// printf("<> state : STATE_DHCP_DISCOVER\r\n"); - send_DHCP_DISCOVER(); - break; - - case STATE_DHCP_REQUEST : -// printf("<> state : STATE_DHCP_REQUEST\r\n"); - - send_DHCP_REQUEST(); - break; - - case STATE_DHCP_REREQUEST : -// printf("<> state : STATE_DHCP_REREQUEST\r\n"); - - send_DHCP_REQUEST(); - break; - - default : - break; - } - - dhcp_tick_1s = 0; - dhcp_tick_next = dhcp_tick_1s + DHCP_WAIT_TIME; - dhcp_retry_count++; - } - } else { // timeout occurred - - switch(dhcp_state) { - case STATE_DHCP_DISCOVER: - dhcp_state = STATE_DHCP_INIT; - ret = DHCP_FAILED; - break; - case STATE_DHCP_REQUEST: - case STATE_DHCP_REREQUEST: - send_DHCP_DISCOVER(); - dhcp_state = STATE_DHCP_DISCOVER; - break; - default : - break; - } - reset_DHCP_timeout(); - } - return ret; -} - -int8_t check_DHCP_leasedIP(void) -{ - uint8_t tmp; - int32_t ret; - - //WIZchip RCR value changed for ARP Timeout count control - tmp = getRCR(); - setRCR(0x03); - - // IP conflict detection : ARP request - ARP reply - // Broadcasting ARP Request for check the IP conflict using UDP sendto() function - ret = WIZCHIP_EXPORT(sendto)(DHCP_SOCKET, (uint8_t *)"CHECK_IP_CONFLICT", 17, DHCP_allocated_ip, 5000); - - // RCR value restore - setRCR(tmp); - - if(ret == SOCKERR_TIMEOUT) { - // UDP send Timeout occurred : allocated IP address is unique, DHCP Success - -#ifdef _DHCP_DEBUG_ - printf("\r\n> Check leased IP - OK\r\n"); -#endif - - return 1; - } else { - // Received ARP reply or etc : IP address conflict occur, DHCP Failed - send_DHCP_DECLINE(); - - ret = dhcp_tick_1s; - while((dhcp_tick_1s - ret) < 2) ; // wait for 1s over; wait to complete to send DECLINE message; - - return 0; - } -} - -void DHCP_init(uint8_t s, DHCP_INIT_BUFFER_TYPE* buf) -{ - uint8_t zeroip[4] = {0,0,0,0}; - getSHAR(DHCP_CHADDR); - if((DHCP_CHADDR[0] | DHCP_CHADDR[1] | DHCP_CHADDR[2] | DHCP_CHADDR[3] | DHCP_CHADDR[4] | DHCP_CHADDR[5]) == 0x00) - { - // assign temporary mac address, you should be set SHAR before call this function. - DHCP_CHADDR[0] = 0x00; - DHCP_CHADDR[1] = 0x08; - DHCP_CHADDR[2] = 0xdc; - DHCP_CHADDR[3] = 0x00; - DHCP_CHADDR[4] = 0x00; - DHCP_CHADDR[5] = 0x00; - setSHAR(DHCP_CHADDR); - } - - DHCP_SOCKET = s; // SOCK_DHCP - pDHCPMSG = (RIP_MSG*)buf; - DHCP_XID = 0x12345678; - - // WIZchip Netinfo Clear - setSIPR(zeroip); - setSIPR(zeroip); - setGAR(zeroip); - - reset_DHCP_timeout(); - dhcp_state = STATE_DHCP_INIT; -} - - -/* Rset the DHCP timeout count and retry count. */ -void reset_DHCP_timeout(void) -{ - dhcp_tick_1s = 0; - dhcp_tick_next = DHCP_WAIT_TIME; - dhcp_retry_count = 0; -} - -void DHCP_time_handler(void) -{ - dhcp_tick_1s++; -} - -void getIPfromDHCP(uint8_t* ip) -{ - ip[0] = DHCP_allocated_ip[0]; - ip[1] = DHCP_allocated_ip[1]; - ip[2] = DHCP_allocated_ip[2]; - ip[3] = DHCP_allocated_ip[3]; -} - -void getGWfromDHCP(uint8_t* ip) -{ - ip[0] =DHCP_allocated_gw[0]; - ip[1] =DHCP_allocated_gw[1]; - ip[2] =DHCP_allocated_gw[2]; - ip[3] =DHCP_allocated_gw[3]; -} - -void getSNfromDHCP(uint8_t* ip) -{ - ip[0] = DHCP_allocated_sn[0]; - ip[1] = DHCP_allocated_sn[1]; - ip[2] = DHCP_allocated_sn[2]; - ip[3] = DHCP_allocated_sn[3]; -} - -void getDNSfromDHCP(uint8_t* ip) -{ - ip[0] = DHCP_allocated_dns[0]; - ip[1] = DHCP_allocated_dns[1]; - ip[2] = DHCP_allocated_dns[2]; - ip[3] = DHCP_allocated_dns[3]; -} - -uint32_t getDHCPLeasetime(void) -{ - return dhcp_lease_time; -} diff --git a/drivers/wiznet5k/internet/dhcp/dhcp.h b/drivers/wiznet5k/internet/dhcp/dhcp.h deleted file mode 100644 index 618a91498b..0000000000 --- a/drivers/wiznet5k/internet/dhcp/dhcp.h +++ /dev/null @@ -1,152 +0,0 @@ -//***************************************************************************** -// -//! \file dhcp.h -//! \brief DHCP APIs Header file. -//! \details Processig DHCP protocol as DISCOVER, OFFER, REQUEST, ACK, NACK and DECLINE. -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2013/11/18> 1st Release -//! <2012/12/20> V1.1.0 -//! 1. Move unreferenced DEFINE to dhcp.c -//! <2012/12/26> V1.1.1 -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** -#ifndef _DHCP_H_ -#define _DHCP_H_ - -/* - * @brief - * @details If you want to display debug & processing message, Define _DHCP_DEBUG_ - * @note If defined, it depends on - */ - -//#define _DHCP_DEBUG_ - -/* Retry to processing DHCP */ -#define MAX_DHCP_RETRY 2 ///< Maximum retry count -#define DHCP_WAIT_TIME 3 ///< Wait Time 3s (was 10s) - -/* UDP port numbers for DHCP */ -#define DHCP_SERVER_PORT 67 ///< DHCP server port number -#define DHCP_CLIENT_PORT 68 ///< DHCP client port number - -#define MAGIC_COOKIE 0x63825363 ///< Any number. You can be modified it any number - -#define DCHP_HOST_NAME "WIZnet\0" - -/* - * @brief return value of @ref DHCP_run() - */ -enum -{ - DHCP_FAILED = 0, ///< Processing Fail - DHCP_RUNNING, ///< Processing DHCP protocol - DHCP_IP_ASSIGN, ///< First Occupy IP from DHPC server (if cbfunc == null, act as default default_ip_assign) - DHCP_IP_CHANGED, ///< Change IP address by new IP address from DHCP (if cbfunc == null, act as default default_ip_update) - DHCP_IP_LEASED, ///< Stand by - DHCP_STOPPED ///< Stop processing DHCP protocol -}; - -#define DHCP_INIT_BUFFER_TYPE uint32_t -#define DHCP_INIT_BUFFER_SIZE (137) -/* - * @brief DHCP client initialization (outside of the main loop) - * @param s - socket number - * @param buf - buffer for processing DHCP message - */ -void DHCP_init(uint8_t s, DHCP_INIT_BUFFER_TYPE* buf); - -/* - * @brief DHCP 1s Tick Timer handler - * @note SHOULD BE register to your system 1s Tick timer handler - */ -void DHCP_time_handler(void); - -/* - * @brief Register call back function - * @param ip_assign - callback func when IP is assigned from DHCP server first - * @param ip_update - callback func when IP is changed - * @prarm ip_conflict - callback func when the assigned IP is conflict with others. - */ -void reg_dhcp_cbfunc(void(*ip_assign)(void), void(*ip_update)(void), void(*ip_conflict)(void)); - -/* - * @brief DHCP client in the main loop - * @return The value is as the follow \n - * @ref DHCP_FAILED \n - * @ref DHCP_RUNNING \n - * @ref DHCP_IP_ASSIGN \n - * @ref DHCP_IP_CHANGED \n - * @ref DHCP_IP_LEASED \n - * @ref DHCP_STOPPED \n - * - * @note This function is always called by you main task. - */ -uint8_t DHCP_run(void); - -/* - * @brief Stop DHCP processing - * @note If you want to restart. call DHCP_init() and DHCP_run() - */ -void DHCP_stop(void); - -/* Get Network information assigned from DHCP server */ -/* - * @brief Get IP address - * @param ip - IP address to be returned - */ -void getIPfromDHCP(uint8_t* ip); -/* - * @brief Get Gateway address - * @param ip - Gateway address to be returned - */ -void getGWfromDHCP(uint8_t* ip); -/* - * @brief Get Subnet mask value - * @param ip - Subnet mask to be returned - */ -void getSNfromDHCP(uint8_t* ip); -/* - * @brief Get DNS address - * @param ip - DNS address to be returned - */ -void getDNSfromDHCP(uint8_t* ip); - -/* - * @brief Get the leased time by DHCP sever - * @return unit 1s - */ -uint32_t getDHCPLeasetime(void); - -#endif /* _DHCP_H_ */ diff --git a/drivers/wiznet5k/internet/dns/dns.c b/drivers/wiznet5k/internet/dns/dns.c deleted file mode 100644 index aa3a738091..0000000000 --- a/drivers/wiznet5k/internet/dns/dns.c +++ /dev/null @@ -1,572 +0,0 @@ -//***************************************************************************** -// -//! \file dns.c -//! \brief DNS APIs Implement file. -//! \details Send DNS query & Receive DNS reponse. \n -//! It depends on stdlib.h & string.h in ansi-c library -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.1.0 -//! 1. Remove secondary DNS server in DNS_run -//! If 1st DNS_run failed, call DNS_run with 2nd DNS again -//! 2. DNS_timerHandler -> DNS_time_handler -//! 3. Remove the unused define -//! 4. Integrated dns.h dns.c & dns_parse.h dns_parse.c into dns.h & dns.c -//! <2013/12/20> V1.1.0 -//! <2018/10/04> Modified HAL_GetTick for use with CircuitPython by Nick Moore -//! -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#include -#include -#include "supervisor/shared/tick.h" - -//#include "Ethernet/socket.h" -//#include "Internet/DNS/dns.h" -#include "../../ethernet/socket.h" -#include "dns.h" - -#ifdef _DNS_DEBUG_ - #include -#endif - -#define INITRTT 2000L /* Initial smoothed response time */ -#define MAXCNAME (MAX_DOMAIN_NAME + (MAX_DOMAIN_NAME>>1)) /* Maximum amount of cname recursion */ - -#define TYPE_A 1 /* Host address */ -#define TYPE_NS 2 /* Name server */ -#define TYPE_MD 3 /* Mail destination (obsolete) */ -#define TYPE_MF 4 /* Mail forwarder (obsolete) */ -#define TYPE_CNAME 5 /* Canonical name */ -#define TYPE_SOA 6 /* Start of Authority */ -#define TYPE_MB 7 /* Mailbox name (experimental) */ -#define TYPE_MG 8 /* Mail group member (experimental) */ -#define TYPE_MR 9 /* Mail rename name (experimental) */ -#define TYPE_NULL 10 /* Null (experimental) */ -#define TYPE_WKS 11 /* Well-known sockets */ -#define TYPE_PTR 12 /* Pointer record */ -#define TYPE_HINFO 13 /* Host information */ -#define TYPE_MINFO 14 /* Mailbox information (experimental)*/ -#define TYPE_MX 15 /* Mail exchanger */ -#define TYPE_TXT 16 /* Text strings */ -#define TYPE_ANY 255 /* Matches any type */ - -#define CLASS_IN 1 /* The ARPA Internet */ - -/* Round trip timing parameters */ -#define AGAIN 8 /* Average RTT gain = 1/8 */ -#define LAGAIN 3 /* Log2(AGAIN) */ -#define DGAIN 4 /* Mean deviation gain = 1/4 */ -#define LDGAIN 2 /* log2(DGAIN) */ - -/* Header for all domain messages */ -struct dhdr -{ - uint16_t id; /* Identification */ - uint8_t qr; /* Query/Response */ -#define QUERY 0 -#define RESPONSE 1 - uint8_t opcode; -#define IQUERY 1 - uint8_t aa; /* Authoratative answer */ - uint8_t tc; /* Truncation */ - uint8_t rd; /* Recursion desired */ - uint8_t ra; /* Recursion available */ - uint8_t rcode; /* Response code */ -#define NO_ERROR 0 -#define FORMAT_ERROR 1 -#define SERVER_FAIL 2 -#define NAME_ERROR 3 -#define NOT_IMPL 4 -#define REFUSED 5 - uint16_t qdcount; /* Question count */ - uint16_t ancount; /* Answer count */ - uint16_t nscount; /* Authority (name server) count */ - uint16_t arcount; /* Additional record count */ -}; - - -uint8_t* pDNSMSG; // DNS message buffer -uint8_t DNS_SOCKET; // SOCKET number for DNS -uint16_t DNS_MSGID; // DNS message ID - - -uint32_t HAL_GetTick(void) { - return supervisor_ticks_ms32(); -} - -uint32_t hal_sys_tick; - -/* converts uint16_t from network buffer to a host byte order integer. */ -uint16_t get16(uint8_t * s) -{ - uint16_t i; - i = *s++ << 8; - i = i + *s; - return i; -} - -/* copies uint16_t to the network buffer with network byte order. */ -uint8_t * put16(uint8_t * s, uint16_t i) -{ - *s++ = i >> 8; - *s++ = i; - return s; -} - - -/* - * CONVERT A DOMAIN NAME TO THE HUMAN-READABLE FORM - * - * Description : This function converts a compressed domain name to the human-readable form - * Arguments : msg - is a pointer to the reply message - * compressed - is a pointer to the domain name in reply message. - * buf - is a pointer to the buffer for the human-readable form name. - * len - is the MAX. size of buffer. - * Returns : the length of compressed message - */ -int parse_name(uint8_t * msg, uint8_t * compressed, char * buf, int16_t len) -{ - uint16_t slen; /* Length of current segment */ - uint8_t * cp; - int clen = 0; /* Total length of compressed name */ - int indirect = 0; /* Set if indirection encountered */ - int nseg = 0; /* Total number of segments in name */ - - cp = compressed; - - for (;;) - { - slen = *cp++; /* Length of this segment */ - - if (!indirect) clen++; - - if ((slen & 0xc0) == 0xc0) - { - if (!indirect) - clen++; - indirect = 1; - /* Follow indirection */ - cp = &msg[((slen & 0x3f)<<8) + *cp]; - slen = *cp++; - } - - if (slen == 0) /* zero length == all done */ - break; - - len -= slen + 1; - - if (len < 0) return -1; - - if (!indirect) clen += slen; - - while (slen-- != 0) *buf++ = (char)*cp++; - *buf++ = '.'; - nseg++; - } - - if (nseg == 0) - { - /* Root name; represent as single dot */ - *buf++ = '.'; - len--; - } - - *buf++ = '\0'; - len--; - - return clen; /* Length of compressed message */ -} - -/* - * PARSE QUESTION SECTION - * - * Description : This function parses the question record of the reply message. - * Arguments : msg - is a pointer to the reply message - * cp - is a pointer to the question record. - * Returns : a pointer the to next record. - */ -uint8_t * dns_question(uint8_t * msg, uint8_t * cp) -{ - int len; - char name[MAXCNAME]; - - len = parse_name(msg, cp, name, MAXCNAME); - - - if (len == -1) return 0; - - cp += len; - cp += 2; /* type */ - cp += 2; /* class */ - - return cp; -} - - -/* - * PARSE ANSER SECTION - * - * Description : This function parses the answer record of the reply message. - * Arguments : msg - is a pointer to the reply message - * cp - is a pointer to the answer record. - * Returns : a pointer the to next record. - */ -uint8_t * dns_answer(uint8_t * msg, uint8_t * cp, uint8_t * ip_from_dns) -{ - int len, type; - char name[MAXCNAME]; - - len = parse_name(msg, cp, name, MAXCNAME); - - if (len == -1) return 0; - - cp += len; - type = get16(cp); - cp += 2; /* type */ - cp += 2; /* class */ - cp += 4; /* ttl */ - cp += 2; /* len */ - - - switch (type) - { - case TYPE_A: - /* Just read the address directly into the structure */ - ip_from_dns[0] = *cp++; - ip_from_dns[1] = *cp++; - ip_from_dns[2] = *cp++; - ip_from_dns[3] = *cp++; - break; - case TYPE_CNAME: - case TYPE_MB: - case TYPE_MG: - case TYPE_MR: - case TYPE_NS: - case TYPE_PTR: - /* These types all consist of a single domain name */ - /* convert it to ASCII format */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - break; - case TYPE_HINFO: - len = *cp++; - cp += len; - - len = *cp++; - cp += len; - break; - case TYPE_MX: - cp += 2; - /* Get domain name of exchanger */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - break; - case TYPE_SOA: - /* Get domain name of name server */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - - /* Get domain name of responsible person */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - - cp += 4; - cp += 4; - cp += 4; - cp += 4; - cp += 4; - break; - case TYPE_TXT: - /* Just stash */ - break; - default: - /* Ignore */ - break; - } - - return cp; -} - -/* - * PARSE THE DNS REPLY - * - * Description : This function parses the reply message from DNS server. - * Arguments : dhdr - is a pointer to the header for DNS message - * buf - is a pointer to the reply message. - * len - is the size of reply message. - * Returns : -1 - Domain name length is too big - * 0 - Fail (Timeout or parse error) - * 1 - Success, - */ -int8_t parseDNSMSG(struct dhdr * pdhdr, uint8_t * pbuf, uint8_t * ip_from_dns) -{ - uint16_t tmp; - uint16_t i; - uint8_t * msg; - uint8_t * cp; - - msg = pbuf; - memset(pdhdr, 0, sizeof(*pdhdr)); - - pdhdr->id = get16(&msg[0]); - tmp = get16(&msg[2]); - if (tmp & 0x8000) pdhdr->qr = 1; - - pdhdr->opcode = (tmp >> 11) & 0xf; - - if (tmp & 0x0400) pdhdr->aa = 1; - if (tmp & 0x0200) pdhdr->tc = 1; - if (tmp & 0x0100) pdhdr->rd = 1; - if (tmp & 0x0080) pdhdr->ra = 1; - - pdhdr->rcode = tmp & 0xf; - pdhdr->qdcount = get16(&msg[4]); - pdhdr->ancount = get16(&msg[6]); - pdhdr->nscount = get16(&msg[8]); - pdhdr->arcount = get16(&msg[10]); - - - /* Now parse the variable length sections */ - cp = &msg[12]; - - /* Question section */ - for (i = 0; i < pdhdr->qdcount; i++) - { - cp = dns_question(msg, cp); - if(!cp) - { -#ifdef _DNS_DEBUG_ - printf("MAX_DOMAIN_NAME is too small, it should be redefined in dns.h\r\n"); -#endif - return -1; - } - } - - /* Answer section */ - for (i = 0; i < pdhdr->ancount; i++) - { - cp = dns_answer(msg, cp, ip_from_dns); - if(!cp) - { -#ifdef _DNS_DEBUG_ - printf("MAX_DOMAIN_NAME is too small, it should be redefined in dns.h\r\n"); -#endif - return -1; - } - - } - - /* Name server (authority) section */ - for (i = 0; i < pdhdr->nscount; i++) - { - ; - } - - /* Additional section */ - for (i = 0; i < pdhdr->arcount; i++) - { - ; - } - - if(pdhdr->rcode == 0) return 1; // No error - else return 0; -} - - -/* - * MAKE DNS QUERY MESSAGE - * - * Description : This function makes DNS query message. - * Arguments : op - Recursion desired - * name - is a pointer to the domain name. - * buf - is a pointer to the buffer for DNS message. - * len - is the MAX. size of buffer. - * Returns : the pointer to the DNS message. - */ -int16_t dns_makequery(uint16_t op, char * name, uint8_t * buf, uint16_t len) -{ - uint8_t *cp; - char *cp1; - char sname[MAXCNAME]; - char *dname; - uint16_t p; - uint16_t dlen; - - cp = buf; - - DNS_MSGID++; - cp = put16(cp, DNS_MSGID); - p = (op << 11) | 0x0100; /* Recursion desired */ - cp = put16(cp, p); - cp = put16(cp, 1); - cp = put16(cp, 0); - cp = put16(cp, 0); - cp = put16(cp, 0); - - strcpy(sname, name); - dname = sname; - dlen = strlen(dname); - for (;;) - { - /* Look for next dot */ - cp1 = strchr(dname, '.'); - - if (cp1 != NULL) len = cp1 - dname; /* More to come */ - else len = dlen; /* Last component */ - - *cp++ = len; /* Write length of component */ - if (len == 0) break; - - /* Copy component up to (but not including) dot */ - memcpy(cp, dname, len); - cp += len; - if (cp1 == NULL) - { - *cp++ = 0; /* Last one; write null and finish */ - break; - } - dname += len+1; - dlen -= len+1; - } - - cp = put16(cp, 0x0001); /* type */ - cp = put16(cp, 0x0001); /* class */ - - return ((int16_t)((uint32_t)(cp) - (uint32_t)(buf))); -} - -/* - * CHECK DNS TIMEOUT - * - * Description : This function check the DNS timeout - * Arguments : None. - * Returns : -1 - timeout occurred, 0 - timer over, but no timeout, 1 - no timer over, no timeout occur - * Note : timeout : retry count and timer both over. - */ - -int8_t check_DNS_timeout(void) -{ - static uint8_t retry_count; - - uint32_t tick = HAL_GetTick(); - if(tick - hal_sys_tick >= DNS_WAIT_TIME * 1000) - { - hal_sys_tick = tick; - if(retry_count >= MAX_DNS_RETRY) { - retry_count = 0; - return -1; // timeout occurred - } - retry_count++; - return 0; // timer over, but no timeout - } - - return 1; // no timer over, no timeout occur -} - - - -/* DNS CLIENT INIT */ -void DNS_init(uint8_t s, uint8_t * buf) -{ - DNS_SOCKET = s; // SOCK_DNS - pDNSMSG = buf; // User's shared buffer - DNS_MSGID = DNS_MSG_ID; -} - -/* DNS CLIENT RUN */ -int8_t DNS_run(uint8_t * dns_ip, uint8_t * name, uint8_t * ip_from_dns) -{ - int8_t ret; - struct dhdr dhp; - uint8_t ip[4]; - uint16_t len, port; - int8_t ret_check_timeout; - - hal_sys_tick = HAL_GetTick(); - - // Socket open - WIZCHIP_EXPORT(socket)(DNS_SOCKET, Sn_MR_UDP, 0, 0); - -#ifdef _DNS_DEBUG_ - printf("> DNS Query to DNS Server : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]); -#endif - - len = dns_makequery(0, (char *)name, pDNSMSG, MAX_DNS_BUF_SIZE); - WIZCHIP_EXPORT(sendto)(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN); - - while (1) - { - if ((len = getSn_RX_RSR(DNS_SOCKET)) > 0) - { - if (len > MAX_DNS_BUF_SIZE) len = MAX_DNS_BUF_SIZE; - len = WIZCHIP_EXPORT(recvfrom)(DNS_SOCKET, pDNSMSG, len, ip, &port); - #ifdef _DNS_DEBUG_ - printf("> Receive DNS message from %d.%d.%d.%d(%d). len = %d\r\n", ip[0], ip[1], ip[2], ip[3],port,len); - #endif - ret = parseDNSMSG(&dhp, pDNSMSG, ip_from_dns); - break; - } - // Check Timeout - ret_check_timeout = check_DNS_timeout(); - if (ret_check_timeout < 0) { - -#ifdef _DNS_DEBUG_ - printf("> DNS Server is not responding : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]); -#endif - return 0; // timeout occurred - } - else if (ret_check_timeout == 0) { - -#ifdef _DNS_DEBUG_ - printf("> DNS Timeout\r\n"); -#endif - WIZCHIP_EXPORT(sendto)(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN); - } - } - WIZCHIP_EXPORT(close)(DNS_SOCKET); - // Return value - // 0 > : failed / 1 - success - return ret; -} diff --git a/drivers/wiznet5k/internet/dns/dns.h b/drivers/wiznet5k/internet/dns/dns.h deleted file mode 100644 index 574b632a6a..0000000000 --- a/drivers/wiznet5k/internet/dns/dns.h +++ /dev/null @@ -1,96 +0,0 @@ -//***************************************************************************** -// -//! \file dns.h -//! \brief DNS APIs Header file. -//! \details Send DNS query & Receive DNS reponse. -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.1.0 -//! 1. Remove secondary DNS server in DNS_run -//! If 1st DNS_run failed, call DNS_run with 2nd DNS again -//! 2. DNS_timerHandler -> DNS_time_handler -//! 3. Move the no reference define to dns.c -//! 4. Integrated dns.h dns.c & dns_parse.h dns_parse.c into dns.h & dns.c -//! <2013/12/20> V1.1.0 -//! -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#ifndef _DNS_H_ -#define _DNS_H_ - -#include -/* - * @brief Define it for Debug & Monitor DNS processing. - * @note If defined, it depends on - */ - -//#define _DNS_DEBUG_ - -#define MAX_DNS_BUF_SIZE 256 ///< maximum size of DNS buffer. */ -/* - * @brief Maximum length of your queried Domain name - * @todo SHOULD BE defined it equal as or greater than your Domain name length + null character(1) - * @note SHOULD BE careful to stack overflow because it is allocated 1.5 times as MAX_DOMAIN_NAME in stack. - */ -#define MAX_DOMAIN_NAME 32 // for example "www.google.com" - -#define MAX_DNS_RETRY 2 ///< Requery Count -#define DNS_WAIT_TIME 4 ///< Wait response time. unit 1s. - -#define IPPORT_DOMAIN 53 ///< DNS server port number - -#define DNS_MSG_ID 0x1122 ///< ID for DNS message. You can be modified it any number -/* - * @brief DNS process initialize - * @param s : Socket number for DNS - * @param buf : Buffer for DNS message - */ -void DNS_init(uint8_t s, uint8_t * buf); - -/* - * @brief DNS process - * @details Send DNS query and receive DNS response - * @param dns_ip : DNS server ip address - * @param name : Domain name to be queried - * @param ip_from_dns : IP address from DNS server - * @return -1 : failed. @ref MAX_DOMIN_NAME is too small \n - * 0 : failed (Timeout or Parse error)\n - * 1 : success - * @note This function blocks until success or fail. max time = @ref MAX_DNS_RETRY * @ref DNS_WAIT_TIME - */ -int8_t DNS_run(uint8_t * dns_ip, uint8_t * name, uint8_t * ip_from_dns); - -#endif /* _DNS_H_ */ diff --git a/extmod/axtls-include/config.h b/extmod/axtls-include/config.h new file mode 100644 index 0000000000..4cb1aed9ca --- /dev/null +++ b/extmod/axtls-include/config.h @@ -0,0 +1,117 @@ +/* + * Automatically generated header file: don't edit + */ + +#define HAVE_DOT_CONFIG 1 +#define CONFIG_PLATFORM_LINUX 1 +#undef CONFIG_PLATFORM_CYGWIN +#undef CONFIG_PLATFORM_WIN32 + +/* + * General Configuration + */ +#define PREFIX "/usr/local" +#undef CONFIG_DEBUG +#undef CONFIG_STRIP_UNWANTED_SECTIONS +#undef CONFIG_VISUAL_STUDIO_7_0 +#undef CONFIG_VISUAL_STUDIO_8_0 +#undef CONFIG_VISUAL_STUDIO_10_0 +#define CONFIG_VISUAL_STUDIO_7_0_BASE "" +#define CONFIG_VISUAL_STUDIO_8_0_BASE "" +#define CONFIG_VISUAL_STUDIO_10_0_BASE "" +#define CONFIG_EXTRA_CFLAGS_OPTIONS "" +#define CONFIG_EXTRA_LDFLAGS_OPTIONS "" + +/* + * SSL Library + */ +#undef CONFIG_SSL_SERVER_ONLY +#undef CONFIG_SSL_CERT_VERIFICATION +#undef CONFIG_SSL_FULL_MODE +#define CONFIG_SSL_SKELETON_MODE 1 +#define CONFIG_SSL_ENABLE_SERVER 1 +#define CONFIG_SSL_ENABLE_CLIENT 1 +#undef CONFIG_SSL_DIAGNOSTICS +#define CONFIG_SSL_PROT_LOW 1 +#undef CONFIG_SSL_PROT_MEDIUM +#undef CONFIG_SSL_PROT_HIGH +#define CONFIG_SSL_AES 1 +#define CONFIG_SSL_USE_DEFAULT_KEY 1 +#define CONFIG_SSL_PRIVATE_KEY_LOCATION "" +#define CONFIG_SSL_PRIVATE_KEY_PASSWORD "" +#define CONFIG_SSL_X509_CERT_LOCATION "" +#undef CONFIG_SSL_GENERATE_X509_CERT +#define CONFIG_SSL_X509_COMMON_NAME "" +#define CONFIG_SSL_X509_ORGANIZATION_NAME "" +#define CONFIG_SSL_X509_ORGANIZATION_UNIT_NAME "" +#undef CONFIG_SSL_HAS_PEM +#undef CONFIG_SSL_USE_PKCS12 +#define CONFIG_SSL_EXPIRY_TIME +#define CONFIG_X509_MAX_CA_CERTS 0 +#define CONFIG_SSL_MAX_CERTS 3 +#undef CONFIG_SSL_CTX_MUTEXING +#undef CONFIG_USE_DEV_URANDOM +#undef CONFIG_WIN32_USE_CRYPTO_LIB +#undef CONFIG_OPENSSL_COMPATIBLE +#undef CONFIG_PERFORMANCE_TESTING +#undef CONFIG_SSL_TEST +#undef CONFIG_AXTLSWRAP +#undef CONFIG_AXHTTPD +#undef CONFIG_HTTP_STATIC_BUILD +#define CONFIG_HTTP_PORT +#define CONFIG_HTTP_HTTPS_PORT +#define CONFIG_HTTP_SESSION_CACHE_SIZE +#define CONFIG_HTTP_WEBROOT "" +#define CONFIG_HTTP_TIMEOUT +#undef CONFIG_HTTP_HAS_CGI +#define CONFIG_HTTP_CGI_EXTENSIONS "" +#undef CONFIG_HTTP_ENABLE_LUA +#define CONFIG_HTTP_LUA_PREFIX "" +#undef CONFIG_HTTP_BUILD_LUA +#define CONFIG_HTTP_CGI_LAUNCHER "" +#undef CONFIG_HTTP_DIRECTORIES +#undef CONFIG_HTTP_HAS_AUTHORIZATION +#undef CONFIG_HTTP_HAS_IPV6 +#undef CONFIG_HTTP_ENABLE_DIFFERENT_USER +#define CONFIG_HTTP_USER "" +#undef CONFIG_HTTP_VERBOSE +#undef CONFIG_HTTP_IS_DAEMON + +/* + * Language Bindings + */ +#undef CONFIG_BINDINGS +#undef CONFIG_CSHARP_BINDINGS +#undef CONFIG_VBNET_BINDINGS +#define CONFIG_DOT_NET_FRAMEWORK_BASE "" +#undef CONFIG_JAVA_BINDINGS +#define CONFIG_JAVA_HOME "" +#undef CONFIG_PERL_BINDINGS +#define CONFIG_PERL_CORE "" +#define CONFIG_PERL_LIB "" +#undef CONFIG_LUA_BINDINGS +#define CONFIG_LUA_CORE "" + +/* + * Samples + */ +#undef CONFIG_SAMPLES +#undef CONFIG_C_SAMPLES +#undef CONFIG_CSHARP_SAMPLES +#undef CONFIG_VBNET_SAMPLES +#undef CONFIG_JAVA_SAMPLES +#undef CONFIG_PERL_SAMPLES +#undef CONFIG_LUA_SAMPLES +#undef CONFIG_BIGINT_CLASSICAL +#undef CONFIG_BIGINT_MONTGOMERY +#undef CONFIG_BIGINT_BARRETT +#undef CONFIG_BIGINT_CRT +#undef CONFIG_BIGINT_KARATSUBA +#define MUL_KARATSUBA_THRESH +#define SQU_KARATSUBA_THRESH +#undef CONFIG_BIGINT_SLIDING_WINDOW +#undef CONFIG_BIGINT_SQUARE +#undef CONFIG_BIGINT_CHECK_ON +#undef CONFIG_INTEGER_32BIT +#undef CONFIG_INTEGER_16BIT +#undef CONFIG_INTEGER_8BIT diff --git a/extmod/axtls-include/version.h b/extmod/axtls-include/version.h new file mode 100644 index 0000000000..df2260e4c6 --- /dev/null +++ b/extmod/axtls-include/version.h @@ -0,0 +1 @@ +#define AXTLS_VERSION "(no version)" diff --git a/extmod/machine_mem.c b/extmod/machine_mem.c deleted file mode 100644 index 9597b32e6c..0000000000 --- a/extmod/machine_mem.c +++ /dev/null @@ -1,94 +0,0 @@ -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George -// -// SPDX-License-Identifier: MIT - -#include "py/runtime.h" -#include "extmod/machine_mem.h" - -#if MICROPY_PY_MACHINE - -// If you wish to override the functions for mapping the machine_mem read/write -// address, then add a #define for MICROPY_MACHINE_MEM_GET_READ_ADDR and/or -// MICROPY_MACHINE_MEM_GET_WRITE_ADDR in your mpconfigport.h. Since the -// prototypes are identical, it is allowable for both of the macros to evaluate -// the to same function. -// -// It is expected that the modmachine.c file for a given port will provide the -// implementations, if the default implementation isn't used. - -#if !defined(MICROPY_MACHINE_MEM_GET_READ_ADDR) || !defined(MICROPY_MACHINE_MEM_GET_WRITE_ADDR) -STATIC uintptr_t machine_mem_get_addr(mp_obj_t addr_o, uint align) { - uintptr_t addr = mp_obj_int_get_truncated(addr_o); - if ((addr & (align - 1)) != 0) { - mp_raise_ValueError_varg(translate("address %08x is not aligned to %d bytes"), addr, align); - } - return addr; -} -#if !defined(MICROPY_MACHINE_MEM_GET_READ_ADDR) -#define MICROPY_MACHINE_MEM_GET_READ_ADDR machine_mem_get_addr -#endif -#if !defined(MICROPY_MACHINE_MEM_GET_WRITE_ADDR) -#define MICROPY_MACHINE_MEM_GET_WRITE_ADDR machine_mem_get_addr -#endif -#endif - -STATIC void machine_mem_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - (void)kind; - machine_mem_obj_t *self = MP_OBJ_TO_PTR(self_in); - mp_printf(print, "<%u-bit memory>", 8 * self->elem_size); -} - -STATIC mp_obj_t machine_mem_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { - // TODO support slice index to read/write multiple values at once - machine_mem_obj_t *self = MP_OBJ_TO_PTR(self_in); - if (value == MP_OBJ_NULL) { - // delete - return MP_OBJ_NULL; // op not supported - } else if (value == MP_OBJ_SENTINEL) { - // load - uintptr_t addr = MICROPY_MACHINE_MEM_GET_READ_ADDR(index, self->elem_size); - uint32_t val; - switch (self->elem_size) { - case 1: - val = (*(uint8_t *)addr); - break; - case 2: - val = (*(uint16_t *)addr); - break; - default: - val = (*(uint32_t *)addr); - break; - } - return mp_obj_new_int(val); - } else { - // store - uintptr_t addr = MICROPY_MACHINE_MEM_GET_WRITE_ADDR(index, self->elem_size); - uint32_t val = mp_obj_get_int_truncated(value); - switch (self->elem_size) { - case 1: - (*(uint8_t *)addr) = val; - break; - case 2: - (*(uint16_t *)addr) = val; - break; - default: - (*(uint32_t *)addr) = val; - break; - } - return mp_const_none; - } -} - -const mp_obj_type_t machine_mem_type = { - { &mp_type_type }, - .name = MP_QSTR_mem, - .print = machine_mem_print, - .subscr = machine_mem_subscr, -}; - -const machine_mem_obj_t machine_mem8_obj = {{&machine_mem_type}, 1}; -const machine_mem_obj_t machine_mem16_obj = {{&machine_mem_type}, 2}; -const machine_mem_obj_t machine_mem32_obj = {{&machine_mem_type}, 4}; - -#endif // MICROPY_PY_MACHINE diff --git a/extmod/machine_mem.h b/extmod/machine_mem.h deleted file mode 100644 index 735887c60e..0000000000 --- a/extmod/machine_mem.h +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2015 Damien P. George -// -// SPDX-License-Identifier: MIT - -#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H -#define MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H - -#include "py/obj.h" - -typedef struct _machine_mem_obj_t { - mp_obj_base_t base; - unsigned elem_size; // in bytes -} machine_mem_obj_t; - -extern const mp_obj_type_t machine_mem_type; - -extern const machine_mem_obj_t machine_mem8_obj; -extern const machine_mem_obj_t machine_mem16_obj; -extern const machine_mem_obj_t machine_mem32_obj; - -#if defined(MICROPY_MACHINE_MEM_GET_READ_ADDR) -uintptr_t MICROPY_MACHINE_MEM_GET_READ_ADDR(mp_obj_t addr_o, uint align); -#endif -#if defined(MICROPY_MACHINE_MEM_GET_WRITE_ADDR) -uintptr_t MICROPY_MACHINE_MEM_GET_WRITE_ADDR(mp_obj_t addr_o, uint align); -#endif - -#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H diff --git a/extmod/machine_pinbase.c b/extmod/machine_pinbase.c deleted file mode 100644 index a5e33c5602..0000000000 --- a/extmod/machine_pinbase.c +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2016 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// -// SPDX-License-Identifier: MIT - -#include "py/mpconfig.h" -#if MICROPY_PY_MACHINE - -#include "py/obj.h" -#include "py/runtime.h" -#include "extmod/virtpin.h" -#include "extmod/machine_pinbase.h" - -// PinBase class - -// As this is abstract class, its instance is null. -// But there should be an instance, as the rest of instance code -// expects that there will be concrete object for inheritance. -typedef struct _mp_pinbase_t { - mp_obj_base_t base; -} mp_pinbase_t; - -STATIC const mp_pinbase_t pinbase_singleton = { - .base = { &machine_pinbase_type }, -}; - -STATIC mp_obj_t pinbase_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { - (void)type; - (void)n_args; - (void)args; - (void)kw_args; - return MP_OBJ_FROM_PTR(&pinbase_singleton); -} - -mp_uint_t pinbase_ioctl(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode); -mp_uint_t pinbase_ioctl(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode) { - (void)errcode; - switch (request) { - case MP_PIN_READ: { - mp_obj_t dest[2]; - mp_load_method(obj, MP_QSTR_value, dest); - return mp_obj_get_int(mp_call_method_n_kw(0, 0, dest)); - } - case MP_PIN_WRITE: { - mp_obj_t dest[3]; - mp_load_method(obj, MP_QSTR_value, dest); - dest[2] = (arg == 0 ? mp_const_false : mp_const_true); - mp_call_method_n_kw(1, 0, dest); - return 0; - } - } - return -1; -} - -STATIC const mp_pin_p_t pinbase_pin_p = { - MP_PROTO_IMPLEMENT(MP_QSTR_protocol_pin) - .ioctl = pinbase_ioctl, -}; - -const mp_obj_type_t machine_pinbase_type = { - { &mp_type_type }, - .name = MP_QSTR_PinBase, - .make_new = pinbase_make_new, - .protocol = &pinbase_pin_p, -}; - -#endif // MICROPY_PY_MACHINE diff --git a/extmod/machine_pinbase.h b/extmod/machine_pinbase.h deleted file mode 100644 index b747563a1e..0000000000 --- a/extmod/machine_pinbase.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) 2016 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// -// SPDX-License-Identifier: MIT - -#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H -#define MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H - -#include "py/obj.h" - -extern const mp_obj_type_t machine_pinbase_type; - -#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H diff --git a/extmod/machine_pulse.c b/extmod/machine_pulse.c deleted file mode 100644 index eaee12b367..0000000000 --- a/extmod/machine_pulse.c +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2016 Damien P. George -// -// SPDX-License-Identifier: MIT - -#include "py/runtime.h" -#include "py/mperrno.h" -#include "extmod/machine_pulse.h" - -#if MICROPY_PY_MACHINE_PULSE - -mp_uint_t machine_time_pulse_us(mp_hal_pin_obj_t pin, int pulse_level, mp_uint_t timeout_us) { - mp_uint_t start = mp_hal_ticks_us(); - while (mp_hal_pin_read(pin) != pulse_level) { - if ((mp_uint_t)(mp_hal_ticks_us() - start) >= timeout_us) { - return (mp_uint_t)-2; - } - } - start = mp_hal_ticks_us(); - while (mp_hal_pin_read(pin) == pulse_level) { - if ((mp_uint_t)(mp_hal_ticks_us() - start) >= timeout_us) { - return (mp_uint_t)-1; - } - } - return mp_hal_ticks_us() - start; -} - -STATIC mp_obj_t machine_time_pulse_us_(size_t n_args, const mp_obj_t *args) { - mp_hal_pin_obj_t pin = mp_hal_get_pin_obj(args[0]); - int level = 0; - if (mp_obj_is_true(args[1])) { - level = 1; - } - mp_uint_t timeout_us = 1000000; - if (n_args > 2) { - timeout_us = mp_obj_get_int(args[2]); - } - mp_uint_t us = machine_time_pulse_us(pin, level, timeout_us); - // May return -1 or -2 in case of timeout - return mp_obj_new_int(us); -} -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_time_pulse_us_obj, 2, 3, machine_time_pulse_us_); - -#endif diff --git a/extmod/machine_pulse.h b/extmod/machine_pulse.h deleted file mode 100644 index a9b0ebc1b4..0000000000 --- a/extmod/machine_pulse.h +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2016 Damien P. George -// -// SPDX-License-Identifier: MIT - -#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H -#define MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H - -#include "py/obj.h" -#include "py/mphal.h" - -mp_uint_t machine_time_pulse_us(mp_hal_pin_obj_t pin, int pulse_level, mp_uint_t timeout_us); - -MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(machine_time_pulse_us_obj); - -#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H diff --git a/extmod/machine_signal.c b/extmod/machine_signal.c deleted file mode 100644 index a8e5ebc928..0000000000 --- a/extmod/machine_signal.c +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) 2017 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// -// SPDX-License-Identifier: MIT - -#include "py/mpconfig.h" -#if MICROPY_PY_MACHINE - -#include - -#include "py/obj.h" -#include "py/runtime.h" -#include "extmod/virtpin.h" -#include "extmod/machine_signal.h" - -// Signal class - -typedef struct _machine_signal_t { - mp_obj_base_t base; - mp_obj_t pin; - bool invert; -} machine_signal_t; - -STATIC mp_obj_t signal_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { - mp_obj_t pin = args[0]; - bool invert = false; - - #if defined(MICROPY_PY_MACHINE_PIN_MAKE_NEW) - mp_pin_p_t *pin_p = (mp_pin_t *)mp_proto_get(QSTR_pin_protocol, pin); - - if (pin_p == NULL) { - // If first argument isn't a Pin-like object, we filter out "invert" - // from keyword arguments and pass them all to the exported Pin - // constructor to create one. - mp_obj_t *pin_args = mp_local_alloc((n_args + n_kw * 2) * sizeof(mp_obj_t)); - memcpy(pin_args, args, n_args * sizeof(mp_obj_t)); - const mp_obj_t *src = args + n_args; - mp_obj_t *dst = pin_args + n_args; - mp_obj_t *sig_value = NULL; - for (size_t cnt = n_kw; cnt; cnt--) { - if (*src == MP_OBJ_NEW_QSTR(MP_QSTR_invert)) { - invert = mp_obj_is_true(src[1]); - n_kw--; - } else { - *dst++ = *src; - *dst++ = src[1]; - } - if (*src == MP_OBJ_NEW_QSTR(MP_QSTR_value)) { - // Value is pertained to Signal, so we should invert - // it for Pin if needed, and we should do it only when - // inversion status is guaranteedly known. - sig_value = dst - 1; - } - src += 2; - } - - if (invert && sig_value != NULL) { - *sig_value = mp_obj_is_true(*sig_value) ? MP_OBJ_NEW_SMALL_INT(0) : MP_OBJ_NEW_SMALL_INT(1); - } - - // Here we pass NULL as a type, hoping that mp_pin_make_new() - // will just ignore it as set a concrete type. If not, we'd need - // to expose port's "default" pin type too. - pin = MICROPY_PY_MACHINE_PIN_MAKE_NEW(NULL, n_args, n_kw, pin_args); - - mp_local_free(pin_args); - } else - #endif - // Otherwise there should be 1 or 2 args - { - if (n_args == 1) { - if (kw_args == NULL || kw_args->used == 0) { - } else if (kw_args->used == 1 && kw_args->table[0].key == MP_OBJ_NEW_QSTR(MP_QSTR_invert)) { - invert = mp_obj_is_true(kw_args->table[0].value); - } else { - goto error; - } - } else { - error: - mp_raise_TypeError(NULL); - } - } - - machine_signal_t *o = m_new_obj(machine_signal_t); - o->base.type = type; - o->pin = pin; - o->invert = invert; - return MP_OBJ_FROM_PTR(o); -} - -STATIC mp_uint_t signal_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { - (void)errcode; - machine_signal_t *self = MP_OBJ_TO_PTR(self_in); - - switch (request) { - case MP_PIN_READ: { - return mp_virtual_pin_read(self->pin) ^ self->invert; - } - case MP_PIN_WRITE: { - mp_virtual_pin_write(self->pin, arg ^ self->invert); - return 0; - } - } - return -1; -} - -// fast method for getting/setting signal value -STATIC mp_obj_t signal_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - mp_arg_check_num_kw_array(n_args, n_kw, 0, 1, false); - if (n_args == 0) { - // get pin - return MP_OBJ_NEW_SMALL_INT(mp_virtual_pin_read(self_in)); - } else { - // set pin - mp_virtual_pin_write(self_in, mp_obj_is_true(args[0])); - return mp_const_none; - } -} - -STATIC mp_obj_t signal_value(size_t n_args, const mp_obj_t *args) { - return signal_call(args[0], n_args - 1, 0, args + 1); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(signal_value_obj, 1, 2, signal_value); - -STATIC mp_obj_t signal_on(mp_obj_t self_in) { - mp_virtual_pin_write(self_in, 1); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(signal_on_obj, signal_on); - -STATIC mp_obj_t signal_off(mp_obj_t self_in) { - mp_virtual_pin_write(self_in, 0); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(signal_off_obj, signal_off); - -STATIC const mp_rom_map_elem_t signal_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&signal_value_obj) }, - { MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&signal_on_obj) }, - { MP_ROM_QSTR(MP_QSTR_off), MP_ROM_PTR(&signal_off_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(signal_locals_dict, signal_locals_dict_table); - -STATIC const mp_pin_p_t signal_pin_p = { - MP_PROTO_IMPLEMENT(MP_QSTR_protocol_pin) - .ioctl = signal_ioctl, -}; - -const mp_obj_type_t machine_signal_type = { - { &mp_type_type }, - .name = MP_QSTR_Signal, - .make_new = signal_make_new, - .call = signal_call, - .protocol = &signal_pin_p, - .locals_dict = (void *)&signal_locals_dict, -}; - -#endif // MICROPY_PY_MACHINE diff --git a/extmod/machine_signal.h b/extmod/machine_signal.h deleted file mode 100644 index 17ffe5563f..0000000000 --- a/extmod/machine_signal.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) 2017 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// -// SPDX-License-Identifier: MIT - -#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H -#define MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H - -#include "py/obj.h" - -extern const mp_obj_type_t machine_signal_type; - -#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H diff --git a/extmod/modbtree.c b/extmod/modbtree.c index ac996218ce..96b60018fe 100644 --- a/extmod/modbtree.c +++ b/extmod/modbtree.c @@ -331,7 +331,7 @@ STATIC mp_obj_t mod_btree_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t openinfo.psize = args.pagesize.u_int; openinfo.minkeypage = args.minkeypage.u_int; - DB *db = __bt_open(pos_args[0], &btree_stream_fvtable, &openinfo, /*dflags*/ 0); + DB *db = __bt_open(MP_OBJ_TO_PTR(pos_args[0]), &btree_stream_fvtable, &openinfo, /*dflags*/ 0); if (db == NULL) { mp_raise_OSError(errno); } diff --git a/extmod/modlwip.c b/extmod/modlwip.c deleted file mode 100644 index 6eb68d3fb9..0000000000 --- a/extmod/modlwip.c +++ /dev/null @@ -1,1449 +0,0 @@ -// Copyright (c) 2015 Galen Hazelwood -// Copyright (c) 2015-2017 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George -// -// SPDX-License-Identifier: MIT - -#include -#include - -#include "py/objlist.h" -#include "py/runtime.h" -#include "py/stream.h" -#include "py/mperrno.h" -#include "py/mphal.h" - -#include "lib/netutils/netutils.h" - -#include "lwip/init.h" -#include "lwip/tcp.h" -#include "lwip/udp.h" -// #include "lwip/raw.h" -#include "lwip/dns.h" -#include "lwip/igmp.h" -#if LWIP_VERSION_MAJOR < 2 -#include "lwip/timers.h" -#include "lwip/tcp_impl.h" -#else -#include "lwip/timeouts.h" -#include "lwip/priv/tcp_priv.h" -#endif - -#if 0 // print debugging info -#define DEBUG_printf DEBUG_printf -#else // don't print debugging info -#define DEBUG_printf(...) (void)0 -#endif - -// All socket options should be globally distinct, -// because we ignore option levels for efficiency. -#define IP_ADD_MEMBERSHIP 0x400 - -// For compatibilily with older lwIP versions. -#ifndef ip_set_option -#define ip_set_option(pcb, opt) ((pcb)->so_options |= (opt)) -#endif -#ifndef ip_reset_option -#define ip_reset_option(pcb, opt) ((pcb)->so_options &= ~(opt)) -#endif - -#if MICROPY_PY_LWIP_SLIP -#include "netif/slipif.h" -#include "lwip/sio.h" -#endif - -#if MICROPY_PY_LWIP_SLIP -/******************************************************************************/ -// Slip object for modlwip. Requires a serial driver for the port that supports -// the lwip serial callback functions. - -typedef struct _lwip_slip_obj_t { - mp_obj_base_t base; - struct netif lwip_netif; -} lwip_slip_obj_t; - -// Slip object is unique for now. Possibly can fix this later. FIXME -STATIC lwip_slip_obj_t lwip_slip_obj; - -// Declare these early. -void mod_lwip_register_poll(void (*poll)(void *arg), void *poll_arg); -void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg); - -STATIC void slip_lwip_poll(void *netif) { - slipif_poll((struct netif *)netif); -} - -STATIC const mp_obj_type_t lwip_slip_type; - -// lwIP SLIP callback functions -sio_fd_t sio_open(u8_t dvnum) { - // We support singleton SLIP interface, so just return any truish value. - return (sio_fd_t)1; -} - -void sio_send(u8_t c, sio_fd_t fd) { - mp_obj_type_t *type = mp_obj_get_type(MP_STATE_VM(lwip_slip_stream)); - int error; - type->stream_p->write(MP_STATE_VM(lwip_slip_stream), &c, 1, &error); -} - -u32_t sio_tryread(sio_fd_t fd, u8_t *data, u32_t len) { - mp_obj_type_t *type = mp_obj_get_type(MP_STATE_VM(lwip_slip_stream)); - int error; - mp_uint_t out_sz = type->stream_p->read(MP_STATE_VM(lwip_slip_stream), data, len, &error); - if (out_sz == MP_STREAM_ERROR) { - if (mp_is_nonblocking_error(error)) { - return 0; - } - // Can't do much else, can we? - return 0; - } - return out_sz; -} - -// constructor lwip.slip(device=integer, iplocal=string, ipremote=string) -STATIC mp_obj_t lwip_slip_make_new(mp_obj_t type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - mp_arg_check_num(n_args, n_kw, 3, 3, false); - - lwip_slip_obj.base.type = &lwip_slip_type; - - MP_STATE_VM(lwip_slip_stream) = args[0]; - - ip_addr_t iplocal, ipremote; - if (!ipaddr_aton(mp_obj_str_get_str(args[1]), &iplocal)) { - mp_raise_ValueError("not a valid local IP"); - } - if (!ipaddr_aton(mp_obj_str_get_str(args[2]), &ipremote)) { - mp_raise_ValueError("not a valid remote IP"); - } - - struct netif *n = &lwip_slip_obj.lwip_netif; - if (netif_add(n, &iplocal, IP_ADDR_BROADCAST, &ipremote, NULL, slipif_init, ip_input) == NULL) { - mp_raise_ValueError("out of memory"); - } - netif_set_up(n); - netif_set_default(n); - mod_lwip_register_poll(slip_lwip_poll, n); - - return (mp_obj_t)&lwip_slip_obj; -} - -STATIC mp_obj_t lwip_slip_status(mp_obj_t self_in) { - // Null function for now. - return mp_const_none; -} - -STATIC MP_DEFINE_CONST_FUN_OBJ_1(lwip_slip_status_obj, lwip_slip_status); - -STATIC const mp_rom_map_elem_t lwip_slip_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&lwip_slip_status_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(lwip_slip_locals_dict, lwip_slip_locals_dict_table); - -STATIC const mp_obj_type_t lwip_slip_type = { - { &mp_type_type }, - .name = MP_QSTR_slip, - .make_new = lwip_slip_make_new, - .locals_dict = (mp_obj_dict_t *)&lwip_slip_locals_dict, -}; - -#endif // MICROPY_PY_LWIP_SLIP - -/******************************************************************************/ -// Table to convert lwIP err_t codes to socket errno codes, from the lwIP -// socket API. - -// lwIP 2 changed LWIP_VERSION and it can no longer be used in macros, -// so we define our own equivalent version that can. -#define LWIP_VERSION_MACRO (LWIP_VERSION_MAJOR << 24 | LWIP_VERSION_MINOR << 16 \ - | LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC) - -// Extension to lwIP error codes -#define _ERR_BADF -16 -// TODO: We just know that change happened somewhere between 1.4.0 and 1.4.1, -// investigate in more detail. -#if LWIP_VERSION_MACRO < 0x01040100 -static const int error_lookup_table[] = { - 0, /* ERR_OK 0 No error, everything OK. */ - MP_ENOMEM, /* ERR_MEM -1 Out of memory error. */ - MP_ENOBUFS, /* ERR_BUF -2 Buffer error. */ - MP_EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ - MP_EHOSTUNREACH, /* ERR_RTE -4 Routing problem. */ - MP_EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ - MP_EINVAL, /* ERR_VAL -6 Illegal value. */ - MP_EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block. */ - - MP_ECONNABORTED, /* ERR_ABRT -8 Connection aborted. */ - MP_ECONNRESET, /* ERR_RST -9 Connection reset. */ - MP_ENOTCONN, /* ERR_CLSD -10 Connection closed. */ - MP_ENOTCONN, /* ERR_CONN -11 Not connected. */ - MP_EIO, /* ERR_ARG -12 Illegal argument. */ - MP_EADDRINUSE, /* ERR_USE -13 Address in use. */ - -1, /* ERR_IF -14 Low-level netif error */ - MP_EALREADY, /* ERR_ISCONN -15 Already connected. */ - MP_EBADF, /* _ERR_BADF -16 Closed socket (null pcb) */ -}; -#elif LWIP_VERSION_MACRO < 0x02000000 -static const int error_lookup_table[] = { - 0, /* ERR_OK 0 No error, everything OK. */ - MP_ENOMEM, /* ERR_MEM -1 Out of memory error. */ - MP_ENOBUFS, /* ERR_BUF -2 Buffer error. */ - MP_EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ - MP_EHOSTUNREACH, /* ERR_RTE -4 Routing problem. */ - MP_EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ - MP_EINVAL, /* ERR_VAL -6 Illegal value. */ - MP_EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block. */ - - MP_EADDRINUSE, /* ERR_USE -8 Address in use. */ - MP_EALREADY, /* ERR_ISCONN -9 Already connected. */ - MP_ECONNABORTED, /* ERR_ABRT -10 Connection aborted. */ - MP_ECONNRESET, /* ERR_RST -11 Connection reset. */ - MP_ENOTCONN, /* ERR_CLSD -12 Connection closed. */ - MP_ENOTCONN, /* ERR_CONN -13 Not connected. */ - MP_EIO, /* ERR_ARG -14 Illegal argument. */ - -1, /* ERR_IF -15 Low-level netif error */ - MP_EBADF, /* _ERR_BADF -16 Closed socket (null pcb) */ -}; -#else -// Matches lwIP 2.0.3 -#undef _ERR_BADF -#define _ERR_BADF -17 -static const int error_lookup_table[] = { - 0, /* ERR_OK 0 No error, everything OK */ - MP_ENOMEM, /* ERR_MEM -1 Out of memory error */ - MP_ENOBUFS, /* ERR_BUF -2 Buffer error */ - MP_EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ - MP_EHOSTUNREACH, /* ERR_RTE -4 Routing problem */ - MP_EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ - MP_EINVAL, /* ERR_VAL -6 Illegal value */ - MP_EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block */ - MP_EADDRINUSE, /* ERR_USE -8 Address in use */ - MP_EALREADY, /* ERR_ALREADY -9 Already connecting */ - MP_EALREADY, /* ERR_ISCONN -10 Conn already established */ - MP_ENOTCONN, /* ERR_CONN -11 Not connected */ - -1, /* ERR_IF -12 Low-level netif error */ - MP_ECONNABORTED, /* ERR_ABRT -13 Connection aborted */ - MP_ECONNRESET, /* ERR_RST -14 Connection reset */ - MP_ENOTCONN, /* ERR_CLSD -15 Connection closed */ - MP_EIO, /* ERR_ARG -16 Illegal argument. */ - MP_EBADF, /* _ERR_BADF -17 Closed socket (null pcb) */ -}; -#endif - -/*******************************************************************************/ -// The socket object provided by lwip.socket. - -#define MOD_NETWORK_AF_INET (2) -#define MOD_NETWORK_AF_INET6 (10) - -#define MOD_NETWORK_SOCK_STREAM (1) -#define MOD_NETWORK_SOCK_DGRAM (2) -#define MOD_NETWORK_SOCK_RAW (3) - -typedef struct _lwip_socket_obj_t { - mp_obj_base_t base; - - volatile union { - struct tcp_pcb *tcp; - struct udp_pcb *udp; - } pcb; - volatile union { - struct pbuf *pbuf; - struct tcp_pcb *connection; - } incoming; - mp_obj_t callback; - byte peer[4]; - mp_uint_t peer_port; - mp_uint_t timeout; - uint16_t recv_offset; - - uint8_t domain; - uint8_t type; - - #define STATE_NEW 0 - #define STATE_CONNECTING 1 - #define STATE_CONNECTED 2 - #define STATE_PEER_CLOSED 3 - // Negative value is lwIP error - int8_t state; -} lwip_socket_obj_t; - -static inline void poll_sockets(void) { - #ifdef MICROPY_EVENT_POLL_HOOK - MICROPY_EVENT_POLL_HOOK; - #else - mp_hal_delay_ms(1); - #endif -} - -/*******************************************************************************/ -// Callback functions for the lwIP raw API. - -static inline void exec_user_callback(lwip_socket_obj_t *socket) { - if (socket->callback != MP_OBJ_NULL) { - mp_call_function_1_protected(socket->callback, socket); - } -} - -// Callback for incoming UDP packets. We simply stash the packet and the source address, -// in case we need it for recvfrom. -#if LWIP_VERSION_MAJOR < 2 -STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, ip_addr_t *addr, u16_t port) -#else -STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) -#endif -{ - lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; - - if (socket->incoming.pbuf != NULL) { - // That's why they call it "unreliable". No room in the inn, drop the packet. - pbuf_free(p); - } else { - socket->incoming.pbuf = p; - socket->peer_port = (mp_uint_t)port; - memcpy(&socket->peer, addr, sizeof(socket->peer)); - } -} - -// Callback for general tcp errors. -STATIC void _lwip_tcp_error(void *arg, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; - - // Pass the error code back via the connection variable. - socket->state = err; - // If we got here, the lwIP stack either has deallocated or will deallocate the pcb. - socket->pcb.tcp = NULL; -} - -// Callback for tcp connection requests. Error code err is unused. (See tcp.h) -STATIC err_t _lwip_tcp_connected(void *arg, struct tcp_pcb *tpcb, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; - - socket->state = STATE_CONNECTED; - return ERR_OK; -} - -// By default, a child socket of listen socket is created with recv -// handler which discards incoming pbuf's. We don't want to do that, -// so set this handler which requests lwIP to keep pbuf's and deliver -// them later. We cannot cache pbufs in child socket on Python side, -// until it is created in accept(). -STATIC err_t _lwip_tcp_recv_unaccepted(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) { - return ERR_BUF; -} - -// "Poll" (idle) callback to be called ASAP after accept callback -// to execute Python callback function, as it can't be executed -// from accept callback itself. -STATIC err_t _lwip_tcp_accept_finished(void *arg, struct tcp_pcb *pcb) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; - tcp_poll(pcb, NULL, 0); - exec_user_callback(socket); - return ERR_OK; -} - -// Callback for incoming tcp connections. -STATIC err_t _lwip_tcp_accept(void *arg, struct tcp_pcb *newpcb, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; - tcp_recv(newpcb, _lwip_tcp_recv_unaccepted); - - if (socket->incoming.connection != NULL) { - DEBUG_printf("_lwip_tcp_accept: Tried to queue >1 pcb waiting for accept\n"); - // We need to handle this better. This single-level structure makes the - // backlog setting kind of pointless. FIXME - return ERR_BUF; - } else { - socket->incoming.connection = newpcb; - if (socket->callback != MP_OBJ_NULL) { - // Schedule accept callback to be called when lwIP is done - // with processing this incoming connection on its side and - // is idle. - tcp_poll(newpcb, _lwip_tcp_accept_finished, 1); - } - return ERR_OK; - } -} - -// Callback for inbound tcp packets. -STATIC err_t _lwip_tcp_recv(void *arg, struct tcp_pcb *tcpb, struct pbuf *p, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; - - if (p == NULL) { - // Other side has closed connection. - DEBUG_printf("_lwip_tcp_recv[%p]: other side closed connection\n", socket); - socket->state = STATE_PEER_CLOSED; - exec_user_callback(socket); - return ERR_OK; - } - - if (socket->incoming.pbuf == NULL) { - socket->incoming.pbuf = p; - } else { - #ifdef SOCKET_SINGLE_PBUF - return ERR_BUF; - #else - pbuf_cat(socket->incoming.pbuf, p); - #endif - } - - exec_user_callback(socket); - - return ERR_OK; -} - -/*******************************************************************************/ -// Functions for socket send/receive operations. Socket send/recv and friends call -// these to do the work. - -// Helper function for send/sendto to handle UDP packets. -STATIC mp_uint_t lwip_udp_send(lwip_socket_obj_t *socket, const byte *buf, mp_uint_t len, byte *ip, mp_uint_t port, int *_errno) { - if (len > 0xffff) { - // Any packet that big is probably going to fail the pbuf_alloc anyway, but may as well try - len = 0xffff; - } - - // FIXME: maybe PBUF_ROM? - struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM); - if (p == NULL) { - *_errno = MP_ENOMEM; - return -1; - } - - memcpy(p->payload, buf, len); - - err_t err; - if (ip == NULL) { - err = udp_send(socket->pcb.udp, p); - } else { - ip_addr_t dest; - IP4_ADDR(&dest, ip[0], ip[1], ip[2], ip[3]); - err = udp_sendto(socket->pcb.udp, p, &dest, port); - } - - pbuf_free(p); - - // udp_sendto can return 1 on occasion for ESP8266 port. It's not known why - // but it seems that the send actually goes through without error in this case. - // So we treat such cases as a success until further investigation. - if (err != ERR_OK && err != 1) { - *_errno = error_lookup_table[-err]; - return -1; - } - - return len; -} - -// Helper function for recv/recvfrom to handle UDP packets -STATIC mp_uint_t lwip_udp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_t len, byte *ip, mp_uint_t *port, int *_errno) { - - if (socket->incoming.pbuf == NULL) { - if (socket->timeout != -1) { - for (mp_uint_t retries = socket->timeout / 100; retries--;) { - mp_hal_delay_ms(100); - if (socket->incoming.pbuf != NULL) { - break; - } - } - if (socket->incoming.pbuf == NULL) { - *_errno = MP_ETIMEDOUT; - return -1; - } - } else { - while (socket->incoming.pbuf == NULL) { - poll_sockets(); - } - } - } - - if (ip != NULL) { - memcpy(ip, &socket->peer, sizeof(socket->peer)); - *port = socket->peer_port; - } - - struct pbuf *p = socket->incoming.pbuf; - - u16_t result = pbuf_copy_partial(p, buf, ((p->tot_len > len) ? len : p->tot_len), 0); - pbuf_free(p); - socket->incoming.pbuf = NULL; - - return (mp_uint_t)result; -} - -// For use in stream virtual methods -#define STREAM_ERROR_CHECK(socket) \ - if (socket->state < 0) { \ - *_errno = error_lookup_table[-socket->state]; \ - return MP_STREAM_ERROR; \ - } \ - assert(socket->pcb.tcp); - - -// Helper function for send/sendto to handle TCP packets -STATIC mp_uint_t lwip_tcp_send(lwip_socket_obj_t *socket, const byte *buf, mp_uint_t len, int *_errno) { - // Check for any pending errors - STREAM_ERROR_CHECK(socket); - - u16_t available = tcp_sndbuf(socket->pcb.tcp); - - if (available == 0) { - // Non-blocking socket - if (socket->timeout == 0) { - *_errno = MP_EAGAIN; - return MP_STREAM_ERROR; - } - - mp_uint_t start = mp_hal_ticks_ms(); - // Assume that STATE_PEER_CLOSED may mean half-closed connection, where peer closed it - // sending direction, but not receiving. Consequently, check for both STATE_CONNECTED - // and STATE_PEER_CLOSED as normal conditions and still waiting for buffers to be sent. - // If peer fully closed socket, we would have socket->state set to ERR_RST (connection - // reset) by error callback. - // Avoid sending too small packets, so wait until at least 16 bytes available - while (socket->state >= STATE_CONNECTED && (available = tcp_sndbuf(socket->pcb.tcp)) < 16) { - if (socket->timeout != -1 && mp_hal_ticks_ms() - start > socket->timeout) { - *_errno = MP_ETIMEDOUT; - return MP_STREAM_ERROR; - } - poll_sockets(); - } - - // While we waited, something could happen - STREAM_ERROR_CHECK(socket); - } - - u16_t write_len = MIN(available, len); - - err_t err = tcp_write(socket->pcb.tcp, buf, write_len, TCP_WRITE_FLAG_COPY); - - // If the output buffer is getting full then send the data to the lower layers - if (err == ERR_OK && tcp_sndbuf(socket->pcb.tcp) < TCP_SND_BUF / 4) { - err = tcp_output(socket->pcb.tcp); - } - - if (err != ERR_OK) { - *_errno = error_lookup_table[-err]; - return MP_STREAM_ERROR; - } - - return write_len; -} - -// Helper function for recv/recvfrom to handle TCP packets -STATIC mp_uint_t lwip_tcp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_t len, int *_errno) { - // Check for any pending errors - STREAM_ERROR_CHECK(socket); - - if (socket->incoming.pbuf == NULL) { - - // Non-blocking socket - if (socket->timeout == 0) { - if (socket->state == STATE_PEER_CLOSED) { - return 0; - } - *_errno = MP_EAGAIN; - return -1; - } - - mp_uint_t start = mp_hal_ticks_ms(); - while (socket->state == STATE_CONNECTED && socket->incoming.pbuf == NULL) { - if (socket->timeout != -1 && mp_hal_ticks_ms() - start > socket->timeout) { - *_errno = MP_ETIMEDOUT; - return -1; - } - poll_sockets(); - } - - if (socket->state == STATE_PEER_CLOSED) { - if (socket->incoming.pbuf == NULL) { - // socket closed and no data left in buffer - return 0; - } - } else if (socket->state != STATE_CONNECTED) { - assert(socket->state < 0); - *_errno = error_lookup_table[-socket->state]; - return -1; - } - } - - assert(socket->pcb.tcp != NULL); - - struct pbuf *p = socket->incoming.pbuf; - - mp_uint_t remaining = p->len - socket->recv_offset; - if (len > remaining) { - len = remaining; - } - - memcpy(buf, (byte *)p->payload + socket->recv_offset, len); - - remaining -= len; - if (remaining == 0) { - socket->incoming.pbuf = p->next; - // If we don't ref here, free() will free the entire chain, - // if we ref, it does what we need: frees 1st buf, and decrements - // next buf's refcount back to 1. - pbuf_ref(p->next); - pbuf_free(p); - socket->recv_offset = 0; - } else { - socket->recv_offset += len; - } - tcp_recved(socket->pcb.tcp, len); - - return len; -} - -/*******************************************************************************/ -// The socket functions provided by lwip.socket. - -STATIC const mp_obj_type_t lwip_socket_type; - -STATIC void lwip_socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - lwip_socket_obj_t *self = self_in; - mp_printf(print, "", self->state, self->timeout, - self->incoming.pbuf, self->recv_offset); -} - -// FIXME: Only supports two arguments at present -STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { - mp_arg_check_num(n_args, n_kw, 0, 4, false); - - lwip_socket_obj_t *socket = m_new_obj_with_finaliser(lwip_socket_obj_t); - socket->base.type = (mp_obj_t)&lwip_socket_type; - socket->domain = MOD_NETWORK_AF_INET; - socket->type = MOD_NETWORK_SOCK_STREAM; - socket->callback = MP_OBJ_NULL; - if (n_args >= 1) { - socket->domain = mp_obj_get_int(args[0]); - if (n_args >= 2) { - socket->type = mp_obj_get_int(args[1]); - } - } - - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: - socket->pcb.tcp = tcp_new(); - break; - case MOD_NETWORK_SOCK_DGRAM: - socket->pcb.udp = udp_new(); - break; - // case MOD_NETWORK_SOCK_RAW: socket->pcb.raw = raw_new(); break; - default: - mp_raise_OSError(MP_EINVAL); - } - - if (socket->pcb.tcp == NULL) { - mp_raise_OSError(MP_ENOMEM); - } - - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - // Register the socket object as our callback argument. - tcp_arg(socket->pcb.tcp, (void *)socket); - // Register our error callback. - tcp_err(socket->pcb.tcp, _lwip_tcp_error); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - // Register our receive callback now. Since UDP sockets don't require binding or connection - // before use, there's no other good time to do it. - udp_recv(socket->pcb.udp, _lwip_udp_incoming, (void *)socket); - break; - } - } - - socket->incoming.pbuf = NULL; - socket->timeout = -1; - socket->state = STATE_NEW; - socket->recv_offset = 0; - return socket; -} - -STATIC mp_obj_t lwip_socket_bind(mp_obj_t self_in, mp_obj_t addr_in) { - lwip_socket_obj_t *socket = self_in; - - uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; - mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG); - - ip_addr_t bind_addr; - IP4_ADDR(&bind_addr, ip[0], ip[1], ip[2], ip[3]); - - err_t err = ERR_ARG; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - err = tcp_bind(socket->pcb.tcp, &bind_addr, port); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - err = udp_bind(socket->pcb.udp, &bind_addr, port); - break; - } - } - - if (err != ERR_OK) { - mp_raise_OSError(error_lookup_table[-err]); - } - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_bind_obj, lwip_socket_bind); - -STATIC mp_obj_t lwip_socket_listen(mp_obj_t self_in, mp_obj_t backlog_in) { - lwip_socket_obj_t *socket = self_in; - mp_int_t backlog = mp_obj_get_int(backlog_in); - - if (socket->pcb.tcp == NULL) { - mp_raise_OSError(MP_EBADF); - } - if (socket->type != MOD_NETWORK_SOCK_STREAM) { - mp_raise_OSError(MP_EOPNOTSUPP); - } - - struct tcp_pcb *new_pcb = tcp_listen_with_backlog(socket->pcb.tcp, (u8_t)backlog); - if (new_pcb == NULL) { - mp_raise_OSError(MP_ENOMEM); - } - socket->pcb.tcp = new_pcb; - tcp_accept(new_pcb, _lwip_tcp_accept); - - // Socket is no longer considered "new" for purposes of polling - socket->state = STATE_CONNECTING; - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_listen_obj, lwip_socket_listen); - -STATIC mp_obj_t lwip_socket_accept(mp_obj_t self_in) { - lwip_socket_obj_t *socket = self_in; - - if (socket->pcb.tcp == NULL) { - mp_raise_OSError(MP_EBADF); - } - if (socket->type != MOD_NETWORK_SOCK_STREAM) { - mp_raise_OSError(MP_EOPNOTSUPP); - } - // I need to do this because "tcp_accepted", later, is a macro. - struct tcp_pcb *listener = socket->pcb.tcp; - if (listener->state != LISTEN) { - mp_raise_OSError(MP_EINVAL); - } - - // accept incoming connection - if (socket->incoming.connection == NULL) { - if (socket->timeout == 0) { - mp_raise_OSError(MP_EAGAIN); - } else if (socket->timeout != -1) { - for (mp_uint_t retries = socket->timeout / 100; retries--;) { - mp_hal_delay_ms(100); - if (socket->incoming.connection != NULL) { - break; - } - } - if (socket->incoming.connection == NULL) { - mp_raise_OSError(MP_ETIMEDOUT); - } - } else { - while (socket->incoming.connection == NULL) { - poll_sockets(); - } - } - } - - // create new socket object - lwip_socket_obj_t *socket2 = m_new_obj_with_finaliser(lwip_socket_obj_t); - socket2->base.type = (mp_obj_t)&lwip_socket_type; - - // We get a new pcb handle... - socket2->pcb.tcp = socket->incoming.connection; - socket->incoming.connection = NULL; - - // ...and set up the new socket for it. - socket2->domain = MOD_NETWORK_AF_INET; - socket2->type = MOD_NETWORK_SOCK_STREAM; - socket2->incoming.pbuf = NULL; - socket2->timeout = socket->timeout; - socket2->state = STATE_CONNECTED; - socket2->recv_offset = 0; - socket2->callback = MP_OBJ_NULL; - tcp_arg(socket2->pcb.tcp, (void *)socket2); - tcp_err(socket2->pcb.tcp, _lwip_tcp_error); - tcp_recv(socket2->pcb.tcp, _lwip_tcp_recv); - - tcp_accepted(listener); - - // make the return value - uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; - memcpy(ip, &(socket2->pcb.tcp->remote_ip), sizeof(ip)); - mp_uint_t port = (mp_uint_t)socket2->pcb.tcp->remote_port; - mp_obj_tuple_t *client = mp_obj_new_tuple(2, NULL); - client->items[0] = socket2; - client->items[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); - - return client; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(lwip_socket_accept_obj, lwip_socket_accept); - -STATIC mp_obj_t lwip_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { - lwip_socket_obj_t *socket = self_in; - - if (socket->pcb.tcp == NULL) { - mp_raise_OSError(MP_EBADF); - } - - // get address - uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; - mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG); - - ip_addr_t dest; - IP4_ADDR(&dest, ip[0], ip[1], ip[2], ip[3]); - - err_t err = ERR_ARG; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - if (socket->state != STATE_NEW) { - if (socket->state == STATE_CONNECTED) { - mp_raise_OSError(MP_EISCONN); - } else { - mp_raise_OSError(MP_EALREADY); - } - } - // Register our receive callback. - tcp_recv(socket->pcb.tcp, _lwip_tcp_recv); - socket->state = STATE_CONNECTING; - err = tcp_connect(socket->pcb.tcp, &dest, port, _lwip_tcp_connected); - if (err != ERR_OK) { - socket->state = STATE_NEW; - mp_raise_OSError(error_lookup_table[-err]); - } - socket->peer_port = (mp_uint_t)port; - memcpy(socket->peer, &dest, sizeof(socket->peer)); - // And now we wait... - if (socket->timeout != -1) { - for (mp_uint_t retries = socket->timeout / 100; retries--;) { - mp_hal_delay_ms(100); - if (socket->state != STATE_CONNECTING) { - break; - } - } - if (socket->state == STATE_CONNECTING) { - mp_raise_OSError(MP_EINPROGRESS); - } - } else { - while (socket->state == STATE_CONNECTING) { - poll_sockets(); - } - } - if (socket->state == STATE_CONNECTED) { - err = ERR_OK; - } else { - err = socket->state; - } - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - err = udp_connect(socket->pcb.udp, &dest, port); - break; - } - } - - if (err != ERR_OK) { - mp_raise_OSError(error_lookup_table[-err]); - } - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_connect_obj, lwip_socket_connect); - -STATIC void lwip_socket_check_connected(lwip_socket_obj_t *socket) { - if (socket->pcb.tcp == NULL) { - // not connected - int _errno = error_lookup_table[-socket->state]; - socket->state = _ERR_BADF; - mp_raise_OSError(_errno); - } -} - -STATIC mp_obj_t lwip_socket_send(mp_obj_t self_in, mp_obj_t buf_in) { - lwip_socket_obj_t *socket = self_in; - int _errno; - - lwip_socket_check_connected(socket); - - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - ret = lwip_tcp_send(socket, bufinfo.buf, bufinfo.len, &_errno); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_send(socket, bufinfo.buf, bufinfo.len, NULL, 0, &_errno); - break; - } - } - if (ret == -1) { - mp_raise_OSError(_errno); - } - - return mp_obj_new_int_from_uint(ret); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_send_obj, lwip_socket_send); - -STATIC mp_obj_t lwip_socket_recv(mp_obj_t self_in, mp_obj_t len_in) { - lwip_socket_obj_t *socket = self_in; - int _errno; - - lwip_socket_check_connected(socket); - - mp_int_t len = mp_obj_get_int(len_in); - vstr_t vstr; - vstr_init_len(&vstr, len); - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_receive(socket, (byte *)vstr.buf, len, NULL, NULL, &_errno); - break; - } - } - if (ret == -1) { - mp_raise_OSError(_errno); - } - - if (ret == 0) { - return mp_const_empty_bytes; - } - vstr.len = ret; - return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_recv_obj, lwip_socket_recv); - -STATIC mp_obj_t lwip_socket_sendto(mp_obj_t self_in, mp_obj_t data_in, mp_obj_t addr_in) { - lwip_socket_obj_t *socket = self_in; - int _errno; - - lwip_socket_check_connected(socket); - - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(data_in, &bufinfo, MP_BUFFER_READ); - - uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; - mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG); - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - ret = lwip_tcp_send(socket, bufinfo.buf, bufinfo.len, &_errno); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_send(socket, bufinfo.buf, bufinfo.len, ip, port, &_errno); - break; - } - } - if (ret == -1) { - mp_raise_OSError(_errno); - } - - return mp_obj_new_int_from_uint(ret); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_3(lwip_socket_sendto_obj, lwip_socket_sendto); - -STATIC mp_obj_t lwip_socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in) { - lwip_socket_obj_t *socket = self_in; - int _errno; - - lwip_socket_check_connected(socket); - - mp_int_t len = mp_obj_get_int(len_in); - vstr_t vstr; - vstr_init_len(&vstr, len); - byte ip[4]; - mp_uint_t port; - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - memcpy(ip, &socket->peer, sizeof(socket->peer)); - port = (mp_uint_t)socket->peer_port; - ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_receive(socket, (byte *)vstr.buf, len, ip, &port, &_errno); - break; - } - } - if (ret == -1) { - mp_raise_OSError(_errno); - } - - mp_obj_t tuple[2]; - if (ret == 0) { - tuple[0] = mp_const_empty_bytes; - } else { - vstr.len = ret; - tuple[0] = mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); - } - tuple[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); - return mp_obj_new_tuple(2, tuple); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_recvfrom_obj, lwip_socket_recvfrom); - -STATIC mp_obj_t lwip_socket_sendall(mp_obj_t self_in, mp_obj_t buf_in) { - lwip_socket_obj_t *socket = self_in; - lwip_socket_check_connected(socket); - - int _errno; - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - if (socket->timeout == 0) { - // Behavior of sendall() for non-blocking sockets isn't explicitly specified. - // But it's specified that "On error, an exception is raised, there is no - // way to determine how much data, if any, was successfully sent." Then, the - // most useful behavior is: check whether we will be able to send all of input - // data without EAGAIN, and if won't be, raise it without sending any. - if (bufinfo.len > tcp_sndbuf(socket->pcb.tcp)) { - mp_raise_OSError(MP_EAGAIN); - } - } - // TODO: In CPython3.5, socket timeout should apply to the - // entire sendall() operation, not to individual send() chunks. - while (bufinfo.len != 0) { - ret = lwip_tcp_send(socket, bufinfo.buf, bufinfo.len, &_errno); - if (ret == -1) { - mp_raise_OSError(_errno); - } - bufinfo.len -= ret; - bufinfo.buf = (char *)bufinfo.buf + ret; - } - break; - } - case MOD_NETWORK_SOCK_DGRAM: - mp_raise_NotImplementedError(NULL); - break; - } - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_sendall_obj, lwip_socket_sendall); - -STATIC mp_obj_t lwip_socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) { - lwip_socket_obj_t *socket = self_in; - mp_uint_t timeout; - if (timeout_in == mp_const_none) { - timeout = -1; - } else { - #if MICROPY_PY_BUILTINS_FLOAT - timeout = 1000 * mp_obj_get_float(timeout_in); - #else - timeout = 1000 * mp_obj_get_int(timeout_in); - #endif - } - socket->timeout = timeout; - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_settimeout_obj, lwip_socket_settimeout); - -STATIC mp_obj_t lwip_socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { - lwip_socket_obj_t *socket = self_in; - bool val = mp_obj_is_true(flag_in); - if (val) { - socket->timeout = -1; - } else { - socket->timeout = 0; - } - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_setblocking_obj, lwip_socket_setblocking); - -STATIC mp_obj_t lwip_socket_setsockopt(size_t n_args, const mp_obj_t *args) { - (void)n_args; // always 4 - lwip_socket_obj_t *socket = args[0]; - - int opt = mp_obj_get_int(args[2]); - if (opt == 20) { - if (args[3] == mp_const_none) { - socket->callback = MP_OBJ_NULL; - } else { - socket->callback = args[3]; - } - return mp_const_none; - } - - switch (opt) { - // level: SOL_SOCKET - case SOF_REUSEADDR: { - mp_int_t val = mp_obj_get_int(args[3]); - // Options are common for UDP and TCP pcb's. - if (val) { - ip_set_option(socket->pcb.tcp, SOF_REUSEADDR); - } else { - ip_reset_option(socket->pcb.tcp, SOF_REUSEADDR); - } - break; - } - - // level: IPPROTO_IP - case IP_ADD_MEMBERSHIP: { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ); - if (bufinfo.len != sizeof(ip_addr_t) * 2) { - mp_raise_ValueError(NULL); - } - - // POSIX setsockopt has order: group addr, if addr, lwIP has it vice-versa - err_t err = igmp_joingroup((ip_addr_t *)bufinfo.buf + 1, bufinfo.buf); - if (err != ERR_OK) { - mp_raise_OSError(error_lookup_table[-err]); - } - break; - } - - default: - printf("Warning: lwip.setsockopt() not implemented\n"); - } - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_socket_setsockopt_obj, 4, 4, lwip_socket_setsockopt); - -STATIC mp_obj_t lwip_socket_makefile(size_t n_args, const mp_obj_t *args) { - (void)n_args; - return args[0]; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_socket_makefile_obj, 1, 3, lwip_socket_makefile); - -STATIC mp_uint_t lwip_socket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { - lwip_socket_obj_t *socket = self_in; - - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: - return lwip_tcp_receive(socket, buf, size, errcode); - case MOD_NETWORK_SOCK_DGRAM: - return lwip_udp_receive(socket, buf, size, NULL, NULL, errcode); - } - // Unreachable - return MP_STREAM_ERROR; -} - -STATIC mp_uint_t lwip_socket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { - lwip_socket_obj_t *socket = self_in; - - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: - return lwip_tcp_send(socket, buf, size, errcode); - case MOD_NETWORK_SOCK_DGRAM: - return lwip_udp_send(socket, buf, size, NULL, 0, errcode); - } - // Unreachable - return MP_STREAM_ERROR; -} - -STATIC mp_uint_t lwip_socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { - lwip_socket_obj_t *socket = self_in; - mp_uint_t ret; - - if (request == MP_STREAM_POLL) { - uintptr_t flags = arg; - ret = 0; - - if (flags & MP_STREAM_POLL_RD && socket->incoming.pbuf != NULL) { - ret |= MP_STREAM_POLL_RD; - } - - // Note: pcb.tcp==NULL if state<0, and in this case we can't call tcp_sndbuf - if (flags & MP_STREAM_POLL_WR && socket->pcb.tcp != NULL && tcp_sndbuf(socket->pcb.tcp) > 0) { - ret |= MP_STREAM_POLL_WR; - } - - if (socket->state == STATE_NEW) { - // New sockets are not connected so set HUP - ret |= flags & MP_STREAM_POLL_HUP; - } else if (socket->state == STATE_PEER_CLOSED) { - // Peer-closed socket is both readable and writable: read will - // return EOF, write - error. Without this poll will hang on a - // socket which was closed by peer. - ret |= flags & (MP_STREAM_POLL_RD | MP_STREAM_POLL_WR); - } else if (socket->state == ERR_RST) { - // Socket was reset by peer, a write will return an error - ret |= flags & (MP_STREAM_POLL_WR | MP_STREAM_POLL_HUP); - } else if (socket->state < 0) { - // Socket in some other error state, use catch-all ERR flag - // TODO: may need to set other return flags here - ret |= flags & MP_STREAM_POLL_ERR; - } - - } else if (request == MP_STREAM_CLOSE) { - bool socket_is_listener = false; - - if (socket->pcb.tcp == NULL) { - return 0; - } - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - if (socket->pcb.tcp->state == LISTEN) { - socket_is_listener = true; - } - if (tcp_close(socket->pcb.tcp) != ERR_OK) { - DEBUG_printf("lwip_close: had to call tcp_abort()\n"); - tcp_abort(socket->pcb.tcp); - } - break; - } - case MOD_NETWORK_SOCK_DGRAM: - udp_remove(socket->pcb.udp); - break; - // case MOD_NETWORK_SOCK_RAW: raw_remove(socket->pcb.raw); break; - } - socket->pcb.tcp = NULL; - socket->state = _ERR_BADF; - if (socket->incoming.pbuf != NULL) { - if (!socket_is_listener) { - pbuf_free(socket->incoming.pbuf); - } else { - tcp_abort(socket->incoming.connection); - } - socket->incoming.pbuf = NULL; - } - ret = 0; - - } else { - *errcode = MP_EINVAL; - ret = MP_STREAM_ERROR; - } - - return ret; -} - -STATIC const mp_rom_map_elem_t lwip_socket_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) }, - { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, - { MP_ROM_QSTR(MP_QSTR_bind), MP_ROM_PTR(&lwip_socket_bind_obj) }, - { MP_ROM_QSTR(MP_QSTR_listen), MP_ROM_PTR(&lwip_socket_listen_obj) }, - { MP_ROM_QSTR(MP_QSTR_accept), MP_ROM_PTR(&lwip_socket_accept_obj) }, - { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&lwip_socket_connect_obj) }, - { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&lwip_socket_send_obj) }, - { MP_ROM_QSTR(MP_QSTR_recv), MP_ROM_PTR(&lwip_socket_recv_obj) }, - { MP_ROM_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&lwip_socket_sendto_obj) }, - { MP_ROM_QSTR(MP_QSTR_recvfrom), MP_ROM_PTR(&lwip_socket_recvfrom_obj) }, - { MP_ROM_QSTR(MP_QSTR_sendall), MP_ROM_PTR(&lwip_socket_sendall_obj) }, - { MP_ROM_QSTR(MP_QSTR_settimeout), MP_ROM_PTR(&lwip_socket_settimeout_obj) }, - { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&lwip_socket_setblocking_obj) }, - { MP_ROM_QSTR(MP_QSTR_setsockopt), MP_ROM_PTR(&lwip_socket_setsockopt_obj) }, - { MP_ROM_QSTR(MP_QSTR_makefile), MP_ROM_PTR(&lwip_socket_makefile_obj) }, - - { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, - { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, - { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, - { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, -}; -STATIC MP_DEFINE_CONST_DICT(lwip_socket_locals_dict, lwip_socket_locals_dict_table); - -STATIC const mp_stream_p_t lwip_socket_stream_p = { - MP_PROTO_IMPLEMENT(MP_QSTR_protocol_stream) - .read = lwip_socket_read, - .write = lwip_socket_write, - .ioctl = lwip_socket_ioctl, -}; - -STATIC const mp_obj_type_t lwip_socket_type = { - { &mp_type_type }, - .name = MP_QSTR_socket, - .print = lwip_socket_print, - .make_new = lwip_socket_make_new, - .protocol = &lwip_socket_stream_p, - .locals_dict = (mp_obj_dict_t *)&lwip_socket_locals_dict, -}; - -/******************************************************************************/ -// Support functions for memory protection. lwIP has its own memory management -// routines for its internal structures, and since they might be called in -// interrupt handlers, they need some protection. -sys_prot_t sys_arch_protect() { - return (sys_prot_t)MICROPY_BEGIN_ATOMIC_SECTION(); -} - -void sys_arch_unprotect(sys_prot_t state) { - MICROPY_END_ATOMIC_SECTION((mp_uint_t)state); -} - -/******************************************************************************/ -// Polling callbacks for the interfaces connected to lwIP. Right now it calls -// itself a "list" but isn't; we only support a single interface. - -typedef struct nic_poll { - void (*poll)(void *arg); - void *poll_arg; -} nic_poll_t; - -STATIC nic_poll_t lwip_poll_list; - -void mod_lwip_register_poll(void (*poll)(void *arg), void *poll_arg) { - lwip_poll_list.poll = poll; - lwip_poll_list.poll_arg = poll_arg; -} - -void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg) { - lwip_poll_list.poll = NULL; -} - -/******************************************************************************/ -// The lwip global functions. - -STATIC mp_obj_t mod_lwip_reset() { - lwip_init(); - lwip_poll_list.poll = NULL; - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_0(mod_lwip_reset_obj, mod_lwip_reset); - -STATIC mp_obj_t mod_lwip_callback() { - if (lwip_poll_list.poll != NULL) { - lwip_poll_list.poll(lwip_poll_list.poll_arg); - } - sys_check_timeouts(); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_0(mod_lwip_callback_obj, mod_lwip_callback); - -typedef struct _getaddrinfo_state_t { - volatile int status; - volatile ip_addr_t ipaddr; -} getaddrinfo_state_t; - -// Callback for incoming DNS requests. -#if LWIP_VERSION_MAJOR < 2 -STATIC void lwip_getaddrinfo_cb(const char *name, ip_addr_t *ipaddr, void *arg) -#else -STATIC void lwip_getaddrinfo_cb(const char *name, const ip_addr_t *ipaddr, void *arg) -#endif -{ - getaddrinfo_state_t *state = arg; - if (ipaddr != NULL) { - state->status = 1; - state->ipaddr = *ipaddr; - } else { - // error - state->status = -2; - } -} - -// lwip.getaddrinfo -STATIC mp_obj_t lwip_getaddrinfo(size_t n_args, const mp_obj_t *args) { - mp_obj_t host_in = args[0], port_in = args[1]; - const char *host = mp_obj_str_get_str(host_in); - mp_int_t port = mp_obj_get_int(port_in); - - // If constraints were passed then check they are compatible with the supported params - if (n_args > 2) { - mp_int_t family = mp_obj_get_int(args[2]); - mp_int_t type = 0; - mp_int_t proto = 0; - mp_int_t flags = 0; - if (n_args > 3) { - type = mp_obj_get_int(args[3]); - if (n_args > 4) { - proto = mp_obj_get_int(args[4]); - if (n_args > 5) { - flags = mp_obj_get_int(args[5]); - } - } - } - if (!((family == 0 || family == MOD_NETWORK_AF_INET) - && (type == 0 || type == MOD_NETWORK_SOCK_STREAM) - && proto == 0 - && flags == 0)) { - mp_warning("unsupported getaddrinfo constraints"); - } - } - - getaddrinfo_state_t state; - state.status = 0; - - err_t ret = dns_gethostbyname(host, (ip_addr_t *)&state.ipaddr, lwip_getaddrinfo_cb, &state); - switch (ret) { - case ERR_OK: - // cached - state.status = 1; - break; - case ERR_INPROGRESS: - while (state.status == 0) { - poll_sockets(); - } - break; - default: - state.status = ret; - } - - if (state.status < 0) { - // TODO: CPython raises gaierror, we raise with native lwIP negative error - // values, to differentiate from normal errno's at least in such way. - mp_raise_OSError(state.status); - } - - mp_obj_tuple_t *tuple = mp_obj_new_tuple(5, NULL); - tuple->items[0] = MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_AF_INET); - tuple->items[1] = MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_SOCK_STREAM); - tuple->items[2] = MP_OBJ_NEW_SMALL_INT(0); - tuple->items[3] = MP_OBJ_NEW_QSTR(MP_QSTR_); - tuple->items[4] = netutils_format_inet_addr((uint8_t *)&state.ipaddr, port, NETUTILS_BIG); - return mp_obj_new_list(1, (mp_obj_t *)&tuple); -} -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_getaddrinfo_obj, 2, 6, lwip_getaddrinfo); - -// Debug functions - -STATIC mp_obj_t lwip_print_pcbs() { - tcp_debug_print_pcbs(); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_0(lwip_print_pcbs_obj, lwip_print_pcbs); - -#if MICROPY_PY_LWIP - -STATIC const mp_rom_map_elem_t mp_module_lwip_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_lwip) }, - { MP_ROM_QSTR(MP_QSTR_reset), MP_ROM_PTR(&mod_lwip_reset_obj) }, - { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&mod_lwip_callback_obj) }, - { MP_ROM_QSTR(MP_QSTR_getaddrinfo), MP_ROM_PTR(&lwip_getaddrinfo_obj) }, - { MP_ROM_QSTR(MP_QSTR_print_pcbs), MP_ROM_PTR(&lwip_print_pcbs_obj) }, - // objects - { MP_ROM_QSTR(MP_QSTR_socket), MP_ROM_PTR(&lwip_socket_type) }, - #if MICROPY_PY_LWIP_SLIP - { MP_ROM_QSTR(MP_QSTR_slip), MP_ROM_PTR(&lwip_slip_type) }, - #endif - // class constants - { MP_ROM_QSTR(MP_QSTR_AF_INET), MP_ROM_INT(MOD_NETWORK_AF_INET) }, - { MP_ROM_QSTR(MP_QSTR_AF_INET6), MP_ROM_INT(MOD_NETWORK_AF_INET6) }, - - { MP_ROM_QSTR(MP_QSTR_SOCK_STREAM), MP_ROM_INT(MOD_NETWORK_SOCK_STREAM) }, - { MP_ROM_QSTR(MP_QSTR_SOCK_DGRAM), MP_ROM_INT(MOD_NETWORK_SOCK_DGRAM) }, - { MP_ROM_QSTR(MP_QSTR_SOCK_RAW), MP_ROM_INT(MOD_NETWORK_SOCK_RAW) }, - - { MP_ROM_QSTR(MP_QSTR_SOL_SOCKET), MP_ROM_INT(1) }, - { MP_ROM_QSTR(MP_QSTR_SO_REUSEADDR), MP_ROM_INT(SOF_REUSEADDR) }, - - { MP_ROM_QSTR(MP_QSTR_IPPROTO_IP), MP_ROM_INT(0) }, - { MP_ROM_QSTR(MP_QSTR_IP_ADD_MEMBERSHIP), MP_ROM_INT(IP_ADD_MEMBERSHIP) }, -}; - -STATIC MP_DEFINE_CONST_DICT(mp_module_lwip_globals, mp_module_lwip_globals_table); - -const mp_obj_module_t mp_module_lwip = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t *)&mp_module_lwip_globals, -}; - -#endif // MICROPY_PY_LWIP diff --git a/extmod/modonewire.c b/extmod/modonewire.c index 8b4ef86b0c..edb7e23cea 100644 --- a/extmod/modonewire.c +++ b/extmod/modonewire.c @@ -13,8 +13,8 @@ // Low-level 1-Wire routines #define TIMING_RESET1 (480) -#define TIMING_RESET2 (40) -#define TIMING_RESET3 (420) +#define TIMING_RESET2 (70) +#define TIMING_RESET3 (410) #define TIMING_READ1 (5) #define TIMING_READ2 (5) #define TIMING_READ3 (40) diff --git a/extmod/moductypes.c b/extmod/moductypes.c index 8499d1c29a..d093d39787 100644 --- a/extmod/moductypes.c +++ b/extmod/moductypes.c @@ -1,4 +1,4 @@ -// Copyright (c) 2014 Paul Sokolovsky +// Copyright (c) 2014-2018 Paul Sokolovsky // SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) // // SPDX-License-Identifier: MIT @@ -73,7 +73,7 @@ enum { #define AGG_TYPE_BITS 2 enum { - STRUCT, PTR, ARRAY, BITFIELD, + STRUCT, PTR, ARRAY, }; // Here we need to set sign bit right @@ -118,7 +118,11 @@ STATIC void uctypes_struct_print(const mp_print_t *print, mp_obj_t self_in, mp_p (void)kind; mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); const char *typen = "unk"; - if (MP_OBJ_IS_TYPE(self->desc, &mp_type_dict)) { + if (MP_OBJ_IS_TYPE(self->desc, &mp_type_dict) + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + || MP_OBJ_IS_TYPE(self->desc, &mp_type_ordereddict) + #endif + ) { typen = "STRUCT"; } else if (MP_OBJ_IS_TYPE(self->desc, &mp_type_tuple)) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc); @@ -191,7 +195,11 @@ STATIC mp_uint_t uctypes_struct_agg_size(mp_obj_tuple_t *t, int layout_type, mp_ } STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_t *max_field_size) { - if (!MP_OBJ_IS_TYPE(desc_in, &mp_type_dict)) { + if (!MP_OBJ_IS_TYPE(desc_in, &mp_type_dict) + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + && !MP_OBJ_IS_TYPE(desc_in, &mp_type_ordereddict) + #endif + ) { if (MP_OBJ_IS_TYPE(desc_in, &mp_type_tuple)) { return uctypes_struct_agg_size((mp_obj_tuple_t *)MP_OBJ_TO_PTR(desc_in), layout_type, max_field_size); } else if (MP_OBJ_IS_SMALL_INT(desc_in)) { @@ -246,7 +254,8 @@ STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_ return total_size; } -STATIC mp_obj_t uctypes_struct_sizeof(mp_obj_t obj_in) { +STATIC mp_obj_t uctypes_struct_sizeof(size_t n_args, const mp_obj_t *args) { + mp_obj_t obj_in = args[0]; mp_uint_t max_field_size = 0; if (MP_OBJ_IS_TYPE(obj_in, &mp_type_bytearray)) { return mp_obj_len(obj_in); @@ -255,15 +264,22 @@ STATIC mp_obj_t uctypes_struct_sizeof(mp_obj_t obj_in) { // We can apply sizeof either to structure definition (a dict) // or to instantiated structure if (MP_OBJ_IS_TYPE(obj_in, &uctypes_struct_type)) { + if (n_args != 1) { + mp_raise_TypeError(NULL); + } // Extract structure definition mp_obj_uctypes_struct_t *obj = MP_OBJ_TO_PTR(obj_in); obj_in = obj->desc; layout_type = obj->flags; + } else { + if (n_args == 2) { + layout_type = mp_obj_get_int(args[1]); + } } mp_uint_t size = uctypes_struct_size(obj_in, layout_type, &max_field_size); return MP_OBJ_NEW_SMALL_INT(size); } -STATIC MP_DEFINE_CONST_FUN_OBJ_1(uctypes_struct_sizeof_obj, uctypes_struct_sizeof); +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(uctypes_struct_sizeof_obj, 1, 2, uctypes_struct_sizeof); static inline mp_obj_t get_unaligned(uint val_type, byte *p, int big_endian) { char struct_type = big_endian ? '>' : '<'; @@ -325,7 +341,7 @@ STATIC mp_obj_t get_aligned(uint val_type, void *p, mp_int_t index) { return mp_obj_new_int_from_ll(((int64_t *)p)[index]); #if MICROPY_PY_BUILTINS_FLOAT case FLOAT32: - return mp_obj_new_float((mp_float_t)((float *)p)[index]); + return mp_obj_new_float(((float *)p)[index]); case FLOAT64: return mp_obj_new_float(((double *)p)[index]); #endif @@ -384,8 +400,11 @@ STATIC void set_aligned(uint val_type, void *p, mp_int_t index, mp_obj_t val) { STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set_val) { mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); - // TODO: Support at least OrderedDict in addition - if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_dict)) { + if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_dict) + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + && !MP_OBJ_IS_TYPE(self->desc, &mp_type_ordereddict) + #endif + ) { mp_raise_TypeError(translate("struct: no fields")); } @@ -589,6 +608,26 @@ STATIC mp_obj_t uctypes_struct_subscr(mp_obj_t base_in, mp_obj_t index_in, mp_ob } } +STATIC mp_obj_t uctypes_struct_unary_op(mp_unary_op_t op, mp_obj_t self_in) { + mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); + switch (op) { + case MP_UNARY_OP_INT: + if (MP_OBJ_IS_TYPE(self->desc, &mp_type_tuple)) { + mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc); + mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]); + uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS); + if (agg_type == PTR) { + byte *p = *(void **)self->addr; + return mp_obj_new_int((mp_int_t)(uintptr_t)p); + } + } + /* fallthru */ + + default: + return MP_OBJ_NULL; // op not supported + } +} + STATIC mp_int_t uctypes_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { (void)flags; mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); @@ -637,6 +676,7 @@ STATIC const mp_obj_type_t uctypes_struct_type = { .make_new = uctypes_struct_make_new, .attr = uctypes_struct_attr, .subscr = uctypes_struct_subscr, + .unary_op = uctypes_struct_unary_op, .buffer_p = { .get_buffer = uctypes_get_buffer }, }; @@ -695,6 +735,30 @@ STATIC const mp_rom_map_elem_t mp_module_uctypes_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_FLOAT64), MP_ROM_INT(TYPE2SMALLINT(FLOAT64, 4)) }, #endif + #if MICROPY_PY_UCTYPES_NATIVE_C_TYPES + // C native type aliases. These depend on GCC-compatible predefined + // preprocessor macros. + #if __SIZEOF_SHORT__ == 2 + { MP_ROM_QSTR(MP_QSTR_SHORT), MP_ROM_INT(TYPE2SMALLINT(INT16, 4)) }, + { MP_ROM_QSTR(MP_QSTR_USHORT), MP_ROM_INT(TYPE2SMALLINT(UINT16, 4)) }, + #endif + #if __SIZEOF_INT__ == 4 + { MP_ROM_QSTR(MP_QSTR_INT), MP_ROM_INT(TYPE2SMALLINT(INT32, 4)) }, + { MP_ROM_QSTR(MP_QSTR_UINT), MP_ROM_INT(TYPE2SMALLINT(UINT32, 4)) }, + #endif + #if __SIZEOF_LONG__ == 4 + { MP_ROM_QSTR(MP_QSTR_LONG), MP_ROM_INT(TYPE2SMALLINT(INT32, 4)) }, + { MP_ROM_QSTR(MP_QSTR_ULONG), MP_ROM_INT(TYPE2SMALLINT(UINT32, 4)) }, + #elif __SIZEOF_LONG__ == 8 + { MP_ROM_QSTR(MP_QSTR_LONG), MP_ROM_INT(TYPE2SMALLINT(INT64, 4)) }, + { MP_ROM_QSTR(MP_QSTR_ULONG), MP_ROM_INT(TYPE2SMALLINT(UINT64, 4)) }, + #endif + #if __SIZEOF_LONG_LONG__ == 8 + { MP_ROM_QSTR(MP_QSTR_LONGLONG), MP_ROM_INT(TYPE2SMALLINT(INT64, 4)) }, + { MP_ROM_QSTR(MP_QSTR_ULONGLONG), MP_ROM_INT(TYPE2SMALLINT(UINT64, 4)) }, + #endif + #endif // MICROPY_PY_UCTYPES_NATIVE_C_TYPES + { MP_ROM_QSTR(MP_QSTR_PTR), MP_ROM_INT(TYPE2SMALLINT(PTR, AGG_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_ARRAY), MP_ROM_INT(TYPE2SMALLINT(ARRAY, AGG_TYPE_BITS)) }, }; diff --git a/extmod/moduhashlib.c b/extmod/moduhashlib.c index e867aeb9ec..7069cc4792 100644 --- a/extmod/moduhashlib.c +++ b/extmod/moduhashlib.c @@ -12,6 +12,10 @@ #if MICROPY_PY_UHASHLIB +#if MICROPY_SSL_MBEDTLS +#include "mbedtls/version.h" +#endif + #if MICROPY_PY_UHASHLIB_SHA256 #if MICROPY_SSL_MBEDTLS @@ -22,13 +26,14 @@ #endif -#if MICROPY_PY_UHASHLIB_SHA1 +#if MICROPY_PY_UHASHLIB_SHA1 || MICROPY_PY_UHASHLIB_MD5 #if MICROPY_SSL_AXTLS #include "lib/axtls/crypto/crypto.h" #endif #if MICROPY_SSL_MBEDTLS +#include "mbedtls/md5.h" #include "mbedtls/sha1.h" #endif @@ -45,12 +50,18 @@ STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg); #if MICROPY_SSL_MBEDTLS -STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { - mp_arg_check_num(n_args, kw_args, 0, 1, false); +#if MBEDTLS_VERSION_NUMBER < 0x02070000 +#define mbedtls_sha256_starts_ret mbedtls_sha256_starts +#define mbedtls_sha256_update_ret mbedtls_sha256_update +#define mbedtls_sha256_finish_ret mbedtls_sha256_finish +#endif + +STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha256_context)); o->base.type = type; mbedtls_sha256_init((mbedtls_sha256_context *)&o->state); - mbedtls_sha256_starts((mbedtls_sha256_context *)&o->state, 0); + mbedtls_sha256_starts_ret((mbedtls_sha256_context *)&o->state, 0); if (n_args == 1) { uhashlib_sha256_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -61,7 +72,7 @@ STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - mbedtls_sha256_update((mbedtls_sha256_context *)&self->state, bufinfo.buf, bufinfo.len); + mbedtls_sha256_update_ret((mbedtls_sha256_context *)&self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -69,7 +80,7 @@ STATIC mp_obj_t uhashlib_sha256_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, 32); - mbedtls_sha256_finish((mbedtls_sha256_context *)&self->state, (unsigned char *)vstr.buf); + mbedtls_sha256_finish_ret((mbedtls_sha256_context *)&self->state, (unsigned char *)vstr.buf); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } @@ -164,12 +175,19 @@ STATIC mp_obj_t uhashlib_sha1_digest(mp_obj_t self_in) { #endif #if MICROPY_SSL_MBEDTLS + +#if MBEDTLS_VERSION_NUMBER < 0x02070000 +#define mbedtls_sha1_starts_ret mbedtls_sha1_starts +#define mbedtls_sha1_update_ret mbedtls_sha1_update +#define mbedtls_sha1_finish_ret mbedtls_sha1_finish +#endif + STATIC mp_obj_t uhashlib_sha1_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha1_context)); o->base.type = type; mbedtls_sha1_init((mbedtls_sha1_context *)o->state); - mbedtls_sha1_starts((mbedtls_sha1_context *)o->state); + mbedtls_sha1_starts_ret((mbedtls_sha1_context *)o->state); if (n_args == 1) { uhashlib_sha1_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -180,7 +198,7 @@ STATIC mp_obj_t uhashlib_sha1_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - mbedtls_sha1_update((mbedtls_sha1_context *)self->state, bufinfo.buf, bufinfo.len); + mbedtls_sha1_update_ret((mbedtls_sha1_context *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -188,7 +206,7 @@ STATIC mp_obj_t uhashlib_sha1_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, 20); - mbedtls_sha1_finish((mbedtls_sha1_context *)self->state, (byte *)vstr.buf); + mbedtls_sha1_finish_ret((mbedtls_sha1_context *)self->state, (byte *)vstr.buf); mbedtls_sha1_free((mbedtls_sha1_context *)self->state); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } @@ -211,6 +229,93 @@ STATIC const mp_obj_type_t uhashlib_sha1_type = { }; #endif +#if MICROPY_PY_UHASHLIB_MD5 +STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg); + +#if MICROPY_SSL_AXTLS +STATIC mp_obj_t uhashlib_md5_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_arg_check_num(n_args, n_kw, 0, 1, false); + mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(MD5_CTX)); + o->base.type = type; + MD5_Init((MD5_CTX *)o->state); + if (n_args == 1) { + uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]); + } + return MP_OBJ_FROM_PTR(o); +} + +STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg) { + mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); + MD5_Update((MD5_CTX *)self->state, bufinfo.buf, bufinfo.len); + return mp_const_none; +} + +STATIC mp_obj_t uhashlib_md5_digest(mp_obj_t self_in) { + mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); + vstr_t vstr; + vstr_init_len(&vstr, MD5_SIZE); + MD5_Final((byte *)vstr.buf, (MD5_CTX *)self->state); + return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); +} +#endif // MICROPY_SSL_AXTLS + +#if MICROPY_SSL_MBEDTLS + +#if MBEDTLS_VERSION_NUMBER < 0x02070000 +#define mbedtls_md5_starts_ret mbedtls_md5_starts +#define mbedtls_md5_update_ret mbedtls_md5_update +#define mbedtls_md5_finish_ret mbedtls_md5_finish +#endif + +STATIC mp_obj_t uhashlib_md5_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_arg_check_num(n_args, n_kw, 0, 1, false); + mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_md5_context)); + o->base.type = type; + mbedtls_md5_init((mbedtls_md5_context *)o->state); + mbedtls_md5_starts_ret((mbedtls_md5_context *)o->state); + if (n_args == 1) { + uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]); + } + return MP_OBJ_FROM_PTR(o); +} + +STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg) { + mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); + mbedtls_md5_update_ret((mbedtls_md5_context *)self->state, bufinfo.buf, bufinfo.len); + return mp_const_none; +} + +STATIC mp_obj_t uhashlib_md5_digest(mp_obj_t self_in) { + mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); + vstr_t vstr; + vstr_init_len(&vstr, 16); + mbedtls_md5_finish_ret((mbedtls_md5_context *)self->state, (byte *)vstr.buf); + mbedtls_md5_free((mbedtls_md5_context *)self->state); + return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); +} +#endif // MICROPY_SSL_MBEDTLS + +STATIC MP_DEFINE_CONST_FUN_OBJ_2(uhashlib_md5_update_obj, uhashlib_md5_update); +STATIC MP_DEFINE_CONST_FUN_OBJ_1(uhashlib_md5_digest_obj, uhashlib_md5_digest); + +STATIC const mp_rom_map_elem_t uhashlib_md5_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&uhashlib_md5_update_obj) }, + { MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&uhashlib_md5_digest_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(uhashlib_md5_locals_dict, uhashlib_md5_locals_dict_table); + +STATIC const mp_obj_type_t uhashlib_md5_type = { + { &mp_type_type }, + .name = MP_QSTR_md5, + .make_new = uhashlib_md5_make_new, + .locals_dict = (void *)&uhashlib_md5_locals_dict, +}; +#endif // MICROPY_PY_UHASHLIB_MD5 + STATIC const mp_rom_map_elem_t mp_module_uhashlib_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_hashlib) }, #if MICROPY_PY_UHASHLIB_SHA256 @@ -219,6 +324,9 @@ STATIC const mp_rom_map_elem_t mp_module_uhashlib_globals_table[] = { #if MICROPY_PY_UHASHLIB_SHA1 { MP_ROM_QSTR(MP_QSTR_sha1), MP_ROM_PTR(&uhashlib_sha1_type) }, #endif + #if MICROPY_PY_UHASHLIB_MD5 + { MP_ROM_QSTR(MP_QSTR_md5), MP_ROM_PTR(&uhashlib_md5_type) }, + #endif }; STATIC MP_DEFINE_CONST_DICT(mp_module_uhashlib_globals, mp_module_uhashlib_globals_table); diff --git a/extmod/moduselect.c b/extmod/moduselect.c index bcdb45bd6d..e88494b279 100644 --- a/extmod/moduselect.c +++ b/extmod/moduselect.c @@ -25,7 +25,7 @@ typedef struct _poll_obj_t { mp_obj_t obj; - mp_uint_t (*ioctl)(mp_obj_t obj, mp_uint_t request, mp_uint_t arg, int *errcode); + mp_uint_t (*ioctl)(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode); mp_uint_t flags; mp_uint_t flags_ret; } poll_obj_t; @@ -33,7 +33,7 @@ typedef struct _poll_obj_t { STATIC void poll_map_add(mp_map_t *poll_map, const mp_obj_t *obj, mp_uint_t obj_len, mp_uint_t flags, bool or_flags) { for (mp_uint_t i = 0; i < obj_len; i++) { mp_map_elem_t *elem = mp_map_lookup(poll_map, mp_obj_id(obj[i]), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND); - if (elem->value == NULL) { + if (elem->value == MP_OBJ_NULL) { // object not found; get its ioctl and add it to the poll list const mp_stream_p_t *stream_p = mp_get_stream_raise(obj[i], MP_STREAM_OP_IOCTL); poll_obj_t *poll_obj = m_new_obj(poll_obj_t); @@ -41,27 +41,27 @@ STATIC void poll_map_add(mp_map_t *poll_map, const mp_obj_t *obj, mp_uint_t obj_ poll_obj->ioctl = stream_p->ioctl; poll_obj->flags = flags; poll_obj->flags_ret = 0; - elem->value = poll_obj; + elem->value = MP_OBJ_FROM_PTR(poll_obj); } else { // object exists; update its flags if (or_flags) { - ((poll_obj_t *)elem->value)->flags |= flags; + ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags |= flags; } else { - ((poll_obj_t *)elem->value)->flags = flags; + ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = flags; } } } } // poll each object in the map -STATIC mp_uint_t poll_map_poll(mp_map_t *poll_map, mp_uint_t *rwx_num) { +STATIC mp_uint_t poll_map_poll(mp_map_t *poll_map, size_t *rwx_num) { mp_uint_t n_ready = 0; for (mp_uint_t i = 0; i < poll_map->alloc; ++i) { if (!MP_MAP_SLOT_IS_FILLED(poll_map, i)) { continue; } - poll_obj_t *poll_obj = (poll_obj_t *)poll_map->table[i].value; + poll_obj_t *poll_obj = MP_OBJ_TO_PTR(poll_map->table[i].value); int errcode; mp_int_t ret = poll_obj->ioctl(poll_obj->obj, MP_STREAM_POLL, poll_obj->flags, &errcode); poll_obj->flags_ret = ret; @@ -138,15 +138,15 @@ STATIC mp_obj_t select_select(uint n_args, const mp_obj_t *args) { if (!MP_MAP_SLOT_IS_FILLED(&poll_map, i)) { continue; } - poll_obj_t *poll_obj = (poll_obj_t *)poll_map.table[i].value; + poll_obj_t *poll_obj = MP_OBJ_TO_PTR(poll_map.table[i].value); if (poll_obj->flags_ret & MP_STREAM_POLL_RD) { - ((mp_obj_list_t *)list_array[0])->items[rwx_len[0]++] = poll_obj->obj; + ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[0]))->items[rwx_len[0]++] = poll_obj->obj; } if (poll_obj->flags_ret & MP_STREAM_POLL_WR) { - ((mp_obj_list_t *)list_array[1])->items[rwx_len[1]++] = poll_obj->obj; + ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[1]))->items[rwx_len[1]++] = poll_obj->obj; } if ((poll_obj->flags_ret & ~(MP_STREAM_POLL_RD | MP_STREAM_POLL_WR)) != 0) { - ((mp_obj_list_t *)list_array[2])->items[rwx_len[2]++] = poll_obj->obj; + ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[2]))->items[rwx_len[2]++] = poll_obj->obj; } } mp_map_deinit(&poll_map); @@ -171,7 +171,7 @@ typedef struct _mp_obj_poll_t { /// \method register(obj[, eventmask]) STATIC mp_obj_t poll_register(uint n_args, const mp_obj_t *args) { - mp_obj_poll_t *self = args[0]; + mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); mp_uint_t flags; if (n_args == 3) { flags = mp_obj_get_int(args[2]); @@ -185,7 +185,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(poll_register_obj, 2, 3, poll_register); /// \method unregister(obj) STATIC mp_obj_t poll_unregister(mp_obj_t self_in, mp_obj_t obj_in) { - mp_obj_poll_t *self = self_in; + mp_obj_poll_t *self = MP_OBJ_TO_PTR(self_in); mp_map_lookup(&self->poll_map, mp_obj_id(obj_in), MP_MAP_LOOKUP_REMOVE_IF_FOUND); // TODO raise KeyError if obj didn't exist in map return mp_const_none; @@ -194,18 +194,18 @@ MP_DEFINE_CONST_FUN_OBJ_2(poll_unregister_obj, poll_unregister); /// \method modify(obj, eventmask) STATIC mp_obj_t poll_modify(mp_obj_t self_in, mp_obj_t obj_in, mp_obj_t eventmask_in) { - mp_obj_poll_t *self = self_in; + mp_obj_poll_t *self = MP_OBJ_TO_PTR(self_in); mp_map_elem_t *elem = mp_map_lookup(&self->poll_map, mp_obj_id(obj_in), MP_MAP_LOOKUP); if (elem == NULL) { mp_raise_OSError(MP_ENOENT); } - ((poll_obj_t *)elem->value)->flags = mp_obj_get_int(eventmask_in); + ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = mp_obj_get_int(eventmask_in); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_3(poll_modify_obj, poll_modify); STATIC mp_uint_t poll_poll_internal(uint n_args, const mp_obj_t *args) { - mp_obj_poll_t *self = args[0]; + mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); // work out timeout (its given already in ms) mp_uint_t timeout = -1; @@ -238,18 +238,18 @@ STATIC mp_uint_t poll_poll_internal(uint n_args, const mp_obj_t *args) { return n_ready; } -STATIC mp_obj_t poll_poll(uint n_args, const mp_obj_t *args) { - mp_obj_poll_t *self = args[0]; +STATIC mp_obj_t poll_poll(size_t n_args, const mp_obj_t *args) { + mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); mp_uint_t n_ready = poll_poll_internal(n_args, args); // one or more objects are ready, or we had a timeout - mp_obj_list_t *ret_list = mp_obj_new_list(n_ready, NULL); + mp_obj_list_t *ret_list = MP_OBJ_TO_PTR(mp_obj_new_list(n_ready, NULL)); n_ready = 0; for (mp_uint_t i = 0; i < self->poll_map.alloc; ++i) { if (!MP_MAP_SLOT_IS_FILLED(&self->poll_map, i)) { continue; } - poll_obj_t *poll_obj = (poll_obj_t *)self->poll_map.table[i].value; + poll_obj_t *poll_obj = MP_OBJ_TO_PTR(self->poll_map.table[i].value); if (poll_obj->flags_ret != 0) { mp_obj_t tuple[2] = {poll_obj->obj, MP_OBJ_NEW_SMALL_INT(poll_obj->flags_ret)}; ret_list->items[n_ready++] = mp_obj_new_tuple(2, tuple); @@ -259,7 +259,7 @@ STATIC mp_obj_t poll_poll(uint n_args, const mp_obj_t *args) { } } } - return ret_list; + return MP_OBJ_FROM_PTR(ret_list); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(poll_poll_obj, 1, 3, poll_poll); @@ -292,7 +292,7 @@ STATIC mp_obj_t poll_iternext(mp_obj_t self_in) { if (!MP_MAP_SLOT_IS_FILLED(&self->poll_map, i)) { continue; } - poll_obj_t *poll_obj = (poll_obj_t *)self->poll_map.table[i].value; + poll_obj_t *poll_obj = MP_OBJ_TO_PTR(self->poll_map.table[i].value); if (poll_obj->flags_ret != 0) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->ret_tuple); t->items[0] = poll_obj->obj; @@ -334,7 +334,7 @@ STATIC mp_obj_t select_poll(void) { mp_map_init(&poll->poll_map, 0); poll->iter_cnt = 0; poll->ret_tuple = MP_OBJ_NULL; - return poll; + return MP_OBJ_FROM_PTR(poll); } MP_DEFINE_CONST_FUN_OBJ_0(mp_select_poll_obj, select_poll); diff --git a/extmod/modussl_axtls.c b/extmod/modussl_axtls.c index 757210871b..673f480b2c 100644 --- a/extmod/modussl_axtls.c +++ b/extmod/modussl_axtls.c @@ -158,21 +158,13 @@ STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, in STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(o_in); - (void)arg; - switch (request) { - case MP_STREAM_CLOSE: - if (self->ssl_sock != NULL) { - ssl_free(self->ssl_sock); - ssl_ctx_free(self->ssl_ctx); - self->ssl_sock = NULL; - mp_stream_close(self->sock); - } - return 0; - - default: - *errcode = MP_EINVAL; - return MP_STREAM_ERROR; + if (request == MP_STREAM_CLOSE && self->ssl_sock != NULL) { + ssl_free(self->ssl_sock); + ssl_ctx_free(self->ssl_ctx); + self->ssl_sock = NULL; } + // Pass all requests down to the underlying socket + return mp_get_stream(self->sock)->ioctl(self->sock, request, arg, errcode); } STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { @@ -220,10 +212,10 @@ STATIC const mp_obj_type_t ussl_socket_type = { STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { // TODO: Implement more args static const mp_arg_t allowed_args[] = { - { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, - { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} }, + { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} }, { MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, - { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} }, }; // TODO: Check that sock implements stream protocol diff --git a/extmod/modussl_mbedtls.c b/extmod/modussl_mbedtls.c index 830d6359aa..05d6047f9b 100644 --- a/extmod/modussl_mbedtls.c +++ b/extmod/modussl_mbedtls.c @@ -249,23 +249,17 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(o_in); - (void)arg; - switch (request) { - case MP_STREAM_CLOSE: - mbedtls_pk_free(&self->pkey); - mbedtls_x509_crt_free(&self->cert); - mbedtls_x509_crt_free(&self->cacert); - mbedtls_ssl_free(&self->ssl); - mbedtls_ssl_config_free(&self->conf); - mbedtls_ctr_drbg_free(&self->ctr_drbg); - mbedtls_entropy_free(&self->entropy); - mp_stream_close(self->sock); - return 0; - - default: - *errcode = MP_EINVAL; - return MP_STREAM_ERROR; + if (request == MP_STREAM_CLOSE) { + mbedtls_pk_free(&self->pkey); + mbedtls_x509_crt_free(&self->cert); + mbedtls_x509_crt_free(&self->cacert); + mbedtls_ssl_free(&self->ssl); + mbedtls_ssl_config_free(&self->conf); + mbedtls_ctr_drbg_free(&self->ctr_drbg); + mbedtls_entropy_free(&self->entropy); } + // Pass all requests down to the underlying socket + return mp_get_stream(self->sock)->ioctl(self->sock, request, arg, errcode); } STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = { diff --git a/extmod/modwebrepl.c b/extmod/modwebrepl.c index f34e14caf5..f470e26dba 100644 --- a/extmod/modwebrepl.c +++ b/extmod/modwebrepl.c @@ -14,7 +14,6 @@ #include "py/mphal.h" #endif #include "extmod/modwebsocket.h" -#include "genhdr/mpversion.h" #if MICROPY_PY_WEBREPL diff --git a/extmod/re1.5/compilecode.c b/extmod/re1.5/compilecode.c index 01d3d14988..81c0bceef7 100644 --- a/extmod/re1.5/compilecode.c +++ b/extmod/re1.5/compilecode.c @@ -8,9 +8,9 @@ ((code ? memmove(code + at + num, code + at, pc - at) : 0), pc += num) #define REL(at, to) (to - at - 2) #define EMIT(at, byte) (code ? (code[at] = byte) : (at)) +#define EMIT_CHECKED(at, byte) (_emit_checked(at, code, byte, &err)) #define PC (prog->bytelen) - static char unescape(char c) { switch (c) { case 'a': @@ -33,9 +33,17 @@ static char unescape(char c) { } +static void _emit_checked(int at, char *code, int val, bool *err) { + *err |= val != (int8_t)val; + if (code) { + code[at] = val; + } +} + static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) { char *code = sizecode ? NULL : prog->insts; + bool err = false; int start = PC; int term = PC; int alt_label = 0; @@ -96,7 +104,7 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) EMIT(PC++, *re); } } - EMIT(term + 1, cnt); + EMIT_CHECKED(term + 1, cnt); break; } case '(': { @@ -107,7 +115,7 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) if (capture) { sub = ++prog->sub; EMIT(PC++, Save); - EMIT(PC++, 2 * sub); + EMIT_CHECKED(PC++, 2 * sub); prog->len++; } else { re += 2; @@ -118,7 +126,7 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) if (capture) { EMIT(PC++, Save); - EMIT(PC++, 2 * sub + 1); + EMIT_CHECKED(PC++, 2 * sub + 1); prog->len++; } @@ -133,7 +141,7 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) } else { EMIT(term, Split); } - EMIT(term + 1, REL(term, PC)); + EMIT_CHECKED(term + 1, REL(term, PC)); prog->len++; term = PC; break; @@ -141,7 +149,7 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) if (PC == term) return NULL; // nothing to repeat INSERT_CODE(term, 2, PC); EMIT(PC, Jmp); - EMIT(PC + 1, REL(PC, term)); + EMIT_CHECKED(PC + 1, REL(PC, term)); PC += 2; if (re[1] == '?') { EMIT(term, RSplit); @@ -149,7 +157,7 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) } else { EMIT(term, Split); } - EMIT(term + 1, REL(term, PC)); + EMIT_CHECKED(term + 1, REL(term, PC)); prog->len += 2; term = PC; break; @@ -161,20 +169,20 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) } else { EMIT(PC, RSplit); } - EMIT(PC + 1, REL(PC, term)); + EMIT_CHECKED(PC + 1, REL(PC, term)); PC += 2; prog->len++; term = PC; break; case '|': if (alt_label) { - EMIT(alt_label, REL(alt_label, PC) + 1); + EMIT_CHECKED(alt_label, REL(alt_label, PC) + 1); } INSERT_CODE(start, 2, PC); EMIT(PC++, Jmp); alt_label = PC++; EMIT(start, Split); - EMIT(start + 1, REL(start, PC)); + EMIT_CHECKED(start + 1, REL(start, PC)); prog->len += 2; term = PC; break; @@ -192,9 +200,9 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) } if (alt_label) { - EMIT(alt_label, REL(alt_label, PC) + 1); + EMIT_CHECKED(alt_label, REL(alt_label, PC) + 1); } - return re; + return err ? NULL : re; } int re1_5_sizecode(const char *re) diff --git a/extmod/uos_dupterm.c b/extmod/uos_dupterm.c index bd2dc639c8..4668279bc8 100644 --- a/extmod/uos_dupterm.c +++ b/extmod/uos_dupterm.c @@ -66,7 +66,7 @@ int mp_uos_dupterm_rx_chr(void) { return buf[0]; } } else { - mp_uos_deactivate(idx, "dupterm: Exception in read() method, deactivating: ", nlr.ret_val); + mp_uos_deactivate(idx, "dupterm: Exception in read() method, deactivating: ", MP_OBJ_FROM_PTR(nlr.ret_val)); } } @@ -84,7 +84,7 @@ void mp_uos_dupterm_tx_strn(const char *str, size_t len) { mp_stream_write(MP_STATE_VM(dupterm_objs[idx]), str, len, MP_STREAM_RW_WRITE); nlr_pop(); } else { - mp_uos_deactivate(idx, "dupterm: Exception in write() method, deactivating: ", nlr.ret_val); + mp_uos_deactivate(idx, "dupterm: Exception in write() method, deactivating: ", MP_OBJ_FROM_PTR(nlr.ret_val)); } } } diff --git a/extmod/vfs.c b/extmod/vfs.c index b20b251938..cac51289fd 100644 --- a/extmod/vfs.c +++ b/extmod/vfs.c @@ -17,6 +17,10 @@ #include "extmod/vfs_fat.h" #endif +#if defined(MICROPY_VFS_POSIX) && MICROPY_VFS_POSIX +#include "extmod/vfs_posix.h" +#endif + // For mp_vfs_proxy_call, the maximum number of additional args that can be passed. // A fixed maximum size is used to avoid the need for a costly variable array. #define PROXY_MAX_ARGS (2) @@ -244,6 +248,13 @@ mp_obj_t mp_vfs_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + #if defined(MICROPY_VFS_POSIX) && MICROPY_VFS_POSIX + // If the file is an integer then delegate straight to the POSIX handler + if (MP_OBJ_IS_SMALL_INT(args[ARG_file].u_obj)) { + return mp_vfs_posix_file_open(&mp_type_textio, args[ARG_file].u_obj, args[ARG_mode].u_obj); + } + #endif + mp_vfs_mount_t *vfs = lookup_path(args[ARG_file].u_obj, &args[ARG_file].u_obj); return mp_vfs_proxy_call(vfs, MP_QSTR_open, 2, (mp_obj_t *)&args); } diff --git a/extmod/vfs_posix.c b/extmod/vfs_posix.c index 02f0e7cea9..ff2ed04715 100644 --- a/extmod/vfs_posix.c +++ b/extmod/vfs_posix.c @@ -172,6 +172,9 @@ STATIC mp_obj_t vfs_posix_ilistdir_it_iternext(mp_obj_t self_in) { } #ifdef _DIRENT_HAVE_D_TYPE + #ifdef DTTOIF + t->items[1] = MP_OBJ_NEW_SMALL_INT(DTTOIF(dirent->d_type)); + #else if (dirent->d_type == DT_DIR) { t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); } else if (dirent->d_type == DT_REG) { @@ -179,10 +182,12 @@ STATIC mp_obj_t vfs_posix_ilistdir_it_iternext(mp_obj_t self_in) { } else { t->items[1] = MP_OBJ_NEW_SMALL_INT(dirent->d_type); } + #endif #else // DT_UNKNOWN should have 0 value on any reasonable system t->items[1] = MP_OBJ_NEW_SMALL_INT(0); #endif + #ifdef _DIRENT_HAVE_D_INO t->items[2] = MP_OBJ_NEW_SMALL_INT(dirent->d_ino); #else @@ -200,6 +205,9 @@ STATIC mp_obj_t vfs_posix_ilistdir(mp_obj_t self_in, mp_obj_t path_in) { iter->iternext = vfs_posix_ilistdir_it_iternext; iter->is_str = mp_obj_get_type(path_in) == &mp_type_str; const char *path = vfs_posix_get_path_str(self, path_in); + if (path[0] == '\0') { + path = "."; + } iter->dir = opendir(path); if (iter->dir == NULL) { mp_raise_OSError(errno); diff --git a/extmod/virtpin.c b/extmod/virtpin.c index bb4935a0bc..e19c05c812 100644 --- a/extmod/virtpin.c +++ b/extmod/virtpin.c @@ -1,4 +1,4 @@ -// Copyright (c) 2016 Paul Sokolovsky +// SPDX-FileCopyrightText: Copyright (c) 2016 Paul Sokolovsky // SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) // // SPDX-License-Identifier: MIT diff --git a/frozen/Adafruit_CircuitPython_MIDI b/frozen/Adafruit_CircuitPython_MIDI new file mode 160000 index 0000000000..669ab7b752 --- /dev/null +++ b/frozen/Adafruit_CircuitPython_MIDI @@ -0,0 +1 @@ +Subproject commit 669ab7b752d6c863577312560faf505656e5e603 diff --git a/frozen/Adafruit_CircuitPython_SimpleMath b/frozen/Adafruit_CircuitPython_SimpleMath new file mode 160000 index 0000000000..cdf9944730 --- /dev/null +++ b/frozen/Adafruit_CircuitPython_SimpleMath @@ -0,0 +1 @@ +Subproject commit cdf99447307473080b2f2e95e7c3667247095ac0 diff --git a/lib/libm/math.c b/lib/libm/math.c index 670d95ed2d..c3dbf657ff 100644 --- a/lib/libm/math.c +++ b/lib/libm/math.c @@ -30,12 +30,17 @@ typedef float float_t; typedef union { float f; struct { - uint64_t m : 23; - uint64_t e : 8; - uint64_t s : 1; + uint32_t m : 23; + uint32_t e : 8; + uint32_t s : 1; }; } float_s_t; +int __signbitf(float f) { + float_s_t u = {.f = f}; + return u.s; +} + #ifndef NDEBUG float copysignf(float x, float y) { float_s_t fx={.f = x}; @@ -55,10 +60,14 @@ static const float _M_LN2 = 0.6931472; float log2f(float x) { return logf(x) / (float)_M_LN2; } float tanhf(float x) { - if (isinf(x)) { - return copysignf(1, x); + int sign = 0; + if (x < 0) { + sign = 1; + x = -x; } - return sinhf(x) / coshf(x); + x = expm1f(-2 * x); + x = x / (x + 2); + return sign ? x : -x; } /*****************************************************************************/ diff --git a/lib/libm/wf_tgamma.c b/lib/libm/wf_tgamma.c index 64b2488d1d..3ff05f331d 100644 --- a/lib/libm/wf_tgamma.c +++ b/lib/libm/wf_tgamma.c @@ -35,6 +35,10 @@ { float y; int local_signgam; + if (!isfinite(x)) { + /* special cases: tgammaf(nan)=nan, tgammaf(inf)=inf, tgammaf(-inf)=nan */ + return x + INFINITY; + } y = expf(__ieee754_lgammaf_r(x,&local_signgam)); if (local_signgam < 0) y = -y; #ifdef _IEEE_LIBM diff --git a/lib/libm_dbl/README b/lib/libm_dbl/README index 512b328261..0ef01af815 100644 --- a/lib/libm_dbl/README +++ b/lib/libm_dbl/README @@ -4,6 +4,10 @@ functions. The files lgamma.c, log10.c and tanh.c are too small to have a meaningful copyright or license. +The file copysign.c contains a double version of the float copysignf provided +in libm/math.c for use in DEBUG builds where the standard library copy is +not available. + The rest of the files in this directory are copied from the musl library, v1.1.16, and, unless otherwise stated in the individual file, have the following copyright and MIT license: diff --git a/lib/libm_dbl/copysign.c b/lib/libm_dbl/copysign.c new file mode 100644 index 0000000000..f42b09bee5 --- /dev/null +++ b/lib/libm_dbl/copysign.c @@ -0,0 +1,48 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2013, 2014 Damien P. George + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "libm.h" + +#ifndef NDEBUG +typedef union { + double d; + struct { + uint64_t m : 52; + uint64_t e : 11; + uint64_t s : 1; + }; +} double_s_t; + +double copysign(double x, double y) { + double_s_t dx={.d = x}; + double_s_t dy={.d = y}; + + // copy sign bit; + dx.s = dy.s; + + return dx.d; +} +#endif diff --git a/lib/libm_dbl/tanh.c b/lib/libm_dbl/tanh.c index 89743ba90f..6bdb7c3999 100644 --- a/lib/libm_dbl/tanh.c +++ b/lib/libm_dbl/tanh.c @@ -1,5 +1,12 @@ #include double tanh(double x) { - return sinh(x) / cosh(x); + int sign = 0; + if (x < 0) { + sign = 1; + x = -x; + } + x = expm1(-2 * x); + x = x / (x + 2); + return sign ? x : -x; } diff --git a/lib/utils/mpirq.c b/lib/utils/mpirq.c new file mode 100644 index 0000000000..dd0c220059 --- /dev/null +++ b/lib/utils/mpirq.c @@ -0,0 +1,124 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2015 Daniel Campora + * 2018 Tobias Badertscher + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "py/runtime.h" +#include "py/gc.h" +#include "lib/utils/mpirq.h" + +/****************************************************************************** + DECLARE PUBLIC DATA + ******************************************************************************/ + +const mp_arg_t mp_irq_init_args[] = { + { MP_QSTR_handler, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} }, + { MP_QSTR_trigger, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_hard, MP_ARG_BOOL, {.u_bool = false} }, +}; + +/****************************************************************************** + DECLARE PRIVATE DATA + ******************************************************************************/ + +/****************************************************************************** + DEFINE PUBLIC FUNCTIONS + ******************************************************************************/ + +mp_irq_obj_t *mp_irq_new(const mp_irq_methods_t *methods, mp_obj_t parent) { + mp_irq_obj_t *self = m_new0(mp_irq_obj_t, 1); + self->base.type = &mp_irq_type; + self->methods = (mp_irq_methods_t *)methods; + self->parent = parent; + self->handler = mp_const_none; + self->ishard = false; + return self; +} + +void mp_irq_handler(mp_irq_obj_t *self) { + if (self->handler != mp_const_none) { + if (self->ishard) { + // When executing code within a handler we must lock the GC to prevent + // any memory allocations. + gc_lock(); + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + mp_call_function_1(self->handler, self->parent); + nlr_pop(); + } else { + // Uncaught exception; disable the callback so that it doesn't run again + self->methods->trigger(self->parent, 0); + self->handler = mp_const_none; + printf("Uncaught exception in IRQ callback handler\n"); + mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); + } + gc_unlock(); + } else { + // Schedule call to user function + mp_sched_schedule(self->handler, self->parent); + } + } +} + +/******************************************************************************/ +// MicroPython bindings + +STATIC mp_obj_t mp_irq_flags(mp_obj_t self_in) { + mp_irq_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_int(self->methods->info(self->parent, MP_IRQ_INFO_FLAGS)); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_irq_flags_obj, mp_irq_flags); + +STATIC mp_obj_t mp_irq_trigger(size_t n_args, const mp_obj_t *args) { + mp_irq_obj_t *self = MP_OBJ_TO_PTR(args[0]); + mp_obj_t ret_obj = mp_obj_new_int(self->methods->info(self->parent, MP_IRQ_INFO_TRIGGERS)); + if (n_args == 2) { + // Set trigger + self->methods->trigger(self->parent, mp_obj_get_int(args[1])); + } + return ret_obj; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_irq_trigger_obj, 1, 2, mp_irq_trigger); + +STATIC mp_obj_t mp_irq_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_arg_check_num(n_args, n_kw, 0, 0, false); + mp_irq_handler(MP_OBJ_TO_PTR(self_in)); + return mp_const_none; +} + +STATIC const mp_rom_map_elem_t mp_irq_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_flags), MP_ROM_PTR(&mp_irq_flags_obj) }, + { MP_ROM_QSTR(MP_QSTR_trigger), MP_ROM_PTR(&mp_irq_trigger_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(mp_irq_locals_dict, mp_irq_locals_dict_table); + +const mp_obj_type_t mp_irq_type = { + { &mp_type_type }, + .name = MP_QSTR_irq, + .call = mp_irq_call, + .locals_dict = (mp_obj_dict_t *)&mp_irq_locals_dict, +}; diff --git a/lib/utils/mpirq.h b/lib/utils/mpirq.h new file mode 100644 index 0000000000..548185b531 --- /dev/null +++ b/lib/utils/mpirq.h @@ -0,0 +1,82 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2015 Daniel Campora + * + * 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. + */ +#ifndef MICROPY_INCLUDED_LIB_UTILS_MPIRQ_H +#define MICROPY_INCLUDED_LIB_UTILS_MPIRQ_H + +/****************************************************************************** + DEFINE CONSTANTS + ******************************************************************************/ + +enum { + MP_IRQ_ARG_INIT_handler = 0, + MP_IRQ_ARG_INIT_trigger, + MP_IRQ_ARG_INIT_hard, + MP_IRQ_ARG_INIT_NUM_ARGS, +}; + +/****************************************************************************** + DEFINE TYPES + ******************************************************************************/ + +typedef mp_obj_t (*mp_irq_init_t)(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args); +typedef mp_uint_t (*mp_irq_uint_method_one_uint_para_t)(mp_obj_t self, mp_uint_t trigger); +typedef mp_uint_t (*mp_irq_int_method_one_para_t)(mp_obj_t self, mp_uint_t info_type); + +enum { + MP_IRQ_INFO_FLAGS, + MP_IRQ_INFO_TRIGGERS, + MP_IRQ_INFO_CNT +}; + +typedef struct _mp_irq_methods_t { + mp_irq_init_t init; + mp_irq_uint_method_one_uint_para_t trigger; + mp_irq_int_method_one_para_t info; +} mp_irq_methods_t; + +typedef struct _mp_irq_obj_t { + mp_obj_base_t base; + mp_irq_methods_t *methods; + mp_obj_t parent; + mp_obj_t handler; + bool ishard; +} mp_irq_obj_t; + +/****************************************************************************** + DECLARE EXPORTED DATA + ******************************************************************************/ + +extern const mp_arg_t mp_irq_init_args[]; +extern const mp_obj_type_t mp_irq_type; + +/****************************************************************************** + DECLARE PUBLIC FUNCTIONS + ******************************************************************************/ + +mp_irq_obj_t *mp_irq_new(const mp_irq_methods_t *methods, mp_obj_t parent); +void mp_irq_handler(mp_irq_obj_t *self); + +#endif // MICROPY_INCLUDED_LIB_UTILS_MPIRQ_H diff --git a/lib/utils/printf.c b/lib/utils/printf.c index 859c7e0017..dbf0c26744 100644 --- a/lib/utils/printf.c +++ b/lib/utils/printf.c @@ -26,8 +26,6 @@ #include "py/mpconfig.h" -#if MICROPY_USE_INTERNAL_PRINTF - #include #include #include @@ -39,6 +37,18 @@ #include "py/formatfloat.h" #endif +#if MICROPY_DEBUG_PRINTERS +int DEBUG_printf(const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + int ret = mp_vprintf(MICROPY_DEBUG_PRINTER, fmt, ap); + va_end(ap); + return ret; +} +#endif + +#if MICROPY_USE_INTERNAL_PRINTF + #undef putchar // Some stdlibs have a #define for putchar int printf(const char *fmt, ...); int vprintf(const char *fmt, va_list ap); @@ -59,20 +69,6 @@ int vprintf(const char *fmt, va_list ap) { return mp_vprintf(&mp_plat_print, fmt, ap); } -#if MICROPY_DEBUG_PRINTERS -extern const mp_print_t MICROPY_DEBUG_PRINTER_DEST; -int DEBUG_printf(const char *fmt, ...) { - va_list ap; - va_start(ap, fmt); - #ifndef MICROPY_DEBUG_PRINTER_DEST - #define MICROPY_DEBUG_PRINTER_DEST mp_plat_print - #endif - int ret = mp_vprintf(&MICROPY_DEBUG_PRINTER_DEST, fmt, ap); - va_end(ap); - return ret; -} -#endif - // need this because gcc optimises printf("%c", c) -> putchar(c), and printf("a") -> putchar('a') int putchar(int c) { char chr = c; diff --git a/lib/utils/pyexec.c b/lib/utils/pyexec.c index 450b5ae326..9a105a42ca 100644 --- a/lib/utils/pyexec.c +++ b/lib/utils/pyexec.c @@ -129,7 +129,7 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input mp_hal_stdout_tx_strn("\x04", 1); } // check for SystemExit - if (mp_obj_is_subclass_fast(mp_obj_get_type((mp_obj_t)nlr.ret_val), &mp_type_SystemExit)) { + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) { // at the moment, the value of SystemExit is unused ret = pyexec_system_exit; #if CIRCUITPY_ALARM @@ -138,7 +138,7 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input #endif } else { if ((mp_obj_t)nlr.ret_val != MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_reload_exception))) { - mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val); + mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); } ret = PYEXEC_EXCEPTION; } @@ -455,6 +455,12 @@ friendly_repl_reset: } #endif + // If the GC is locked at this point there is no way out except a reset, + // so force the GC to be unlocked to help the user debug what went wrong. + if (MP_STATE_MEM(gc_lock_depth) != 0) { + MP_STATE_MEM(gc_lock_depth) = 0; + } + vstr_reset(&line); int ret = readline(&line, ">>> "); mp_parse_input_kind_t parse_input_kind = MP_PARSE_SINGLE_INPUT; diff --git a/lib/utils/sys_stdio_mphal.c b/lib/utils/sys_stdio_mphal.c index e2e1999c25..c3757626c1 100644 --- a/lib/utils/sys_stdio_mphal.c +++ b/lib/utils/sys_stdio_mphal.c @@ -172,7 +172,7 @@ STATIC const mp_obj_type_t stdio_buffer_obj_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &stdio_buffer_obj_stream_p, - .locals_dict = (mp_obj_t)&stdio_locals_dict, + .locals_dict = (mp_obj_dict_t *)&stdio_locals_dict, }; STATIC const sys_stdio_obj_t stdio_buffer_obj = {{&stdio_buffer_obj_type}, .fd = 0}; // fd unused diff --git a/locale/ID.po b/locale/ID.po index 2592a4e40d..213537ea56 100644 --- a/locale/ID.po +++ b/locale/ID.po @@ -6,15 +6,15 @@ msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2021-01-15 19:49+0000\n" -"Last-Translator: oon arfiandwi \n" +"PO-Revision-Date: 2021-04-07 12:23+0000\n" +"Last-Translator: Reza Almanda \n" "Language-Team: LANGUAGE \n" "Language: ID\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" -"X-Generator: Weblate 4.5-dev\n" +"X-Generator: Weblate 4.6-dev\n" #: main.c msgid "" @@ -29,6 +29,8 @@ msgid "" "\n" "Code stopped by auto-reload.\n" msgstr "" +"\n" +"Kode berhenti oleh auto-reload.\n" #: supervisor/shared/safe_mode.c msgid "" @@ -443,8 +445,8 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "Mencoba alokasi heap ketika MicroPython VM tidak berjalan." +msgid "Attempted heap allocation when VM not running." +msgstr "" #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -852,9 +854,8 @@ msgid "Data chunk must follow fmt chunk" msgstr "Potongan data harus mengikuti fmt chunk" #: ports/nrf/common-hal/_bleio/Adapter.c -#, fuzzy msgid "Data too large for advertisement packet" -msgstr "Tidak bisa menyesuaikan data ke dalam paket advertisment" +msgstr "Data terlalu besar untuk paket advertisment" #: shared-bindings/audiobusio/PDMIn.c msgid "Destination capacity is smaller than destination_length." @@ -898,6 +899,11 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "Channel EXTINT sedang digunakan" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "Error pada regex" @@ -970,9 +976,9 @@ msgid "Failed sending command." msgstr "Gagal mengirim perintah." #: ports/nrf/sd_mutex.c -#, fuzzy, c-format +#, c-format msgid "Failed to acquire mutex, err 0x%04x" -msgstr "Gagal untuk mendapatkan mutex, status: 0x%08lX" +msgstr "Gagal memperoleh mutex, err 0x%04x" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c #: ports/raspberrypi/common-hal/busio/UART.c @@ -1019,14 +1025,18 @@ msgid "Failed to parse MP3 file" msgstr "Gagal mengurai file MP3" #: ports/nrf/sd_mutex.c -#, fuzzy, c-format +#, c-format msgid "Failed to release mutex, err 0x%04x" -msgstr "Gagal untuk melepaskan mutex, status: 0x%08lX" +msgstr "Gagal melepaskan mutex, err 0x%04x" #: supervisor/shared/safe_mode.c msgid "Failed to write internal flash." msgstr "Gagal menulis flash internal." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "File sudah ada" @@ -1099,10 +1109,6 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1228,6 +1234,10 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "Pin DAC yang diberikan tidak valid" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1419,14 +1429,6 @@ msgstr "Nilai x maksimum ketika dicerminkan adalah %d" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "Lompatan NLR MicroPython gagal. Kemungkinan kerusakan memori." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "Kesalahan fatal MicroPython." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Penundaan mulai mikrofon harus dalam kisaran 0,0 hingga 1,0" @@ -1478,6 +1480,10 @@ msgstr "Harus menyediakan pin MISO atau MOSI" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Harus menggunakan kelipatan 6 pin rgb, bukan %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1622,11 +1628,11 @@ msgstr "" msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c -#, fuzzy msgid "Not connected" -msgstr "Tidak dapat menyambungkan ke AP" +msgstr "Tidak terhubung" #: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c #: shared-bindings/audiopwmio/PWMAudioOut.c @@ -1635,7 +1641,7 @@ msgstr "Tidak berfungsi" #: main.c msgid "Not running saved code.\n" -msgstr "" +msgstr "Tidak menjalankan kode yang disimpan.\n" #: shared-bindings/_bleio/__init__.c msgid "Not settable" @@ -1847,6 +1853,8 @@ msgstr "Buffer awalan harus ada di heap" #: main.c msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" msgstr "" +"Tekan sembarang tombol untuk masuk ke REPL. Tekan CTRL-D untuk memuat " +"ulang.\n" #: main.c msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" @@ -1926,9 +1934,8 @@ msgid "Read-only filesystem" msgstr "sistem file (filesystem) bersifat Read-only" #: shared-module/displayio/Bitmap.c -#, fuzzy msgid "Read-only object" -msgstr "sistem file (filesystem) bersifat Read-only" +msgstr "Objek Read-only" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "Received response was invalid" @@ -2166,9 +2173,8 @@ msgid "Too many displays" msgstr "Terlalu banyak tampilan" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" -"Total data yang akan ditulis lebih besar daripada outgoing_packet_length" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2308,9 +2314,8 @@ msgid "Unsupported baudrate" msgstr "Baudrate tidak didukung" #: shared-module/displayio/display_core.c -#, fuzzy msgid "Unsupported display bus type" -msgstr "Baudrate tidak didukung" +msgstr "Tipe bus tampilan tidak didukung" #: shared-module/audiocore/WaveFile.c msgid "Unsupported format" @@ -2342,10 +2347,6 @@ msgstr "Panjang nilai > max_length" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Fungsi Viper saat ini tidak mendukung lebih dari 4 argumen" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "Tegangan baca habis waktu" @@ -2431,11 +2432,6 @@ msgstr "sebuah objek menyerupai byte (bytes-like) dibutuhkan" msgid "abort() called" msgstr "abort() dipanggil" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "alamat %08x tidak selaras dengan %d bytes" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "alamat di luar batas" @@ -2444,6 +2440,10 @@ msgstr "alamat di luar batas" msgid "addresses is empty" msgstr "alamatnya kosong" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "arg berisi urutan kosong" @@ -2543,18 +2543,13 @@ msgstr "" msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" #: shared-module/struct/__init__.c -#, fuzzy msgid "buffer size must match format" -msgstr "buffers harus mempunyai panjang yang sama" +msgstr "ukuran buffer harus sesuai dengan format" #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c msgid "buffer slices must be of equal length" @@ -2631,6 +2626,10 @@ msgstr "tidak dapat menetapkan ke ekspresi" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "" @@ -2639,6 +2638,10 @@ msgstr "" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2989,7 +2992,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -3042,8 +3045,8 @@ msgid "full" msgstr "" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "fungsi tidak dapat mengambil argumen keyword" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3097,6 +3100,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "" @@ -3245,6 +3252,10 @@ msgstr "" msgid "invalid cert" msgstr "cert tidak valid" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "indeks dupterm tidak valid" @@ -3300,10 +3311,6 @@ msgstr "" msgid "invalid syntax for number" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "" @@ -3476,6 +3483,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3706,10 +3717,6 @@ msgstr "" msgid "palette_index should be an int" msgstr "" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "anotasi parameter haruse sebuah identifier" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3764,6 +3771,8 @@ msgstr "" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3789,6 +3798,10 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "" @@ -4018,9 +4031,8 @@ msgid "timeout must be < 655.35 secs" msgstr "" #: shared-bindings/_bleio/CharacteristicBuffer.c -#, fuzzy msgid "timeout must be >= 0.0" -msgstr "bits harus memilki nilai 8" +msgstr "waktu habis harus >= 0,0" #: shared-module/sdcardio/SDCard.c msgid "timeout waiting for v1 card" @@ -4063,10 +4075,6 @@ msgstr "" msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "" @@ -4148,7 +4156,7 @@ msgstr "" msgid "unknown type" msgstr "tipe tidak diketahui" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "" @@ -4201,10 +4209,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4232,20 +4236,20 @@ msgstr "" #: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" -msgstr "" +msgstr "indeks sumbu salah" #: extmod/ulab/code/ulab_create.c msgid "wrong axis specified" -msgstr "" +msgstr "sumbu yang ditentukan salah" #: extmod/ulab/code/numpy/compare/compare.c #: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" -msgstr "" +msgstr "tipe input salah" #: extmod/ulab/code/ulab_create.c py/objstr.c msgid "wrong number of arguments" -msgstr "" +msgstr "jumlah argumen salah" #: py/runtime.c msgid "wrong number of values to unpack" @@ -4281,16 +4285,41 @@ msgstr "" #: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" -msgstr "" +msgstr "zi harus ndarray" #: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" -msgstr "" +msgstr "zi harus berjenis float" #: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Fungsi Viper saat ini tidak mendukung lebih dari 4 argumen" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "alamat %08x tidak selaras dengan %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "fungsi tidak dapat mengambil argumen keyword" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "anotasi parameter haruse sebuah identifier" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "" +#~ "Total data yang akan ditulis lebih besar daripada outgoing_packet_length" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "Mencoba alokasi heap ketika MicroPython VM tidak berjalan." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "Lompatan NLR MicroPython gagal. Kemungkinan kerusakan memori." + +#~ msgid "MicroPython fatal error." +#~ msgstr "Kesalahan fatal MicroPython." + #~ msgid "Nordic Soft Device failure assertion." #~ msgstr "Pernyataan kegagalan Perangkat Lunak Nordic." diff --git a/locale/circuitpython.pot b/locale/circuitpython.pot index b8586ff136..9d276a8342 100644 --- a/locale/circuitpython.pot +++ b/locale/circuitpython.pot @@ -366,7 +366,7 @@ msgstr "" msgid "All state machines in use" msgstr "" -#: ports/atmel-samd/audio_dma.c ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/audio_dma.c msgid "All sync event channels in use" msgstr "" @@ -454,7 +454,7 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" #: shared-bindings/wifi/Radio.c @@ -904,6 +904,11 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "" @@ -1033,6 +1038,10 @@ msgstr "" msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "" @@ -1201,6 +1210,7 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "" @@ -1228,6 +1238,10 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1267,6 +1281,11 @@ msgstr "" msgid "Invalid channel count" msgstr "" +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "Invalid data_count %d" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Invalid direction." msgstr "" @@ -1419,14 +1438,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1478,6 +1489,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1622,6 +1637,7 @@ msgstr "" msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2147,7 +2163,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2319,10 +2335,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2402,11 +2414,6 @@ msgstr "" msgid "abort() called" msgstr "" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "" @@ -2415,6 +2422,10 @@ msgstr "" msgid "addresses is empty" msgstr "" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "" @@ -2514,10 +2525,6 @@ msgstr "" msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2601,6 +2608,10 @@ msgstr "" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "" @@ -2609,6 +2620,10 @@ msgstr "" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2807,6 +2822,11 @@ msgstr "" msgid "data must be of equal length" msgstr "" +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "data pin #%d in use" +msgstr "" + #: extmod/ulab/code/ndarray.c msgid "data type not understood" msgstr "" @@ -2959,7 +2979,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -3012,7 +3032,7 @@ msgid "full" msgstr "" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "" #: py/argcheck.c @@ -3067,6 +3087,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "" @@ -3215,6 +3239,10 @@ msgstr "" msgid "invalid cert" msgstr "" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "" @@ -3442,6 +3470,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3675,10 +3707,6 @@ msgstr "" msgid "palette_index should be an int" msgstr "" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3734,6 +3762,7 @@ msgstr "" #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3759,6 +3788,10 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "" @@ -4113,7 +4146,7 @@ msgstr "" msgid "unknown type" msgstr "" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "" diff --git a/locale/cs.po b/locale/cs.po index 654023f1f5..874f0bf329 100644 --- a/locale/cs.po +++ b/locale/cs.po @@ -441,7 +441,7 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" #: shared-bindings/wifi/Radio.c @@ -882,6 +882,11 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "" @@ -1011,6 +1016,10 @@ msgstr "" msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "" @@ -1083,10 +1092,6 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1210,6 +1215,10 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1401,14 +1410,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1460,6 +1461,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1604,6 +1609,7 @@ msgstr "" msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2129,7 +2135,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2301,10 +2307,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2384,11 +2386,6 @@ msgstr "" msgid "abort() called" msgstr "" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "" @@ -2397,6 +2394,10 @@ msgstr "" msgid "addresses is empty" msgstr "" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "" @@ -2496,10 +2497,6 @@ msgstr "" msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2583,6 +2580,10 @@ msgstr "" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "" @@ -2591,6 +2592,10 @@ msgstr "" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2941,7 +2946,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -2994,7 +2999,7 @@ msgid "full" msgstr "" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "" #: py/argcheck.c @@ -3049,6 +3054,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "" @@ -3197,6 +3206,10 @@ msgstr "" msgid "invalid cert" msgstr "" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "" @@ -3252,10 +3265,6 @@ msgstr "" msgid "invalid syntax for number" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "" @@ -3428,6 +3437,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3657,10 +3670,6 @@ msgstr "" msgid "palette_index should be an int" msgstr "" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3715,6 +3724,8 @@ msgstr "" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3740,6 +3751,10 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "" @@ -4013,10 +4028,6 @@ msgstr "" msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "" @@ -4098,7 +4109,7 @@ msgstr "" msgid "unknown type" msgstr "" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "" @@ -4151,10 +4162,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" diff --git a/locale/de_DE.po b/locale/de_DE.po index e3e2ddbd45..d59651ef3e 100644 --- a/locale/de_DE.po +++ b/locale/de_DE.po @@ -447,10 +447,8 @@ msgid "Attempt to allocate %d blocks" msgstr "Versuche %d Blöcke zu allokieren" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" -"Versuch einer Heap Reservierung, wenn die MicroPython-VM nicht ausgeführt " -"wird." #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -899,6 +897,11 @@ msgstr "ESP-IDF Speicherallozierung fehlgeschlagen" msgid "EXTINT channel already in use" msgstr "EXTINT Kanal ist schon in Benutzung" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "Fehler in regex" @@ -1029,6 +1032,10 @@ msgstr "Mutex konnte nicht freigegeben werden. Status: 0x%04x" msgid "Failed to write internal flash." msgstr "Interner Flash konnte nicht geschrieben werden." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "Datei existiert" @@ -1103,10 +1110,6 @@ msgstr "I2C Peripherie in Verwendung" msgid "I2SOut not available" msgstr "I2SOut nicht verfügbar" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IOs 0, 2 & 4 unterstützen keinen internen Pull up im sleep-Modus" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1232,6 +1235,10 @@ msgstr "Ungültige BSSID" msgid "Invalid DAC pin supplied" msgstr "Ungültiger DAC-Pin angegeben" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1423,15 +1430,6 @@ msgstr "Maximaler x-Wert beim Spiegeln ist %d" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" -"MicroPython NLR-Sprung fehlgeschlagen. Wahrscheinlich Speicherbeschädigung." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "Schwerwiegender MicroPython-Fehler." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1484,6 +1482,10 @@ msgstr "Muss MISO- oder MOSI-Pin bereitstellen" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Muss ein Vielfaches von 6 RGB-Pins verwenden, nicht %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1628,6 +1630,7 @@ msgstr "" msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2176,10 +2179,8 @@ msgid "Too many displays" msgstr "Zu viele displays" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" -"Die Gesamtzahl der zu schreibenden Daten ist größer als " -"outgoing_packet_length" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2354,10 +2355,6 @@ msgstr "Länge des Wertes > max_length" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Viper-Funktionen unterstützen derzeit nicht mehr als 4 Argumente" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "Zeitüberschreitung beim Lesen der Spannung" @@ -2448,11 +2445,6 @@ msgstr "ein Byte-ähnliches Objekt ist erforderlich" msgid "abort() called" msgstr "abort() wurde aufgerufen" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "Addresse %08x ist nicht an %d bytes ausgerichtet" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "Adresse außerhalb der Grenzen" @@ -2461,6 +2453,10 @@ msgstr "Adresse außerhalb der Grenzen" msgid "addresses is empty" msgstr "adresses ist leer" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "arg ist eine leere Sequenz" @@ -2560,10 +2556,6 @@ msgstr "Zweig ist außerhalb der Reichweite" msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "Puffer muss ein bytes-artiges Objekt sein" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2649,6 +2641,10 @@ msgstr "kann keinem Ausdruck zuweisen" msgid "can't convert %q to %q" msgstr "kann %q nicht zu %q konvertieren" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "Kann '%q' Objekt nicht implizit nach %q konvertieren" @@ -2657,6 +2653,10 @@ msgstr "Kann '%q' Objekt nicht implizit nach %q konvertieren" msgid "can't convert to %q" msgstr "kann nicht zu %q konvertieren" +#: py/runtime.c +msgid "can't convert to int" +msgstr "kann nicht nach int konvertieren" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "Kann nicht implizit nach str konvertieren" @@ -3017,7 +3017,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string: einzelne '}' nicht erlaubt" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "Die Datei muss eine im Byte-Modus geöffnete Datei sein" @@ -3070,8 +3070,8 @@ msgid "full" msgstr "voll" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "Funktion akzeptiert keine Schlüsselwort-Argumente" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3127,6 +3127,10 @@ msgstr "Generator läuft bereits" msgid "generator ignored GeneratorExit" msgstr "Generator ignoriert GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic muss 2048 Byte lang sein" @@ -3275,6 +3279,10 @@ msgstr "" msgid "invalid cert" msgstr "ungültiges cert" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "ungültiger dupterm index" @@ -3330,10 +3338,6 @@ msgstr "ungültige Syntax für integer mit Basis %d" msgid "invalid syntax for number" msgstr "ungültige Syntax für number" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() arg 1 muss eine Klasse sein" @@ -3512,6 +3516,10 @@ msgstr "native Ausbeute (yield)" msgid "need more than %d values to unpack" msgstr "Zum Entpacken sind mehr als %d Werte erforderlich" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "negative Potenz ohne Gleitkomma (float) Unterstützung" @@ -3745,10 +3753,6 @@ msgstr "Die Palette muss 32 Byte lang sein" msgid "palette_index should be an int" msgstr "palette_index sollte ein int sein" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "parameter annotation muss ein identifier sein" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "Die Parameter müssen Register der Reihenfolge a2 bis a5 sein" @@ -3803,6 +3807,8 @@ msgstr "pow () mit 3 Argumenten erfordert Integer" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3828,6 +3834,10 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "" @@ -4104,10 +4114,6 @@ msgstr "" msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "tupel/list hat falsche Länge" @@ -4193,7 +4199,7 @@ msgstr "Unbekannter Formatcode '%c' für Objekt vom Typ '%q'" msgid "unknown type" msgstr "unbekannter Typ" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "unbekannter Typ '%q'" @@ -4246,10 +4252,6 @@ msgstr "Wert muss in %d Byte(s) passen" msgid "value_count must be > 0" msgstr "value_count muss größer als 0 sein" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4336,6 +4338,42 @@ msgstr "" msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Viper-Funktionen unterstützen derzeit nicht mehr als 4 Argumente" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "Addresse %08x ist nicht an %d bytes ausgerichtet" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "Funktion akzeptiert keine Schlüsselwort-Argumente" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "parameter annotation muss ein identifier sein" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "" +#~ "Die Gesamtzahl der zu schreibenden Daten ist größer als " +#~ "outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IOs 0, 2 & 4 unterstützen keinen internen Pull up im sleep-Modus" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "Puffer muss ein bytes-artiges Objekt sein" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "" +#~ "Versuch einer Heap Reservierung, wenn die MicroPython-VM nicht ausgeführt " +#~ "wird." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "" +#~ "MicroPython NLR-Sprung fehlgeschlagen. Wahrscheinlich " +#~ "Speicherbeschädigung." + +#~ msgid "MicroPython fatal error." +#~ msgstr "Schwerwiegender MicroPython-Fehler." + #~ msgid "argument must be ndarray" #~ msgstr "Argument muss ein ndarray sein" @@ -4545,9 +4583,6 @@ msgstr "" #~ msgid "can't convert to float" #~ msgstr "kann nicht nach float konvertieren" -#~ msgid "can't convert to int" -#~ msgstr "kann nicht nach int konvertieren" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "Objekt '%s' ist weder tupel noch list" diff --git a/locale/el.po b/locale/el.po index 1f7fabf381..93d1c14efe 100644 --- a/locale/el.po +++ b/locale/el.po @@ -438,7 +438,7 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" #: shared-bindings/wifi/Radio.c @@ -879,6 +879,11 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "" @@ -1008,6 +1013,10 @@ msgstr "" msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "" @@ -1080,10 +1089,6 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1207,6 +1212,10 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1398,14 +1407,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1457,6 +1458,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1601,6 +1606,7 @@ msgstr "" msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2126,7 +2132,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2298,10 +2304,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2381,11 +2383,6 @@ msgstr "" msgid "abort() called" msgstr "" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "" @@ -2394,6 +2391,10 @@ msgstr "" msgid "addresses is empty" msgstr "" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "" @@ -2493,10 +2494,6 @@ msgstr "" msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2580,6 +2577,10 @@ msgstr "" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "" @@ -2588,6 +2589,10 @@ msgstr "" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2938,7 +2943,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -2991,7 +2996,7 @@ msgid "full" msgstr "" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "" #: py/argcheck.c @@ -3046,6 +3051,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "" @@ -3194,6 +3203,10 @@ msgstr "" msgid "invalid cert" msgstr "" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "" @@ -3249,10 +3262,6 @@ msgstr "" msgid "invalid syntax for number" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "" @@ -3425,6 +3434,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3654,10 +3667,6 @@ msgstr "" msgid "palette_index should be an int" msgstr "" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3712,6 +3721,8 @@ msgstr "" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3737,6 +3748,10 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "" @@ -4010,10 +4025,6 @@ msgstr "" msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "" @@ -4095,7 +4106,7 @@ msgstr "" msgid "unknown type" msgstr "" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "" @@ -4148,10 +4159,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" diff --git a/locale/en_GB.po b/locale/en_GB.po index 135f738872..f3fd1e71ad 100644 --- a/locale/en_GB.po +++ b/locale/en_GB.po @@ -7,15 +7,15 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"PO-Revision-Date: 2021-03-25 23:30+0000\n" -"Last-Translator: Gareth Coleman \n" +"PO-Revision-Date: 2021-04-11 01:30+0000\n" +"Last-Translator: Hugo Dahl \n" "Language-Team: none\n" "Language: en_GB\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=n != 1;\n" -"X-Generator: Weblate 4.5.2-dev\n" +"X-Generator: Weblate 4.6-dev\n" #: main.c msgid "" @@ -447,9 +447,8 @@ msgid "Attempt to allocate %d blocks" msgstr "Attempt to allocate %d blocks" #: supervisor/shared/safe_mode.c -#, fuzzy -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "Attempted heap allocation when CircuitPython VM not running." +msgid "Attempted heap allocation when VM not running." +msgstr "" #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -895,6 +894,11 @@ msgstr "ESP-IDF memory allocation failed" msgid "EXTINT channel already in use" msgstr "EXTINT channel already in use" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "Error in regex" @@ -1024,6 +1028,10 @@ msgstr "Failed to release mutex, err 0x%04x" msgid "Failed to write internal flash." msgstr "Failed to write internal flash." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "File exists" @@ -1096,10 +1104,6 @@ msgstr "I2C peripheral in use" msgid "I2SOut not available" msgstr "I2SOut not available" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IOs 0, 2 & 4 do not support internal pullup in sleep" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1225,6 +1229,10 @@ msgstr "Invalid BSSID" msgid "Invalid DAC pin supplied" msgstr "Invalid DAC pin supplied" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1416,16 +1424,6 @@ msgstr "Maximum x value when mirrored is %d" msgid "Messages limited to 8 bytes" msgstr "Messages limited to 8 bytes" -#: supervisor/shared/safe_mode.c -#, fuzzy -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "CircuitPython NLR jump failed. Likely memory corruption." - -#: supervisor/shared/safe_mode.c -#, fuzzy -msgid "MicroPython fatal error." -msgstr "CircuitPython fatal error." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Microphone startup delay must be in range 0.0 to 1.0" @@ -1477,6 +1475,10 @@ msgstr "Must provide MISO or MOSI pin" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Must use a multiple of 6 rgb pins, not %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "NVS Error" @@ -1621,6 +1623,7 @@ msgstr "" msgid "Not a valid IP string" msgstr "Not a valid IP string" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2166,8 +2169,8 @@ msgid "Too many displays" msgstr "Too many displays" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" -msgstr "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" +msgstr "" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2340,10 +2343,6 @@ msgstr "Value length > max_length" msgid "Version was invalid" msgstr "Version was invalid" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Viper functions don't currently support more than 4 arguments" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "Voltage read timed out" @@ -2428,11 +2427,6 @@ msgstr "a bytes-like object is required" msgid "abort() called" msgstr "abort() called" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "address %08x is not aligned to %d bytes" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "address out of bounds" @@ -2441,6 +2435,10 @@ msgstr "address out of bounds" msgid "addresses is empty" msgstr "addresses is empty" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "arg is an empty sequence" @@ -2540,10 +2538,6 @@ msgstr "Branch not in range" msgid "buffer is smaller than requested size" msgstr "Buffer is smaller than requested size" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "Buffer must be a bytes-like object" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "Buffer size must be a multiple of element size" @@ -2627,6 +2621,10 @@ msgstr "Can't assign to expression" msgid "can't convert %q to %q" msgstr "Can't convert %q to %q" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "Can't convert '%q' object to %q implicitly" @@ -2635,6 +2633,10 @@ msgstr "Can't convert '%q' object to %q implicitly" msgid "can't convert to %q" msgstr "Can't convert to %q" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "Can't convert to str implicitly" @@ -2988,7 +2990,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string: single '}' is not allowed" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "file must be a file opened in byte mode" @@ -3041,8 +3043,8 @@ msgid "full" msgstr "full" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3096,6 +3098,10 @@ msgstr "generator already executing" msgid "generator ignored GeneratorExit" msgstr "generator ignored GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic must be 2048 bytes long" @@ -3244,6 +3250,10 @@ msgstr "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" msgid "invalid cert" msgstr "invalid cert" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "invalid dupterm index" @@ -3300,10 +3310,6 @@ msgstr "invalid syntax for integer with base %d" msgid "invalid syntax for number" msgstr "invalid syntax for number" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "io must be rtc io" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() arg 1 must be a class" @@ -3476,6 +3482,10 @@ msgstr "native yield" msgid "need more than %d values to unpack" msgstr "need more than %d values to unpack" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "negative power with no float support" @@ -3705,10 +3715,6 @@ msgstr "palette must be 32 bytes long" msgid "palette_index should be an int" msgstr "palette_index should be an int" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "parameter annotation must be an identifier" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "parameters must be registers in sequence a2 to a5" @@ -3763,6 +3769,8 @@ msgstr "pow() with 3 arguments requires integers" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3788,6 +3796,10 @@ msgstr "pressing boot button at start up.\n" msgid "pressing both buttons at start up.\n" msgstr "pressing both buttons at start up.\n" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "pull masks conflict with direction masks" @@ -4063,10 +4075,6 @@ msgstr "trapz is defined for 1D arrays" msgid "trapz is defined for 1D arrays of equal length" msgstr "trapz is defined for 1D arrays of equal length" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "trigger level must be 0 or 1" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "tuple/list has wrong length" @@ -4148,7 +4156,7 @@ msgstr "unknown format code '%c' for object of type '%q'" msgid "unknown type" msgstr "unknown type" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "unknown type '%q'" @@ -4201,10 +4209,6 @@ msgstr "value must fit in %d byte(s)" msgid "value_count must be > 0" msgstr "value_count must be > 0" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "wakeup conflict" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "WatchDog not initialised" @@ -4291,6 +4295,46 @@ msgstr "zi must be of float type" msgid "zi must be of shape (n_section, 2)" msgstr "zi must be of shape (n_section, 2)" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Viper functions don't currently support more than 4 arguments" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "address %08x is not aligned to %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "function does not take keyword arguments" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "parameter annotation must be an identifier" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "Total data to write is larger than outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IOs 0, 2 & 4 do not support internal pullup in sleep" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "Buffer must be a bytes-like object" + +#~ msgid "io must be rtc io" +#~ msgstr "io must be rtc io" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "trigger level must be 0 or 1" + +#~ msgid "wakeup conflict" +#~ msgstr "wakeup conflict" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "Attempted heap allocation when MicroPython VM not running." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "MicroPython NLR jump failed. Likely memory corruption." + +#, fuzzy +#~ msgid "MicroPython fatal error." +#~ msgstr "CircuitPython fatal error." + #~ msgid "argument must be ndarray" #~ msgstr "argument must be ndarray" diff --git a/locale/es.po b/locale/es.po index 2f7a7a7b9c..2b0538e8b3 100644 --- a/locale/es.po +++ b/locale/es.po @@ -8,7 +8,7 @@ msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2021-04-05 22:35+0000\n" +"PO-Revision-Date: 2021-04-22 17:16+0000\n" "Last-Translator: Jose David M \n" "Language-Team: \n" "Language: es\n" @@ -16,7 +16,7 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=n != 1;\n" -"X-Generator: Weblate 4.6-dev\n" +"X-Generator: Weblate 4.7-dev\n" #: main.c msgid "" @@ -426,7 +426,7 @@ msgstr "El pin proporcionado no soporta AnalogOut" #: ports/stm/common-hal/audiopwmio/PWMAudioOut.c msgid "Another PWMAudioOut is already active" -msgstr "" +msgstr "Otra salida PWMAudioOut esta ya activada" #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c @@ -451,10 +451,8 @@ msgid "Attempt to allocate %d blocks" msgstr "Tratando de localizar %d bloques" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "" -"Se intentó asignación del montículo, sin que la VM de MicroPython esté " -"ejecutando." +msgid "Attempted heap allocation when VM not running." +msgstr "Asignación del montículo mientras la VM no esta ejecutándose." #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -905,6 +903,11 @@ msgstr "Fallo ESP-IDF al tomar la memoria" msgid "EXTINT channel already in use" msgstr "El canal EXTINT ya está siendo utilizado" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "Error en el flujo MIDI en la posición %d" + #: extmod/modure.c msgid "Error in regex" msgstr "Error en regex" @@ -1007,7 +1010,7 @@ msgstr "Fallo al tomar memoria para búsqueda wifi" #: ports/stm/common-hal/audiopwmio/PWMAudioOut.c msgid "Failed to buffer the sample" -msgstr "" +msgstr "Fallo al hacer el búfer de la muestra" #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" @@ -1034,6 +1037,10 @@ msgstr "No se puede liberar el mutex, err 0x%04x" msgid "Failed to write internal flash." msgstr "Error al escribir el flash interno." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "Error grave." + #: py/moduerrno.c msgid "File exists" msgstr "El archivo ya existe" @@ -1107,10 +1114,6 @@ msgstr "Dispositivo I2C en uso" msgid "I2SOut not available" msgstr "I2SOut no disponible" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IOs 0, 2 y 4 no soportan pullup interno durante sleep" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1243,6 +1246,10 @@ msgstr "BSSID inválido" msgid "Invalid DAC pin supplied" msgstr "Pin suministrado inválido para DAC" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "Archivo MIDI inválido" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1434,14 +1441,6 @@ msgstr "Valor máximo de x cuando se refleja es %d" msgid "Messages limited to 8 bytes" msgstr "Mensajes limitados a 8 bytes" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "MicroPython NLR jump falló. Probable corrupción de la memoria." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "Error fatal de MicroPython." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Micrófono demora de inicio debe estar en el rango 0.0 a 1.0" @@ -1497,6 +1496,10 @@ msgstr "Debe proporcionar un pin MISO o MOSI" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Debe usar un múltiplo de 6 pines rgb, no %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "Salto NLR falló. Probablemente corrupción de memoria." + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "Error NVS" @@ -1641,6 +1644,7 @@ msgstr "El firmware del sistema Nordic no tiene memoria" msgid "Not a valid IP string" msgstr "No es una cadena de IP válida" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2194,9 +2198,8 @@ msgid "Too many displays" msgstr "Muchos displays" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" -msgstr "" -"Los datos totales a escribir son más grandes que outgoing_packet_length" +msgid "Total data to write is larger than %q" +msgstr "La cantidad total de datos es mas grande que %q" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2369,10 +2372,6 @@ msgstr "Tamaño de valor > max_length" msgid "Version was invalid" msgstr "La versión era invalida" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "funciones Viper no soportan por el momento, más de 4 argumentos" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "Tiempo de espera agotado para lectura de voltaje" @@ -2461,11 +2460,6 @@ msgstr "se requiere un objeto bytes-like" msgid "abort() called" msgstr "se llamó abort()" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "la dirección %08x no esta alineada a %d bytes" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "address fuera de límites" @@ -2474,6 +2468,10 @@ msgstr "address fuera de límites" msgid "addresses is empty" msgstr "addresses esta vacío" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "argumento es una secuencia vacía" @@ -2573,10 +2571,6 @@ msgstr "la rama no está dentro del rango" msgid "buffer is smaller than requested size" msgstr "El buffer es mas pequeño que el requerido" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "buffer debe de ser un objeto bytes-like" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "El tamaño del buffer debe ser un múltiplo del tamaño del elemento" @@ -2660,6 +2654,10 @@ msgstr "no se puede asignar a la expresión" msgid "can't convert %q to %q" msgstr "no puede convertir %q a %q" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "no se puede convertir el objeto '%q' a %q implícitamente" @@ -2668,6 +2666,10 @@ msgstr "no se puede convertir el objeto '%q' a %q implícitamente" msgid "can't convert to %q" msgstr "no puede convertir a %q" +#: py/runtime.c +msgid "can't convert to int" +msgstr "no se puede convertir a int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "no se puede convertir a str implícitamente" @@ -3025,7 +3027,7 @@ msgid "f-string: single '}' is not allowed" msgstr "cadena-f: solo '}' no está permitido" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "el archivo deberia ser una archivo abierto en modo byte" @@ -3078,8 +3080,8 @@ msgid "full" msgstr "lleno" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "la función no tiene argumentos por palabra clave" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3133,6 +3135,10 @@ msgstr "generador ya se esta ejecutando" msgid "generator ignored GeneratorExit" msgstr "generador ignorado GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic debe ser 2048 bytes de largo" @@ -3281,6 +3287,10 @@ msgstr "los bits_per_pixel %d no son validos, deben ser 1, 4, 8, 16, 24 o 32" msgid "invalid cert" msgstr "certificado inválido" +#: py/compile.c +msgid "invalid decorator" +msgstr "decorador invalido" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "index dupterm inválido" @@ -3336,10 +3346,6 @@ msgstr "sintaxis inválida para entero con base %d" msgid "invalid syntax for number" msgstr "sintaxis inválida para número" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "io debe ser rtc io" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() arg 1 debe ser una clase" @@ -3516,6 +3522,10 @@ msgstr "yield nativo" msgid "need more than %d values to unpack" msgstr "necesita más de %d valores para descomprimir" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "potencia negativa sin float support" @@ -3748,10 +3758,6 @@ msgstr "palette debe ser 32 bytes de largo" msgid "palette_index should be an int" msgstr "palette_index deberia ser un int" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "parámetro de anotación debe ser un identificador" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "los parámetros deben ser registros en secuencia de a2 a a5" @@ -3806,6 +3812,8 @@ msgstr "pow() con 3 argumentos requiere enteros" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3831,6 +3839,10 @@ msgstr "presionando botón de arranque al inicio.\n" msgid "pressing both buttons at start up.\n" msgstr "presionando ambos botones al inicio.\n" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "presione el botón izquierdo al arranque\n" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "máscara de pull en conflicto con máscara de dirección" @@ -4107,10 +4119,6 @@ msgstr "trapz esta definido para matrices 1D" msgid "trapz is defined for 1D arrays of equal length" msgstr "trapz está definido para arreglos 1D de igual tamaño" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "nivel de accionamiento debe ser 0 o 1" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "tupla/lista tiene una longitud incorrecta" @@ -4192,7 +4200,7 @@ msgstr "formato de código desconocicdo '%c' para objeto de tipo '%q'" msgid "unknown type" msgstr "tipo desconocido" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "tipo desconocido '%q'" @@ -4245,10 +4253,6 @@ msgstr "el valor debe caber en %d byte(s)" msgid "value_count must be > 0" msgstr "value_count debe ser > 0" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "conflicto de wakeup" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "watchdog no inicializado" @@ -4335,6 +4339,48 @@ msgstr "zi debe ser de tipo flotante" msgid "zi must be of shape (n_section, 2)" msgstr "zi debe ser una forma (n_section,2)" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "funciones Viper no soportan por el momento, más de 4 argumentos" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "la dirección %08x no esta alineada a %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "la función no tiene argumentos por palabra clave" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "parámetro de anotación debe ser un identificador" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "" +#~ "Los datos totales a escribir son más grandes que outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IOs 0, 2 y 4 no soportan pullup interno durante sleep" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "buffer debe de ser un objeto bytes-like" + +#~ msgid "io must be rtc io" +#~ msgstr "io debe ser rtc io" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "nivel de accionamiento debe ser 0 o 1" + +#~ msgid "wakeup conflict" +#~ msgstr "conflicto de wakeup" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "" +#~ "Se intentó asignación del montículo, sin que la VM de MicroPython esté " +#~ "ejecutando." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "MicroPython NLR jump falló. Probable corrupción de la memoria." + +#~ msgid "MicroPython fatal error." +#~ msgstr "Error fatal de MicroPython." + #~ msgid "argument must be ndarray" #~ msgstr "argumento debe ser ndarray" @@ -4600,9 +4646,6 @@ msgstr "zi debe ser una forma (n_section,2)" #~ msgid "can't convert to float" #~ msgstr "no se puede convertir a float" -#~ msgid "can't convert to int" -#~ msgstr "no se puede convertir a int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "el objeto '%s' no es una tupla o lista" diff --git a/locale/fil.po b/locale/fil.po index 23d1be9718..aa1badbfaf 100644 --- a/locale/fil.po +++ b/locale/fil.po @@ -441,7 +441,7 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" #: shared-bindings/wifi/Radio.c @@ -890,6 +890,11 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "Ginagamit na ang EXTINT channel" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "May pagkakamali sa REGEX" @@ -1021,6 +1026,10 @@ msgstr "Nabigo sa pagrelease ng mutex, status: 0x%08lX" msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "Mayroong file" @@ -1093,10 +1102,6 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1222,6 +1227,10 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1413,14 +1422,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Ang delay ng startup ng mikropono ay dapat na nasa 0.0 hanggang 1.0" @@ -1472,6 +1473,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1616,6 +1621,7 @@ msgstr "" msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c #, fuzzy @@ -2146,7 +2152,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2320,12 +2326,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" -"Ang mga function ng Viper ay kasalukuyang hindi sumusuporta sa higit sa 4 na " -"argumento" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2411,11 +2411,6 @@ msgstr "a bytes-like object ay kailangan" msgid "abort() called" msgstr "abort() tinawag" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "address %08x ay hindi pantay sa %d bytes" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "wala sa sakop ang address" @@ -2424,6 +2419,10 @@ msgstr "wala sa sakop ang address" msgid "addresses is empty" msgstr "walang laman ang address" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "arg ay walang laman na sequence" @@ -2523,10 +2522,6 @@ msgstr "branch wala sa range" msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "buffer ay dapat bytes-like object" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2612,6 +2607,10 @@ msgstr "hindi ma i-assign sa expression" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "hindi maaaring i-convert ang '%q' na bagay sa %q nang walang pahiwatig" @@ -2620,6 +2619,10 @@ msgstr "hindi maaaring i-convert ang '%q' na bagay sa %q nang walang pahiwatig" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "hindi ma-convert sa int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "hindi ma i-convert sa string ng walang pahiwatig" @@ -2980,7 +2983,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "file ay dapat buksan sa byte mode" @@ -3033,8 +3036,8 @@ msgid "full" msgstr "puno" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "ang function ay hindi kumukuha ng mga argumento ng keyword" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3089,6 +3092,10 @@ msgstr "insinasagawa na ng generator" msgid "generator ignored GeneratorExit" msgstr "hindi pinansin ng generator ang GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic ay dapat 2048 bytes ang haba" @@ -3237,6 +3244,10 @@ msgstr "" msgid "invalid cert" msgstr "mali ang cert" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "mali ang dupterm index" @@ -3292,10 +3303,6 @@ msgstr "maling sintaks sa integer na may base %d" msgid "invalid syntax for number" msgstr "maling sintaks sa number" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() arg 1 ay dapat na class" @@ -3472,6 +3479,10 @@ msgstr "native yield" msgid "need more than %d values to unpack" msgstr "kailangan ng higit sa %d na halaga upang i-unpack" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "negatibong power na walang float support" @@ -3702,10 +3713,6 @@ msgstr "ang palette ay dapat 32 bytes ang haba" msgid "palette_index should be an int" msgstr "palette_index ay dapat na int" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "parameter annotation ay dapat na identifier" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "ang mga parameter ay dapat na nagrerehistro sa sequence a2 hanggang a5" @@ -3761,6 +3768,8 @@ msgstr "pow() na may 3 argumento kailangan ng integers" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3786,6 +3795,10 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "" @@ -4063,10 +4076,6 @@ msgstr "" msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "mali ang haba ng tuple/list" @@ -4148,7 +4157,7 @@ msgstr "" msgid "unknown type" msgstr "hindi malaman ang type (unknown type)" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "hindi malaman ang type '%q'" @@ -4201,10 +4210,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4293,6 +4298,23 @@ msgstr "" msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "" +#~ "Ang mga function ng Viper ay kasalukuyang hindi sumusuporta sa higit sa 4 " +#~ "na argumento" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "address %08x ay hindi pantay sa %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "ang function ay hindi kumukuha ng mga argumento ng keyword" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "parameter annotation ay dapat na identifier" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "buffer ay dapat bytes-like object" + #~ msgid "Group full" #~ msgstr "Puno ang group" @@ -4367,9 +4389,6 @@ msgstr "" #~ msgid "can't convert to float" #~ msgstr "hindi ma-convert sa float" -#~ msgid "can't convert to int" -#~ msgstr "hindi ma-convert sa int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "object '%s' ay hindi tuple o list" diff --git a/locale/fr.po b/locale/fr.po index 19d98f770a..941f877fe4 100644 --- a/locale/fr.po +++ b/locale/fr.po @@ -8,14 +8,14 @@ msgstr "" "Project-Id-Version: 0.1\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2021-04-03 21:57+0000\n" +"PO-Revision-Date: 2021-04-22 17:16+0000\n" "Last-Translator: Hugo Dahl \n" "Language: fr\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=n > 1;\n" -"X-Generator: Weblate 4.6-dev\n" +"X-Generator: Weblate 4.7-dev\n" #: main.c msgid "" @@ -426,7 +426,7 @@ msgstr "'AnalogOut' n'est pas supporté sur la broche indiquée" #: ports/stm/common-hal/audiopwmio/PWMAudioOut.c msgid "Another PWMAudioOut is already active" -msgstr "" +msgstr "Un autre PWMAudioOut est déjà actif" #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c @@ -435,11 +435,11 @@ msgstr "Un autre envoi est déjà actif" #: shared-bindings/pulseio/PulseOut.c msgid "Array must contain halfwords (type 'H')" -msgstr "Le tableau doit contenir des demi-mots (type 'H')" +msgstr "La matrice doit contenir des demi-mots (type 'H')" #: shared-bindings/alarm/SleepMemory.c shared-bindings/nvm/ByteArray.c msgid "Array values should be single bytes." -msgstr "Les valeurs du tableau doivent être des octets singuliers." +msgstr "Les valeurs de la matrice doivent être des octets singuliers." #: shared-bindings/microcontroller/Pin.c msgid "At most %d %q may be specified (not %d)" @@ -451,10 +451,10 @@ msgid "Attempt to allocate %d blocks" msgstr "Tentative d'allocation de %d blocs" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" -"Tentative d'allocation de segments lorsque la machine virtuelle MicroPython " -"n'est pas en cours d'exécution." +"Tentative d'allocation à la pile quand la Machine Virtuelle n'est pas en " +"exécution." #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -911,6 +911,11 @@ msgstr "ESP-IDF échec d'allocation de la mémoire" msgid "EXTINT channel already in use" msgstr "Canal EXTINT déjà utilisé" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "Erreur dans le flot MIDI à la position %d" + #: extmod/modure.c msgid "Error in regex" msgstr "Erreur dans l'expression régulière" @@ -973,7 +978,7 @@ msgstr "La FFT est définie uniquement pour les ndarrays" #: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" -msgstr "FFT n'est implémenté que pour les tableaux linéaires" +msgstr "FFT n'est implémenté que pour les matrices linéaires" #: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" @@ -1014,7 +1019,7 @@ msgstr "Impossible d'allouer la mémoire pour le scan wifi" #: ports/stm/common-hal/audiopwmio/PWMAudioOut.c msgid "Failed to buffer the sample" -msgstr "" +msgstr "Échec du tamponage de l'échantillon" #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" @@ -1041,6 +1046,10 @@ msgstr "Impossible de libérer mutex, err 0x%04x" msgid "Failed to write internal flash." msgstr "Échec de l'écriture vers flash interne." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "Erreurre fatale." + #: py/moduerrno.c msgid "File exists" msgstr "Le fichier existe" @@ -1115,10 +1124,6 @@ msgstr "périphérique I2C utilisé" msgid "I2SOut not available" msgstr "I2SOut n'est pas disponible" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IOs 0, 2 & 4 ne supportent pas l'éleveuse interne en mode someil" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1253,6 +1258,10 @@ msgstr "BSSID invalide" msgid "Invalid DAC pin supplied" msgstr "Broche DAC non valide fournie" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "Fichier MIDI invalide" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1444,14 +1453,6 @@ msgstr "La valeur maximale de x est %d lors d'une opération miroir" msgid "Messages limited to 8 bytes" msgstr "Messages limités à 8 octets" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "Échec du saut MicroPython NLR. Corruption de la mémoire probable." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "Erreur fatale MicroPython." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Le délais au démarrage du micro doit être entre 0.0 et 1.0" @@ -1505,6 +1506,10 @@ msgstr "Doit fournir une broche MISO ou MOSI" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Doit utiliser un multiple de 6 broches RVB, pas %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "Saut NLR échoué. Corruption de mémoire probable." + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "Erreur NVS" @@ -1649,6 +1654,7 @@ msgstr "Logiciel systême Nordic hors de mémoire" msgid "Not a valid IP string" msgstr "Chaîne IP non valide" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2203,9 +2209,8 @@ msgid "Too many displays" msgstr "Trop d'affichages" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" -msgstr "" -"Le nombre total de données à écrire est supérieur à outgoing_packet_length" +msgid "Total data to write is larger than %q" +msgstr "Quantité de données à écrire est plus que %q" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2382,11 +2387,6 @@ msgstr "Longueur de la valeur > max_length" msgid "Version was invalid" msgstr "Version est invalide" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" -"les fonctions de Viper ne supportent pas plus de 4 arguments actuellement" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "La lecture de la tension a expiré" @@ -2475,11 +2475,6 @@ msgstr "un objet 'bytes-like' est requis" msgid "abort() called" msgstr "abort() appelé" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "l'adresse %08x n'est pas alignée sur %d octets" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "adresse hors limites" @@ -2488,17 +2483,21 @@ msgstr "adresse hors limites" msgid "addresses is empty" msgstr "adresses vides" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "l'argument est une séquence vide" #: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" -msgstr "L'argument argsort doit être un ndarray" +msgstr "Le paramêtre argsort doit être un ndarray" #: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" -msgstr "argsort n'est pas mis en œuvre pour les tableaux aplatis" +msgstr "argsort n'est pas mis en œuvre pour les matrices aplatis" #: py/runtime.c msgid "argument has wrong type" @@ -2520,12 +2519,12 @@ msgstr "les paramètres doivent être des ndarrays" #: extmod/ulab/code/ndarray.c msgid "array and index length must be equal" -msgstr "la longueur du tableau et de l'index doivent être égaux" +msgstr "la taille de la matrice et de l'index doivent être égaux" #: py/objarray.c shared-bindings/alarm/SleepMemory.c #: shared-bindings/nvm/ByteArray.c msgid "array/bytes required on right side" -msgstr "tableau/octets requis à droite" +msgstr "matrice/octets requis à la droite" #: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" @@ -2587,10 +2586,6 @@ msgstr "branche hors-bornes" msgid "buffer is smaller than requested size" msgstr "tampon est plus petit que la taille demandée" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "le tampon doit être un objet bytes-like" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "taille du tampon doit être un multiple de la taille de l'élement" @@ -2675,6 +2670,10 @@ msgstr "ne peut pas assigner à une expression" msgid "can't convert %q to %q" msgstr "impossible de convertir %q en %q" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "impossible de convertir l'objet '%q' en '%q' implicitement" @@ -2683,6 +2682,10 @@ msgstr "impossible de convertir l'objet '%q' en '%q' implicitement" msgid "can't convert to %q" msgstr "impossible de convertir en %q" +#: py/runtime.c +msgid "can't convert to int" +msgstr "ne peut convertir en entier 'int'" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "impossible de convertir en chaine 'str' implicitement" @@ -2828,8 +2831,7 @@ msgstr "" #: shared-bindings/displayio/Palette.c msgid "color buffer must be a bytearray or array of type 'b' or 'B'" -msgstr "" -"le tampon de couleur doit être un bytearray ou un tableau de type 'b' ou 'B'" +msgstr "tampon color doit être un bytearray ou une matrice de type 'b' ou 'B'" #: shared-bindings/displayio/Palette.c msgid "color must be between 0x000000 and 0xffffff" @@ -2861,11 +2863,11 @@ msgstr "conversion en objet" #: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" -msgstr "les arguments convolve doivent être des tableaux linéaires" +msgstr "les paramêtres pour convolve doivent être des matrices linéaires" #: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" -msgstr "les arguments convolve doivent être des ndarrays" +msgstr "les paramêtres pour convolve doivent être des ndarrays" #: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" @@ -2881,7 +2883,7 @@ msgstr "impossible de déterminer la version de la carte SD" #: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" -msgstr "cross est défini pour les tableaux 1D de longueur 3" +msgstr "cross est défini pour les matrices 1D de longueur 3" #: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" @@ -2911,12 +2913,13 @@ msgstr "default n'est pas une fonction" msgid "" "destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" msgstr "" -"le tampon de destination doit être un tableau de type 'B' pour bit_depth = 8" +"le tampon de destination doit être une matrice de type 'B' pour bit_depth = 8" #: shared-bindings/audiobusio/PDMIn.c msgid "destination buffer must be an array of type 'H' for bit_depth = 16" msgstr "" -"le tampon de destination doit être un tableau de type 'H' pour bit_depth = 16" +"le tampon de destination doit être une matrice de type 'H' pour bit_depth = " +"16" #: shared-bindings/audiobusio/PDMIn.c msgid "destination_length must be an int >= 0" @@ -2928,7 +2931,7 @@ msgstr "la séquence de mise à jour de dict a une mauvaise longueur" #: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" -msgstr "l'argument diff doit être un ndarray" +msgstr "le paramêtre diff doit être un ndarray" #: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" @@ -3047,7 +3050,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string : single '}' n'est pas autorisé" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "le fichier doit être un fichier ouvert en mode 'byte'" @@ -3065,11 +3068,11 @@ msgstr "le premier argument doit être une fonction" #: extmod/ulab/code/ulab_create.c msgid "first argument must be a tuple of ndarrays" -msgstr "le premier argument doit être un tuple de ndarrays" +msgstr "le premier paramêtre doit être un tuple de ndarrays" #: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" -msgstr "le premier argument doit être un ndarray" +msgstr "le premier paramêtre doit être un ndarray" #: py/objtype.c msgid "first argument to super() must be type" @@ -3081,7 +3084,7 @@ msgstr "l'ordre d'aplatissement doit être «C» ou «F»" #: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" -msgstr "l'argument flip doit être un ndarray" +msgstr "le paramêtre flip doit être un ndarray" #: py/objint.c msgid "float too big" @@ -3100,8 +3103,8 @@ msgid "full" msgstr "plein" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "la fonction ne prend pas d'arguments nommés" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3118,7 +3121,7 @@ msgstr "la fonction a le même signe aux extrémités de l’intervalle" #: extmod/ulab/code/ndarray.c msgid "function is defined for ndarrays only" -msgstr "La fonction n'est définie que pour les ndarrays" +msgstr "fonction définie que pour les ndarrays" #: py/argcheck.c #, c-format @@ -3155,6 +3158,10 @@ msgstr "générateur déjà en cours d'exécution" msgid "generator ignored GeneratorExit" msgstr "le générateur a ignoré GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic doit être long de 2048 octets" @@ -3224,11 +3231,11 @@ msgstr "Paramètre entrant doit être un chiffre entier, un tuple, ou une liste" #: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" -msgstr "la longueur du tableau d'entrée doit être une puissance de 2" +msgstr "longueur de la matrice d'entrée doit être une puissance de 2" #: extmod/ulab/code/ulab_create.c msgid "input arrays are not compatible" -msgstr "les tableaux d'entrée ne sont pas compatibles" +msgstr "les matrices d'entrée ne sont pas compatibles" #: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" @@ -3244,7 +3251,7 @@ msgstr "la matrice d'entrée est singulière" #: extmod/ulab/code/user/user.c msgid "input must be a dense ndarray" -msgstr "l'entrée doit être un tableau dense" +msgstr "l'entrée doit être un ndarray dense" #: extmod/ulab/code/ulab_create.c msgid "input must be a tensor of rank 2" @@ -3284,7 +3291,7 @@ msgstr "entier requis" #: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" -msgstr "interp est défini pour les tableaux 1D de longueur égale" +msgstr "interp est défini pour les matrices 1D de longueur égale" #: shared-bindings/_bleio/Adapter.c #, c-format @@ -3304,6 +3311,10 @@ msgstr "bits_per_pixel %d est invalid, doit être 1, 4, 8, 16, 24 ou 32" msgid "invalid cert" msgstr "certificat invalide" +#: py/compile.c +msgid "invalid decorator" +msgstr "décorateur invalide" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "index invalide pour dupterm" @@ -3359,10 +3370,6 @@ msgstr "syntaxe invalide pour un entier de base %d" msgid "invalid syntax for number" msgstr "syntaxe invalide pour un nombre" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "io doit être rtc io" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "l'argument 1 de issubclass() doit être une classe" @@ -3539,6 +3546,10 @@ msgstr "'yield' natif" msgid "need more than %d values to unpack" msgstr "nécessite plus de %d valeurs à dégrouper" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "puissance négative sans support des nombres à virgule flottante" @@ -3718,11 +3729,11 @@ msgstr "les opérandes ne pouvaient pas être diffusés ensemble" #: extmod/ulab/code/ndarray.c msgid "operation is implemented for 1D Boolean arrays only" -msgstr "opération implémentée que pour des tableaux 1D booléennes" +msgstr "opération implémentée que pour les matrices 1D booléennes" #: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" -msgstr "l'opération n'est pas implémentée sur les ndarrays" +msgstr "l'opération n'est pas implémentée pour les ndarrays" #: extmod/ulab/code/ndarray.c msgid "operation is not supported for given type" @@ -3741,11 +3752,11 @@ msgstr "" #: extmod/ulab/code/utils/utils.c msgid "out array is too small" -msgstr "" +msgstr "matrice de sortie est trop petite" #: extmod/ulab/code/utils/utils.c msgid "out must be a float dense array" -msgstr "" +msgstr "la matrice sortante doit être de type float" #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" @@ -3772,10 +3783,6 @@ msgstr "la palette doit être longue de 32 octets" msgid "palette_index should be an int" msgstr "palette_index devrait être un entier 'int'" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "l'annotation du paramètre doit être un identifiant" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "les paramètres doivent être des registres dans la séquence a2 à a5" @@ -3831,6 +3838,8 @@ msgstr "pow() avec 3 arguments nécessite des entiers" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3856,6 +3865,10 @@ msgstr "bouton boot appuyé lors du démarrage.\n" msgid "pressing both buttons at start up.\n" msgstr "les deux boutons appuyés lors du démarrage.\n" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "appuyer le bouton de gauche au démarage\n" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "masque pull est en conflit avec les masques de direction" @@ -3924,8 +3937,8 @@ msgid "" "sample_source buffer must be a bytearray or array of type 'h', 'H', 'b' or " "'B'" msgstr "" -"le tampon de sample_source doit être un bytearray ou un tableau de type " -"'h','H', 'b' ou 'B'" +"tampon sample_source doit être un bytearray ou une matrice de type 'h', 'H', " +"'b' ou 'B'" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c @@ -3962,7 +3975,7 @@ msgstr "'}' seule rencontrée dans une chaîne de format" #: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" -msgstr "la taille est définie pour les ndarrays uniquement" +msgstr "la taille n'est définie que pour les ndarrays" #: shared-bindings/time/__init__.c msgid "sleep length must be non-negative" @@ -3986,11 +3999,11 @@ msgstr "redémarrage logiciel\n" #: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" -msgstr "l'argument de «sort» doit être un ndarray" +msgstr "le paramètre de «sort» doit être un ndarray" #: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" -msgstr "le tableau sos doit être de forme (n_section, 6)" +msgstr "la matrice sos doit être de forme (n_section, 6)" #: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" @@ -4035,7 +4048,7 @@ msgstr "les indices d'une chaîne doivent être des entiers, pas %q" #: py/stream.c msgid "string not supported; use bytes or bytearray" msgstr "" -"chaîne de carac. non supportée ; utilisez des bytes ou un tableau de bytes" +"chaîne de carac. non supportée; utilisez des bytes ou une matrice de bytes" #: extmod/moductypes.c msgid "struct: cannot index" @@ -4105,7 +4118,7 @@ msgstr "timestamp hors bornes pour 'time_t' de la plateforme" #: extmod/ulab/code/ndarray.c msgid "tobytes can be invoked for dense arrays only" -msgstr "tobytes ne peut être appelé que pour des tableaux dense" +msgstr "tobytes ne peut être appelée que pour des matrices dense" #: shared-module/struct/__init__.c msgid "too many arguments provided with the given format" @@ -4126,15 +4139,11 @@ msgstr "trop de valeur à dégrouper (%d attendues)" #: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" -msgstr "trapz est défini pour tableaux à une dimension" +msgstr "trapz est définie pour matrices à une dimension" #: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" -msgstr "trapz n'est défini que pour des tableaux 1D de longueur égale" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "niveau du déclencheur doit être 0 ou 1" +msgstr "trapz n'est défini que pour des matrices 1D de longueur égales" #: py/obj.c msgid "tuple/list has wrong length" @@ -4217,7 +4226,7 @@ msgstr "code de formatage inconnu '%c' pour objet de type '%q'" msgid "unknown type" msgstr "type inconnu" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "type '%q' inconnu" @@ -4270,10 +4279,6 @@ msgstr "la valeur doit tenir dans %d octet(s)" msgid "value_count must be > 0" msgstr "'value_count' doit être > 0" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "conflit au réveil" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "chien de garde (watchdog) non initialisé" @@ -4350,7 +4355,7 @@ msgstr "'step' nul" #: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" -msgstr "zi doit être ndarray" +msgstr "zi doit être un ndarray" #: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" @@ -4360,6 +4365,49 @@ msgstr "zi doit être de type float" msgid "zi must be of shape (n_section, 2)" msgstr "zi doit être de forme (n_section, 2)" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "" +#~ "les fonctions de Viper ne supportent pas plus de 4 arguments actuellement" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "l'adresse %08x n'est pas alignée sur %d octets" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "la fonction ne prend pas d'arguments nommés" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "l'annotation du paramètre doit être un identifiant" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "" +#~ "Le nombre total de données à écrire est supérieur à outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IOs 0, 2 & 4 ne supportent pas l'éleveuse interne en mode someil" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "le tampon doit être un objet bytes-like" + +#~ msgid "io must be rtc io" +#~ msgstr "io doit être rtc io" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "niveau du déclencheur doit être 0 ou 1" + +#~ msgid "wakeup conflict" +#~ msgstr "conflit au réveil" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "" +#~ "Tentative d'allocation de segments lorsque la machine virtuelle " +#~ "MicroPython n'est pas en cours d'exécution." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "Échec du saut MicroPython NLR. Corruption de la mémoire probable." + +#~ msgid "MicroPython fatal error." +#~ msgstr "Erreur fatale MicroPython." + #~ msgid "argument must be ndarray" #~ msgstr "l'argument doit être un ndarray" @@ -4627,9 +4675,6 @@ msgstr "zi doit être de forme (n_section, 2)" #~ msgid "can't convert to float" #~ msgstr "ne peut convertir en nombre à virgule flottante 'float'" -#~ msgid "can't convert to int" -#~ msgstr "ne peut convertir en entier 'int'" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "l'objet '%s' n'est pas un tuple ou une liste" diff --git a/locale/hi.po b/locale/hi.po index 388a85472b..ff2a0530e5 100644 --- a/locale/hi.po +++ b/locale/hi.po @@ -438,7 +438,7 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" #: shared-bindings/wifi/Radio.c @@ -879,6 +879,11 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "" @@ -1008,6 +1013,10 @@ msgstr "" msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "" @@ -1080,10 +1089,6 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1207,6 +1212,10 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1398,14 +1407,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1457,6 +1458,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1601,6 +1606,7 @@ msgstr "" msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2126,7 +2132,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2298,10 +2304,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2381,11 +2383,6 @@ msgstr "" msgid "abort() called" msgstr "" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "" @@ -2394,6 +2391,10 @@ msgstr "" msgid "addresses is empty" msgstr "" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "" @@ -2493,10 +2494,6 @@ msgstr "" msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2580,6 +2577,10 @@ msgstr "" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "" @@ -2588,6 +2589,10 @@ msgstr "" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2938,7 +2943,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -2991,7 +2996,7 @@ msgid "full" msgstr "" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "" #: py/argcheck.c @@ -3046,6 +3051,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "" @@ -3194,6 +3203,10 @@ msgstr "" msgid "invalid cert" msgstr "" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "" @@ -3249,10 +3262,6 @@ msgstr "" msgid "invalid syntax for number" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "" @@ -3425,6 +3434,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3654,10 +3667,6 @@ msgstr "" msgid "palette_index should be an int" msgstr "" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3712,6 +3721,8 @@ msgstr "" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3737,6 +3748,10 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "" @@ -4010,10 +4025,6 @@ msgstr "" msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "" @@ -4095,7 +4106,7 @@ msgstr "" msgid "unknown type" msgstr "" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "" @@ -4148,10 +4159,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" diff --git a/locale/it_IT.po b/locale/it_IT.po index 241b07d7ec..188e25d16f 100644 --- a/locale/it_IT.po +++ b/locale/it_IT.po @@ -450,8 +450,8 @@ msgid "Attempt to allocate %d blocks" msgstr "Provo ad allocare %d blocchi" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "Provo l'allocazione quando MicroPython VM non è attivo." +msgid "Attempted heap allocation when VM not running." +msgstr "" #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -899,6 +899,11 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "Canale EXTINT già in uso" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "Errore nella regex" @@ -1030,6 +1035,10 @@ msgstr "Impossibile rilasciare il mutex, err 0x%04x" msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "File esistente" @@ -1102,10 +1111,6 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1231,6 +1236,10 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1425,14 +1434,6 @@ msgstr "Valore massimo di x quando rispachiato è %d" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1485,6 +1486,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1629,6 +1634,7 @@ msgstr "" msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c #, fuzzy @@ -2167,7 +2173,7 @@ msgid "Too many displays" msgstr "Troppi schermi" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2341,10 +2347,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Le funzioni Viper non supportano più di 4 argomenti al momento" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2424,11 +2426,6 @@ msgstr "un oggetto byte-like è richiesto" msgid "abort() called" msgstr "abort() chiamato" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "l'indirizzo %08x non è allineato a %d bytes" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "indirizzo fuori limite" @@ -2437,6 +2434,10 @@ msgstr "indirizzo fuori limite" msgid "addresses is empty" msgstr "gli indirizzi sono vuoti" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "l'argomento è una sequenza vuota" @@ -2538,10 +2539,6 @@ msgstr "argomento di chr() non è in range(256)" msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2627,6 +2624,10 @@ msgstr "impossibile assegnare all'espressione" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "impossibile convertire l'oggetto '%q' implicitamente in %q" @@ -2635,6 +2636,10 @@ msgstr "impossibile convertire l'oggetto '%q' implicitamente in %q" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "non è possibile convertire a int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "impossibile convertire a stringa implicitamente" @@ -2991,7 +2996,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -3044,8 +3049,8 @@ msgid "full" msgstr "pieno" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "la funzione non prende argomenti nominati" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3100,6 +3105,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic deve essere lunga 2048 byte" @@ -3248,6 +3257,10 @@ msgstr "" msgid "invalid cert" msgstr "certificato non valido" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "indice dupterm non valido" @@ -3303,10 +3316,6 @@ msgstr "sintassi invalida per l'intero con base %d" msgid "invalid syntax for number" msgstr "sintassi invalida per il numero" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "il primo argomento di issubclass() deve essere una classe" @@ -3484,6 +3493,10 @@ msgstr "yield nativo" msgid "need more than %d values to unpack" msgstr "necessari più di %d valori da scompattare" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "potenza negativa senza supporto per float" @@ -3718,10 +3731,6 @@ msgstr "la palette deve essere lunga 32 byte" msgid "palette_index should be an int" msgstr "palette_index deve essere un int" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "parametri devono essere i registri in sequenza da a2 a a5" @@ -3778,6 +3787,8 @@ msgstr "pow() con 3 argomenti richiede interi" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3803,6 +3814,10 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "" @@ -4080,10 +4095,6 @@ msgstr "" msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "tupla/lista ha la lunghezza sbagliata" @@ -4165,7 +4176,7 @@ msgstr "" msgid "unknown type" msgstr "tipo sconosciuto" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "tipo '%q' sconosciuto" @@ -4218,10 +4229,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4310,6 +4317,18 @@ msgstr "" msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Le funzioni Viper non supportano più di 4 argomenti al momento" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "l'indirizzo %08x non è allineato a %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "la funzione non prende argomenti nominati" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "Provo l'allocazione quando MicroPython VM non è attivo." + #~ msgid "Group full" #~ msgstr "Gruppo pieno" @@ -4384,9 +4403,6 @@ msgstr "" #~ msgid "can't convert to float" #~ msgstr "non è possibile convertire a float" -#~ msgid "can't convert to int" -#~ msgstr "non è possibile convertire a int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "oggetto '%s' non è una tupla o una lista" diff --git a/locale/ja.po b/locale/ja.po index e2b5d926af..0d3e93d1c2 100644 --- a/locale/ja.po +++ b/locale/ja.po @@ -443,8 +443,8 @@ msgid "Attempt to allocate %d blocks" msgstr "%d個のブロックの確保を試みました" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "MicroPython VMの非実行時にヒープ確保を試みました" +msgid "Attempted heap allocation when VM not running." +msgstr "" #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -890,6 +890,11 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "EXTINTチャネルはすでに使用されています" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "正規表現にエラーがあります" @@ -1019,6 +1024,10 @@ msgstr "ミューテックスの開放に失敗。エラー 0x%04x" msgid "Failed to write internal flash." msgstr "内部フラッシュ書き込みに失敗" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "ファイルが存在します" @@ -1091,10 +1100,6 @@ msgstr "" msgid "I2SOut not available" msgstr "I2SOutが利用できません" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1220,6 +1225,10 @@ msgstr "不正なBSSID" msgid "Invalid DAC pin supplied" msgstr "不正なDACピンが与えられました" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1411,14 +1420,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "MicroPython NLRジャンプ失敗。メモリ破壊の可能性あり" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "MicroPython致命的エラー" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "マイクのスタートアップディレイは 0.0 から 1.0 の間でなければなりません" @@ -1470,6 +1471,10 @@ msgstr "MISOピンまたはMOSIピンが必要" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "%d個でなく6の倍数個のrgbピンを使ってください" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1614,6 +1619,7 @@ msgstr "" msgid "Not a valid IP string" msgstr "不正なIP文字列です" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2148,7 +2154,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2321,10 +2327,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "電圧読み取りがタイムアウト" @@ -2404,11 +2406,6 @@ msgstr "bytes-likeオブジェクトが必要" msgid "abort() called" msgstr "abort()が呼ばれました" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "アドレスが範囲外" @@ -2417,6 +2414,10 @@ msgstr "アドレスが範囲外" msgid "addresses is empty" msgstr "" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "" @@ -2516,10 +2517,6 @@ msgstr "" msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "バッファはbytes-likeオブジェクトでなければなりません" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2603,6 +2600,10 @@ msgstr "式には代入できません" msgid "can't convert %q to %q" msgstr "%qを%qに変換できません" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "オブジェクト '%q' を %q に暗黙に変換できません" @@ -2611,6 +2612,10 @@ msgstr "オブジェクト '%q' を %q に暗黙に変換できません" msgid "can't convert to %q" msgstr "%q に変換できません" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2965,7 +2970,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string: 1つだけの'}'は許されません" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "fileはバイトモードで開かれたファイルでなければなりません" @@ -3018,7 +3023,7 @@ msgid "full" msgstr "" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "" #: py/argcheck.c @@ -3073,6 +3078,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphicは2048バイトでなければなりません" @@ -3222,6 +3231,10 @@ msgstr "" msgid "invalid cert" msgstr "不正な証明書" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "不正なduptermインデクス" @@ -3277,10 +3290,6 @@ msgstr "" msgid "invalid syntax for number" msgstr "数字として不正な構文" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass()の第1引数はクラスでなければなりません" @@ -3453,6 +3462,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "アンパックする値は%d個では足りません" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3682,10 +3695,6 @@ msgstr "パレットの長さは32バイトでなければなりません" msgid "palette_index should be an int" msgstr "palette_indexには整数が必要" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "引数アノテーションは識別子でなければなりません" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3742,6 +3751,8 @@ msgstr "pow()の第3引数には整数が必要" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3767,6 +3778,10 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "" @@ -4041,10 +4056,6 @@ msgstr "" msgid "trapz is defined for 1D arrays of equal length" msgstr "trapzは同じ長さの1次元arrayに対して定義されています" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "タプル/リストの長さが正しくありません" @@ -4126,7 +4137,7 @@ msgstr "型'%q'のオブジェクトに対する不明な書式コード'%c'" msgid "unknown type" msgstr "不明な型" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "不明な型 '%q'" @@ -4179,10 +4190,6 @@ msgstr "値は%dバイトに収まらなければなりません" msgid "value_count must be > 0" msgstr "value_countは0より大きくなければなりません" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4269,6 +4276,21 @@ msgstr "ziはfloat値でなければなりません" msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "引数アノテーションは識別子でなければなりません" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "バッファはbytes-likeオブジェクトでなければなりません" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "MicroPython VMの非実行時にヒープ確保を試みました" + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "MicroPython NLRジャンプ失敗。メモリ破壊の可能性あり" + +#~ msgid "MicroPython fatal error." +#~ msgstr "MicroPython致命的エラー" + #~ msgid "argument must be ndarray" #~ msgstr "引数はndarrayでなければなりません" diff --git a/locale/ko.po b/locale/ko.po index 3b8eeebe6d..7adda96b93 100644 --- a/locale/ko.po +++ b/locale/ko.po @@ -439,7 +439,7 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" #: shared-bindings/wifi/Radio.c @@ -882,6 +882,11 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "Regex에 오류가 있습니다." @@ -1011,6 +1016,10 @@ msgstr "" msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "" @@ -1083,10 +1092,6 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1210,6 +1215,10 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1401,14 +1410,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1460,6 +1461,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1604,6 +1609,7 @@ msgstr "" msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2129,7 +2135,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2302,10 +2308,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2385,11 +2387,6 @@ msgstr "" msgid "abort() called" msgstr "" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "" @@ -2398,6 +2395,10 @@ msgstr "" msgid "addresses is empty" msgstr "" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "" @@ -2497,10 +2498,6 @@ msgstr "" msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2584,6 +2581,10 @@ msgstr "" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "" @@ -2592,6 +2593,10 @@ msgstr "" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2942,7 +2947,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -2995,7 +3000,7 @@ msgid "full" msgstr "완전한(full)" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "" #: py/argcheck.c @@ -3050,6 +3055,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "" @@ -3198,6 +3207,10 @@ msgstr "" msgid "invalid cert" msgstr "cert가 유효하지 않습니다" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "Dupterm index가 유효하지 않습니다" @@ -3253,10 +3266,6 @@ msgstr "구문(syntax)가 정수가 유효하지 않습니다" msgid "invalid syntax for number" msgstr "숫자에 대한 구문(syntax)가 유효하지 않습니다" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "" @@ -3429,6 +3438,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3658,10 +3671,6 @@ msgstr "" msgid "palette_index should be an int" msgstr "" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3716,6 +3725,8 @@ msgstr "" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3741,6 +3752,10 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "" @@ -4014,10 +4029,6 @@ msgstr "" msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "" @@ -4099,7 +4110,7 @@ msgstr "" msgid "unknown type" msgstr "" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "" @@ -4152,10 +4163,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" diff --git a/locale/nl.po b/locale/nl.po index 3285f52150..abc7a00a57 100644 --- a/locale/nl.po +++ b/locale/nl.po @@ -441,8 +441,8 @@ msgid "Attempt to allocate %d blocks" msgstr "Poging om %d blokken toe te wijzen" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "heap allocatie geprobeerd terwijl MicroPython VM niet draait." +msgid "Attempted heap allocation when VM not running." +msgstr "" #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -890,6 +890,11 @@ msgstr "ESP-IDF geheugen toewijzing mislukt" msgid "EXTINT channel already in use" msgstr "EXTINT kanaal al in gebruik" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "Fout in regex" @@ -1019,6 +1024,10 @@ msgstr "Mislukt mutex los te laten, err 0x%04x" msgid "Failed to write internal flash." msgstr "Schrijven naar interne flash mislukt." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "Bestand bestaat" @@ -1092,10 +1101,6 @@ msgstr "" msgid "I2SOut not available" msgstr "I2SOut is niet beschikbaar" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IO's 0, 2 en 4 ondersteunen geen interne pullup in slaapstand" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1221,6 +1226,10 @@ msgstr "Ongeldig BSSID" msgid "Invalid DAC pin supplied" msgstr "Ongeldige DAC pin opgegeven" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1412,14 +1421,6 @@ msgstr "Maximale x waarde indien gespiegeld is %d" msgid "Messages limited to 8 bytes" msgstr "Berichten zijn beperkt tot 8 bytes" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "MicroPython NLR sprong mislukt. Waarschijnlijk geheugen corruptie." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "MicroPython fatale fout." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Microfoon opstart vertraging moet in bereik van 0.0 tot 1.0 zijn" @@ -1471,6 +1472,10 @@ msgstr "MISO of MOSI moeten worden gegeven" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Een meervoud van 6 rgb pinnen moet worden gebruikt, niet %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "NVS-fout" @@ -1615,6 +1620,7 @@ msgstr "" msgid "Not a valid IP string" msgstr "Geen geldige IP string" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2166,8 +2172,8 @@ msgid "Too many displays" msgstr "Teveel beeldschermen" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" -msgstr "Totale data om te schrijven is groter dan outgoing_packet_length" +msgid "Total data to write is larger than %q" +msgstr "" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2340,10 +2346,6 @@ msgstr "Waarde length > max_length" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Viper-functies ondersteunen momenteel niet meer dan 4 argumenten" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "Voltage lees time-out" @@ -2432,11 +2434,6 @@ msgstr "een bytes-achtig object is vereist" msgid "abort() called" msgstr "abort() aangeroepen" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "adres %08x is niet afgestemd op %d bytes" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "adres buiten bereik" @@ -2445,6 +2442,10 @@ msgstr "adres buiten bereik" msgid "addresses is empty" msgstr "adressen zijn leeg" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "arg is een lege sequentie" @@ -2544,10 +2545,6 @@ msgstr "pad (branch) niet binnen bereik" msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "buffer moet een byte-achtig object zijn" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2632,6 +2629,10 @@ msgstr "kan niet toewijzen aan expressie" msgid "can't convert %q to %q" msgstr "kan %q niet naar %q converteren" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "kan '%q' object niet omzetten naar %q impliciet" @@ -2640,6 +2641,10 @@ msgstr "kan '%q' object niet omzetten naar %q impliciet" msgid "can't convert to %q" msgstr "kan niet naar %q converteren" +#: py/runtime.c +msgid "can't convert to int" +msgstr "kan niet omzetten naar int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "kan niet omzetten naar str impliciet" @@ -2993,7 +2998,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string: enkele '}' is niet toegestaan" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "bestand moet een bestand zijn geopend in byte modus" @@ -3046,8 +3051,8 @@ msgid "full" msgstr "vol" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "functie accepteert geen keyword argumenten" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3102,6 +3107,10 @@ msgstr "generator wordt al uitgevoerd" msgid "generator ignored GeneratorExit" msgstr "generator negeerde GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic moet 2048 bytes lang zijn" @@ -3250,6 +3259,10 @@ msgstr "" msgid "invalid cert" msgstr "ongeldig certificaat" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "ongeldige dupterm index" @@ -3305,10 +3318,6 @@ msgstr "ongeldige syntax voor integer met grondtal %d" msgid "invalid syntax for number" msgstr "ongeldige syntax voor nummer" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "io moet rtc io zijn" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() argument 1 moet een klasse zijn" @@ -3484,6 +3493,10 @@ msgstr "natuurlijke opbrengst (native yield)" msgid "need more than %d values to unpack" msgstr "Om uit te pakken zijn meer dan %d waarden vereist" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "negatieve macht terwijl er geen ondersteuning is voor float" @@ -3713,10 +3726,6 @@ msgstr "palette moet 32 bytes lang zijn" msgid "palette_index should be an int" msgstr "palette_index moet een int zijn" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "parameter annotatie moet een identifier zijn" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "parameters moeten registers zijn in de volgorde a2 tot a5" @@ -3772,6 +3781,8 @@ msgstr "pow() met 3 argumenten vereist integers" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3797,6 +3808,10 @@ msgstr "druk bootknop in bij opstarten.\n" msgid "pressing both buttons at start up.\n" msgstr "druk beide knoppen in bij opstarten.\n" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "" @@ -4072,10 +4087,6 @@ msgstr "" msgid "trapz is defined for 1D arrays of equal length" msgstr "trapz is gedefinieerd voor eendimensionale arrays van gelijke lengte" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "triggerniveau moet 0 of 1 zijn" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "tuple of lijst heeft onjuiste lengte" @@ -4157,7 +4168,7 @@ msgstr "onbekende formaatcode '%c' voor object van type '%q'" msgid "unknown type" msgstr "onbekend type" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "onbekend type '%q'" @@ -4210,10 +4221,6 @@ msgstr "waarde moet in %d byte(s) passen" msgid "value_count must be > 0" msgstr "value_count moet groter dan 0 zijn" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "conflict bij ontwaken" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "watchdog niet geïnitialiseerd" @@ -4300,6 +4307,45 @@ msgstr "zi moet van type float zijn" msgid "zi must be of shape (n_section, 2)" msgstr "zi moet vorm (n_section, 2) hebben" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Viper-functies ondersteunen momenteel niet meer dan 4 argumenten" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "adres %08x is niet afgestemd op %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "functie accepteert geen keyword argumenten" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "parameter annotatie moet een identifier zijn" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "Totale data om te schrijven is groter dan outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IO's 0, 2 en 4 ondersteunen geen interne pullup in slaapstand" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "buffer moet een byte-achtig object zijn" + +#~ msgid "io must be rtc io" +#~ msgstr "io moet rtc io zijn" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "triggerniveau moet 0 of 1 zijn" + +#~ msgid "wakeup conflict" +#~ msgstr "conflict bij ontwaken" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "heap allocatie geprobeerd terwijl MicroPython VM niet draait." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "MicroPython NLR sprong mislukt. Waarschijnlijk geheugen corruptie." + +#~ msgid "MicroPython fatal error." +#~ msgstr "MicroPython fatale fout." + #~ msgid "argument must be ndarray" #~ msgstr "argument moet ndarray zijn" @@ -4543,9 +4589,6 @@ msgstr "zi moet vorm (n_section, 2) hebben" #~ msgid "can't convert to float" #~ msgstr "kan niet omzetten naar float" -#~ msgid "can't convert to int" -#~ msgstr "kan niet omzetten naar int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "object '%s' is geen tuple of lijst" diff --git a/locale/pl.po b/locale/pl.po index 295901c994..1fbc6e4e34 100644 --- a/locale/pl.po +++ b/locale/pl.po @@ -443,8 +443,8 @@ msgid "Attempt to allocate %d blocks" msgstr "Próba przydzielenia %d bloków" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "Próba przydziału sterty, gdy MicroPython VM nie działa." +msgid "Attempted heap allocation when VM not running." +msgstr "" #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -890,6 +890,11 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "Kanał EXTINT w użyciu" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "Błąd w regex" @@ -1019,6 +1024,10 @@ msgstr "Nie udało się zwolnić blokady, błąd 0x%04x" msgid "Failed to write internal flash." msgstr "Nie udało się zapisać wewnętrznej pamięci flash." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "Plik istnieje" @@ -1091,10 +1100,6 @@ msgstr "" msgid "I2SOut not available" msgstr "I2SOut niedostępne" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1220,6 +1225,10 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1411,15 +1420,6 @@ msgstr "Największa wartość x przy odwróceniu to %d" msgid "Messages limited to 8 bytes" msgstr "Wiadomości ograniczone do 8 bajtów" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" -"Skok MicroRython NLR nie powiódł się. Prawdopodobne uszkodzenie pamięci." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "Błąd krytyczny MicroPython." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Opóźnienie włączenia mikrofonu musi być w zakresie od 0.0 do 1.0" @@ -1471,6 +1471,10 @@ msgstr "Należy podać pin MISO lub MOSI" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1615,6 +1619,7 @@ msgstr "" msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2140,7 +2145,7 @@ msgid "Too many displays" msgstr "Zbyt wiele wyświetlaczy" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2312,10 +2317,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Funkcje Viper nie obsługują obecnie więcej niż 4 argumentów" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2401,11 +2402,6 @@ msgstr "wymagany obiekt typu bytes" msgid "abort() called" msgstr "Wywołano abort()" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "adres %08x nie jest wyrównany do %d bajtów" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "adres poza zakresem" @@ -2414,6 +2410,10 @@ msgstr "adres poza zakresem" msgid "addresses is empty" msgstr "adres jest pusty" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "arg jest puste" @@ -2513,10 +2513,6 @@ msgstr "skok poza zakres" msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "bufor mysi być typu bytes" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2600,6 +2596,10 @@ msgstr "przypisanie do wyrażenia" msgid "can't convert %q to %q" msgstr "nie można dokonać konwersji %q na %q" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "nie można automatycznie skonwertować '%q' do '%q'" @@ -2608,6 +2608,10 @@ msgstr "nie można automatycznie skonwertować '%q' do '%q'" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "nie można skonwertować do int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "nie można automatycznie skonwertować do str" @@ -2959,7 +2963,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "file musi być otwarte w trybie bajtowym" @@ -3012,8 +3016,8 @@ msgid "full" msgstr "pełny" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "funkcja nie bierze argumentów nazwanych" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3067,6 +3071,10 @@ msgstr "generator już się wykonuje" msgid "generator ignored GeneratorExit" msgstr "generator zignorował GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic musi mieć 2048 bajtów długości" @@ -3215,6 +3223,10 @@ msgstr "" msgid "invalid cert" msgstr "zły ceryfikat" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "zły indeks dupterm" @@ -3270,10 +3282,6 @@ msgstr "zła składnia dla liczby całkowitej w bazie %d" msgid "invalid syntax for number" msgstr "zła składnia dla liczby" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "argument 1 dla issubclass() musi być klasą" @@ -3446,6 +3454,10 @@ msgstr "natywny yield" msgid "need more than %d values to unpack" msgstr "potrzeba więcej niż %d do rozpakowania" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "ujemna potęga, ale brak obsługi liczb zmiennoprzecinkowych" @@ -3675,10 +3687,6 @@ msgstr "paleta musi mieć 32 bajty długości" msgid "palette_index should be an int" msgstr "palette_index powinien być całkowity" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "anotacja parametru musi być identyfikatorem" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "parametry muszą być rejestrami w kolejności a2 do a5" @@ -3734,6 +3742,8 @@ msgstr "trzyargumentowe pow() wymaga liczb całkowitych" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3759,6 +3769,10 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "" @@ -4033,10 +4047,6 @@ msgstr "" msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "krotka/lista ma złą długość" @@ -4118,7 +4128,7 @@ msgstr "" msgid "unknown type" msgstr "zły typ" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "zły typ '%q'" @@ -4171,10 +4181,6 @@ msgstr "wartość musi mieścić się w %d bajtach" msgid "value_count must be > 0" msgstr "value_count musi być > 0" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4261,6 +4267,31 @@ msgstr "" msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Funkcje Viper nie obsługują obecnie więcej niż 4 argumentów" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "adres %08x nie jest wyrównany do %d bajtów" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "funkcja nie bierze argumentów nazwanych" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "anotacja parametru musi być identyfikatorem" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "bufor mysi być typu bytes" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "Próba przydziału sterty, gdy MicroPython VM nie działa." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "" +#~ "Skok MicroRython NLR nie powiódł się. Prawdopodobne uszkodzenie pamięci." + +#~ msgid "MicroPython fatal error." +#~ msgstr "Błąd krytyczny MicroPython." + #~ msgid "vectors must have same lengths" #~ msgstr "wektory muszą mieć identyczną długość" @@ -4389,9 +4420,6 @@ msgstr "" #~ msgid "can't convert to float" #~ msgstr "nie można skonwertować do float" -#~ msgid "can't convert to int" -#~ msgstr "nie można skonwertować do int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "obiekt '%s' nie jest krotką ani listą" diff --git a/locale/pt_BR.po b/locale/pt_BR.po index 19a27387a1..e3a9e6675e 100644 --- a/locale/pt_BR.po +++ b/locale/pt_BR.po @@ -6,7 +6,7 @@ msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2021-04-05 22:35+0000\n" +"PO-Revision-Date: 2021-04-22 17:16+0000\n" "Last-Translator: Wellington Terumi Uemura \n" "Language-Team: \n" "Language: pt_BR\n" @@ -14,7 +14,7 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=n > 1;\n" -"X-Generator: Weblate 4.6-dev\n" +"X-Generator: Weblate 4.7-dev\n" #: main.c msgid "" @@ -426,7 +426,7 @@ msgstr "Saída analógica não suportada no pino fornecido" #: ports/stm/common-hal/audiopwmio/PWMAudioOut.c msgid "Another PWMAudioOut is already active" -msgstr "" +msgstr "Um outro PWMAudioOut já está ativo" #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c @@ -451,10 +451,9 @@ msgid "Attempt to allocate %d blocks" msgstr "Tentativa de alocar %d blocos" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" -"A tentativa da área de alocação dinâmica de variáveis (heap) quando o " -"MicroPython VM não está em execução." +"Tentativa de alocação das pilhas quando o VM não estiver em funcionamento." #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -908,6 +907,11 @@ msgstr "Houve uma falha na alocação da memória ESP-IDF" msgid "EXTINT channel already in use" msgstr "Canal EXTINT em uso" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "Houve um erro no fluxo MIDI na posição %d" + #: extmod/modure.c msgid "Error in regex" msgstr "Erro no regex" @@ -1010,7 +1014,7 @@ msgstr "Houve uma falha na alocação da memória para a varredura do Wifi" #: ports/stm/common-hal/audiopwmio/PWMAudioOut.c msgid "Failed to buffer the sample" -msgstr "" +msgstr "Houve uma falha ao fazer uma memória prévia (buffer) da amostra" #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" @@ -1037,6 +1041,10 @@ msgstr "Houve uma falha ao liberar o mutex, err 0x%04x" msgid "Failed to write internal flash." msgstr "Falha ao gravar o flash interno." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "Erro fatal." + #: py/moduerrno.c msgid "File exists" msgstr "Arquivo já existe" @@ -1110,10 +1118,6 @@ msgstr "Periférico I2C em uso" msgid "I2SOut not available" msgstr "O I2SOut não está disponível" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IOs 0, 2 e 4 não suportam pullup interno em repouso (sleep)" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1245,6 +1249,10 @@ msgstr "BSSID Inválido" msgid "Invalid DAC pin supplied" msgstr "O pino DAC informado é inválido" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "O arquivo MIDI é inválido" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1436,14 +1444,6 @@ msgstr "O valor máximo de x quando espelhado é %d" msgid "Messages limited to 8 bytes" msgstr "As mensagens estão limitadas a 8 bytes" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "O salto do MicroPython NLR falhou. Possível corrupção de memória." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "Houve um erro fatal do MicroPython." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "O atraso na inicialização do microfone deve estar entre 0,0 e 1,0" @@ -1495,6 +1495,10 @@ msgstr "Deve informar os pinos MISO ou MOSI" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Deve utilizar um múltiplo de 6 pinos rgb, não %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "O salto NLR falhou. Possível corrupção da memória." + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "Erro NVS" @@ -1641,6 +1645,7 @@ msgstr "O firmware do sistema nórdico está sem memória" msgid "Not a valid IP string" msgstr "Não é uma sequência válida de IP" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2199,9 +2204,8 @@ msgid "Too many displays" msgstr "Exibições demais" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" -msgstr "" -"O total dos dados que serão gravados é maior que outgoing_packet_length" +msgid "Total data to write is larger than %q" +msgstr "O total dos dados que serão escritos é maior do que %q" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2374,10 +2378,6 @@ msgstr "O comprimento do valor é > max_length" msgid "Version was invalid" msgstr "A versão era inválida" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Atualmente, as funções do Viper não suportam mais de 4 argumentos" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "O tempo limite de leitura da tensão expirou" @@ -2467,11 +2467,6 @@ msgstr "é necessário objetos tipo bytes" msgid "abort() called" msgstr "abort() chamado" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "endereço %08x não está alinhado com %d bytes" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "endereço fora dos limites" @@ -2480,6 +2475,10 @@ msgstr "endereço fora dos limites" msgid "addresses is empty" msgstr "os endereços estão vazios" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "o arg é uma sequência vazia" @@ -2579,10 +2578,6 @@ msgstr "ramo fora do alcance" msgid "buffer is smaller than requested size" msgstr "o tamanho do buffer é menor do que o tamanho que foi solicitado" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "o buffer deve ser um objeto como bytes" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "o tamanho do buffer deve ser um múltiplo do tamanho do elemento" @@ -2666,6 +2661,10 @@ msgstr "a expressão não pode ser atribuída" msgid "can't convert %q to %q" msgstr "não é possível converter %q para %q" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "não é possível converter implicitamente o objeto '%q' para %q" @@ -2674,6 +2673,10 @@ msgstr "não é possível converter implicitamente o objeto '%q' para %q" msgid "can't convert to %q" msgstr "não é possível converter para %q" +#: py/runtime.c +msgid "can't convert to int" +msgstr "não é possível converter para int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "não é possível converter implicitamente para str" @@ -3033,7 +3036,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string: um único '}' não é permitido" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "o arquivo deve ser um arquivo aberto no modo byte" @@ -3086,8 +3089,8 @@ msgid "full" msgstr "cheio" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "função não aceita argumentos de palavras-chave" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3141,6 +3144,10 @@ msgstr "o gerador já está em execução" msgid "generator ignored GeneratorExit" msgstr "ignorando o gerador GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "o gráfico deve ter 2048 bytes de comprimento" @@ -3290,6 +3297,10 @@ msgstr "bits_per_pixel %d é inválido, deve ser, 1, 4, 8, 16, 24, ou 32" msgid "invalid cert" msgstr "certificado inválido" +#: py/compile.c +msgid "invalid decorator" +msgstr "decorador inválido" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "Índice de dupterm inválido" @@ -3345,10 +3356,6 @@ msgstr "sintaxe inválida para o número inteiro com base %d" msgid "invalid syntax for number" msgstr "sintaxe inválida para o número" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "O io deve ser rtc io" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() arg 1 deve ser uma classe" @@ -3526,6 +3533,10 @@ msgstr "rendimento nativo" msgid "need more than %d values to unpack" msgstr "precisa de mais de %d valores para desempacotar" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "potência negativa sem suporte de flutuação" @@ -3760,10 +3771,6 @@ msgstr "a paleta deve ter 32 bytes de comprimento" msgid "palette_index should be an int" msgstr "palette_index deve ser um int" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "a anotação do parâmetro deve ser um identificador" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "os parâmetros devem ser registradores na sequência a2 até a5" @@ -3818,6 +3825,8 @@ msgstr "o pow() com 3 argumentos requer números inteiros" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3843,6 +3852,10 @@ msgstr "pressionando o botão de boot na inicialização.\n" msgid "pressing both buttons at start up.\n" msgstr "pressionando ambos os botões durante a inicialização.\n" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "pressionando o botão esquerdo durante a inicialização\n" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "puxe as máscaras em conflito com as máscaras de direção" @@ -4118,10 +4131,6 @@ msgstr "Trapz está definido para arrays 1D" msgid "trapz is defined for 1D arrays of equal length" msgstr "o trapz está definido para 1D arrays de igual tamanho" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "nível do gatilho deve ser 0 ou 1" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "a tupla/lista está com tamanho incorreto" @@ -4203,7 +4212,7 @@ msgstr "o formato do código '%c' é desconhecido para o objeto do tipo '%q'" msgid "unknown type" msgstr "tipo desconhecido" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "tipo desconhecido '%q'" @@ -4256,10 +4265,6 @@ msgstr "o valor deve caber em %d byte(s)" msgid "value_count must be > 0" msgstr "o value_count deve ser > 0" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "conflito de wakeup" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "o watchdog não foi inicializado" @@ -4346,6 +4351,48 @@ msgstr "zi deve ser de um tipo float" msgid "zi must be of shape (n_section, 2)" msgstr "zi deve estar na forma (n_section, 2)" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Atualmente, as funções do Viper não suportam mais de 4 argumentos" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "endereço %08x não está alinhado com %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "função não aceita argumentos de palavras-chave" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "a anotação do parâmetro deve ser um identificador" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "" +#~ "O total dos dados que serão gravados é maior que outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IOs 0, 2 e 4 não suportam pullup interno em repouso (sleep)" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "o buffer deve ser um objeto como bytes" + +#~ msgid "io must be rtc io" +#~ msgstr "O io deve ser rtc io" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "nível do gatilho deve ser 0 ou 1" + +#~ msgid "wakeup conflict" +#~ msgstr "conflito de wakeup" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "" +#~ "A tentativa da área de alocação dinâmica de variáveis (heap) quando o " +#~ "MicroPython VM não está em execução." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "O salto do MicroPython NLR falhou. Possível corrupção de memória." + +#~ msgid "MicroPython fatal error." +#~ msgstr "Houve um erro fatal do MicroPython." + #~ msgid "argument must be ndarray" #~ msgstr "o argumento deve ser ndarray" @@ -4638,9 +4685,6 @@ msgstr "zi deve estar na forma (n_section, 2)" #~ msgid "can't convert to float" #~ msgstr "não é possível converter para float" -#~ msgid "can't convert to int" -#~ msgstr "não é possível converter para int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "o objeto '%s' não é uma tupla ou uma lista" diff --git a/locale/sv.po b/locale/sv.po index 5feb28845d..29d7e22ca2 100644 --- a/locale/sv.po +++ b/locale/sv.po @@ -6,7 +6,7 @@ msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2021-04-06 14:41+0000\n" +"PO-Revision-Date: 2021-04-23 12:37+0000\n" "Last-Translator: Jonny Bergdahl \n" "Language-Team: LANGUAGE \n" "Language: sv\n" @@ -14,7 +14,7 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=n != 1;\n" -"X-Generator: Weblate 4.6-dev\n" +"X-Generator: Weblate 4.7-dev\n" #: main.c msgid "" @@ -446,8 +446,8 @@ msgid "Attempt to allocate %d blocks" msgstr "Försök att tilldela %d block" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "Försökte tilldela heap när MicroPython VM inte körs." +msgid "Attempted heap allocation when VM not running." +msgstr "Försök till heap-allokering när den virtuella maskinen inte är igång." #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -896,6 +896,11 @@ msgstr "ESP-IDF-minnetilldelning misslyckades" msgid "EXTINT channel already in use" msgstr "EXTINT-kanalen används redan" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "Fel i MIDI-ström vid position %d" + #: extmod/modure.c msgid "Error in regex" msgstr "Fel i regex" @@ -1025,6 +1030,10 @@ msgstr "Det gick inte att frigöra mutex, fel 0x%04x" msgid "Failed to write internal flash." msgstr "Det gick inte att skriva till intern flash." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "Fatalt fel." + #: py/moduerrno.c msgid "File exists" msgstr "Filen finns redan" @@ -1097,10 +1106,6 @@ msgstr "I2C-enhet används redan" msgid "I2SOut not available" msgstr "I2SOut är inte tillgängligt" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IO 0, 2 & 4 stöder inte intern pullup för sovläge" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1228,6 +1233,10 @@ msgstr "Ogiltig BSSID" msgid "Invalid DAC pin supplied" msgstr "Ogiltig DAC-pinne angiven" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "Ogiltig MIDI-fil" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1419,14 +1428,6 @@ msgstr "Maximum x-värde vid spegling är %d" msgid "Messages limited to 8 bytes" msgstr "Meddelanden begränsad till 8 byte" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "MicroPython NLR jump misslyckades. Troligen korrupt minne." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "MicroPython fatalt fel." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1479,6 +1480,10 @@ msgstr "Måste ange MISO- eller MOSI-pinne" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Måste använda ett multipel av 6 rgb-pinnar, inte %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "NLR jump misslyckades. Troligen korrupt minne." + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "NVS-fel" @@ -1623,6 +1628,7 @@ msgstr "Nordic systemfirmware fick slut på minne" msgid "Not a valid IP string" msgstr "Inte en giltig IP-sträng" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2172,8 +2178,8 @@ msgid "Too many displays" msgstr "För många displayer" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" -msgstr "Total data som ska skrivas är större än outgoing_packet_length" +msgid "Total data to write is larger than %q" +msgstr "Totala data att skriva är större än %q" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2346,10 +2352,6 @@ msgstr "Värdets längd > max_length" msgid "Version was invalid" msgstr "Versionen var ogiltig" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Viper-funktioner stöder för närvarande inte mer än fyra argument" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "Avläsning av spänning tog för lång tid" @@ -2435,11 +2437,6 @@ msgstr "ett bytesliknande objekt krävs" msgid "abort() called" msgstr "abort() anropad" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "adressen %08x är inte justerad till %d byte" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "adress utanför gränsen" @@ -2448,6 +2445,10 @@ msgstr "adress utanför gränsen" msgid "addresses is empty" msgstr "adresserna är tomma" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "Annoteringen måste vara en identifierare" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "arg är en tom sekvens" @@ -2547,10 +2548,6 @@ msgstr "branch utanför räckvidd" msgid "buffer is smaller than requested size" msgstr "bufferten är mindre än begärd storlek" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "buffer måste vara en byte-liknande objekt" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "buffertstorlek måste vara en multipel av elementstorlek" @@ -2634,6 +2631,10 @@ msgstr "kan inte tilldela uttryck" msgid "can't convert %q to %q" msgstr "kan inte konvertera %q till %q" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "kan inte konvertera %q till int" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "kan inte konvertera '%q' objekt implicit till %q" @@ -2642,6 +2643,10 @@ msgstr "kan inte konvertera '%q' objekt implicit till %q" msgid "can't convert to %q" msgstr "kan inte konvertera till %q" +#: py/runtime.c +msgid "can't convert to int" +msgstr "kan inte konvertera till int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "kan inte implicit konvertera till str" @@ -2997,7 +3002,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string: singel '}' är inte tillåten" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "filen måste vara en fil som öppnats i byte-läge" @@ -3050,7 +3055,7 @@ msgid "full" msgstr "full" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "funktionen tar inte nyckelordsargument" #: py/argcheck.c @@ -3105,6 +3110,10 @@ msgstr "generatorn kör redan" msgid "generator ignored GeneratorExit" msgstr "generatorn ignorerade GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "generator kastade StopIteration" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic måste vara 2048 byte lång" @@ -3253,6 +3262,10 @@ msgstr "ogiltig bits_per_pixel %d, måste vara 1, 4, 8, 16, 24 eller 32" msgid "invalid cert" msgstr "ogiltigt certifikat" +#: py/compile.c +msgid "invalid decorator" +msgstr "ogiltig dekorator" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "ogiltigt dupterm index" @@ -3308,10 +3321,6 @@ msgstr "ogiltig syntax för heltal med bas %d" msgid "invalid syntax for number" msgstr "ogiltig syntax för tal" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "io måste vara rtc io" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() arg 1 måste vara en klass" @@ -3487,6 +3496,10 @@ msgstr "native yield" msgid "need more than %d values to unpack" msgstr "behöver mer än %d värden för att packa upp" +#: py/modmath.c +msgid "negative factorial" +msgstr "negativ faktoriell" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "negativ exponent utan stöd för flyttal" @@ -3716,10 +3729,6 @@ msgstr "palette måste vara 32 bytes lång" msgid "palette_index should be an int" msgstr "palette_index ska vara en int" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "parametern annotation måste vara en identifierare" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "parametrarna måste registreras i följd a2-a5" @@ -3775,6 +3784,8 @@ msgstr "pow() med 3 argument kräver heltal" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3800,6 +3811,10 @@ msgstr "trycka på startknappen vid start.\n" msgid "pressing both buttons at start up.\n" msgstr "trycka båda knapparna vid uppstart.\n" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "håll ner vänster knapp vid start\n" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "pull-mask är i konflikt med riktnings-mask" @@ -4075,10 +4090,6 @@ msgstr "trapz är definierat för 1D-matriser" msgid "trapz is defined for 1D arrays of equal length" msgstr "trapz är definierad för 1D-matriser med samma längd" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "triggernivå måste vara 0 eller 1" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "tupel/lista har fel längd" @@ -4160,7 +4171,7 @@ msgstr "okänd formatkod '%c' för objekt av typ '%q'" msgid "unknown type" msgstr "okänd typ" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "okänd typ '%q'" @@ -4213,10 +4224,6 @@ msgstr "värdet måste passa i %d byte(s)" msgid "value_count must be > 0" msgstr "value_count måste vara > 0" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "wakeup-konflikt" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "watchdog är inte initierad" @@ -4303,6 +4310,45 @@ msgstr "zi måste vara av typ float" msgid "zi must be of shape (n_section, 2)" msgstr "zi måste vara i formen (n_section, 2)" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Viper-funktioner stöder för närvarande inte mer än fyra argument" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "adressen %08x är inte justerad till %d byte" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "funktionen tar inte nyckelordsargument" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "parametern annotation måste vara en identifierare" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "Total data som ska skrivas är större än outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IO 0, 2 & 4 stöder inte intern pullup för sovläge" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "buffer måste vara en byte-liknande objekt" + +#~ msgid "io must be rtc io" +#~ msgstr "io måste vara rtc io" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "triggernivå måste vara 0 eller 1" + +#~ msgid "wakeup conflict" +#~ msgstr "wakeup-konflikt" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "Försökte tilldela heap när MicroPython VM inte körs." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "MicroPython NLR jump misslyckades. Troligen korrupt minne." + +#~ msgid "MicroPython fatal error." +#~ msgstr "MicroPython fatalt fel." + #~ msgid "argument must be ndarray" #~ msgstr "argument måste vara ndarray" @@ -4578,9 +4624,6 @@ msgstr "zi måste vara i formen (n_section, 2)" #~ msgid "can't convert to float" #~ msgstr "kan inte konvertera till float" -#~ msgid "can't convert to int" -#~ msgstr "kan inte konvertera till int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "objektet '%s' är inte en tupel eller lista" diff --git a/locale/zh_Latn_pinyin.po b/locale/zh_Latn_pinyin.po index 14c0a9eca0..8062dfe3ee 100644 --- a/locale/zh_Latn_pinyin.po +++ b/locale/zh_Latn_pinyin.po @@ -7,7 +7,7 @@ msgstr "" "Project-Id-Version: circuitpython-cn\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2021-03-29 08:26+0000\n" +"PO-Revision-Date: 2021-04-19 19:15+0000\n" "Last-Translator: hexthat \n" "Language-Team: Chinese Hanyu Pinyin\n" "Language: zh_Latn_pinyin\n" @@ -15,7 +15,7 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" -"X-Generator: Weblate 4.6-dev\n" +"X-Generator: Weblate 4.7-dev\n" #: main.c msgid "" @@ -423,7 +423,7 @@ msgstr "Wèi zhīchí zhǐdìng de yǐn jiǎo AnalogOut" #: ports/stm/common-hal/audiopwmio/PWMAudioOut.c msgid "Another PWMAudioOut is already active" -msgstr "" +msgstr "lìng yí gè PWMAudioOut yǐ jīng chǔ yú huó dòng zhuàng tài" #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c @@ -448,8 +448,8 @@ msgid "Attempt to allocate %d blocks" msgstr "cháng shì fēn pèi %d kuài" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "MicroPython VM zài wèi yùnxíng shí chángshì fēnpèi duī." +msgid "Attempted heap allocation when VM not running." +msgstr "dāng VM bú yùn xíng shí, cháng shì duī fēn pèi." #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -895,6 +895,11 @@ msgstr "ESP-IDF nèicún fēnpèi shībài" msgid "EXTINT channel already in use" msgstr "EXTINT píndào yǐjīng shǐyòng" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "wèi yú %d wèi zhì de MIDI liú zhōng de cuò wù" + #: extmod/modure.c msgid "Error in regex" msgstr "Zhèngzé biǎodá shì cuòwù" @@ -997,7 +1002,7 @@ msgstr "Wúfǎ fēnpèi wifi sǎomiáo nèicún" #: ports/stm/common-hal/audiopwmio/PWMAudioOut.c msgid "Failed to buffer the sample" -msgstr "" +msgstr "wèi néng huǎn chōng yàng běn" #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" @@ -1024,6 +1029,10 @@ msgstr "Wúfǎ shìfàng mutex, err 0x%04x" msgid "Failed to write internal flash." msgstr "Wúfǎ xiě rù nèibù shǎncún." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "zhì mìng cuò wù." + #: py/moduerrno.c msgid "File exists" msgstr "Wénjiàn cúnzài" @@ -1096,10 +1105,6 @@ msgstr "I2C wài shè zhèng zài shǐ yòng zhōng" msgid "I2SOut not available" msgstr "I2SOut bù kě yòng" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IOS 0, 2 + 4 bù zhī chí shuì mián zhōng de nèi bù shàng lā" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" @@ -1230,6 +1235,10 @@ msgstr "Wúxiào de BSSID" msgid "Invalid DAC pin supplied" msgstr "Tí gōng liǎo wúxiào de DAC yǐn jiǎo" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "wú xiào de MIDI wén jiàn" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c #: ports/cxd56/common-hal/pwmio/PWMOut.c #: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -1421,14 +1430,6 @@ msgstr "Jìngxiàng shí de zuìdà X zhí wèi%d" msgid "Messages limited to 8 bytes" msgstr "Yóujiàn xiànzhì wèi 8 gè zì jié" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "MicroPython NLR tiào zhuǎn shībài. Kěnéng shì nèicún sǔnhuài." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "MicroPython zhìmìng cuòwù." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Màikèfēng qǐdòng yánchí bìxū zài 0.0 Dào 1.0 De fànwéi nèi" @@ -1481,6 +1482,10 @@ msgstr "Bìxū tígōng MISO huò MOSI yǐn jiǎo" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "bì xū shǐ yòng 6 RGB yǐn jiǎo de bèi shù, ér bù shì %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "NLR tiào zhuǎn shī bài. kě néng shì nèi cún sǔn huài." + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "NVS cuò wù" @@ -1615,16 +1620,17 @@ msgstr "Méiyǒu jìshí qì" #: supervisor/shared/safe_mode.c msgid "Nordic system firmware failure assertion." -msgstr "" +msgstr "běi ōu xì tǒng gù jiàn gù zhàng duàn yán." #: ports/nrf/common-hal/_bleio/__init__.c msgid "Nordic system firmware out of memory" -msgstr "" +msgstr "běi ōu xì tǒng gù jiàn chū nèi cún" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "Wúxiào de IP zìfú chuàn" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -2169,8 +2175,8 @@ msgid "Too many displays" msgstr "Xiǎnshì tài duō" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" -msgstr "Yào xiě rù de zǒng shùjù dàyú outgoing_packet_length" +msgid "Total data to write is larger than %q" +msgstr "" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2288,7 +2294,7 @@ msgstr "Wèizhī de ānquán cuòwù: 0x%04x" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format msgid "Unknown system firmware error: %04x" -msgstr "" +msgstr "wèi zhī xì tǒng gù jiàn cuò wù: %04x" #: shared-bindings/_pixelbuf/PixelBuf.c #, c-format @@ -2343,10 +2349,6 @@ msgstr "Zhí chángdù > zuìdà chángdù" msgid "Version was invalid" msgstr "bǎn běn wú xiào" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Viper hánshù mùqián bù zhīchí chāoguò 4 gè cānshù" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "Diànyā dòu qǔ chāoshí" @@ -2433,11 +2435,6 @@ msgstr "xūyào yīgè zì jié lèi duìxiàng" msgid "abort() called" msgstr "zhōngzhǐ () diàoyòng" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "wèi zhǐ %08x wèi yǔ %d wèi yuán zǔ duìqí" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "dìzhǐ chāochū biānjiè" @@ -2446,6 +2443,10 @@ msgstr "dìzhǐ chāochū biānjiè" msgid "addresses is empty" msgstr "dìzhǐ wèi kōng" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "cānshù shì yīgè kōng de xùliè" @@ -2545,10 +2546,6 @@ msgstr "fēnzhī bùzài fànwéi nèi" msgid "buffer is smaller than requested size" msgstr "huǎn chōng qū xiǎo yú qǐng qiú de dà xiǎo" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "huǎnchōng qū bìxū shì zì jié lèi duìxiàng" - #: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "huǎn chōng qū dà xiǎo bì xū shì yuán sù dà xiǎo de bèi shù" @@ -2632,6 +2629,10 @@ msgstr "bùnéng fēnpèi dào biǎodá shì" msgid "can't convert %q to %q" msgstr "Wúfǎ jiāng %q zhuǎnhuàn wèi %q" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "wúfǎ jiāng '%q' duìxiàng zhuǎnhuàn wèi %q yǐn hán" @@ -2640,6 +2641,10 @@ msgstr "wúfǎ jiāng '%q' duìxiàng zhuǎnhuàn wèi %q yǐn hán" msgid "can't convert to %q" msgstr "wúfǎ zhuǎnhuàn wèi %q" +#: py/runtime.c +msgid "can't convert to int" +msgstr "bùnéng zhuǎnhuàn wèi int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "bùnéng mò shì zhuǎnhuàn wèi str" @@ -2996,7 +3001,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string: bù yǔnxǔ shǐyòng dāngè '}'" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "wénjiàn bìxū shì zài zì jié móshì xià dǎkāi de wénjiàn" @@ -3049,8 +3054,8 @@ msgid "full" msgstr "chōngfèn" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "hánshù méiyǒu guānjiàn cí cānshù" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3104,6 +3109,10 @@ msgstr "shēngchéng qì yǐjīng zhíxíng" msgid "generator ignored GeneratorExit" msgstr "shēngchéng qì hūlüè shēngchéng qì tuìchū" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "túxíng bìxū wèi 2048 zì jié" @@ -3252,6 +3261,10 @@ msgstr "wú xiào bits_per_pixel %d, bì xū shì, 1, 4, 8, 16, 24, huò 32" msgid "invalid cert" msgstr "zhèngshū wúxiào" +#: py/compile.c +msgid "invalid decorator" +msgstr "wú xiào zhuāng shì" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "dupterm suǒyǐn wúxiào" @@ -3307,10 +3320,6 @@ msgstr "jīshù wèi %d de zhěng shǔ de yǔfǎ wúxiào" msgid "invalid syntax for number" msgstr "wúxiào de hàomǎ yǔfǎ" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "IO bì xū shì RTC IO" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() cānshù 1 bìxū shì yīgè lèi" @@ -3484,6 +3493,10 @@ msgstr "yuán chǎn" msgid "need more than %d values to unpack" msgstr "xūyào chāoguò%d de zhí cáinéng jiědú" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "méiyǒu fú diǎn zhīchí de xiāojí gōnglǜ" @@ -3682,11 +3695,11 @@ msgstr "ord() yùqí zìfú, dàn chángdù zìfú chuàn %d" #: extmod/ulab/code/utils/utils.c msgid "out array is too small" -msgstr "" +msgstr "chū zhèn liè tài xiǎo" #: extmod/ulab/code/utils/utils.c msgid "out must be a float dense array" -msgstr "" +msgstr "chū bì xū shì yí gè fú dòng mì jí zhèn liè" #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" @@ -3713,10 +3726,6 @@ msgstr "yánsè bìxū shì 32 gè zì jié" msgid "palette_index should be an int" msgstr "yánsè suǒyǐn yīnggāi shì yīgè zhěngshù" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "cānshù zhùshì bìxū shì biāozhì fú" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "cānshù bìxū shì xùliè a2 zhì a5 de dēngjì shù" @@ -3771,6 +3780,8 @@ msgstr "pow() yǒu 3 cānshù xūyào zhěngshù" #: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -3796,6 +3807,10 @@ msgstr "Zài qǐdòng shí àn qǐdòng ànniǔ.\n" msgid "pressing both buttons at start up.\n" msgstr "zài qǐdòng shí tóngshí àn xià liǎng gè ànniǔ.\n" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" msgstr "lā kǒu zhào yǔ fāng xiàng miàn mó chōng tū" @@ -4071,10 +4086,6 @@ msgstr "wéi 1D shù zǔ dìng yì xiàn jǐng" msgid "trapz is defined for 1D arrays of equal length" msgstr "Trapz shì wèi děng zhǎng de 1D shùzǔ dìngyì de" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "chù fā jí bié bì xū wéi 0 huò 1" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "yuán zǔ/lièbiǎo chángdù cuòwù" @@ -4156,7 +4167,7 @@ msgstr "lèixíng '%q' de duìxiàng de wèizhī géshì dàimǎ '%c'" msgid "unknown type" msgstr "wèizhī lèixíng" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "wèizhī lèixíng '%q'" @@ -4209,10 +4220,6 @@ msgstr "Zhí bìxū fúhé %d zì jié" msgid "value_count must be > 0" msgstr "zhí jìshù bìxū wèi > 0" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "huàn xǐng chōng tū" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "wèi chū shǐ huà jiān shì qì" @@ -4299,6 +4306,45 @@ msgstr "zi bìxū wèi fú diǎn xíng" msgid "zi must be of shape (n_section, 2)" msgstr "zi bìxū jùyǒu xíngzhuàng (n_section,2)" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Viper hánshù mùqián bù zhīchí chāoguò 4 gè cānshù" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "wèi zhǐ %08x wèi yǔ %d wèi yuán zǔ duìqí" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "hánshù méiyǒu guānjiàn cí cānshù" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "cānshù zhùshì bìxū shì biāozhì fú" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "Yào xiě rù de zǒng shùjù dàyú outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IOS 0, 2 + 4 bù zhī chí shuì mián zhōng de nèi bù shàng lā" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "huǎnchōng qū bìxū shì zì jié lèi duìxiàng" + +#~ msgid "io must be rtc io" +#~ msgstr "IO bì xū shì RTC IO" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "chù fā jí bié bì xū wéi 0 huò 1" + +#~ msgid "wakeup conflict" +#~ msgstr "huàn xǐng chōng tū" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "MicroPython VM zài wèi yùnxíng shí chángshì fēnpèi duī." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "MicroPython NLR tiào zhuǎn shībài. Kěnéng shì nèicún sǔnhuài." + +#~ msgid "MicroPython fatal error." +#~ msgstr "MicroPython zhìmìng cuòwù." + #~ msgid "argument must be ndarray" #~ msgstr "Cānshù bìxū shì ndarray" @@ -4548,9 +4594,6 @@ msgstr "zi bìxū jùyǒu xíngzhuàng (n_section,2)" #~ msgid "can't convert to float" #~ msgstr "bùnéng zhuǎnhuàn wèi fú diǎn" -#~ msgid "can't convert to int" -#~ msgstr "bùnéng zhuǎnhuàn wèi int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "duìxiàng '%s' bùshì yuán zǔ huò lièbiǎo" diff --git a/main.c b/main.c index 4ec6b5ccb1..00c43275fb 100755 --- a/main.c +++ b/main.c @@ -60,6 +60,7 @@ #include "supervisor/shared/translate.h" #include "supervisor/shared/workflow.h" #include "supervisor/usb.h" +#include "supervisor/workflow.h" #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/microcontroller/Processor.h" @@ -210,7 +211,10 @@ STATIC void stop_mp(void) { #endif background_callback_reset(); + + #if CIRCUITPY_USB usb_background(); + #endif gc_deinit(); } diff --git a/mpy-cross/Makefile b/mpy-cross/Makefile index 3ff379ed36..200080bbe5 100644 --- a/mpy-cross/Makefile +++ b/mpy-cross/Makefile @@ -9,6 +9,8 @@ ifneq ($(findstring undefine,$(.FEATURES)),) override undefine COPT override undefine CFLAGS_EXTRA override undefine LDFLAGS_EXTRA +override undefine MICROPY_FORCE_32BIT +override undefine CROSS_COMPILE override undefine FROZEN_DIR override undefine FROZEN_MPY_DIR override undefine BUILD diff --git a/mpy-cross/mphalport.h b/mpy-cross/mphalport.h index 245b99c4c3..b45ff339ba 100644 --- a/mpy-cross/mphalport.h +++ b/mpy-cross/mphalport.h @@ -2,4 +2,5 @@ // // SPDX-License-Identifier: MIT -// empty file +// prevent including extmod/virtpin.h +#define mp_hal_pin_obj_t diff --git a/mpy-cross/mpy-cross.mk b/mpy-cross/mpy-cross.mk index 629054af9e..c6ef9d8165 100644 --- a/mpy-cross/mpy-cross.mk +++ b/mpy-cross/mpy-cross.mk @@ -22,8 +22,8 @@ UNAME_S := $(shell uname -s) # include py core make definitions include $(TOP)/py/py.mk -INC += -I. -INC += -I$(TOP) +INC += -I. +INC += -I$(TOP) INC += -I$(BUILD) # compiler settings @@ -79,7 +79,7 @@ ifneq (,$(findstring mingw,$(COMPILER_TARGET))) SRC_C += fmode.c endif -OBJ = $(PY_O) +OBJ = $(PY_CORE_O) OBJ += $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) $(BUILD)/supervisor/shared/translate.o: $(HEADER_BUILD)/qstrdefs.generated.h diff --git a/ports/atmel-samd/audio_dma.c b/ports/atmel-samd/audio_dma.c index 0fe71e6d5d..7b1ca42c06 100644 --- a/ports/atmel-samd/audio_dma.c +++ b/ports/atmel-samd/audio_dma.c @@ -45,7 +45,15 @@ static volatile bool audio_dma_pending[AUDIO_DMA_CHANNEL_COUNT]; static bool audio_dma_allocated[AUDIO_DMA_CHANNEL_COUNT]; -uint8_t audio_dma_allocate_channel(void) { +uint8_t find_sync_event_channel_raise() { + uint8_t event_channel = find_sync_event_channel(); + if (event_channel >= EVSYS_SYNCH_NUM) { + mp_raise_RuntimeError(translate("All sync event channels in use")); + } + return event_channel; +} + +uint8_t dma_allocate_channel(void) { uint8_t channel; for (channel = 0; channel < AUDIO_DMA_CHANNEL_COUNT; channel++) { if (!audio_dma_allocated[channel]) { @@ -56,7 +64,7 @@ uint8_t audio_dma_allocate_channel(void) { return channel; // i.e., return failure } -void audio_dma_free_channel(uint8_t channel) { +void dma_free_channel(uint8_t channel) { assert(channel < AUDIO_DMA_CHANNEL_COUNT); assert(audio_dma_allocated[channel]); audio_dma_disable_channel(channel); @@ -180,7 +188,7 @@ audio_dma_result audio_dma_setup_playback(audio_dma_t *dma, bool output_signed, uint32_t output_register_address, uint8_t dma_trigger_source) { - uint8_t dma_channel = audio_dma_allocate_channel(); + uint8_t dma_channel = dma_allocate_channel(); if (dma_channel >= AUDIO_DMA_CHANNEL_COUNT) { return AUDIO_DMA_DMA_BUSY; } @@ -230,11 +238,7 @@ audio_dma_result audio_dma_setup_playback(audio_dma_t *dma, // We're likely double buffering so set up the block interrupts. turn_on_event_system(); - dma->event_channel = find_sync_event_channel(); - - if (dma->event_channel >= EVSYS_SYNCH_NUM) { - mp_raise_RuntimeError(translate("All sync event channels in use")); - } + dma->event_channel = find_sync_event_channel_raise(); init_event_channel_interrupt(dma->event_channel, CORE_GCLK, EVSYS_ID_GEN_DMAC_CH_0 + dma_channel); // We keep the audio_dma_t for internal use and the sample as a root pointer because it @@ -302,7 +306,7 @@ void audio_dma_stop(audio_dma_t *dma) { disable_event_channel(dma->event_channel); MP_STATE_PORT(playing_audio)[channel] = NULL; audio_dma_state[channel] = NULL; - audio_dma_free_channel(dma->dma_channel); + dma_free_channel(dma->dma_channel); } dma->dma_channel = AUDIO_DMA_CHANNEL_COUNT; } diff --git a/ports/atmel-samd/audio_dma.h b/ports/atmel-samd/audio_dma.h index 5506cff628..4e7d193b1d 100644 --- a/ports/atmel-samd/audio_dma.h +++ b/ports/atmel-samd/audio_dma.h @@ -66,8 +66,8 @@ uint8_t audiosample_channel_count(mp_obj_t sample_obj); void audio_dma_init(audio_dma_t *dma); void audio_dma_reset(void); -uint8_t audio_dma_allocate_channel(void); -void audio_dma_free_channel(uint8_t channel); +uint8_t dma_allocate_channel(void); +void dma_free_channel(uint8_t channel); // This sets everything up but doesn't start the timer. // Sample is the python object for the sample to play. @@ -97,4 +97,6 @@ bool audio_dma_get_paused(audio_dma_t *dma); void audio_dma_background(void); +uint8_t find_sync_event_channel_raise(void); + #endif // MICROPY_INCLUDED_ATMEL_SAMD_AUDIO_DMA_H diff --git a/ports/atmel-samd/boards/rotary_trinkey_m0/board.c b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/board.c similarity index 100% rename from ports/atmel-samd/boards/rotary_trinkey_m0/board.c rename to ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/board.c diff --git a/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/mpconfigboard.h b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/mpconfigboard.h new file mode 100644 index 0000000000..3cd85ac1bc --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/mpconfigboard.h @@ -0,0 +1,58 @@ +#define MICROPY_HW_BOARD_NAME "Adafruit NeoKey Trinkey M0" +#define MICROPY_HW_MCU_NAME "samd21e18" + +#define MICROPY_HW_NEOPIXEL (&pin_PA15) + +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) + +#define IGNORE_PIN_PA00 1 +#define IGNORE_PIN_PA01 1 +#define IGNORE_PIN_PA02 1 +#define IGNORE_PIN_PA03 1 +#define IGNORE_PIN_PA04 1 +#define IGNORE_PIN_PA05 1 +#define IGNORE_PIN_PA06 1 +#define IGNORE_PIN_PA08 1 +#define IGNORE_PIN_PA09 1 +#define IGNORE_PIN_PA10 1 +#define IGNORE_PIN_PA11 1 +#define IGNORE_PIN_PA12 1 +#define IGNORE_PIN_PA13 1 +#define IGNORE_PIN_PA14 1 +#define IGNORE_PIN_PA16 1 +#define IGNORE_PIN_PA17 1 +#define IGNORE_PIN_PA18 1 +#define IGNORE_PIN_PA19 1 +#define IGNORE_PIN_PA20 1 +#define IGNORE_PIN_PA21 1 +// USB is always used internally so skip the pin objects for it. +#define IGNORE_PIN_PA24 1 +#define IGNORE_PIN_PA25 1 +#define IGNORE_PIN_PA27 1 +#define IGNORE_PIN_PA29 1 +#define IGNORE_PIN_PA30 1 +#define IGNORE_PIN_PA31 1 +#define IGNORE_PIN_PB00 1 +#define IGNORE_PIN_PB01 1 +#define IGNORE_PIN_PB02 1 +#define IGNORE_PIN_PB03 1 +#define IGNORE_PIN_PB04 1 +#define IGNORE_PIN_PB05 1 +#define IGNORE_PIN_PB06 1 +#define IGNORE_PIN_PB07 1 +#define IGNORE_PIN_PB08 1 +#define IGNORE_PIN_PB09 1 +#define IGNORE_PIN_PB10 1 +#define IGNORE_PIN_PB11 1 +#define IGNORE_PIN_PB12 1 +#define IGNORE_PIN_PB13 1 +#define IGNORE_PIN_PB14 1 +#define IGNORE_PIN_PB15 1 +#define IGNORE_PIN_PB16 1 +#define IGNORE_PIN_PB17 1 +#define IGNORE_PIN_PB22 1 +#define IGNORE_PIN_PB23 1 +#define IGNORE_PIN_PB30 1 +#define IGNORE_PIN_PB31 1 diff --git a/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/mpconfigboard.mk new file mode 100644 index 0000000000..56cbede39f --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/mpconfigboard.mk @@ -0,0 +1,34 @@ +USB_VID = 0x239A +USB_PID = 0x8100 +USB_PRODUCT = "NeoKey Trinkey M0" +USB_MANUFACTURER = "Adafruit Industries LLC" + +CHIP_VARIANT = SAMD21E18A +CHIP_FAMILY = samd21 + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = NONE + +CIRCUITPY_ANALOGIO = 0 +CIRCUITPY_ROTARYIO = 0 +CIRCUITPY_RTC = 0 +CIRCUITPY_SAMD = 0 +CIRCUITPY_PS2IO = 0 +CIRCUITPY_PULSEIO = 0 +CIRCUITPY_PWMIO = 0 +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_BUSIO = 0 +CIRCUITPY_STORAGE = 1 + +CIRCUITPY_MATH = 1 +CIRCUITPY_PIXELBUF = 1 +CIRCUITPY_USB_MIDI = 1 +CIRCUITPY_TOUCHIO = 1 +CIRCUITPY_FULL_BUILD = 0 + +SUPEROPT_GC = 0 +SUPEROPT_VM = 0 + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_HID diff --git a/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/pins.c b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/pins.c new file mode 100644 index 0000000000..df8dfb0bfa --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/pins.c @@ -0,0 +1,8 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_TOUCH), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_SWITCH), MP_ROM_PTR(&pin_PA28) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/board.c b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/board.c new file mode 100644 index 0000000000..cde441b3d9 --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/board.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "common-hal/microcontroller/Pin.h" +#include "supervisor/shared/board.h" +#include "hal/include/hal_gpio.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.h b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.h new file mode 100644 index 0000000000..a760fbe376 --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.h @@ -0,0 +1,58 @@ +#define MICROPY_HW_BOARD_NAME "Adafruit ProxLight Trinkey M0" +#define MICROPY_HW_MCU_NAME "samd21e18" + +#define MICROPY_HW_NEOPIXEL (&pin_PA15) + +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) + +#define IGNORE_PIN_PA01 1 +#define IGNORE_PIN_PA02 1 +#define IGNORE_PIN_PA04 1 +#define IGNORE_PIN_PA05 1 +#define IGNORE_PIN_PA06 1 +#define IGNORE_PIN_PA08 1 +#define IGNORE_PIN_PA09 1 +#define IGNORE_PIN_PA10 1 +#define IGNORE_PIN_PA11 1 +#define IGNORE_PIN_PA12 1 +#define IGNORE_PIN_PA13 1 +#define IGNORE_PIN_PA14 1 +#define IGNORE_PIN_PA18 1 +#define IGNORE_PIN_PA19 1 +#define IGNORE_PIN_PA20 1 +#define IGNORE_PIN_PA21 1 +// USB is always used internally so skip the pin objects for it. +#define IGNORE_PIN_PA24 1 +#define IGNORE_PIN_PA25 1 +#define IGNORE_PIN_PA27 1 +#define IGNORE_PIN_PA28 1 +#define IGNORE_PIN_PA29 1 +#define IGNORE_PIN_PA30 1 +#define IGNORE_PIN_PA31 1 +#define IGNORE_PIN_PB00 1 +#define IGNORE_PIN_PB01 1 +#define IGNORE_PIN_PB02 1 +#define IGNORE_PIN_PB03 1 +#define IGNORE_PIN_PB04 1 +#define IGNORE_PIN_PB05 1 +#define IGNORE_PIN_PB06 1 +#define IGNORE_PIN_PB07 1 +#define IGNORE_PIN_PB08 1 +#define IGNORE_PIN_PB09 1 +#define IGNORE_PIN_PB10 1 +#define IGNORE_PIN_PB11 1 +#define IGNORE_PIN_PB12 1 +#define IGNORE_PIN_PB13 1 +#define IGNORE_PIN_PB14 1 +#define IGNORE_PIN_PB15 1 +#define IGNORE_PIN_PB16 1 +#define IGNORE_PIN_PB17 1 +#define IGNORE_PIN_PB22 1 +#define IGNORE_PIN_PB23 1 +#define IGNORE_PIN_PB30 1 +#define IGNORE_PIN_PB31 1 + +#define DEFAULT_I2C_BUS_SCL (&pin_PA17) +#define DEFAULT_I2C_BUS_SDA (&pin_PA16) diff --git a/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk new file mode 100644 index 0000000000..92e7a17f3e --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk @@ -0,0 +1,33 @@ +USB_VID = 0x239A +USB_PID = 0x8104 +USB_PRODUCT = "ProxLight Trinkey M0" +USB_MANUFACTURER = "Adafruit Industries LLC" + +CHIP_VARIANT = SAMD21E18A +CHIP_FAMILY = samd21 + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = NONE + +CIRCUITPY_ANALOGIO = 0 +CIRCUITPY_ROTARYIO = 0 +CIRCUITPY_RTC = 0 +CIRCUITPY_SAMD = 0 +CIRCUITPY_PS2IO = 0 +CIRCUITPY_PULSEIO = 0 +CIRCUITPY_PWMIO = 0 +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_BUSIO = 1 +CIRCUITPY_STORAGE = 1 + +CIRCUITPY_MATH = 1 +CIRCUITPY_PIXELBUF = 0 +CIRCUITPY_USB_MIDI = 1 +CIRCUITPY_TOUCHIO = 1 +CIRCUITPY_FULL_BUILD = 0 + +SUPEROPT_GC = 0 +SUPEROPT_VM = 0 + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_HID diff --git a/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/pins.c b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/pins.c new file mode 100644 index 0000000000..21410f8ad1 --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/pins.c @@ -0,0 +1,15 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_INTERRUPT), MP_ROM_PTR(&pin_PA00) }, + + { MP_ROM_QSTR(MP_QSTR_TOUCH2), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH1), MP_ROM_PTR(&pin_PA07) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA17) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/board.c b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/board.c new file mode 100644 index 0000000000..cde441b3d9 --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/board.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "common-hal/microcontroller/Pin.h" +#include "supervisor/shared/board.h" +#include "hal/include/hal_gpio.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/rotary_trinkey_m0/mpconfigboard.h b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/mpconfigboard.h similarity index 100% rename from ports/atmel-samd/boards/rotary_trinkey_m0/mpconfigboard.h rename to ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/mpconfigboard.h diff --git a/ports/atmel-samd/boards/rotary_trinkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/mpconfigboard.mk similarity index 97% rename from ports/atmel-samd/boards/rotary_trinkey_m0/mpconfigboard.mk rename to ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/mpconfigboard.mk index b071378c1d..29cc9ee195 100644 --- a/ports/atmel-samd/boards/rotary_trinkey_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/mpconfigboard.mk @@ -18,7 +18,7 @@ CIRCUITPY_PULSEIO = 0 CIRCUITPY_PWMIO = 0 CIRCUITPY_AUDIOCORE = 0 CIRCUITPY_BUSIO = 0 -CIRCUITPY_STORAGE = 0 +CIRCUITPY_STORAGE = 1 CIRCUITPY_MATH = 0 CIRCUITPY_PIXELBUF = 1 diff --git a/ports/atmel-samd/boards/rotary_trinkey_m0/pins.c b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/pins.c similarity index 100% rename from ports/atmel-samd/boards/rotary_trinkey_m0/pins.c rename to ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/pins.c diff --git a/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/board.c b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/board.c new file mode 100644 index 0000000000..cde441b3d9 --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/board.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "common-hal/microcontroller/Pin.h" +#include "supervisor/shared/board.h" +#include "hal/include/hal_gpio.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/mpconfigboard.h b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/mpconfigboard.h new file mode 100644 index 0000000000..1d9a4122df --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/mpconfigboard.h @@ -0,0 +1,58 @@ +#define MICROPY_HW_BOARD_NAME "Adafruit Slide Trinkey M0" +#define MICROPY_HW_MCU_NAME "samd21e18" + +#define MICROPY_HW_NEOPIXEL (&pin_PA06) + +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) + +#define IGNORE_PIN_PA00 1 +#define IGNORE_PIN_PA01 1 +#define IGNORE_PIN_PA02 1 +#define IGNORE_PIN_PA03 1 +#define IGNORE_PIN_PA04 1 +#define IGNORE_PIN_PA05 1 +#define IGNORE_PIN_PA08 1 +#define IGNORE_PIN_PA09 1 +#define IGNORE_PIN_PA10 1 +#define IGNORE_PIN_PA11 1 +#define IGNORE_PIN_PA12 1 +#define IGNORE_PIN_PA13 1 +#define IGNORE_PIN_PA14 1 +#define IGNORE_PIN_PA15 1 +#define IGNORE_PIN_PA16 1 +#define IGNORE_PIN_PA17 1 +#define IGNORE_PIN_PA18 1 +#define IGNORE_PIN_PA19 1 +#define IGNORE_PIN_PA20 1 +#define IGNORE_PIN_PA21 1 +// USB is always used internally so skip the pin objects for it. +#define IGNORE_PIN_PA24 1 +#define IGNORE_PIN_PA25 1 +#define IGNORE_PIN_PA27 1 +#define IGNORE_PIN_PA29 1 +#define IGNORE_PIN_PA30 1 +#define IGNORE_PIN_PA31 1 +#define IGNORE_PIN_PB00 1 +#define IGNORE_PIN_PB01 1 +#define IGNORE_PIN_PB02 1 +#define IGNORE_PIN_PB03 1 +#define IGNORE_PIN_PB04 1 +#define IGNORE_PIN_PB05 1 +#define IGNORE_PIN_PB06 1 +#define IGNORE_PIN_PB07 1 +#define IGNORE_PIN_PB08 1 +#define IGNORE_PIN_PB09 1 +#define IGNORE_PIN_PB10 1 +#define IGNORE_PIN_PB11 1 +#define IGNORE_PIN_PB12 1 +#define IGNORE_PIN_PB13 1 +#define IGNORE_PIN_PB14 1 +#define IGNORE_PIN_PB15 1 +#define IGNORE_PIN_PB16 1 +#define IGNORE_PIN_PB17 1 +#define IGNORE_PIN_PB22 1 +#define IGNORE_PIN_PB23 1 +#define IGNORE_PIN_PB30 1 +#define IGNORE_PIN_PB31 1 diff --git a/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/mpconfigboard.mk new file mode 100644 index 0000000000..2bc2def52e --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/mpconfigboard.mk @@ -0,0 +1,35 @@ +USB_VID = 0x239A +USB_PID = 0x8102 +USB_PRODUCT = "Slide Trinkey M0" +USB_MANUFACTURER = "Adafruit Industries LLC" + +CHIP_VARIANT = SAMD21E18A +CHIP_FAMILY = samd21 + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = NONE + +CIRCUITPY_ANALOGIO = 1 +CIRCUITPY_ROTARYIO = 0 +CIRCUITPY_RTC = 0 +CIRCUITPY_SAMD = 0 +CIRCUITPY_PS2IO = 0 +CIRCUITPY_PULSEIO = 0 +CIRCUITPY_PWMIO = 0 +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_BUSIO = 0 +CIRCUITPY_STORAGE = 1 + +CIRCUITPY_MATH = 1 +CIRCUITPY_PIXELBUF = 1 +CIRCUITPY_USB_MIDI = 1 +CIRCUITPY_TOUCHIO = 1 +CIRCUITPY_FULL_BUILD = 0 + +SUPEROPT_GC = 0 +SUPEROPT_VM = 0 + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_SimpleMath +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_HID diff --git a/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/pins.c b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/pins.c new file mode 100644 index 0000000000..c48c69206a --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/pins.c @@ -0,0 +1,8 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + //{ MP_ROM_QSTR(MP_QSTR_TOUCH), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_POTENTIOMETER), MP_ROM_PTR(&pin_PA07) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51/board.c b/ports/atmel-samd/boards/bdmicro_vina_d51/board.c index bb6ad8bc0d..7af05ba45a 100644 --- a/ports/atmel-samd/boards/bdmicro_vina_d51/board.c +++ b/ports/atmel-samd/boards/bdmicro_vina_d51/board.c @@ -26,17 +26,9 @@ #include "supervisor/board.h" #include "mpconfigboard.h" +#include "hal/include/hal_gpio.h" void board_init(void) { - // struct port_config pin_conf; - // port_get_config_defaults(&pin_conf); - // - // pin_conf.direction = PORT_PIN_DIR_OUTPUT; - // port_pin_set_config(MICROPY_HW_LED_TX, &pin_conf); - // port_pin_set_output_level(MICROPY_HW_LED_TX, true); - // - // port_pin_set_config(MICROPY_HW_LED_RX, &pin_conf); - // port_pin_set_output_level(MICROPY_HW_LED_RX, true); } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.h b/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.h index 8b015df05e..24d78b8ed1 100644 --- a/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.h +++ b/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.h @@ -1,3 +1,6 @@ +// More than one revision of this board is available. +// This board specifies PCB Revision 10 + #define MICROPY_HW_BOARD_NAME "BDMICRO VINA-D51" #define MICROPY_HW_MCU_NAME "samd51n20" @@ -12,13 +15,13 @@ #define BOARD_HAS_CRYSTAL 1 -#define DEFAULT_I2C_BUS_SCL (&pin_PA16) -#define DEFAULT_I2C_BUS_SDA (&pin_PA17) -#define DEFAULT_UART_BUS_RX (&pin_PB20) +#define DEFAULT_I2C_BUS_SCL (&pin_PA12) +#define DEFAULT_I2C_BUS_SDA (&pin_PA13) #define DEFAULT_UART_BUS_TX (&pin_PB21) +#define DEFAULT_UART_BUS_RX (&pin_PB20) +#define DEFAULT_SPI_BUS_SCK (&pin_PC28) #define DEFAULT_SPI_BUS_MISO (&pin_PB23) #define DEFAULT_SPI_BUS_MOSI (&pin_PC27) -#define DEFAULT_SPI_BUS_SCK (&pin_PC28) #define MICROPY_HW_LED_STATUS (&pin_PA23) #define MICROPY_HW_LED_RX (&pin_PC05) #define MICROPY_HW_LED_TX (&pin_PC06) diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.mk b/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.mk index de350f7ab0..13487413f4 100644 --- a/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.mk +++ b/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.mk @@ -1,5 +1,8 @@ +# More than one revision of this board is available. +# This board specifies PCB Revision 10 + USB_VID = 0x31e2 -USB_PID = 0x2011 +USB_PID = 0x2021 USB_PRODUCT = "VINA-D51" USB_MANUFACTURER = "BDMICRO LLC" diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51/pins.c b/ports/atmel-samd/boards/bdmicro_vina_d51/pins.c index 8eeab8a9a5..e7595d9789 100644 --- a/ports/atmel-samd/boards/bdmicro_vina_d51/pins.c +++ b/ports/atmel-samd/boards/bdmicro_vina_d51/pins.c @@ -1,3 +1,6 @@ +// More than one revision of this board is available. +// This board specifies PCB Revision 10 + #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_global_dict_table[] = { @@ -13,6 +16,42 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_PB04) }, { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_PB05) }, { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_PB06) }, + { MP_ROM_QSTR(MP_QSTR_AUX_1), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_AUX_UART_TX), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_AUX_SPI_MOSI), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_AUX_I2C_SDA), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_MOSI), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_TX), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_AUX_10), MP_ROM_PTR(&pin_PC01) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_IRQ), MP_ROM_PTR(&pin_PC01) }, + { MP_ROM_QSTR(MP_QSTR_AUX_11), MP_ROM_PTR(&pin_PC10) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_GPIO_3), MP_ROM_PTR(&pin_PC10) }, + { MP_ROM_QSTR(MP_QSTR_AUX_12), MP_ROM_PTR(&pin_PC11) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_GPIO_1), MP_ROM_PTR(&pin_PC11) }, + { MP_ROM_QSTR(MP_QSTR_AUX_3), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_AUX_UART_RTS), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_AUX_SPI_SS), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_SS), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_GPIO0), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_AUX_4), MP_ROM_PTR(&pin_PC14) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_RESET), MP_ROM_PTR(&pin_PC14) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_RESET), MP_ROM_PTR(&pin_PC14) }, + { MP_ROM_QSTR(MP_QSTR_AUX_5), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_AUX_UART_CTS), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_AUX_SPI_MISO), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_MISO), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_GPIO2), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_AUX_6), MP_ROM_PTR(&pin_PC15) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_EN), MP_ROM_PTR(&pin_PC15) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_CH_PD), MP_ROM_PTR(&pin_PC15) }, + { MP_ROM_QSTR(MP_QSTR_AUX_8), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_AUX_UART_RX), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_AUX_SPI_SCK), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_AUX_I2C_SCL), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_SCK), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_RX), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_AUX_9), MP_ROM_PTR(&pin_PA27) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_WAKE), MP_ROM_PTR(&pin_PA27) }, { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PB31) }, { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PC16) }, { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PC13) }, @@ -30,26 +69,10 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PC12) }, { MP_ROM_QSTR(MP_QSTR_DAC0), MP_ROM_PTR(&pin_PA02) }, { MP_ROM_QSTR(MP_QSTR_DAC1), MP_ROM_PTR(&pin_PA05) }, - { MP_ROM_QSTR(MP_QSTR_ESP01_EN), MP_ROM_PTR(&pin_PC15) }, - { MP_ROM_QSTR(MP_QSTR_E5), MP_ROM_PTR(&pin_PC15) }, - { MP_ROM_QSTR(MP_QSTR_ESP01_GPIO0), MP_ROM_PTR(&pin_PA18) }, - { MP_ROM_QSTR(MP_QSTR_E3), MP_ROM_PTR(&pin_PA18) }, - { MP_ROM_QSTR(MP_QSTR_ESP01_GPIO2), MP_ROM_PTR(&pin_PA19) }, - { MP_ROM_QSTR(MP_QSTR_E4), MP_ROM_PTR(&pin_PA19) }, - { MP_ROM_QSTR(MP_QSTR_ESP01_RESET), MP_ROM_PTR(&pin_PC14) }, - { MP_ROM_QSTR(MP_QSTR_E6), MP_ROM_PTR(&pin_PC14) }, - { MP_ROM_QSTR(MP_QSTR_ESP01_RX), MP_ROM_PTR(&pin_PA12) }, - { MP_ROM_QSTR(MP_QSTR_UART3_RX), MP_ROM_PTR(&pin_PA12) }, - { MP_ROM_QSTR(MP_QSTR_I2C3_SCL), MP_ROM_PTR(&pin_PA12) }, - { MP_ROM_QSTR(MP_QSTR_E2), MP_ROM_PTR(&pin_PA12) }, - { MP_ROM_QSTR(MP_QSTR_ESP01_TX), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_UART3_TX), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_I2C3_SDA), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_E1), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_I2C1_SCL), MP_ROM_PTR(&pin_PA16) }, - { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA16) }, - { MP_ROM_QSTR(MP_QSTR_I2C1_SDA), MP_ROM_PTR(&pin_PA17) }, - { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_I2C1_SCL), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_I2C1_SDA), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA13) }, { MP_ROM_QSTR(MP_QSTR_I2S_FS_0), MP_ROM_PTR(&pin_PA20) }, { MP_ROM_QSTR(MP_QSTR_I2S_MCK_0), MP_ROM_PTR(&pin_PB17) }, { MP_ROM_QSTR(MP_QSTR_I2S_SCK_0), MP_ROM_PTR(&pin_PB16) }, @@ -65,13 +88,13 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_RS485_RX), MP_ROM_PTR(&pin_PB03) }, { MP_ROM_QSTR(MP_QSTR_RS485_TE), MP_ROM_PTR(&pin_PB00) }, { MP_ROM_QSTR(MP_QSTR_RS485_TX), MP_ROM_PTR(&pin_PB02) }, - { MP_ROM_QSTR(MP_QSTR_SPI_MISO), MP_ROM_PTR(&pin_PB23) }, + { MP_ROM_QSTR(MP_QSTR_SPI1_MISO), MP_ROM_PTR(&pin_PB23) }, { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_PB23) }, - { MP_ROM_QSTR(MP_QSTR_SPI_MOSI), MP_ROM_PTR(&pin_PC27) }, + { MP_ROM_QSTR(MP_QSTR_SPI1_MOSI), MP_ROM_PTR(&pin_PC27) }, { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_PC27) }, - { MP_ROM_QSTR(MP_QSTR_SPI_SCK), MP_ROM_PTR(&pin_PC28) }, + { MP_ROM_QSTR(MP_QSTR_SPI1_SCK), MP_ROM_PTR(&pin_PC28) }, { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_PC28) }, - { MP_ROM_QSTR(MP_QSTR_SPI_SS), MP_ROM_PTR(&pin_PB22) }, + { MP_ROM_QSTR(MP_QSTR_SPI1_SS), MP_ROM_PTR(&pin_PB22) }, { MP_ROM_QSTR(MP_QSTR_SS), MP_ROM_PTR(&pin_PB22) }, { MP_ROM_QSTR(MP_QSTR_UART1_CTS), MP_ROM_PTR(&pin_PC25) }, { MP_ROM_QSTR(MP_QSTR_UART1_RTS), MP_ROM_PTR(&pin_PC24) }, diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/board.c b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/board.c new file mode 100644 index 0000000000..bb6ad8bc0d --- /dev/null +++ b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/board.c @@ -0,0 +1,47 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "mpconfigboard.h" + +void board_init(void) { + // struct port_config pin_conf; + // port_get_config_defaults(&pin_conf); + // + // pin_conf.direction = PORT_PIN_DIR_OUTPUT; + // port_pin_set_config(MICROPY_HW_LED_TX, &pin_conf); + // port_pin_set_output_level(MICROPY_HW_LED_TX, true); + // + // port_pin_set_config(MICROPY_HW_LED_RX, &pin_conf); + // port_pin_set_output_level(MICROPY_HW_LED_RX, true); +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/mpconfigboard.h b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/mpconfigboard.h new file mode 100644 index 0000000000..8b015df05e --- /dev/null +++ b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/mpconfigboard.h @@ -0,0 +1,28 @@ +#define MICROPY_HW_BOARD_NAME "BDMICRO VINA-D51" +#define MICROPY_HW_MCU_NAME "samd51n20" + +#define CIRCUITPY_MCU_FAMILY samd51 + +// These are pins not to reset. +// Don't reset QSPI data pins +#define MICROPY_PORT_A (PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11) +#define MICROPY_PORT_B (PORT_PB10 | PORT_PB11) +#define MICROPY_PORT_C (0) +#define MICROPY_PORT_D (0) + +#define BOARD_HAS_CRYSTAL 1 + +#define DEFAULT_I2C_BUS_SCL (&pin_PA16) +#define DEFAULT_I2C_BUS_SDA (&pin_PA17) +#define DEFAULT_UART_BUS_RX (&pin_PB20) +#define DEFAULT_UART_BUS_TX (&pin_PB21) +#define DEFAULT_SPI_BUS_MISO (&pin_PB23) +#define DEFAULT_SPI_BUS_MOSI (&pin_PC27) +#define DEFAULT_SPI_BUS_SCK (&pin_PC28) +#define MICROPY_HW_LED_STATUS (&pin_PA23) +#define MICROPY_HW_LED_RX (&pin_PC05) +#define MICROPY_HW_LED_TX (&pin_PC06) + +// USB is always used internally so skip the pin objects for it. +#define IGNORE_PIN_PA24 1 +#define IGNORE_PIN_PA25 1 diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/mpconfigboard.mk b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/mpconfigboard.mk new file mode 100644 index 0000000000..de350f7ab0 --- /dev/null +++ b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/mpconfigboard.mk @@ -0,0 +1,11 @@ +USB_VID = 0x31e2 +USB_PID = 0x2011 +USB_PRODUCT = "VINA-D51" +USB_MANUFACTURER = "BDMICRO LLC" + +CHIP_VARIANT = SAMD51N20A +CHIP_FAMILY = samd51 + +QSPI_FLASH_FILESYSTEM = 1 +EXTERNAL_FLASH_DEVICES = "MX25L51245G","GD25S512MD" +LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/pins.c b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/pins.c new file mode 100644 index 0000000000..8eeab8a9a5 --- /dev/null +++ b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/pins.c @@ -0,0 +1,90 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_A10), MP_ROM_PTR(&pin_PB07) }, + { MP_ROM_QSTR(MP_QSTR_A11), MP_ROM_PTR(&pin_PC00) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PC02) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_PC03) }, + { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_PB04) }, + { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_PB05) }, + { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_PB06) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PB31) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PC16) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PC13) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PA14) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PB12) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PB13) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PC17) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PC18) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PC19) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PC20) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PC21) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PB18) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PB19) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PC12) }, + { MP_ROM_QSTR(MP_QSTR_DAC0), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_DAC1), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_EN), MP_ROM_PTR(&pin_PC15) }, + { MP_ROM_QSTR(MP_QSTR_E5), MP_ROM_PTR(&pin_PC15) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_GPIO0), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_E3), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_GPIO2), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_E4), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_RESET), MP_ROM_PTR(&pin_PC14) }, + { MP_ROM_QSTR(MP_QSTR_E6), MP_ROM_PTR(&pin_PC14) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_RX), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_UART3_RX), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_I2C3_SCL), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_E2), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_TX), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_UART3_TX), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_I2C3_SDA), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_E1), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_I2C1_SCL), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_I2C1_SDA), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_I2S_FS_0), MP_ROM_PTR(&pin_PA20) }, + { MP_ROM_QSTR(MP_QSTR_I2S_MCK_0), MP_ROM_PTR(&pin_PB17) }, + { MP_ROM_QSTR(MP_QSTR_I2S_SCK_0), MP_ROM_PTR(&pin_PB16) }, + { MP_ROM_QSTR(MP_QSTR_I2S_SDI), MP_ROM_PTR(&pin_PA22) }, + { MP_ROM_QSTR(MP_QSTR_I2S_SDO), MP_ROM_PTR(&pin_PA21) }, + { MP_ROM_QSTR(MP_QSTR_LED_B), MP_ROM_PTR(&pin_PA23) }, + { MP_ROM_QSTR(MP_QSTR_LED_STATUS), MP_ROM_PTR(&pin_PA23) }, + { MP_ROM_QSTR(MP_QSTR_LED_G), MP_ROM_PTR(&pin_PB15) }, + { MP_ROM_QSTR(MP_QSTR_LED_R), MP_ROM_PTR(&pin_PB14) }, + { MP_ROM_QSTR(MP_QSTR_LED_RX), MP_ROM_PTR(&pin_PC05) }, + { MP_ROM_QSTR(MP_QSTR_LED_TX), MP_ROM_PTR(&pin_PC06) }, + { MP_ROM_QSTR(MP_QSTR_RS485_RE), MP_ROM_PTR(&pin_PB01) }, + { MP_ROM_QSTR(MP_QSTR_RS485_RX), MP_ROM_PTR(&pin_PB03) }, + { MP_ROM_QSTR(MP_QSTR_RS485_TE), MP_ROM_PTR(&pin_PB00) }, + { MP_ROM_QSTR(MP_QSTR_RS485_TX), MP_ROM_PTR(&pin_PB02) }, + { MP_ROM_QSTR(MP_QSTR_SPI_MISO), MP_ROM_PTR(&pin_PB23) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_PB23) }, + { MP_ROM_QSTR(MP_QSTR_SPI_MOSI), MP_ROM_PTR(&pin_PC27) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_PC27) }, + { MP_ROM_QSTR(MP_QSTR_SPI_SCK), MP_ROM_PTR(&pin_PC28) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_PC28) }, + { MP_ROM_QSTR(MP_QSTR_SPI_SS), MP_ROM_PTR(&pin_PB22) }, + { MP_ROM_QSTR(MP_QSTR_SS), MP_ROM_PTR(&pin_PB22) }, + { MP_ROM_QSTR(MP_QSTR_UART1_CTS), MP_ROM_PTR(&pin_PC25) }, + { MP_ROM_QSTR(MP_QSTR_UART1_RTS), MP_ROM_PTR(&pin_PC24) }, + { MP_ROM_QSTR(MP_QSTR_UART1_RX), MP_ROM_PTR(&pin_PB24) }, + { MP_ROM_QSTR(MP_QSTR_UART1_TX), MP_ROM_PTR(&pin_PB25) }, + { MP_ROM_QSTR(MP_QSTR_UART2_RX), MP_ROM_PTR(&pin_PB20) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_PB20) }, + { MP_ROM_QSTR(MP_QSTR_I2C2_SCL), MP_ROM_PTR(&pin_PB20) }, + { MP_ROM_QSTR(MP_QSTR_UART2_TX), MP_ROM_PTR(&pin_PB21) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_PB21) }, + { MP_ROM_QSTR(MP_QSTR_I2C2_SDA), MP_ROM_PTR(&pin_PB21) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/atmel-samd/boards/feather_m0_adalogger/mpconfigboard.h b/ports/atmel-samd/boards/feather_m0_adalogger/mpconfigboard.h index a0fde67ef6..704c0552d3 100644 --- a/ports/atmel-samd/boards/feather_m0_adalogger/mpconfigboard.h +++ b/ports/atmel-samd/boards/feather_m0_adalogger/mpconfigboard.h @@ -8,8 +8,8 @@ #define MICROPY_PORT_B (0) #define MICROPY_PORT_C (0) -#define DEFAULT_I2C_BUS_SCL (&pin_PA22) -#define DEFAULT_I2C_BUS_SDA (&pin_PA23) +#define DEFAULT_I2C_BUS_SDA (&pin_PA22) +#define DEFAULT_I2C_BUS_SCL (&pin_PA23) #define DEFAULT_SPI_BUS_SCK (&pin_PB11) #define DEFAULT_SPI_BUS_MOSI (&pin_PB10) diff --git a/ports/atmel-samd/boards/grandcentral_m4_express/mpconfigboard.mk b/ports/atmel-samd/boards/grandcentral_m4_express/mpconfigboard.mk index 88c6e9bf16..6d9ecff636 100644 --- a/ports/atmel-samd/boards/grandcentral_m4_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/grandcentral_m4_express/mpconfigboard.mk @@ -11,3 +11,4 @@ EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ, GD25Q64C" LONGINT_IMPL = MPZ CIRCUITPY_SDIOIO = 1 +CIRCUITPY_IMAGECAPTURE = 1 diff --git a/ports/atmel-samd/boards/neopixel_trinkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/neopixel_trinkey_m0/mpconfigboard.mk index 8607385d22..0f90dba6a1 100644 --- a/ports/atmel-samd/boards/neopixel_trinkey_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/neopixel_trinkey_m0/mpconfigboard.mk @@ -18,7 +18,7 @@ CIRCUITPY_PULSEIO = 0 CIRCUITPY_PWMIO = 0 CIRCUITPY_AUDIOCORE = 0 CIRCUITPY_BUSIO = 0 -CIRCUITPY_STORAGE = 0 +CIRCUITPY_STORAGE = 1 CIRCUITPY_MATH = 1 CIRCUITPY_PIXELBUF = 1 diff --git a/ports/atmel-samd/boards/sensebox_mcu/board.c b/ports/atmel-samd/boards/sensebox_mcu/board.c new file mode 100644 index 0000000000..7af05ba45a --- /dev/null +++ b/ports/atmel-samd/boards/sensebox_mcu/board.c @@ -0,0 +1,39 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "hal/include/hal_gpio.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/sensebox_mcu/mpconfigboard.h b/ports/atmel-samd/boards/sensebox_mcu/mpconfigboard.h new file mode 100644 index 0000000000..13aca289f6 --- /dev/null +++ b/ports/atmel-samd/boards/sensebox_mcu/mpconfigboard.h @@ -0,0 +1,24 @@ +#define MICROPY_HW_BOARD_NAME "senseBox MCU" +#define MICROPY_HW_MCU_NAME "senseBox" + +#define MICROPY_HW_LED_STATUS (&pin_PA27) + +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) + +#define DEFAULT_I2C_BUS_SCL (&pin_PA09) +#define DEFAULT_I2C_BUS_SDA (&pin_PA08) + +#define DEFAULT_SPI_BUS_SCK (&pin_PA17) +#define DEFAULT_SPI_BUS_MOSI (&pin_PA16) +#define DEFAULT_SPI_BUS_MISO (&pin_PA19) + +#define DEFAULT_UART_BUS_RX (&pin_PA23) +#define DEFAULT_UART_BUS_TX (&pin_PA22) + +#define SAMD21_BOD33_LEVEL (6) + +// USB is always used internally so skip the pin objects for it. +#define IGNORE_PIN_PA24 1 +#define IGNORE_PIN_PA25 1 diff --git a/ports/atmel-samd/boards/sensebox_mcu/mpconfigboard.mk b/ports/atmel-samd/boards/sensebox_mcu/mpconfigboard.mk new file mode 100644 index 0000000000..f5ce4a5d13 --- /dev/null +++ b/ports/atmel-samd/boards/sensebox_mcu/mpconfigboard.mk @@ -0,0 +1,14 @@ +USB_VID = 0x04D8 +USB_PID = 0xEF67 +USB_PRODUCT = "senseBox MCU" +USB_MANUFACTURER = "senseBox" + +CHIP_VARIANT = SAMD21G18A +CHIP_FAMILY = samd21 + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = NONE +CIRCUITPY_FULL_BUILD = 0 + +SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/sensebox_mcu/pins.c b/ports/atmel-samd/boards/sensebox_mcu/pins.c new file mode 100644 index 0000000000..55afcc989e --- /dev/null +++ b/ports/atmel-samd/boards/sensebox_mcu/pins.c @@ -0,0 +1,71 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + + // Analog pins + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_PA02) }, + + // Digital pins + // { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PA20) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PA27) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PA28) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PB02) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PA22) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PA23) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PB09) }, + + // UART pins + { MP_ROM_QSTR(MP_QSTR_UART_PWR), MP_ROM_PTR(&pin_PB02) }, + { MP_ROM_QSTR(MP_QSTR_TX1), MP_ROM_PTR(&pin_PA22) }, + { MP_ROM_QSTR(MP_QSTR_RX1), MP_ROM_PTR(&pin_PA23) }, + { MP_ROM_QSTR(MP_QSTR_TX2), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_RX2), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_PA22) }, // alias of TX1 + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_PA23) }, // alias of RX1 + + // SPI pins + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_PA19) }, + + // I2C pins + { MP_ROM_QSTR(MP_QSTR_I2C_PWR), MP_ROM_PTR(&pin_PB11) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA08) }, + + // LED pins + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PA27) }, + { MP_ROM_QSTR(MP_QSTR_RED_LED), MP_ROM_PTR(&pin_PA27) }, + { MP_ROM_QSTR(MP_QSTR_GREEN_LED), MP_ROM_PTR(&pin_PA28) }, + + // XBEE pins + { MP_ROM_QSTR(MP_QSTR_XB1_PWR), MP_ROM_PTR(&pin_PB03) }, + { MP_ROM_QSTR(MP_QSTR_XB2_PWR), MP_ROM_PTR(&pin_PB10) }, + { MP_ROM_QSTR(MP_QSTR_XB1_CS), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_XB2_CS), MP_ROM_PTR(&pin_PA14) }, + { MP_ROM_QSTR(MP_QSTR_XB1_INT), MP_ROM_PTR(&pin_PA21) }, + { MP_ROM_QSTR(MP_QSTR_XB2_INT), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_XB1_RX), MP_ROM_PTR(&pin_PA23) }, + { MP_ROM_QSTR(MP_QSTR_XB1_TX), MP_ROM_PTR(&pin_PA22) }, + { MP_ROM_QSTR(MP_QSTR_XB2_RX), MP_ROM_PTR(&pin_PA11) }, + { MP_ROM_QSTR(MP_QSTR_XB2_TX), MP_ROM_PTR(&pin_PA10) }, + + + // Comm objects + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/atmel-samd/common-hal/audiobusio/PDMIn.c b/ports/atmel-samd/common-hal/audiobusio/PDMIn.c index 8911aef2f1..6ea70e39dc 100644 --- a/ports/atmel-samd/common-hal/audiobusio/PDMIn.c +++ b/ports/atmel-samd/common-hal/audiobusio/PDMIn.c @@ -367,11 +367,8 @@ static uint16_t filter_sample(uint32_t pdm_samples[4]) { // output_buffer_length is the number of slots, not the number of bytes. uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t* self, uint16_t* output_buffer, uint32_t output_buffer_length) { - uint8_t dma_channel = audio_dma_allocate_channel(); - uint8_t event_channel = find_sync_event_channel(); - if (event_channel >= EVSYS_SYNCH_NUM) { - mp_raise_RuntimeError(translate("All sync event channels in use")); - } + uint8_t dma_channel = dma_allocate_channel(); + uint8_t event_channel = find_sync_event_channel_raise(); // We allocate two buffers on the stack to use for double buffering. const uint8_t samples_per_buffer = SAMPLES_PER_BUFFER; @@ -476,7 +473,7 @@ uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t* se } disable_event_channel(event_channel); - audio_dma_free_channel(dma_channel); + dma_free_channel(dma_channel); // Turn off serializer, but leave clock on, to avoid mic startup delay. i2s_set_serializer_enable(self->serializer, false); diff --git a/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c b/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c new file mode 100644 index 0000000000..074c2b6d23 --- /dev/null +++ b/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c @@ -0,0 +1,198 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/obj.h" +#include "py/runtime.h" + +#include "lib/utils/context_manager_helpers.h" +#include "lib/utils/interrupt_char.h" + +#include "shared-bindings/imagecapture/ParallelImageCapture.h" +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "common-hal/imagecapture/ParallelImageCapture.h" + +#include "hal/include/hal_gpio.h" +#include "atmel_start_pins.h" + +#include "audio_dma.h" +#include "samd/clocks.h" +#include "samd/events.h" + +#define GPIO_PIN_FUNCTION_PCC (GPIO_PIN_FUNCTION_K) + +#define PIN_PCC_D0 (PIN_PA16) +#define PIN_PCC_DEN1 (PIN_PA12) +#define PIN_PCC_DEN2 (PIN_PA13) +#define PIN_PCC_CLK (PIN_PA14) + +void common_hal_imagecapture_parallelimagecapture_construct(imagecapture_parallelimagecapture_obj_t *self, + const mcu_pin_obj_t *data0, + const mcu_pin_obj_t *data_clock, + const mcu_pin_obj_t *vertical_sync, + const mcu_pin_obj_t *horizontal_reference, + int data_count) +{ + if (data0->number != PIN_PCC_D0) { + mp_raise_ValueError_varg(translate("Invalid %q pin"), MP_QSTR_data0); + } + // The peripheral supports 8, 10, 12, or 14 data bits, but the code only supports 8 at present + if (data_count != 8) + { + mp_raise_ValueError_varg(translate("Invalid data_count %d"), data_count); + } + if (vertical_sync && vertical_sync->number != PIN_PCC_DEN1) { + mp_raise_ValueError_varg(translate("Invalid %q pin"), MP_QSTR_vsync); + } + if (horizontal_reference && horizontal_reference->number != PIN_PCC_DEN2) { + mp_raise_ValueError_varg(translate("Invalid %q pin"), MP_QSTR_href); + } + if (data_clock->number != PIN_PCC_CLK) { + mp_raise_ValueError_varg(translate("Invalid %q pin"), MP_QSTR_data_clock); + } + // technically, 0 was validated as free already but check again + for (int i=0; inumber + i)) { + mp_raise_ValueError_varg(translate("data pin #%d in use"), i); + } + } + + PCC->MR.bit.PCEN = 0; // Make sure PCC is disabled before setting MR reg + + PCC->IDR.reg = 0b1111; // Disable all PCC interrupts + MCLK->APBDMASK.bit.PCC_ = 1; // Enable PCC clock + + // Accumulate 4 bytes into RHR register (two 16-bit pixels) + PCC->MR.reg = PCC_MR_CID(0x1) | // Clear on falling DEN1 (VSYNC) + PCC_MR_ISIZE(0x0) | // Input data bus is 8 bits + PCC_MR_DSIZE(0x2); // "4 data" at a time (accumulate in RHR) + + PCC->MR.bit.PCEN = 1; // Enable PCC + + + // Now we know we can allocate all pins + self->data_count = data_count; + self->vertical_sync = vertical_sync ? vertical_sync->number : NO_PIN; + self->horizontal_reference = horizontal_reference ? horizontal_reference->number : NO_PIN; + gpio_set_pin_direction(PIN_PCC_CLK, GPIO_DIRECTION_IN); + gpio_set_pin_pull_mode(PIN_PCC_CLK, GPIO_PULL_OFF); + gpio_set_pin_function(PIN_PCC_CLK, GPIO_PIN_FUNCTION_PCC); + //claim_pin_number(PIN_PCC_CLK); + if (vertical_sync) { + gpio_set_pin_direction(PIN_PCC_DEN1, GPIO_DIRECTION_IN); + gpio_set_pin_pull_mode(PIN_PCC_DEN1, GPIO_PULL_OFF); + gpio_set_pin_function(PIN_PCC_DEN1, GPIO_PIN_FUNCTION_PCC); // VSYNC + //claim_pin_number(PIN_PCC_DEN1); + } + if (horizontal_reference) { + gpio_set_pin_direction(PIN_PCC_DEN2, GPIO_DIRECTION_IN); + gpio_set_pin_pull_mode(PIN_PCC_DEN2, GPIO_PULL_OFF); + gpio_set_pin_function(PIN_PCC_DEN2, GPIO_PIN_FUNCTION_PCC); // HSYNC + //claim_pin_number(PIN_PCC_DEN2); + } + for (int i=0; ivertical_sync); + reset_pin_number(self->horizontal_reference); + reset_pin_number(PIN_PCC_CLK); + for (int i=0; idata_count; i++) { + reset_pin_number(PIN_PCC_D0 + i); + } + self->data_count = 0; +} + +bool common_hal_imagecapture_parallelimagecapture_deinited(imagecapture_parallelimagecapture_obj_t *self) +{ + return self->data_count == 0; +} + +static void setup_dma(DmacDescriptor* descriptor, size_t count, uint32_t *buffer) { + descriptor->BTCTRL.reg = DMAC_BTCTRL_VALID | + DMAC_BTCTRL_BLOCKACT_NOACT | + DMAC_BTCTRL_EVOSEL_BLOCK | + DMAC_BTCTRL_DSTINC | + DMAC_BTCTRL_BEATSIZE_WORD; + descriptor->BTCNT.reg = count; + descriptor->DSTADDR.reg = (uint32_t)buffer + 4*count; + descriptor->SRCADDR.reg = (uint32_t)&PCC->RHR.reg; + descriptor->DESCADDR.reg = 0; +} + +#include + +void common_hal_imagecapture_parallelimagecapture_capture(imagecapture_parallelimagecapture_obj_t *self, void *buffer, size_t bufsize) +{ + + uint8_t dma_channel = dma_allocate_channel(); + + uint32_t *dest = buffer; + size_t count = bufsize / 4; // PCC receives 4 bytes (2 pixels) at a time + + turn_on_event_system(); + + setup_dma(dma_descriptor(dma_channel), count, dest); + dma_configure(dma_channel, PCC_DMAC_ID_RX, true); + + if (self->vertical_sync) { + const volatile uint32_t *vsync_reg = &PORT->Group[(self->vertical_sync / 32)].IN.reg; + uint32_t vsync_bit = 1 << (self->vertical_sync % 32); + + while (*vsync_reg & vsync_bit) + { + // Wait for VSYNC low (frame end) + + RUN_BACKGROUND_TASKS; + // Allow user to break out of a timeout with a KeyboardInterrupt. + if (mp_hal_is_interrupted()) { + dma_free_channel(dma_channel); + return; + } + } + } + + dma_enable_channel(dma_channel); + + while (DMAC->Channel[dma_channel].CHCTRLA.bit.ENABLE) { + RUN_BACKGROUND_TASKS; + if (mp_hal_is_interrupted()) { + break; + } + } + + dma_disable_channel(dma_channel); + dma_free_channel(dma_channel); +} diff --git a/drivers/bus/qspi.h b/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.h similarity index 53% rename from drivers/bus/qspi.h rename to ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.h index 81587b08b3..67311c5b00 100644 --- a/drivers/bus/qspi.h +++ b/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.h @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2017-2018 Damien P. George + * Copyright (c) 2021 Jeff Epler for Adafruit Industries * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -23,35 +23,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef MICROPY_INCLUDED_DRIVERS_BUS_QSPI_H -#define MICROPY_INCLUDED_DRIVERS_BUS_QSPI_H -#include "py/mphal.h" +#pragma once -enum { - MP_QSPI_IOCTL_INIT, - MP_QSPI_IOCTL_DEINIT, - MP_QSPI_IOCTL_BUS_ACQUIRE, - MP_QSPI_IOCTL_BUS_RELEASE, +#include "shared-bindings/imagecapture/ParallelImageCapture.h" + +struct imagecapture_parallelimagecapture_obj { + mp_obj_base_t base; + uint8_t data_pin, data_clock, vertical_sync, horizontal_reference, data_count; }; - -typedef struct _mp_qspi_proto_t { - int (*ioctl)(void *self, uint32_t cmd); - void (*write_cmd_data)(void *self, uint8_t cmd, size_t len, uint32_t data); - void (*write_cmd_addr_data)(void *self, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src); - uint32_t (*read_cmd)(void *self, uint8_t cmd, size_t len); - void (*read_cmd_qaddr_qdata)(void *self, uint8_t cmd, uint32_t addr, size_t len, uint8_t *dest); -} mp_qspi_proto_t; - -typedef struct _mp_soft_qspi_obj_t { - mp_hal_pin_obj_t cs; - mp_hal_pin_obj_t clk; - mp_hal_pin_obj_t io0; - mp_hal_pin_obj_t io1; - mp_hal_pin_obj_t io2; - mp_hal_pin_obj_t io3; -} mp_soft_qspi_obj_t; - -extern const mp_qspi_proto_t mp_soft_qspi_proto; - -#endif // MICROPY_INCLUDED_DRIVERS_BUS_QSPI_H diff --git a/ports/atmel-samd/common-hal/imagecapture/__init__.c b/ports/atmel-samd/common-hal/imagecapture/__init__.c new file mode 100644 index 0000000000..e69de29bb2 diff --git a/ports/atmel-samd/common-hal/imagecapture/__init__.h b/ports/atmel-samd/common-hal/imagecapture/__init__.h new file mode 100644 index 0000000000..e69de29bb2 diff --git a/ports/atmel-samd/common-hal/pulseio/PulseIn.c b/ports/atmel-samd/common-hal/pulseio/PulseIn.c index f65d583640..20c79642a3 100644 --- a/ports/atmel-samd/common-hal/pulseio/PulseIn.c +++ b/ports/atmel-samd/common-hal/pulseio/PulseIn.c @@ -137,7 +137,7 @@ void pulsein_interrupt_handler(uint8_t channel) { void pulsein_reset() { #ifdef SAMD21 - rtc_end_pulsein(); + rtc_end_pulse(); #endif refcount = 0; pulsein_tc_index = 0xff; @@ -236,7 +236,7 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, // Set config will enable the EIC. pulsein_set_config(self, true); #ifdef SAMD21 - rtc_start_pulsein(); + rtc_start_pulse(); #endif } @@ -250,7 +250,7 @@ void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self) { return; } #ifdef SAMD21 - rtc_end_pulsein(); + rtc_end_pulse(); #endif set_eic_handler(self->channel, EIC_HANDLER_NO_INTERRUPT); turn_off_eic_channel(self->channel); diff --git a/ports/atmel-samd/common-hal/pulseio/PulseIn.h b/ports/atmel-samd/common-hal/pulseio/PulseIn.h index b91bbd703b..e8fed8e5a0 100644 --- a/ports/atmel-samd/common-hal/pulseio/PulseIn.h +++ b/ports/atmel-samd/common-hal/pulseio/PulseIn.h @@ -51,8 +51,8 @@ void pulsein_reset(void); void pulsein_interrupt_handler(uint8_t channel); void pulsein_timer_interrupt_handler(uint8_t index); #ifdef SAMD21 -void rtc_start_pulsein(void); -void rtc_end_pulsein(void); +void rtc_start_pulse(void); +void rtc_end_pulse(void); #endif diff --git a/ports/atmel-samd/common-hal/pulseio/PulseOut.c b/ports/atmel-samd/common-hal/pulseio/PulseOut.c index 086052a973..ebfd4e7b1a 100644 --- a/ports/atmel-samd/common-hal/pulseio/PulseOut.c +++ b/ports/atmel-samd/common-hal/pulseio/PulseOut.c @@ -93,6 +93,9 @@ void pulseout_reset() { refcount = 0; pulseout_tc_index = 0xff; active_pincfg = NULL; +#ifdef SAMD21 + rtc_end_pulse(); +#endif } void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, @@ -159,6 +162,10 @@ void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, // Turn off the pinmux which should connect the port output. turn_off(self->pincfg); +#ifdef SAMD21 + rtc_start_pulse(); +#endif + } bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t* self) { @@ -180,6 +187,9 @@ void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t* self) { pulseout_tc_index = 0xff; } self->pin = NO_PIN; +#ifdef SAMD21 + rtc_end_pulse(); +#endif } void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t* self, uint16_t* pulses, uint16_t length) { diff --git a/ports/atmel-samd/common-hal/pulseio/PulseOut.h b/ports/atmel-samd/common-hal/pulseio/PulseOut.h index 634088128f..8f8e504fab 100644 --- a/ports/atmel-samd/common-hal/pulseio/PulseOut.h +++ b/ports/atmel-samd/common-hal/pulseio/PulseOut.h @@ -39,5 +39,9 @@ typedef struct { void pulseout_reset(void); void pulseout_interrupt_handler(uint8_t index); +#ifdef SAMD21 +void rtc_start_pulse(void); +void rtc_end_pulse(void); +#endif #endif // MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_PULSEIO_PULSEOUT_H diff --git a/ports/atmel-samd/common-hal/pwmio/PWMOut.c b/ports/atmel-samd/common-hal/pwmio/PWMOut.c index b5142c21e1..c46145d7d7 100644 --- a/ports/atmel-samd/common-hal/pwmio/PWMOut.c +++ b/ports/atmel-samd/common-hal/pwmio/PWMOut.c @@ -156,7 +156,8 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, return PWMOUT_INVALID_PIN; } - if (frequency == 0 || frequency > 6000000) { + uint32_t system_clock = common_hal_mcu_processor_get_frequency(); + if (frequency == 0 || frequency > system_clock/2) { return PWMOUT_INVALID_FREQUENCY; } @@ -237,7 +238,6 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, resolution = tcc_sizes[timer->index]; } // First determine the divisor that gets us the highest resolution. - uint32_t system_clock = common_hal_mcu_processor_get_frequency(); uint32_t top; uint8_t divisor; for (divisor = 0; divisor < 8; divisor++) { @@ -413,7 +413,8 @@ uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t* self) { void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t frequency) { - if (frequency == 0 || frequency > 6000000) { + uint32_t system_clock = common_hal_mcu_processor_get_frequency(); + if (frequency == 0 || frequency > system_clock/2) { mp_raise_ValueError(translate("Invalid PWM frequency")); } const pin_timer_t* t = self->timer; @@ -424,7 +425,6 @@ void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, // TCC resolution varies so look it up. resolution = tcc_sizes[t->index]; } - uint32_t system_clock = common_hal_mcu_processor_get_frequency(); uint32_t new_top; uint8_t new_divisor; for (new_divisor = 0; new_divisor < 8; new_divisor++) { diff --git a/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c b/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c index 0922718f96..4b74b438ff 100644 --- a/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c @@ -25,6 +25,7 @@ */ #include "common-hal/rotaryio/IncrementalEncoder.h" +#include "shared-module/rotaryio/IncrementalEncoder.h" #include "atmel_start_pins.h" @@ -68,11 +69,9 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode self->position = 0; self->quarter_count = 0; - // Top two bits of self->last_state don't matter, because they'll be gone as soon as - // interrupt handler is called. - self->last_state = + shared_module_softencoder_state_init(self, ((uint8_t) gpio_get_pin_level(self->pin_a) << 1) | - (uint8_t) gpio_get_pin_level(self->pin_b); + (uint8_t) gpio_get_pin_level(self->pin_b)); claim_pin(pin_a); claim_pin(pin_b); @@ -106,66 +105,12 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o self->pin_b = NO_PIN; } -mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t* self) { - return self->position; -} - -void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t* self, - mp_int_t new_position) { - self->position = new_position; -} - void incrementalencoder_interrupt_handler(uint8_t channel) { rotaryio_incrementalencoder_obj_t* self = get_eic_channel_data(channel); - // This table also works for detent both at 11 and 00 - // For 11 at detent: - // Turning cw: 11->01->00->10->11 - // Turning ccw: 11->10->00->01->11 - // For 00 at detent: - // Turning cw: 00->10->11->10->00 - // Turning ccw: 00->01->11->10->00 - - // index table by state - #define BAD 7 - static const int8_t transitions[16] = { - 0, // 00 -> 00 no movement - -1, // 00 -> 01 3/4 ccw (11 detent) or 1/4 ccw (00 at detent) - +1, // 00 -> 10 3/4 cw or 1/4 cw - BAD, // 00 -> 11 non-Gray-code transition - +1, // 01 -> 00 2/4 or 4/4 cw - 0, // 01 -> 01 no movement - BAD, // 01 -> 10 non-Gray-code transition - -1, // 01 -> 11 4/4 or 2/4 ccw - -1, // 10 -> 00 2/4 or 4/4 ccw - BAD, // 10 -> 01 non-Gray-code transition - 0, // 10 -> 10 no movement - +1, // 10 -> 11 4/4 or 2/4 cw - BAD, // 11 -> 00 non-Gray-code transition - +1, // 11 -> 01 1/4 or 3/4 cw - -1, // 11 -> 10 1/4 or 3/4 ccw - 0, // 11 -> 11 no movement - }; - - // Shift the old AB bits to the "old" position, and set the new AB bits. - // TODO(tannewt): If we need more speed then read the pin directly. gpio_get_pin_level has - // smarts to compensate for pin direction we don't need. - self->last_state = (self->last_state & 0x3) << 2 | + uint8_t new_state = ((uint8_t) gpio_get_pin_level(self->pin_a) << 1) | (uint8_t) gpio_get_pin_level(self->pin_b); - int8_t quarter_incr = transitions[self->last_state]; - if (quarter_incr == BAD) { - // Missed a transition. We don't know which way we're going, so do nothing. - return; - } - - self->quarter_count += quarter_incr; - if (self->quarter_count >= 4) { - self->position += 1; - self->quarter_count = 0; - } else if (self->quarter_count <= -4) { - self->position -= 1; - self->quarter_count = 0; - } + shared_module_softencoder_state_update(self, new_state); } diff --git a/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.h b/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.h index e07cc84d5d..2560997a97 100644 --- a/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.h +++ b/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.h @@ -35,10 +35,10 @@ typedef struct { mp_obj_base_t base; uint8_t pin_a; uint8_t pin_b; - uint8_t eic_channel_a:4; - uint8_t eic_channel_b:4; - uint8_t last_state:4; // - int8_t quarter_count:4; // count intermediate transitions between detents + uint8_t eic_channel_a; + uint8_t eic_channel_b; + uint8_t state; // + int8_t quarter_count; // count intermediate transitions between detents mp_int_t position; } rotaryio_incrementalencoder_obj_t; diff --git a/ports/atmel-samd/mpconfigport.mk b/ports/atmel-samd/mpconfigport.mk index 559db97ca3..3537123cce 100644 --- a/ports/atmel-samd/mpconfigport.mk +++ b/ports/atmel-samd/mpconfigport.mk @@ -23,6 +23,8 @@ INTERNAL_LIBM = 1 # Number of USB endpoint pairs. USB_NUM_EP = 8 +CIRCUITPY_ROTARYIO_SOFTENCODER = 1 + ###################################################################### # Put samd21-only choices here. @@ -37,6 +39,7 @@ CIRCUITPY_BUILTINS_POW3 ?= 0 CIRCUITPY_COMPUTED_GOTO_SAVE_SPACE ?= 1 CIRCUITPY_FREQUENCYIO ?= 0 CIRCUITPY_JSON ?= 0 +CIRCUITPY_SYNTHIO ?= 0 CIRCUITPY_TOUCHIO_USE_NATIVE ?= 1 # No room for HCI _bleio on SAMD21. @@ -83,3 +86,22 @@ CIRCUITPY_FRAMEBUFFERIO ?= $(CIRCUITPY_FULL_BUILD) endif # samd51 ###################################################################### + +###################################################################### +# Put same51-only choices here. + +ifeq ($(CHIP_FAMILY),same51) + +# No native touchio on SAMD51. +CIRCUITPY_TOUCHIO_USE_NATIVE = 0 + +# The ?='s allow overriding in mpconfigboard.mk. + +CIRCUITPY_NETWORK ?= 0 +CIRCUITPY_PS2IO ?= 1 +CIRCUITPY_SAMD ?= 1 +CIRCUITPY_RGBMATRIX ?= $(CIRCUITPY_FULL_BUILD) +CIRCUITPY_FRAMEBUFFERIO ?= $(CIRCUITPY_FULL_BUILD) + +endif # same51 +###################################################################### diff --git a/ports/atmel-samd/supervisor/port.c b/ports/atmel-samd/supervisor/port.c index c2e27e1e7f..2137c47559 100644 --- a/ports/atmel-samd/supervisor/port.c +++ b/ports/atmel-samd/supervisor/port.c @@ -102,12 +102,12 @@ static void rtc_set_continuous(bool continuous) { while (RTC->MODE0.STATUS.bit.SYNCBUSY); } -void rtc_start_pulsein(void) { +void rtc_start_pulse(void) { rtc_set_continuous(true); hold_interrupt = true; } -void rtc_end_pulsein(void) { +void rtc_end_pulse(void) { hold_interrupt = false; rtc_set_continuous(false); } diff --git a/ports/esp32s2/Makefile b/ports/esp32s2/Makefile index b4ff0612b3..bd79fe383c 100644 --- a/ports/esp32s2/Makefile +++ b/ports/esp32s2/Makefile @@ -201,7 +201,7 @@ SRC_C += \ peripherals/rmt.c \ supervisor/shared/memory.c -ifneq ($(USB),FALSE) +ifneq ($(CIRCUITPY_USB),0) SRC_C += lib/tinyusb/src/portable/espressif/esp32s2/dcd_esp32s2.c endif diff --git a/ports/esp32s2/boards/atmegazero_esp32s2/board.c b/ports/esp32s2/boards/atmegazero_esp32s2/board.c new file mode 100644 index 0000000000..d8fd3a0a2b --- /dev/null +++ b/ports/esp32s2/boards/atmegazero_esp32s2/board.c @@ -0,0 +1,61 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" + +void board_init(void) { + // USB + common_hal_never_reset_pin(&pin_GPIO19); + common_hal_never_reset_pin(&pin_GPIO20); + + // Debug UART +#ifdef DEBUG + common_hal_never_reset_pin(&pin_GPIO43); + common_hal_never_reset_pin(&pin_GPIO44); +#endif /* DEBUG */ + + // SPI Flash and RAM + common_hal_never_reset_pin(&pin_GPIO26); + common_hal_never_reset_pin(&pin_GPIO27); + common_hal_never_reset_pin(&pin_GPIO28); + common_hal_never_reset_pin(&pin_GPIO29); + common_hal_never_reset_pin(&pin_GPIO30); + common_hal_never_reset_pin(&pin_GPIO31); + common_hal_never_reset_pin(&pin_GPIO32); +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { + +} + +void board_deinit(void) { +} diff --git a/ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h b/ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h new file mode 100644 index 0000000000..3ef4e7eede --- /dev/null +++ b/ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h @@ -0,0 +1,47 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * 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. + */ + +//Micropython setup + +#define MICROPY_HW_BOARD_NAME "ATMegaZero ESP32-S2" +#define MICROPY_HW_MCU_NAME "ESP32S2" + +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) +#define BOARD_USER_SAFE_MODE_ACTION translate("pressing boot button at start up.\n") + +#define AUTORESET_DELAY_MS 500 + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO9) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO8) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO36) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO35) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO37) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO40) diff --git a/ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.mk b/ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.mk new file mode 100644 index 0000000000..9a5d947e6c --- /dev/null +++ b/ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.mk @@ -0,0 +1,15 @@ +USB_VID = 0x239A +USB_PID = 0x8009 +USB_PRODUCT = "ATMegaZero ESP32-S2" +USB_MANUFACTURER = "ATMegaZero" + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = MPZ + +# The default queue depth of 16 overflows on release builds, +# so increase it to 32. +CFLAGS += -DCFG_TUD_TASK_QUEUE_SZ=32 + +CIRCUITPY_ESP_FLASH_MODE=qio +CIRCUITPY_ESP_FLASH_FREQ=40m +CIRCUITPY_ESP_FLASH_SIZE=16MB diff --git a/ports/esp32s2/boards/atmegazero_esp32s2/pins.c b/ports/esp32s2/boards/atmegazero_esp32s2/pins.c new file mode 100644 index 0000000000..cfc4ef6223 --- /dev/null +++ b/ports/esp32s2/boards/atmegazero_esp32s2/pins.c @@ -0,0 +1,80 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_IO6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_IO8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_IO9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_IO10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_IO11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_IO12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_IO13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_IO17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_IO18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_IO33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_IO34), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_IO35), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_IO36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_IO37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_IO38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_IO40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_IO44), MP_ROM_PTR(&pin_GPIO44) }, + + { MP_ROM_QSTR(MP_QSTR_PD5), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_HWD), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_AREF), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO44) }, + + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_DAC1), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_DAC2), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO37) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO40) }, + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/esp32s2/boards/atmegazero_esp32s2/sdkconfig b/ports/esp32s2/boards/atmegazero_esp32s2/sdkconfig new file mode 100644 index 0000000000..f42e0784c4 --- /dev/null +++ b/ports/esp32s2/boards/atmegazero_esp32s2/sdkconfig @@ -0,0 +1,39 @@ +CONFIG_ESP32S2_SPIRAM_SUPPORT=y + +# +# SPI RAM config +# +# CONFIG_SPIRAM_TYPE_AUTO is not set +# CONFIG_SPIRAM_TYPE_ESPPSRAM16 is not set +# CONFIG_SPIRAM_TYPE_ESPPSRAM32 is not set +CONFIG_SPIRAM_TYPE_ESPPSRAM64=y +CONFIG_SPIRAM_SIZE=8388608 + +# +# PSRAM clock and cs IO for ESP32S2 +# +CONFIG_DEFAULT_PSRAM_CLK_IO=30 +CONFIG_DEFAULT_PSRAM_CS_IO=26 +# end of PSRAM clock and cs IO for ESP32S2 + +# CONFIG_SPIRAM_FETCH_INSTRUCTIONS is not set +# CONFIG_SPIRAM_RODATA is not set +# CONFIG_SPIRAM_SPEED_80M is not set +CONFIG_SPIRAM_SPEED_40M=y +# CONFIG_SPIRAM_SPEED_26M is not set +# CONFIG_SPIRAM_SPEED_20M is not set +CONFIG_SPIRAM=y +CONFIG_SPIRAM_BOOT_INIT=y +# CONFIG_SPIRAM_IGNORE_NOTFOUND is not set +CONFIG_SPIRAM_USE_MEMMAP=y +# CONFIG_SPIRAM_USE_CAPS_ALLOC is not set +# CONFIG_SPIRAM_USE_MALLOC is not set +CONFIG_SPIRAM_MEMTEST=y +# CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY is not set +# end of SPI RAM config + +# +# LWIP +# +CONFIG_LWIP_LOCAL_HOSTNAME="ATMegaZero-Esp32s2" +# end of LWIP diff --git a/ports/esp32s2/common-hal/busio/UART.c b/ports/esp32s2/common-hal/busio/UART.c index 7da5c0f944..7af43a476d 100644 --- a/ports/esp32s2/common-hal/busio/UART.c +++ b/ports/esp32s2/common-hal/busio/UART.c @@ -291,13 +291,14 @@ size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, mp_raise_ValueError(translate("No TX pin")); } - while (len > 0) { - int count = uart_tx_chars(self->uart_num, (const char *)data, len); + size_t left_to_write = len; + while (left_to_write > 0) { + int count = uart_tx_chars(self->uart_num, (const char *)data, left_to_write); if (count < 0) { *errcode = MP_EAGAIN; return MP_STREAM_ERROR; } - len -= count; + left_to_write -= count; data += count; RUN_BACKGROUND_TASKS; } diff --git a/ports/litex/Makefile b/ports/litex/Makefile index f384f24577..9f0d807469 100644 --- a/ports/litex/Makefile +++ b/ports/litex/Makefile @@ -136,7 +136,7 @@ SRC_C += \ lib/utils/sys_stdio_mphal.c \ supervisor/shared/memory.c -ifneq ($(USB),FALSE) +ifneq ($(CIRCUITPY_USB),0) SRC_C += lib/tinyusb/src/portable/valentyusb/eptri/dcd_eptri.c endif diff --git a/ports/litex/supervisor/internal_flash.c b/ports/litex/supervisor/internal_flash.c index 989fffcc47..5c58c7bc49 100644 --- a/ports/litex/supervisor/internal_flash.c +++ b/ports/litex/supervisor/internal_flash.c @@ -310,7 +310,7 @@ mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block, uint32_t n uint32_t src = lba2addr(block); memcpy(dest, (uint8_t *)src, FILESYSTEM_BLOCK_SIZE * num_blocks); - #if USB_AVAILABLE + #if CIRCUITPY_USB usb_background(); #endif @@ -347,7 +347,7 @@ mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t lba, uint32 src += count * FILESYSTEM_BLOCK_SIZE; num_blocks -= count; - #if USB_AVAILABLE + #if CIRCUITPY_USB usb_background(); #endif } diff --git a/ports/mimxrt10xx/mpconfigport.mk b/ports/mimxrt10xx/mpconfigport.mk index 36d8f7deb8..31b0dbfdac 100644 --- a/ports/mimxrt10xx/mpconfigport.mk +++ b/ports/mimxrt10xx/mpconfigport.mk @@ -23,6 +23,7 @@ INTERNAL_FLASH_FILESYSTEM = 1 CIRCUITPY_AUDIOIO = 0 CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_BUSDEVICE = 1 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 CIRCUITPY_NVM = 0 diff --git a/ports/nrf/Makefile b/ports/nrf/Makefile index 278625e92d..0b44f054f1 100755 --- a/ports/nrf/Makefile +++ b/ports/nrf/Makefile @@ -177,6 +177,7 @@ SRC_C += \ sd_mutex.c \ supervisor/shared/memory.c +ifneq ($(CIRCUITPY_USB),0) # USB source files for nrf52840 ifeq ($(MCU_SUB_VARIANT),nrf52840) SRC_C += \ @@ -187,6 +188,7 @@ ifeq ($(MCU_SUB_VARIANT),nrf52833) SRC_C += \ lib/tinyusb/src/portable/nordic/nrf5x/dcd_nrf5x.c endif +endif # CIRCUITPY_USB ifeq ($(CIRCUITPY_NETWORK),1) CFLAGS += -DMICROPY_PY_NETWORK=1 diff --git a/ports/nrf/bluetooth/ble_drv.c b/ports/nrf/bluetooth/ble_drv.c index f1a982024c..cb923227b2 100644 --- a/ports/nrf/bluetooth/ble_drv.c +++ b/ports/nrf/bluetooth/ble_drv.c @@ -98,6 +98,7 @@ void SD_EVT_IRQHandler(void) { uint32_t evt_id; while (sd_evt_get(&evt_id) != NRF_ERROR_NOT_FOUND) { switch (evt_id) { + #if CIRCUITPY_USB // usb power event case NRF_EVT_POWER_USB_DETECTED: case NRF_EVT_POWER_USB_POWER_READY: @@ -109,6 +110,7 @@ void SD_EVT_IRQHandler(void) { tusb_hal_nrf_power_event(usbevt); } break; + #endif // Set flag indicating that a flash operation has finished. case NRF_EVT_FLASH_OPERATION_SUCCESS: diff --git a/ports/nrf/boards/aramcon2_badge/board.c b/ports/nrf/boards/aramcon2_badge/board.c new file mode 100644 index 0000000000..1759822a2a --- /dev/null +++ b/ports/nrf/boards/aramcon2_badge/board.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Uri Shaked + * Copyright (c) 2021 Benjamin Meisels + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "common-hal/microcontroller/Pin.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { + +} diff --git a/ports/nrf/boards/aramcon2_badge/mpconfigboard.h b/ports/nrf/boards/aramcon2_badge/mpconfigboard.h new file mode 100644 index 0000000000..7691d1e461 --- /dev/null +++ b/ports/nrf/boards/aramcon2_badge/mpconfigboard.h @@ -0,0 +1,68 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Uri Shaked + * Copyright (c) 2021 Benjamin Meisels + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#include "nrfx/hal/nrf_gpio.h" + +#define MICROPY_HW_BOARD_NAME "ARAMCON2 Badge" +#define MICROPY_HW_MCU_NAME "nRF52840" + +#define MICROPY_HW_LED_STATUS (&pin_P1_11) + +// Board does not have a 32kHz crystal. It does have a 32MHz crystal. +#define BOARD_HAS_32KHZ_XTAL (0) + +#ifdef QSPI_FLASH_FILESYSTEM +#define MICROPY_QSPI_DATA0 NRF_GPIO_PIN_MAP(0, 22) +#define MICROPY_QSPI_DATA1 NRF_GPIO_PIN_MAP(0, 20) +#define MICROPY_QSPI_DATA2 NRF_GPIO_PIN_MAP(1, 4) +#define MICROPY_QSPI_DATA3 NRF_GPIO_PIN_MAP(1, 6) +#define MICROPY_QSPI_SCK NRF_GPIO_PIN_MAP(1, 0) +#define MICROPY_QSPI_CS NRF_GPIO_PIN_MAP(1, 2) +#endif + +#ifdef SPI_FLASH_FILESYSTEM +#define SPI_FLASH_MOSI_PIN &pin_P0_20 +#define SPI_FLASH_MISO_PIN &pin_P0_22 +#define SPI_FLASH_SCK_PIN &pin_P1_00 +#define SPI_FLASH_CS_PIN &pin_P1_02 +#endif + +#define CIRCUITPY_BOOT_BUTTON (&pin_P0_29) + +#define BOARD_USER_SAFE_MODE_ACTION translate("pressing the left button at start up\n") + +#define CIRCUITPY_AUTORELOAD_DELAY_MS 500 + +#define CIRCUITPY_INTERNAL_NVM_SIZE (4096) + +#define BOARD_FLASH_SIZE (FLASH_SIZE - 0x4000 - CIRCUITPY_INTERNAL_NVM_SIZE) + +#define DEFAULT_I2C_BUS_SCL (&pin_P0_28) +#define DEFAULT_I2C_BUS_SDA (&pin_P0_03) + +#define DEFAULT_SPI_BUS_SCK (&pin_P0_01) +#define DEFAULT_SPI_BUS_MOSI (&pin_P1_10) +#define DEFAULT_SPI_BUS_MISO (&pin_P1_09) diff --git a/ports/nrf/boards/aramcon2_badge/mpconfigboard.mk b/ports/nrf/boards/aramcon2_badge/mpconfigboard.mk new file mode 100644 index 0000000000..514712f489 --- /dev/null +++ b/ports/nrf/boards/aramcon2_badge/mpconfigboard.mk @@ -0,0 +1,11 @@ +USB_VID = 0x239A +USB_PID = 0x807C +USB_PRODUCT = "ARAMCON2 Badge" +USB_MANUFACTURER = "ARAMCON Badge Team" + +MCU_CHIP = nrf52840 + +QSPI_FLASH_FILESYSTEM = 1 +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" + +CIRCUITPY_DISPLAYIO = 1 diff --git a/ports/nrf/boards/aramcon2_badge/pins.c b/ports/nrf/boards/aramcon2_badge/pins.c new file mode 100644 index 0000000000..0a44f0d5a9 --- /dev/null +++ b/ports/nrf/boards/aramcon2_badge/pins.c @@ -0,0 +1,42 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR_UP_BUTTON), MP_ROM_PTR(&pin_P0_31) }, + { MP_ROM_QSTR(MP_QSTR_LEFT_BUTTON), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_DOWN_BUTTON), MP_ROM_PTR(&pin_P1_13) }, + { MP_ROM_QSTR(MP_QSTR_RIGHT_BUTTON), MP_ROM_PTR(&pin_P0_02) }, + { MP_ROM_QSTR(MP_QSTR_ACTION_BUTTON), MP_ROM_PTR(&pin_P0_10) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_P1_11) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_P0_28) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_P0_03) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_P0_01) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_P1_10) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_P1_09) }, + + { MP_ROM_QSTR(MP_QSTR_GPIO1), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_GPIO2), MP_ROM_PTR(&pin_P0_05) }, + + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_P0_15) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_P0_00) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_P0_13) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_P0_24) }, + + { MP_ROM_QSTR(MP_QSTR_DISP_BUSY), MP_ROM_PTR(&pin_P0_26) }, + { MP_ROM_QSTR(MP_QSTR_DISP_CS), MP_ROM_PTR(&pin_P0_07) }, + { MP_ROM_QSTR(MP_QSTR_DISP_DC), MP_ROM_PTR(&pin_P0_12) }, + { MP_ROM_QSTR(MP_QSTR_DISP_RESET), MP_ROM_PTR(&pin_P0_06) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_P0_08) }, + + { MP_ROM_QSTR(MP_QSTR_VIBRATION_MOTOR), MP_ROM_PTR(&pin_P0_17) }, + + { MP_ROM_QSTR(MP_QSTR_BATTERY_SENSE), MP_ROM_PTR(&pin_P0_30) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, +}; + +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/nrf/boards/simmel/mpconfigboard.mk b/ports/nrf/boards/simmel/mpconfigboard.mk index 005ec8af2f..b4a1417a53 100644 --- a/ports/nrf/boards/simmel/mpconfigboard.mk +++ b/ports/nrf/boards/simmel/mpconfigboard.mk @@ -15,6 +15,7 @@ CIRCUITPY_AUDIOMP3 = 0 CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_BUSDEVICE = 0 CIRCUITPY_BUSIO = 1 +CIRCUITPY_COUNTIO = 0 CIRCUITPY_DISPLAYIO = 0 CIRCUITPY_ERRNO = 0 CIRCUITPY_FRAMEBUFFERIO = 0 diff --git a/ports/nrf/common-hal/_bleio/Adapter.c b/ports/nrf/common-hal/_bleio/Adapter.c index 20e9a16560..26555e24da 100644 --- a/ports/nrf/common-hal/_bleio/Adapter.c +++ b/ports/nrf/common-hal/_bleio/Adapter.c @@ -351,8 +351,11 @@ void common_hal_bleio_adapter_set_enabled(bleio_adapter_obj_t *self, bool enable } else { err_code = sd_softdevice_disable(); } + + #if CIRCUITPY_USB // Re-init USB hardware init_usb_hardware(); + #endif check_nrf_error(err_code); diff --git a/ports/nrf/common-hal/_bleio/Characteristic.c b/ports/nrf/common-hal/_bleio/Characteristic.c index 4c5de3124e..f651b93b6b 100644 --- a/ports/nrf/common-hal/_bleio/Characteristic.c +++ b/ports/nrf/common-hal/_bleio/Characteristic.c @@ -131,6 +131,10 @@ size_t common_hal_bleio_characteristic_get_value(bleio_characteristic_obj_t *sel return 0; } +size_t common_hal_bleio_characteristic_get_max_length(bleio_characteristic_obj_t *self) { + return self->max_length; +} + void common_hal_bleio_characteristic_set_value(bleio_characteristic_obj_t *self, mp_buffer_info_t *bufinfo) { // Do GATT operations only if this characteristic has been added to a registered service. if (self->handle != BLE_GATT_HANDLE_INVALID) { diff --git a/ports/nrf/common-hal/_bleio/PacketBuffer.c b/ports/nrf/common-hal/_bleio/PacketBuffer.c index 311988eb46..260e20514b 100644 --- a/ports/nrf/common-hal/_bleio/PacketBuffer.c +++ b/ports/nrf/common-hal/_bleio/PacketBuffer.c @@ -42,7 +42,8 @@ STATIC void write_to_ringbuf(bleio_packet_buffer_obj_t *self, uint8_t *data, uint16_t len) { if (len + sizeof(uint16_t) > ringbuf_capacity(&self->ringbuf)) { - // This shouldn't happen. + // This shouldn't happen but can if our buffer size was much smaller than + // the writes the client actually makes. return; } // Push all the data onto the ring buffer. @@ -189,7 +190,7 @@ STATIC bool packet_buffer_on_ble_server_evt(ble_evt_t *ble_evt, void *param) { void common_hal_bleio_packet_buffer_construct( bleio_packet_buffer_obj_t *self, bleio_characteristic_obj_t *characteristic, - size_t buffer_size) { + size_t buffer_size, size_t max_packet_size) { self->characteristic = characteristic; self->client = self->characteristic->service->is_remote; @@ -206,8 +207,11 @@ void common_hal_bleio_packet_buffer_construct( self->conn_handle = BLE_CONN_HANDLE_INVALID; } + // Cap the packet size to our implementation limits. + self->max_packet_size = MIN(max_packet_size, BLE_GATTS_VAR_ATTR_LEN_MAX - 3); + if (incoming) { - if (!ringbuf_alloc(&self->ringbuf, buffer_size * (sizeof(uint16_t) + characteristic->max_length), false)) { + if (!ringbuf_alloc(&self->ringbuf, buffer_size * (sizeof(uint16_t) + self->max_packet_size), false)) { mp_raise_ValueError(translate("Buffer too large and unable to allocate")); } } @@ -216,8 +220,8 @@ void common_hal_bleio_packet_buffer_construct( self->packet_queued = false; self->pending_index = 0; self->pending_size = 0; - self->outgoing[0] = m_malloc(characteristic->max_length, false); - self->outgoing[1] = m_malloc(characteristic->max_length, false); + self->outgoing[0] = m_malloc(self->max_packet_size, false); + self->outgoing[1] = m_malloc(self->max_packet_size, false); } else { self->outgoing[0] = NULL; self->outgoing[1] = NULL; @@ -252,6 +256,9 @@ void common_hal_bleio_packet_buffer_construct( } mp_int_t common_hal_bleio_packet_buffer_readinto(bleio_packet_buffer_obj_t *self, uint8_t *data, size_t len) { + if (self->conn_handle == BLE_CONN_HANDLE_INVALID) { + mp_raise_ConnectionError(translate("Not connected")); + } if (ringbuf_num_filled(&self->ringbuf) < 2) { return 0; } @@ -293,10 +300,16 @@ mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, u } uint16_t outgoing_packet_length = common_hal_bleio_packet_buffer_get_outgoing_packet_length(self); - if (len + header_len > outgoing_packet_length) { + uint16_t total_len = len + header_len; + if (total_len > outgoing_packet_length) { // Supplied data will not fit in a single BLE packet. - mp_raise_ValueError(translate("Total data to write is larger than outgoing_packet_length")); + mp_raise_ValueError_varg(translate("Total data to write is larger than %q"), MP_QSTR_outgoing_packet_length); } + if (total_len > self->max_packet_size) { + // Supplied data will not fit in a single BLE packet. + mp_raise_ValueError_varg(translate("Total data to write is larger than %q"), MP_QSTR_max_packet_size); + } + outgoing_packet_length = MIN(outgoing_packet_length, self->max_packet_size); if (len + self->pending_size > outgoing_packet_length) { // No room to append len bytes to packet. Wait until we get a free buffer, @@ -357,8 +370,7 @@ mp_int_t common_hal_bleio_packet_buffer_get_incoming_packet_length(bleio_packet_ if (self->conn_handle != BLE_CONN_HANDLE_INVALID) { bleio_connection_internal_t *connection = bleio_conn_handle_to_connection(self->conn_handle); if (connection) { - return MIN(common_hal_bleio_connection_get_max_packet_length(connection), - self->characteristic->max_length); + return common_hal_bleio_connection_get_max_packet_length(connection); } } // There's no current connection, so we don't know the MTU, and @@ -388,15 +400,29 @@ mp_int_t common_hal_bleio_packet_buffer_get_outgoing_packet_length(bleio_packet_ if (self->conn_handle != BLE_CONN_HANDLE_INVALID) { bleio_connection_internal_t *connection = bleio_conn_handle_to_connection(self->conn_handle); if (connection) { - return MIN(common_hal_bleio_connection_get_max_packet_length(connection), - self->characteristic->max_length); + return MIN(MIN(common_hal_bleio_connection_get_max_packet_length(connection), + self->max_packet_size), + self->characteristic->max_length); } } // There's no current connection, so we don't know the MTU, and // we can't tell what the largest outgoing packet length would be. return -1; } - return self->characteristic->max_length; + // If we are talking to a remote service, we'll be bound by the MTU. (We don't actually + // know the max size of the remote characteristic.) + if (self->characteristic->service != NULL && + self->characteristic->service->is_remote) { + // We are talking to a remote service so we're writing. + if (self->conn_handle != BLE_CONN_HANDLE_INVALID) { + bleio_connection_internal_t *connection = bleio_conn_handle_to_connection(self->conn_handle); + if (connection) { + return MIN(common_hal_bleio_connection_get_max_packet_length(connection), + self->max_packet_size); + } + } + } + return MIN(self->characteristic->max_length, self->max_packet_size); } bool common_hal_bleio_packet_buffer_deinited(bleio_packet_buffer_obj_t *self) { diff --git a/ports/nrf/common-hal/_bleio/PacketBuffer.h b/ports/nrf/common-hal/_bleio/PacketBuffer.h index 94e0f11d80..6f2626565b 100644 --- a/ports/nrf/common-hal/_bleio/PacketBuffer.h +++ b/ports/nrf/common-hal/_bleio/PacketBuffer.h @@ -44,6 +44,7 @@ typedef struct { // We remember the conn_handle so we can do a NOTIFY/INDICATE to a client. // We can find out the conn_handle on a Characteristic write or a CCCD write (but not a read). volatile uint16_t conn_handle; + uint16_t max_packet_size; uint8_t pending_index; uint8_t write_type; bool client; diff --git a/ports/nrf/common-hal/countio/Counter.c b/ports/nrf/common-hal/countio/Counter.c new file mode 100644 index 0000000000..94fadae7c3 --- /dev/null +++ b/ports/nrf/common-hal/countio/Counter.c @@ -0,0 +1,66 @@ + +#include "common-hal/countio/Counter.h" +#include "nrfx_gpiote.h" + +// obj array to map pin number -> self since nrfx hide the mapping +static countio_counter_obj_t *_countio_objs[NUMBER_OF_PINS]; + +static void _intr_handler(nrfx_gpiote_pin_t pin, nrf_gpiote_polarity_t action) { + countio_counter_obj_t *self = _countio_objs[pin]; + if (!self) { + return; + } + self->count += 1; +} + +void common_hal_countio_counter_construct(countio_counter_obj_t* self, + const mcu_pin_obj_t* pin_a) { + + self->pin_a = pin_a->number; + _countio_objs[self->pin_a] = self; + + self->count = 0; + + nrfx_gpiote_in_config_t cfg = { + .sense = NRF_GPIOTE_POLARITY_HITOLO, + .pull = NRF_GPIO_PIN_PULLUP, + .is_watcher = false, + .hi_accuracy = true, + .skip_gpio_setup = false + }; + + nrfx_gpiote_in_init(self->pin_a, &cfg, _intr_handler); + nrfx_gpiote_in_event_enable(self->pin_a, true); + + claim_pin(pin_a); + +} + +bool common_hal_countio_counter_deinited(countio_counter_obj_t* self) { + return self->pin_a == NO_PIN; +} + +void common_hal_countio_counter_deinit(countio_counter_obj_t* self) { + if (common_hal_countio_counter_deinited(self)) { + return; + } + _countio_objs[self->pin_a] = NULL; + + nrfx_gpiote_in_event_disable(self->pin_a); + nrfx_gpiote_in_uninit(self->pin_a); + reset_pin_number(self->pin_a); + self->pin_a = NO_PIN; +} + +mp_int_t common_hal_countio_counter_get_count(countio_counter_obj_t* self) { + return self->count; +} + +void common_hal_countio_counter_set_count(countio_counter_obj_t* self, + mp_int_t new_count) { + self->count = new_count; +} + +void common_hal_countio_counter_reset(countio_counter_obj_t* self){ + self->count = 0; +} diff --git a/ports/nrf/common-hal/countio/Counter.h b/ports/nrf/common-hal/countio/Counter.h new file mode 100644 index 0000000000..cf40a63a02 --- /dev/null +++ b/ports/nrf/common-hal/countio/Counter.h @@ -0,0 +1,15 @@ + +#ifndef MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_COUNTIO_COUNTER_H +#define MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_COUNTIO_COUNTER_H + +#include "common-hal/microcontroller/Pin.h" + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + uint8_t pin_a; + mp_int_t count; +} countio_counter_obj_t; + +#endif // MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_COUNTIO_COUNT_H diff --git a/ports/nrf/common-hal/countio/__init__.c b/ports/nrf/common-hal/countio/__init__.c new file mode 100644 index 0000000000..b95b20d153 --- /dev/null +++ b/ports/nrf/common-hal/countio/__init__.c @@ -0,0 +1 @@ +//No countio module functions diff --git a/ports/nrf/common-hal/rotaryio/IncrementalEncoder.c b/ports/nrf/common-hal/rotaryio/IncrementalEncoder.c index ef5e9ee5ae..8b46c3bd79 100644 --- a/ports/nrf/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/nrf/common-hal/rotaryio/IncrementalEncoder.c @@ -25,6 +25,7 @@ */ #include "common-hal/rotaryio/IncrementalEncoder.h" +#include "shared-module/rotaryio/IncrementalEncoder.h" #include "nrfx_gpiote.h" #include "py/runtime.h" @@ -40,29 +41,11 @@ static void _intr_handler(nrfx_gpiote_pin_t pin, nrf_gpiote_polarity_t action) { return; } - // reads a state 0 .. 3 *in order*. - uint8_t new_state = nrf_gpio_pin_read(self->pin_a); - new_state = (new_state << 1) + (new_state ^ nrf_gpio_pin_read(self->pin_b)); + uint8_t new_state = + ((uint8_t) nrf_gpio_pin_read(self->pin_a) << 1) | + (uint8_t) nrf_gpio_pin_read(self->pin_b); - uint8_t change = (new_state - self->state) & 0x03; - if (change == 1) { - self->quarter++; - } else if (change == 3) { - self->quarter--; - } - // ignore other state transitions - - self->state = new_state; - - // logic from the atmel-samd port: provides some damping and scales movement - // down by 4:1. - if (self->quarter >= 4) { - self->position++; - self->quarter = 0; - } else if (self->quarter <= -4) { - self->position--; - self->quarter = 0; - } + shared_module_softencoder_state_update(self, new_state); } void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencoder_obj_t *self, @@ -110,12 +93,3 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o self->pin_a = NO_PIN; self->pin_b = NO_PIN; } - -mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t *self) { - return self->position; -} - -void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t *self, - mp_int_t new_position) { - self->position = new_position; -} diff --git a/ports/nrf/common-hal/rotaryio/IncrementalEncoder.h b/ports/nrf/common-hal/rotaryio/IncrementalEncoder.h index 1d0fe41839..3693131056 100644 --- a/ports/nrf/common-hal/rotaryio/IncrementalEncoder.h +++ b/ports/nrf/common-hal/rotaryio/IncrementalEncoder.h @@ -35,8 +35,8 @@ typedef struct { mp_obj_base_t base; uint8_t pin_a; uint8_t pin_b; - uint8_t state; - int8_t quarter; + uint8_t state; // + int8_t quarter_count; // count intermediate transitions between detents mp_int_t position; } rotaryio_incrementalencoder_obj_t; diff --git a/ports/nrf/mpconfigport.mk b/ports/nrf/mpconfigport.mk index 2bb7cca59f..aa070c95e3 100644 --- a/ports/nrf/mpconfigport.mk +++ b/ports/nrf/mpconfigport.mk @@ -38,9 +38,10 @@ CIRCUITPY_RTC ?= 1 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_RGBMATRIX ?= 1 +CIRCUITPY_ROTARYIO_SOFTENCODER = 1 CIRCUITPY_FRAMEBUFFERIO ?= 1 -CIRCUITPY_COUNTIO = 0 +CIRCUITPY_COUNTIO ?= 1 CIRCUITPY_WATCHDOG ?= 1 # nRF52840-specific diff --git a/ports/raspberrypi/bindings/rp2pio/StateMachine.c b/ports/raspberrypi/bindings/rp2pio/StateMachine.c index fe36423256..b85ee5d2d4 100644 --- a/ports/raspberrypi/bindings/rp2pio/StateMachine.c +++ b/ports/raspberrypi/bindings/rp2pio/StateMachine.c @@ -241,6 +241,7 @@ STATIC mp_obj_t rp2pio_statemachine_make_new(const mp_obj_type_t *type, size_t n first_in_pin, args[ARG_in_pin_count].u_int, args[ARG_pull_in_pin_up].u_int, args[ARG_pull_in_pin_down].u_int, first_set_pin, args[ARG_set_pin_count].u_int, args[ARG_initial_set_pin_state].u_int, args[ARG_initial_set_pin_direction].u_int, first_sideset_pin, args[ARG_sideset_pin_count].u_int, args[ARG_initial_sideset_pin_state].u_int, args[ARG_initial_sideset_pin_direction].u_int, + 0, args[ARG_exclusive_pin_use].u_bool, args[ARG_auto_pull].u_bool, pull_threshold, args[ARG_out_shift_right].u_bool, args[ARG_wait_for_txstall].u_bool, diff --git a/ports/raspberrypi/bindings/rp2pio/StateMachine.h b/ports/raspberrypi/bindings/rp2pio/StateMachine.h index bb65ade0e3..0ebcca5291 100644 --- a/ports/raspberrypi/bindings/rp2pio/StateMachine.h +++ b/ports/raspberrypi/bindings/rp2pio/StateMachine.h @@ -44,6 +44,7 @@ void common_hal_rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, const mcu_pin_obj_t *first_in_pin, uint8_t in_pin_count, uint32_t pull_pin_up, uint32_t pull_pin_down, const mcu_pin_obj_t *first_set_pin, uint8_t set_pin_count, uint32_t initial_set_pin_state, uint32_t initial_set_pin_direction, const mcu_pin_obj_t *first_sideset_pin, uint8_t sideset_pin_count, uint32_t initial_sideset_pin_state, uint32_t initial_sideset_pin_direction, + uint32_t wait_gpio_mask, bool exclusive_pin_use, bool auto_pull, uint8_t pull_threshold, bool out_shift_right, bool wait_for_txstall, diff --git a/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.h b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.h index 6b84afb649..a1947deaeb 100644 --- a/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.h +++ b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.h @@ -1,4 +1,4 @@ -#define MICROPY_HW_BOARD_NAME "Adafruit QTPy RP2040" +#define MICROPY_HW_BOARD_NAME "Adafruit QT Py RP2040" #define MICROPY_HW_MCU_NAME "rp2040" #define MICROPY_HW_NEOPIXEL (&pin_GPIO12) diff --git a/ports/raspberrypi/boards/adafruit_qtpy_rp2040/pins.c b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/pins.c index 150aa374ed..e9e726f35a 100644 --- a/ports/raspberrypi/boards/adafruit_qtpy_rp2040/pins.c +++ b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/pins.c @@ -11,7 +11,7 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO27) }, { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO26) }, - { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO26) }, { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO24) }, { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO24) }, diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_16mb/board.c b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/board.c new file mode 100644 index 0000000000..67486d4c23 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/board.c @@ -0,0 +1,37 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_16mb/mpconfigboard.h b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/mpconfigboard.h new file mode 100644 index 0000000000..4261b9e006 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/mpconfigboard.h @@ -0,0 +1,10 @@ +#define MICROPY_HW_BOARD_NAME "Pimoroni Pico LiPo (16MB)" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_VBUS_DETECT (&pin_GPIO24) +#define MICROPY_HW_BAT_SENSE (&pin_GPIO29) + +#define MICROPY_HW_USER_SW (&pin_GPIO23) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_16mb/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/mpconfigboard.mk new file mode 100644 index 0000000000..129f408e5e --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/mpconfigboard.mk @@ -0,0 +1,11 @@ +USB_VID = 0x2E8A +USB_PID = 0x1003 +USB_PRODUCT = "Pimoroni Pico LiPo (16MB)" +USB_MANUFACTURER = "Pimoroni" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" + +CIRCUITPY__EVE = 1 diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_16mb/pins.c b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/pins.c new file mode 100644 index 0000000000..229d510ead --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/pins.c @@ -0,0 +1,52 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_GP0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_GP1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_GP2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_GP3), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_GP4), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_GP5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_GP6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_GP7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_GP8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_GP9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_GP10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_GP11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_GP12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_GP13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_GP14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_GP15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_GP16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_GP17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_GP18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_GP21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + + { MP_ROM_QSTR(MP_QSTR_USER_SW), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_VBUS_DETECT), MP_ROM_PTR(&pin_GPIO24) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GP25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GP26_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP27_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP28_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_GP28), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_BAT_SENSE), MP_ROM_PTR(&pin_GPIO29) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_4mb/board.c b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/board.c new file mode 100644 index 0000000000..67486d4c23 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/board.c @@ -0,0 +1,37 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_4mb/mpconfigboard.h b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/mpconfigboard.h new file mode 100644 index 0000000000..e34a05abf2 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/mpconfigboard.h @@ -0,0 +1,10 @@ +#define MICROPY_HW_BOARD_NAME "Pimoroni Pico LiPo (4MB)" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_VBUS_DETECT (&pin_GPIO24) +#define MICROPY_HW_BAT_SENSE (&pin_GPIO29) + +#define MICROPY_HW_USER_SW (&pin_GPIO23) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_4mb/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/mpconfigboard.mk new file mode 100644 index 0000000000..a82ee9c0ea --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/mpconfigboard.mk @@ -0,0 +1,11 @@ +USB_VID = 0x2E8A +USB_PID = 0x1002 +USB_PRODUCT = "Pimoroni Pico LiPo (4MB)" +USB_MANUFACTURER = "Pimoroni" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" + +CIRCUITPY__EVE = 1 diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_4mb/pins.c b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/pins.c new file mode 100644 index 0000000000..229d510ead --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/pins.c @@ -0,0 +1,52 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_GP0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_GP1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_GP2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_GP3), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_GP4), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_GP5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_GP6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_GP7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_GP8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_GP9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_GP10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_GP11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_GP12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_GP13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_GP14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_GP15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_GP16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_GP17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_GP18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_GP21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + + { MP_ROM_QSTR(MP_QSTR_USER_SW), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_VBUS_DETECT), MP_ROM_PTR(&pin_GPIO24) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GP25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GP26_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP27_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP28_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_GP28), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_BAT_SENSE), MP_ROM_PTR(&pin_GPIO29) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/raspberrypi/boards/raspberry_pi_pico/pins.c b/ports/raspberrypi/boards/raspberry_pi_pico/pins.c index e1927bc80c..057eaec2af 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico/pins.c +++ b/ports/raspberrypi/boards/raspberry_pi_pico/pins.c @@ -24,18 +24,28 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, { MP_ROM_QSTR(MP_QSTR_GP21), MP_ROM_PTR(&pin_GPIO21) }, { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_SMPS_MODE), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_GP23), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_GP24), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO25) }, { MP_ROM_QSTR(MP_QSTR_GP25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GP26_A0), MP_ROM_PTR(&pin_GPIO26) }, { MP_ROM_QSTR(MP_QSTR_GP26), MP_ROM_PTR(&pin_GPIO26) }, { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP27_A1), MP_ROM_PTR(&pin_GPIO27) }, { MP_ROM_QSTR(MP_QSTR_GP27), MP_ROM_PTR(&pin_GPIO27) }, { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP28_A2), MP_ROM_PTR(&pin_GPIO28) }, { MP_ROM_QSTR(MP_QSTR_GP28), MP_ROM_PTR(&pin_GPIO28) }, { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_GPIO29) }, }; diff --git a/ports/raspberrypi/boards/sparkfun_micromod_rp2040/board.c b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/board.c new file mode 100644 index 0000000000..c4021a83e9 --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/board.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +#include "shared-bindings/microcontroller/Pin.h" +#include "src/rp2_common/hardware_gpio/include/hardware/gpio.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/sparkfun_micromod_rp2040/mpconfigboard.h b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/mpconfigboard.h new file mode 100644 index 0000000000..d7dd7a6376 --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/mpconfigboard.h @@ -0,0 +1,12 @@ +#define MICROPY_HW_BOARD_NAME "SparkFun MicroMod ATP - RP2040" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO14) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO15) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO12) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO1) +#define DEFAULT_UART_BUS_TX (&pin_GPIO0) diff --git a/ports/raspberrypi/boards/sparkfun_micromod_rp2040/mpconfigboard.mk b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/mpconfigboard.mk new file mode 100644 index 0000000000..2ed559d8db --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/mpconfigboard.mk @@ -0,0 +1,9 @@ +USB_VID = 0x1B4F +USB_PID = 0x0024 +USB_PRODUCT = "MicroMod RP2040" +USB_MANUFACTURER = "SparkFun" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxM" diff --git a/ports/raspberrypi/boards/sparkfun_micromod_rp2040/pins.c b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/pins.c new file mode 100644 index 0000000000..00d6c30cb8 --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/pins.c @@ -0,0 +1,105 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + // D (Digital only) pins (D0,D1) + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO7) }, // GPIO6 - D0 + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO7) }, // GPIO7 - D1 + + // A (ADC) pins (A0,A1) + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO26) }, // GPIO26 - A0 | ADC0 + { MP_ROM_QSTR(MP_QSTR_ADC0), MP_ROM_PTR(&pin_GPIO26) }, // ADC0 alias + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, // GPIO27 - A1 | ADC1 + { MP_ROM_QSTR(MP_QSTR_ADC1), MP_ROM_PTR(&pin_GPIO27) }, // ADC1 alias + + // G (General/BUS) pins (G0-G7, G8 NC, G9-G10, G11 NC) + { MP_ROM_QSTR(MP_QSTR_G0), MP_ROM_PTR(&pin_GPIO16) }, // GPIO16 - G0 | BUS0 + { MP_ROM_QSTR(MP_QSTR_BUS0), MP_ROM_PTR(&pin_GPIO16) }, // BUS0 alias + { MP_ROM_QSTR(MP_QSTR_G1), MP_ROM_PTR(&pin_GPIO17) }, // GPIO17 - G1 | BUS1 + { MP_ROM_QSTR(MP_QSTR_BUS1), MP_ROM_PTR(&pin_GPIO17) }, // BUS1 alias + { MP_ROM_QSTR(MP_QSTR_G2), MP_ROM_PTR(&pin_GPIO18) }, // GPIO18 - G2 | BUS2 + { MP_ROM_QSTR(MP_QSTR_BUS2), MP_ROM_PTR(&pin_GPIO18) }, // BUS2 alias + { MP_ROM_QSTR(MP_QSTR_G3), MP_ROM_PTR(&pin_GPIO19) }, // GPIO19 - G3 | BUS3 + { MP_ROM_QSTR(MP_QSTR_BUS3), MP_ROM_PTR(&pin_GPIO19) }, // BUS3 alias + { MP_ROM_QSTR(MP_QSTR_G4), MP_ROM_PTR(&pin_GPIO20) }, // GPIO20 - G4 | BUS4 | SPI_CIPO + { MP_ROM_QSTR(MP_QSTR_BUS4), MP_ROM_PTR(&pin_GPIO20) }, // BUS4 alias + { MP_ROM_QSTR(MP_QSTR_G5), MP_ROM_PTR(&pin_GPIO21) }, // GPIO21 - G5 | BUS5 | SPI_CS + { MP_ROM_QSTR(MP_QSTR_BUS5), MP_ROM_PTR(&pin_GPIO21) }, // BUS5 alias + { MP_ROM_QSTR(MP_QSTR_G6), MP_ROM_PTR(&pin_GPIO22) }, // GPIO22 - G6 | BUS6 | SPI_SCK + { MP_ROM_QSTR(MP_QSTR_BUS6), MP_ROM_PTR(&pin_GPIO22) }, // BUS6 alias + { MP_ROM_QSTR(MP_QSTR_G7), MP_ROM_PTR(&pin_GPIO23) }, // GPIO23 - G7 | BUS7 | SPI_COPI + { MP_ROM_QSTR(MP_QSTR_BUS7), MP_ROM_PTR(&pin_GPIO23) }, // BUS7 alias + // NC - G8 + { MP_ROM_QSTR(MP_QSTR_G9), MP_ROM_PTR(&pin_GPIO28) }, // GPIO28- G9 | BUS9 | ADC_D- | CAM_HSYNC + { MP_ROM_QSTR(MP_QSTR_BUS9), MP_ROM_PTR(&pin_GPIO28) }, // BUS9 alias + { MP_ROM_QSTR(MP_QSTR_ADC_DM), MP_ROM_PTR(&pin_GPIO28) }, // ADC_DM alias + { MP_ROM_QSTR(MP_QSTR_CAM_HSYNC), MP_ROM_PTR(&pin_GPIO28) }, // CAM_HSYNC alias + { MP_ROM_QSTR(MP_QSTR_G10), MP_ROM_PTR(&pin_GPIO25) }, // GPIO25 - G10 | BUS10 | ADC_D+ | CAM_VSYNC + { MP_ROM_QSTR(MP_QSTR_BUS10), MP_ROM_PTR(&pin_GPIO25) }, // BUS10 alias + { MP_ROM_QSTR(MP_QSTR_ADC_DP), MP_ROM_PTR(&pin_GPIO25) }, // ADC_DP alias + { MP_ROM_QSTR(MP_QSTR_CAM_VSYNC), MP_ROM_PTR(&pin_GPIO25) }, // CAM_VSYNC alias + // NC - G11 + + // PWM pins (PWM0,PWM1) + { MP_ROM_QSTR(MP_QSTR_PWM0), MP_ROM_PTR(&pin_GPIO13) }, // GPIO13 - PWM0 + { MP_ROM_QSTR(MP_QSTR_PWM1), MP_ROM_PTR(&pin_GPIO24) }, // GPIO24 - PWM1 | AUD_MCLK + + // AUD (audio) + { MP_ROM_QSTR(MP_QSTR_AUD_MCLK), MP_ROM_PTR(&pin_GPIO24) }, // GPIO24 - AUD_MCLK | PWM1 + { MP_ROM_QSTR(MP_QSTR_AUD_OUT), MP_ROM_PTR(&pin_GPIO10) }, // GPIO10 - AUD_OUT | SDIO_DAT2 + { MP_ROM_QSTR(MP_QSTR_AUD_IN), MP_ROM_PTR(&pin_GPIO11) }, // GPIO11 - AUD_IN | SDIO_DAT1 + { MP_ROM_QSTR(MP_QSTR_AUD_LRCLK), MP_ROM_PTR(&pin_GPIO2) }, // GPIO2 - AUD_LRCLK | CTS1 + { MP_ROM_QSTR(MP_QSTR_AUD_BCLK), MP_ROM_PTR(&pin_GPIO3) }, // GPIO3 - AUD_BCLK | UART_RTS1 + + // Battery Voltage Monitor + { MP_ROM_QSTR(MP_QSTR_BATT_VIN3), MP_ROM_PTR(&pin_GPIO29) }, // GPIO29 - BATT_VIN/3 (ADC03) + + + // I2C + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO4) }, // GPIO4 - SDA + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO5) }, // GPIO5 - SCL + + { MP_ROM_QSTR(MP_QSTR_I2C_INT), MP_ROM_PTR(&pin_GPIO8) }, // GPIO9 - I2C_INT | TX2 + + // SPI + { MP_ROM_QSTR(MP_QSTR_CIPO), MP_ROM_PTR(&pin_GPIO20) }, // GPIO20 - CIPO | SPI_CIPO | G4 + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO20) }, // MISO alias + { MP_ROM_QSTR(MP_QSTR_COPI), MP_ROM_PTR(&pin_GPIO23) }, // GPIO23 - COPI | SPI_COPI | G7 + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO23) }, // MOSI alias + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO22) }, // GPIO22 - SCK | SPI_SCK | G6 + { MP_ROM_QSTR(MP_QSTR_CS), MP_ROM_PTR(&pin_GPIO21) }, // GPIO21 - /CS | SPI_/CS | G5 + + // SDI/SPI1 + { MP_ROM_QSTR(MP_QSTR_SDIO_CLK), MP_ROM_PTR(&pin_GPIO14) }, // GPIO14 - SDIO SCK | SDIO_CLK + { MP_ROM_QSTR(MP_QSTR_SPI_SCK1), MP_ROM_PTR(&pin_GPIO14) }, // SPI_SCK1 alias + { MP_ROM_QSTR(MP_QSTR_SDIO_CMD), MP_ROM_PTR(&pin_GPIO15) }, // GPIO15 - SDIO CMD | SDIO_CMD + { MP_ROM_QSTR(MP_QSTR_SPI_COPI1), MP_ROM_PTR(&pin_GPIO15) },// SPI_COPI1 alias + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA0), MP_ROM_PTR(&pin_GPIO12) },// GPIO12 - SDIO DATA0 | SDIO_DATA0 + { MP_ROM_QSTR(MP_QSTR_SPI_CIPO1), MP_ROM_PTR(&pin_GPIO12) }, // SPI_CIPO1 alias + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA1), MP_ROM_PTR(&pin_GPIO11) },// GPIO11 - SDIO DATA1 | SDIO_DATA1 | AUD_IN + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA2), MP_ROM_PTR(&pin_GPIO10) },// GPIO10 - SDIO DATA2 | SDIO_DATA2 | AUD_OUT + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA3), MP_ROM_PTR(&pin_GPIO9) },// GPIO9 - SDIO DATA3 | SDIO_DATA3 | SPI_CS1 + { MP_ROM_QSTR(MP_QSTR_SPI_CS1), MP_ROM_PTR(&pin_GPIO9) }, // SPI_CS1 alias + + // Status LED + { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_GPIO25) }, // GPIO25 - LED_BUILTIN | STAT | Blue LED | G10 + + // UART + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO1) }, // GPIO1 - UART RX | UART_RX1 | RX1 + { MP_ROM_QSTR(MP_QSTR_RX1), MP_ROM_PTR(&pin_GPIO1) }, // RX1 alias + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO0) }, // GPIO0 - UART TX | UART_TX1 | TX1 + { MP_ROM_QSTR(MP_QSTR_TX1), MP_ROM_PTR(&pin_GPIO0) }, // TX1 alias + { MP_ROM_QSTR(MP_QSTR_CTS), MP_ROM_PTR(&pin_GPIO2) }, // GPIO2 - UART CTS | CTS1 (TRACEDATA3) + { MP_ROM_QSTR(MP_QSTR_CTS1), MP_ROM_PTR(&pin_GPIO2) }, // CTS1 alias + { MP_ROM_QSTR(MP_QSTR_RTS), MP_ROM_PTR(&pin_GPIO3) }, // GPIO3 - UART RTS | RTS1 + { MP_ROM_QSTR(MP_QSTR_RTS1), MP_ROM_PTR(&pin_GPIO3) }, // RTS1 alias + + { MP_ROM_QSTR(MP_QSTR_RX2), MP_ROM_PTR(&pin_GPIO9) }, // GPIO9 - UART RX | UART_RX2 | RX2 | SDIO_DAT3 | SPI_CS1 + { MP_ROM_QSTR(MP_QSTR_TX2), MP_ROM_PTR(&pin_GPIO8) }, // GPIO8 - UART TX | UART_TX2 | TX2 | I2C_INT + + // Board objects + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/raspberrypi/common-hal/audiobusio/I2SOut.c b/ports/raspberrypi/common-hal/audiobusio/I2SOut.c index 5f77a74a5e..0ad44c2527 100644 --- a/ports/raspberrypi/common-hal/audiobusio/I2SOut.c +++ b/ports/raspberrypi/common-hal/audiobusio/I2SOut.c @@ -126,6 +126,7 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t *self, 0, 0, // in pulls NULL, 0, 0, 0x1f, // set pins bit_clock, 2, 0, 0x1f, // sideset pins + 0, // wait gpio pins true, // exclusive pin use false, 32, false, // shift out left to start with MSB false, // Wait for txstall diff --git a/ports/raspberrypi/common-hal/audiobusio/PDMIn.c b/ports/raspberrypi/common-hal/audiobusio/PDMIn.c index bbcfbb805a..3f2b448eac 100644 --- a/ports/raspberrypi/common-hal/audiobusio/PDMIn.c +++ b/ports/raspberrypi/common-hal/audiobusio/PDMIn.c @@ -71,6 +71,7 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, 0, 0, // in pulls NULL, 0, 0, 0x1f, // set pins clock_pin, 1, 0, 0x1f, // sideset pins + 0, // wait gpio pins true, // exclusive pin use false, 32, false, // out settings false, // Wait for txstall diff --git a/ports/raspberrypi/common-hal/busio/UART.c b/ports/raspberrypi/common-hal/busio/UART.c index 2d8ff099eb..e7ba64b098 100644 --- a/ports/raspberrypi/common-hal/busio/UART.c +++ b/ports/raspberrypi/common-hal/busio/UART.c @@ -191,12 +191,13 @@ size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, mp_raise_ValueError(translate("No TX pin")); } - while (len > 0) { - while (uart_is_writable(self->uart) && len > 0) { + size_t left_to_write = len; + while (left_to_write > 0) { + while (uart_is_writable(self->uart) && left_to_write > 0) { // Write and advance. uart_get_hw(self->uart)->dr = *data++; // Decrease how many chars left to write. - len--; + left_to_write--; } RUN_BACKGROUND_TASKS; } diff --git a/ports/raspberrypi/common-hal/displayio/ParallelBus.c b/ports/raspberrypi/common-hal/displayio/ParallelBus.c index 8a976fb251..80dbb13bb7 100644 --- a/ports/raspberrypi/common-hal/displayio/ParallelBus.c +++ b/ports/raspberrypi/common-hal/displayio/ParallelBus.c @@ -99,6 +99,7 @@ void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t *sel NULL, 0, 0, 0, // first in pin, # in pins NULL, 0, 0, 0, // first set pin write, 1, 0, 1, // first sideset pin + 0, // wait gpio pins true, // exclusive pin usage true, 8, true, // TX, auto pull every 8 bits. shift left to output msb first false, // wait for TX stall diff --git a/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c b/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c new file mode 100644 index 0000000000..2c91a2fa16 --- /dev/null +++ b/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c @@ -0,0 +1,135 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/obj.h" +#include "py/runtime.h" + +#include "lib/utils/context_manager_helpers.h" +#include "lib/utils/interrupt_char.h" + +#include "bindings/rp2pio/StateMachine.h" +#include "bindings/rp2pio/__init__.h" +#include "common-hal/imagecapture/ParallelImageCapture.h" +#include "shared-bindings/imagecapture/ParallelImageCapture.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/microcontroller/Processor.h" +#include "shared-bindings/microcontroller/__init__.h" + +#include "src/rp2_common/hardware_pio/include/hardware/pio.h" +#include "src/rp2_common/hardware_pio/include/hardware/pio_instructions.h" + +// Define this to (1), and you can scope the instruction-pointer of the state machine on D26..28 (note the weird encoding though!) +#define DEBUG_STATE_MACHINE (0) +#if DEBUG_STATE_MACHINE +#define SIDE(x) ((x)<<8) +#else +#define SIDE(x) (0) +#endif + +#define _0 SIDE(0b11100) +#define _1 SIDE(0b00000) +#define _2 SIDE(0b10000) +#define _3 SIDE(0b10100) +#define _4 SIDE(0b11000) +#define _5 SIDE(0b10100) + +#define IMAGECAPTURE_CODE(width, pclk, vsync, href) \ + { \ +/* 0 */ pio_encode_wait_gpio(0, vsync) | _0, \ +/* 1 */ pio_encode_wait_gpio(1, vsync) | _1, \ + /* .wrap_target */ \ +/* 2 */ pio_encode_wait_gpio(1, href) | _2, \ +/* 3 */ pio_encode_wait_gpio(1, pclk) | _3, \ +/* 4 */ pio_encode_in(pio_pins, width) | _4, \ +/* 5 */ pio_encode_wait_gpio(0, pclk) | _5, \ + /* .wrap */ \ + } + +void common_hal_imagecapture_parallelimagecapture_construct(imagecapture_parallelimagecapture_obj_t *self, + const mcu_pin_obj_t *data0, + const mcu_pin_obj_t *data_clock, + const mcu_pin_obj_t *vertical_sync, + const mcu_pin_obj_t *horizontal_reference, + int data_count) +{ + + uint16_t imagecapture_code[] = IMAGECAPTURE_CODE(data_count, data_clock->number, vertical_sync->number, horizontal_reference->number); + + common_hal_rp2pio_statemachine_construct(&self->state_machine, + imagecapture_code, MP_ARRAY_SIZE(imagecapture_code), + common_hal_mcu_processor_get_frequency(), // full speed (4 instructions per loop -> max pclk 30MHz @ 120MHz) + 0, 0, // init + NULL, 0, 0, 0, // out pins + data0, data_count, // in pins + 0, 0, // in pulls + NULL, 0, 0, 0, // set pins +#if DEBUG_STATE_MACHINE + &pin_GPIO26, 3, 7, 7, // sideset pins +#else + NULL, 0, 0, 0, // sideset pins +#endif + (1<number) | (1<number) | (1<number), // wait gpio pins + true, // exclusive pin use + false, 32, false, // out settings + false, // wait for txstall + true, 32, true); // in settings + + PIO pio = self->state_machine.pio; + uint8_t pio_index = pio_get_index(pio); + uint sm = self->state_machine.state_machine; + rp2pio_statemachine_set_wrap(&self->state_machine, 2, 5); +} + +void common_hal_imagecapture_parallelimagecapture_deinit(imagecapture_parallelimagecapture_obj_t *self) +{ + if (common_hal_imagecapture_parallelimagecapture_deinited(self)) { + return; + } + return common_hal_rp2pio_statemachine_deinit(&self->state_machine); +} + +bool common_hal_imagecapture_parallelimagecapture_deinited(imagecapture_parallelimagecapture_obj_t *self) +{ + return common_hal_rp2pio_statemachine_deinited(&self->state_machine); +} + +void common_hal_imagecapture_parallelimagecapture_capture(imagecapture_parallelimagecapture_obj_t *self, void *buffer, size_t bufsize) +{ + PIO pio = self->state_machine.pio; + uint sm = self->state_machine.state_machine; + uint8_t offset = rp2pio_statemachine_program_offset(&self->state_machine); + + pio_sm_set_enabled(pio, sm, false); + pio_sm_clear_fifos(pio, sm); + + pio_sm_restart(pio, sm); + pio_sm_exec(pio, sm, pio_encode_jmp(offset)); + pio_sm_set_enabled(pio, sm, true); + + common_hal_rp2pio_statemachine_readinto(&self->state_machine, buffer, bufsize, 4); + + pio_sm_set_enabled(pio, sm, false); +} diff --git a/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.h b/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.h new file mode 100644 index 0000000000..9f5d1ab32f --- /dev/null +++ b/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.h @@ -0,0 +1,35 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * 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. + */ + +#pragma once + +#include "common-hal/rp2pio/StateMachine.h" +#include "shared-bindings/imagecapture/ParallelImageCapture.h" + +struct imagecapture_parallelimagecapture_obj { + mp_obj_base_t base; + rp2pio_statemachine_obj_t state_machine; +}; diff --git a/ports/raspberrypi/common-hal/imagecapture/__init__.c b/ports/raspberrypi/common-hal/imagecapture/__init__.c new file mode 100644 index 0000000000..e69de29bb2 diff --git a/ports/raspberrypi/common-hal/imagecapture/__init__.h b/ports/raspberrypi/common-hal/imagecapture/__init__.h new file mode 100644 index 0000000000..e69de29bb2 diff --git a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c index a3cf05ca65..c441ea2e84 100644 --- a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c @@ -28,6 +28,7 @@ #include #include "common-hal/rotaryio/IncrementalEncoder.h" +#include "shared-module/rotaryio/IncrementalEncoder.h" #include "bindings/rp2pio/__init__.h" #include "bindings/rp2pio/StateMachine.h" @@ -60,9 +61,12 @@ STATIC void incrementalencoder_interrupt_handler(void *self_in); void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencoder_obj_t *self, const mcu_pin_obj_t *pin_a, const mcu_pin_obj_t *pin_b) { mp_obj_t pins[] = {MP_OBJ_FROM_PTR(pin_a), MP_OBJ_FROM_PTR(pin_b)}; + // Start out with swapped to match behavior with other ports. + self->swapped = true; if (!common_hal_rp2pio_pins_are_sequential(2, pins)) { pins[0] = MP_OBJ_FROM_PTR(pin_b); pins[1] = MP_OBJ_FROM_PTR(pin_a); + self->swapped = false; if (!common_hal_rp2pio_pins_are_sequential(2, pins)) { mp_raise_RuntimeError(translate("Pins must be sequential")); } @@ -80,6 +84,7 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode 3, 0, // in pulls NULL, 0, 0, 0x1f, // set pins NULL, 0, 0, 0x1f, // sideset pins + 0, // wait gpio pins true, // exclusive pin use false, 32, false, // out settings false, // Wait for txstall @@ -88,12 +93,10 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode common_hal_rp2pio_statemachine_run(&self->state_machine, encoder_init, MP_ARRAY_SIZE(encoder_init)); // We're guaranteed by the init code that some output will be available promptly - uint8_t state; - common_hal_rp2pio_statemachine_readinto(&self->state_machine, &state, 1, 1); - // Top two bits of self->last_state don't matter, because they'll be gone as soon as - // interrupt handler is called. - self->last_state = state & 3; + uint8_t quiescent_state; + common_hal_rp2pio_statemachine_readinto(&self->state_machine, &quiescent_state, 1, 1); + shared_module_softencoder_state_init(self, quiescent_state & 3); common_hal_rp2pio_statemachine_set_interrupt_handler(&self->state_machine, incrementalencoder_interrupt_handler, self, PIO_IRQ0_INTF_SM0_RXNEMPTY_BITS); } @@ -109,67 +112,20 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o common_hal_rp2pio_statemachine_deinit(&self->state_machine); } -mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t *self) { - return self->position; -} - -void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t *self, - mp_int_t new_position) { - self->position = new_position; -} - STATIC void incrementalencoder_interrupt_handler(void *self_in) { rotaryio_incrementalencoder_obj_t *self = self_in; - // This table also works for detent both at 11 and 00 - // For 11 at detent: - // Turning cw: 11->01->00->10->11 - // Turning ccw: 11->10->00->01->11 - // For 00 at detent: - // Turning cw: 00->10->11->10->00 - // Turning ccw: 00->01->11->10->00 - - // index table by state - #define BAD 7 - static const int8_t transitions[16] = { - 0, // 00 -> 00 no movement - -1, // 00 -> 01 3/4 ccw (11 detent) or 1/4 ccw (00 at detent) - +1, // 00 -> 10 3/4 cw or 1/4 cw - BAD, // 00 -> 11 non-Gray-code transition - +1, // 01 -> 00 2/4 or 4/4 cw - 0, // 01 -> 01 no movement - BAD, // 01 -> 10 non-Gray-code transition - -1, // 01 -> 11 4/4 or 2/4 ccw - -1, // 10 -> 00 2/4 or 4/4 ccw - BAD, // 10 -> 01 non-Gray-code transition - 0, // 10 -> 10 no movement - +1, // 10 -> 11 4/4 or 2/4 cw - BAD, // 11 -> 00 non-Gray-code transition - +1, // 11 -> 01 1/4 or 3/4 cw - -1, // 11 -> 10 1/4 or 3/4 ccw - 0, // 11 -> 11 no movement - }; while (common_hal_rp2pio_statemachine_get_in_waiting(&self->state_machine)) { // Bypass all the logic of StateMachine.c:_transfer, we need something // very simple and fast for an interrupt! - uint8_t new = self->state_machine.pio->rxf[self->state_machine.state_machine]; - - // Shift the old AB bits to the "old" position, and set the new AB bits. - self->last_state = (self->last_state & 0x3) << 2 | (new & 0x3); - - int8_t quarter_incr = transitions[self->last_state]; - if (quarter_incr == BAD) { - // Missed a transition. We don't know which way we're going, so do nothing. - return; - } - - self->quarter_count += quarter_incr; - if (self->quarter_count >= 4) { - self->position += 1; - self->quarter_count = 0; - } else if (self->quarter_count <= -4) { - self->position -= 1; - self->quarter_count = 0; + uint8_t new_state = self->state_machine.pio->rxf[self->state_machine.state_machine]; + if (self->swapped) { + if (new_state == 0x1) { + new_state = 0x2; + } else if (new_state == 0x2) { + new_state = 0x1; + } } + shared_module_softencoder_state_update(self, new_state); } } diff --git a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h index 83fe97d316..6745d95a1c 100644 --- a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h +++ b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h @@ -34,7 +34,8 @@ typedef struct { mp_obj_base_t base; rp2pio_statemachine_obj_t state_machine; - uint8_t last_state : 4; // - int8_t quarter_count : 4; // count intermediate transitions between detents + uint8_t state; // + int8_t quarter_count; // count intermediate transitions between detents + bool swapped; // Did the pins need to be swapped to be sequential? mp_int_t position; } rotaryio_incrementalencoder_obj_t; diff --git a/ports/raspberrypi/common-hal/rp2pio/StateMachine.c b/ports/raspberrypi/common-hal/rp2pio/StateMachine.c index 716693228f..21ec09c42c 100644 --- a/ports/raspberrypi/common-hal/rp2pio/StateMachine.c +++ b/ports/raspberrypi/common-hal/rp2pio/StateMachine.c @@ -329,13 +329,14 @@ void common_hal_rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, uint32_t pull_pin_up, uint32_t pull_pin_down, const mcu_pin_obj_t *first_set_pin, uint8_t set_pin_count, uint32_t initial_set_pin_state, uint32_t initial_set_pin_direction, const mcu_pin_obj_t *first_sideset_pin, uint8_t sideset_pin_count, uint32_t initial_sideset_pin_state, uint32_t initial_sideset_pin_direction, + uint32_t wait_gpio_mask, bool exclusive_pin_use, bool auto_pull, uint8_t pull_threshold, bool out_shift_right, bool wait_for_txstall, bool auto_push, uint8_t push_threshold, bool in_shift_right) { // First, check that all pins are free OR already in use by any PIO if exclusive_pin_use is false. - uint32_t pins_we_use = 0; + uint32_t pins_we_use = wait_gpio_mask; pins_we_use |= _check_pins_free(first_out_pin, out_pin_count, exclusive_pin_use); pins_we_use |= _check_pins_free(first_in_pin, in_pin_count, exclusive_pin_use); pins_we_use |= _check_pins_free(first_set_pin, set_pin_count, exclusive_pin_use); @@ -801,3 +802,16 @@ STATIC void rp2pio_statemachine_interrupt_handler(void) { } } } + +uint8_t rp2pio_statemachine_program_offset(rp2pio_statemachine_obj_t *self) { + uint8_t pio_index = pio_get_index(self->pio); + uint8_t sm = self->state_machine; + return _current_program_offset[pio_index][sm]; +} + +void rp2pio_statemachine_set_wrap(rp2pio_statemachine_obj_t *self, uint wrap_target, uint wrap) { + uint8_t sm = self->state_machine; + uint8_t offset = rp2pio_statemachine_program_offset(self); + + pio_sm_set_wrap(self->pio, sm, offset+wrap_target, offset+wrap); +} diff --git a/ports/raspberrypi/common-hal/rp2pio/StateMachine.h b/ports/raspberrypi/common-hal/rp2pio/StateMachine.h index 38410a3629..2503aace8d 100644 --- a/ports/raspberrypi/common-hal/rp2pio/StateMachine.h +++ b/ports/raspberrypi/common-hal/rp2pio/StateMachine.h @@ -74,6 +74,9 @@ bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, bool auto_push, uint8_t push_threshold, bool in_shift_right, bool claim_pins); +uint8_t rp2pio_statemachine_program_offset(rp2pio_statemachine_obj_t *self); +void rp2pio_statemachine_set_wrap(rp2pio_statemachine_obj_t *self, uint wrap_target, uint wrap); + void rp2pio_statemachine_deinit(rp2pio_statemachine_obj_t *self, bool leave_pins); extern const mp_obj_type_t rp2pio_statemachine_type; diff --git a/ports/raspberrypi/mpconfigport.mk b/ports/raspberrypi/mpconfigport.mk index b8d602e146..75c5d227f0 100644 --- a/ports/raspberrypi/mpconfigport.mk +++ b/ports/raspberrypi/mpconfigport.mk @@ -23,9 +23,11 @@ CIRCUITPY_FRAMEBUFFERIO ?= 1 CIRCUITPY_FULL_BUILD ?= 1 CIRCUITPY_AUDIOMP3 ?= 1 CIRCUITPY_BITOPS ?= 1 +CIRCUITPY_IMAGECAPTURE ?= 1 CIRCUITPY_PWMIO ?= 1 CIRCUITPY_RGBMATRIX ?= 1 CIRCUITPY_ROTARYIO ?= 1 +CIRCUITPY_ROTARYIO_SOFTENCODER = 1 # Things that need to be implemented. # Use PWM interally @@ -42,8 +44,7 @@ CIRCUITPY_AUDIOBUSIO ?= 1 CIRCUITPY_AUDIOCORE ?= 1 CIRCUITPY_AUDIOPWMIO ?= 1 -# These libraries require Cortex M4+ for fancy math instructions. -CIRCUITPY_AUDIOMIXER ?= 0 +CIRCUITPY_AUDIOMIXER = 1 INTERNAL_LIBM = 1 diff --git a/ports/stm/Makefile b/ports/stm/Makefile index e09fe736cc..49548b0db3 100755 --- a/ports/stm/Makefile +++ b/ports/stm/Makefile @@ -238,7 +238,7 @@ SRC_C += \ lib/utils/sys_stdio_mphal.c \ supervisor/shared/memory.c -ifneq ($(USB),FALSE) +ifneq ($(CIRCUITPY_USB),0) SRC_C += lib/tinyusb/src/portable/st/synopsys/dcd_synopsys.c endif diff --git a/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.mk b/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.mk index ed124ce27e..211a658967 100644 --- a/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.mk +++ b/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.mk @@ -5,7 +5,7 @@ USB_MANUFACTURER = "Unknown" SPI_FLASH_FILESYSTEM = 1 #See supervisor/shared/external_flash/devices.h for options -EXTERNAL_FLASH_DEVICES = GD25Q16C,W25Q64FV,W25Q64JVxQ +EXTERNAL_FLASH_DEVICES = GD25Q16C,W25Q64FV,W25Q32JVxQ,W25Q64JVxQ LONGINT_IMPL = MPZ INTERNAL_FLASH_FILESYSTEM = 0 @@ -16,3 +16,5 @@ MCU_PACKAGE = UFQFPN48 LD_COMMON = boards/common_default.ld LD_FILE = boards/STM32F411_nvm_nofs.ld + +CIRCUITPY_SYNTHIO = 0 diff --git a/ports/unix/Makefile b/ports/unix/Makefile index 305c0549d1..bb900a29b3 100644 --- a/ports/unix/Makefile +++ b/ports/unix/Makefile @@ -76,6 +76,9 @@ LDFLAGS_ARCH = -Wl,-Map=$@.map,--cref -Wl,--gc-sections endif LDFLAGS = -Lbuild $(LDFLAGS_MOD) $(LDFLAGS_ARCH) -lm $(LDFLAGS_EXTRA) +# Flags to link with pthread library +LIBPTHREAD = -lpthread + ifeq ($(MICROPY_FORCE_32BIT),1) # Note: you may need to install i386 versions of dependency packages, # starting with linux-libc-dev:i386 @@ -101,17 +104,17 @@ SRC_MOD += modusocket.c endif ifeq ($(MICROPY_PY_THREAD),1) CFLAGS_MOD += -DMICROPY_PY_THREAD=1 -DMICROPY_PY_THREAD_GIL=0 -LDFLAGS_MOD += -lpthread +LDFLAGS_MOD += $(LIBPTHREAD) endif ifeq ($(MICROPY_PY_FFI),1) ifeq ($(MICROPY_STANDALONE),1) -LIBFFI_CFLAGS_MOD := -I$(shell ls -1d $(TOP)/lib/libffi/build_dir/out/lib/libffi-*/include) +LIBFFI_CFLAGS_MOD := -I$(shell ls -1d $(BUILD)/lib/libffi/out/lib/libffi-*/include) ifeq ($(MICROPY_FORCE_32BIT),1) - LIBFFI_LDFLAGS_MOD = $(TOP)/lib/libffi/build_dir/out/lib32/libffi.a + LIBFFI_LDFLAGS_MOD = $(BUILD)/lib/libffi/out/lib32/libffi.a else - LIBFFI_LDFLAGS_MOD = $(TOP)/lib/libffi/build_dir/out/lib/libffi.a + LIBFFI_LDFLAGS_MOD = $(BUILD)/lib/libffi/out/lib/libffi.a endif else LIBFFI_CFLAGS_MOD := $(shell pkg-config --cflags libffi) @@ -141,7 +144,6 @@ SRC_C += \ mpthreadport.c \ input.c \ file.c \ - modmachine.c \ modos.c \ moduos_vfs.c \ modtime.c \ @@ -156,12 +158,6 @@ SRC_C += \ supervisor/shared/translate.c \ $(SRC_MOD) -PY_EXTMOD_O_BASENAME += \ - extmod/machine_mem.o \ - extmod/machine_pinbase.o \ - extmod/machine_signal.o \ - extmod/machine_pulse.o \ - LIB_SRC_C = $(addprefix lib/,\ $(LIB_SRC_C_EXTRA) \ timeutils/timeutils.c \ @@ -232,8 +228,7 @@ nanbox: CFLAGS_EXTRA='-DMP_CONFIGFILE=""' \ BUILD=build-nanbox \ PROG=micropython_nanbox \ - MICROPY_FORCE_32BIT=1 \ - MICROPY_PY_USSL=0 + MICROPY_FORCE_32BIT=1 freedos: $(MAKE) \ @@ -264,9 +259,9 @@ coverage: coverage_test: coverage $(eval DIRNAME=ports/$(notdir $(CURDIR))) - cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests --auto-jobs - cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests --auto-jobs -d thread - cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests --auto-jobs --emit native + cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests -j1 + cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests -j1 -d thread + cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests -j1 --emit native cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests -j1 --via-mpy -d basics float cat $(TOP)/tests/basics/0prelim.py | ./micropython_coverage | grep -q 'abc' gcov -o build-coverage/py $(TOP)/py/*.c @@ -297,23 +292,19 @@ endif deplibs: libffi axtls +libffi: $(BUILD)/lib/libffi/include/ffi.h + +$(TOP)/lib/libffi/configure: $(TOP)/lib/libffi/autogen.sh + cd $(TOP)/lib/libffi; ./autogen.sh + # install-exec-recursive & install-data-am targets are used to avoid building # docs and depending on makeinfo -libffi: - cd $(TOP)/lib/libffi; git clean -d -x -f - cd $(TOP)/lib/libffi; ./autogen.sh - mkdir -p $(TOP)/lib/libffi/build_dir; cd $(TOP)/lib/libffi/build_dir; \ - ../configure $(CROSS_COMPILE_HOST) --prefix=$$PWD/out --disable-structs CC="$(CC)" CXX="$(CXX)" LD="$(LD)" CFLAGS="-Os -fomit-frame-pointer -fstrict-aliasing -ffast-math -fno-exceptions"; \ +$(BUILD)/lib/libffi/include/ffi.h: $(TOP)/lib/libffi/configure + mkdir -p $(BUILD)/lib/libffi; cd $(BUILD)/lib/libffi; \ + $(abspath $(TOP))/lib/libffi/configure $(CROSS_COMPILE_HOST) --prefix=$$PWD/out --disable-structs CC="$(CC)" CXX="$(CXX)" LD="$(LD)" CFLAGS="-Os -fomit-frame-pointer -fstrict-aliasing -ffast-math -fno-exceptions"; \ $(MAKE) install-exec-recursive; $(MAKE) -C include install-data-am -axtls: $(BUILD)/libaxtls.a - -$(BUILD)/libaxtls.a: $(TOP)/lib/axtls/README | $(OBJ_DIRS) - cd $(TOP)/lib/axtls; cp config/upyconfig config/.config - cd $(TOP)/lib/axtls; $(MAKE) oldconfig -B - cd $(TOP)/lib/axtls; $(MAKE) clean - cd $(TOP)/lib/axtls; $(MAKE) all CC="$(CC)" LD="$(LD)" - cp $(TOP)/lib/axtls/_stage/libaxtls.a $@ +axtls: $(TOP)/lib/axtls/README $(TOP)/lib/axtls/README: @echo "You cloned without --recursive, fetching submodules for you." diff --git a/ports/unix/file.c b/ports/unix/file.c index 892457ed56..745593c81c 100644 --- a/ports/unix/file.c +++ b/ports/unix/file.c @@ -125,6 +125,8 @@ STATIC mp_uint_t fdfile_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, i o->fd = -1; #endif return 0; + case MP_STREAM_GET_FILENO: + return o->fd; default: *errcode = EINVAL; return MP_STREAM_ERROR; diff --git a/ports/unix/main.c b/ports/unix/main.c index eb7f7521fa..715ad56589 100644 --- a/ports/unix/main.c +++ b/ports/unix/main.c @@ -511,9 +511,6 @@ MP_NOINLINE int main_(int argc, char **argv) { } } - - - mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_argv), 0); #if defined(MICROPY_UNIX_COVERAGE) diff --git a/ports/unix/modffi.c b/ports/unix/modffi.c index a64d4a7b23..894702330f 100644 --- a/ports/unix/modffi.c +++ b/ports/unix/modffi.c @@ -117,6 +117,10 @@ STATIC ffi_type *char2ffi_type(char c) { return &ffi_type_slong; case 'L': return &ffi_type_ulong; + case 'q': + return &ffi_type_sint64; + case 'Q': + return &ffi_type_uint64; #if MICROPY_PY_BUILTINS_FLOAT case 'f': return &ffi_type_float; diff --git a/ports/unix/modjni.c b/ports/unix/modjni.c index a0d0cb1de6..3ff5c61f50 100644 --- a/ports/unix/modjni.c +++ b/ports/unix/modjni.c @@ -118,7 +118,7 @@ STATIC void print_jobject(const mp_print_t *print, jobject obj) { // jclass STATIC void jclass_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - mp_obj_jclass_t *self = self_in; + mp_obj_jclass_t *self = MP_OBJ_TO_PTR(self_in); if (kind == PRINT_REPR) { mp_printf(print, "cls); } @@ -131,7 +131,7 @@ STATIC void jclass_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin STATIC void jclass_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { if (dest[0] == MP_OBJ_NULL) { // load attribute - mp_obj_jclass_t *self = self_in; + mp_obj_jclass_t *self = MP_OBJ_TO_PTR(self_in); const char *attr = qstr_str(attr_in); jstring field_name = JJ(NewStringUTF, attr); @@ -151,7 +151,7 @@ STATIC void jclass_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { o->meth = NULL; o->obj = self->cls; o->is_static = true; - dest[0] = o; + dest[0] = MP_OBJ_FROM_PTR(o); } } @@ -159,7 +159,7 @@ STATIC mp_obj_t jclass_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const if (n_kw != 0) { mp_raise_TypeError("kwargs not supported"); } - mp_obj_jclass_t *self = self_in; + mp_obj_jclass_t *self = MP_OBJ_TO_PTR(self_in); jarray methods = JJ(CallObjectMethod, self->cls, Class_getConstructors_mid); @@ -186,13 +186,13 @@ STATIC mp_obj_t new_jclass(jclass jc) { mp_obj_jclass_t *o = m_new_obj(mp_obj_jclass_t); o->base.type = &jclass_type; o->cls = jc; - return o; + return MP_OBJ_FROM_PTR(o); } // jobject STATIC void jobject_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - mp_obj_jobject_t *self = self_in; + mp_obj_jobject_t *self = MP_OBJ_TO_PTR(self_in); if (kind == PRINT_REPR) { mp_printf(print, "obj); } @@ -205,7 +205,7 @@ STATIC void jobject_print(const mp_print_t *print, mp_obj_t self_in, mp_print_ki STATIC void jobject_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { if (dest[0] == MP_OBJ_NULL) { // load attribute - mp_obj_jobject_t *self = self_in; + mp_obj_jobject_t *self = MP_OBJ_TO_PTR(self_in); const char *attr = qstr_str(attr_in); jclass obj_class = JJ(GetObjectClass, self->obj); @@ -229,7 +229,7 @@ STATIC void jobject_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { o->meth = NULL; o->obj = self->obj; o->is_static = false; - dest[0] = o; + dest[0] = MP_OBJ_FROM_PTR(o); } } @@ -242,7 +242,7 @@ STATIC void get_jclass_name(jobject obj, char *buf) { } STATIC mp_obj_t jobject_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { - mp_obj_jobject_t *self = self_in; + mp_obj_jobject_t *self = MP_OBJ_TO_PTR(self_in); mp_uint_t idx = mp_obj_get_int(index); char class_name[64]; get_jclass_name(self->obj, class_name); @@ -292,7 +292,7 @@ STATIC mp_obj_t jobject_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) } STATIC mp_obj_t jobject_unary_op(mp_unary_op_t op, mp_obj_t self_in) { - mp_obj_jobject_t *self = self_in; + mp_obj_jobject_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { case MP_UNARY_OP_BOOL: case MP_UNARY_OP_LEN: { @@ -316,9 +316,9 @@ MP_DEFINE_CONST_FUN_OBJ_2(subscr_load_adaptor_obj, subscr_load_adaptor); // .getiter special method which returns iterator which works in terms // of object subscription. -STATIC mp_obj_t subscr_getiter(mp_obj_t self_in) { - mp_obj_t dest[2] = {(mp_obj_t)&subscr_load_adaptor_obj, self_in}; - return mp_obj_new_getitem_iter(dest); +STATIC mp_obj_t subscr_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) { + mp_obj_t dest[2] = {MP_OBJ_FROM_PTR(&subscr_load_adaptor_obj), self_in}; + return mp_obj_new_getitem_iter(dest, iter_buf); } STATIC const mp_obj_type_t jobject_type = { @@ -346,7 +346,7 @@ STATIC mp_obj_t new_jobject(jobject jo) { mp_obj_jobject_t *o = m_new_obj(mp_obj_jobject_t); o->base.type = &jobject_type; o->obj = jo; - return o; + return MP_OBJ_FROM_PTR(o); } } @@ -356,7 +356,7 @@ STATIC mp_obj_t new_jobject(jobject jo) { STATIC void jmethod_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; - mp_obj_jmethod_t *self = self_in; + mp_obj_jmethod_t *self = MP_OBJ_TO_PTR(self_in); // Variable value printed as cast to int mp_printf(print, "", qstr_str(self->name)); } @@ -408,7 +408,7 @@ STATIC bool py2jvalue(const char **jtypesig, mp_obj_t arg, jvalue *out) { if (!is_object) { return false; } - mp_obj_jobject_t *jo = arg; + mp_obj_jobject_t *jo = MP_OBJ_TO_PTR(arg); if (!MATCH(expected_type, "java.lang.Object")) { char class_name[64]; get_jclass_name(jo->obj, class_name); @@ -490,8 +490,8 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool // printf("name=%p meth_name=%s\n", name, meth_name); bool found = true; - for (int i = 0; i < n_args && *arg_types != ')'; i++) { - if (!py2jvalue(&arg_types, args[i], &jargs[i])) { + for (size_t j = 0; j < n_args && *arg_types != ')'; j++) { + if (!py2jvalue(&arg_types, args[j], &jargs[j])) { goto next_method; } @@ -507,13 +507,12 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool if (found) { // printf("found!\n"); jmethodID method_id = JJ(FromReflectedMethod, meth); - jobject res; - mp_obj_t ret; if (is_constr) { JJ(ReleaseStringUTFChars, name_o, decl); - res = JJ(NewObjectA, obj, method_id, jargs); + jobject res = JJ(NewObjectA, obj, method_id, jargs); return new_jobject(res); } else { + mp_obj_t ret; if (MATCH(ret_type, "void")) { JJ(CallVoidMethodA, obj, method_id, jargs); check_exception(); @@ -527,7 +526,7 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool check_exception(); ret = mp_obj_new_bool(res); } else if (is_object_type(ret_type)) { - res = JJ(CallObjectMethodA, obj, method_id, jargs); + jobject res = JJ(CallObjectMethodA, obj, method_id, jargs); check_exception(); ret = new_jobject(res); } else { @@ -556,7 +555,7 @@ STATIC mp_obj_t jmethod_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const if (n_kw != 0) { mp_raise_TypeError("kwargs not supported"); } - mp_obj_jmethod_t *self = self_in; + mp_obj_jmethod_t *self = MP_OBJ_TO_PTR(self_in); const char *name = qstr_str(self->name); // jstring meth_name = JJ(NewStringUTF, name); @@ -585,7 +584,7 @@ STATIC const mp_obj_type_t jmethod_type = { #define LIBJVM_SO "libjvm.so" #endif -STATIC void create_jvm() { +STATIC void create_jvm(void) { JavaVMInitArgs args; JavaVMOption options; options.optionString = "-Djava.class.path=."; @@ -648,7 +647,7 @@ STATIC mp_obj_t mod_jni_cls(mp_obj_t cls_name_in) { mp_obj_jclass_t *o = m_new_obj(mp_obj_jclass_t); o->base.type = &jclass_type; o->cls = cls; - return o; + return MP_OBJ_FROM_PTR(o); } MP_DEFINE_CONST_FUN_OBJ_1(mod_jni_cls_obj, mod_jni_cls); @@ -661,7 +660,7 @@ STATIC mp_obj_t mod_jni_array(mp_obj_t type_in, mp_obj_t size_in) { if (MP_OBJ_IS_TYPE(type_in, &jclass_type)) { - mp_obj_jclass_t *jcls = type_in; + mp_obj_jclass_t *jcls = MP_OBJ_TO_PTR(type_in); res = JJ(NewObjectArray, size, jcls->cls, NULL); } else if (MP_OBJ_IS_STR(type_in)) { @@ -700,8 +699,8 @@ STATIC mp_obj_t mod_jni_array(mp_obj_t type_in, mp_obj_t size_in) { MP_DEFINE_CONST_FUN_OBJ_2(mod_jni_array_obj, mod_jni_array); -STATIC mp_obj_t mod_jni_env() { - return mp_obj_new_int((mp_int_t)env); +STATIC mp_obj_t mod_jni_env(void) { + return mp_obj_new_int((mp_int_t)(uintptr_t)env); } MP_DEFINE_CONST_FUN_OBJ_0(mod_jni_env_obj, mod_jni_env); diff --git a/ports/unix/modos.c b/ports/unix/modos.c index 57e00fa0c5..43d7590518 100644 --- a/ports/unix/modos.c +++ b/ports/unix/modos.c @@ -37,6 +37,7 @@ #include "py/runtime.h" #include "py/objtuple.h" #include "py/mphal.h" +#include "extmod/vfs.h" #include "extmod/misc.h" #ifdef __ANDROID__ @@ -106,16 +107,21 @@ STATIC mp_obj_t mod_os_statvfs(mp_obj_t path_in) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_os_statvfs_obj, mod_os_statvfs); #endif -STATIC mp_obj_t mod_os_unlink(mp_obj_t path_in) { +STATIC mp_obj_t mod_os_remove(mp_obj_t path_in) { const char *path = mp_obj_str_get_str(path_in); + // Note that POSIX requires remove() to be able to delete a directory + // too (act as rmdir()). This is POSIX extenstion to ANSI C semantics + // of that function. But Python remove() follows ANSI C, and explicitly + // required to raise exception on attempt to remove a directory. Thus, + // call POSIX unlink() here. int r = unlink(path); RAISE_ERRNO(r, errno); return mp_const_none; } -STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_os_unlink_obj, mod_os_unlink); +STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_os_remove_obj, mod_os_remove); STATIC mp_obj_t mod_os_system(mp_obj_t cmd_in) { const char *cmd = mp_obj_str_get_str(cmd_in); @@ -172,12 +178,24 @@ STATIC mp_obj_t listdir_next(mp_obj_t self_in) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL)); t->items[0] = mp_obj_new_str(dirent->d_name, strlen(dirent->d_name)); + #ifdef _DIRENT_HAVE_D_TYPE - t->items[1] = MP_OBJ_NEW_SMALL_INT(dirent->d_type); + #ifdef DTTOIF + t->items[1] = MP_OBJ_NEW_SMALL_INT(DTTOIF(dirent->d_type)); + #else + if (dirent->d_type == DT_DIR) { + t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); + } else if (dirent->d_type == DT_REG) { + t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFREG); + } else { + t->items[1] = MP_OBJ_NEW_SMALL_INT(dirent->d_type); + } + #endif #else // DT_UNKNOWN should have 0 value on any reasonable system t->items[1] = MP_OBJ_NEW_SMALL_INT(0); #endif + #ifdef _DIRENT_HAVE_D_INO t->items[2] = MP_OBJ_NEW_SMALL_INT(dirent->d_ino); #else @@ -217,7 +235,7 @@ STATIC const mp_rom_map_elem_t mp_module_os_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&mod_os_statvfs_obj) }, #endif { MP_ROM_QSTR(MP_QSTR_system), MP_ROM_PTR(&mod_os_system_obj) }, - { MP_ROM_QSTR(MP_QSTR_unlink), MP_ROM_PTR(&mod_os_unlink_obj) }, + { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&mod_os_remove_obj) }, { MP_ROM_QSTR(MP_QSTR_getenv), MP_ROM_PTR(&mod_os_getenv_obj) }, { MP_ROM_QSTR(MP_QSTR_mkdir), MP_ROM_PTR(&mod_os_mkdir_obj) }, { MP_ROM_QSTR(MP_QSTR_ilistdir), MP_ROM_PTR(&mod_os_ilistdir_obj) }, diff --git a/ports/unix/moduselect.c b/ports/unix/moduselect.c index 4d0fa37c10..d4c6a8e179 100644 --- a/ports/unix/moduselect.c +++ b/ports/unix/moduselect.c @@ -34,6 +34,7 @@ #include #include "py/runtime.h" +#include "py/stream.h" #include "py/obj.h" #include "py/objlist.h" #include "py/objtuple.h" @@ -65,19 +66,15 @@ typedef struct _mp_obj_poll_t { } mp_obj_poll_t; STATIC int get_fd(mp_obj_t fdlike) { - int fd; - // Shortcut for fdfile compatible types - if (MP_OBJ_IS_TYPE(fdlike, &mp_type_fileio) - #if MICROPY_PY_SOCKET - || MP_OBJ_IS_TYPE(fdlike, &mp_type_socket) - #endif - ) { - mp_obj_fdfile_t *fdfile = MP_OBJ_TO_PTR(fdlike); - fd = fdfile->fd; - } else { - fd = mp_obj_get_int(fdlike); + if (MP_OBJ_IS_OBJ(fdlike)) { + const mp_stream_p_t *stream_p = mp_get_stream_raise(fdlike, MP_STREAM_OP_IOCTL); + int err; + mp_uint_t res = stream_p->ioctl(fdlike, MP_STREAM_GET_FILENO, 0, &err); + if (res != MP_STREAM_ERROR) { + return res; + } } - return fd; + return mp_obj_get_int(fdlike); } /// \method register(obj[, eventmask]) @@ -161,13 +158,13 @@ STATIC mp_obj_t poll_modify(mp_obj_t self_in, mp_obj_t obj_in, mp_obj_t eventmas for (int i = self->len - 1; i >= 0; i--) { if (entries->fd == fd) { entries->events = mp_obj_get_int(eventmask_in); - break; + return mp_const_none; } entries++; } - // TODO raise KeyError if obj didn't exist in map - return mp_const_none; + // obj doesn't exist in poller + mp_raise_OSError(MP_ENOENT); } MP_DEFINE_CONST_FUN_OBJ_3(poll_modify_obj, poll_modify); diff --git a/ports/unix/modusocket.c b/ports/unix/modusocket.c index 89480c0cc6..24778b6b55 100644 --- a/ports/unix/modusocket.c +++ b/ports/unix/modusocket.c @@ -37,6 +37,7 @@ #include #include #include +#include #include "py/objtuple.h" #include "py/objstr.h" @@ -67,6 +68,7 @@ typedef struct _mp_obj_socket_t { mp_obj_base_t base; int fd; + bool blocking; } mp_obj_socket_t; const mp_obj_type_t mp_type_socket; @@ -80,6 +82,7 @@ STATIC mp_obj_socket_t *socket_new(int fd) { mp_obj_socket_t *o = m_new_obj(mp_obj_socket_t); o->base.type = &mp_type_socket; o->fd = fd; + o->blocking = true; return o; } @@ -94,7 +97,14 @@ STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errc mp_obj_socket_t *o = MP_OBJ_TO_PTR(o_in); mp_int_t r = read(o->fd, buf, size); if (r == -1) { - *errcode = errno; + int err = errno; + // On blocking socket, we get EAGAIN in case SO_RCVTIMEO/SO_SNDTIMEO + // timed out, and need to convert that to ETIMEDOUT. + if (err == EAGAIN && o->blocking) { + err = MP_ETIMEDOUT; + } + + *errcode = err; return MP_STREAM_ERROR; } return r; @@ -104,7 +114,14 @@ STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, in mp_obj_socket_t *o = MP_OBJ_TO_PTR(o_in); mp_int_t r = write(o->fd, buf, size); if (r == -1) { - *errcode = errno; + int err = errno; + // On blocking socket, we get EAGAIN in case SO_RCVTIMEO/SO_SNDTIMEO + // timed out, and need to convert that to ETIMEDOUT. + if (err == EAGAIN && o->blocking) { + err = MP_ETIMEDOUT; + } + + *errcode = err; return MP_STREAM_ERROR; } return r; @@ -125,6 +142,9 @@ STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, i close(self->fd); return 0; + case MP_STREAM_GET_FILENO: + return self->fd; + default: *errcode = MP_EINVAL; return MP_STREAM_ERROR; @@ -309,10 +329,49 @@ STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { } flags = fcntl(self->fd, F_SETFL, flags); RAISE_ERRNO(flags, errno); + self->blocking = val; return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); +STATIC mp_obj_t socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) { + mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in); + struct timeval tv = {0,}; + bool new_blocking = true; + + if (timeout_in == mp_const_none) { + setsockopt(self->fd, SOL_SOCKET, SO_RCVTIMEO, NULL, 0); + setsockopt(self->fd, SOL_SOCKET, SO_SNDTIMEO, NULL, 0); + } else { + #if MICROPY_PY_BUILTINS_FLOAT + mp_float_t val = mp_obj_get_float(timeout_in); + double ipart; + tv.tv_usec = round(modf(val, &ipart) * 1000000); + tv.tv_sec = ipart; + #else + tv.tv_sec = mp_obj_get_int(timeout_in); + #endif + + // For SO_RCVTIMEO/SO_SNDTIMEO, zero timeout means infinity, but + // for Python API it means non-blocking. + if (tv.tv_sec == 0 && tv.tv_usec == 0) { + new_blocking = false; + } else { + setsockopt(self->fd, SOL_SOCKET, SO_RCVTIMEO, + &tv, sizeof(struct timeval)); + setsockopt(self->fd, SOL_SOCKET, SO_SNDTIMEO, + &tv, sizeof(struct timeval)); + } + } + + if (self->blocking != new_blocking) { + socket_setblocking(self_in, mp_obj_new_bool(new_blocking)); + } + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_settimeout_obj, socket_settimeout); + STATIC mp_obj_t socket_makefile(size_t n_args, const mp_obj_t *args) { // TODO: CPython explicitly says that closing returned object doesn't close // the original socket (Python2 at all says that fd is dup()ed). But we @@ -368,6 +427,7 @@ STATIC const mp_rom_map_elem_t usocket_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&socket_sendto_obj) }, { MP_ROM_QSTR(MP_QSTR_setsockopt), MP_ROM_PTR(&socket_setsockopt_obj) }, { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) }, + { MP_ROM_QSTR(MP_QSTR_settimeout), MP_ROM_PTR(&socket_settimeout_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, }; diff --git a/ports/unix/mpconfigport.h b/ports/unix/mpconfigport.h index bae0245d05..01e5876b0b 100644 --- a/ports/unix/mpconfigport.h +++ b/ports/unix/mpconfigport.h @@ -54,7 +54,7 @@ #define MICROPY_DEBUG_PRINTERS (1) // Printing debug to stderr may give tests which // check stdout a chance to pass, etc. -#define MICROPY_DEBUG_PRINTER_DEST mp_stderr_print +#define MICROPY_DEBUG_PRINTER (&mp_stderr_print) #define MICROPY_READER_POSIX (1) #define MICROPY_USE_READLINE_HISTORY (1) #define MICROPY_HELPER_REPL (1) @@ -125,7 +125,9 @@ #define MICROPY_PY_UTIMEQ (1) #define MICROPY_PY_UHASHLIB (1) #if MICROPY_PY_USSL +#define MICROPY_PY_UHASHLIB_MD5 (1) #define MICROPY_PY_UHASHLIB_SHA1 (1) +#define MICROPY_PY_UCRYPTOLIB (1) #endif #define MICROPY_PY_UBINASCII (1) #define MICROPY_PY_UBINASCII_CRC32 (1) @@ -133,9 +135,9 @@ #ifndef MICROPY_PY_USELECT_POSIX #define MICROPY_PY_USELECT_POSIX (1) #endif -#define MICROPY_PY_WEBSOCKET (1) -#define MICROPY_PY_MACHINE (1) -#define MICROPY_PY_MACHINE_PULSE (1) +#define MICROPY_PY_WEBSOCKET (0) +#define MICROPY_PY_MACHINE (0) +#define MICROPY_PY_MACHINE_PULSE (0) #define MICROPY_MACHINE_MEM_GET_READ_ADDR mod_machine_mem_get_addr #define MICROPY_MACHINE_MEM_GET_WRITE_ADDR mod_machine_mem_get_addr @@ -189,6 +191,11 @@ extern const struct _mp_obj_module_t mp_module_jni; #else #define MICROPY_PY_FFI_DEF #endif +#if MICROPY_PY_MACHINE +#define MICROPY_PY_MACHINE_DEF { MP_ROM_QSTR(MP_QSTR_umachine), MP_ROM_PTR(&mp_module_machine) }, +#else +#define MICROPY_PY_MACHINE_DEF +#endif #if MICROPY_PY_JNI #define MICROPY_PY_JNI_DEF { MP_ROM_QSTR(MP_QSTR_jni), MP_ROM_PTR(&mp_module_jni) }, #else @@ -220,7 +227,7 @@ extern const struct _mp_obj_module_t mp_module_jni; MICROPY_PY_JNI_DEF \ MICROPY_PY_UTIME_DEF \ MICROPY_PY_SOCKET_DEF \ - { MP_ROM_QSTR(MP_QSTR_umachine), MP_ROM_PTR(&mp_module_machine) }, \ + MICROPY_PY_MACHINE_DEF \ MICROPY_PY_UOS_DEF \ MICROPY_PY_USELECT_DEF \ MICROPY_PY_TERMIOS_DEF \ diff --git a/ports/unix/mpconfigport.mk b/ports/unix/mpconfigport.mk index 6bb1c9693f..d0e5686024 100644 --- a/ports/unix/mpconfigport.mk +++ b/ports/unix/mpconfigport.mk @@ -24,11 +24,11 @@ MICROPY_PY_SOCKET = 1 MICROPY_PY_FFI = 1 # ussl module requires one of the TLS libraries below -MICROPY_PY_USSL = 1 +MICROPY_PY_USSL = 0 # axTLS has minimal size and fully integrated with MicroPython, but # implements only a subset of modern TLS functionality, so may have # problems with some servers. -MICROPY_SSL_AXTLS = 1 +MICROPY_SSL_AXTLS = 0 # mbedTLS is more up to date and complete implementation, but also # more bloated. Configuring and building of mbedTLS should be done # outside of MicroPython, it can just link with mbedTLS library. diff --git a/ports/unix/mpconfigport_coverage.h b/ports/unix/mpconfigport_coverage.h index 468d69a733..27086a167d 100644 --- a/ports/unix/mpconfigport_coverage.h +++ b/ports/unix/mpconfigport_coverage.h @@ -32,23 +32,32 @@ #include +#define MICROPY_OPT_MATH_FACTORIAL (1) #define MICROPY_FLOAT_HIGH_QUALITY_HASH (1) #define MICROPY_ENABLE_SCHEDULER (1) #define MICROPY_READER_VFS (1) +#define MICROPY_MODULE_GETATTR (1) #define MICROPY_PY_DELATTR_SETATTR (1) #define MICROPY_PY_REVERSE_SPECIAL_METHODS (1) #define MICROPY_PY_BUILTINS_RANGE_BINOP (1) #define MICROPY_PY_BUILTINS_HELP (1) #define MICROPY_PY_BUILTINS_HELP_MODULES (1) #define MICROPY_PY_SYS_GETSIZEOF (1) +#define MICROPY_PY_MATH_FACTORIAL (1) #define MICROPY_PY_URANDOM_EXTRA_FUNCS (1) #define MICROPY_PY_IO_BUFFEREDWRITER (1) #define MICROPY_PY_IO_RESOURCE_STREAM (1) +#define MICROPY_PY_URE_MATCH_GROUPS (1) +#define MICROPY_PY_URE_MATCH_SPAN_START_END (1) +#define MICROPY_PY_URE_SUB (1) #define MICROPY_VFS_POSIX (1) #undef MICROPY_VFS_FAT #define MICROPY_VFS_FAT (1) #define MICROPY_FATFS_USE_LABEL (1) #define MICROPY_PY_FRAMEBUF (1) +#define MICROPY_PY_COLLECTIONS_NAMEDTUPLE__ASDICT (1) +#define MICROPY_PY_COLLECTIONS_ORDEREDDICT (1) +#define MICROPY_PY_UCRYPTOLIB (1) // TODO these should be generic, not bound to fatfs #define mp_type_fileio mp_type_vfs_posix_fileio diff --git a/ports/unix/mpconfigport_minimal.h b/ports/unix/mpconfigport_minimal.h index 1a13d5725b..3977818b03 100644 --- a/ports/unix/mpconfigport_minimal.h +++ b/ports/unix/mpconfigport_minimal.h @@ -65,6 +65,8 @@ #define MICROPY_PY_BUILTINS_REVERSED (0) #define MICROPY_PY_BUILTINS_SET (0) #define MICROPY_PY_BUILTINS_SLICE (0) +#define MICROPY_PY_BUILTINS_STR_COUNT (0) +#define MICROPY_PY_BUILTINS_STR_OP_MODULO (0) #define MICROPY_PY_BUILTINS_STR_UNICODE (0) #define MICROPY_PY_BUILTINS_PROPERTY (0) #define MICROPY_PY_BUILTINS_MIN_MAX (0) diff --git a/py/argcheck.c b/py/argcheck.c index 7fba9dc274..684fb204f0 100644 --- a/py/argcheck.c +++ b/py/argcheck.c @@ -31,27 +31,20 @@ #include "supervisor/shared/translate.h" - -void mp_arg_check_num(size_t n_args, mp_map_t *kw_args, size_t n_args_min, size_t n_args_max, bool takes_kw) { - size_t n_kw = 0; - if (kw_args != NULL) { - n_kw = kw_args->used; - } - mp_arg_check_num_kw_array(n_args, n_kw, n_args_min, n_args_max, takes_kw); -} - -void mp_arg_check_num_kw_array(size_t n_args, size_t n_kw, size_t n_args_min, size_t n_args_max, bool takes_kw) { - // NOTE(tannewt): This prevents this function from being optimized away. - // Without it, functions can crash when reading invalid args. - __asm volatile (""); +void mp_arg_check_num_sig(size_t n_args, size_t n_kw, uint32_t sig) { // TODO maybe take the function name as an argument so we can print nicer error messages - if (n_kw > 0 && !takes_kw) { - #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_arg_error_terse_mismatch(); - #else - mp_raise_TypeError(translate("function does not take keyword arguments")); - #endif + // The reverse of MP_OBJ_FUN_MAKE_SIG + bool takes_kw = sig & 1; + size_t n_args_min = sig >> 17; + size_t n_args_max = (sig >> 1) & 0xffff; + + if (n_kw && !takes_kw) { + if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { + mp_arg_error_terse_mismatch(); + } else { + mp_raise_TypeError(translate("function doesn't take keyword arguments")); + } } if (n_args_min == n_args_max) { @@ -85,6 +78,18 @@ void mp_arg_check_num_kw_array(size_t n_args, size_t n_kw, size_t n_args_min, si } } +inline void mp_arg_check_num(size_t n_args, mp_map_t *kw_args, size_t n_args_min, size_t n_args_max, bool takes_kw) { + size_t n_kw = 0; + if (kw_args != NULL) { + n_kw = kw_args->used; + } + mp_arg_check_num_sig(n_args, n_kw, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, takes_kw)); +} + +inline void mp_arg_check_num_kw_array(size_t n_args, size_t n_kw, size_t n_args_min, size_t n_args_max, bool takes_kw) { + mp_arg_check_num_sig(n_args, n_kw, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, takes_kw)); +} + void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals) { size_t pos_found = 0, kws_found = 0; for (size_t i = 0; i < n_allowed; i++) { diff --git a/py/asmarm.c b/py/asmarm.c index 644548cfd4..871f0bb486 100644 --- a/py/asmarm.c +++ b/py/asmarm.c @@ -273,6 +273,21 @@ void asm_arm_mov_reg_local_addr(asm_arm_t *as, uint rd, int local_num) { emit_al(as, asm_arm_op_add_imm(rd, ASM_ARM_REG_SP, local_num << 2)); } +void asm_arm_mov_reg_pcrel(asm_arm_t *as, uint reg_dest, uint label) { + assert(label < as->base.max_num_labels); + mp_uint_t dest = as->base.label_offsets[label]; + mp_int_t rel = dest - as->base.code_offset; + rel -= 12 + 8; // adjust for load of rel, and then PC+8 prefetch of add_reg_reg_reg + + // To load rel int reg_dest, insert immediate into code and jump over it + emit_al(as, 0x59f0000 | (reg_dest << 12)); // ldr rd, [pc] + emit_al(as, 0xa000000); // b pc + emit(as, rel); + + // Do reg_dest += PC + asm_arm_add_reg_reg_reg(as, reg_dest, reg_dest, ASM_ARM_REG_PC); +} + void asm_arm_lsl_reg_reg(asm_arm_t *as, uint rd, uint rs) { // mov rd, rd, lsl rs emit_al(as, 0x1a00010 | (rd << 12) | (rs << 8) | rd); @@ -347,19 +362,15 @@ void asm_arm_b_label(asm_arm_t *as, uint label) { asm_arm_bcc_label(as, ASM_ARM_CC_AL, label); } -void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp) { - // If the table offset fits into the ldr instruction - if (fun_id < (0x1000 / 4)) { - emit_al(as, asm_arm_op_mov_reg(ASM_ARM_REG_LR, ASM_ARM_REG_PC)); // mov lr, pc - emit_al(as, 0x597f000 | (fun_id << 2)); // ldr pc, [r7, #fun_id*4] - return; - } +void asm_arm_bl_ind(asm_arm_t *as, uint fun_id, uint reg_temp) { + // The table offset should fit into the ldr instruction + assert(fun_id < (0x1000 / 4)); + emit_al(as, asm_arm_op_mov_reg(ASM_ARM_REG_LR, ASM_ARM_REG_PC)); // mov lr, pc + emit_al(as, 0x597f000 | (fun_id << 2)); // ldr pc, [r7, #fun_id*4] +} - emit_al(as, 0x59f0004 | (reg_temp << 12)); // ldr rd, [pc, #4] - // Set lr after fun_ptr - emit_al(as, asm_arm_op_add_imm(ASM_ARM_REG_LR, ASM_ARM_REG_PC, 4)); // add lr, pc, #4 - emit_al(as, asm_arm_op_mov_reg(ASM_ARM_REG_PC, reg_temp)); // mov pc, reg_temp - emit(as, (uint)fun_ptr); +void asm_arm_bx_reg(asm_arm_t *as, uint reg_src) { + emit_al(as, 0x012fff10 | reg_src); } #endif // MICROPY_EMIT_ARM diff --git a/py/asmarm.h b/py/asmarm.h index f63106a9b6..76850cb468 100644 --- a/py/asmarm.h +++ b/py/asmarm.h @@ -98,6 +98,7 @@ void asm_arm_and_reg_reg_reg(asm_arm_t *as, uint rd, uint rn, uint rm); void asm_arm_eor_reg_reg_reg(asm_arm_t *as, uint rd, uint rn, uint rm); void asm_arm_orr_reg_reg_reg(asm_arm_t *as, uint rd, uint rn, uint rm); void asm_arm_mov_reg_local_addr(asm_arm_t *as, uint rd, int local_num); +void asm_arm_mov_reg_pcrel(asm_arm_t *as, uint reg_dest, uint label); void asm_arm_lsl_reg_reg(asm_arm_t *as, uint rd, uint rs); void asm_arm_asr_reg_reg(asm_arm_t *as, uint rd, uint rs); @@ -120,7 +121,11 @@ void asm_arm_pop(asm_arm_t *as, uint reglist); // control flow void asm_arm_bcc_label(asm_arm_t *as, int cond, uint label); void asm_arm_b_label(asm_arm_t *as, uint label); -void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp); +void asm_arm_bl_ind(asm_arm_t *as, uint fun_id, uint reg_temp); +void asm_arm_bx_reg(asm_arm_t *as, uint reg_src); + +// Holds a pointer to mp_fun_table +#define ASM_ARM_REG_FUN_TABLE ASM_ARM_REG_R7 #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -144,18 +149,21 @@ void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp); #define REG_LOCAL_3 ASM_ARM_REG_R6 #define REG_LOCAL_NUM (3) +// Holds a pointer to mp_fun_table +#define REG_FUN_TABLE ASM_ARM_REG_FUN_TABLE + #define ASM_T asm_arm_t #define ASM_END_PASS asm_arm_end_pass #define ASM_ENTRY asm_arm_entry #define ASM_EXIT asm_arm_exit #define ASM_JUMP asm_arm_b_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ asm_arm_cmp_reg_i8(as, reg, 0); \ asm_arm_bcc_label(as, ASM_ARM_CC_EQ, label); \ } while (0) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ do { \ asm_arm_cmp_reg_i8(as, reg, 0); \ asm_arm_bcc_label(as, ASM_ARM_CC_NE, label); \ @@ -165,14 +173,15 @@ void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp); asm_arm_cmp_reg_reg(as, reg1, reg2); \ asm_arm_bcc_label(as, ASM_ARM_CC_EQ, label); \ } while (0) -#define ASM_CALL_IND(as, ptr, idx) asm_arm_bl_ind(as, ptr, idx, ASM_ARM_REG_R3) +#define ASM_JUMP_REG(as, reg) asm_arm_bx_reg((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_arm_bl_ind(as, idx, ASM_ARM_REG_R3) #define ASM_MOV_LOCAL_REG(as, local_num, reg_src) asm_arm_mov_local_reg((as), (local_num), (reg_src)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_arm_mov_reg_i32((as), (reg_dest), (imm)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_arm_mov_reg_i32((as), (reg_dest), (imm)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_arm_mov_reg_local((as), (reg_dest), (local_num)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_arm_mov_reg_reg((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_arm_mov_reg_local_addr((as), (reg_dest), (local_num)) +#define ASM_MOV_REG_PCREL(as, reg_dest, label) asm_arm_mov_reg_pcrel((as), (reg_dest), (label)) #define ASM_LSL_REG_REG(as, reg_dest, reg_shift) asm_arm_lsl_reg_reg((as), (reg_dest), (reg_shift)) #define ASM_ASR_REG_REG(as, reg_dest, reg_shift) asm_arm_asr_reg_reg((as), (reg_dest), (reg_shift)) diff --git a/py/asmthumb.c b/py/asmthumb.c index 33ec420046..df7c88568c 100644 --- a/py/asmthumb.c +++ b/py/asmthumb.c @@ -36,6 +36,8 @@ #include "py/mphal.h" #include "py/asmthumb.h" +#define UNSIGNED_FIT5(x) ((uint32_t)(x) < 32) +#define UNSIGNED_FIT7(x) ((uint32_t)(x) < 128) #define UNSIGNED_FIT8(x) (((x) & 0xffffff00) == 0) #define UNSIGNED_FIT16(x) (((x) & 0xffff0000) == 0) #define SIGNED_FIT8(x) (((x) & 0xffffff80) == 0) || (((x) & 0xffffff80) == 0xffffff80) @@ -43,6 +45,15 @@ #define SIGNED_FIT12(x) (((x) & 0xfffff800) == 0) || (((x) & 0xfffff800) == 0xfffff800) #define SIGNED_FIT23(x) (((x) & 0xffc00000) == 0) || (((x) & 0xffc00000) == 0xffc00000) +// Note: these actually take an imm12 but the high-bit is not encoded here +#define OP_ADD_W_RRI_HI(reg_src) (0xf200 | (reg_src)) +#define OP_ADD_W_RRI_LO(reg_dest, imm11) ((imm11 << 4 & 0x7000) | reg_dest << 8 | (imm11 & 0xff)) +#define OP_SUB_W_RRI_HI(reg_src) (0xf2a0 | (reg_src)) +#define OP_SUB_W_RRI_LO(reg_dest, imm11) ((imm11 << 4 & 0x7000) | reg_dest << 8 | (imm11 & 0xff)) + +#define OP_LDR_W_HI(reg_base) (0xf8d0 | (reg_base)) +#define OP_LDR_W_LO(reg_dest, imm12) ((reg_dest) << 12 | (imm12)) + static inline byte *asm_thumb_get_cur_to_write_bytes(asm_thumb_t *as, int n) { return mp_asm_base_get_cur_to_write_bytes(&as->base, n); } @@ -51,7 +62,7 @@ void asm_thumb_end_pass(asm_thumb_t *as) { (void)as; // could check labels are resolved... - #if defined(MCU_SERIES_F7) + #if defined(__ICACHE_PRESENT) && __ICACHE_PRESENT == 1 if (as->base.pass == MP_ASM_PASS_EMIT) { // flush D-cache, so the code emitted is stored in memory MP_HAL_CLEAN_DCACHE(as->base.code_base, as->base.code_size); @@ -89,6 +100,7 @@ STATIC void asm_thumb_write_word32(asm_thumb_t *as, int w32) { #define OP_POP_RLIST(rlolist) (0xbc00 | (rlolist)) #define OP_POP_RLIST_PC(rlolist) (0xbc00 | 0x0100 | (rlolist)) +// The number of words must fit in 7 unsigned bits #define OP_ADD_SP(num_words) (0xb000 | (num_words)) #define OP_SUB_SP(num_words) (0xb080 | (num_words)) @@ -142,7 +154,11 @@ void asm_thumb_entry(asm_thumb_t *as, int num_locals) { } asm_thumb_op16(as, OP_PUSH_RLIST_LR(reglist)); if (stack_adjust > 0) { - asm_thumb_op16(as, OP_SUB_SP(stack_adjust)); + if (UNSIGNED_FIT7(stack_adjust)) { + asm_thumb_op16(as, OP_SUB_SP(stack_adjust)); + } else { + asm_thumb_op32(as, OP_SUB_W_RRI_HI(ASM_THUMB_REG_SP), OP_SUB_W_RRI_LO(ASM_THUMB_REG_SP, stack_adjust * 4)); + } } as->push_reglist = reglist; as->stack_adjust = stack_adjust; @@ -150,7 +166,11 @@ void asm_thumb_entry(asm_thumb_t *as, int num_locals) { void asm_thumb_exit(asm_thumb_t *as) { if (as->stack_adjust > 0) { - asm_thumb_op16(as, OP_ADD_SP(as->stack_adjust)); + if (UNSIGNED_FIT7(as->stack_adjust)) { + asm_thumb_op16(as, OP_ADD_SP(as->stack_adjust)); + } else { + asm_thumb_op32(as, OP_ADD_W_RRI_HI(ASM_THUMB_REG_SP), OP_ADD_W_RRI_LO(ASM_THUMB_REG_SP, as->stack_adjust * 4)); + } } asm_thumb_op16(as, OP_POP_RLIST_PC(as->push_reglist)); } @@ -269,21 +289,6 @@ void asm_thumb_mov_reg_i32_optimised(asm_thumb_t *as, uint reg_dest, int i32) { } } -// i32 is stored as a full word in the code, and aligned to machine-word boundary -// TODO this is very inefficient, improve it! -void asm_thumb_mov_reg_i32_aligned(asm_thumb_t *as, uint reg_dest, int i32) { - // align on machine-word + 2 - if ((as->base.code_offset & 3) == 0) { - asm_thumb_op16(as, ASM_THUMB_OP_NOP); - } - // jump over the i32 value (instruction prefetch adds 2 to PC) - asm_thumb_op16(as, OP_B_N(2)); - // store i32 on machine-word aligned boundary - mp_asm_base_data(&as->base, 4, i32); - // do the actual load of the i32 value - asm_thumb_mov_reg_i32_optimised(as, reg_dest, i32); -} - #define OP_STR_TO_SP_OFFSET(rlo_dest, word_offset) (0x9000 | ((rlo_dest) << 8) | ((word_offset) & 0x00ff)) #define OP_LDR_FROM_SP_OFFSET(rlo_dest, word_offset) (0x9800 | ((rlo_dest) << 8) | ((word_offset) & 0x00ff)) @@ -310,6 +315,27 @@ void asm_thumb_mov_reg_local_addr(asm_thumb_t *as, uint rlo_dest, int local_num) asm_thumb_op16(as, OP_ADD_REG_SP_OFFSET(rlo_dest, word_offset)); } +void asm_thumb_mov_reg_pcrel(asm_thumb_t *as, uint rlo_dest, uint label) { + mp_uint_t dest = get_label_dest(as, label); + mp_int_t rel = dest - as->base.code_offset; + rel -= 4 + 4; // adjust for mov_reg_i16 and then PC+4 prefetch of add_reg_reg + rel |= 1; // to stay in Thumb state when jumping to this address + asm_thumb_mov_reg_i16(as, ASM_THUMB_OP_MOVW, rlo_dest, rel); // 4 bytes + asm_thumb_add_reg_reg(as, rlo_dest, ASM_THUMB_REG_R15); // 2 bytes +} + +static inline void asm_thumb_ldr_reg_reg_i12(asm_thumb_t *as, uint reg_dest, uint reg_base, uint word_offset) { + asm_thumb_op32(as, OP_LDR_W_HI(reg_base), OP_LDR_W_LO(reg_dest, word_offset * 4)); +} + +void asm_thumb_ldr_reg_reg_i12_optimised(asm_thumb_t *as, uint reg_dest, uint reg_base, uint word_offset) { + if (reg_dest < ASM_THUMB_REG_R8 && reg_base < ASM_THUMB_REG_R8 && UNSIGNED_FIT5(word_offset)) { + asm_thumb_ldr_rlo_rlo_i5(as, reg_dest, reg_base, word_offset); + } else { + asm_thumb_ldr_reg_reg_i12(as, reg_dest, reg_base, word_offset); + } +} + // this could be wrong, because it should have a range of +/- 16MiB... #define OP_BW_HI(byte_offset) (0xf000 | (((byte_offset) >> 12) & 0x07ff)) #define OP_BW_LO(byte_offset) (0xb800 | (((byte_offset) >> 1) & 0x07ff)) @@ -355,25 +381,10 @@ void asm_thumb_bcc_label(asm_thumb_t *as, int cond, uint label) { #define OP_BLX(reg) (0x4780 | ((reg) << 3)) #define OP_SVC(arg) (0xdf00 | (arg)) -void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp) { - /* TODO make this use less bytes - uint rlo_base = ASM_THUMB_REG_R3; - uint rlo_dest = ASM_THUMB_REG_R7; - uint word_offset = 4; - asm_thumb_op16(as, 0x0000); - asm_thumb_op16(as, 0x6800 | (word_offset << 6) | (rlo_base << 3) | rlo_dest); // ldr rlo_dest, [rlo_base, #offset] - asm_thumb_op16(as, 0x4780 | (ASM_THUMB_REG_R9 << 3)); // blx reg - */ - - if (fun_id < 32) { - // load ptr to function from table, indexed by fun_id (must be in range 0-31); 4 bytes - asm_thumb_op16(as, ASM_THUMB_FORMAT_9_10_ENCODE(ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, reg_temp, ASM_THUMB_REG_R7, fun_id)); - asm_thumb_op16(as, OP_BLX(reg_temp)); - } else { - // load ptr to function into register using immediate; 6 bytes - asm_thumb_mov_reg_i32(as, reg_temp, (mp_uint_t)fun_ptr); - asm_thumb_op16(as, OP_BLX(reg_temp)); - } +void asm_thumb_bl_ind(asm_thumb_t *as, uint fun_id, uint reg_temp) { + // Load ptr to function from table, indexed by fun_id, then call it + asm_thumb_ldr_reg_reg_i12_optimised(as, reg_temp, ASM_THUMB_REG_FUN_TABLE, fun_id); + asm_thumb_op16(as, OP_BLX(reg_temp)); } #endif // MICROPY_EMIT_THUMB || MICROPY_EMIT_INLINE_THUMB diff --git a/py/asmthumb.h b/py/asmthumb.h index 6acf305a2d..b4828b125d 100644 --- a/py/asmthumb.h +++ b/py/asmthumb.h @@ -46,6 +46,7 @@ #define ASM_THUMB_REG_R13 (13) #define ASM_THUMB_REG_R14 (14) #define ASM_THUMB_REG_R15 (15) +#define ASM_THUMB_REG_SP (ASM_THUMB_REG_R13) #define ASM_THUMB_REG_LR (REG_R14) #define ASM_THUMB_CC_EQ (0x0) @@ -195,6 +196,26 @@ static inline void asm_thumb_cmp_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rl asm_thumb_format_4(as, ASM_THUMB_FORMAT_4_CMP, rlo_dest, rlo_src); } +// FORMAT 5: hi register operations (add, cmp, mov, bx) +// For add/cmp/mov, at least one of the args must be a high register + +#define ASM_THUMB_FORMAT_5_ADD (0x4400) +#define ASM_THUMB_FORMAT_5_BX (0x4700) + +#define ASM_THUMB_FORMAT_5_ENCODE(op, r_dest, r_src) \ + ((op) | ((r_dest) << 4 & 0x0080) | ((r_src) << 3) | ((r_dest) & 0x0007)) + +static inline void asm_thumb_format_5(asm_thumb_t *as, uint op, uint r_dest, uint r_src) { + asm_thumb_op16(as, ASM_THUMB_FORMAT_5_ENCODE(op, r_dest, r_src)); +} + +static inline void asm_thumb_add_reg_reg(asm_thumb_t *as, uint r_dest, uint r_src) { + asm_thumb_format_5(as, ASM_THUMB_FORMAT_5_ADD, r_dest, r_src); +} +static inline void asm_thumb_bx_reg(asm_thumb_t *as, uint r_src) { + asm_thumb_format_5(as, ASM_THUMB_FORMAT_5_BX, 0, r_src); +} + // FORMAT 9: load/store with immediate offset // For word transfers the offset must be aligned, and >>2 @@ -251,14 +272,19 @@ bool asm_thumb_bl_label(asm_thumb_t *as, uint label); void asm_thumb_mov_reg_i32(asm_thumb_t *as, uint reg_dest, mp_uint_t i32_src); // convenience void asm_thumb_mov_reg_i32_optimised(asm_thumb_t *as, uint reg_dest, int i32_src); // convenience -void asm_thumb_mov_reg_i32_aligned(asm_thumb_t *as, uint reg_dest, int i32); // convenience void asm_thumb_mov_local_reg(asm_thumb_t *as, int local_num_dest, uint rlo_src); // convenience void asm_thumb_mov_reg_local(asm_thumb_t *as, uint rlo_dest, int local_num); // convenience void asm_thumb_mov_reg_local_addr(asm_thumb_t *as, uint rlo_dest, int local_num); // convenience +void asm_thumb_mov_reg_pcrel(asm_thumb_t *as, uint rlo_dest, uint label); + +void asm_thumb_ldr_reg_reg_i12_optimised(asm_thumb_t *as, uint reg_dest, uint reg_base, uint byte_offset); // convenience void asm_thumb_b_label(asm_thumb_t *as, uint label); // convenience: picks narrow or wide branch void asm_thumb_bcc_label(asm_thumb_t *as, int cc, uint label); // convenience: picks narrow or wide branch -void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp); // convenience +void asm_thumb_bl_ind(asm_thumb_t *as, uint fun_id, uint reg_temp); // convenience + +// Holds a pointer to mp_fun_table +#define ASM_THUMB_REG_FUN_TABLE ASM_THUMB_REG_R7 #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -283,18 +309,20 @@ void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp #define REG_LOCAL_3 ASM_THUMB_REG_R6 #define REG_LOCAL_NUM (3) +#define REG_FUN_TABLE ASM_THUMB_REG_FUN_TABLE + #define ASM_T asm_thumb_t #define ASM_END_PASS asm_thumb_end_pass #define ASM_ENTRY asm_thumb_entry #define ASM_EXIT asm_thumb_exit #define ASM_JUMP asm_thumb_b_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ asm_thumb_cmp_rlo_i8(as, reg, 0); \ asm_thumb_bcc_label(as, ASM_THUMB_CC_EQ, label); \ } while (0) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ do { \ asm_thumb_cmp_rlo_i8(as, reg, 0); \ asm_thumb_bcc_label(as, ASM_THUMB_CC_NE, label); \ @@ -304,14 +332,15 @@ void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp asm_thumb_cmp_rlo_rlo(as, reg1, reg2); \ asm_thumb_bcc_label(as, ASM_THUMB_CC_EQ, label); \ } while (0) -#define ASM_CALL_IND(as, ptr, idx) asm_thumb_bl_ind(as, ptr, idx, ASM_THUMB_REG_R3) +#define ASM_JUMP_REG(as, reg) asm_thumb_bx_reg((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_thumb_bl_ind(as, idx, ASM_THUMB_REG_R3) #define ASM_MOV_LOCAL_REG(as, local_num, reg) asm_thumb_mov_local_reg((as), (local_num), (reg)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_thumb_mov_reg_i32_optimised((as), (reg_dest), (imm)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_thumb_mov_reg_i32_aligned((as), (reg_dest), (imm)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_thumb_mov_reg_local((as), (reg_dest), (local_num)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_thumb_mov_reg_reg((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_thumb_mov_reg_local_addr((as), (reg_dest), (local_num)) +#define ASM_MOV_REG_PCREL(as, rlo_dest, label) asm_thumb_mov_reg_pcrel((as), (rlo_dest), (label)) #define ASM_LSL_REG_REG(as, reg_dest, reg_shift) asm_thumb_format_4((as), ASM_THUMB_FORMAT_4_LSL, (reg_dest), (reg_shift)) #define ASM_ASR_REG_REG(as, reg_dest, reg_shift) asm_thumb_format_4((as), ASM_THUMB_FORMAT_4_ASR, (reg_dest), (reg_shift)) @@ -323,7 +352,7 @@ void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp #define ASM_MUL_REG_REG(as, reg_dest, reg_src) asm_thumb_format_4((as), ASM_THUMB_FORMAT_4_MUL, (reg_dest), (reg_src)) #define ASM_LOAD_REG_REG(as, reg_dest, reg_base) asm_thumb_ldr_rlo_rlo_i5((as), (reg_dest), (reg_base), 0) -#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_thumb_ldr_rlo_rlo_i5((as), (reg_dest), (reg_base), (word_offset)) +#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_thumb_ldr_reg_reg_i12_optimised((as), (reg_dest), (reg_base), (word_offset)) #define ASM_LOAD8_REG_REG(as, reg_dest, reg_base) asm_thumb_ldrb_rlo_rlo_i5((as), (reg_dest), (reg_base), 0) #define ASM_LOAD16_REG_REG(as, reg_dest, reg_base) asm_thumb_ldrh_rlo_rlo_i5((as), (reg_dest), (reg_base), 0) #define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) asm_thumb_ldr_rlo_rlo_i5((as), (reg_dest), (reg_base), 0) diff --git a/py/asmx64.c b/py/asmx64.c index 4e45f77a40..b881491121 100644 --- a/py/asmx64.c +++ b/py/asmx64.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George + * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -73,8 +73,10 @@ #define OPCODE_CMP_R64_WITH_RM64 (0x39) /* /r */ // #define OPCODE_CMP_RM32_WITH_R32 (0x3b) #define OPCODE_TEST_R8_WITH_RM8 (0x84) /* /r */ +#define OPCODE_TEST_R64_WITH_RM64 (0x85) /* /r */ #define OPCODE_JMP_REL8 (0xeb) #define OPCODE_JMP_REL32 (0xe9) +#define OPCODE_JMP_RM64 (0xff) /* /4 */ #define OPCODE_JCC_REL8 (0x70) /* | jcc type */ #define OPCODE_JCC_REL32_A (0x0f) #define OPCODE_JCC_REL32_B (0x80) /* | jcc type */ @@ -181,21 +183,22 @@ STATIC void asm_x64_write_word32_to(asm_x64_t *as, int offset, int w32) { */ STATIC void asm_x64_write_r64_disp(asm_x64_t *as, int r64, int disp_r64, int disp_offset) { - assert(disp_r64 != ASM_X64_REG_RSP); - - if (disp_r64 == ASM_X64_REG_R12) { - // special case for r12; not fully implemented - assert(SIGNED_FIT8(disp_offset)); - asm_x64_write_byte_3(as, MODRM_R64(r64) | MODRM_RM_DISP8 | MODRM_RM_R64(disp_r64), 0x24, IMM32_L0(disp_offset)); - return; - } - - if (disp_offset == 0 && disp_r64 != ASM_X64_REG_RBP) { - asm_x64_write_byte_1(as, MODRM_R64(r64) | MODRM_RM_DISP0 | MODRM_RM_R64(disp_r64)); + uint8_t rm_disp; + if (disp_offset == 0 && (disp_r64 & 7) != ASM_X64_REG_RBP) { + rm_disp = MODRM_RM_DISP0; } else if (SIGNED_FIT8(disp_offset)) { - asm_x64_write_byte_2(as, MODRM_R64(r64) | MODRM_RM_DISP8 | MODRM_RM_R64(disp_r64), IMM32_L0(disp_offset)); + rm_disp = MODRM_RM_DISP8; } else { - asm_x64_write_byte_1(as, MODRM_R64(r64) | MODRM_RM_DISP32 | MODRM_RM_R64(disp_r64)); + rm_disp = MODRM_RM_DISP32; + } + asm_x64_write_byte_1(as, MODRM_R64(r64) | rm_disp | MODRM_RM_R64(disp_r64)); + if ((disp_r64 & 7) == ASM_X64_REG_RSP) { + // Special case for rsp and r12, they need a SIB byte + asm_x64_write_byte_1(as, 0x24); + } + if (rm_disp == MODRM_RM_DISP8) { + asm_x64_write_byte_1(as, IMM32_L0(disp_offset)); + } else if (rm_disp == MODRM_RM_DISP32) { asm_x64_write_word32(as, disp_offset); } } @@ -361,15 +364,6 @@ void asm_x64_mov_i64_to_r64_optimised(asm_x64_t *as, int64_t src_i64, int dest_r } } -// src_i64 is stored as a full word in the code, and aligned to machine-word boundary -void asm_x64_mov_i64_to_r64_aligned(asm_x64_t *as, int64_t src_i64, int dest_r64) { - // mov instruction uses 2 bytes for the instruction, before the i64 - while (((as->base.code_offset + 2) & (WORD_SIZE - 1)) != 0) { - asm_x64_nop(as); - } - asm_x64_mov_i64_to_r64(as, src_i64, dest_r64); -} - void asm_x64_and_r64_r64(asm_x64_t *as, int dest_r64, int src_r64) { asm_x64_generic_r64_r64(as, dest_r64, src_r64, OPCODE_AND_R64_TO_RM64); } @@ -465,17 +459,25 @@ void asm_x64_cmp_i32_with_r32(asm_x64_t *as, int src_i32, int src_r32) { */ void asm_x64_test_r8_with_r8(asm_x64_t *as, int src_r64_a, int src_r64_b) { - // TODO implement for other registers - assert(src_r64_a == ASM_X64_REG_RAX); - assert(src_r64_b == ASM_X64_REG_RAX); + assert(src_r64_a < 8); + assert(src_r64_b < 8); asm_x64_write_byte_2(as, OPCODE_TEST_R8_WITH_RM8, MODRM_R64(src_r64_a) | MODRM_RM_REG | MODRM_RM_R64(src_r64_b)); } +void asm_x64_test_r64_with_r64(asm_x64_t *as, int src_r64_a, int src_r64_b) { + asm_x64_generic_r64_r64(as, src_r64_b, src_r64_a, OPCODE_TEST_R64_WITH_RM64); +} + void asm_x64_setcc_r8(asm_x64_t *as, int jcc_type, int dest_r8) { assert(dest_r8 < 8); asm_x64_write_byte_3(as, OPCODE_SETCC_RM8_A, OPCODE_SETCC_RM8_B | jcc_type, MODRM_R64(0) | MODRM_RM_REG | MODRM_RM_R64(dest_r8)); } +void asm_x64_jmp_reg(asm_x64_t *as, int src_r64) { + assert(src_r64 < 8); + asm_x64_write_byte_2(as, OPCODE_JMP_RM64, MODRM_R64(4) | MODRM_RM_REG | MODRM_RM_R64(src_r64)); +} + STATIC mp_uint_t get_label_dest(asm_x64_t *as, mp_uint_t label) { assert(label < as->base.max_num_labels); return as->base.label_offsets[label]; @@ -528,63 +530,72 @@ void asm_x64_jcc_label(asm_x64_t *as, int jcc_type, mp_uint_t label) { void asm_x64_entry(asm_x64_t *as, int num_locals) { assert(num_locals >= 0); asm_x64_push_r64(as, ASM_X64_REG_RBP); - asm_x64_mov_r64_r64(as, ASM_X64_REG_RBP, ASM_X64_REG_RSP); - num_locals |= 1; // make it odd so stack is aligned on 16 byte boundary - asm_x64_sub_r64_i32(as, ASM_X64_REG_RSP, num_locals * WORD_SIZE); asm_x64_push_r64(as, ASM_X64_REG_RBX); asm_x64_push_r64(as, ASM_X64_REG_R12); asm_x64_push_r64(as, ASM_X64_REG_R13); + num_locals |= 1; // make it odd so stack is aligned on 16 byte boundary + asm_x64_sub_r64_i32(as, ASM_X64_REG_RSP, num_locals * WORD_SIZE); as->num_locals = num_locals; } void asm_x64_exit(asm_x64_t *as) { + asm_x64_sub_r64_i32(as, ASM_X64_REG_RSP, -as->num_locals * WORD_SIZE); asm_x64_pop_r64(as, ASM_X64_REG_R13); asm_x64_pop_r64(as, ASM_X64_REG_R12); asm_x64_pop_r64(as, ASM_X64_REG_RBX); - asm_x64_write_byte_1(as, OPCODE_LEAVE); + asm_x64_pop_r64(as, ASM_X64_REG_RBP); asm_x64_ret(as); } // locals: // - stored on the stack in ascending order // - numbered 0 through as->num_locals-1 -// - RBP points above the last local +// - RSP points to the first local // -// | RBP -// v +// | RSP +// v // l0 l1 l2 ... l(n-1) // ^ ^ // | low address | high address in RAM // -STATIC int asm_x64_local_offset_from_ebp(asm_x64_t *as, int local_num) { - return (-as->num_locals + local_num) * WORD_SIZE; +STATIC int asm_x64_local_offset_from_rsp(asm_x64_t *as, int local_num) { + (void)as; + // Stack is full descending, RSP points to local0 + return local_num * WORD_SIZE; } void asm_x64_mov_local_to_r64(asm_x64_t *as, int src_local_num, int dest_r64) { - asm_x64_mov_mem64_to_r64(as, ASM_X64_REG_RBP, asm_x64_local_offset_from_ebp(as, src_local_num), dest_r64); + asm_x64_mov_mem64_to_r64(as, ASM_X64_REG_RSP, asm_x64_local_offset_from_rsp(as, src_local_num), dest_r64); } void asm_x64_mov_r64_to_local(asm_x64_t *as, int src_r64, int dest_local_num) { - asm_x64_mov_r64_to_mem64(as, src_r64, ASM_X64_REG_RBP, asm_x64_local_offset_from_ebp(as, dest_local_num)); + asm_x64_mov_r64_to_mem64(as, src_r64, ASM_X64_REG_RSP, asm_x64_local_offset_from_rsp(as, dest_local_num)); } void asm_x64_mov_local_addr_to_r64(asm_x64_t *as, int local_num, int dest_r64) { - int offset = asm_x64_local_offset_from_ebp(as, local_num); + int offset = asm_x64_local_offset_from_rsp(as, local_num); if (offset == 0) { - asm_x64_mov_r64_r64(as, dest_r64, ASM_X64_REG_RBP); + asm_x64_mov_r64_r64(as, dest_r64, ASM_X64_REG_RSP); } else { - asm_x64_lea_disp_to_r64(as, ASM_X64_REG_RBP, offset, dest_r64); + asm_x64_lea_disp_to_r64(as, ASM_X64_REG_RSP, offset, dest_r64); } } +void asm_x64_mov_reg_pcrel(asm_x64_t *as, int dest_r64, mp_uint_t label) { + mp_uint_t dest = get_label_dest(as, label); + mp_int_t rel = dest - (as->base.code_offset + 7); + asm_x64_write_byte_3(as, REX_PREFIX | REX_W | REX_R_FROM_R64(dest_r64), OPCODE_LEA_MEM_TO_R64, MODRM_R64(dest_r64) | MODRM_RM_R64(5)); + asm_x64_write_word32(as, rel); +} + /* void asm_x64_push_local(asm_x64_t *as, int local_num) { - asm_x64_push_disp(as, ASM_X64_REG_RBP, asm_x64_local_offset_from_ebp(as, local_num)); + asm_x64_push_disp(as, ASM_X64_REG_RSP, asm_x64_local_offset_from_rsp(as, local_num)); } void asm_x64_push_local_addr(asm_x64_t *as, int local_num, int temp_r64) { - asm_x64_mov_r64_r64(as, temp_r64, ASM_X64_REG_RBP); - asm_x64_add_i32_to_r32(as, asm_x64_local_offset_from_ebp(as, local_num), temp_r64); + asm_x64_mov_r64_r64(as, temp_r64, ASM_X64_REG_RSP); + asm_x64_add_i32_to_r32(as, asm_x64_local_offset_from_rsp(as, local_num), temp_r64); asm_x64_push_r64(as, temp_r64); } */ @@ -610,21 +621,10 @@ void asm_x64_call_i1(asm_x64_t *as, void* func, int i1) { } */ -void asm_x64_call_ind(asm_x64_t *as, void *ptr, int temp_r64) { +void asm_x64_call_ind(asm_x64_t *as, size_t fun_id, int temp_r64) { assert(temp_r64 < 8); - #ifdef __LP64__ - asm_x64_mov_i64_to_r64_optimised(as, (int64_t)ptr, temp_r64); - #else - // If we get here, sizeof(int) == sizeof(void*). - asm_x64_mov_i64_to_r64_optimised(as, (int64_t)(unsigned int)ptr, temp_r64); - #endif + asm_x64_mov_mem64_to_r64(as, ASM_X64_REG_FUN_TABLE, fun_id * WORD_SIZE, temp_r64); asm_x64_write_byte_2(as, OPCODE_CALL_RM32, MODRM_R64(2) | MODRM_RM_REG | MODRM_RM_R64(temp_r64)); - // this reduces code size by 2 bytes per call, but doesn't seem to speed it up at all - // doesn't work anymore because calls are 64 bits away - /* - asm_x64_write_byte_1(as, OPCODE_CALL_REL32); - asm_x64_write_word32(as, ptr - (void*)(as->code_base + as->code_offset + 4)); - */ } #endif // MICROPY_EMIT_X64 diff --git a/py/asmx64.h b/py/asmx64.h index 804e3b7098..ceea426d74 100644 --- a/py/asmx64.h +++ b/py/asmx64.h @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George + * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -85,7 +85,6 @@ void asm_x64_pop_r64(asm_x64_t *as, int dest_r64); void asm_x64_mov_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); void asm_x64_mov_i64_to_r64(asm_x64_t *as, int64_t src_i64, int dest_r64); void asm_x64_mov_i64_to_r64_optimised(asm_x64_t *as, int64_t src_i64, int dest_r64); -void asm_x64_mov_i64_to_r64_aligned(asm_x64_t *as, int64_t src_i64, int dest_r64); void asm_x64_mov_r8_to_mem8(asm_x64_t *as, int src_r64, int dest_r64, int dest_disp); void asm_x64_mov_r16_to_mem16(asm_x64_t *as, int src_r64, int dest_r64, int dest_disp); void asm_x64_mov_r32_to_mem32(asm_x64_t *as, int src_r64, int dest_r64, int dest_disp); @@ -104,7 +103,9 @@ void asm_x64_sub_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); void asm_x64_mul_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); void asm_x64_cmp_r64_with_r64(asm_x64_t *as, int src_r64_a, int src_r64_b); void asm_x64_test_r8_with_r8(asm_x64_t *as, int src_r64_a, int src_r64_b); +void asm_x64_test_r64_with_r64(asm_x64_t *as, int src_r64_a, int src_r64_b); void asm_x64_setcc_r8(asm_x64_t *as, int jcc_type, int dest_r8); +void asm_x64_jmp_reg(asm_x64_t *as, int src_r64); void asm_x64_jmp_label(asm_x64_t *as, mp_uint_t label); void asm_x64_jcc_label(asm_x64_t *as, int jcc_type, mp_uint_t label); void asm_x64_entry(asm_x64_t *as, int num_locals); @@ -112,7 +113,11 @@ void asm_x64_exit(asm_x64_t *as); void asm_x64_mov_local_to_r64(asm_x64_t *as, int src_local_num, int dest_r64); void asm_x64_mov_r64_to_local(asm_x64_t *as, int src_r64, int dest_local_num); void asm_x64_mov_local_addr_to_r64(asm_x64_t *as, int local_num, int dest_r64); -void asm_x64_call_ind(asm_x64_t *as, void *ptr, int temp_r32); +void asm_x64_mov_reg_pcrel(asm_x64_t *as, int dest_r64, mp_uint_t label); +void asm_x64_call_ind(asm_x64_t *as, size_t fun_id, int temp_r32); + +// Holds a pointer to mp_fun_table +#define ASM_X64_REG_FUN_TABLE ASM_X64_REG_RBP #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -139,20 +144,31 @@ void asm_x64_call_ind(asm_x64_t *as, void *ptr, int temp_r32); #define REG_LOCAL_3 ASM_X64_REG_R13 #define REG_LOCAL_NUM (3) +// Holds a pointer to mp_fun_table +#define REG_FUN_TABLE ASM_X64_REG_FUN_TABLE + #define ASM_T asm_x64_t #define ASM_END_PASS asm_x64_end_pass #define ASM_ENTRY asm_x64_entry #define ASM_EXIT asm_x64_exit #define ASM_JUMP asm_x64_jmp_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ - asm_x64_test_r8_with_r8(as, reg, reg); \ + if (bool_test) { \ + asm_x64_test_r8_with_r8((as), (reg), (reg)); \ + } else { \ + asm_x64_test_r64_with_r64((as), (reg), (reg)); \ + } \ asm_x64_jcc_label(as, ASM_X64_CC_JZ, label); \ } while (0) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ do { \ - asm_x64_test_r8_with_r8(as, reg, reg); \ + if (bool_test) { \ + asm_x64_test_r8_with_r8((as), (reg), (reg)); \ + } else { \ + asm_x64_test_r64_with_r64((as), (reg), (reg)); \ + } \ asm_x64_jcc_label(as, ASM_X64_CC_JNZ, label); \ } while (0) #define ASM_JUMP_IF_REG_EQ(as, reg1, reg2, label) \ @@ -160,14 +176,15 @@ void asm_x64_call_ind(asm_x64_t *as, void *ptr, int temp_r32); asm_x64_cmp_r64_with_r64(as, reg1, reg2); \ asm_x64_jcc_label(as, ASM_X64_CC_JE, label); \ } while (0) -#define ASM_CALL_IND(as, ptr, idx) asm_x64_call_ind(as, ptr, ASM_X64_REG_RAX) +#define ASM_JUMP_REG(as, reg) asm_x64_jmp_reg((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_x64_call_ind(as, idx, ASM_X64_REG_RAX) #define ASM_MOV_LOCAL_REG(as, local_num, reg_src) asm_x64_mov_r64_to_local((as), (reg_src), (local_num)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_x64_mov_i64_to_r64_optimised((as), (imm), (reg_dest)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_x64_mov_i64_to_r64_aligned((as), (imm), (reg_dest)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_x64_mov_local_to_r64((as), (local_num), (reg_dest)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_x64_mov_r64_r64((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_x64_mov_local_addr_to_r64((as), (local_num), (reg_dest)) +#define ASM_MOV_REG_PCREL(as, reg_dest, label) asm_x64_mov_reg_pcrel((as), (reg_dest), (label)) #define ASM_LSL_REG(as, reg) asm_x64_shl_r64_cl((as), (reg)) #define ASM_ASR_REG(as, reg) asm_x64_sar_r64_cl((as), (reg)) diff --git a/py/asmx86.c b/py/asmx86.c index 05783354ed..b238321bda 100644 --- a/py/asmx86.c +++ b/py/asmx86.c @@ -73,8 +73,10 @@ #define OPCODE_CMP_R32_WITH_RM32 (0x39) // #define OPCODE_CMP_RM32_WITH_R32 (0x3b) #define OPCODE_TEST_R8_WITH_RM8 (0x84) /* /r */ +#define OPCODE_TEST_R32_WITH_RM32 (0x85) /* /r */ #define OPCODE_JMP_REL8 (0xeb) #define OPCODE_JMP_REL32 (0xe9) +#define OPCODE_JMP_RM32 (0xff) /* /4 */ #define OPCODE_JCC_REL8 (0x70) /* | jcc type */ #define OPCODE_JCC_REL32_A (0x0f) #define OPCODE_JCC_REL32_B (0x80) /* | jcc type */ @@ -135,14 +137,22 @@ STATIC void asm_x86_write_word32(asm_x86_t *as, int w32) { } STATIC void asm_x86_write_r32_disp(asm_x86_t *as, int r32, int disp_r32, int disp_offset) { - assert(disp_r32 != ASM_X86_REG_ESP); - + uint8_t rm_disp; if (disp_offset == 0 && disp_r32 != ASM_X86_REG_EBP) { - asm_x86_write_byte_1(as, MODRM_R32(r32) | MODRM_RM_DISP0 | MODRM_RM_R32(disp_r32)); + rm_disp = MODRM_RM_DISP0; } else if (SIGNED_FIT8(disp_offset)) { - asm_x86_write_byte_2(as, MODRM_R32(r32) | MODRM_RM_DISP8 | MODRM_RM_R32(disp_r32), IMM32_L0(disp_offset)); + rm_disp = MODRM_RM_DISP8; } else { - asm_x86_write_byte_1(as, MODRM_R32(r32) | MODRM_RM_DISP32 | MODRM_RM_R32(disp_r32)); + rm_disp = MODRM_RM_DISP32; + } + asm_x86_write_byte_1(as, MODRM_R32(r32) | rm_disp | MODRM_RM_R32(disp_r32)); + if (disp_r32 == ASM_X86_REG_ESP) { + // Special case for esp, it needs a SIB byte + asm_x86_write_byte_1(as, 0x24); + } + if (rm_disp == MODRM_RM_DISP8) { + asm_x86_write_byte_1(as, IMM32_L0(disp_offset)); + } else if (rm_disp == MODRM_RM_DISP32) { asm_x86_write_word32(as, disp_offset); } } @@ -151,9 +161,11 @@ STATIC void asm_x86_generic_r32_r32(asm_x86_t *as, int dest_r32, int src_r32, in asm_x86_write_byte_2(as, op, MODRM_R32(src_r32) | MODRM_RM_REG | MODRM_RM_R32(dest_r32)); } +#if 0 STATIC void asm_x86_nop(asm_x86_t *as) { asm_x86_write_byte_1(as, OPCODE_NOP); } +#endif STATIC void asm_x86_push_r32(asm_x86_t *as, int src_r32) { asm_x86_write_byte_1(as, OPCODE_PUSH_R32 | src_r32); @@ -229,15 +241,6 @@ void asm_x86_mov_i32_to_r32(asm_x86_t *as, int32_t src_i32, int dest_r32) { asm_x86_write_word32(as, src_i32); } -// src_i32 is stored as a full word in the code, and aligned to machine-word boundary -void asm_x86_mov_i32_to_r32_aligned(asm_x86_t *as, int32_t src_i32, int dest_r32) { - // mov instruction uses 1 byte for the instruction, before the i32 - while (((as->base.code_offset + 1) & (WORD_SIZE - 1)) != 0) { - asm_x86_nop(as); - } - asm_x86_mov_i32_to_r32(as, src_i32, dest_r32); -} - void asm_x86_and_r32_r32(asm_x86_t *as, int dest_r32, int src_r32) { asm_x86_generic_r32_r32(as, dest_r32, src_r32, OPCODE_AND_R32_TO_RM32); } @@ -312,7 +315,7 @@ void asm_x86_sar_r32_by_imm(asm_x86_t *as, int r32, int imm) { #endif void asm_x86_cmp_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b) { - asm_x86_write_byte_2(as, OPCODE_CMP_R32_WITH_RM32, MODRM_R32(src_r32_a) | MODRM_RM_REG | MODRM_RM_R32(src_r32_b)); + asm_x86_generic_r32_r32(as, src_r32_b, src_r32_a, OPCODE_CMP_R32_WITH_RM32); } #if 0 @@ -328,16 +331,21 @@ void asm_x86_cmp_i32_with_r32(asm_x86_t *as, int src_i32, int src_r32) { #endif void asm_x86_test_r8_with_r8(asm_x86_t *as, int src_r32_a, int src_r32_b) { - // TODO implement for other registers - assert(src_r32_a == ASM_X86_REG_EAX); - assert(src_r32_b == ASM_X86_REG_EAX); asm_x86_write_byte_2(as, OPCODE_TEST_R8_WITH_RM8, MODRM_R32(src_r32_a) | MODRM_RM_REG | MODRM_RM_R32(src_r32_b)); } +void asm_x86_test_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b) { + asm_x86_generic_r32_r32(as, src_r32_b, src_r32_a, OPCODE_TEST_R32_WITH_RM32); +} + void asm_x86_setcc_r8(asm_x86_t *as, mp_uint_t jcc_type, int dest_r8) { asm_x86_write_byte_3(as, OPCODE_SETCC_RM8_A, OPCODE_SETCC_RM8_B | jcc_type, MODRM_R32(0) | MODRM_RM_REG | MODRM_RM_R32(dest_r8)); } +void asm_x86_jmp_reg(asm_x86_t *as, int src_r32) { + asm_x86_write_byte_2(as, OPCODE_JMP_RM32, MODRM_R32(4) | MODRM_RM_REG | MODRM_RM_R32(src_r32)); +} + STATIC mp_uint_t get_label_dest(asm_x86_t *as, mp_uint_t label) { assert(label < as->base.max_num_labels); return as->base.label_offsets[label]; @@ -390,86 +398,102 @@ void asm_x86_jcc_label(asm_x86_t *as, mp_uint_t jcc_type, mp_uint_t label) { void asm_x86_entry(asm_x86_t *as, int num_locals) { assert(num_locals >= 0); asm_x86_push_r32(as, ASM_X86_REG_EBP); - asm_x86_mov_r32_r32(as, ASM_X86_REG_EBP, ASM_X86_REG_ESP); - if (num_locals > 0) { - asm_x86_sub_r32_i32(as, ASM_X86_REG_ESP, num_locals * WORD_SIZE); - } asm_x86_push_r32(as, ASM_X86_REG_EBX); asm_x86_push_r32(as, ASM_X86_REG_ESI); asm_x86_push_r32(as, ASM_X86_REG_EDI); - // TODO align stack on 16-byte boundary + num_locals |= 1; // make it odd so stack is aligned on 16 byte boundary + asm_x86_sub_r32_i32(as, ASM_X86_REG_ESP, num_locals * WORD_SIZE); as->num_locals = num_locals; } void asm_x86_exit(asm_x86_t *as) { + asm_x86_sub_r32_i32(as, ASM_X86_REG_ESP, -as->num_locals * WORD_SIZE); asm_x86_pop_r32(as, ASM_X86_REG_EDI); asm_x86_pop_r32(as, ASM_X86_REG_ESI); asm_x86_pop_r32(as, ASM_X86_REG_EBX); - asm_x86_write_byte_1(as, OPCODE_LEAVE); + asm_x86_pop_r32(as, ASM_X86_REG_EBP); asm_x86_ret(as); } +STATIC int asm_x86_arg_offset_from_esp(asm_x86_t *as, size_t arg_num) { + // Above esp are: locals, 4 saved registers, return eip, arguments + return (as->num_locals + 4 + 1 + arg_num) * WORD_SIZE; +} + #if 0 void asm_x86_push_arg(asm_x86_t *as, int src_arg_num) { - asm_x86_push_disp(as, ASM_X86_REG_EBP, 2 * WORD_SIZE + src_arg_num * WORD_SIZE); + asm_x86_push_disp(as, ASM_X86_REG_ESP, asm_x86_arg_offset_from_esp(as, src_arg_num)); } #endif void asm_x86_mov_arg_to_r32(asm_x86_t *as, int src_arg_num, int dest_r32) { - asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_EBP, 2 * WORD_SIZE + src_arg_num * WORD_SIZE, dest_r32); + asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_ESP, asm_x86_arg_offset_from_esp(as, src_arg_num), dest_r32); } #if 0 void asm_x86_mov_r32_to_arg(asm_x86_t *as, int src_r32, int dest_arg_num) { - asm_x86_mov_r32_to_mem32(as, src_r32, ASM_X86_REG_EBP, 2 * WORD_SIZE + dest_arg_num * WORD_SIZE); + asm_x86_mov_r32_to_mem32(as, src_r32, ASM_X86_REG_ESP, asm_x86_arg_offset_from_esp(as, dest_arg_num)); } #endif // locals: // - stored on the stack in ascending order // - numbered 0 through as->num_locals-1 -// - EBP points above the last local +// - ESP points to the first local // -// | EBP -// v +// | ESP +// v // l0 l1 l2 ... l(n-1) // ^ ^ // | low address | high address in RAM // -STATIC int asm_x86_local_offset_from_ebp(asm_x86_t *as, int local_num) { - return (-as->num_locals + local_num) * WORD_SIZE; +STATIC int asm_x86_local_offset_from_esp(asm_x86_t *as, int local_num) { + (void)as; + // Stack is full descending, ESP points to local0 + return local_num * WORD_SIZE; } void asm_x86_mov_local_to_r32(asm_x86_t *as, int src_local_num, int dest_r32) { - asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_EBP, asm_x86_local_offset_from_ebp(as, src_local_num), dest_r32); + asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_ESP, asm_x86_local_offset_from_esp(as, src_local_num), dest_r32); } void asm_x86_mov_r32_to_local(asm_x86_t *as, int src_r32, int dest_local_num) { - asm_x86_mov_r32_to_mem32(as, src_r32, ASM_X86_REG_EBP, asm_x86_local_offset_from_ebp(as, dest_local_num)); + asm_x86_mov_r32_to_mem32(as, src_r32, ASM_X86_REG_ESP, asm_x86_local_offset_from_esp(as, dest_local_num)); } void asm_x86_mov_local_addr_to_r32(asm_x86_t *as, int local_num, int dest_r32) { - int offset = asm_x86_local_offset_from_ebp(as, local_num); + int offset = asm_x86_local_offset_from_esp(as, local_num); if (offset == 0) { - asm_x86_mov_r32_r32(as, dest_r32, ASM_X86_REG_EBP); + asm_x86_mov_r32_r32(as, dest_r32, ASM_X86_REG_ESP); } else { - asm_x86_lea_disp_to_r32(as, ASM_X86_REG_EBP, offset, dest_r32); + asm_x86_lea_disp_to_r32(as, ASM_X86_REG_ESP, offset, dest_r32); } } +void asm_x86_mov_reg_pcrel(asm_x86_t *as, int dest_r32, mp_uint_t label) { + asm_x86_write_byte_1(as, OPCODE_CALL_REL32); + asm_x86_write_word32(as, 0); + mp_uint_t dest = get_label_dest(as, label); + mp_int_t rel = dest - as->base.code_offset; + asm_x86_pop_r32(as, dest_r32); + // PC rel is usually a forward reference, so need to assume it's large + asm_x86_write_byte_2(as, OPCODE_ADD_I32_TO_RM32, MODRM_R32(0) | MODRM_RM_REG | MODRM_RM_R32(dest_r32)); + asm_x86_write_word32(as, rel); +} + #if 0 void asm_x86_push_local(asm_x86_t *as, int local_num) { - asm_x86_push_disp(as, ASM_X86_REG_EBP, asm_x86_local_offset_from_ebp(as, local_num)); + asm_x86_push_disp(as, ASM_X86_REG_ESP, asm_x86_local_offset_from_esp(as, local_num)); } void asm_x86_push_local_addr(asm_x86_t *as, int local_num, int temp_r32) { - asm_x86_mov_r32_r32(as, temp_r32, ASM_X86_REG_EBP); - asm_x86_add_i32_to_r32(as, asm_x86_local_offset_from_ebp(as, local_num), temp_r32); + asm_x86_mov_r32_r32(as, temp_r32, ASM_X86_REG_ESP); + asm_x86_add_i32_to_r32(as, asm_x86_local_offset_from_esp(as, local_num), temp_r32); asm_x86_push_r32(as, temp_r32); } #endif -void asm_x86_call_ind(asm_x86_t *as, void *ptr, mp_uint_t n_args, int temp_r32) { +void asm_x86_call_ind(asm_x86_t *as, size_t fun_id, mp_uint_t n_args, int temp_r32) { // TODO align stack on 16-byte boundary before the call assert(n_args <= 5); if (n_args > 4) { @@ -487,20 +511,10 @@ void asm_x86_call_ind(asm_x86_t *as, void *ptr, mp_uint_t n_args, int temp_r32) if (n_args > 0) { asm_x86_push_r32(as, ASM_X86_REG_ARG_1); } - #ifdef __LP64__ - // We wouldn't run x86 code on an x64 machine. This is here to enable - // testing of the x86 emitter only. - asm_x86_mov_i32_to_r32(as, (int32_t)(int64_t)ptr, temp_r32); - #else - // If we get here, sizeof(int) == sizeof(void*). - asm_x86_mov_i32_to_r32(as, (int32_t)ptr, temp_r32); - #endif + + // Load the pointer to the function and make the call + asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_FUN_TABLE, fun_id * WORD_SIZE, temp_r32); asm_x86_write_byte_2(as, OPCODE_CALL_RM32, MODRM_R32(2) | MODRM_RM_REG | MODRM_RM_R32(temp_r32)); - // this reduces code size by 2 bytes per call, but doesn't seem to speed it up at all - /* - asm_x86_write_byte_1(as, OPCODE_CALL_REL32); - asm_x86_write_word32(as, ptr - (void*)(as->code_base + as->base.code_offset + 4)); - */ // the caller must clean up the stack if (n_args > 0) { diff --git a/py/asmx86.h b/py/asmx86.h index 1fa7ff7383..930350d11b 100644 --- a/py/asmx86.h +++ b/py/asmx86.h @@ -84,7 +84,6 @@ static inline void asm_x86_end_pass(asm_x86_t *as) { void asm_x86_mov_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); void asm_x86_mov_i32_to_r32(asm_x86_t *as, int32_t src_i32, int dest_r32); -void asm_x86_mov_i32_to_r32_aligned(asm_x86_t *as, int32_t src_i32, int dest_r32); void asm_x86_mov_r8_to_mem8(asm_x86_t *as, int src_r32, int dest_r32, int dest_disp); void asm_x86_mov_r16_to_mem16(asm_x86_t *as, int src_r32, int dest_r32, int dest_disp); void asm_x86_mov_r32_to_mem32(asm_x86_t *as, int src_r32, int dest_r32, int dest_disp); @@ -101,7 +100,9 @@ void asm_x86_sub_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); void asm_x86_mul_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); void asm_x86_cmp_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b); void asm_x86_test_r8_with_r8(asm_x86_t *as, int src_r32_a, int src_r32_b); +void asm_x86_test_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b); void asm_x86_setcc_r8(asm_x86_t *as, mp_uint_t jcc_type, int dest_r8); +void asm_x86_jmp_reg(asm_x86_t *as, int src_r86); void asm_x86_jmp_label(asm_x86_t *as, mp_uint_t label); void asm_x86_jcc_label(asm_x86_t *as, mp_uint_t jcc_type, mp_uint_t label); void asm_x86_entry(asm_x86_t *as, int num_locals); @@ -110,7 +111,11 @@ void asm_x86_mov_arg_to_r32(asm_x86_t *as, int src_arg_num, int dest_r32); void asm_x86_mov_local_to_r32(asm_x86_t *as, int src_local_num, int dest_r32); void asm_x86_mov_r32_to_local(asm_x86_t *as, int src_r32, int dest_local_num); void asm_x86_mov_local_addr_to_r32(asm_x86_t *as, int local_num, int dest_r32); -void asm_x86_call_ind(asm_x86_t *as, void *ptr, mp_uint_t n_args, int temp_r32); +void asm_x86_mov_reg_pcrel(asm_x86_t *as, int dest_r64, mp_uint_t label); +void asm_x86_call_ind(asm_x86_t *as, size_t fun_id, mp_uint_t n_args, int temp_r32); + +// Holds a pointer to mp_fun_table +#define ASM_X86_REG_FUN_TABLE ASM_X86_REG_EBP #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -137,20 +142,31 @@ void asm_x86_call_ind(asm_x86_t *as, void *ptr, mp_uint_t n_args, int temp_r32); #define REG_LOCAL_3 ASM_X86_REG_EDI #define REG_LOCAL_NUM (3) +// Holds a pointer to mp_fun_table +#define REG_FUN_TABLE ASM_X86_REG_FUN_TABLE + #define ASM_T asm_x86_t #define ASM_END_PASS asm_x86_end_pass #define ASM_ENTRY asm_x86_entry #define ASM_EXIT asm_x86_exit #define ASM_JUMP asm_x86_jmp_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ - asm_x86_test_r8_with_r8(as, reg, reg); \ + if (bool_test) { \ + asm_x86_test_r8_with_r8(as, reg, reg); \ + } else { \ + asm_x86_test_r32_with_r32(as, reg, reg); \ + } \ asm_x86_jcc_label(as, ASM_X86_CC_JZ, label); \ } while (0) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ do { \ - asm_x86_test_r8_with_r8(as, reg, reg); \ + if (bool_test) { \ + asm_x86_test_r8_with_r8(as, reg, reg); \ + } else { \ + asm_x86_test_r32_with_r32(as, reg, reg); \ + } \ asm_x86_jcc_label(as, ASM_X86_CC_JNZ, label); \ } while (0) #define ASM_JUMP_IF_REG_EQ(as, reg1, reg2, label) \ @@ -158,14 +174,15 @@ void asm_x86_call_ind(asm_x86_t *as, void *ptr, mp_uint_t n_args, int temp_r32); asm_x86_cmp_r32_with_r32(as, reg1, reg2); \ asm_x86_jcc_label(as, ASM_X86_CC_JE, label); \ } while (0) -#define ASM_CALL_IND(as, ptr, idx) asm_x86_call_ind(as, ptr, mp_f_n_args[idx], ASM_X86_REG_EAX) +#define ASM_JUMP_REG(as, reg) asm_x86_jmp_reg((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_x86_call_ind(as, idx, mp_f_n_args[idx], ASM_X86_REG_EAX) #define ASM_MOV_LOCAL_REG(as, local_num, reg_src) asm_x86_mov_r32_to_local((as), (reg_src), (local_num)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_x86_mov_i32_to_r32((as), (imm), (reg_dest)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_x86_mov_i32_to_r32_aligned((as), (imm), (reg_dest)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_x86_mov_local_to_r32((as), (local_num), (reg_dest)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_x86_mov_r32_r32((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_x86_mov_local_addr_to_r32((as), (local_num), (reg_dest)) +#define ASM_MOV_REG_PCREL(as, reg_dest, label) asm_x86_mov_reg_pcrel((as), (reg_dest), (label)) #define ASM_LSL_REG(as, reg) asm_x86_shl_r32_cl((as), (reg)) #define ASM_ASR_REG(as, reg) asm_x86_sar_r32_cl((as), (reg)) diff --git a/py/asmxtensa.c b/py/asmxtensa.c index 5678eafd1d..a8e3a2655c 100644 --- a/py/asmxtensa.c +++ b/py/asmxtensa.c @@ -37,6 +37,7 @@ #define WORD_SIZE (4) #define SIGNED_FIT8(x) ((((x) & 0xffffff80) == 0) || (((x) & 0xffffff80) == 0xffffff80)) #define SIGNED_FIT12(x) ((((x) & 0xfffff800) == 0) || (((x) & 0xfffff800) == 0xfffff800)) +#define NUM_REGS_SAVED (5) void asm_xtensa_end_pass(asm_xtensa_t *as) { as->num_const = as->cur_const; @@ -67,26 +68,37 @@ void asm_xtensa_entry(asm_xtensa_t *as, int num_locals) { mp_asm_base_get_cur_to_write_bytes(&as->base, 1); // padding/alignment byte as->const_table = (uint32_t *)mp_asm_base_get_cur_to_write_bytes(&as->base, as->num_const * 4); - // adjust the stack-pointer to store a0, a12, a13, a14 and locals, 16-byte aligned - as->stack_adjust = (((4 + num_locals) * WORD_SIZE) + 15) & ~15; - asm_xtensa_op_addi(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, -as->stack_adjust); + // adjust the stack-pointer to store a0, a12, a13, a14, a15 and locals, 16-byte aligned + as->stack_adjust = (((NUM_REGS_SAVED + num_locals) * WORD_SIZE) + 15) & ~15; + if (SIGNED_FIT8(-as->stack_adjust)) { + asm_xtensa_op_addi(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, -as->stack_adjust); + } else { + asm_xtensa_op_movi(as, ASM_XTENSA_REG_A9, as->stack_adjust); + asm_xtensa_op_sub(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A9); + } - // save return value (a0) and callee-save registers (a12, a13, a14) + // save return value (a0) and callee-save registers (a12, a13, a14, a15) asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A0, ASM_XTENSA_REG_A1, 0); - asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A12, ASM_XTENSA_REG_A1, 1); - asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A13, ASM_XTENSA_REG_A1, 2); - asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A14, ASM_XTENSA_REG_A1, 3); + for (int i = 1; i < NUM_REGS_SAVED; ++i) { + asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A11 + i, ASM_XTENSA_REG_A1, i); + } } void asm_xtensa_exit(asm_xtensa_t *as) { // restore registers - asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A14, ASM_XTENSA_REG_A1, 3); - asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A13, ASM_XTENSA_REG_A1, 2); - asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A12, ASM_XTENSA_REG_A1, 1); + for (int i = NUM_REGS_SAVED - 1; i >= 1; --i) { + asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A11 + i, ASM_XTENSA_REG_A1, i); + } asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A0, ASM_XTENSA_REG_A1, 0); // restore stack-pointer and return - asm_xtensa_op_addi(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, as->stack_adjust); + if (SIGNED_FIT8(as->stack_adjust)) { + asm_xtensa_op_addi(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, as->stack_adjust); + } else { + asm_xtensa_op_movi(as, ASM_XTENSA_REG_A9, as->stack_adjust); + asm_xtensa_op_add_n(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A9); + } + asm_xtensa_op_ret_n(as); } @@ -149,7 +161,8 @@ void asm_xtensa_mov_reg_i32(asm_xtensa_t *as, uint reg_dest, uint32_t i32) { asm_xtensa_op_movi(as, reg_dest, i32); } else { // load the constant - asm_xtensa_op_l32r(as, reg_dest, as->base.code_offset, 4 + as->cur_const * WORD_SIZE); + uint32_t const_table_offset = (uint8_t *)as->const_table - as->base.code_base; + asm_xtensa_op_l32r(as, reg_dest, as->base.code_offset, const_table_offset + as->cur_const * WORD_SIZE); // store the constant in the table if (as->const_table != NULL) { as->const_table[as->cur_const] = i32; @@ -159,16 +172,52 @@ void asm_xtensa_mov_reg_i32(asm_xtensa_t *as, uint reg_dest, uint32_t i32) { } void asm_xtensa_mov_local_reg(asm_xtensa_t *as, int local_num, uint reg_src) { - asm_xtensa_op_s32i(as, reg_src, ASM_XTENSA_REG_A1, 4 + local_num); + asm_xtensa_op_s32i(as, reg_src, ASM_XTENSA_REG_A1, NUM_REGS_SAVED + local_num); } void asm_xtensa_mov_reg_local(asm_xtensa_t *as, uint reg_dest, int local_num) { - asm_xtensa_op_l32i(as, reg_dest, ASM_XTENSA_REG_A1, 4 + local_num); + asm_xtensa_op_l32i(as, reg_dest, ASM_XTENSA_REG_A1, NUM_REGS_SAVED + local_num); } void asm_xtensa_mov_reg_local_addr(asm_xtensa_t *as, uint reg_dest, int local_num) { - asm_xtensa_op_mov_n(as, reg_dest, ASM_XTENSA_REG_A1); - asm_xtensa_op_addi(as, reg_dest, reg_dest, (4 + local_num) * WORD_SIZE); + uint off = (NUM_REGS_SAVED + local_num) * WORD_SIZE; + if (SIGNED_FIT8(off)) { + asm_xtensa_op_addi(as, reg_dest, ASM_XTENSA_REG_A1, off); + } else { + asm_xtensa_op_movi(as, reg_dest, off); + asm_xtensa_op_add_n(as, reg_dest, reg_dest, ASM_XTENSA_REG_A1); + } +} + +void asm_xtensa_mov_reg_pcrel(asm_xtensa_t *as, uint reg_dest, uint label) { + // Get relative offset from PC + uint32_t dest = get_label_dest(as, label); + int32_t rel = dest - as->base.code_offset; + rel -= 3 + 3; // account for 3 bytes of movi instruction, 3 bytes call0 adjustment + asm_xtensa_op_movi(as, reg_dest, rel); // imm has 12-bit range + + // Use call0 to get PC+3 into a0 + // call0 destination must be aligned on 4 bytes: + // - code_offset&3=0: off=0, pad=1 + // - code_offset&3=1: off=0, pad=0 + // - code_offset&3=2: off=1, pad=3 + // - code_offset&3=3: off=1, pad=2 + uint32_t off = as->base.code_offset >> 1 & 1; + uint32_t pad = (5 - as->base.code_offset) & 3; + asm_xtensa_op_call0(as, off); + mp_asm_base_get_cur_to_write_bytes(&as->base, pad); + + // Add PC to relative offset + asm_xtensa_op_add_n(as, reg_dest, reg_dest, ASM_XTENSA_REG_A0); +} + +void asm_xtensa_call_ind(asm_xtensa_t *as, uint idx) { + if (idx < 16) { + asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A0, ASM_XTENSA_REG_FUN_TABLE, idx); + } else { + asm_xtensa_op_l32i(as, ASM_XTENSA_REG_A0, ASM_XTENSA_REG_FUN_TABLE, idx); + } + asm_xtensa_op_callx0(as, ASM_XTENSA_REG_A0); } #endif // MICROPY_EMIT_XTENSA || MICROPY_EMIT_INLINE_XTENSA diff --git a/py/asmxtensa.h b/py/asmxtensa.h index d43824338d..685b3f9492 100644 --- a/py/asmxtensa.h +++ b/py/asmxtensa.h @@ -113,12 +113,12 @@ void asm_xtensa_op24(asm_xtensa_t *as, uint32_t op); // raw instructions -static inline void asm_xtensa_op_add(asm_xtensa_t *as, uint reg_dest, uint reg_src_a, uint reg_src_b) { - asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRR(0, 0, 8, reg_dest, reg_src_a, reg_src_b)); +static inline void asm_xtensa_op_add_n(asm_xtensa_t *as, uint reg_dest, uint reg_src_a, uint reg_src_b) { + asm_xtensa_op16(as, ASM_XTENSA_ENCODE_RRRN(10, reg_dest, reg_src_a, reg_src_b)); } static inline void asm_xtensa_op_addi(asm_xtensa_t *as, uint reg_dest, uint reg_src, int imm8) { - asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRI8(2, 12, reg_dest, reg_src, imm8 & 0xff)); + asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRI8(2, 12, reg_src, reg_dest, imm8 & 0xff)); } static inline void asm_xtensa_op_and(asm_xtensa_t *as, uint reg_dest, uint reg_src_a, uint reg_src_b) { @@ -133,6 +133,10 @@ static inline void asm_xtensa_op_bccz(asm_xtensa_t *as, uint cond, uint reg_src, asm_xtensa_op24(as, ASM_XTENSA_ENCODE_BRI12(6, reg_src, cond, 1, rel12 & 0xfff)); } +static inline void asm_xtensa_op_call0(asm_xtensa_t *as, int32_t rel18) { + asm_xtensa_op24(as, ASM_XTENSA_ENCODE_CALL(5, 0, rel18 & 0x3ffff)); +} + static inline void asm_xtensa_op_callx0(asm_xtensa_t *as, uint reg) { asm_xtensa_op24(as, ASM_XTENSA_ENCODE_CALLX(0, 0, 0, 0, reg, 3, 0)); } @@ -238,6 +242,11 @@ void asm_xtensa_mov_reg_i32(asm_xtensa_t *as, uint reg_dest, uint32_t i32); void asm_xtensa_mov_local_reg(asm_xtensa_t *as, int local_num, uint reg_src); void asm_xtensa_mov_reg_local(asm_xtensa_t *as, uint reg_dest, int local_num); void asm_xtensa_mov_reg_local_addr(asm_xtensa_t *as, uint reg_dest, int local_num); +void asm_xtensa_mov_reg_pcrel(asm_xtensa_t *as, uint reg_dest, uint label); +void asm_xtensa_call_ind(asm_xtensa_t *as, uint idx); + +// Holds a pointer to mp_fun_table +#define ASM_XTENSA_REG_FUN_TABLE ASM_XTENSA_REG_A15 #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -262,30 +271,29 @@ void asm_xtensa_mov_reg_local_addr(asm_xtensa_t *as, uint reg_dest, int local_nu #define REG_LOCAL_3 ASM_XTENSA_REG_A14 #define REG_LOCAL_NUM (3) +#define REG_FUN_TABLE ASM_XTENSA_REG_FUN_TABLE + #define ASM_T asm_xtensa_t #define ASM_END_PASS asm_xtensa_end_pass #define ASM_ENTRY asm_xtensa_entry #define ASM_EXIT asm_xtensa_exit #define ASM_JUMP asm_xtensa_j_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ asm_xtensa_bccz_reg_label(as, ASM_XTENSA_CCZ_EQ, reg, label) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ asm_xtensa_bccz_reg_label(as, ASM_XTENSA_CCZ_NE, reg, label) #define ASM_JUMP_IF_REG_EQ(as, reg1, reg2, label) \ asm_xtensa_bcc_reg_reg_label(as, ASM_XTENSA_CC_EQ, reg1, reg2, label) -#define ASM_CALL_IND(as, ptr, idx) \ - do { \ - asm_xtensa_mov_reg_i32(as, ASM_XTENSA_REG_A0, (uint32_t)ptr); \ - asm_xtensa_op_callx0(as, ASM_XTENSA_REG_A0); \ - } while (0) +#define ASM_JUMP_REG(as, reg) asm_xtensa_op_jx((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_xtensa_call_ind((as), (idx)) #define ASM_MOV_LOCAL_REG(as, local_num, reg_src) asm_xtensa_mov_local_reg((as), (local_num), (reg_src)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_xtensa_mov_reg_i32((as), (reg_dest), (imm)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_xtensa_mov_reg_i32((as), (reg_dest), (imm)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_xtensa_mov_reg_local((as), (reg_dest), (local_num)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_mov_n((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_xtensa_mov_reg_local_addr((as), (reg_dest), (local_num)) +#define ASM_MOV_REG_PCREL(as, reg_dest, label) asm_xtensa_mov_reg_pcrel((as), (reg_dest), (label)) #define ASM_LSL_REG_REG(as, reg_dest, reg_shift) \ do { \ @@ -300,7 +308,7 @@ void asm_xtensa_mov_reg_local_addr(asm_xtensa_t *as, uint reg_dest, int local_nu #define ASM_OR_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_or((as), (reg_dest), (reg_dest), (reg_src)) #define ASM_XOR_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_xor((as), (reg_dest), (reg_dest), (reg_src)) #define ASM_AND_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_and((as), (reg_dest), (reg_dest), (reg_src)) -#define ASM_ADD_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_add((as), (reg_dest), (reg_dest), (reg_src)) +#define ASM_ADD_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_add_n((as), (reg_dest), (reg_dest), (reg_src)) #define ASM_SUB_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_sub((as), (reg_dest), (reg_dest), (reg_src)) #define ASM_MUL_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_mull((as), (reg_dest), (reg_dest), (reg_src)) diff --git a/py/bc.c b/py/bc.c index 40a70fe515..1e2c0bbae1 100644 --- a/py/bc.c +++ b/py/bc.c @@ -302,7 +302,7 @@ void mp_setup_code_state(mp_code_state_t *code_state, size_t n_args, size_t n_kw // MP_BC_MAKE_CLOSURE_DEFARGS // MP_BC_RAISE_VARARGS // There are 4 special opcodes that have an extra byte only when -// MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE is enabled: +// MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE is enabled (and they take a qstr): // MP_BC_LOAD_NAME // MP_BC_LOAD_GLOBAL // MP_BC_LOAD_ATTR @@ -396,18 +396,20 @@ uint mp_opcode_format(const byte *ip, size_t *opcode_size) { uint f = (opcode_format_table[*ip >> 2] >> (2 * (*ip & 3))) & 3; const byte *ip_start = ip; if (f == MP_OPCODE_QSTR) { + if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE_DYNAMIC) { + if (*ip == MP_BC_LOAD_NAME + || *ip == MP_BC_LOAD_GLOBAL + || *ip == MP_BC_LOAD_ATTR + || *ip == MP_BC_STORE_ATTR) { + ip += 1; + } + } ip += 3; } else { int extra_byte = ( *ip == MP_BC_RAISE_VARARGS || *ip == MP_BC_MAKE_CLOSURE || *ip == MP_BC_MAKE_CLOSURE_DEFARGS - #if MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE - || *ip == MP_BC_LOAD_NAME - || *ip == MP_BC_LOAD_GLOBAL - || *ip == MP_BC_LOAD_ATTR - || *ip == MP_BC_STORE_ATTR - #endif ); ip += 1; if (f == MP_OPCODE_VAR_UINT) { diff --git a/py/binary.c b/py/binary.c index 846058525f..cd61d74fa8 100644 --- a/py/binary.c +++ b/py/binary.c @@ -371,11 +371,7 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte ** } } - if (val_type == 'x') { - memset(p, 0, 1); - } else { - mp_binary_set_int(MIN((size_t)size, sizeof(val)), struct_type == '>', p, val); - } + mp_binary_set_int(MIN((size_t)size, sizeof(val)), struct_type == '>', p, val); } void mp_binary_set_val_array(char typecode, void *p, mp_uint_t index, mp_obj_t val_in) { diff --git a/py/builtin.h b/py/builtin.h index 2275691fc8..58c4c1e524 100644 --- a/py/builtin.h +++ b/py/builtin.h @@ -106,6 +106,7 @@ extern const mp_obj_module_t mp_module_ujson; extern const mp_obj_module_t mp_module_ure; extern const mp_obj_module_t mp_module_uheapq; extern const mp_obj_module_t mp_module_uhashlib; +extern const mp_obj_module_t mp_module_ucryptolib; extern const mp_obj_module_t mp_module_ubinascii; extern const mp_obj_module_t mp_module_urandom; extern const mp_obj_module_t mp_module_uselect; diff --git a/py/builtinhelp.c b/py/builtinhelp.c index 2e77e6dd93..225126029e 100644 --- a/py/builtinhelp.c +++ b/py/builtinhelp.c @@ -167,13 +167,13 @@ STATIC void mp_help_print_obj(const mp_obj_t obj) { mp_map_t *map = NULL; if (type == &mp_type_module) { - map = mp_obj_dict_get_map(mp_obj_module_get_globals(obj)); + map = &mp_obj_module_get_globals(obj)->map; } else { if (type == &mp_type_type) { type = MP_OBJ_TO_PTR(obj); } - if (type->locals_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(type->locals_dict, &mp_type_dict)) { - map = mp_obj_dict_get_map(type->locals_dict); + if (type->locals_dict != NULL) { + map = &type->locals_dict->map; } } if (map != NULL) { diff --git a/py/circuitpy_defns.mk b/py/circuitpy_defns.mk index bb177c5d07..93488d3d90 100644 --- a/py/circuitpy_defns.mk +++ b/py/circuitpy_defns.mk @@ -280,6 +280,9 @@ endif ifeq ($(CIRCUITPY_SUPERVISOR),1) SRC_PATTERNS += supervisor/% endif +ifeq ($(CIRCUITPY_SYNTHIO),1) +SRC_PATTERNS += synthio/% +endif ifeq ($(CIRCUITPY_TERMINALIO),1) SRC_PATTERNS += terminalio/% fontio/% endif @@ -316,6 +319,9 @@ endif ifeq ($(CIRCUITPY_PEW),1) SRC_PATTERNS += _pew/% endif +ifeq ($(CIRCUITPY_IMAGECAPTURE),1) +SRC_PATTERNS += imagecapture/% +endif ifeq ($(CIRCUITPY_MSGPACK),1) SRC_PATTERNS += msgpack/% endif @@ -364,8 +370,11 @@ SRC_COMMON_HAL_ALL = \ digitalio/DigitalInOut.c \ digitalio/__init__.c \ displayio/ParallelBus.c \ + dualbank/__init__.c \ frequencyio/FrequencyIn.c \ frequencyio/__init__.c \ + imagecapture/ParallelImageCapture.c \ + imagecapture/__init__.c \ gnss/__init__.c \ gnss/GNSS.c \ gnss/PositionFix.c \ @@ -379,7 +388,6 @@ SRC_COMMON_HAL_ALL = \ nvm/ByteArray.c \ nvm/__init__.c \ os/__init__.c \ - dualbank/__init__.c \ ps2io/Ps2.c \ ps2io/__init__.c \ pulseio/PulseIn.c \ @@ -518,11 +526,14 @@ SRC_SHARED_MODULE_ALL = \ random/__init__.c \ rgbmatrix/RGBMatrix.c \ rgbmatrix/__init__.c \ + rotaryio/IncrementalEncoder.c \ sharpdisplay/SharpMemoryFramebuffer.c \ sharpdisplay/__init__.c \ socket/__init__.c \ storage/__init__.c \ struct/__init__.c \ + synthio/MidiTrack.c \ + synthio/__init__.c \ terminalio/Terminal.c \ terminalio/__init__.c \ time/__init__.c \ diff --git a/py/circuitpy_mpconfig.h b/py/circuitpy_mpconfig.h index eedda7ad73..15881f41bd 100644 --- a/py/circuitpy_mpconfig.h +++ b/py/circuitpy_mpconfig.h @@ -412,6 +412,13 @@ extern const struct _mp_obj_module_t terminalio_module; #define TERMINALIO_MODULE #endif +#if CIRCUITPY_DUALBANK +extern const struct _mp_obj_module_t dualbank_module; +#define DUALBANK_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_dualbank), (mp_obj_t)&dualbank_module }, +#else +#define DUALBANK_MODULE +#endif + #if CIRCUITPY_ERRNO #define MICROPY_PY_UERRNO (1) // Uses about 80 bytes. @@ -486,6 +493,13 @@ extern const struct _mp_obj_module_t i2cperipheral_module; #define I2CPERIPHERAL_MODULE #endif +#if CIRCUITPY_IMAGECAPTURE +extern const struct _mp_obj_module_t imagecapture_module; +#define IMAGECAPTURE_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_imagecapture), (mp_obj_t)&imagecapture_module }, +#else +#define IMAGECAPTURE_MODULE +#endif + #if CIRCUITPY_IPADDRESS extern const struct _mp_obj_module_t ipaddress_module; #define IPADDRESS_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_ipaddress), (mp_obj_t)&ipaddress_module }, @@ -574,13 +588,6 @@ extern const struct _mp_obj_module_t os_module; #define OS_MODULE_ALT_NAME #endif -#if CIRCUITPY_DUALBANK -extern const struct _mp_obj_module_t dualbank_module; -#define DUALBANK_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_dualbank), (mp_obj_t)&dualbank_module }, -#else -#define DUALBANK_MODULE -#endif - #if CIRCUITPY_PEW extern const struct _mp_obj_module_t pew_module; #define PEW_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR__pew),(mp_obj_t)&pew_module }, @@ -728,6 +735,13 @@ extern const struct _mp_obj_module_t supervisor_module; #define SUPERVISOR_MODULE #endif +#if CIRCUITPY_SYNTHIO +#define SYNTHIO_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_synthio), (mp_obj_t)&synthio_module }, +extern const struct _mp_obj_module_t synthio_module; +#else +#define SYNTHIO_MODULE +#endif + #if CIRCUITPY_TIME extern const struct _mp_obj_module_t time_module; #define TIME_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_time), (mp_obj_t)&time_module }, @@ -853,6 +867,7 @@ extern const struct _mp_obj_module_t msgpack_module; COUNTIO_MODULE \ DIGITALIO_MODULE \ DISPLAYIO_MODULE \ + DUALBANK_MODULE \ FONTIO_MODULE \ TERMINALIO_MODULE \ VECTORIO_MODULE \ @@ -865,6 +880,7 @@ extern const struct _mp_obj_module_t msgpack_module; GNSS_MODULE \ I2CPERIPHERAL_MODULE \ IPADDRESS_MODULE \ + IMAGECAPTURE_MODULE \ JSON_MODULE \ MATH_MODULE \ _EVE_MODULE \ @@ -875,7 +891,6 @@ extern const struct _mp_obj_module_t msgpack_module; NETWORK_MODULE \ SOCKET_MODULE \ WIZNET_MODULE \ - DUALBANK_MODULE \ PEW_MODULE \ PIXELBUF_MODULE \ PS2IO_MODULE \ @@ -897,6 +912,7 @@ extern const struct _mp_obj_module_t msgpack_module; STORAGE_MODULE \ STRUCT_MODULE \ SUPERVISOR_MODULE \ + SYNTHIO_MODULE \ TOUCHIO_MODULE \ UHEAP_MODULE \ USB_CDC_MODULE \ diff --git a/py/circuitpy_mpconfig.mk b/py/circuitpy_mpconfig.mk index 5dc59cc73b..1758d8fe4c 100644 --- a/py/circuitpy_mpconfig.mk +++ b/py/circuitpy_mpconfig.mk @@ -218,6 +218,9 @@ CFLAGS += -DCIRCUITPY_NVM=$(CIRCUITPY_NVM) CIRCUITPY_OS ?= 1 CFLAGS += -DCIRCUITPY_OS=$(CIRCUITPY_OS) +CIRCUITPY_IMAGECAPTURE ?= 0 +CFLAGS += -DCIRCUITPY_IMAGECAPTURE=$(CIRCUITPY_IMAGECAPTURE) + CIRCUITPY_PEW ?= 0 CFLAGS += -DCIRCUITPY_PEW=$(CIRCUITPY_PEW) diff --git a/py/compile.c b/py/compile.c index 4a9fdc7db8..a484022bb9 100644 --- a/py/compile.c +++ b/py/compile.c @@ -172,7 +172,18 @@ STATIC uint comp_next_label(compiler_t *comp) { return comp->next_label++; } -STATIC void compile_increase_except_level(compiler_t *comp) { +#if MICROPY_EMIT_NATIVE +STATIC void reserve_labels_for_native(compiler_t *comp, int n) { + if (comp->scope_cur->emit_options != MP_EMIT_OPT_BYTECODE) { + comp->next_label += n; + } +} +#else +#define reserve_labels_for_native(comp, n) +#endif + +STATIC void compile_increase_except_level(compiler_t *comp, uint label, int kind) { + EMIT_ARG(setup_block, label, kind); comp->cur_except_level += 1; if (comp->cur_except_level > comp->scope_cur->exc_stack_size) { comp->scope_cur->exc_stack_size = comp->cur_except_level; @@ -182,6 +193,8 @@ STATIC void compile_increase_except_level(compiler_t *comp) { STATIC void compile_decrease_except_level(compiler_t *comp) { assert(comp->cur_except_level > 0); comp->cur_except_level -= 1; + EMIT(end_finally); + reserve_labels_for_native(comp, 1); } STATIC scope_t *scope_new_and_link(compiler_t *comp, scope_kind_t kind, mp_parse_node_t pn, uint emit_options) { @@ -556,6 +569,11 @@ STATIC void close_over_variables_etc(compiler_t *comp, scope_t *this_scope, int } this_scope->num_def_pos_args = n_pos_defaults; + #if MICROPY_EMIT_NATIVE + // When creating a function/closure it will take a reference to the current globals + comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_REFGLOBALS | MP_SCOPE_FLAG_HASCONSTS; + #endif + // make closed over variables, if any // ensure they are closed over in the order defined in the outer scope (mainly to agree with CPython) int nfree = 0; @@ -768,7 +786,7 @@ STATIC bool compile_built_in_decorator(compiler_t *comp, int name_len, mp_parse_ } if (name_len != 2) { - compile_syntax_error(comp, name_nodes[0], translate("invalid micropython decorator")); + compile_syntax_error(comp, name_nodes[0], translate("invalid decorator")); return true; } @@ -1173,23 +1191,24 @@ STATIC void compile_import_from(compiler_t *comp, mp_parse_node_struct_t *pns) { } } -STATIC void compile_declare_global(compiler_t *comp, mp_parse_node_t pn, qstr qst, bool added, id_info_t *id_info) { - if (!added && id_info->kind != ID_INFO_KIND_GLOBAL_EXPLICIT) { +STATIC void compile_declare_global(compiler_t *comp, mp_parse_node_t pn, id_info_t *id_info) { + if (id_info->kind != ID_INFO_KIND_UNDECIDED && id_info->kind != ID_INFO_KIND_GLOBAL_EXPLICIT) { compile_syntax_error(comp, pn, translate("identifier redefined as global")); return; } id_info->kind = ID_INFO_KIND_GLOBAL_EXPLICIT; // if the id exists in the global scope, set its kind to EXPLICIT_GLOBAL - id_info = scope_find_global(comp->scope_cur, qst); + id_info = scope_find_global(comp->scope_cur, id_info->qst); if (id_info != NULL) { id_info->kind = ID_INFO_KIND_GLOBAL_EXPLICIT; } } -STATIC void compile_declare_nonlocal(compiler_t *comp, mp_parse_node_t pn, qstr qst, bool added, id_info_t *id_info) { - if (added) { - scope_find_local_and_close_over(comp->scope_cur, id_info, qst); +STATIC void compile_declare_nonlocal(compiler_t *comp, mp_parse_node_t pn, id_info_t *id_info) { + if (id_info->kind == ID_INFO_KIND_UNDECIDED) { + id_info->kind = ID_INFO_KIND_GLOBAL_IMPLICIT; + scope_check_to_close_over(comp->scope_cur, id_info); if (id_info->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { compile_syntax_error(comp, pn, translate("no binding for nonlocal found")); } @@ -1211,12 +1230,11 @@ STATIC void compile_global_nonlocal_stmt(compiler_t *comp, mp_parse_node_struct_ int n = mp_parse_node_extract_list(&pns->nodes[0], PN_name_list, &nodes); for (int i = 0; i < n; i++) { qstr qst = MP_PARSE_NODE_LEAF_ARG(nodes[i]); - bool added; - id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, qst, &added); + id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, qst, ID_INFO_KIND_UNDECIDED); if (is_global) { - compile_declare_global(comp, (mp_parse_node_t)pns, qst, added, id_info); + compile_declare_global(comp, (mp_parse_node_t)pns, id_info); } else { - compile_declare_nonlocal(comp, (mp_parse_node_t)pns, qst, added, id_info); + compile_declare_nonlocal(comp, (mp_parse_node_t)pns, id_info); } } } @@ -1524,8 +1542,7 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ uint l1 = comp_next_label(comp); uint success_label = comp_next_label(comp); - EMIT_ARG(setup_block, l1, MP_EMIT_SETUP_BLOCK_EXCEPT); - compile_increase_except_level(comp); + compile_increase_except_level(comp, l1, MP_EMIT_SETUP_BLOCK_EXCEPT); compile_node(comp, pn_body); // body EMIT(pop_block); @@ -1579,8 +1596,7 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ uint l3 = 0; if (qstr_exception_local != 0) { l3 = comp_next_label(comp); - EMIT_ARG(setup_block, l3, MP_EMIT_SETUP_BLOCK_FINALLY); - compile_increase_except_level(comp); + compile_increase_except_level(comp, l3, MP_EMIT_SETUP_BLOCK_FINALLY); } compile_node(comp, pns_except->nodes[1]); if (qstr_exception_local != 0) { @@ -1595,7 +1611,6 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ compile_delete_id(comp, qstr_exception_local); compile_decrease_except_level(comp); - EMIT(end_finally); } EMIT_ARG(jump, l2); EMIT_ARG(label_assign, end_finally_label); @@ -1603,7 +1618,6 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ } compile_decrease_except_level(comp); - EMIT(end_finally); EMIT(end_except_handler); EMIT_ARG(label_assign, success_label); @@ -1614,8 +1628,7 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ STATIC void compile_try_finally(compiler_t *comp, mp_parse_node_t pn_body, int n_except, mp_parse_node_t *pn_except, mp_parse_node_t pn_else, mp_parse_node_t pn_finally) { uint l_finally_block = comp_next_label(comp); - EMIT_ARG(setup_block, l_finally_block, MP_EMIT_SETUP_BLOCK_FINALLY); - compile_increase_except_level(comp); + compile_increase_except_level(comp, l_finally_block, MP_EMIT_SETUP_BLOCK_FINALLY); if (n_except == 0) { assert(MP_PARSE_NODE_IS_NULL(pn_else)); @@ -1631,7 +1644,6 @@ STATIC void compile_try_finally(compiler_t *comp, mp_parse_node_t pn_body, int n compile_node(comp, pn_finally); compile_decrease_except_level(comp); - EMIT(end_finally); } STATIC void compile_try_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { @@ -1667,30 +1679,24 @@ STATIC void compile_with_stmt_helper(compiler_t *comp, int n, mp_parse_node_t *n compile_node(comp, body); } else { uint l_end = comp_next_label(comp); - if (MICROPY_EMIT_NATIVE && comp->scope_cur->emit_options != MP_EMIT_OPT_BYTECODE) { - // we need to allocate an extra label for the native emitter - // it will use l_end+1 as an auxiliary label - comp_next_label(comp); - } if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes[0], PN_with_item)) { // this pre-bit is of the form "a as b" mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)nodes[0]; compile_node(comp, pns->nodes[0]); - EMIT_ARG(setup_block, l_end, MP_EMIT_SETUP_BLOCK_WITH); + compile_increase_except_level(comp, l_end, MP_EMIT_SETUP_BLOCK_WITH); c_assign(comp, pns->nodes[1], ASSIGN_STORE); } else { // this pre-bit is just an expression compile_node(comp, nodes[0]); - EMIT_ARG(setup_block, l_end, MP_EMIT_SETUP_BLOCK_WITH); + compile_increase_except_level(comp, l_end, MP_EMIT_SETUP_BLOCK_WITH); EMIT(pop_top); } - compile_increase_except_level(comp); // compile additional pre-bits and the body compile_with_stmt_helper(comp, n - 1, nodes + 1, body); // finish this with block EMIT_ARG(with_cleanup, l_end); + reserve_labels_for_native(comp, 3); // used by native's with_cleanup compile_decrease_except_level(comp); - EMIT(end_finally); } } @@ -1708,6 +1714,7 @@ STATIC void compile_yield_from(compiler_t *comp) { EMIT_ARG(get_iter, false); EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT_ARG(yield, MP_EMIT_YIELD_FROM); + reserve_labels_for_native(comp, 3); } #if MICROPY_PY_ASYNC_AWAIT @@ -1749,8 +1756,7 @@ STATIC void compile_async_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns EMIT_ARG(label_assign, continue_label); - EMIT_ARG(setup_block, try_exception_label, MP_EMIT_SETUP_BLOCK_EXCEPT); - compile_increase_except_level(comp); + compile_increase_except_level(comp, try_exception_label, MP_EMIT_SETUP_BLOCK_EXCEPT); compile_load_id(comp, context); compile_await_object_method(comp, MP_QSTR___anext__); @@ -1771,7 +1777,6 @@ STATIC void compile_async_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns EMIT_ARG(label_assign, try_finally_label); EMIT_ARG(adjust_stack_size, 1); // if we jump here, the exc is on the stack compile_decrease_except_level(comp); - EMIT(end_finally); EMIT(end_except_handler); EMIT_ARG(label_assign, try_else_label); @@ -1792,46 +1797,70 @@ STATIC void compile_async_with_stmt_helper(compiler_t *comp, int n, mp_parse_nod // no more pre-bits, compile the body of the with compile_node(comp, body); } else { - uint try_exception_label = comp_next_label(comp); - uint no_reraise_label = comp_next_label(comp); - uint try_else_label = comp_next_label(comp); - uint end_label = comp_next_label(comp); - qstr context; + uint l_finally_block = comp_next_label(comp); + uint l_aexit_no_exc = comp_next_label(comp); + uint l_ret_unwind_jump = comp_next_label(comp); + uint l_end = comp_next_label(comp); if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes[0], PN_with_item)) { // this pre-bit is of the form "a as b" mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)nodes[0]; compile_node(comp, pns->nodes[0]); - context = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); - compile_store_id(comp, context); - compile_load_id(comp, context); + EMIT(dup_top); compile_await_object_method(comp, MP_QSTR___aenter__); c_assign(comp, pns->nodes[1], ASSIGN_STORE); } else { // this pre-bit is just an expression compile_node(comp, nodes[0]); - context = MP_PARSE_NODE_LEAF_ARG(nodes[0]); - compile_store_id(comp, context); - compile_load_id(comp, context); + EMIT(dup_top); compile_await_object_method(comp, MP_QSTR___aenter__); EMIT(pop_top); } - compile_load_id(comp, context); - EMIT_ARG(load_method, MP_QSTR___aexit__, false); + // To keep the Python stack size down, and because we can't access values on + // this stack further down than 3 elements (via rot_three), we don't preload + // __aexit__ (as per normal with) but rather wait until we need it below. - EMIT_ARG(setup_block, try_exception_label, MP_EMIT_SETUP_BLOCK_EXCEPT); - compile_increase_except_level(comp); - // compile additional pre-bits and the body + // Start the try-finally statement + compile_increase_except_level(comp, l_finally_block, MP_EMIT_SETUP_BLOCK_FINALLY); + + // Compile any additional pre-bits of the "async with", and also the body + EMIT_ARG(adjust_stack_size, 3); // stack adjust for possible UNWIND_JUMP state compile_async_with_stmt_helper(comp, n - 1, nodes + 1, body); - // finish this with block + EMIT_ARG(adjust_stack_size, -3); + + // Finish the "try" block EMIT(pop_block); - EMIT_ARG(jump, try_else_label); // jump over exception handler - EMIT_ARG(label_assign, try_exception_label); // start of exception handler - EMIT(start_except_handler); + // At this point, after the with body has executed, we have 3 cases: + // 1. no exception, we just fall through to this point; stack: (..., ctx_mgr) + // 2. exception propagating out, we get to the finally block; stack: (..., ctx_mgr, exc) + // 3. return or unwind jump, we get to the finally block; stack: (..., ctx_mgr, X, INT) - // at this point the stack contains: ..., __aexit__, self, exc + // Handle case 1: call __aexit__ + // Stack: (..., ctx_mgr) + EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); // to tell end_finally there's no exception + EMIT(rot_two); + EMIT_ARG(jump, l_aexit_no_exc); // jump to code below to call __aexit__ + + // Start of "finally" block + // At this point we have case 2 or 3, we detect which one by the TOS being an exception or not + EMIT_ARG(label_assign, l_finally_block); + + // Detect if TOS an exception or not + EMIT(dup_top); + EMIT_LOAD_GLOBAL(MP_QSTR_Exception); + EMIT_ARG(binary_op, MP_BINARY_OP_EXCEPTION_MATCH); + EMIT_ARG(pop_jump_if, false, l_ret_unwind_jump); // if not an exception then we have case 3 + + // Handle case 2: call __aexit__ and either swallow or re-raise the exception + // Stack: (..., ctx_mgr, exc) + EMIT(dup_top); + EMIT(rot_three); + EMIT(rot_two); + EMIT_ARG(load_method, MP_QSTR___aexit__, false); + EMIT(rot_three); + EMIT(rot_three); EMIT(dup_top); #if MICROPY_CPYTHON_COMPAT EMIT_ARG(attr, MP_QSTR___class__, MP_EMIT_ATTR_LOAD); // get type(exc) @@ -1842,32 +1871,37 @@ STATIC void compile_async_with_stmt_helper(compiler_t *comp, int n, mp_parse_nod #endif EMIT(rot_two); EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); // dummy traceback value - // at this point the stack contains: ..., __aexit__, self, type(exc), exc, None + // Stack: (..., exc, __aexit__, ctx_mgr, type(exc), exc, None) EMIT_ARG(call_method, 3, 0, 0); - compile_yield_from(comp); - EMIT_ARG(pop_jump_if, true, no_reraise_label); - EMIT_ARG(raise_varargs, 0); + EMIT_ARG(pop_jump_if, false, l_end); + EMIT(pop_top); // pop exception + EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); // replace with None to swallow exception + EMIT_ARG(jump, l_end); + EMIT_ARG(adjust_stack_size, 2); - EMIT_ARG(label_assign, no_reraise_label); - EMIT(pop_except); - EMIT_ARG(jump, end_label); - - EMIT_ARG(adjust_stack_size, 3); // adjust for __aexit__, self, exc - compile_decrease_except_level(comp); - EMIT(end_finally); - EMIT(end_except_handler); - - EMIT_ARG(label_assign, try_else_label); // start of try-else handler + // Handle case 3: call __aexit__ + // Stack: (..., ctx_mgr, X, INT) + EMIT_ARG(label_assign, l_ret_unwind_jump); + EMIT(rot_three); + EMIT(rot_three); + EMIT_ARG(label_assign, l_aexit_no_exc); + EMIT_ARG(load_method, MP_QSTR___aexit__, false); EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT(dup_top); EMIT(dup_top); EMIT_ARG(call_method, 3, 0, 0); compile_yield_from(comp); EMIT(pop_top); + EMIT_ARG(adjust_stack_size, -1); - EMIT_ARG(label_assign, end_label); - + // End of "finally" block + // Stack can have one of three configurations: + // a. (..., None) - from either case 1, or case 2 with swallowed exception + // b. (..., exc) - from case 2 with re-raised exception + // c. (..., X, INT) - from case 3 + EMIT_ARG(label_assign, l_end); + compile_decrease_except_level(comp); } } @@ -2688,6 +2722,7 @@ STATIC void compile_yield_expr(compiler_t *comp, mp_parse_node_struct_t *pns) { if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) { EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT_ARG(yield, MP_EMIT_YIELD_VALUE); + reserve_labels_for_native(comp, 1); } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_yield_arg_from)) { pns = (mp_parse_node_struct_t *)pns->nodes[0]; #if MICROPY_PY_ASYNC_AWAIT @@ -2701,6 +2736,7 @@ STATIC void compile_yield_expr(compiler_t *comp, mp_parse_node_struct_t *pns) { } else { compile_node(comp, pns->nodes[0]); EMIT_ARG(yield, MP_EMIT_YIELD_VALUE); + reserve_labels_for_native(comp, 1); } } @@ -2733,6 +2769,9 @@ STATIC mp_obj_t get_const_object(mp_parse_node_struct_t *pns) { } STATIC void compile_const_object(compiler_t *comp, mp_parse_node_struct_t *pns) { + #if MICROPY_EMIT_NATIVE + comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_HASCONSTS; + #endif EMIT_ARG(load_const_obj, get_const_object(pns)); } @@ -2755,7 +2794,7 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { } else if (MP_PARSE_NODE_IS_SMALL_INT(pn)) { mp_int_t arg = MP_PARSE_NODE_LEAF_SMALL_INT(pn); #if MICROPY_DYNAMIC_COMPILER - mp_uint_t sign_mask = -(1 << (mp_dynamic_compiler.small_int_bits - 1)); + mp_uint_t sign_mask = -((mp_uint_t)1 << (mp_dynamic_compiler.small_int_bits - 1)); if ((arg & sign_mask) == 0 || (arg & sign_mask) == sign_mask) { // integer fits in target runtime's small-int EMIT_ARG(load_const_small_int, arg); @@ -2767,6 +2806,9 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { } else { EMIT_ARG(load_const_obj, mp_obj_new_int_from_ll(arg)); } + #if MICROPY_EMIT_NATIVE + comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_HASCONSTS; + #endif } #else EMIT_ARG(load_const_small_int, arg); @@ -2789,6 +2831,9 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { const byte *data = qstr_data(arg, &len); EMIT_ARG(load_const_obj, mp_obj_new_bytes(data, len)); } + #if MICROPY_EMIT_NATIVE + comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_HASCONSTS; + #endif break; case MP_PARSE_NODE_TOKEN: default: @@ -2810,6 +2855,25 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { } } +#if MICROPY_EMIT_NATIVE +STATIC int compile_viper_type_annotation(compiler_t *comp, mp_parse_node_t pn_annotation) { + int native_type = MP_NATIVE_TYPE_OBJ; + if (MP_PARSE_NODE_IS_NULL(pn_annotation)) { + // No annotation, type defaults to object + } else if (MP_PARSE_NODE_IS_ID(pn_annotation)) { + qstr type_name = MP_PARSE_NODE_LEAF_ARG(pn_annotation); + native_type = mp_native_type_from_qstr(type_name); + if (native_type < 0) { + comp->compile_error = mp_obj_new_exception_msg_varg(&mp_type_ViperTypeError, translate("unknown type '%q'"), type_name); + native_type = 0; + } + } else { + compile_syntax_error(comp, pn_annotation, translate("annotation must be an identifier")); + } + return native_type; +} +#endif + STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn, pn_kind_t pn_name, pn_kind_t pn_star, pn_kind_t pn_dbl_star) { // check that **kw is last if ((comp->scope_cur->scope_flags & MP_SCOPE_FLAG_VARKEYWORDS) != 0) { @@ -2819,6 +2883,7 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn qstr param_name = MP_QSTR_NULL; uint param_flag = ID_FLAG_IS_PARAM; + mp_parse_node_struct_t *pns = NULL; if (MP_PARSE_NODE_IS_ID(pn)) { param_name = MP_PARSE_NODE_LEAF_ARG(pn); if (comp->have_star) { @@ -2830,8 +2895,9 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn } } else { assert(MP_PARSE_NODE_IS_STRUCT(pn)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; + pns = (mp_parse_node_struct_t *)pn; if (MP_PARSE_NODE_STRUCT_KIND(pns) == pn_name) { + // named parameter with possible annotation param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); if (comp->have_star) { // comes after a star, so counts as a keyword-only parameter @@ -2852,10 +2918,12 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn // bare star // TODO see http://www.python.org/dev/peps/pep-3102/ // assert(comp->scope_cur->num_dict_params == 0); + pns = NULL; } else if (MP_PARSE_NODE_IS_ID(pns->nodes[0])) { // named star comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_VARARGS; param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); + pns = NULL; } else { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_tfpdef)); // should be // named star with possible annotation @@ -2864,6 +2932,7 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); } } else { + // double star with possible annotation assert(MP_PARSE_NODE_STRUCT_KIND(pns) == pn_dbl_star); // should be param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); param_flag = ID_FLAG_IS_PARAM | ID_FLAG_IS_DBL_STAR_PARAM; @@ -2872,14 +2941,21 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn } if (param_name != MP_QSTR_NULL) { - bool added; - id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, param_name, &added); - if (!added) { + id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, param_name, ID_INFO_KIND_UNDECIDED); + if (id_info->kind != ID_INFO_KIND_UNDECIDED) { compile_syntax_error(comp, pn, translate("name reused for argument")); return; } id_info->kind = ID_INFO_KIND_LOCAL; id_info->flags = param_flag; + + #if MICROPY_EMIT_NATIVE + if (comp->scope_cur->emit_options == MP_EMIT_OPT_VIPER && pn_name == PN_typedargslist_name && pns != NULL) { + id_info->flags |= compile_viper_type_annotation(comp, pns->nodes[1]) << ID_FLAG_VIPER_TYPE_POS; + } + #else + (void)pns; + #endif } } @@ -2891,49 +2967,6 @@ STATIC void compile_scope_lambda_param(compiler_t *comp, mp_parse_node_t pn) { compile_scope_func_lambda_param(comp, pn, PN_varargslist_name, PN_varargslist_star, PN_varargslist_dbl_star); } -#if MICROPY_EMIT_NATIVE -STATIC void compile_scope_func_annotations(compiler_t *comp, mp_parse_node_t pn) { - if (!MP_PARSE_NODE_IS_STRUCT(pn)) { - // no annotation - return; - } - - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; - if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_typedargslist_name) { - // named parameter with possible annotation - // fallthrough - } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_typedargslist_star) { - if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_tfpdef)) { - // named star with possible annotation - pns = (mp_parse_node_struct_t *)pns->nodes[0]; - // fallthrough - } else { - // no annotation - return; - } - } else { - assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_typedargslist_dbl_star); - // double star with possible annotation - // fallthrough - } - - mp_parse_node_t pn_annotation = pns->nodes[1]; - - if (!MP_PARSE_NODE_IS_NULL(pn_annotation)) { - qstr param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); - id_info_t *id_info = scope_find(comp->scope_cur, param_name); - assert(id_info != NULL); - - if (MP_PARSE_NODE_IS_ID(pn_annotation)) { - qstr arg_type = MP_PARSE_NODE_LEAF_ARG(pn_annotation); - EMIT_ARG(set_native_type, MP_EMIT_NATIVE_TYPE_ARG, id_info->local_num, arg_type); - } else { - compile_syntax_error(comp, pn_annotation, translate("parameter annotation must be an identifier")); - } - } -} -#endif // MICROPY_EMIT_NATIVE - STATIC void compile_scope_comp_iter(compiler_t *comp, mp_parse_node_struct_t *pns_comp_for, mp_parse_node_t pn_inner_expr, int for_depth) { uint l_top = comp_next_label(comp); uint l_end = comp_next_label(comp); @@ -2948,6 +2981,7 @@ tail_recursion: compile_node(comp, pn_inner_expr); if (comp->scope_cur->kind == SCOPE_GEN_EXPR) { EMIT_ARG(yield, MP_EMIT_YIELD_VALUE); + reserve_labels_for_native(comp, 1); EMIT(pop_top); } else { EMIT_ARG(store_comp, comp->scope_cur->kind, 4 * for_depth + 5); @@ -3022,6 +3056,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { comp->scope_cur = scope; comp->next_label = 0; EMIT_ARG(start_pass, pass, scope); + reserve_labels_for_native(comp, 6); // used by native's start_pass if (comp->pass == MP_PASS_SCOPE) { // reset maximum stack sizes in scope @@ -3053,28 +3088,14 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { if (comp->pass == MP_PASS_SCOPE) { comp->have_star = false; apply_to_single_or_list(comp, pns->nodes[1], PN_typedargslist, compile_scope_func_param); - } - #if MICROPY_EMIT_NATIVE - else if (scope->emit_options == MP_EMIT_OPT_VIPER) { - // compile annotations; only needed on latter compiler passes - // only needed for viper emitter - // argument annotations - apply_to_single_or_list(comp, pns->nodes[1], PN_typedargslist, compile_scope_func_annotations); - - // pns->nodes[2] is return/whole function annotation - mp_parse_node_t pn_annotation = pns->nodes[2]; - if (!MP_PARSE_NODE_IS_NULL(pn_annotation)) { - // nodes[2] can be null or a test-expr - if (MP_PARSE_NODE_IS_ID(pn_annotation)) { - qstr ret_type = MP_PARSE_NODE_LEAF_ARG(pn_annotation); - EMIT_ARG(set_native_type, MP_EMIT_NATIVE_TYPE_RETURN, 0, ret_type); - } else { - compile_syntax_error(comp, pn_annotation, translate("return annotation must be an identifier")); - } + #if MICROPY_EMIT_NATIVE + if (scope->emit_options == MP_EMIT_OPT_VIPER) { + // Compile return type; pns->nodes[2] is return/whole function annotation + scope->scope_flags |= compile_viper_type_annotation(comp, pns->nodes[2]) << MP_SCOPE_FLAG_VIPERRET_POS; } + #endif // MICROPY_EMIT_NATIVE } - #endif // MICROPY_EMIT_NATIVE compile_node(comp, pns->nodes[3]); // 3 is function body // emit return if it wasn't the last opcode @@ -3117,10 +3138,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { // so we use the blank qstr. qstr qstr_arg = MP_QSTR_; if (comp->pass == MP_PASS_SCOPE) { - bool added; - id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, qstr_arg, &added); - assert(added); - id_info->kind = ID_INFO_KIND_LOCAL; + scope_find_or_add_id(comp->scope_cur, qstr_arg, ID_INFO_KIND_LOCAL); scope->num_pos_args = 1; } @@ -3160,10 +3178,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_classdef); if (comp->pass == MP_PASS_SCOPE) { - bool added; - id_info_t *id_info = scope_find_or_add_id(scope, MP_QSTR___class__, &added); - assert(added); - id_info->kind = ID_INFO_KIND_LOCAL; + scope_find_or_add_id(scope, MP_QSTR___class__, ID_INFO_KIND_LOCAL); } compile_load_id(comp, MP_QSTR___name__); @@ -3393,6 +3408,17 @@ STATIC void scope_compute_things(scope_t *scope) { if (SCOPE_IS_FUNC_LIKE(scope->kind) && id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { id->kind = ID_INFO_KIND_GLOBAL_EXPLICIT; } + #if MICROPY_EMIT_NATIVE + if (id->kind == ID_INFO_KIND_GLOBAL_EXPLICIT) { + // This function makes a reference to a global variable + if (scope->emit_options == MP_EMIT_OPT_VIPER + && mp_native_type_from_qstr(id->qst) >= MP_NATIVE_TYPE_INT) { + // A casting operator in viper mode, not a real global reference + } else { + scope->scope_flags |= MP_SCOPE_FLAG_REFGLOBALS; + } + } + #endif // params always count for 1 local, even if they are a cell if (id->kind == ID_INFO_KIND_LOCAL || (id->flags & ID_FLAG_IS_PARAM)) { id->local_num = scope->num_locals++; @@ -3476,6 +3502,14 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f #endif } else { compile_scope(comp, s, MP_PASS_SCOPE); + + // Check if any implicitly declared variables should be closed over + for (size_t i = 0; i < s->id_info_len; ++i) { + id_info_t *id = &s->id_info[i]; + if (id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { + scope_check_to_close_over(s, id); + } + } } // update maximim number of labels needed @@ -3530,11 +3564,10 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f case MP_EMIT_OPT_NATIVE_PYTHON: case MP_EMIT_OPT_VIPER: if (emit_native == NULL) { - emit_native = NATIVE_EMITTER(new)(&comp->compile_error, max_num_labels); + emit_native = NATIVE_EMITTER(new)(&comp->compile_error, &comp->next_label, max_num_labels); } comp->emit_method_table = &NATIVE_EMITTER(method_table); comp->emit = emit_native; - EMIT_ARG(set_native_type, MP_EMIT_NATIVE_TYPE_ENABLE, s->emit_options == MP_EMIT_OPT_VIPER, 0); break; #endif // MICROPY_EMIT_NATIVE diff --git a/py/compile.h b/py/compile.h index 0f8d023a25..b9c0c653fa 100644 --- a/py/compile.h +++ b/py/compile.h @@ -30,15 +30,6 @@ #include "py/parse.h" #include "py/emitglue.h" -// These must fit in 8 bits; see scope.h -enum { - MP_EMIT_OPT_NONE, - MP_EMIT_OPT_BYTECODE, - MP_EMIT_OPT_NATIVE_PYTHON, - MP_EMIT_OPT_VIPER, - MP_EMIT_OPT_ASM, -}; - // the compiler will raise an exception if an error occurred // the compiler will clear the parse tree before it returns mp_obj_t mp_compile(mp_parse_tree_t *parse_tree, qstr source_file, uint emit_opt, bool is_repl); diff --git a/py/emit.h b/py/emit.h index b142e0641b..24a31f8e23 100644 --- a/py/emit.h +++ b/py/emit.h @@ -51,10 +51,6 @@ typedef enum { #define MP_EMIT_BREAK_FROM_FOR (0x8000) -#define MP_EMIT_NATIVE_TYPE_ENABLE (0) -#define MP_EMIT_NATIVE_TYPE_RETURN (1) -#define MP_EMIT_NATIVE_TYPE_ARG (2) - // Kind for emit_id_ops->local() #define MP_EMIT_IDOP_LOCAL_FAST (0) #define MP_EMIT_IDOP_LOCAL_DEREF (1) @@ -102,7 +98,6 @@ typedef struct _mp_emit_method_table_id_ops_t { } mp_emit_method_table_id_ops_t; typedef struct _emit_method_table_t { - void (*set_native_type)(emit_t *emit, mp_uint_t op, mp_uint_t arg1, qstr arg2); void (*start_pass)(emit_t *emit, pass_kind_t pass, scope_t *scope); void (*end_pass)(emit_t *emit); bool (*last_emit_was_return_value)(emit_t *emit); @@ -162,7 +157,12 @@ typedef struct _emit_method_table_t { void (*end_except_handler)(emit_t *emit); } emit_method_table_t; -void mp_emit_common_get_id_for_load(scope_t *scope, qstr qst); +int mp_native_type_from_qstr(qstr qst); + +static inline void mp_emit_common_get_id_for_load(scope_t *scope, qstr qst) { + scope_find_or_add_id(scope, qst, ID_INFO_KIND_GLOBAL_IMPLICIT); +} + void mp_emit_common_get_id_for_modification(scope_t *scope, qstr qst); void mp_emit_common_id_op(emit_t *emit, const mp_emit_method_table_id_ops_t *emit_method_table, scope_t *scope, qstr qst); @@ -178,11 +178,11 @@ extern const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_store_id_ops; extern const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_delete_id_ops; emit_t *emit_bc_new(void); -emit_t *emit_native_x64_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); -emit_t *emit_native_x86_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); -emit_t *emit_native_thumb_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); -emit_t *emit_native_arm_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); -emit_t *emit_native_xtensa_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); +emit_t *emit_native_x64_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_x86_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_thumb_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_arm_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_xtensa_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); void emit_bc_set_max_num_labels(emit_t *emit, mp_uint_t max_num_labels); diff --git a/py/emitbc.c b/py/emitbc.c index 37960cb6b4..7e2989276f 100644 --- a/py/emitbc.c +++ b/py/emitbc.c @@ -331,6 +331,10 @@ void mp_emit_bc_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scope) { // the highest slot in the state (fastn[0], see vm.c). n_state = 1; } + #if MICROPY_DEBUG_VM_STACK_OVERFLOW + // An extra slot in the stack is needed to detect VM stack overflow + n_state += 1; + #endif emit_write_code_info_uint(emit, n_state); emit_write_code_info_uint(emit, scope->exc_stack_size); } @@ -916,7 +920,6 @@ void mp_emit_bc_end_except_handler(emit_t *emit) { #if MICROPY_EMIT_NATIVE const emit_method_table_t emit_bc_method_table = { - NULL, // set_native_type is never called when emitting bytecode mp_emit_bc_start_pass, mp_emit_bc_end_pass, mp_emit_bc_last_emit_was_return_value, diff --git a/py/emitcommon.c b/py/emitcommon.c index 88c9803a6e..177418c30a 100644 --- a/py/emitcommon.c +++ b/py/emitcommon.c @@ -30,26 +30,10 @@ #if MICROPY_ENABLE_COMPILER -void mp_emit_common_get_id_for_load(scope_t *scope, qstr qst) { - // name adding/lookup - bool added; - id_info_t *id = scope_find_or_add_id(scope, qst, &added); - if (added) { - scope_find_local_and_close_over(scope, id, qst); - } -} - void mp_emit_common_get_id_for_modification(scope_t *scope, qstr qst) { // name adding/lookup - bool added; - id_info_t *id = scope_find_or_add_id(scope, qst, &added); - if (added) { - if (SCOPE_IS_FUNC_LIKE(scope->kind)) { - id->kind = ID_INFO_KIND_LOCAL; - } else { - id->kind = ID_INFO_KIND_GLOBAL_IMPLICIT; - } - } else if (SCOPE_IS_FUNC_LIKE(scope->kind) && id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { + id_info_t *id = scope_find_or_add_id(scope, qst, ID_INFO_KIND_GLOBAL_IMPLICIT); + if (SCOPE_IS_FUNC_LIKE(scope->kind) && id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { // rebind as a local variable id->kind = ID_INFO_KIND_LOCAL; } diff --git a/py/emitglue.c b/py/emitglue.c index d0286803e7..4949053410 100644 --- a/py/emitglue.c +++ b/py/emitglue.c @@ -76,6 +76,9 @@ void mp_emit_glue_assign_bytecode(mp_raw_code_t *rc, const byte *code, #endif #ifdef DEBUG_PRINT + #if !MICROPY_DEBUG_PRINTERS + const size_t len = 0; + #endif DEBUG_printf("assign byte code: code=%p len=" UINT_FMT " flags=%x\n", code, len, (uint)scope_flags); #endif #if MICROPY_DEBUG_PRINTERS @@ -131,10 +134,8 @@ mp_obj_t mp_make_function_from_raw_code(const mp_raw_code_t *rc, mp_obj_t def_ar switch (rc->kind) { #if MICROPY_EMIT_NATIVE case MP_CODE_NATIVE_PY: - fun = mp_obj_new_fun_native(def_args, def_kw_args, rc->data.u_native.fun_data, rc->data.u_native.const_table); - break; case MP_CODE_NATIVE_VIPER: - fun = mp_obj_new_fun_viper(rc->n_pos_args, rc->data.u_native.fun_data, rc->data.u_native.type_sig); + fun = mp_obj_new_fun_native(def_args, def_kw_args, rc->data.u_native.fun_data, rc->data.u_native.const_table); break; #endif #if MICROPY_EMIT_INLINE_ASM diff --git a/py/emitglue.h b/py/emitglue.h index 2ddcc3e53e..fc352fdbab 100644 --- a/py/emitglue.h +++ b/py/emitglue.h @@ -30,6 +30,15 @@ // These variables and functions glue the code emitters to the runtime. +// These must fit in 8 bits; see scope.h +enum { + MP_EMIT_OPT_NONE, + MP_EMIT_OPT_BYTECODE, + MP_EMIT_OPT_NATIVE_PYTHON, + MP_EMIT_OPT_VIPER, + MP_EMIT_OPT_ASM, +}; + typedef enum { MP_CODE_UNUSED, MP_CODE_RESERVED, diff --git a/py/emitnarm.c b/py/emitnarm.c index 1b585f821b..8297ad6192 100644 --- a/py/emitnarm.c +++ b/py/emitnarm.c @@ -8,6 +8,11 @@ #define GENERIC_ASM_API (1) #include "py/asmarm.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (3) // r4 +#define NLR_BUF_IDX_LOCAL_2 (4) // r5 +#define NLR_BUF_IDX_LOCAL_3 (5) // r6 + #define N_ARM (1) #define EXPORT_FUN(name) emit_native_arm_##name #include "py/emitnative.c" diff --git a/py/emitnative.c b/py/emitnative.c index 57b75030a4..bcf7793c86 100644 --- a/py/emitnative.c +++ b/py/emitnative.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George + * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -49,8 +49,6 @@ #include "py/emit.h" #include "py/bc.h" -#include "supervisor/shared/translate.h" - #if MICROPY_DEBUG_VERBOSE // print debugging info #define DEBUG_PRINT (1) #define DEBUG_printf DEBUG_printf @@ -59,30 +57,76 @@ #endif #ifndef N_X64 - #define N_X64 (0) +#define N_X64 (0) #endif + #ifndef N_X86 - #define N_X86 (0) +#define N_X86 (0) #endif + #ifndef N_THUMB - #define N_THUMB (0) +#define N_THUMB (0) #endif + #ifndef N_ARM - #define N_ARM (0) +#define N_ARM (0) #endif + #ifndef N_XTENSA - #define N_XTENSA (0) +#define N_XTENSA (0) #endif // wrapper around everything in this file #if N_X64 || N_X86 || N_THUMB || N_ARM || N_XTENSA -// define additional generic helper macros -#define ASM_MOV_LOCAL_IMM_VIA(as, local_num, imm, reg_temp) \ - do { \ - ASM_MOV_REG_IMM((as), (reg_temp), (imm)); \ - ASM_MOV_LOCAL_REG((as), (local_num), (reg_temp)); \ - } while (false) +// C stack layout for native functions: +// 0: nlr_buf_t [optional] +// emit->code_state_start: mp_code_state_t +// emit->stack_start: Python object stack | emit->n_state +// locals (reversed, L0 at end) | +// +// C stack layout for native generator functions: +// 0=emit->stack_start: nlr_buf_t +// +// Then REG_GENERATOR_STATE points to: +// 0=emit->code_state_start: mp_code_state_t +// emit->stack_start: Python object stack | emit->n_state +// locals (reversed, L0 at end) | +// +// C stack layout for viper functions: +// 0: nlr_buf_t [optional] +// emit->code_state_start: fun_obj, old_globals [optional] +// emit->stack_start: Python object stack | emit->n_state +// locals (reversed, L0 at end) | +// (L0-L2 may be in regs instead) + +// Word index of nlr_buf_t.ret_val +#define NLR_BUF_IDX_RET_VAL (1) + +// Whether the viper function needs access to fun_obj +#define NEED_FUN_OBJ(emit) ((emit)->scope->exc_stack_size > 0 \ + || ((emit)->scope->scope_flags & (MP_SCOPE_FLAG_REFGLOBALS | MP_SCOPE_FLAG_HASCONSTS))) + +// Whether the native/viper function needs to be wrapped in an exception handler +#define NEED_GLOBAL_EXC_HANDLER(emit) ((emit)->scope->exc_stack_size > 0 \ + || ((emit)->scope->scope_flags & (MP_SCOPE_FLAG_GENERATOR | MP_SCOPE_FLAG_REFGLOBALS))) + +// Whether registers can be used to store locals (only true if there are no +// exception handlers, because otherwise an nlr_jump will restore registers to +// their state at the start of the function and updates to locals will be lost) +#define CAN_USE_REGS_FOR_LOCALS(emit) ((emit)->scope->exc_stack_size == 0 && !(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) + +// Indices within the local C stack for various variables +#define LOCAL_IDX_EXC_VAL(emit) (NLR_BUF_IDX_RET_VAL) +#define LOCAL_IDX_EXC_HANDLER_PC(emit) (NLR_BUF_IDX_LOCAL_1) +#define LOCAL_IDX_EXC_HANDLER_UNWIND(emit) (NLR_BUF_IDX_LOCAL_2) +#define LOCAL_IDX_RET_VAL(emit) (NLR_BUF_IDX_LOCAL_3) +#define LOCAL_IDX_FUN_OBJ(emit) ((emit)->code_state_start + offsetof(mp_code_state_t, fun_bc) / sizeof(uintptr_t)) +#define LOCAL_IDX_OLD_GLOBALS(emit) ((emit)->code_state_start + offsetof(mp_code_state_t, ip) / sizeof(uintptr_t)) +#define LOCAL_IDX_GEN_PC(emit) ((emit)->code_state_start + offsetof(mp_code_state_t, ip) / sizeof(uintptr_t)) +#define LOCAL_IDX_LOCAL_VAR(emit, local_num) ((emit)->stack_start + (emit)->n_state - 1 - (local_num)) + +#define REG_GENERATOR_STATE (REG_LOCAL_3) #define EMIT_NATIVE_VIPER_TYPE_ERROR(emit, ...) do { \ *emit->error_slot = mp_obj_new_exception_msg_varg(&mp_type_ViperTypeError, __VA_ARGS__); \ @@ -112,6 +156,29 @@ typedef enum { VTYPE_BUILTIN_CAST = 0x70 | MP_NATIVE_TYPE_OBJ, } vtype_kind_t; +int mp_native_type_from_qstr(qstr qst) { + switch (qst) { + case MP_QSTR_object: + return MP_NATIVE_TYPE_OBJ; + case MP_QSTR_bool: + return MP_NATIVE_TYPE_BOOL; + case MP_QSTR_int: + return MP_NATIVE_TYPE_INT; + case MP_QSTR_uint: + return MP_NATIVE_TYPE_UINT; + case MP_QSTR_ptr: + return MP_NATIVE_TYPE_PTR; + case MP_QSTR_ptr8: + return MP_NATIVE_TYPE_PTR8; + case MP_QSTR_ptr16: + return MP_NATIVE_TYPE_PTR16; + case MP_QSTR_ptr32: + return MP_NATIVE_TYPE_PTR32; + default: + return -1; + } +} + STATIC qstr vtype_to_qstr(vtype_kind_t vtype) { switch (vtype) { case VTYPE_PYOBJ: @@ -145,14 +212,24 @@ typedef struct _stack_info_t { } data; } stack_info_t; +#define UNWIND_LABEL_UNUSED (0x7fff) +#define UNWIND_LABEL_DO_FINAL_UNWIND (0x7ffe) + +typedef struct _exc_stack_entry_t { + uint16_t label : 15; + uint16_t is_finally : 1; + uint16_t unwind_label : 15; + uint16_t is_active : 1; +} exc_stack_entry_t; + struct _emit_t { mp_obj_t *error_slot; + uint *label_slot; + uint exit_label; int pass; bool do_viper_types; - vtype_kind_t return_vtype; - mp_uint_t local_vtype_alloc; vtype_kind_t *local_vtype; @@ -160,12 +237,22 @@ struct _emit_t { stack_info_t *stack_info; vtype_kind_t saved_stack_vtype; + size_t exc_stack_alloc; + size_t exc_stack_size; + exc_stack_entry_t *exc_stack; + int prelude_offset; - int const_table_offset; + int start_offset; int n_state; - int stack_start; + uint16_t code_state_start; + uint16_t stack_start; int stack_size; + uint16_t const_table_cur_obj; + uint16_t const_table_num_obj; + uint16_t const_table_cur_raw_code; + mp_uint_t *const_table; + bool last_emit_was_return_value; scope_t *scope; @@ -173,9 +260,19 @@ struct _emit_t { ASM_T *as; }; -emit_t *EXPORT_FUN(new)(mp_obj_t * error_slot, mp_uint_t max_num_labels) { +STATIC const uint8_t reg_local_table[REG_LOCAL_NUM] = {REG_LOCAL_1, REG_LOCAL_2, REG_LOCAL_3}; + +STATIC void emit_native_global_exc_entry(emit_t *emit); +STATIC void emit_native_global_exc_exit(emit_t *emit); + +emit_t *EXPORT_FUN(new)(mp_obj_t * error_slot, uint *label_slot, mp_uint_t max_num_labels) { emit_t *emit = m_new0(emit_t, 1); emit->error_slot = error_slot; + emit->label_slot = label_slot; + emit->stack_info_alloc = 8; + emit->stack_info = m_new(stack_info_t, emit->stack_info_alloc); + emit->exc_stack_alloc = 8; + emit->exc_stack = m_new(exc_stack_entry_t, emit->exc_stack_alloc); emit->as = m_new0(ASM_T, 1); mp_asm_base_init(&emit->as->base, max_num_labels); return emit; @@ -184,72 +281,57 @@ emit_t *EXPORT_FUN(new)(mp_obj_t * error_slot, mp_uint_t max_num_labels) { void EXPORT_FUN(free)(emit_t * emit) { mp_asm_base_deinit(&emit->as->base, false); m_del_obj(ASM_T, emit->as); + m_del(exc_stack_entry_t, emit->exc_stack, emit->exc_stack_alloc); m_del(vtype_kind_t, emit->local_vtype, emit->local_vtype_alloc); m_del(stack_info_t, emit->stack_info, emit->stack_info_alloc); m_del_obj(emit_t, emit); } -STATIC void emit_native_set_native_type(emit_t *emit, mp_uint_t op, mp_uint_t arg1, qstr arg2) { - switch (op) { - case MP_EMIT_NATIVE_TYPE_ENABLE: - emit->do_viper_types = arg1; - break; +STATIC void emit_call_with_imm_arg(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val, int arg_reg); - default: { - vtype_kind_t type; - switch (arg2) { - case MP_QSTR_object: - type = VTYPE_PYOBJ; - break; - case MP_QSTR_bool: - type = VTYPE_BOOL; - break; - case MP_QSTR_int: - type = VTYPE_INT; - break; - case MP_QSTR_uint: - type = VTYPE_UINT; - break; - case MP_QSTR_ptr: - type = VTYPE_PTR; - break; - case MP_QSTR_ptr8: - type = VTYPE_PTR8; - break; - case MP_QSTR_ptr16: - type = VTYPE_PTR16; - break; - case MP_QSTR_ptr32: - type = VTYPE_PTR32; - break; - default: - EMIT_NATIVE_VIPER_TYPE_ERROR(emit, translate("unknown type '%q'"), arg2); - return; - } - if (op == MP_EMIT_NATIVE_TYPE_RETURN) { - emit->return_vtype = type; - } else { - assert(arg1 < emit->local_vtype_alloc); - emit->local_vtype[arg1] = type; - } - break; - } +STATIC void emit_native_mov_reg_const(emit_t *emit, int reg_dest, int const_val) { + ASM_LOAD_REG_REG_OFFSET(emit->as, reg_dest, REG_FUN_TABLE, const_val); +} + +STATIC void emit_native_mov_state_reg(emit_t *emit, int local_num, int reg_src) { + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + ASM_STORE_REG_REG_OFFSET(emit->as, reg_src, REG_GENERATOR_STATE, local_num); + } else { + ASM_MOV_LOCAL_REG(emit->as, local_num, reg_src); } } -STATIC void emit_pre_pop_reg(emit_t *emit, vtype_kind_t *vtype, int reg_dest); -STATIC void emit_post_push_reg(emit_t *emit, vtype_kind_t vtype, int reg); -STATIC void emit_native_load_fast(emit_t *emit, qstr qst, mp_uint_t local_num); -STATIC void emit_native_store_fast(emit_t *emit, qstr qst, mp_uint_t local_num); +STATIC void emit_native_mov_reg_state(emit_t *emit, int reg_dest, int local_num) { + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + ASM_LOAD_REG_REG_OFFSET(emit->as, reg_dest, REG_GENERATOR_STATE, local_num); + } else { + ASM_MOV_REG_LOCAL(emit->as, reg_dest, local_num); + } +} -#define STATE_START (sizeof(mp_code_state_t) / sizeof(mp_uint_t)) +STATIC void emit_native_mov_reg_state_addr(emit_t *emit, int reg_dest, int local_num) { + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + ASM_MOV_REG_IMM(emit->as, reg_dest, local_num * ASM_WORD_SIZE); + ASM_ADD_REG_REG(emit->as, reg_dest, REG_GENERATOR_STATE); + } else { + ASM_MOV_REG_LOCAL_ADDR(emit->as, reg_dest, local_num); + } +} + +#define emit_native_mov_state_imm_via(emit, local_num, imm, reg_temp) \ + do { \ + ASM_MOV_REG_IMM((emit)->as, (reg_temp), (imm)); \ + emit_native_mov_state_reg((emit), (local_num), (reg_temp)); \ + } while (false) STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scope) { DEBUG_printf("start_pass(pass=%u, scope=%p)\n", pass, scope); emit->pass = pass; - emit->stack_start = 0; + emit->do_viper_types = scope->emit_options == MP_EMIT_OPT_VIPER; emit->stack_size = 0; + emit->const_table_cur_obj = 1; // first entry is for mp_fun_table + emit->const_table_cur_raw_code = 0; emit->last_emit_was_return_value = false; emit->scope = scope; @@ -259,17 +341,6 @@ STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop emit->local_vtype_alloc = scope->num_locals; } - // allocate memory for keeping track of the objects on the stack - // XXX don't know stack size on entry, and it should be maximum over all scopes - // XXX this is such a big hack and really needs to be fixed - if (emit->stack_info == NULL) { - emit->stack_info_alloc = scope->stack_size + 200; - emit->stack_info = m_new(stack_info_t, emit->stack_info_alloc); - } - - // set default type for return - emit->return_vtype = VTYPE_PYOBJ; - // set default type for arguments mp_uint_t num_args = emit->scope->num_pos_args + emit->scope->num_kwonly_args; if (scope->scope_flags & MP_SCOPE_FLAG_VARARGS) { @@ -282,6 +353,17 @@ STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop emit->local_vtype[i] = VTYPE_PYOBJ; } + // Set viper type for arguments + if (emit->do_viper_types) { + for (int i = 0; i < emit->scope->id_info_len; ++i) { + id_info_t *id = &emit->scope->id_info[i]; + if (id->flags & ID_FLAG_IS_PARAM) { + assert(id->local_num < emit->local_vtype_alloc); + emit->local_vtype[id->local_num] = id->flags >> ID_FLAG_VIPER_TYPE_POS; + } + } + } + // local variables begin unbound, and have unknown type for (mp_uint_t i = num_args; i < emit->local_vtype_alloc; i++) { emit->local_vtype[i] = VTYPE_UNBOUND; @@ -297,111 +379,171 @@ STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop // generate code for entry to function + // Work out start of code state (mp_code_state_t or reduced version for viper) + emit->code_state_start = 0; + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + emit->code_state_start = sizeof(nlr_buf_t) / sizeof(uintptr_t); + } + if (emit->do_viper_types) { - - // right now we have a restriction of maximum of 4 arguments - if (scope->num_pos_args >= 5) { - EMIT_NATIVE_VIPER_TYPE_ERROR(emit, translate("Viper functions don't currently support more than 4 arguments")); - return; - } - - // entry to function - int num_locals = 0; - if (pass > MP_PASS_SCOPE) { - num_locals = scope->num_locals - REG_LOCAL_NUM; - if (num_locals < 0) { - num_locals = 0; + // Work out size of state (locals plus stack) + // n_state counts all stack and locals, even those in registers + emit->n_state = scope->num_locals + scope->stack_size; + int num_locals_in_regs = 0; + if (CAN_USE_REGS_FOR_LOCALS(emit)) { + num_locals_in_regs = scope->num_locals; + if (num_locals_in_regs > REG_LOCAL_NUM) { + num_locals_in_regs = REG_LOCAL_NUM; + } + // Need a spot for REG_LOCAL_3 if 4 or more args (see below) + if (scope->num_pos_args >= 4) { + --num_locals_in_regs; } - emit->stack_start = num_locals; - num_locals += scope->stack_size; } - ASM_ENTRY(emit->as, num_locals); - // TODO don't load r7 if we don't need it - #if N_THUMB - asm_thumb_mov_reg_i32(emit->as, ASM_THUMB_REG_R7, (mp_uint_t)mp_fun_table); - #elif N_ARM - asm_arm_mov_reg_i32(emit->as, ASM_ARM_REG_R7, (mp_uint_t)mp_fun_table); - #endif + // Work out where the locals and Python stack start within the C stack + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + // Reserve 2 words for function object and old globals + emit->stack_start = emit->code_state_start + 2; + } else if (scope->scope_flags & MP_SCOPE_FLAG_HASCONSTS) { + // Reserve 1 word for function object, to access const table + emit->stack_start = emit->code_state_start + 1; + } else { + emit->stack_start = emit->code_state_start + 0; + } + + // Entry to function + ASM_ENTRY(emit->as, emit->stack_start + emit->n_state - num_locals_in_regs); #if N_X86 - for (int i = 0; i < scope->num_pos_args; i++) { - if (i == 0) { - asm_x86_mov_arg_to_r32(emit->as, i, REG_LOCAL_1); - } else if (i == 1) { - asm_x86_mov_arg_to_r32(emit->as, i, REG_LOCAL_2); - } else if (i == 2) { - asm_x86_mov_arg_to_r32(emit->as, i, REG_LOCAL_3); - } else { - asm_x86_mov_arg_to_r32(emit->as, i, REG_TEMP0); - asm_x86_mov_r32_to_local(emit->as, REG_TEMP0, i - REG_LOCAL_NUM); - } - } - #else - for (int i = 0; i < scope->num_pos_args; i++) { - if (i == 0) { - ASM_MOV_REG_REG(emit->as, REG_LOCAL_1, REG_ARG_1); - } else if (i == 1) { - ASM_MOV_REG_REG(emit->as, REG_LOCAL_2, REG_ARG_2); - } else if (i == 2) { - ASM_MOV_REG_REG(emit->as, REG_LOCAL_3, REG_ARG_3); - } else { - assert(i == 3); // should be true; max 4 args is checked above - ASM_MOV_LOCAL_REG(emit->as, i - REG_LOCAL_NUM, REG_ARG_4); - } - } + asm_x86_mov_arg_to_r32(emit->as, 0, REG_ARG_1); #endif + // Load REG_FUN_TABLE with a pointer to mp_fun_table, found in the const_table + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_LOCAL_3, REG_ARG_1, offsetof(mp_obj_fun_bc_t, const_table) / sizeof(uintptr_t)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_FUN_TABLE, REG_LOCAL_3, 0); + + // Store function object (passed as first arg) to stack if needed + if (NEED_FUN_OBJ(emit)) { + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_FUN_OBJ(emit), REG_ARG_1); + } + + // Put n_args in REG_ARG_1, n_kw in REG_ARG_2, args array in REG_LOCAL_3 + #if N_X86 + asm_x86_mov_arg_to_r32(emit->as, 1, REG_ARG_1); + asm_x86_mov_arg_to_r32(emit->as, 2, REG_ARG_2); + asm_x86_mov_arg_to_r32(emit->as, 3, REG_LOCAL_3); + #else + ASM_MOV_REG_REG(emit->as, REG_ARG_1, REG_ARG_2); + ASM_MOV_REG_REG(emit->as, REG_ARG_2, REG_ARG_3); + ASM_MOV_REG_REG(emit->as, REG_LOCAL_3, REG_ARG_4); + #endif + + // Check number of args matches this function, and call mp_arg_check_num_sig if not + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_ARG_2, *emit->label_slot + 4, true); + ASM_MOV_REG_IMM(emit->as, REG_ARG_3, scope->num_pos_args); + ASM_JUMP_IF_REG_EQ(emit->as, REG_ARG_1, REG_ARG_3, *emit->label_slot + 5); + mp_asm_base_label_assign(&emit->as->base, *emit->label_slot + 4); + ASM_MOV_REG_IMM(emit->as, REG_ARG_3, MP_OBJ_FUN_MAKE_SIG(scope->num_pos_args, scope->num_pos_args, false)); + ASM_CALL_IND(emit->as, MP_F_ARG_CHECK_NUM_SIG); + mp_asm_base_label_assign(&emit->as->base, *emit->label_slot + 5); + + // Store arguments into locals (reg or stack), converting to native if needed + for (int i = 0; i < emit->scope->num_pos_args; i++) { + int r = REG_ARG_1; + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_ARG_1, REG_LOCAL_3, i); + if (emit->local_vtype[i] != VTYPE_PYOBJ) { + emit_call_with_imm_arg(emit, MP_F_CONVERT_OBJ_TO_NATIVE, emit->local_vtype[i], REG_ARG_2); + r = REG_RET; + } + // REG_LOCAL_3 points to the args array so be sure not to overwrite it if it's still needed + if (i < REG_LOCAL_NUM && CAN_USE_REGS_FOR_LOCALS(emit) && (i != 2 || emit->scope->num_pos_args == 3)) { + ASM_MOV_REG_REG(emit->as, reg_local_table[i], r); + } else { + emit_native_mov_state_reg(emit, LOCAL_IDX_LOCAL_VAR(emit, i), r); + } + } + // Get 3rd local from the stack back into REG_LOCAL_3 if this reg couldn't be written to above + if (emit->scope->num_pos_args >= 4 && CAN_USE_REGS_FOR_LOCALS(emit)) { + ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_3, LOCAL_IDX_LOCAL_VAR(emit, 2)); + } + + emit_native_global_exc_entry(emit); + } else { // work out size of state (locals plus stack) emit->n_state = scope->num_locals + scope->stack_size; - // allocate space on C-stack for code_state structure, which includes state - ASM_ENTRY(emit->as, STATE_START + emit->n_state); + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + emit->code_state_start = 0; + emit->stack_start = sizeof(mp_code_state_t) / sizeof(mp_uint_t); + mp_asm_base_data(&emit->as->base, ASM_WORD_SIZE, (uintptr_t)emit->prelude_offset); + mp_asm_base_data(&emit->as->base, ASM_WORD_SIZE, (uintptr_t)emit->start_offset); + ASM_ENTRY(emit->as, sizeof(nlr_buf_t) / sizeof(uintptr_t)); - // TODO don't load r7 if we don't need it - #if N_THUMB - asm_thumb_mov_reg_i32(emit->as, ASM_THUMB_REG_R7, (mp_uint_t)mp_fun_table); - #elif N_ARM - asm_arm_mov_reg_i32(emit->as, ASM_ARM_REG_R7, (mp_uint_t)mp_fun_table); - #endif + // Put address of code_state into REG_GENERATOR_STATE + #if N_X86 + asm_x86_mov_arg_to_r32(emit->as, 0, REG_GENERATOR_STATE); + #else + ASM_MOV_REG_REG(emit->as, REG_GENERATOR_STATE, REG_ARG_1); + #endif - // prepare incoming arguments for call to mp_setup_code_state + // Put throw value into LOCAL_IDX_EXC_VAL slot, for yield/yield-from + #if N_X86 + asm_x86_mov_arg_to_r32(emit->as, 1, REG_ARG_2); + #endif + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_ARG_2); - #if N_X86 - asm_x86_mov_arg_to_r32(emit->as, 0, REG_ARG_1); - asm_x86_mov_arg_to_r32(emit->as, 1, REG_ARG_2); - asm_x86_mov_arg_to_r32(emit->as, 2, REG_ARG_3); - asm_x86_mov_arg_to_r32(emit->as, 3, REG_ARG_4); - #endif + // Load REG_FUN_TABLE with a pointer to mp_fun_table, found in the const_table + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_TEMP0, REG_GENERATOR_STATE, LOCAL_IDX_FUN_OBJ(emit)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_TEMP0, REG_TEMP0, offsetof(mp_obj_fun_bc_t, const_table) / sizeof(uintptr_t)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_FUN_TABLE, REG_TEMP0, emit->scope->num_pos_args + emit->scope->num_kwonly_args); + } else { + // The locals and stack start after the code_state structure + emit->stack_start = emit->code_state_start + sizeof(mp_code_state_t) / sizeof(mp_uint_t); - // set code_state.fun_bc - ASM_MOV_LOCAL_REG(emit->as, offsetof(mp_code_state_t, fun_bc) / sizeof(uintptr_t), REG_ARG_1); + // Allocate space on C-stack for code_state structure, which includes state + ASM_ENTRY(emit->as, emit->stack_start + emit->n_state); - // set code_state.ip (offset from start of this function to prelude info) - // XXX this encoding may change size - ASM_MOV_LOCAL_IMM_VIA(emit->as, offsetof(mp_code_state_t, ip) / sizeof(uintptr_t), emit->prelude_offset, REG_ARG_1); + // Prepare incoming arguments for call to mp_setup_code_state - // put address of code_state into first arg - ASM_MOV_REG_LOCAL_ADDR(emit->as, REG_ARG_1, 0); + #if N_X86 + asm_x86_mov_arg_to_r32(emit->as, 0, REG_ARG_1); + asm_x86_mov_arg_to_r32(emit->as, 1, REG_ARG_2); + asm_x86_mov_arg_to_r32(emit->as, 2, REG_ARG_3); + asm_x86_mov_arg_to_r32(emit->as, 3, REG_ARG_4); + #endif - // call mp_setup_code_state to prepare code_state structure - #if N_THUMB - asm_thumb_bl_ind(emit->as, mp_fun_table[MP_F_SETUP_CODE_STATE], MP_F_SETUP_CODE_STATE, ASM_THUMB_REG_R4); - #elif N_ARM - asm_arm_bl_ind(emit->as, mp_fun_table[MP_F_SETUP_CODE_STATE], MP_F_SETUP_CODE_STATE, ASM_ARM_REG_R4); - #else - ASM_CALL_IND(emit->as, mp_fun_table[MP_F_SETUP_CODE_STATE], MP_F_SETUP_CODE_STATE); - #endif + // Load REG_FUN_TABLE with a pointer to mp_fun_table, found in the const_table + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_LOCAL_3, REG_ARG_1, offsetof(mp_obj_fun_bc_t, const_table) / sizeof(uintptr_t)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_FUN_TABLE, REG_LOCAL_3, emit->scope->num_pos_args + emit->scope->num_kwonly_args); - // cache some locals in registers - if (scope->num_locals > 0) { - ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_1, STATE_START + emit->n_state - 1 - 0); - if (scope->num_locals > 1) { - ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_2, STATE_START + emit->n_state - 1 - 1); - if (scope->num_locals > 2) { - ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_3, STATE_START + emit->n_state - 1 - 2); - } + // Set code_state.fun_bc + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_FUN_OBJ(emit), REG_ARG_1); + + // Set code_state.ip (offset from start of this function to prelude info) + // TODO this encoding may change size in the final pass, need to make it fixed + emit_native_mov_state_imm_via(emit, emit->code_state_start + offsetof(mp_code_state_t, ip) / sizeof(uintptr_t), emit->prelude_offset, REG_ARG_1); + + // Put address of code_state into first arg + ASM_MOV_REG_LOCAL_ADDR(emit->as, REG_ARG_1, emit->code_state_start); + + // Call mp_setup_code_state to prepare code_state structure + #if N_THUMB + asm_thumb_bl_ind(emit->as, MP_F_SETUP_CODE_STATE, ASM_THUMB_REG_R4); + #elif N_ARM + asm_arm_bl_ind(emit->as, MP_F_SETUP_CODE_STATE, ASM_ARM_REG_R4); + #else + ASM_CALL_IND(emit->as, MP_F_SETUP_CODE_STATE); + #endif + } + + emit_native_global_exc_entry(emit); + + // cache some locals in registers, but only if no exception handlers + if (CAN_USE_REGS_FOR_LOCALS(emit)) { + for (int i = 0; i < REG_LOCAL_NUM && i < scope->num_locals; ++i) { + ASM_MOV_REG_LOCAL(emit->as, reg_local_table[i], LOCAL_IDX_LOCAL_VAR(emit, i)); } } @@ -412,14 +554,28 @@ STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop emit->local_vtype[id->local_num] = VTYPE_PYOBJ; } } + + if (pass == MP_PASS_EMIT) { + // write argument names as qstr objects + // see comment in corresponding part of emitbc.c about the logic here + for (int i = 0; i < scope->num_pos_args + scope->num_kwonly_args; i++) { + qstr qst = MP_QSTR__star_; + for (int j = 0; j < scope->id_info_len; ++j) { + id_info_t *id = &scope->id_info[j]; + if ((id->flags & ID_FLAG_IS_PARAM) && id->local_num == i) { + qst = id->qst; + break; + } + } + emit->const_table[i] = (mp_uint_t)MP_OBJ_NEW_QSTR(qst); + } + } } } STATIC void emit_native_end_pass(emit_t *emit) { - if (!emit->last_emit_was_return_value) { - ASM_EXIT(emit->as); - } + emit_native_global_exc_exit(emit); if (!emit->do_viper_types) { emit->prelude_offset = mp_asm_base_get_code_pos(&emit->as->base); @@ -451,49 +607,38 @@ STATIC void emit_native_end_pass(emit_t *emit) { } } mp_asm_base_data(&emit->as->base, 1, 255); // end of list sentinel - - mp_asm_base_align(&emit->as->base, ASM_WORD_SIZE); - emit->const_table_offset = mp_asm_base_get_code_pos(&emit->as->base); - - // write argument names as qstr objects - // see comment in corresponding part of emitbc.c about the logic here - for (int i = 0; i < emit->scope->num_pos_args + emit->scope->num_kwonly_args; i++) { - qstr qst = MP_QSTR__star_; - for (int j = 0; j < emit->scope->id_info_len; ++j) { - id_info_t *id = &emit->scope->id_info[j]; - if ((id->flags & ID_FLAG_IS_PARAM) && id->local_num == i) { - qst = id->qst; - break; - } - } - mp_asm_base_data(&emit->as->base, ASM_WORD_SIZE, (mp_uint_t)MP_OBJ_NEW_QSTR(qst)); - } - } ASM_END_PASS(emit->as); // check stack is back to zero size assert(emit->stack_size == 0); + assert(emit->exc_stack_size == 0); + + // Deal with const table accounting + assert(emit->pass <= MP_PASS_STACK_SIZE || (emit->const_table_num_obj == emit->const_table_cur_obj)); + emit->const_table_num_obj = emit->const_table_cur_obj; + if (emit->pass == MP_PASS_CODE_SIZE) { + size_t const_table_alloc = emit->const_table_num_obj + emit->const_table_cur_raw_code; + size_t nqstr = 0; + if (!emit->do_viper_types) { + // Add room for qstr names of arguments + nqstr = emit->scope->num_pos_args + emit->scope->num_kwonly_args; + const_table_alloc += nqstr; + } + emit->const_table = m_new(mp_uint_t, const_table_alloc); + // Store mp_fun_table pointer just after qstrs + emit->const_table[nqstr] = (mp_uint_t)(uintptr_t)mp_fun_table; + } if (emit->pass == MP_PASS_EMIT) { void *f = mp_asm_base_get_code(&emit->as->base); mp_uint_t f_len = mp_asm_base_get_code_size(&emit->as->base); - // compute type signature - // note that the lower 4 bits of a vtype are tho correct MP_NATIVE_TYPE_xxx - mp_uint_t type_sig = emit->return_vtype & 0xf; - for (mp_uint_t i = 0; i < emit->scope->num_pos_args; i++) { - type_sig |= (emit->local_vtype[i] & 0xf) << (i * 4 + 4); - } - - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wcast-align" mp_emit_glue_assign_native(emit->scope->raw_code, emit->do_viper_types ? MP_CODE_NATIVE_VIPER : MP_CODE_NATIVE_PY, - f, f_len, (mp_uint_t *)((byte *)f + emit->const_table_offset), - emit->scope->num_pos_args, emit->scope->scope_flags, type_sig); - #pragma GCC diagnostic pop + f, f_len, emit->const_table, + emit->scope->num_pos_args, emit->scope->scope_flags, 0); } } @@ -501,8 +646,17 @@ STATIC bool emit_native_last_emit_was_return_value(emit_t *emit) { return emit->last_emit_was_return_value; } +STATIC void ensure_extra_stack(emit_t *emit, size_t delta) { + if (emit->stack_size + delta > emit->stack_info_alloc) { + size_t new_alloc = (emit->stack_size + delta + 8) & ~3; + emit->stack_info = m_renew(stack_info_t, emit->stack_info, emit->stack_info_alloc, new_alloc); + emit->stack_info_alloc = new_alloc; + } +} + STATIC void adjust_stack(emit_t *emit, mp_int_t stack_size_delta) { assert((mp_int_t)emit->stack_size + stack_size_delta >= 0); + assert((mp_int_t)emit->stack_size + stack_size_delta <= (mp_int_t)emit->stack_info_alloc); emit->stack_size += stack_size_delta; if (emit->pass > MP_PASS_SCOPE && emit->stack_size > emit->scope->stack_size) { emit->scope->stack_size = emit->stack_size; @@ -519,6 +673,9 @@ STATIC void adjust_stack(emit_t *emit, mp_int_t stack_size_delta) { STATIC void emit_native_adjust_stack_size(emit_t *emit, mp_int_t delta) { DEBUG_printf("adjust_stack_size(" INT_FMT ")\n", delta); + if (delta > 0) { + ensure_extra_stack(emit, delta); + } // If we are adjusting the stack in a positive direction (pushing) then we // need to fill in values for the stack kind and vtype of the newly-pushed // entries. These should be set to "value" (ie not reg or imm) because we @@ -555,7 +712,12 @@ STATIC stack_info_t *peek_stack(emit_t *emit, mp_uint_t depth) { // depth==0 is top, depth==1 is before top, etc STATIC vtype_kind_t peek_vtype(emit_t *emit, mp_uint_t depth) { - return peek_stack(emit, depth)->vtype; + if (emit->do_viper_types) { + return peek_stack(emit, depth)->vtype; + } else { + // Type is always PYOBJ even if the intermediate stored value is not + return VTYPE_PYOBJ; + } } // pos=1 is TOS, pos=2 is next, etc @@ -567,7 +729,7 @@ STATIC void need_reg_single(emit_t *emit, int reg_needed, int skip_stack_pos) { stack_info_t *si = &emit->stack_info[i]; if (si->kind == STACK_REG && si->data.u_reg == reg_needed) { si->kind = STACK_VALUE; - ASM_MOV_LOCAL_REG(emit->as, emit->stack_start + i, si->data.u_reg); + emit_native_mov_state_reg(emit, emit->stack_start + i, si->data.u_reg); } } } @@ -578,11 +740,31 @@ STATIC void need_reg_all(emit_t *emit) { stack_info_t *si = &emit->stack_info[i]; if (si->kind == STACK_REG) { si->kind = STACK_VALUE; - ASM_MOV_LOCAL_REG(emit->as, emit->stack_start + i, si->data.u_reg); + emit_native_mov_state_reg(emit, emit->stack_start + i, si->data.u_reg); } } } +STATIC vtype_kind_t load_reg_stack_imm(emit_t *emit, int reg_dest, const stack_info_t *si, bool convert_to_pyobj) { + if (!convert_to_pyobj && emit->do_viper_types) { + ASM_MOV_REG_IMM(emit->as, reg_dest, si->data.u_imm); + return si->vtype; + } else { + if (si->vtype == VTYPE_PYOBJ) { + ASM_MOV_REG_IMM(emit->as, reg_dest, si->data.u_imm); + } else if (si->vtype == VTYPE_BOOL) { + emit_native_mov_reg_const(emit, reg_dest, MP_F_CONST_FALSE_OBJ + si->data.u_imm); + } else if (si->vtype == VTYPE_INT || si->vtype == VTYPE_UINT) { + ASM_MOV_REG_IMM(emit->as, reg_dest, (uintptr_t)MP_OBJ_NEW_SMALL_INT(si->data.u_imm)); + } else if (si->vtype == VTYPE_PTR_NONE) { + emit_native_mov_reg_const(emit, reg_dest, MP_F_CONST_NONE_OBJ); + } else { + mp_raise_NotImplementedError(translate("conversion to object")); + } + return VTYPE_PYOBJ; + } +} + STATIC void need_stack_settled(emit_t *emit) { DEBUG_printf(" need_stack_settled; stack_size=%d\n", emit->stack_size); for (int i = 0; i < emit->stack_size; i++) { @@ -590,7 +772,7 @@ STATIC void need_stack_settled(emit_t *emit) { if (si->kind == STACK_REG) { DEBUG_printf(" reg(%u) to local(%u)\n", si->data.u_reg, emit->stack_start + i); si->kind = STACK_VALUE; - ASM_MOV_LOCAL_REG(emit->as, emit->stack_start + i, si->data.u_reg); + emit_native_mov_state_reg(emit, emit->stack_start + i, si->data.u_reg); } } for (int i = 0; i < emit->stack_size; i++) { @@ -598,7 +780,8 @@ STATIC void need_stack_settled(emit_t *emit) { if (si->kind == STACK_IMM) { DEBUG_printf(" imm(" INT_FMT ") to local(%u)\n", si->data.u_imm, emit->stack_start + i); si->kind = STACK_VALUE; - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + i, si->data.u_imm, REG_TEMP0); + si->vtype = load_reg_stack_imm(emit, REG_TEMP0, si, false); + emit_native_mov_state_reg(emit, emit->stack_start + i, REG_TEMP0); } } } @@ -610,7 +793,7 @@ STATIC void emit_access_stack(emit_t *emit, int pos, vtype_kind_t *vtype, int re *vtype = si->vtype; switch (si->kind) { case STACK_VALUE: - ASM_MOV_REG_LOCAL(emit->as, reg_dest, emit->stack_start + emit->stack_size - pos); + emit_native_mov_reg_state(emit, reg_dest, emit->stack_start + emit->stack_size - pos); break; case STACK_REG: @@ -620,7 +803,7 @@ STATIC void emit_access_stack(emit_t *emit, int pos, vtype_kind_t *vtype, int re break; case STACK_IMM: - ASM_MOV_REG_IMM(emit->as, reg_dest, si->data.u_imm); + *vtype = load_reg_stack_imm(emit, reg_dest, si, false); break; } } @@ -632,7 +815,7 @@ STATIC void emit_fold_stack_top(emit_t *emit, int reg_dest) { si[0] = si[1]; if (si->kind == STACK_VALUE) { // if folded element was on the stack we need to put it in a register - ASM_MOV_REG_LOCAL(emit->as, reg_dest, emit->stack_start + emit->stack_size - 1); + emit_native_mov_reg_state(emit, reg_dest, emit->stack_start + emit->stack_size - 1); si->kind = STACK_REG; si->data.u_reg = reg_dest; } @@ -686,6 +869,7 @@ STATIC void emit_post_top_set_vtype(emit_t *emit, vtype_kind_t new_vtype) { } STATIC void emit_post_push_reg(emit_t *emit, vtype_kind_t vtype, int reg) { + ensure_extra_stack(emit, 1); stack_info_t *si = &emit->stack_info[emit->stack_size]; si->vtype = vtype; si->kind = STACK_REG; @@ -694,6 +878,7 @@ STATIC void emit_post_push_reg(emit_t *emit, vtype_kind_t vtype, int reg) { } STATIC void emit_post_push_imm(emit_t *emit, vtype_kind_t vtype, mp_int_t imm) { + ensure_extra_stack(emit, 1); stack_info_t *si = &emit->stack_info[emit->stack_size]; si->vtype = vtype; si->kind = STACK_IMM; @@ -721,36 +906,20 @@ STATIC void emit_post_push_reg_reg_reg_reg(emit_t *emit, vtype_kind_t vtypea, in STATIC void emit_call(emit_t *emit, mp_fun_kind_t fun_kind) { need_reg_all(emit); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); + ASM_CALL_IND(emit->as, fun_kind); } STATIC void emit_call_with_imm_arg(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val, int arg_reg) { need_reg_all(emit); ASM_MOV_REG_IMM(emit->as, arg_reg, arg_val); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); -} - -// the first arg is stored in the code aligned on a mp_uint_t boundary -STATIC void emit_call_with_imm_arg_aligned(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val, int arg_reg) { - need_reg_all(emit); - ASM_MOV_REG_ALIGNED_IMM(emit->as, arg_reg, arg_val); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); + ASM_CALL_IND(emit->as, fun_kind); } STATIC void emit_call_with_2_imm_args(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val1, int arg_reg1, mp_int_t arg_val2, int arg_reg2) { need_reg_all(emit); ASM_MOV_REG_IMM(emit->as, arg_reg1, arg_val1); ASM_MOV_REG_IMM(emit->as, arg_reg2, arg_val2); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); -} - -// the first arg is stored in the code aligned on a mp_uint_t boundary -STATIC void emit_call_with_3_imm_args_and_first_aligned(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val1, int arg_reg1, mp_int_t arg_val2, int arg_reg2, mp_int_t arg_val3, int arg_reg3) { - need_reg_all(emit); - ASM_MOV_REG_ALIGNED_IMM(emit->as, arg_reg1, arg_val1); - ASM_MOV_REG_IMM(emit->as, arg_reg2, arg_val2); - ASM_MOV_REG_IMM(emit->as, arg_reg3, arg_val3); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); + ASM_CALL_IND(emit->as, fun_kind); } // vtype of all n_pop objects is VTYPE_PYOBJ @@ -767,27 +936,8 @@ STATIC void emit_get_stack_pointer_to_reg_for_pop(emit_t *emit, mp_uint_t reg_de // must convert them to VTYPE_PYOBJ for viper code if (si->kind == STACK_IMM) { si->kind = STACK_VALUE; - switch (si->vtype) { - case VTYPE_PYOBJ: - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + emit->stack_size - 1 - i, si->data.u_imm, reg_dest); - break; - case VTYPE_BOOL: - if (si->data.u_imm == 0) { - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + emit->stack_size - 1 - i, (mp_uint_t)mp_const_false, reg_dest); - } else { - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + emit->stack_size - 1 - i, (mp_uint_t)mp_const_true, reg_dest); - } - si->vtype = VTYPE_PYOBJ; - break; - case VTYPE_INT: - case VTYPE_UINT: - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + emit->stack_size - 1 - i, (uintptr_t)MP_OBJ_NEW_SMALL_INT(si->data.u_imm), reg_dest); - si->vtype = VTYPE_PYOBJ; - break; - default: - // not handled - mp_raise_NotImplementedError(translate("conversion to object")); - } + si->vtype = load_reg_stack_imm(emit, reg_dest, si, true); + emit_native_mov_state_reg(emit, emit->stack_start + emit->stack_size - 1 - i, reg_dest); } // verify that this value is on the stack @@ -799,9 +949,9 @@ STATIC void emit_get_stack_pointer_to_reg_for_pop(emit_t *emit, mp_uint_t reg_de stack_info_t *si = &emit->stack_info[emit->stack_size - 1 - i]; if (si->vtype != VTYPE_PYOBJ) { mp_uint_t local_num = emit->stack_start + emit->stack_size - 1 - i; - ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, local_num); + emit_native_mov_reg_state(emit, REG_ARG_1, local_num); emit_call_with_imm_arg(emit, MP_F_CONVERT_NATIVE_TO_OBJ, si->vtype, REG_ARG_2); // arg2 = type - ASM_MOV_LOCAL_REG(emit->as, local_num, REG_RET); + emit_native_mov_state_reg(emit, local_num, REG_RET); si->vtype = VTYPE_PYOBJ; DEBUG_printf(" convert_native_to_obj(local_num=" UINT_FMT ")\n", local_num); } @@ -809,59 +959,266 @@ STATIC void emit_get_stack_pointer_to_reg_for_pop(emit_t *emit, mp_uint_t reg_de // Adujust the stack for a pop of n_pop items, and load the stack pointer into reg_dest. adjust_stack(emit, -n_pop); - ASM_MOV_REG_LOCAL_ADDR(emit->as, reg_dest, emit->stack_start + emit->stack_size); + emit_native_mov_reg_state_addr(emit, reg_dest, emit->stack_start + emit->stack_size); } // vtype of all n_push objects is VTYPE_PYOBJ STATIC void emit_get_stack_pointer_to_reg_for_push(emit_t *emit, mp_uint_t reg_dest, mp_uint_t n_push) { need_reg_all(emit); + ensure_extra_stack(emit, n_push); for (mp_uint_t i = 0; i < n_push; i++) { emit->stack_info[emit->stack_size + i].kind = STACK_VALUE; emit->stack_info[emit->stack_size + i].vtype = VTYPE_PYOBJ; } - ASM_MOV_REG_LOCAL_ADDR(emit->as, reg_dest, emit->stack_start + emit->stack_size); + emit_native_mov_reg_state_addr(emit, reg_dest, emit->stack_start + emit->stack_size); adjust_stack(emit, n_push); } +STATIC void emit_native_push_exc_stack(emit_t *emit, uint label, bool is_finally) { + if (emit->exc_stack_size + 1 > emit->exc_stack_alloc) { + size_t new_alloc = emit->exc_stack_alloc + 4; + emit->exc_stack = m_renew(exc_stack_entry_t, emit->exc_stack, emit->exc_stack_alloc, new_alloc); + emit->exc_stack_alloc = new_alloc; + } + + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size++]; + e->label = label; + e->is_finally = is_finally; + e->unwind_label = UNWIND_LABEL_UNUSED; + e->is_active = true; + + ASM_MOV_REG_PCREL(emit->as, REG_RET, label); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_RET); +} + +STATIC void emit_native_leave_exc_stack(emit_t *emit, bool start_of_handler) { + assert(emit->exc_stack_size > 0); + + // Get current exception handler and deactivate it + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; + e->is_active = false; + + // Find next innermost active exception handler, to restore as current handler + for (--e; e >= emit->exc_stack && !e->is_active; --e) { + } + + // Update the PC of the new exception handler + if (e < emit->exc_stack) { + // No active handler, clear handler PC to zero + if (start_of_handler) { + // Optimisation: PC is already cleared by global exc handler + return; + } + ASM_XOR_REG_REG(emit->as, REG_RET, REG_RET); + } else { + // Found new active handler, get its PC + ASM_MOV_REG_PCREL(emit->as, REG_RET, e->label); + } + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_RET); +} + +STATIC exc_stack_entry_t *emit_native_pop_exc_stack(emit_t *emit) { + assert(emit->exc_stack_size > 0); + exc_stack_entry_t *e = &emit->exc_stack[--emit->exc_stack_size]; + assert(e->is_active == false); + return e; +} + +STATIC void emit_load_reg_with_ptr(emit_t *emit, int reg, mp_uint_t ptr, size_t table_off) { + if (!emit->do_viper_types) { + // Skip qstr names of arguments + table_off += emit->scope->num_pos_args + emit->scope->num_kwonly_args; + } + if (emit->pass == MP_PASS_EMIT) { + emit->const_table[table_off] = ptr; + } + emit_native_mov_reg_state(emit, REG_TEMP0, LOCAL_IDX_FUN_OBJ(emit)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_TEMP0, REG_TEMP0, offsetof(mp_obj_fun_bc_t, const_table) / sizeof(uintptr_t)); + ASM_LOAD_REG_REG_OFFSET(emit->as, reg, REG_TEMP0, table_off); +} + +STATIC void emit_load_reg_with_object(emit_t *emit, int reg, mp_obj_t obj) { + size_t table_off = emit->const_table_cur_obj++; + emit_load_reg_with_ptr(emit, reg, (mp_uint_t)obj, table_off); +} + +STATIC void emit_load_reg_with_raw_code(emit_t *emit, int reg, mp_raw_code_t *rc) { + size_t table_off = emit->const_table_num_obj + emit->const_table_cur_raw_code++; + emit_load_reg_with_ptr(emit, reg, (mp_uint_t)rc, table_off); +} + STATIC void emit_native_label_assign(emit_t *emit, mp_uint_t l) { DEBUG_printf("label_assign(" UINT_FMT ")\n", l); + + bool is_finally = false; + if (emit->exc_stack_size > 0) { + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; + is_finally = e->is_finally && e->label == l; + } + + if (is_finally) { + // Label is at start of finally handler: store TOS into exception slot + vtype_kind_t vtype; + emit_pre_pop_reg(emit, &vtype, REG_TEMP0); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); + } + emit_native_pre(emit); // need to commit stack because we can jump here from elsewhere need_stack_settled(emit); mp_asm_base_label_assign(&emit->as->base, l); emit_post(emit); + + if (is_finally) { + // Label is at start of finally handler: pop exception stack + emit_native_leave_exc_stack(emit, false); + } +} + +STATIC void emit_native_global_exc_entry(emit_t *emit) { + // Note: 4 labels are reserved for this function, starting at *emit->label_slot + + emit->exit_label = *emit->label_slot; + + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + mp_uint_t nlr_label = *emit->label_slot + 1; + mp_uint_t start_label = *emit->label_slot + 2; + mp_uint_t global_except_label = *emit->label_slot + 3; + + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + // Set new globals + emit_native_mov_reg_state(emit, REG_ARG_1, LOCAL_IDX_FUN_OBJ(emit)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_ARG_1, REG_ARG_1, offsetof(mp_obj_fun_bc_t, globals) / sizeof(uintptr_t)); + emit_call(emit, MP_F_NATIVE_SWAP_GLOBALS); + + // Save old globals (or NULL if globals didn't change) + emit_native_mov_state_reg(emit, LOCAL_IDX_OLD_GLOBALS(emit), REG_RET); + } + + if (emit->scope->exc_stack_size == 0) { + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + // Optimisation: if globals didn't change don't push the nlr context + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, start_label, false); + } + + // Wrap everything in an nlr context + ASM_MOV_REG_LOCAL_ADDR(emit->as, REG_ARG_1, 0); + emit_call(emit, MP_F_NLR_PUSH); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, start_label, true); + } else { + // Clear the unwind state + ASM_XOR_REG_REG(emit->as, REG_TEMP0, REG_TEMP0); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_UNWIND(emit), REG_TEMP0); + + // Put PC of start code block into REG_LOCAL_1 + ASM_MOV_REG_PCREL(emit->as, REG_LOCAL_1, start_label); + + // Wrap everything in an nlr context + emit_native_label_assign(emit, nlr_label); + ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_2, LOCAL_IDX_EXC_HANDLER_UNWIND(emit)); + ASM_MOV_REG_LOCAL_ADDR(emit->as, REG_ARG_1, 0); + emit_call(emit, MP_F_NLR_PUSH); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_UNWIND(emit), REG_LOCAL_2); + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, global_except_label, true); + + // Clear PC of current code block, and jump there to resume execution + ASM_XOR_REG_REG(emit->as, REG_TEMP0, REG_TEMP0); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_TEMP0); + ASM_JUMP_REG(emit->as, REG_LOCAL_1); + + // Global exception handler: check for valid exception handler + emit_native_label_assign(emit, global_except_label); + ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_1, LOCAL_IDX_EXC_HANDLER_PC(emit)); + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_LOCAL_1, nlr_label, false); + } + + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + // Restore old globals + emit_native_mov_reg_state(emit, REG_ARG_1, LOCAL_IDX_OLD_GLOBALS(emit)); + emit_call(emit, MP_F_NATIVE_SWAP_GLOBALS); + } + + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + // Store return value in state[0] + ASM_MOV_REG_LOCAL(emit->as, REG_TEMP0, LOCAL_IDX_EXC_VAL(emit)); + ASM_STORE_REG_REG_OFFSET(emit->as, REG_TEMP0, REG_GENERATOR_STATE, offsetof(mp_code_state_t, state) / sizeof(uintptr_t)); + + // Load return kind + ASM_MOV_REG_IMM(emit->as, REG_RET, MP_VM_RETURN_EXCEPTION); + + ASM_EXIT(emit->as); + } else { + // Re-raise exception out to caller + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); + emit_call(emit, MP_F_NATIVE_RAISE); + } + + // Label for start of function + emit_native_label_assign(emit, start_label); + + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + emit_native_mov_reg_state(emit, REG_TEMP0, LOCAL_IDX_GEN_PC(emit)); + ASM_JUMP_REG(emit->as, REG_TEMP0); + emit->start_offset = mp_asm_base_get_code_pos(&emit->as->base); + + // This is the first entry of the generator + + // Check LOCAL_IDX_EXC_VAL for any injected value + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); + emit_call(emit, MP_F_NATIVE_RAISE); + } + } +} + +STATIC void emit_native_global_exc_exit(emit_t *emit) { + // Label for end of function + emit_native_label_assign(emit, emit->exit_label); + + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + // Get old globals + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + emit_native_mov_reg_state(emit, REG_ARG_1, LOCAL_IDX_OLD_GLOBALS(emit)); + + if (emit->scope->exc_stack_size == 0) { + // Optimisation: if globals didn't change then don't restore them and don't do nlr_pop + ASM_JUMP_IF_REG_ZERO(emit->as, REG_ARG_1, emit->exit_label + 1, false); + } + + // Restore old globals + emit_call(emit, MP_F_NATIVE_SWAP_GLOBALS); + } + + // Pop the nlr context + emit_call(emit, MP_F_NLR_POP); + + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + if (emit->scope->exc_stack_size == 0) { + // Destination label for above optimisation + emit_native_label_assign(emit, emit->exit_label + 1); + } + } + + // Load return value + ASM_MOV_REG_LOCAL(emit->as, REG_RET, LOCAL_IDX_RET_VAL(emit)); + } + + ASM_EXIT(emit->as); } STATIC void emit_native_import_name(emit_t *emit, qstr qst) { DEBUG_printf("import_name %s\n", qstr_str(qst)); // get arguments from stack: arg2 = fromlist, arg3 = level - // if using viper types these arguments must be converted to proper objects - if (emit->do_viper_types) { - // fromlist should be None or a tuple - stack_info_t *top = peek_stack(emit, 0); - if (top->vtype == VTYPE_PTR_NONE) { - emit_pre_pop_discard(emit); - ASM_MOV_REG_IMM(emit->as, REG_ARG_2, (mp_uint_t)mp_const_none); - } else { - vtype_kind_t vtype_fromlist; - emit_pre_pop_reg(emit, &vtype_fromlist, REG_ARG_2); - assert(vtype_fromlist == VTYPE_PYOBJ); - } - - // level argument should be an immediate integer - top = peek_stack(emit, 0); - assert(top->vtype == VTYPE_INT && top->kind == STACK_IMM); - ASM_MOV_REG_IMM(emit->as, REG_ARG_3, (mp_uint_t)MP_OBJ_NEW_SMALL_INT(top->data.u_imm)); - emit_pre_pop_discard(emit); - - } else { - vtype_kind_t vtype_fromlist; - vtype_kind_t vtype_level; - emit_pre_pop_reg_reg(emit, &vtype_fromlist, REG_ARG_2, &vtype_level, REG_ARG_3); - assert(vtype_fromlist == VTYPE_PYOBJ); - assert(vtype_level == VTYPE_PYOBJ); - } + // If using viper types these arguments must be converted to proper objects, and + // to accomplish this viper types are turned off for the emit_pre_pop_reg_reg call. + bool orig_do_viper_types = emit->do_viper_types; + emit->do_viper_types = false; + vtype_kind_t vtype_fromlist; + vtype_kind_t vtype_level; + emit_pre_pop_reg_reg(emit, &vtype_fromlist, REG_ARG_2, &vtype_level, REG_ARG_3); + assert(vtype_fromlist == VTYPE_PYOBJ); + assert(vtype_level == VTYPE_PYOBJ); + emit->do_viper_types = orig_do_viper_types; emit_call_with_imm_arg(emit, MP_F_IMPORT_NAME, qst, REG_ARG_1); // arg1 = import name emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); @@ -898,58 +1255,22 @@ STATIC void emit_native_import(emit_t *emit, qstr qst, int kind) { STATIC void emit_native_load_const_tok(emit_t *emit, mp_token_kind_t tok) { DEBUG_printf("load_const_tok(tok=%u)\n", tok); - emit_native_pre(emit); - vtype_kind_t vtype; - mp_uint_t val; - if (emit->do_viper_types) { - switch (tok) { - case MP_TOKEN_KW_NONE: - vtype = VTYPE_PTR_NONE; - val = 0; - break; - case MP_TOKEN_KW_FALSE: - vtype = VTYPE_BOOL; - val = 0; - break; - case MP_TOKEN_KW_TRUE: - vtype = VTYPE_BOOL; - val = 1; - break; - default: - assert(tok == MP_TOKEN_ELLIPSIS); - vtype = VTYPE_PYOBJ; - val = (mp_uint_t)&mp_const_ellipsis_obj; - break; - } + if (tok == MP_TOKEN_ELLIPSIS) { + emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)MP_OBJ_FROM_PTR(&mp_const_ellipsis_obj)); } else { - vtype = VTYPE_PYOBJ; - switch (tok) { - case MP_TOKEN_KW_NONE: - val = (mp_uint_t)mp_const_none; - break; - case MP_TOKEN_KW_FALSE: - val = (mp_uint_t)mp_const_false; - break; - case MP_TOKEN_KW_TRUE: - val = (mp_uint_t)mp_const_true; - break; - default: - assert(tok == MP_TOKEN_ELLIPSIS); - val = (mp_uint_t)&mp_const_ellipsis_obj; - break; + emit_native_pre(emit); + if (tok == MP_TOKEN_KW_NONE) { + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); + } else { + emit_post_push_imm(emit, VTYPE_BOOL, tok == MP_TOKEN_KW_FALSE ? 0 : 1); } } - emit_post_push_imm(emit, vtype, val); } STATIC void emit_native_load_const_small_int(emit_t *emit, mp_int_t arg) { DEBUG_printf("load_const_small_int(int=" INT_FMT ")\n", arg); emit_native_pre(emit); - if (emit->do_viper_types) { - emit_post_push_imm(emit, VTYPE_INT, arg); - } else { - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)MP_OBJ_NEW_SMALL_INT(arg)); - } + emit_post_push_imm(emit, VTYPE_INT, arg); } STATIC void emit_native_load_const_str(emit_t *emit, qstr qst) { @@ -970,7 +1291,7 @@ STATIC void emit_native_load_const_str(emit_t *emit, qstr qst) { STATIC void emit_native_load_const_obj(emit_t *emit, mp_obj_t obj) { emit_native_pre(emit); need_reg_single(emit, REG_RET, 0); - ASM_MOV_REG_ALIGNED_IMM(emit->as, REG_RET, (mp_uint_t)obj); + emit_load_reg_with_object(emit, REG_RET, obj); emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } @@ -986,19 +1307,11 @@ STATIC void emit_native_load_fast(emit_t *emit, qstr qst, mp_uint_t local_num) { EMIT_NATIVE_VIPER_TYPE_ERROR(emit, translate("local '%q' used before type known"), qst); } emit_native_pre(emit); - if (local_num == 0) { - emit_post_push_reg(emit, vtype, REG_LOCAL_1); - } else if (local_num == 1) { - emit_post_push_reg(emit, vtype, REG_LOCAL_2); - } else if (local_num == 2) { - emit_post_push_reg(emit, vtype, REG_LOCAL_3); + if (local_num < REG_LOCAL_NUM && CAN_USE_REGS_FOR_LOCALS(emit)) { + emit_post_push_reg(emit, vtype, reg_local_table[local_num]); } else { need_reg_single(emit, REG_TEMP0, 0); - if (emit->do_viper_types) { - ASM_MOV_REG_LOCAL(emit->as, REG_TEMP0, local_num - REG_LOCAL_NUM); - } else { - ASM_MOV_REG_LOCAL(emit->as, REG_TEMP0, STATE_START + emit->n_state - 1 - local_num); - } + emit_native_mov_reg_state(emit, REG_TEMP0, LOCAL_IDX_LOCAL_VAR(emit, local_num)); emit_post_push_reg(emit, vtype, REG_TEMP0); } } @@ -1033,23 +1346,9 @@ STATIC void emit_native_load_global(emit_t *emit, qstr qst, int kind) { DEBUG_printf("load_global(%s)\n", qstr_str(qst)); if (emit->do_viper_types) { // check for builtin casting operators - if (qst == MP_QSTR_int) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_INT); - return; - } else if (qst == MP_QSTR_uint) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_UINT); - return; - } else if (qst == MP_QSTR_ptr) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_PTR); - return; - } else if (qst == MP_QSTR_ptr8) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_PTR8); - return; - } else if (qst == MP_QSTR_ptr16) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_PTR16); - return; - } else if (qst == MP_QSTR_ptr32) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_PTR32); + int native_type = mp_native_type_from_qstr(qst); + if (native_type >= MP_NATIVE_TYPE_INT) { + emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, native_type); return; } } @@ -1227,19 +1526,11 @@ STATIC void emit_native_load_subscr(emit_t *emit) { STATIC void emit_native_store_fast(emit_t *emit, qstr qst, mp_uint_t local_num) { vtype_kind_t vtype; - if (local_num == 0) { - emit_pre_pop_reg(emit, &vtype, REG_LOCAL_1); - } else if (local_num == 1) { - emit_pre_pop_reg(emit, &vtype, REG_LOCAL_2); - } else if (local_num == 2) { - emit_pre_pop_reg(emit, &vtype, REG_LOCAL_3); + if (local_num < REG_LOCAL_NUM && CAN_USE_REGS_FOR_LOCALS(emit)) { + emit_pre_pop_reg(emit, &vtype, reg_local_table[local_num]); } else { emit_pre_pop_reg(emit, &vtype, REG_TEMP0); - if (emit->do_viper_types) { - ASM_MOV_LOCAL_REG(emit->as, local_num - REG_LOCAL_NUM, REG_TEMP0); - } else { - ASM_MOV_LOCAL_REG(emit->as, STATE_START + emit->n_state - 1 - local_num, REG_TEMP0); - } + emit_native_mov_state_reg(emit, LOCAL_IDX_LOCAL_VAR(emit, local_num), REG_TEMP0); } emit_post(emit); @@ -1387,10 +1678,6 @@ STATIC void emit_native_store_subscr(emit_t *emit) { } #endif ASM_MOV_REG_IMM(emit->as, reg_index, index_value << 1); - #if N_ARM - asm_arm_strh_reg_reg_reg(emit->as, reg_value, reg_base, reg_index); - return; - #endif ASM_ADD_REG_REG(emit->as, reg_index, reg_base); // add 2*index to base reg_base = reg_index; } @@ -1407,11 +1694,12 @@ STATIC void emit_native_store_subscr(emit_t *emit) { break; } #endif - ASM_MOV_REG_IMM(emit->as, reg_index, index_value << 2); #if N_ARM + ASM_MOV_REG_IMM(emit->as, reg_index, index_value); asm_arm_str_reg_reg_reg(emit->as, reg_value, reg_base, reg_index); return; #endif + ASM_MOV_REG_IMM(emit->as, reg_index, index_value << 2); ASM_ADD_REG_REG(emit->as, reg_index, reg_base); // add 4*index to base reg_base = reg_index; } @@ -1587,7 +1875,7 @@ STATIC void emit_native_jump(emit_t *emit, mp_uint_t label) { emit_post(emit); } -STATIC void emit_native_jump_helper(emit_t *emit, bool pop) { +STATIC void emit_native_jump_helper(emit_t *emit, bool cond, mp_uint_t label, bool pop) { vtype_kind_t vtype = peek_vtype(emit, 0); if (vtype == VTYPE_PYOBJ) { emit_pre_pop_reg(emit, &vtype, REG_ARG_1); @@ -1612,34 +1900,69 @@ STATIC void emit_native_jump_helper(emit_t *emit, bool pop) { } // need to commit stack because we may jump elsewhere need_stack_settled(emit); + // Emit the jump + if (cond) { + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label, vtype == VTYPE_PYOBJ); + } else { + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label, vtype == VTYPE_PYOBJ); + } + if (!pop) { + adjust_stack(emit, -1); + } + emit_post(emit); } STATIC void emit_native_pop_jump_if(emit_t *emit, bool cond, mp_uint_t label) { DEBUG_printf("pop_jump_if(cond=%u, label=" UINT_FMT ")\n", cond, label); - emit_native_jump_helper(emit, true); - if (cond) { - ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label); - } else { - ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label); - } - emit_post(emit); + emit_native_jump_helper(emit, cond, label, true); } STATIC void emit_native_jump_if_or_pop(emit_t *emit, bool cond, mp_uint_t label) { DEBUG_printf("jump_if_or_pop(cond=%u, label=" UINT_FMT ")\n", cond, label); - emit_native_jump_helper(emit, false); - if (cond) { - ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label); - } else { - ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label); - } - adjust_stack(emit, -1); - emit_post(emit); + emit_native_jump_helper(emit, cond, label, false); } STATIC void emit_native_unwind_jump(emit_t *emit, mp_uint_t label, mp_uint_t except_depth) { - (void)except_depth; - emit_native_jump(emit, label & ~MP_EMIT_BREAK_FROM_FOR); // TODO properly + if (except_depth > 0) { + exc_stack_entry_t *first_finally = NULL; + exc_stack_entry_t *prev_finally = NULL; + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; + for (; except_depth > 0; --except_depth, --e) { + if (e->is_finally && e->is_active) { + // Found an active finally handler + if (first_finally == NULL) { + first_finally = e; + } + if (prev_finally != NULL) { + // Mark prev finally as needed to unwind a jump + prev_finally->unwind_label = e->label; + } + prev_finally = e; + } + } + if (prev_finally == NULL) { + // No finally, handle the jump ourselves + // First, restore the exception handler address for the jump + if (e < emit->exc_stack) { + ASM_XOR_REG_REG(emit->as, REG_RET, REG_RET); + } else { + ASM_MOV_REG_PCREL(emit->as, REG_RET, e->label); + } + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_RET); + } else { + // Last finally should do our jump for us + // Mark finally as needing to decide the type of jump + prev_finally->unwind_label = UNWIND_LABEL_DO_FINAL_UNWIND; + ASM_MOV_REG_PCREL(emit->as, REG_RET, label & ~MP_EMIT_BREAK_FROM_FOR); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_UNWIND(emit), REG_RET); + // Cancel any active exception (see also emit_native_pop_except) + emit_native_mov_reg_const(emit, REG_RET, MP_F_CONST_NONE_OBJ); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_RET); + // Jump to the innermost active finally + label = first_finally->label; + } + } + emit_native_jump(emit, label & ~MP_EMIT_BREAK_FROM_FOR); } STATIC void emit_native_setup_with(emit_t *emit, mp_uint_t label) { @@ -1675,13 +1998,10 @@ STATIC void emit_native_setup_with(emit_t *emit, mp_uint_t label) { // need to commit stack because we may jump elsewhere need_stack_settled(emit); - emit_get_stack_pointer_to_reg_for_push(emit, REG_ARG_1, sizeof(nlr_buf_t) / sizeof(mp_uint_t)); // arg1 = pointer to nlr buf - emit_call(emit, MP_F_NLR_PUSH); - ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label); + emit_native_push_exc_stack(emit, label, true); - emit_access_stack(emit, sizeof(nlr_buf_t) / sizeof(mp_uint_t) + 1, &vtype, REG_RET); // access return value of __enter__ - emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); // push return value of __enter__ - // stack: (..., __exit__, self, as_value, nlr_buf, as_value) + emit_native_dup_top(emit); + // stack: (..., __exit__, self, as_value, as_value) } STATIC void emit_native_setup_block(emit_t *emit, mp_uint_t label, int kind) { @@ -1690,82 +2010,78 @@ STATIC void emit_native_setup_block(emit_t *emit, mp_uint_t label, int kind) { } else { // Set up except and finally emit_native_pre(emit); - // need to commit stack because we may jump elsewhere need_stack_settled(emit); - emit_get_stack_pointer_to_reg_for_push(emit, REG_ARG_1, sizeof(nlr_buf_t) / sizeof(mp_uint_t)); // arg1 = pointer to nlr buf - emit_call(emit, MP_F_NLR_PUSH); - ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label); + emit_native_push_exc_stack(emit, label, kind == MP_EMIT_SETUP_BLOCK_FINALLY); emit_post(emit); } } STATIC void emit_native_with_cleanup(emit_t *emit, mp_uint_t label) { - // note: label+1 is available as an auxiliary label + // Note: 3 labels are reserved for this function, starting at *emit->label_slot - // stack: (..., __exit__, self, as_value, nlr_buf) + // stack: (..., __exit__, self, as_value) emit_native_pre(emit); - emit_call(emit, MP_F_NLR_POP); - adjust_stack(emit, -(mp_int_t)(sizeof(nlr_buf_t) / sizeof(mp_uint_t)) - 1); + emit_native_leave_exc_stack(emit, false); + adjust_stack(emit, -1); // stack: (..., __exit__, self) + // Label for case where __exit__ is called from an unwind jump + emit_native_label_assign(emit, *emit->label_slot + 2); + // call __exit__ - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_3, 5); emit_call_with_2_imm_args(emit, MP_F_CALL_METHOD_N_KW, 3, REG_ARG_1, 0, REG_ARG_2); - // jump to after with cleanup nlr_catch block - adjust_stack(emit, 1); // dummy nlr_buf.prev - emit_native_load_const_tok(emit, MP_TOKEN_KW_NONE); // nlr_buf.ret_val = no exception - emit_native_jump(emit, label + 1); + // Replace exc with None and finish + emit_native_jump(emit, *emit->label_slot); // nlr_catch - emit_native_label_assign(emit, label); + // Don't use emit_native_label_assign because this isn't a real finally label + mp_asm_base_label_assign(&emit->as->base, label); - // adjust stack counter for: __exit__, self, as_value - adjust_stack(emit, 3); - // stack: (..., __exit__, self, as_value, nlr_buf.prev, nlr_buf.ret_val) + // Leave with's exception handler + emit_native_leave_exc_stack(emit, true); - vtype_kind_t vtype; - emit_pre_pop_reg(emit, &vtype, REG_ARG_1); // get the thrown value (exc) - adjust_stack(emit, -2); // discard nlr_buf.prev and as_value + // Adjust stack counter for: __exit__, self (implicitly discard as_value which is above self) + emit_native_adjust_stack_size(emit, 2); // stack: (..., __exit__, self) - // REG_ARG_1=exc - emit_pre_pop_reg(emit, &vtype, REG_ARG_2); // self - emit_pre_pop_reg(emit, &vtype, REG_ARG_3); // __exit__ - adjust_stack(emit, 1); // dummy nlr_buf.prev - emit_post_push_reg(emit, vtype, REG_ARG_1); // push exc to save it for later - emit_post_push_reg(emit, vtype, REG_ARG_3); // __exit__ - emit_post_push_reg(emit, vtype, REG_ARG_2); // self - // stack: (..., exc, __exit__, self) - // REG_ARG_1=exc + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); // get exc + + // Check if exc is None and jump to non-exc handler if it is + emit_native_mov_reg_const(emit, REG_ARG_2, MP_F_CONST_NONE_OBJ); + ASM_JUMP_IF_REG_EQ(emit->as, REG_ARG_1, REG_ARG_2, *emit->label_slot + 2); ASM_LOAD_REG_REG_OFFSET(emit->as, REG_ARG_2, REG_ARG_1, 0); // get type(exc) emit_post_push_reg(emit, VTYPE_PYOBJ, REG_ARG_2); // push type(exc) emit_post_push_reg(emit, VTYPE_PYOBJ, REG_ARG_1); // push exc value - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); // traceback info - // stack: (..., exc, __exit__, self, type(exc), exc, traceback) + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); // traceback info + // Stack: (..., __exit__, self, type(exc), exc, traceback) // call __exit__ method emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_3, 5); emit_call_with_2_imm_args(emit, MP_F_CALL_METHOD_N_KW, 3, REG_ARG_1, 0, REG_ARG_2); - // stack: (..., exc) + // Stack: (...) - // if REG_RET is true then we need to replace top-of-stack with None (swallow exception) + // If REG_RET is true then we need to replace exception with None (swallow exception) if (REG_ARG_1 != REG_RET) { ASM_MOV_REG_REG(emit->as, REG_ARG_1, REG_RET); } emit_call(emit, MP_F_OBJ_IS_TRUE); - ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label + 1); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, *emit->label_slot + 1, true); - // replace exc with None - emit_pre_pop_discard(emit); - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); + // Replace exception with None + emit_native_label_assign(emit, *emit->label_slot); + emit_native_mov_reg_const(emit, REG_TEMP0, MP_F_CONST_NONE_OBJ); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); // end of with cleanup nlr_catch block - emit_native_label_assign(emit, label + 1); + emit_native_label_assign(emit, *emit->label_slot + 1); + + // Exception is in nlr_buf.ret_val slot } STATIC void emit_native_end_finally(emit_t *emit) { @@ -1774,10 +2090,23 @@ STATIC void emit_native_end_finally(emit_t *emit) { // if exc == None: pass // else: raise exc // the check if exc is None is done in the MP_F_NATIVE_RAISE stub - vtype_kind_t vtype; - emit_pre_pop_reg(emit, &vtype, REG_ARG_1); // get nlr_buf.ret_val - emit_pre_pop_discard(emit); // discard nlr_buf.prev + emit_native_pre(emit); + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); emit_call(emit, MP_F_NATIVE_RAISE); + + // Get state for this finally and see if we need to unwind + exc_stack_entry_t *e = emit_native_pop_exc_stack(emit); + if (e->unwind_label != UNWIND_LABEL_UNUSED) { + ASM_MOV_REG_LOCAL(emit->as, REG_RET, LOCAL_IDX_EXC_HANDLER_UNWIND(emit)); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, *emit->label_slot, false); + if (e->unwind_label == UNWIND_LABEL_DO_FINAL_UNWIND) { + ASM_JUMP_REG(emit->as, REG_RET); + } else { + emit_native_jump(emit, e->unwind_label); + } + emit_native_label_assign(emit, *emit->label_slot); + } + emit_post(emit); } @@ -1804,8 +2133,13 @@ STATIC void emit_native_for_iter(emit_t *emit, mp_uint_t label) { emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_1, MP_OBJ_ITER_BUF_NSLOTS); adjust_stack(emit, MP_OBJ_ITER_BUF_NSLOTS); emit_call(emit, MP_F_NATIVE_ITERNEXT); + #ifdef NDEBUG + MP_STATIC_ASSERT(MP_OBJ_STOP_ITERATION == 0); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label, false); + #else ASM_MOV_REG_IMM(emit->as, REG_TEMP1, (mp_uint_t)MP_OBJ_STOP_ITERATION); ASM_JUMP_IF_REG_EQ(emit->as, REG_RET, REG_TEMP1, label); + #endif emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } @@ -1818,13 +2152,16 @@ STATIC void emit_native_for_iter_end(emit_t *emit) { STATIC void emit_native_pop_block(emit_t *emit) { emit_native_pre(emit); - emit_call(emit, MP_F_NLR_POP); - adjust_stack(emit, -(mp_int_t)(sizeof(nlr_buf_t) / sizeof(mp_uint_t)) + 1); + if (!emit->exc_stack[emit->exc_stack_size - 1].is_finally) { + emit_native_leave_exc_stack(emit, false); + } emit_post(emit); } STATIC void emit_native_pop_except(emit_t *emit) { - (void)emit; + // Cancel any active exception so subsequent handlers don't see it + emit_native_mov_reg_const(emit, REG_TEMP0, MP_F_CONST_NONE_OBJ); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); } STATIC void emit_native_unary_op(emit_t *emit, mp_unary_op_t op) { @@ -2061,8 +2398,7 @@ STATIC void emit_native_build_slice(emit_t *emit, mp_uint_t n_args) { emit_pre_pop_reg_reg(emit, &vtype_stop, REG_ARG_2, &vtype_start, REG_ARG_1); // arg1 = start, arg2 = stop assert(vtype_start == VTYPE_PYOBJ); assert(vtype_stop == VTYPE_PYOBJ); - emit_call_with_imm_arg(emit, MP_F_NEW_SLICE, (mp_uint_t)mp_const_none, REG_ARG_3); // arg3 = step - emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); + emit_native_mov_reg_const(emit, REG_ARG_3, MP_F_CONST_NONE_OBJ); // arg3 = step } else { assert(n_args == 3); vtype_kind_t vtype_start, vtype_stop, vtype_step; @@ -2070,9 +2406,9 @@ STATIC void emit_native_build_slice(emit_t *emit, mp_uint_t n_args) { assert(vtype_start == VTYPE_PYOBJ); assert(vtype_stop == VTYPE_PYOBJ); assert(vtype_step == VTYPE_PYOBJ); - emit_call(emit, MP_F_NEW_SLICE); - emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } + emit_call(emit, MP_F_NEW_SLICE); + emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } #endif @@ -2127,14 +2463,18 @@ STATIC void emit_native_make_function(emit_t *emit, scope_t *scope, mp_uint_t n_ // call runtime, with type info for args, or don't support dict/default params, or only support Python objects for them emit_native_pre(emit); if (n_pos_defaults == 0 && n_kw_defaults == 0) { - emit_call_with_3_imm_args_and_first_aligned(emit, MP_F_MAKE_FUNCTION_FROM_RAW_CODE, (mp_uint_t)scope->raw_code, REG_ARG_1, (mp_uint_t)MP_OBJ_NULL, REG_ARG_2, (mp_uint_t)MP_OBJ_NULL, REG_ARG_3); + need_reg_all(emit); + ASM_MOV_REG_IMM(emit->as, REG_ARG_2, (mp_uint_t)MP_OBJ_NULL); + ASM_MOV_REG_IMM(emit->as, REG_ARG_3, (mp_uint_t)MP_OBJ_NULL); } else { vtype_kind_t vtype_def_tuple, vtype_def_dict; emit_pre_pop_reg_reg(emit, &vtype_def_dict, REG_ARG_3, &vtype_def_tuple, REG_ARG_2); assert(vtype_def_tuple == VTYPE_PYOBJ); assert(vtype_def_dict == VTYPE_PYOBJ); - emit_call_with_imm_arg_aligned(emit, MP_F_MAKE_FUNCTION_FROM_RAW_CODE, (mp_uint_t)scope->raw_code, REG_ARG_1); + need_reg_all(emit); } + emit_load_reg_with_raw_code(emit, REG_ARG_1, scope->raw_code); + ASM_CALL_IND(emit->as, MP_F_MAKE_FUNCTION_FROM_RAW_CODE); emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } @@ -2147,8 +2487,8 @@ STATIC void emit_native_make_closure(emit_t *emit, scope_t *scope, mp_uint_t n_c emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_3, n_closed_over + 2); ASM_MOV_REG_IMM(emit->as, REG_ARG_2, 0x100 | n_closed_over); } - ASM_MOV_REG_ALIGNED_IMM(emit->as, REG_ARG_1, (mp_uint_t)scope->raw_code); - ASM_CALL_IND(emit->as, mp_fun_table[MP_F_MAKE_CLOSURE_FROM_RAW_CODE], MP_F_MAKE_CLOSURE_FROM_RAW_CODE); + emit_load_reg_with_raw_code(emit, REG_ARG_1, scope->raw_code); + ASM_CALL_IND(emit->as, MP_F_MAKE_CLOSURE_FROM_RAW_CODE); emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } @@ -2222,30 +2562,54 @@ STATIC void emit_native_call_method(emit_t *emit, mp_uint_t n_positional, mp_uin STATIC void emit_native_return_value(emit_t *emit) { DEBUG_printf("return_value\n"); + + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + // Save pointer to current stack position for caller to access return value + emit_get_stack_pointer_to_reg_for_pop(emit, REG_TEMP0, 1); + emit_native_mov_state_reg(emit, offsetof(mp_code_state_t, sp) / sizeof(uintptr_t), REG_TEMP0); + + // Put return type in return value slot + ASM_MOV_REG_IMM(emit->as, REG_TEMP0, MP_VM_RETURN_NORMAL); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_RET_VAL(emit), REG_TEMP0); + + // Do the unwinding jump to get to the return handler + emit_native_unwind_jump(emit, emit->exit_label, emit->exc_stack_size); + emit->last_emit_was_return_value = true; + return; + } + if (emit->do_viper_types) { + vtype_kind_t return_vtype = emit->scope->scope_flags >> MP_SCOPE_FLAG_VIPERRET_POS; if (peek_vtype(emit, 0) == VTYPE_PTR_NONE) { emit_pre_pop_discard(emit); - if (emit->return_vtype == VTYPE_PYOBJ) { - ASM_MOV_REG_IMM(emit->as, REG_RET, (mp_uint_t)mp_const_none); + if (return_vtype == VTYPE_PYOBJ) { + emit_native_mov_reg_const(emit, REG_RET, MP_F_CONST_NONE_OBJ); } else { - ASM_MOV_REG_IMM(emit->as, REG_RET, 0); + ASM_MOV_REG_IMM(emit->as, REG_ARG_1, 0); } } else { vtype_kind_t vtype; - emit_pre_pop_reg(emit, &vtype, REG_RET); - if (vtype != emit->return_vtype) { + emit_pre_pop_reg(emit, &vtype, return_vtype == VTYPE_PYOBJ ? REG_RET : REG_ARG_1); + if (vtype != return_vtype) { EMIT_NATIVE_VIPER_TYPE_ERROR(emit, translate("return expected '%q' but got '%q'"), - vtype_to_qstr(emit->return_vtype), vtype_to_qstr(vtype)); + vtype_to_qstr(return_vtype), vtype_to_qstr(vtype)); } } + if (return_vtype != VTYPE_PYOBJ) { + emit_call_with_imm_arg(emit, MP_F_CONVERT_NATIVE_TO_OBJ, return_vtype, REG_ARG_2); + } } else { vtype_kind_t vtype; emit_pre_pop_reg(emit, &vtype, REG_RET); assert(vtype == VTYPE_PYOBJ); } + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + // Save return value for the global exception handler to use + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_RET_VAL(emit), REG_RET); + } + emit_native_unwind_jump(emit, emit->exit_label, emit->exc_stack_size); emit->last_emit_was_return_value = true; - ASM_EXIT(emit->as); } STATIC void emit_native_raise_varargs(emit_t *emit, mp_uint_t n_args) { @@ -2260,29 +2624,101 @@ STATIC void emit_native_raise_varargs(emit_t *emit, mp_uint_t n_args) { } STATIC void emit_native_yield(emit_t *emit, int kind) { - // not supported (for now) - (void)emit; - (void)kind; - mp_raise_NotImplementedError(translate("native yield")); + // Note: 1 (yield) or 3 (yield from) labels are reserved for this function, starting at *emit->label_slot + + if (emit->do_viper_types) { + mp_raise_NotImplementedError(translate("native yield")); + } + emit->scope->scope_flags |= MP_SCOPE_FLAG_GENERATOR; + + need_stack_settled(emit); + + if (kind == MP_EMIT_YIELD_FROM) { + + // Top of yield-from loop, conceptually implementing: + // for item in generator: + // yield item + + // Jump to start of loop + emit_native_jump(emit, *emit->label_slot + 2); + + // Label for top of loop + emit_native_label_assign(emit, *emit->label_slot + 1); + } + + // Save pointer to current stack position for caller to access yielded value + emit_get_stack_pointer_to_reg_for_pop(emit, REG_TEMP0, 1); + emit_native_mov_state_reg(emit, offsetof(mp_code_state_t, sp) / sizeof(uintptr_t), REG_TEMP0); + + // Put return type in return value slot + ASM_MOV_REG_IMM(emit->as, REG_TEMP0, MP_VM_RETURN_YIELD); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_RET_VAL(emit), REG_TEMP0); + + // Save re-entry PC + ASM_MOV_REG_PCREL(emit->as, REG_TEMP0, *emit->label_slot); + emit_native_mov_state_reg(emit, LOCAL_IDX_GEN_PC(emit), REG_TEMP0); + + // Jump to exit handler + ASM_JUMP(emit->as, emit->exit_label); + + // Label re-entry point + mp_asm_base_label_assign(&emit->as->base, *emit->label_slot); + + // Re-open any active exception handler + if (emit->exc_stack_size > 0) { + // Find innermost active exception handler, to restore as current handler + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; + for (; e >= emit->exc_stack; --e) { + if (e->is_active) { + // Found active handler, get its PC + ASM_MOV_REG_PCREL(emit->as, REG_RET, e->label); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_RET); + } + } + } + + emit_native_adjust_stack_size(emit, 1); // send_value + + if (kind == MP_EMIT_YIELD_VALUE) { + // Check LOCAL_IDX_EXC_VAL for any injected value + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); + emit_call(emit, MP_F_NATIVE_RAISE); + } else { + // Label loop entry + emit_native_label_assign(emit, *emit->label_slot + 2); + + // Get the next item from the delegate generator + vtype_kind_t vtype; + emit_pre_pop_reg(emit, &vtype, REG_ARG_2); // send_value + emit_access_stack(emit, 1, &vtype, REG_ARG_1); // generator + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_3, LOCAL_IDX_EXC_VAL(emit)); // throw_value + emit_post_push_reg(emit, VTYPE_PYOBJ, REG_ARG_3); + emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_3, 1); // ret_value + emit_call(emit, MP_F_NATIVE_YIELD_FROM); + + // If returned non-zero then generator continues + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, *emit->label_slot + 1, true); + + // Pop exhausted gen, replace with ret_value + emit_native_adjust_stack_size(emit, 1); // ret_value + emit_fold_stack_top(emit, REG_ARG_1); + } } STATIC void emit_native_start_except_handler(emit_t *emit) { - // This instruction follows an nlr_pop, so the stack counter is back to zero, when really - // it should be up by a whole nlr_buf_t. We then want to pop the nlr_buf_t here, but save - // the first 2 elements, so we can get the thrown value. - adjust_stack(emit, 1); - vtype_kind_t vtype_nlr; - emit_pre_pop_reg(emit, &vtype_nlr, REG_ARG_1); // get the thrown value - emit_pre_pop_discard(emit); // discard the linked-list pointer in the nlr_buf - emit_post_push_reg_reg_reg(emit, VTYPE_PYOBJ, REG_ARG_1, VTYPE_PYOBJ, REG_ARG_1, VTYPE_PYOBJ, REG_ARG_1); // push the 3 exception items + // Protected block has finished so leave the current exception handler + emit_native_leave_exc_stack(emit, true); + + // Get and push nlr_buf.ret_val + ASM_MOV_REG_LOCAL(emit->as, REG_TEMP0, LOCAL_IDX_EXC_VAL(emit)); + emit_post_push_reg(emit, VTYPE_PYOBJ, REG_TEMP0); } STATIC void emit_native_end_except_handler(emit_t *emit) { - adjust_stack(emit, -1); + adjust_stack(emit, -1); // pop the exception (end_finally didn't use it) } const emit_method_table_t EXPORT_FUN(method_table) = { - emit_native_set_native_type, emit_native_start_pass, emit_native_end_pass, emit_native_last_emit_was_return_value, diff --git a/py/emitnthumb.c b/py/emitnthumb.c index 2b68ca3a13..1c33e7a68b 100644 --- a/py/emitnthumb.c +++ b/py/emitnthumb.c @@ -8,6 +8,11 @@ #define GENERIC_ASM_API (1) #include "py/asmthumb.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (3) // r4 +#define NLR_BUF_IDX_LOCAL_2 (4) // r5 +#define NLR_BUF_IDX_LOCAL_3 (5) // r6 + #define N_THUMB (1) #define EXPORT_FUN(name) emit_native_thumb_##name #include "py/emitnative.c" diff --git a/py/emitnx64.c b/py/emitnx64.c index b9800f636e..4abb3ecad3 100644 --- a/py/emitnx64.c +++ b/py/emitnx64.c @@ -8,6 +8,11 @@ #define GENERIC_ASM_API (1) #include "py/asmx64.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (5) // rbx +#define NLR_BUF_IDX_LOCAL_2 (6) // r12 +#define NLR_BUF_IDX_LOCAL_3 (7) // r13 + #define N_X64 (1) #define EXPORT_FUN(name) emit_native_x64_##name #include "py/emitnative.c" diff --git a/py/emitnx86.c b/py/emitnx86.c index 5d2bbb267a..7c96c3b82b 100644 --- a/py/emitnx86.c +++ b/py/emitnx86.c @@ -9,10 +9,16 @@ #define GENERIC_ASM_API (1) #include "py/asmx86.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (5) // ebx +#define NLR_BUF_IDX_LOCAL_2 (7) // esi +#define NLR_BUF_IDX_LOCAL_3 (6) // edi + // x86 needs a table to know how many args a given function has STATIC byte mp_f_n_args[MP_F_NUMBER_OF] = { [MP_F_CONVERT_OBJ_TO_NATIVE] = 2, [MP_F_CONVERT_NATIVE_TO_OBJ] = 2, + [MP_F_NATIVE_SWAP_GLOBALS] = 1, [MP_F_LOAD_NAME] = 1, [MP_F_LOAD_GLOBAL] = 1, [MP_F_LOAD_BUILD_CLASS] = 0, @@ -56,9 +62,11 @@ STATIC byte mp_f_n_args[MP_F_NUMBER_OF] = { [MP_F_DELETE_GLOBAL] = 1, [MP_F_NEW_CELL] = 1, [MP_F_MAKE_CLOSURE_FROM_RAW_CODE] = 3, - [MP_F_SETUP_CODE_STATE] = 5, + [MP_F_ARG_CHECK_NUM_SIG] = 3, + [MP_F_SETUP_CODE_STATE] = 4, [MP_F_SMALL_INT_FLOOR_DIVIDE] = 2, [MP_F_SMALL_INT_MODULO] = 2, + [MP_F_NATIVE_YIELD_FROM] = 3, }; #define N_X86 (1) diff --git a/py/emitnxtensa.c b/py/emitnxtensa.c index 1a423e21eb..34089e90dc 100644 --- a/py/emitnxtensa.c +++ b/py/emitnxtensa.c @@ -8,6 +8,11 @@ #define GENERIC_ASM_API (1) #include "py/asmxtensa.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (8) // a12 +#define NLR_BUF_IDX_LOCAL_2 (9) // a13 +#define NLR_BUF_IDX_LOCAL_3 (10) // a14 + #define N_XTENSA (1) #define EXPORT_FUN(name) emit_native_xtensa_##name #include "py/emitnative.c" diff --git a/py/gc.c b/py/gc.c index cb7e454193..c29624c3af 100644 --- a/py/gc.c +++ b/py/gc.c @@ -480,7 +480,8 @@ bool gc_alloc_possible(void) { // We place long lived objects at the end of the heap rather than the start. This reduces // fragmentation by localizing the heap churn to one portion of memory (the start of the heap.) -void *gc_alloc(size_t n_bytes, bool has_finaliser, bool long_lived) { +void *gc_alloc(size_t n_bytes, unsigned int alloc_flags, bool long_lived) { + bool has_finaliser = alloc_flags & GC_ALLOC_FLAG_HAS_FINALISER; size_t n_blocks = ((n_bytes + BYTES_PER_BLOCK - 1) & (~(BYTES_PER_BLOCK - 1))) / BYTES_PER_BLOCK; DEBUG_printf("gc_alloc(" UINT_FMT " bytes -> " UINT_FMT " blocks)\n", n_bytes, n_blocks); @@ -1153,7 +1154,8 @@ void gc_dump_alloc_table(void) { GC_EXIT(); } -#if DEBUG_PRINT +#if 0 +// For testing the GC functions void gc_test(void) { mp_uint_t len = 500; mp_uint_t *heap = malloc(len); diff --git a/py/gc.h b/py/gc.h index ddbaeb40a6..0cc432b94e 100644 --- a/py/gc.h +++ b/py/gc.h @@ -60,11 +60,15 @@ void gc_collect_end(void); // Is the gc heap available? bool gc_alloc_possible(void); -void *gc_alloc(size_t n_bytes, bool has_finaliser, bool long_lived); // Use this function to sweep the whole heap and run all finalisers void gc_sweep_all(void); +enum { + GC_ALLOC_FLAG_HAS_FINALISER = 1, +}; + +void *gc_alloc(size_t n_bytes, unsigned int alloc_flags, bool long_lived); void gc_free(void *ptr); // does not call finaliser size_t gc_nbytes(const void *ptr); bool gc_has_finaliser(const void *ptr); diff --git a/py/makeqstrdata.py b/py/makeqstrdata.py index 0ad749005c..6a6125fe20 100644 --- a/py/makeqstrdata.py +++ b/py/makeqstrdata.py @@ -12,7 +12,6 @@ from __future__ import print_function import re import sys -from math import log import collections import gettext import os.path @@ -167,7 +166,7 @@ def compute_huffman_coding(translations, compression_filename): sum_len = 0 while True: # Until the dictionary is filled to capacity, use a heuristic to find - # the best "word" (2- to 9-gram) to add to it. + # the best "word" (3- to 9-gram) to add to it. # # The TextSplitter allows us to avoid considering parts of the text # that are already covered by a previously chosen word, for example @@ -179,32 +178,25 @@ def compute_huffman_coding(translations, compression_filename): for t in texts: for (found, word) in extractor.iter_words(t): if not found: - for substr in iter_substrings(word, minlen=2, maxlen=9): + for substr in iter_substrings(word, minlen=3, maxlen=9): counter[substr] += 1 # Score the candidates we found. This is an empirical formula only, # chosen for its effectiveness. scores = sorted( - ((s, (len(s) - 1) ** log(max(occ - 2, 1)), occ) for (s, occ) in counter.items()), + ((s, (len(s) - 1) ** (occ + 4)) for (s, occ) in counter.items() if occ > 4), key=lambda x: x[1], reverse=True, ) - # Do we have a "word" that occurred 5 times and got a score of at least - # 5? Horray. Pick the one with the highest score. - word = None - for (s, score, occ) in scores: - if occ < 5: - continue - if score < 5: - break - word = s + # Pick the one with the highest score. + if not scores: break + word = scores[0][0] + # If we can successfully add it to the dictionary, do so. Otherwise, # we've filled the dictionary to capacity and are done. - if not word: - break if sum_len + len(word) - 2 > max_words_len: break if len(words) == max_words: @@ -456,27 +448,24 @@ def parse_input_headers(infiles): return qcfgs, qstrs, i18ns +def escape_bytes(qstr): + if all(32 <= ord(c) <= 126 and c != "\\" and c != '"' for c in qstr): + # qstr is all printable ASCII so render it as-is (for easier debugging) + return qstr + else: + # qstr contains non-printable codes so render entire thing as hex pairs + qbytes = bytes_cons(qstr, "utf8") + return "".join(("\\x%02x" % b) for b in qbytes) def make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr): qbytes = bytes_cons(qstr, "utf8") qlen = len(qbytes) qhash = compute_hash(qbytes, cfg_bytes_hash) - if all(32 <= ord(c) <= 126 and c != "\\" and c != '"' for c in qstr): - # qstr is all printable ASCII so render it as-is (for easier debugging) - qdata = qstr - else: - # qstr contains non-printable codes so render entire thing as hex pairs - qdata = "".join(("\\x%02x" % b) for b in qbytes) if qlen >= (1 << (8 * cfg_bytes_len)): print("qstr is too long:", qstr) assert False - qlen_str = ("\\x%02x" * cfg_bytes_len) % tuple( - ((qlen >> (8 * i)) & 0xFF) for i in range(cfg_bytes_len) - ) - qhash_str = ("\\x%02x" * cfg_bytes_hash) % tuple( - ((qhash >> (8 * i)) & 0xFF) for i in range(cfg_bytes_hash) - ) - return '(const byte*)"%s%s" "%s"' % (qhash_str, qlen_str, qdata) + qdata = escape_bytes(qstr) + return '%d, %d, "%s"' % (qhash, qlen, qdata) def print_qstr_data(encoding_table, qcfgs, qstrs, i18ns): @@ -489,10 +478,7 @@ def print_qstr_data(encoding_table, qcfgs, qstrs, i18ns): print("") # add NULL qstr with no hash or data - print( - 'QDEF(MP_QSTR_NULL, (const byte*)"%s%s" "")' - % ("\\x00" * cfg_bytes_hash, "\\x00" * cfg_bytes_len) - ) + print('QDEF(MP_QSTR_NULL, 0, 0, "")') total_qstr_size = 0 total_qstr_compressed_size = 0 diff --git a/py/malloc.c b/py/malloc.c index e06d20e956..5c09a2d283 100644 --- a/py/malloc.c +++ b/py/malloc.c @@ -62,6 +62,13 @@ #define realloc(ptr, n) gc_realloc(ptr, n, true) #define realloc_ext(ptr, n, mv) gc_realloc(ptr, n, mv) #else + +// GC is disabled. Use system malloc/realloc/free. + +#if MICROPY_ENABLE_FINALISER +#error MICROPY_ENABLE_FINALISER requires MICROPY_ENABLE_GC +#endif + #define malloc_ll(b, ll) malloc(b) #define malloc_with_finaliser(b) malloc((b)) @@ -75,6 +82,7 @@ STATIC void *realloc_ext(void *ptr, size_t n_bytes, bool allow_move) { return NULL; } } + #endif // MICROPY_ENABLE_GC void *m_malloc(size_t num_bytes, bool long_lived) { diff --git a/py/map.c b/py/map.c index a37a3c984d..06695c8de8 100644 --- a/py/map.c +++ b/py/map.c @@ -425,13 +425,13 @@ void mp_set_clear(mp_set_t *set) { #if defined(DEBUG_PRINT) && DEBUG_PRINT void mp_map_dump(mp_map_t *map) { for (size_t i = 0; i < map->alloc; i++) { - if (map->table[i].key != NULL) { + if (map->table[i].key != MP_OBJ_NULL) { mp_obj_print(map->table[i].key, PRINT_REPR); } else { - printf("(nil)"); + DEBUG_printf("(nil)"); } - printf(": %p\n", map->table[i].value); + DEBUG_printf(": %p\n", map->table[i].value); } - printf("---\n"); + DEBUG_printf("---\n"); } #endif diff --git a/py/misc.h b/py/misc.h index cb7192a56f..acb0d50cec 100644 --- a/py/misc.h +++ b/py/misc.h @@ -55,6 +55,13 @@ typedef unsigned int uint; // Static assertion macro #define MP_STATIC_ASSERT(cond) ((void)sizeof(char[1 - 2 * !(cond)])) +// Explicit fallthrough delcarations for case statements +#ifdef __GNUC__ +#define FALLTHROUGH __attribute__((fallthrough)) +#else +#define FALLTHROUGH ((void)0) /* FALLTHROUGH */ +#endif + /** memory allocation ******************************************/ // TODO make a lazy m_renew that can increase by a smaller amount than requested (but by at least 1 more element) diff --git a/py/mkrules.mk b/py/mkrules.mk index 549b0e5e42..2721d293e0 100644 --- a/py/mkrules.mk +++ b/py/mkrules.mk @@ -107,7 +107,7 @@ endif ifneq ($(FROZEN_MPY_DIRS),) # to build the MicroPython cross compiler # Currently not used, because the wrong mpy-cross may be left over from a previous build. Build by hand to make sure. -$(MPY_CROSS): $(TOP)/py/*.[ch] $(TOP)/mpy-cross/*.[ch] $(TOP)/ports/windows/fmode.c +$(MPY_CROSS): $(TOP)/py/*.[ch] $(TOP)/mpy-cross/*.[ch] $(TOP)/mpy-cross/fmode.c $(Q)$(MAKE) -C $(TOP)/mpy-cross # Copy all the modules and single python files to freeze to a common area, omitting top-level dirs (the repo names). diff --git a/py/modbuiltins.c b/py/modbuiltins.c index ccf29cfe1c..49d88f728e 100644 --- a/py/modbuiltins.c +++ b/py/modbuiltins.c @@ -220,7 +220,12 @@ STATIC mp_obj_t mp_builtin_hash(mp_obj_t o_in) { MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_hash_obj, mp_builtin_hash); STATIC mp_obj_t mp_builtin_hex(mp_obj_t o_in) { + #if MICROPY_PY_BUILTINS_STR_OP_MODULO return mp_binary_op(MP_BINARY_OP_MODULO, MP_OBJ_NEW_QSTR(MP_QSTR__percent__hash_x), o_in); + #else + mp_obj_t args[] = { MP_OBJ_NEW_QSTR(MP_QSTR__brace_open__colon__hash_x_brace_close_), o_in }; + return mp_obj_str_format(MP_ARRAY_SIZE(args), args, NULL); + #endif } MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_hex_obj, mp_builtin_hex); @@ -325,7 +330,12 @@ STATIC mp_obj_t mp_builtin_next(mp_obj_t o) { MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_next_obj, mp_builtin_next); STATIC mp_obj_t mp_builtin_oct(mp_obj_t o_in) { + #if MICROPY_PY_BUILTINS_STR_OP_MODULO return mp_binary_op(MP_BINARY_OP_MODULO, MP_OBJ_NEW_QSTR(MP_QSTR__percent__hash_o), o_in); + #else + mp_obj_t args[] = { MP_OBJ_NEW_QSTR(MP_QSTR__brace_open__colon__hash_o_brace_close_), o_in }; + return mp_obj_str_format(MP_ARRAY_SIZE(args), args, NULL); + #endif } MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_oct_obj, mp_builtin_oct); diff --git a/py/modio.c b/py/modio.c index 01cb65af59..e88a9b04f3 100644 --- a/py/modio.c +++ b/py/modio.c @@ -44,7 +44,7 @@ extern const mp_obj_type_t mp_type_textio; STATIC const mp_obj_type_t mp_type_iobase; -STATIC mp_obj_base_t iobase_singleton = {&mp_type_iobase}; +STATIC const mp_obj_base_t iobase_singleton = {&mp_type_iobase}; STATIC mp_obj_t iobase_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { (void)type; diff --git a/py/modmath.c b/py/modmath.c index 2e271aed3d..9df345a564 100644 --- a/py/modmath.c +++ b/py/modmath.c @@ -238,6 +238,70 @@ STATIC mp_obj_t mp_math_degrees(mp_obj_t x_obj) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_degrees_obj, mp_math_degrees); +#if MICROPY_PY_MATH_FACTORIAL + +#if MICROPY_OPT_MATH_FACTORIAL + +// factorial(x): slightly efficient recursive implementation +STATIC mp_obj_t mp_math_factorial_inner(mp_uint_t start, mp_uint_t end) { + if (start == end) { + return mp_obj_new_int(start); + } else if (end - start == 1) { + return mp_binary_op(MP_BINARY_OP_MULTIPLY, MP_OBJ_NEW_SMALL_INT(start), MP_OBJ_NEW_SMALL_INT(end)); + } else if (end - start == 2) { + mp_obj_t left = MP_OBJ_NEW_SMALL_INT(start); + mp_obj_t middle = MP_OBJ_NEW_SMALL_INT(start + 1); + mp_obj_t right = MP_OBJ_NEW_SMALL_INT(end); + mp_obj_t tmp = mp_binary_op(MP_BINARY_OP_MULTIPLY, left, middle); + return mp_binary_op(MP_BINARY_OP_MULTIPLY, tmp, right); + } else { + mp_uint_t middle = start + ((end - start) >> 1); + mp_obj_t left = mp_math_factorial_inner(start, middle); + mp_obj_t right = mp_math_factorial_inner(middle + 1, end); + return mp_binary_op(MP_BINARY_OP_MULTIPLY, left, right); + } +} +STATIC mp_obj_t mp_math_factorial(mp_obj_t x_obj) { + mp_int_t max = mp_obj_get_int(x_obj); + if (max < 0) { + mp_raise_msg(&mp_type_ValueError, translate("negative factorial")); + } else if (max == 0) { + return MP_OBJ_NEW_SMALL_INT(1); + } + return mp_math_factorial_inner(1, max); +} + +#else + +// factorial(x): squared difference implementation +// based on http://www.luschny.de/math/factorial/index.html +STATIC mp_obj_t mp_math_factorial(mp_obj_t x_obj) { + mp_int_t max = mp_obj_get_int(x_obj); + if (max < 0) { + mp_raise_msg(&mp_type_ValueError, translate("negative factorial")); + } else if (max <= 1) { + return MP_OBJ_NEW_SMALL_INT(1); + } + mp_int_t h = max >> 1; + mp_int_t q = h * h; + mp_int_t r = q << 1; + if (max & 1) { + r *= max; + } + mp_obj_t prod = MP_OBJ_NEW_SMALL_INT(r); + for (mp_int_t num = 1; num < max - 2; num += 2) { + q -= num; + prod = mp_binary_op(MP_BINARY_OP_MULTIPLY, prod, MP_OBJ_NEW_SMALL_INT(q)); + } + return prod; +} + +#endif + +STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_factorial_obj, mp_math_factorial); + +#endif + STATIC const mp_rom_map_elem_t mp_module_math_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_math) }, { MP_ROM_QSTR(MP_QSTR_e), mp_const_float_e }, @@ -280,6 +344,9 @@ STATIC const mp_rom_map_elem_t mp_module_math_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_trunc), MP_ROM_PTR(&mp_math_trunc_obj) }, { MP_ROM_QSTR(MP_QSTR_radians), MP_ROM_PTR(&mp_math_radians_obj) }, { MP_ROM_QSTR(MP_QSTR_degrees), MP_ROM_PTR(&mp_math_degrees_obj) }, + #if MICROPY_PY_MATH_FACTORIAL + { MP_ROM_QSTR(MP_QSTR_factorial), MP_ROM_PTR(&mp_math_factorial_obj) }, + #endif #if MICROPY_PY_MATH_SPECIAL_FUNCTIONS { MP_ROM_QSTR(MP_QSTR_erf), MP_ROM_PTR(&mp_math_erf_obj) }, { MP_ROM_QSTR(MP_QSTR_erfc), MP_ROM_PTR(&mp_math_erfc_obj) }, diff --git a/py/modstruct.c b/py/modstruct.c index 1c5319608d..8f78fa234a 100644 --- a/py/modstruct.c +++ b/py/modstruct.c @@ -214,9 +214,11 @@ STATIC void struct_pack_into_internal(mp_obj_t fmt_in, byte *p, size_t n_args, c p += cnt; } else { while (cnt--) { - mp_binary_set_val(fmt_type, *fmt, args[i], &p); // Pad bytes don't have a corresponding argument. - if (*fmt != 'x') { + if (*fmt == 'x') { + mp_binary_set_val(fmt_type, *fmt, MP_OBJ_NEW_SMALL_INT(0), &p); + } else { + mp_binary_set_val(fmt_type, *fmt, args[i], &p); i++; } } diff --git a/py/mpconfig.h b/py/mpconfig.h index 043386d7c0..6badacaf6c 100644 --- a/py/mpconfig.h +++ b/py/mpconfig.h @@ -111,6 +111,15 @@ #define MICROPY_ALLOC_GC_STACK_SIZE (64) #endif +// The C-type to use for entries in the GC stack. By default it allows the +// heap to be as large as the address space, but the bit-width of this type can +// be reduced to save memory when the heap is small enough. The type must be +// big enough to index all blocks in the heap, which is set by +// heap-size-in-bytes / MICROPY_BYTES_PER_GC_BLOCK. +#ifndef MICROPY_GC_STACK_ENTRY_TYPE +#define MICROPY_GC_STACK_ENTRY_TYPE size_t +#endif + // Be conservative and always clear to zero newly (re)allocated memory in the GC. // This helps eliminate stray pointers that hold on to memory that's no longer // used. It decreases performance due to unnecessary memory clearing. @@ -390,6 +399,11 @@ #define MICROPY_MEM_STATS (0) #endif +// The mp_print_t printer used for debugging output +#ifndef MICROPY_DEBUG_PRINTER +#define MICROPY_DEBUG_PRINTER (&mp_plat_print) +#endif + // Whether to build functions that print debugging info: // mp_bytecode_print // mp_parse_node_print @@ -402,6 +416,11 @@ #define MICROPY_DEBUG_VERBOSE (0) #endif +// Whether to enable a simple VM stack overflow check +#ifndef MICROPY_DEBUG_VM_STACK_OVERFLOW +#define MICROPY_DEBUG_VM_STACK_OVERFLOW (0) +#endif + /*****************************************************************************/ /* Optimisations */ @@ -434,6 +453,12 @@ #define MICROPY_OPT_MPZ_BITWISE (0) #endif + +// Whether math.factorial is large, fast and recursive (1) or small and slow (0). +#ifndef MICROPY_OPT_MATH_FACTORIAL +#define MICROPY_OPT_MATH_FACTORIAL (0) +#endif + /*****************************************************************************/ /* Python internal features */ @@ -664,6 +689,11 @@ typedef double mp_float_t; #define MICROPY_MODULE_BUILTIN_INIT (0) #endif +// Whether to support module-level __getattr__ (see PEP 562) +#ifndef MICROPY_MODULE_GETATTR +#define MICROPY_MODULE_GETATTR (0) +#endif + // Whether module weak links are supported #ifndef MICROPY_MODULE_WEAK_LINKS #define MICROPY_MODULE_WEAK_LINKS (0) @@ -796,6 +826,16 @@ typedef double mp_float_t; #define MICROPY_PY_BUILTINS_STR_CENTER (0) #endif +// Whether str.count() method provided +#ifndef MICROPY_PY_BUILTINS_STR_COUNT +#define MICROPY_PY_BUILTINS_STR_COUNT (1) +#endif + +// Whether str % (...) formatting operator provided +#ifndef MICROPY_PY_BUILTINS_STR_OP_MODULO +#define MICROPY_PY_BUILTINS_STR_OP_MODULO (1) +#endif + // Whether str.partition()/str.rpartition() method provided #ifndef MICROPY_PY_BUILTINS_STR_PARTITION #define MICROPY_PY_BUILTINS_STR_PARTITION (0) @@ -811,6 +851,11 @@ typedef double mp_float_t; #define MICROPY_PY_BUILTINS_BYTEARRAY (1) #endif +// Whether to support dict.fromkeys() class method +#ifndef MICROPY_PY_BUILTINS_DICT_FROMKEYS +#define MICROPY_PY_BUILTINS_DICT_FROMKEYS (1) +#endif + // Whether to support memoryview object #ifndef MICROPY_PY_BUILTINS_MEMORYVIEW #define MICROPY_PY_BUILTINS_MEMORYVIEW (0) @@ -1026,6 +1071,11 @@ typedef double mp_float_t; #define MICROPY_PY_MATH_SPECIAL_FUNCTIONS (0) #endif +// Whether to provide math.factorial function +#ifndef MICROPY_PY_MATH_FACTORIAL +#define MICROPY_PY_MATH_FACTORIAL (0) +#endif + // Whether to provide "cmath" module #ifndef MICROPY_PY_CMATH #define MICROPY_PY_CMATH (0) @@ -1178,6 +1228,12 @@ typedef double mp_float_t; #define MICROPY_PY_UCTYPES (0) #endif +// Whether to provide SHORT, INT, LONG, etc. types in addition to +// exact-bitness types like INT16, INT32, etc. +#ifndef MICROPY_PY_UCTYPES_NATIVE_C_TYPES +#define MICROPY_PY_UCTYPES_NATIVE_C_TYPES (1) +#endif + #ifndef MICROPY_PY_UZLIB #define MICROPY_PY_UZLIB (0) #endif @@ -1219,6 +1275,10 @@ typedef double mp_float_t; #define MICROPY_PY_UHASHLIB (0) #endif +#ifndef MICROPY_PY_UHASHLIB_MD5 +#define MICROPY_PY_UHASHLIB_MD5 (0) +#endif + #ifndef MICROPY_PY_UHASHLIB_SHA1 #define MICROPY_PY_UHASHLIB_SHA1 (0) #endif @@ -1227,6 +1287,14 @@ typedef double mp_float_t; #define MICROPY_PY_UHASHLIB_SHA256 (1) #endif +#ifndef MICROPY_PY_UCRYPTOLIB +#define MICROPY_PY_UCRYPTOLIB (0) +#endif + +#ifndef MICROPY_PY_UCRYPTOLIB_CONSTS +#define MICROPY_PY_UCRYPTOLIB_CONSTS (0) +#endif + #ifndef MICROPY_PY_UBINASCII #define MICROPY_PY_UBINASCII (0) #endif diff --git a/py/mpstate.h b/py/mpstate.h index 139f23cb4f..0c57563acc 100644 --- a/py/mpstate.h +++ b/py/mpstate.h @@ -79,7 +79,7 @@ typedef struct _mp_state_mem_t { void *gc_lowest_long_lived_ptr; int gc_stack_overflow; - size_t gc_stack[MICROPY_ALLOC_GC_STACK_SIZE]; + MICROPY_GC_STACK_ENTRY_TYPE gc_stack[MICROPY_ALLOC_GC_STACK_SIZE]; uint16_t gc_lock_depth; // This variable controls auto garbage collection. If set to false then the @@ -197,7 +197,7 @@ typedef struct _mp_state_vm_t { // pointer and sizes to store interned string data // (qstr_last_chunk can be root pointer but is also stored in qstr pool) - byte *qstr_last_chunk; + char *qstr_last_chunk; size_t qstr_last_alloc; size_t qstr_last_used; diff --git a/py/nativeglue.c b/py/nativeglue.c index 05e257ab02..7662aaeaf6 100644 --- a/py/nativeglue.c +++ b/py/nativeglue.c @@ -89,6 +89,20 @@ mp_obj_t mp_convert_native_to_obj(mp_uint_t val, mp_uint_t type) { #if MICROPY_EMIT_NATIVE +mp_obj_dict_t *mp_native_swap_globals(mp_obj_dict_t *new_globals) { + if (new_globals == NULL) { + // Globals were the originally the same so don't restore them + return NULL; + } + mp_obj_dict_t *old_globals = mp_globals_get(); + if (old_globals == new_globals) { + // Don't set globals if they are the same, and return NULL to indicate this + return NULL; + } + mp_globals_set(new_globals); + return old_globals; +} + // wrapper that accepts n_args and n_kw in one argument // (native emitter can only pass at most 3 arguments to a function) mp_obj_t mp_native_call_function_n_kw(mp_obj_t fun_in, size_t n_args_kw, const mp_obj_t *args) { @@ -98,7 +112,7 @@ mp_obj_t mp_native_call_function_n_kw(mp_obj_t fun_in, size_t n_args_kw, const m // wrapper that makes raise obj and raises it // END_FINALLY opcode requires that we don't raise if o==None void mp_native_raise(mp_obj_t o) { - if (o != mp_const_none) { + if (o != MP_OBJ_NULL && o != mp_const_none) { nlr_raise(mp_make_raise_obj(o)); } } @@ -129,10 +143,50 @@ STATIC mp_obj_t mp_native_iternext(mp_obj_iter_buf_t *iter) { return mp_iternext(obj); } +STATIC bool mp_native_yield_from(mp_obj_t gen, mp_obj_t send_value, mp_obj_t *ret_value) { + mp_vm_return_kind_t ret_kind; + nlr_buf_t nlr_buf; + mp_obj_t throw_value = *ret_value; + if (nlr_push(&nlr_buf) == 0) { + if (throw_value != MP_OBJ_NULL) { + send_value = MP_OBJ_NULL; + } + ret_kind = mp_resume(gen, send_value, throw_value, ret_value); + nlr_pop(); + } else { + ret_kind = MP_VM_RETURN_EXCEPTION; + *ret_value = nlr_buf.ret_val; + } + + if (ret_kind == MP_VM_RETURN_YIELD) { + return true; + } else if (ret_kind == MP_VM_RETURN_NORMAL) { + if (*ret_value == MP_OBJ_STOP_ITERATION) { + *ret_value = mp_const_none; + } + } else { + assert(ret_kind == MP_VM_RETURN_EXCEPTION); + if (!mp_obj_exception_match(*ret_value, MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { + nlr_raise(*ret_value); + } + *ret_value = mp_obj_exception_get_value(*ret_value); + } + + if (throw_value != MP_OBJ_NULL && mp_obj_exception_match(throw_value, MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { + nlr_raise(mp_make_raise_obj(throw_value)); + } + + return false; +} + // these must correspond to the respective enum in runtime0.h -void *const mp_fun_table[MP_F_NUMBER_OF] = { +const void *const mp_fun_table[MP_F_NUMBER_OF] = { + &mp_const_none_obj, + &mp_const_false_obj, + &mp_const_true_obj, mp_convert_obj_to_native, mp_convert_native_to_obj, + mp_native_swap_globals, mp_load_name, mp_load_global, mp_load_build_class, @@ -176,9 +230,11 @@ void *const mp_fun_table[MP_F_NUMBER_OF] = { mp_delete_global, mp_obj_new_cell, mp_make_closure_from_raw_code, + mp_arg_check_num_sig, mp_setup_code_state, mp_small_int_floor_divide, mp_small_int_modulo, + mp_native_yield_from, }; /* diff --git a/py/obj.c b/py/obj.c index b271362536..6b2dded57e 100644 --- a/py/obj.c +++ b/py/obj.c @@ -269,12 +269,8 @@ mp_int_t mp_obj_get_int(mp_const_obj_t arg) { } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) { return mp_obj_int_get_checked(arg); } else { - #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError_varg(translate("can't convert to %q"), MP_QSTR_int); - #else - mp_raise_TypeError_varg( - translate("can't convert %q to %q"), mp_obj_get_type_qstr(arg), MP_QSTR_int); - #endif + mp_obj_t res = mp_unary_op(MP_UNARY_OP_INT, (mp_obj_t)arg); + return mp_obj_int_get_checked(res); } } diff --git a/py/obj.h b/py/obj.h index fcea402c63..4e32ce8b0e 100644 --- a/py/obj.h +++ b/py/obj.h @@ -149,6 +149,7 @@ static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) { #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 1) #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 1) | 1)) +#if MICROPY_PY_BUILTINS_FLOAT #define mp_const_float_e MP_ROM_PTR((mp_obj_t)(((0x402df854 & ~3) | 2) + 0x80800000)) #define mp_const_float_pi MP_ROM_PTR((mp_obj_t)(((0x40490fdb & ~3) | 2) + 0x80800000)) @@ -169,6 +170,7 @@ static inline mp_obj_t mp_obj_new_float(mp_float_t f) { } num = {.f = f}; return (mp_obj_t)(((num.u & ~0x3) | 2) + 0x80800000); } +#endif static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) { return (((mp_uint_t)(o)) & 0xff800007) == 0x00000006; @@ -183,18 +185,23 @@ static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) { #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) { - return (((mp_int_t)(o)) & 0xffff000000000000) == 0x0001000000000000; + return (((uint64_t)(o)) & 0xffff000000000000) == 0x0001000000000000; } #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)((o) << 16)) >> 17) #define MP_OBJ_NEW_SMALL_INT(small_int) (((((uint64_t)(small_int)) & 0x7fffffffffff) << 1) | 0x0001000000000001) static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) { - return (((mp_int_t)(o)) & 0xffff000000000000) == 0x0002000000000000; + return (((uint64_t)(o)) & 0xffff000000000000) == 0x0002000000000000; } #define MP_OBJ_QSTR_VALUE(o) ((((uint32_t)(o)) >> 1) & 0xffffffff) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 1) | 0x0002000000000001)) #if MICROPY_PY_BUILTINS_FLOAT + +#if MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_DOUBLE +#error MICROPY_OBJ_REPR_D requires MICROPY_FLOAT_IMPL_DOUBLE +#endif + #define mp_const_float_e {((mp_obj_t)((uint64_t)0x4005bf0a8b145769 + 0x8004000000000000))} #define mp_const_float_pi {((mp_obj_t)((uint64_t)0x400921fb54442d18 + 0x8004000000000000))} @@ -290,6 +297,9 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; #define MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(obj_name) extern const mp_obj_fun_builtin_var_t obj_name #define MP_DECLARE_CONST_FUN_OBJ_KW(obj_name) extern const mp_obj_fun_builtin_var_t obj_name +#define MP_OBJ_FUN_ARGS_MAX (0xffff) // to set maximum value in n_args_max below +#define MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, takes_kw) ((uint32_t)((((uint32_t)(n_args_min)) << 17) | (((uint32_t)(n_args_max)) << 1) | ((takes_kw) ? 1 : 0))) + #define MP_DEFINE_CONST_FUN_OBJ_0(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t obj_name = \ {{&mp_type_fun_builtin_0}, .fun._0 = fun_name} @@ -304,13 +314,14 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; {{&mp_type_fun_builtin_3}, .fun._3 = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_VAR(obj_name, n_args_min, fun_name) \ const mp_obj_fun_builtin_var_t obj_name = \ - {{&mp_type_fun_builtin_var}, false, n_args_min, MP_OBJ_FUN_ARGS_MAX, .fun.var = fun_name} + {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, false), .fun.var = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(obj_name, n_args_min, n_args_max, fun_name) \ const mp_obj_fun_builtin_var_t obj_name = \ - {{&mp_type_fun_builtin_var}, false, n_args_min, n_args_max, .fun.var = fun_name} + {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, false), .fun.var = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_KW(obj_name, n_args_min, fun_name) \ const mp_obj_fun_builtin_var_t obj_name = \ - {{&mp_type_fun_builtin_var}, true, n_args_min, MP_OBJ_FUN_ARGS_MAX, .fun.kw = fun_name} + {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, true), .fun.kw = fun_name} + #define MP_DEFINE_CONST_PROP_GET(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t fun_name##_obj = {{&mp_type_fun_builtin_1}, .fun._1 = fun_name}; \ const mp_obj_property_t obj_name = { \ @@ -610,6 +621,8 @@ extern const mp_obj_type_t mp_type_slice; extern const mp_obj_type_t mp_type_zip; extern const mp_obj_type_t mp_type_array; extern const mp_obj_type_t mp_type_super; +extern const mp_obj_type_t mp_type_gen_wrap; +extern const mp_obj_type_t mp_type_native_gen_wrap; extern const mp_obj_type_t mp_type_gen_instance; extern const mp_obj_type_t mp_type_fun_builtin_0; extern const mp_obj_type_t mp_type_fun_builtin_1; @@ -617,6 +630,9 @@ extern const mp_obj_type_t mp_type_fun_builtin_2; extern const mp_obj_type_t mp_type_fun_builtin_3; extern const mp_obj_type_t mp_type_fun_builtin_var; extern const mp_obj_type_t mp_type_fun_bc; +#if MICROPY_EMIT_NATIVE +extern const mp_obj_type_t mp_type_fun_native; +#endif extern const mp_obj_type_t mp_type_module; extern const mp_obj_type_t mp_type_staticmethod; extern const mp_obj_type_t mp_type_classmethod; @@ -841,7 +857,9 @@ size_t mp_obj_dict_len(mp_obj_t self_in); mp_obj_t mp_obj_dict_get(mp_obj_t self_in, mp_obj_t index); mp_obj_t mp_obj_dict_store(mp_obj_t self_in, mp_obj_t key, mp_obj_t value); mp_obj_t mp_obj_dict_delete(mp_obj_t self_in, mp_obj_t key); -mp_map_t *mp_obj_dict_get_map(mp_obj_t self_in); +static inline mp_map_t *mp_obj_dict_get_map(mp_obj_t dict) { + return &((mp_obj_dict_t *)MP_OBJ_TO_PTR(dict))->map; +} // set void mp_obj_set_store(mp_obj_t self_in, mp_obj_t item); @@ -861,12 +879,9 @@ typedef struct _mp_obj_fun_builtin_fixed_t { } fun; } mp_obj_fun_builtin_fixed_t; -#define MP_OBJ_FUN_ARGS_MAX (0xffff) // to set maximum value in n_args_max below typedef struct _mp_obj_fun_builtin_var_t { mp_obj_base_t base; - bool is_kw : 1; - mp_uint_t n_args_min : 15; // inclusive - mp_uint_t n_args_max : 16; // inclusive + uint32_t sig; // see MP_OBJ_FUN_MAKE_SIG union { mp_fun_var_t var; mp_fun_kw_t kw; diff --git a/py/objarray.c b/py/objarray.c index e6024f720c..7864d79867 100644 --- a/py/objarray.c +++ b/py/objarray.c @@ -52,11 +52,14 @@ // Note that we don't handle the case where the original buffer might change // size due to a resize of the original parent object. -// make (& TYPECODE_MASK) a null operation if memorview not enabled #if MICROPY_PY_BUILTINS_MEMORYVIEW #define TYPECODE_MASK (0x7f) +#define memview_offset free #else +// make (& TYPECODE_MASK) a null operation if memorview not enabled #define TYPECODE_MASK (~(size_t)0) +// memview_offset should not be accessed if memoryview is not enabled, +// so not defined to catch errors #endif STATIC mp_obj_t array_iterator_new(mp_obj_t array_in, mp_obj_iter_buf_t *iter_buf); @@ -186,7 +189,7 @@ STATIC mp_obj_t array_make_new(const mp_obj_type_t *type_in, size_t n_args, cons #if MICROPY_PY_BUILTINS_BYTEARRAY STATIC mp_obj_t bytearray_make_new(const mp_obj_type_t *type_in, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { (void)type_in; - mp_arg_check_num(n_args, kw_args, 0, 1, false); + mp_arg_check_num(n_args, kw_args, 0, 3, false); if (n_args == 0) { // no args: construct an empty bytearray @@ -210,7 +213,7 @@ mp_obj_t mp_obj_new_memoryview(byte typecode, size_t nitems, void *items) { mp_obj_array_t *self = m_new_obj(mp_obj_array_t); self->base.type = &mp_type_memoryview; self->typecode = typecode; - self->free = 0; + self->memview_offset = 0; self->len = nitems; self->items = items; return MP_OBJ_FROM_PTR(self); @@ -338,10 +341,10 @@ STATIC mp_obj_t array_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs } case MP_BINARY_OP_CONTAINS: { + #if MICROPY_PY_BUILTINS_BYTEARRAY + // Can search string only in bytearray mp_buffer_info_t lhs_bufinfo; mp_buffer_info_t rhs_bufinfo; - - // Can search string only in bytearray if (mp_get_buffer(rhs_in, &rhs_bufinfo, MP_BUFFER_READ)) { if (!MP_OBJ_IS_TYPE(lhs_in, &mp_type_bytearray)) { return mp_const_false; @@ -350,6 +353,7 @@ STATIC mp_obj_t array_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs return mp_obj_new_bool( find_subbytes(lhs_bufinfo.buf, lhs_bufinfo.len, rhs_bufinfo.buf, rhs_bufinfo.len, 1) != NULL); } + #endif // Otherwise, can only look for a scalar numeric value in an array if (MP_OBJ_IS_INT(rhs_in) || mp_obj_is_float(rhs_in)) { @@ -522,7 +526,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value src_items = src_slice->items; #if MICROPY_PY_BUILTINS_MEMORYVIEW if (MP_OBJ_IS_TYPE(value, &mp_type_memoryview)) { - src_items = (uint8_t *)src_items + (src_slice->free * item_sz); + src_items = (uint8_t *)src_items + (src_slice->memview_offset * item_sz); } #endif } else if (MP_OBJ_IS_TYPE(value, &mp_type_bytes)) { @@ -549,7 +553,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value if (len_adj != 0) { goto compat_error; } - dest_items += o->free * item_sz; + dest_items += o->memview_offset * item_sz; } #endif if (len_adj > 0) { @@ -587,7 +591,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value } else if (o->base.type == &mp_type_memoryview) { res = m_new_obj(mp_obj_array_t); *res = *o; - res->free += slice.start; + res->memview_offset += slice.start; res->len = slice.stop - slice.start; #endif } else { @@ -600,7 +604,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value size_t index = mp_get_index(o->base.type, o->len, index_in, false); #if MICROPY_PY_BUILTINS_MEMORYVIEW if (o->base.type == &mp_type_memoryview) { - index += o->free; + index += o->memview_offset; if (value != MP_OBJ_SENTINEL && !(o->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW)) { // store to read-only memoryview return MP_OBJ_NULL; @@ -631,7 +635,7 @@ STATIC mp_int_t array_get_buffer(mp_obj_t o_in, mp_buffer_info_t *bufinfo, mp_ui // read-only memoryview return 1; } - bufinfo->buf = (uint8_t *)bufinfo->buf + (size_t)o->free * sz; + bufinfo->buf = (uint8_t *)bufinfo->buf + (size_t)o->memview_offset * sz; } #else (void)flags; @@ -806,7 +810,7 @@ STATIC mp_obj_t array_iterator_new(mp_obj_t array_in, mp_obj_iter_buf_t *iter_bu o->cur = 0; #if MICROPY_PY_BUILTINS_MEMORYVIEW if (array->base.type == &mp_type_memoryview) { - o->offset = array->free; + o->offset = array->memview_offset; } #endif return MP_OBJ_FROM_PTR(o); diff --git a/py/objarray.h b/py/objarray.h index 7ad5328f0e..062de8b577 100644 --- a/py/objarray.h +++ b/py/objarray.h @@ -32,11 +32,18 @@ // Used only for memoryview types, set in "typecode" to indicate a writable memoryview #define MP_OBJ_ARRAY_TYPECODE_FLAG_RW (0x80) +// This structure is used for all of bytearray, array.array, memoryview +// objects. Note that memoryview has different meaning for some fields, +// see comment at the beginning of objarray.c. typedef struct _mp_obj_array_t { mp_obj_base_t base; size_t typecode : 8; // free is number of unused elements after len used elements // alloc size = len + free + // But for memoryview, 'free' is reused as offset (in elements) into the + // parent object. (Union is not used to not go into a complication of + // union-of-bitfields with different toolchains). See comments in + // objarray.c. size_t free : (8 * sizeof(size_t) - 8); size_t len; // in elements void *items; diff --git a/py/objboundmeth.c b/py/objboundmeth.c index cdb7257973..995e058735 100644 --- a/py/objboundmeth.c +++ b/py/objboundmeth.c @@ -89,13 +89,9 @@ STATIC void bound_meth_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { // not load attribute return; } - if (attr == MP_QSTR___name__) { - mp_obj_bound_meth_t *o = MP_OBJ_TO_PTR(self_in); - dest[0] = MP_OBJ_NEW_QSTR(mp_obj_fun_get_name(o->meth)); - } else if (attr == MP_QSTR___func__) { - mp_obj_bound_meth_t *o = MP_OBJ_TO_PTR(self_in); - dest[0] = o->meth; - } + // Delegate the load to the method object + mp_obj_bound_meth_t *self = MP_OBJ_TO_PTR(self_in); + mp_load_method_maybe(self->meth, attr, dest); } #endif diff --git a/py/objdict.c b/py/objdict.c index 24484566f3..4394af9edb 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -167,7 +167,7 @@ STATIC mp_obj_t dict_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_ } } -// TODO: Make sure this is inlined in dict_subscr() below. +// Note: Make sure this is inlined in load part of dict_subscr() below. mp_obj_t mp_obj_dict_get(mp_obj_t self_in, mp_obj_t index) { mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); mp_map_elem_t *elem = mp_map_lookup(&self->map, index, MP_MAP_LOOKUP); @@ -234,6 +234,7 @@ STATIC mp_obj_t dict_copy(mp_obj_t self_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(dict_copy_obj, dict_copy); +#if MICROPY_PY_BUILTINS_DICT_FROMKEYS // this is a classmethod STATIC mp_obj_t dict_fromkeys(size_t n_args, const mp_obj_t *args) { mp_obj_t iter = mp_getiter(args[1], NULL); @@ -263,6 +264,7 @@ STATIC mp_obj_t dict_fromkeys(size_t n_args, const mp_obj_t *args) { } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_fromkeys_fun_obj, 2, 3, dict_fromkeys); STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(dict_fromkeys_obj, MP_ROM_PTR(&dict_fromkeys_fun_obj)); +#endif STATIC mp_obj_t dict_get_helper(size_t n_args, const mp_obj_t *args, mp_map_lookup_kind_t lookup_kind) { mp_check_self(MP_OBJ_IS_DICT_TYPE(args[0])); @@ -535,7 +537,9 @@ STATIC mp_obj_t dict_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) { STATIC const mp_rom_map_elem_t dict_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_clear), MP_ROM_PTR(&dict_clear_obj) }, { MP_ROM_QSTR(MP_QSTR_copy), MP_ROM_PTR(&dict_copy_obj) }, + #if MICROPY_PY_BUILTINS_DICT_FROMKEYS { MP_ROM_QSTR(MP_QSTR_fromkeys), MP_ROM_PTR(&dict_fromkeys_obj) }, + #endif { MP_ROM_QSTR(MP_QSTR_get), MP_ROM_PTR(&dict_get_obj) }, { MP_ROM_QSTR(MP_QSTR_items), MP_ROM_PTR(&dict_items_obj) }, { MP_ROM_QSTR(MP_QSTR_keys), MP_ROM_PTR(&dict_keys_obj) }, @@ -607,9 +611,3 @@ mp_obj_t mp_obj_dict_delete(mp_obj_t self_in, mp_obj_t key) { dict_get_helper(2, args, MP_MAP_LOOKUP_REMOVE_IF_FOUND); return self_in; } - -mp_map_t *mp_obj_dict_get_map(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(self_in)); - mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); - return &self->map; -} diff --git a/py/objexcept.c b/py/objexcept.c index fb6424fa48..2ea1dc7c79 100644 --- a/py/objexcept.c +++ b/py/objexcept.c @@ -43,12 +43,23 @@ // Number of items per traceback entry (file, line, block) #define TRACEBACK_ENTRY_LEN (3) -// Number of traceback entries to reserve in the emergency exception buffer -#define EMG_TRACEBACK_ALLOC (2 * TRACEBACK_ENTRY_LEN) - -// Optionally allocated buffer for storing the first argument of an exception -// allocated when the heap is locked. +// Optionally allocated buffer for storing some traceback, the tuple argument, +// and possible string object and data, for when the heap is locked. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF + +// When used the layout of the emergency exception buffer is: +// - traceback entry (file, line, block) +// - traceback entry (file, line, block) +// - mp_obj_tuple_t object +// - n_args * mp_obj_t for tuple +// - mp_obj_str_t object +// - string data +#define EMG_BUF_TRACEBACK_OFFSET (0) +#define EMG_BUF_TRACEBACK_SIZE (2 * TRACEBACK_ENTRY_LEN * sizeof(size_t)) +#define EMG_BUF_TUPLE_OFFSET (EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE) +#define EMG_BUF_TUPLE_SIZE(n_args) (sizeof(mp_obj_tuple_t) + n_args * sizeof(mp_obj_t)) +#define EMG_BUF_STR_OFFSET (EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(1)) + #if MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE > 0 #define mp_emergency_exception_buf_size MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE @@ -162,9 +173,9 @@ mp_obj_t mp_obj_exception_make_new(const mp_obj_type_t *type, size_t n_args, con // reserved room (after the traceback data) for a tuple with 1 element. // Otherwise we are free to use the whole buffer after the traceback data. if (o_tuple == NULL && mp_emergency_exception_buf_size >= - EMG_TRACEBACK_ALLOC * sizeof(size_t) + sizeof(mp_obj_tuple_t) + n_args * sizeof(mp_obj_t)) { + EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(n_args)) { o_tuple = (mp_obj_tuple_t *) - ((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + EMG_TRACEBACK_ALLOC * sizeof(size_t)); + ((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + EMG_BUF_TUPLE_OFFSET); } #endif @@ -414,11 +425,10 @@ mp_obj_t mp_obj_new_exception_msg_vlist(const mp_obj_type_t *exc_type, const com // that buffer to store the string object and its data (at least 16 bytes for // the string data), reserving room at the start for the traceback and 1-tuple. if ((o_str == NULL || o_str_buf == NULL) - && mp_emergency_exception_buf_size >= EMG_TRACEBACK_ALLOC * sizeof(size_t) - + sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t) + sizeof(mp_obj_str_t) + 16) { + && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + sizeof(mp_obj_str_t) + 16) { used_emg_buf = true; o_str = (mp_obj_str_t *)((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) - + EMG_TRACEBACK_ALLOC * sizeof(size_t) + sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t)); + + EMG_BUF_STR_OFFSET); o_str_buf = (byte *)&o_str[1]; o_str_alloc = (uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + mp_emergency_exception_buf_size - o_str_buf; @@ -510,11 +520,12 @@ void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qs self->traceback_data = m_new_maybe(size_t, TRACEBACK_ENTRY_LEN); if (self->traceback_data == NULL) { #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF - if (mp_emergency_exception_buf_size >= EMG_TRACEBACK_ALLOC * sizeof(size_t)) { + if (mp_emergency_exception_buf_size >= EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE) { // There is room in the emergency buffer for traceback data - size_t *tb = (size_t *)MP_STATE_VM(mp_emergency_exception_buf); + size_t *tb = (size_t *)((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + + EMG_BUF_TRACEBACK_OFFSET); self->traceback_data = tb; - self->traceback_alloc = EMG_TRACEBACK_ALLOC; + self->traceback_alloc = EMG_BUF_TRACEBACK_SIZE / sizeof(size_t); } else { // Can't allocate and no room in emergency buffer return; diff --git a/py/objfloat.c b/py/objfloat.c index 5c0a87ea3d..3bdfa0b757 100644 --- a/py/objfloat.c +++ b/py/objfloat.c @@ -172,8 +172,7 @@ STATIC mp_obj_t float_unary_op(mp_unary_op_t op, mp_obj_t o_in) { case MP_UNARY_OP_NEGATIVE: return mp_obj_new_float(-val); case MP_UNARY_OP_ABS: { - // TODO check for NaN etc - if (val < 0) { + if (signbit(val)) { return mp_obj_new_float(-val); } else { return o_in; diff --git a/py/objfun.c b/py/objfun.c index 69045c6323..5e4792a7dd 100644 --- a/py/objfun.c +++ b/py/objfun.c @@ -112,9 +112,9 @@ STATIC mp_obj_t fun_builtin_var_call(mp_obj_t self_in, size_t n_args, size_t n_k mp_obj_fun_builtin_var_t *self = MP_OBJ_TO_PTR(self_in); // check number of arguments - mp_arg_check_num_kw_array(n_args, n_kw, self->n_args_min, self->n_args_max, self->is_kw); + mp_arg_check_num_sig(n_args, n_kw, self->sig); - if (self->is_kw) { + if (self->sig & 1) { // function allows keywords // we create a map directly from the given args array @@ -149,10 +149,6 @@ qstr mp_obj_code_get_name(const byte *code_info) { #endif } -#if MICROPY_EMIT_NATIVE -STATIC const mp_obj_type_t mp_type_fun_native; -#endif - qstr mp_obj_fun_get_name(mp_const_obj_t fun_in) { const mp_obj_fun_bc_t *fun = MP_OBJ_TO_PTR(fun_in); #if MICROPY_EMIT_NATIVE @@ -197,17 +193,12 @@ STATIC void dump_args(const mp_obj_t *a, size_t sz) { // than this will try to use the heap, with fallback to stack allocation. #define VM_MAX_STATE_ON_STACK (11 * sizeof(mp_uint_t)) -// Set this to 1 to enable a simple stack overflow check. -#define VM_DETECT_STACK_OVERFLOW (0) - #define DECODE_CODESTATE_SIZE(bytecode, n_state_out_var, state_size_out_var) \ { \ /* bytecode prelude: state size and exception stack size */ \ n_state_out_var = mp_decode_uint_value(bytecode); \ size_t n_exc_stack = mp_decode_uint_value(mp_decode_uint_skip(bytecode)); \ \ - n_state_out_var += VM_DETECT_STACK_OVERFLOW; \ - \ /* state size in bytes */ \ state_size_out_var = n_state_out_var * sizeof(mp_obj_t) \ + n_exc_stack * sizeof(mp_exc_stack_t); \ @@ -259,8 +250,8 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size dump_args(args, n_args); DEBUG_printf("Input kw args: "); dump_args(args + n_args, n_kw * 2); + mp_obj_fun_bc_t *self = MP_OBJ_TO_PTR(self_in); - DEBUG_printf("Func n_def_args: %d\n", self->n_def_args); size_t n_state, state_size; DECODE_CODESTATE_SIZE(self->bytecode, n_state, state_size); @@ -272,9 +263,17 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size #else if (state_size > VM_MAX_STATE_ON_STACK) { code_state = m_new_obj_var_maybe(mp_code_state_t, byte, state_size); + #if MICROPY_DEBUG_VM_STACK_OVERFLOW + if (code_state != NULL) { + memset(code_state->state, 0, state_size); + } + #endif } if (code_state == NULL) { code_state = alloca(sizeof(mp_code_state_t) + state_size); + #if MICROPY_DEBUG_VM_STACK_OVERFLOW + memset(code_state->state, 0, state_size); + #endif state_size = 0; // indicate that we allocated using alloca } #endif @@ -286,27 +285,30 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size mp_vm_return_kind_t vm_return_kind = mp_execute_bytecode(code_state, MP_OBJ_NULL); mp_globals_set(code_state->old_globals); - #if VM_DETECT_STACK_OVERFLOW + #if MICROPY_DEBUG_VM_STACK_OVERFLOW if (vm_return_kind == MP_VM_RETURN_NORMAL) { if (code_state->sp < code_state->state) { - printf("VM stack underflow: " INT_FMT "\n", code_state->sp - code_state->state); + mp_printf(MICROPY_DEBUG_PRINTER, "VM stack underflow: " INT_FMT "\n", code_state->sp - code_state->state); assert(0); } } - // We can't check the case when an exception is returned in state[n_state - 1] + const byte *bytecode_ptr = mp_decode_uint_skip(mp_decode_uint_skip(self->bytecode)); + size_t n_pos_args = bytecode_ptr[1]; + size_t n_kwonly_args = bytecode_ptr[2]; + // We can't check the case when an exception is returned in state[0] // and there are no arguments, because in this case our detection slot may have // been overwritten by the returned exception (which is allowed). - if (!(vm_return_kind == MP_VM_RETURN_EXCEPTION && self->n_pos_args + self->n_kwonly_args == 0)) { + if (!(vm_return_kind == MP_VM_RETURN_EXCEPTION && n_pos_args + n_kwonly_args == 0)) { // Just check to see that we have at least 1 null object left in the state. bool overflow = true; - for (size_t i = 0; i < n_state - self->n_pos_args - self->n_kwonly_args; i++) { + for (size_t i = 0; i < n_state - n_pos_args - n_kwonly_args; ++i) { if (code_state->state[i] == MP_OBJ_NULL) { overflow = false; break; } } if (overflow) { - printf("VM stack overflow state=%p n_state+1=" UINT_FMT "\n", code_state->state, n_state); + mp_printf(MICROPY_DEBUG_PRINTER, "VM stack overflow state=%p n_state+1=" UINT_FMT "\n", code_state->state, n_state); assert(0); } } @@ -319,8 +321,8 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size } else { // must be an exception because normal functions can't yield assert(vm_return_kind == MP_VM_RETURN_EXCEPTION); - // return value is in fastn[0]==state[n_state - 1] - result = code_state->state[n_state - 1]; + // returned exception is in state[0] + result = code_state->state[0]; } #if MICROPY_ENABLE_PYSTACK @@ -340,7 +342,7 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size } #if MICROPY_PY_FUNCTION_ATTRS -STATIC void fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { +void mp_obj_fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { if (dest[0] != MP_OBJ_NULL) { // not load attribute return; @@ -360,7 +362,7 @@ const mp_obj_type_t mp_type_fun_bc = { .call = fun_bc_call, .unary_op = mp_generic_unary_op, #if MICROPY_PY_FUNCTION_ATTRS - .attr = fun_bc_attr, + .attr = mp_obj_fun_bc_attr, #endif }; @@ -402,7 +404,7 @@ STATIC mp_obj_t fun_native_call(mp_obj_t self_in, size_t n_args, size_t n_kw, co return fun(self_in, n_args, n_kw, args); } -STATIC const mp_obj_type_t mp_type_fun_native = { +const mp_obj_type_t mp_type_fun_native = { { &mp_type_type }, .name = MP_QSTR_function, .call = fun_native_call, @@ -417,72 +419,6 @@ mp_obj_t mp_obj_new_fun_native(mp_obj_t def_args_in, mp_obj_t def_kw_args, const #endif // MICROPY_EMIT_NATIVE -/******************************************************************************/ -/* viper functions */ - -#if MICROPY_EMIT_NATIVE - -typedef struct _mp_obj_fun_viper_t { - mp_obj_base_t base; - size_t n_args; - void *fun_data; // GC must be able to trace this pointer - mp_uint_t type_sig; -} mp_obj_fun_viper_t; - -typedef mp_uint_t (*viper_fun_0_t)(void); -typedef mp_uint_t (*viper_fun_1_t)(mp_uint_t); -typedef mp_uint_t (*viper_fun_2_t)(mp_uint_t, mp_uint_t); -typedef mp_uint_t (*viper_fun_3_t)(mp_uint_t, mp_uint_t, mp_uint_t); -typedef mp_uint_t (*viper_fun_4_t)(mp_uint_t, mp_uint_t, mp_uint_t, mp_uint_t); - -STATIC mp_obj_t fun_viper_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - mp_obj_fun_viper_t *self = self_in; - - mp_arg_check_num_kw_array(n_args, n_kw, self->n_args, self->n_args, false); - - void *fun = MICROPY_MAKE_POINTER_CALLABLE(self->fun_data); - - mp_uint_t ret; - if (n_args == 0) { - ret = ((viper_fun_0_t)fun)(); - } else if (n_args == 1) { - ret = ((viper_fun_1_t)fun)(mp_convert_obj_to_native(args[0], self->type_sig >> 4)); - } else if (n_args == 2) { - ret = ((viper_fun_2_t)fun)(mp_convert_obj_to_native(args[0], self->type_sig >> 4), mp_convert_obj_to_native(args[1], self->type_sig >> 8)); - } else if (n_args == 3) { - ret = ((viper_fun_3_t)fun)(mp_convert_obj_to_native(args[0], self->type_sig >> 4), mp_convert_obj_to_native(args[1], self->type_sig >> 8), mp_convert_obj_to_native(args[2], self->type_sig >> 12)); - } else { - // compiler allows at most 4 arguments - assert(n_args == 4); - ret = ((viper_fun_4_t)fun)( - mp_convert_obj_to_native(args[0], self->type_sig >> 4), - mp_convert_obj_to_native(args[1], self->type_sig >> 8), - mp_convert_obj_to_native(args[2], self->type_sig >> 12), - mp_convert_obj_to_native(args[3], self->type_sig >> 16) - ); - } - - return mp_convert_native_to_obj(ret, self->type_sig); -} - -STATIC const mp_obj_type_t mp_type_fun_viper = { - { &mp_type_type }, - .name = MP_QSTR_function, - .call = fun_viper_call, - .unary_op = mp_generic_unary_op, -}; - -mp_obj_t mp_obj_new_fun_viper(size_t n_args, void *fun_data, mp_uint_t type_sig) { - mp_obj_fun_viper_t *o = m_new_obj(mp_obj_fun_viper_t); - o->base.type = &mp_type_fun_viper; - o->n_args = n_args; - o->fun_data = fun_data; - o->type_sig = type_sig; - return o; -} - -#endif // MICROPY_EMIT_NATIVE - /******************************************************************************/ /* inline assembler functions */ diff --git a/py/objfun.h b/py/objfun.h index 457c3cf48c..ba533fd329 100644 --- a/py/objfun.h +++ b/py/objfun.h @@ -41,4 +41,6 @@ typedef struct _mp_obj_fun_bc_t { mp_obj_t extra_args[]; } mp_obj_fun_bc_t; +void mp_obj_fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest); + #endif // MICROPY_INCLUDED_PY_OBJFUN_H diff --git a/py/objgenerator.c b/py/objgenerator.c index 9ca5812d84..5336f7f36a 100644 --- a/py/objgenerator.c +++ b/py/objgenerator.c @@ -52,7 +52,51 @@ typedef struct _mp_obj_gen_instance_t { mp_code_state_t code_state; } mp_obj_gen_instance_t; -STATIC mp_obj_t gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { +/******************************************************************************/ +// native generator wrapper + +#if MICROPY_EMIT_NATIVE + +STATIC mp_obj_t native_gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_obj_gen_wrap_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_fun_bc_t *self_fun = (mp_obj_fun_bc_t *)self->fun; + + // Determine start of prelude, and extract n_state from it +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-align" + uintptr_t prelude_offset = ((uintptr_t *)self_fun->bytecode)[0]; +#pragma GCC diagnostic pop + size_t n_state = mp_decode_uint_value(self_fun->bytecode + prelude_offset); + size_t n_exc_stack = 0; + + // Allocate the generator object, with room for local stack and exception stack + mp_obj_gen_instance_t *o = m_new_obj_var(mp_obj_gen_instance_t, byte, + n_state * sizeof(mp_obj_t) + n_exc_stack * sizeof(mp_exc_stack_t)); + o->base.type = &mp_type_gen_instance; + + // Parse the input arguments and set up the code state + o->coroutine_generator = self->coroutine_generator; + o->globals = self_fun->globals; + o->code_state.fun_bc = self_fun; + o->code_state.ip = (const byte *)prelude_offset; + mp_setup_code_state(&o->code_state, n_args, n_kw, args); + + // Indicate we are a native function, which doesn't use this variable + o->code_state.exc_sp = NULL; + + // Prepare the generator instance for execution +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-align" + uintptr_t start_offset = ((uintptr_t *)self_fun->bytecode)[1]; +#pragma GCC diagnostic pop + o->code_state.ip = MICROPY_MAKE_POINTER_CALLABLE((void *)(self_fun->bytecode + start_offset)); + + return MP_OBJ_FROM_PTR(o); +} + +#endif // MICROPY_EMIT_NATIVE + +STATIC mp_obj_t bc_gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_obj_gen_wrap_t *self = MP_OBJ_TO_PTR(self_in); mp_obj_fun_bc_t *self_fun = (mp_obj_fun_bc_t *)self->fun; assert(self_fun->base.type == &mp_type_fun_bc); @@ -74,13 +118,37 @@ STATIC mp_obj_t gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, cons return MP_OBJ_FROM_PTR(o); } +STATIC mp_obj_t gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_obj_gen_wrap_t *self = MP_OBJ_TO_PTR(self_in); + + #if MICROPY_EMIT_NATIVE + mp_obj_fun_bc_t *self_fun = (mp_obj_fun_bc_t *)self->fun; + if (self_fun->base.type == &mp_type_fun_native) { + return native_gen_wrap_call(self, n_args, n_kw, args); + } + #endif + return bc_gen_wrap_call(self, n_args, n_kw, args); +} + +#if MICROPY_PY_FUNCTION_ATTRS +static void gen_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { + mp_obj_gen_wrap_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_fun_bc_t *self_fun = (mp_obj_fun_bc_t *)self->fun; + mp_obj_fun_bc_attr(self_fun, attr, dest); +} +#endif + const mp_obj_type_t mp_type_gen_wrap = { { &mp_type_type }, .name = MP_QSTR_generator, .call = gen_wrap_call, .unary_op = mp_generic_unary_op, + #if MICROPY_PY_FUNCTION_ATTRS + .attr = gen_attr, + #endif }; + mp_obj_t mp_obj_new_gen_wrap(mp_obj_t fun, bool is_coroutine) { mp_obj_gen_wrap_t *o = m_new_obj(mp_obj_gen_wrap_t); o->base.type = &mp_type_gen_wrap; @@ -140,7 +208,22 @@ mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_ self->code_state.old_globals = mp_globals_get(); mp_globals_set(self->globals); self->globals = NULL; - mp_vm_return_kind_t ret_kind = mp_execute_bytecode(&self->code_state, throw_value); + + mp_vm_return_kind_t ret_kind; + + #if MICROPY_EMIT_NATIVE + if (self->code_state.exc_sp == NULL) { + // A native generator, with entry point 2 words into the "bytecode" pointer + typedef uintptr_t (*mp_fun_native_gen_t)(void *, mp_obj_t); + mp_fun_native_gen_t fun = MICROPY_MAKE_POINTER_CALLABLE((const void *)(self->code_state.fun_bc->bytecode + 2 * sizeof(uintptr_t))); + ret_kind = fun((void *)&self->code_state, throw_value); + } else + #endif + { + // A bytecode generator + ret_kind = mp_execute_bytecode(&self->code_state, throw_value); + } + self->globals = mp_globals_get(); mp_globals_set(self->code_state.old_globals); @@ -150,8 +233,6 @@ mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_ // Explicitly mark generator as completed. If we don't do this, // subsequent next() may re-execute statements after last yield // again and again, leading to side effects. - // TODO: check how return with value behaves under such conditions - // in CPython. self->code_state.ip = 0; *ret_val = *self->code_state.sp; break; @@ -164,9 +245,12 @@ mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_ break; case MP_VM_RETURN_EXCEPTION: { - size_t n_state = mp_decode_uint_value(self->code_state.fun_bc->bytecode); self->code_state.ip = 0; - *ret_val = self->code_state.state[n_state - 1]; + *ret_val = self->code_state.state[0]; + // PEP479: if StopIteration is raised inside a generator it is replaced with RuntimeError + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(*ret_val)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { + *ret_val = mp_obj_new_exception_msg(&mp_type_RuntimeError, translate("generator raised StopIteration")); + } break; } } @@ -190,15 +274,6 @@ STATIC mp_obj_t gen_resume_and_raise(mp_obj_t self_in, mp_obj_t send_value, mp_o return ret; case MP_VM_RETURN_EXCEPTION: - // TODO: Optimization of returning MP_OBJ_STOP_ITERATION is really part - // of mp_iternext() protocol, but this function is called by other methods - // too, which may not handled MP_OBJ_STOP_ITERATION. - if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { - mp_obj_t val = mp_obj_exception_get_value(ret); - if (val == mp_const_none) { - return MP_OBJ_STOP_ITERATION; - } - } nlr_raise(ret); } } @@ -260,11 +335,10 @@ STATIC mp_obj_t gen_instance_close(mp_obj_t self_in) { case MP_VM_RETURN_YIELD: mp_raise_RuntimeError(translate("generator ignored GeneratorExit")); - // Swallow StopIteration & GeneratorExit (== successful close), and re-raise any other + // Swallow GeneratorExit (== successful close), and re-raise any other case MP_VM_RETURN_EXCEPTION: // ret should always be an instance of an exception class - if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit)) || - mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { return mp_const_none; } nlr_raise(ret); diff --git a/py/objint.c b/py/objint.c index 50062351e6..ac9eb70591 100644 --- a/py/objint.c +++ b/py/objint.c @@ -64,14 +64,12 @@ STATIC mp_obj_t mp_obj_int_make_new(const mp_obj_type_t *type_in, size_t n_args, return mp_obj_new_int_from_float(mp_obj_float_get(args[0])); #endif } else { - // try to convert to small int (eg from bool) - return MP_OBJ_NEW_SMALL_INT(mp_obj_get_int(args[0])); + return mp_unary_op(MP_UNARY_OP_INT, args[0]); } case 2: default: { // should be a string, parse it - // TODO proper error checking of argument types size_t l; const char *s = mp_obj_str_get_data(args[0], &l); return mp_parse_num_integer(s, l, mp_obj_get_int(args[1]), NULL); diff --git a/py/objmodule.c b/py/objmodule.c index 0ac40229d4..efe4650157 100644 --- a/py/objmodule.c +++ b/py/objmodule.c @@ -64,6 +64,13 @@ STATIC void module_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { mp_map_elem_t *elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP); if (elem != NULL) { dest[0] = elem->value; + #if MICROPY_MODULE_GETATTR + } else if (attr != MP_QSTR___getattr__) { + elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(MP_QSTR___getattr__), MP_MAP_LOOKUP); + if (elem != NULL) { + dest[0] = mp_call_function_1(elem->value, MP_OBJ_NEW_QSTR(attr)); + } + #endif } } else { // delete/store attribute diff --git a/py/objnamedtuple.c b/py/objnamedtuple.c index 15b50c2d19..d1ca17c502 100644 --- a/py/objnamedtuple.c +++ b/py/objnamedtuple.c @@ -4,7 +4,7 @@ * The MIT License (MIT) * * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2014 Paul Sokolovsky + * SPDX-FileCopyrightText: Copyright (c) 2014 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -46,15 +46,21 @@ size_t mp_obj_namedtuple_find_field(const mp_obj_namedtuple_type_t *type, qstr n return (size_t)-1; } -#if MICROPY_PY_COLLECTIONS_ORDEREDDICT +#if MICROPY_PY_COLLECTIONS_NAMEDTUPLE__ASDICT STATIC mp_obj_t namedtuple_asdict(mp_obj_t self_in) { mp_obj_namedtuple_t *self = MP_OBJ_TO_PTR(self_in); const qstr *fields = ((mp_obj_namedtuple_type_t *)self->tuple.base.type)->fields; mp_obj_t dict = mp_obj_new_dict(self->tuple.len); - // make it an OrderedDict mp_obj_dict_t *dictObj = MP_OBJ_TO_PTR(dict); + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + // make it an OrderedDict dictObj->base.type = &mp_type_ordereddict; dictObj->map.is_ordered = 1; + #else + dictObj->base.type = &mp_type_dict; + dictObj->map.is_ordered = 0; + #endif + for (size_t i = 0; i < self->tuple.len; ++i) { mp_obj_dict_store(dict, MP_OBJ_NEW_QSTR(fields[i]), self->tuple.items[i]); } diff --git a/py/objslice.c b/py/objslice.c index a2beb7dd21..9bccde76db 100644 --- a/py/objslice.c +++ b/py/objslice.c @@ -38,8 +38,6 @@ #if MICROPY_PY_BUILTINS_SLICE -// TODO: This implements only variant of slice with 2 integer args only. -// CPython supports 3rd arg (step), plus args can be arbitrary Python objects. typedef struct _mp_obj_slice_t { mp_obj_base_t base; mp_obj_t start; diff --git a/py/objstr.c b/py/objstr.c index e3c0e78e31..a1c611e381 100644 --- a/py/objstr.c +++ b/py/objstr.c @@ -37,7 +37,9 @@ #include "supervisor/shared/translate.h" +#if MICROPY_PY_BUILTINS_STR_OP_MODULO STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict); +#endif STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf); STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in); @@ -317,6 +319,7 @@ const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { // check for modulo if (op == MP_BINARY_OP_MODULO) { + #if MICROPY_PY_BUILTINS_STR_OP_MODULO mp_obj_t *args = &rhs_in; size_t n_args = 1; mp_obj_t dict = MP_OBJ_NULL; @@ -327,6 +330,9 @@ mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i dict = rhs_in; } return str_modulo_format(lhs_in, n_args, args, dict); + #else + return MP_OBJ_NULL; + #endif } // from now on we need lhs type and data, so extract them @@ -947,6 +953,7 @@ STATIC bool arg_looks_numeric(mp_obj_t arg) { ; } +#if MICROPY_PY_BUILTINS_STR_OP_MODULO STATIC mp_obj_t arg_as_int(mp_obj_t arg) { #if MICROPY_PY_BUILTINS_FLOAT if (mp_obj_is_float(arg)) { @@ -955,6 +962,7 @@ STATIC mp_obj_t arg_as_int(mp_obj_t arg) { #endif return arg; } +#endif #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE STATIC NORETURN void terse_str_format_value_error(void) { @@ -1416,10 +1424,11 @@ mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs GET_STR_DATA_LEN(args[0], str, len); int arg_i = 0; vstr_t vstr = mp_obj_str_format_helper((const char *)str, (const char *)str + len, &arg_i, n_args, args, kwargs); - return mp_obj_new_str_from_vstr(&mp_type_str, &vstr); + return mp_obj_new_str_from_vstr(mp_obj_get_type(args[0]), &vstr); } MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format); +#if MICROPY_PY_BUILTINS_STR_OP_MODULO STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict) { mp_check_self(MP_OBJ_IS_STR_OR_BYTES(pattern)); @@ -1620,6 +1629,7 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ return mp_obj_new_str_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr); } +#endif // The implementation is optimized, returning the original string if there's // nothing to replace. @@ -1729,6 +1739,7 @@ STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) { } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace); +#if MICROPY_PY_BUILTINS_STR_COUNT STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) { const mp_obj_type_t *self_type = mp_obj_get_type(args[0]); mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0])); @@ -1769,6 +1780,7 @@ STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) { return MP_OBJ_NEW_SMALL_INT(num_occurrences); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count); +#endif #if MICROPY_PY_BUILTINS_STR_PARTITION STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) { @@ -1979,7 +1991,9 @@ STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) }, { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) }, { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) }, + #if MICROPY_PY_BUILTINS_STR_COUNT { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) }, + #endif #if MICROPY_PY_BUILTINS_STR_PARTITION { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) }, { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) }, diff --git a/py/objstringio.c b/py/objstringio.c index cc853aba6d..793ec84f31 100644 --- a/py/objstringio.c +++ b/py/objstringio.c @@ -196,22 +196,18 @@ STATIC mp_obj_t stringio_make_new(const mp_obj_type_t *type_in, size_t n_args, c mp_obj_stringio_t *o = stringio_new(type_in); if (n_args > 0) { - if (MP_OBJ_IS_INT(args[0])) { - sz = mp_obj_get_int(args[0]); - } else { - mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); + mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); - if (MP_OBJ_IS_STR_OR_BYTES(args[0])) { - o->vstr = m_new_obj(vstr_t); - vstr_init_fixed_buf(o->vstr, bufinfo.len, bufinfo.buf); - o->vstr->len = bufinfo.len; - o->ref_obj = args[0]; - return MP_OBJ_FROM_PTR(o); - } - - sz = bufinfo.len; - initdata = true; + if (MP_OBJ_IS_STR_OR_BYTES(args[0])) { + o->vstr = m_new_obj(vstr_t); + vstr_init_fixed_buf(o->vstr, bufinfo.len, bufinfo.buf); + o->vstr->len = bufinfo.len; + o->ref_obj = args[0]; + return MP_OBJ_FROM_PTR(o); } + + sz = bufinfo.len; + initdata = true; } o->vstr = vstr_new(sz); diff --git a/py/objstrunicode.c b/py/objstrunicode.c index c86d48e63c..d77bbeebcd 100644 --- a/py/objstrunicode.c +++ b/py/objstrunicode.c @@ -264,7 +264,9 @@ STATIC const mp_rom_map_elem_t struni_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) }, { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) }, { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) }, + #if MICROPY_PY_BUILTINS_STR_COUNT { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) }, + #endif #if MICROPY_PY_BUILTINS_STR_PARTITION { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) }, { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) }, diff --git a/py/objtype.c b/py/objtype.c index b7b2d156b2..1f9bc386ad 100644 --- a/py/objtype.c +++ b/py/objtype.c @@ -190,11 +190,13 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_t mp_convert_member_lookup(MP_OBJ_FROM_PTR(obj), type, elem->value, lookup->dest); } #if DEBUG_PRINT - printf("mp_obj_class_lookup: Returning: "); - mp_obj_print(lookup->dest[0], PRINT_REPR); - printf(" "); - // Don't try to repr() lookup->dest[1], as we can be called recursively - printf("<%q @%p>\n", mp_obj_get_type_qstr(lookup->dest[1]), lookup->dest[1]); + DEBUG_printf("mp_obj_class_lookup: Returning: "); + mp_obj_print_helper(MICROPY_DEBUG_PRINTER, lookup->dest[0], PRINT_REPR); + if (lookup->dest[1] != MP_OBJ_NULL) { + // Don't try to repr() lookup->dest[1], as we can be called recursively + DEBUG_printf(" <%s @%p>", mp_obj_get_type_str(lookup->dest[1]), MP_OBJ_TO_PTR(lookup->dest[1])); + } + DEBUG_printf("\n"); #endif return; } @@ -399,6 +401,7 @@ const byte mp_unary_op_method_name[MP_UNARY_OP_NUM_RUNTIME] = { [MP_UNARY_OP_BOOL] = MP_QSTR___bool__, [MP_UNARY_OP_LEN] = MP_QSTR___len__, [MP_UNARY_OP_HASH] = MP_QSTR___hash__, + [MP_UNARY_OP_INT] = MP_QSTR___int__, #if MICROPY_PY_ALL_SPECIAL_METHODS [MP_UNARY_OP_POSITIVE] = MP_QSTR___pos__, [MP_UNARY_OP_NEGATIVE] = MP_QSTR___neg__, @@ -444,9 +447,21 @@ STATIC mp_obj_t instance_unary_op(mp_unary_op_t op, mp_obj_t self_in) { return mp_unary_op(op, self->subobj[0]); } else if (member[0] != MP_OBJ_NULL) { mp_obj_t val = mp_call_function_1(member[0], self_in); - // __hash__ must return a small int - if (op == MP_UNARY_OP_HASH) { - val = MP_OBJ_NEW_SMALL_INT(mp_obj_get_int_truncated(val)); + + switch (op) { + case MP_UNARY_OP_HASH: + // __hash__ must return a small int + val = MP_OBJ_NEW_SMALL_INT(mp_obj_get_int_truncated(val)); + break; + case MP_UNARY_OP_INT: + // Must return int + if (!MP_OBJ_IS_INT(val)) { + mp_raise_TypeError(NULL); + } + break; + default: + // No need to do anything + ; } return val; } else { @@ -483,8 +498,7 @@ const byte mp_binary_op_method_name[MP_BINARY_OP_NUM_RUNTIME] = { // MP_BINARY_OP_NOT_EQUAL, // a != b calls a == b and inverts result [MP_BINARY_OP_CONTAINS] = MP_QSTR___contains__, - // All inplace methods are optional, and normal methods will be used - // as a fallback. + // If an inplace method is not found a normal method will be used as a fallback [MP_BINARY_OP_INPLACE_ADD] = MP_QSTR___iadd__, [MP_BINARY_OP_INPLACE_SUBTRACT] = MP_QSTR___isub__, #if MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS @@ -679,7 +693,6 @@ STATIC void mp_obj_instance_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *des mp_load_method_maybe(self_in, MP_QSTR___getattr__, dest2); if (dest2[0] != MP_OBJ_NULL) { // __getattr__ exists, call it and return its result - // XXX if this fails to load the requested attr, should we catch the attribute error and return silently? dest2[2] = MP_OBJ_NEW_QSTR(attr); dest[0] = mp_call_method_n_kw(1, 0, dest2); return; @@ -822,41 +835,32 @@ STATIC void mp_obj_instance_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { STATIC mp_obj_t instance_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in); - mp_obj_t member[2] = {MP_OBJ_NULL}; + mp_obj_t member[4] = {MP_OBJ_NULL, MP_OBJ_NULL, index, value}; struct class_lookup_data lookup = { .obj = self, .meth_offset = offsetof(mp_obj_type_t, subscr), .dest = member, .is_type = false, }; - size_t meth_args; if (value == MP_OBJ_NULL) { // delete item lookup.attr = MP_QSTR___delitem__; - mp_obj_class_lookup(&lookup, self->base.type); - meth_args = 2; } else if (value == MP_OBJ_SENTINEL) { // load item lookup.attr = MP_QSTR___getitem__; - mp_obj_class_lookup(&lookup, self->base.type); - meth_args = 2; } else { // store item lookup.attr = MP_QSTR___setitem__; - mp_obj_class_lookup(&lookup, self->base.type); - meth_args = 3; } - if (member[0] == MP_OBJ_SENTINEL) { // native base subscr exists - mp_obj_type_t *subobj_type = mp_obj_get_type(self->subobj[0]); - // return mp_obj_subscr(self->subobj[0], index, value, instance); - mp_obj_t ret = subobj_type->subscr(self_in, index, value); + mp_obj_class_lookup(&lookup, self->base.type); + if (member[0] == MP_OBJ_SENTINEL) { + mp_obj_t ret = mp_obj_subscr(self->subobj[0], index, value); // May have called port specific C code. Make sure it didn't mess up the heap. assert_heap_ok(); return ret; } else if (member[0] != MP_OBJ_NULL) { - mp_obj_t args[3] = {self_in, index, value}; - // TODO probably need to call mp_convert_member_lookup, and use mp_call_method_n_kw - mp_obj_t ret = mp_call_function_n_kw(member[0], meth_args, 0, args); + size_t n_args = value == MP_OBJ_NULL || value == MP_OBJ_SENTINEL ? 1 : 2; + mp_obj_t ret = mp_call_method_n_kw(n_args, 0, member); if (value == MP_OBJ_SENTINEL) { return ret; } else { @@ -1064,8 +1068,6 @@ STATIC void type_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { } else { // delete/store attribute - // TODO CPython allows STORE_ATTR to a class, but is this the correct implementation? - if (self->locals_dict != NULL) { assert(self->locals_dict->base.type == &mp_type_dict); // MicroPython restriction, for now mp_map_t *locals_map = &self->locals_dict->map; diff --git a/py/parsenum.c b/py/parsenum.c index 96f05ff82e..ec27d04e43 100644 --- a/py/parsenum.c +++ b/py/parsenum.c @@ -177,14 +177,20 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool // DEC_VAL_MAX only needs to be rough and is used to retain precision while not overflowing // SMALL_NORMAL_VAL is the smallest power of 10 that is still a normal float +// EXACT_POWER_OF_10 is the largest value of x so that 10^x can be stored exactly in a float +// Note: EXACT_POWER_OF_10 is at least floor(log_5(2^mantissa_length)). Indeed, 10^n = 2^n * 5^n +// so we only have to store the 5^n part in the mantissa (the 2^n part will go into the float's +// exponent). #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT #define DEC_VAL_MAX 1e20F #define SMALL_NORMAL_VAL (1e-37F) #define SMALL_NORMAL_EXP (-37) +#define EXACT_POWER_OF_10 (9) #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE #define DEC_VAL_MAX 1e200 #define SMALL_NORMAL_VAL (1e-307) #define SMALL_NORMAL_EXP (-307) +#define EXACT_POWER_OF_10 (22) #endif const char *top = str + len; @@ -297,7 +303,17 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool exp_val -= SMALL_NORMAL_EXP; dec_val *= SMALL_NORMAL_VAL; } - dec_val *= MICROPY_FLOAT_C_FUN(pow)(10, exp_val); + + // At this point, we need to multiply the mantissa by its base 10 exponent. If possible, + // we would rather manipulate numbers that have an exact representation in IEEE754. It + // turns out small positive powers of 10 do, whereas small negative powers of 10 don't. + // So in that case, we'll yield a division of exact values rather than a multiplication + // of slightly erroneous values. + if (exp_val < 0 && exp_val >= -EXACT_POWER_OF_10) { + dec_val /= MICROPY_FLOAT_C_FUN(pow)(10, -exp_val); + } else { + dec_val *= MICROPY_FLOAT_C_FUN(pow)(10, exp_val); + } } // negate value if needed diff --git a/py/py.mk b/py/py.mk index ae12e1976d..f61bad1faf 100644 --- a/py/py.mk +++ b/py/py.mk @@ -79,7 +79,7 @@ endif ifeq ($(MICROPY_PY_BTREE),1) BTREE_DIR = lib/berkeley-db-1.xx -BTREE_DEFS = -D__DBINTERFACE_PRIVATE=1 -Dmpool_error=printf -Dabort=abort_ -Dvirt_fd_t=mp_obj_t "-DVIRT_FD_T_HEADER=" $(BTREE_DEFS_EXTRA) +BTREE_DEFS = -D__DBINTERFACE_PRIVATE=1 -Dmpool_error=printf -Dabort=abort_ "-Dvirt_fd_t=void*" $(BTREE_DEFS_EXTRA) INC += -I$(TOP)/$(BTREE_DIR)/PORT/include SRC_MOD += extmod/modbtree.c SRC_MOD += $(addprefix $(BTREE_DIR)/,\ @@ -261,12 +261,8 @@ PY_EXTMOD_O_BASENAME = \ extmod/moduhashlib.o \ extmod/modubinascii.o \ extmod/virtpin.o \ - extmod/modussl_axtls.o \ - extmod/modussl_mbedtls.o \ extmod/modurandom.o \ extmod/moduselect.o \ - extmod/modwebsocket.o \ - extmod/modwebrepl.o \ extmod/modframebuf.o \ extmod/vfs.o \ extmod/vfs_reader.o \ @@ -379,7 +375,7 @@ endif # may require disabling tail jump optimization. This will make sure that # each opcode has its own dispatching jump which will improve branch # branch predictor efficiency. -# http://article.gmane.org/gmane.comp.lang.lua.general/75426 +# https://marc.info/?l=lua-l&m=129778596120851 # http://hg.python.org/cpython/file/b127046831e2/Python/ceval.c#l828 # http://www.emulators.com/docs/nx25_nostradamus.htm #-fno-crossjumping diff --git a/py/qstr.c b/py/qstr.c index 2ae65379c7..a10adc578a 100644 --- a/py/qstr.c +++ b/py/qstr.c @@ -37,7 +37,6 @@ // NOTE: we are using linear arrays to store and search for qstr's (unique strings, interned strings) // ultimately we will replace this with a static hash table of some kind -// also probably need to include the length in the string data, to allow null bytes in the string #if MICROPY_DEBUG_VERBOSE // print debugging info #define DEBUG_printf DEBUG_printf @@ -46,34 +45,9 @@ #endif // A qstr is an index into the qstr pool. -// The data for a qstr contains (hash, length, data): -// - hash (configurable number of bytes) -// - length (configurable number of bytes) -// - data ("length" number of bytes) -// - \0 terminated (so they can be printed using printf) +// The data for a qstr is \0 terminated (so they can be printed using printf) -#if MICROPY_QSTR_BYTES_IN_HASH == 1 - #define Q_HASH_MASK (0xff) - #define Q_GET_HASH(q) ((mp_uint_t)(q)[0]) - #define Q_SET_HASH(q, hash) do { (q)[0] = (hash); } while (0) -#elif MICROPY_QSTR_BYTES_IN_HASH == 2 - #define Q_HASH_MASK (0xffff) - #define Q_GET_HASH(q) ((mp_uint_t)(q)[0] | ((mp_uint_t)(q)[1] << 8)) - #define Q_SET_HASH(q, hash) do { (q)[0] = (hash); (q)[1] = (hash) >> 8; } while (0) -#else - #error unimplemented qstr hash decoding -#endif -#define Q_GET_ALLOC(q) (MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + Q_GET_LENGTH(q) + 1) -#define Q_GET_DATA(q) ((q) + MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN) -#if MICROPY_QSTR_BYTES_IN_LEN == 1 - #define Q_GET_LENGTH(q) ((q)[MICROPY_QSTR_BYTES_IN_HASH]) - #define Q_SET_LENGTH(q, len) do { (q)[MICROPY_QSTR_BYTES_IN_HASH] = (len); } while (0) -#elif MICROPY_QSTR_BYTES_IN_LEN == 2 - #define Q_GET_LENGTH(q) ((q)[MICROPY_QSTR_BYTES_IN_HASH] | ((q)[MICROPY_QSTR_BYTES_IN_HASH + 1] << 8)) - #define Q_SET_LENGTH(q, len) do { (q)[MICROPY_QSTR_BYTES_IN_HASH] = (len); (q)[MICROPY_QSTR_BYTES_IN_HASH + 1] = (len) >> 8; } while (0) -#else - #error unimplemented qstr length decoding -#endif +#define Q_HASH_MASK ((1 << (8 * MICROPY_QSTR_BYTES_IN_HASH)) - 1) #if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL #define QSTR_ENTER() mp_thread_mutex_lock(&MP_STATE_VM(qstr_mutex), 1) @@ -83,6 +57,10 @@ #define QSTR_EXIT() #endif +// Initial number of entries for qstr pool, set so that the first dynamically +// allocated pool is twice this size. The value here must be <= MP_QSTRnumber_of. +#define MICROPY_ALLOC_QSTR_ENTRIES_INIT (10) + // this must match the equivalent function in makeqstrdata.py mp_uint_t qstr_compute_hash(const byte *data, size_t len) { // djb2 algorithm; see http://www.cse.yorku.ca/~oz/hash.html @@ -98,14 +76,25 @@ mp_uint_t qstr_compute_hash(const byte *data, size_t len) { return hash; } +const qstr_attr_t mp_qstr_const_attr[] = { + #ifndef NO_QSTR +#define QDEF(id, hash, len, str) { hash, len }, +#define TRANSLATION(id, length, compressed ...) + #include "genhdr/qstrdefs.generated.h" +#undef TRANSLATION +#undef QDEF + #endif +}; + const qstr_pool_t mp_qstr_const_pool = { NULL, // no previous pool 0, // no previous pool - 10, // set so that the first dynamically allocated pool is twice this size; must be <= the len (just below) + MICROPY_ALLOC_QSTR_ENTRIES_INIT, MP_QSTRnumber_of, // corresponds to number of strings in array just below + (qstr_attr_t *)mp_qstr_const_attr, { #ifndef NO_QSTR -#define QDEF(id, str) str, +#define QDEF(id, hash, len, str) str, #define TRANSLATION(id, length, compressed ...) #include "genhdr/qstrdefs.generated.h" #undef TRANSLATION @@ -130,20 +119,22 @@ void qstr_init(void) { #endif } -STATIC const byte *find_qstr(qstr q) { +STATIC const char *find_qstr(qstr q, qstr_attr_t *attr) { // search pool for this qstr // total_prev_len==0 in the final pool, so the loop will always terminate qstr_pool_t *pool = MP_STATE_VM(last_pool); while (q < pool->total_prev_len) { pool = pool->prev; } - assert(q - pool->total_prev_len < pool->len); - return pool->qstrs[q - pool->total_prev_len]; + q -= pool->total_prev_len; + assert(q < pool->len); + *attr = pool->attrs[q]; + return pool->qstrs[q]; } // qstr_mutex must be taken while in this function -STATIC qstr qstr_add(const byte *q_ptr) { - DEBUG_printf("QSTR: add hash=%d len=%d data=%.*s\n", Q_GET_HASH(q_ptr), Q_GET_LENGTH(q_ptr), Q_GET_LENGTH(q_ptr), Q_GET_DATA(q_ptr)); +STATIC qstr qstr_add(mp_uint_t hash, mp_uint_t len, const char *q_ptr) { + DEBUG_printf("QSTR: add hash=%d len=%d data=%.*s\n", hash, len, len, q_ptr); // make sure we have room in the pool for a new qstr if (MP_STATE_VM(last_pool)->len >= MP_STATE_VM(last_pool)->alloc) { @@ -151,11 +142,20 @@ STATIC qstr qstr_add(const byte *q_ptr) { if (new_pool_length > MICROPY_QSTR_POOL_MAX_ENTRIES) { new_pool_length = MICROPY_QSTR_POOL_MAX_ENTRIES; } - qstr_pool_t *pool = m_new_ll_obj_var_maybe(qstr_pool_t, const char *, new_pool_length); - if (pool == NULL) { + #ifdef MICROPY_QSTR_EXTRA_POOL + // Put a lower bound on the allocation size in case the extra qstr pool has few entries + if (new_pool_length < MICROPY_ALLOC_QSTR_ENTRIES_INIT) { + new_pool_length = MICROPY_ALLOC_QSTR_ENTRIES_INIT; + } + #endif + mp_uint_t pool_size = sizeof(qstr_pool_t) + sizeof(const char *) * new_pool_length; + void *chunk = m_malloc_maybe(pool_size + sizeof(qstr_attr_t) * new_pool_length, true); + if (chunk == NULL) { QSTR_EXIT(); m_malloc_fail(new_pool_length); } + qstr_pool_t *pool = (qstr_pool_t *)chunk; + pool->attrs = (qstr_attr_t *)(void *)((char *)chunk + pool_size); pool->prev = MP_STATE_VM(last_pool); pool->total_prev_len = MP_STATE_VM(last_pool)->total_prev_len + MP_STATE_VM(last_pool)->len; pool->alloc = new_pool_length; @@ -165,10 +165,14 @@ STATIC qstr qstr_add(const byte *q_ptr) { } // add the new qstr - MP_STATE_VM(last_pool)->qstrs[MP_STATE_VM(last_pool)->len++] = q_ptr; + mp_uint_t at = MP_STATE_VM(last_pool)->len; + MP_STATE_VM(last_pool)->attrs[at].hash = hash; + MP_STATE_VM(last_pool)->attrs[at].len = len; + MP_STATE_VM(last_pool)->qstrs[at] = q_ptr; + MP_STATE_VM(last_pool)->len++; // return id for the newly-added qstr - return MP_STATE_VM(last_pool)->total_prev_len + MP_STATE_VM(last_pool)->len - 1; + return MP_STATE_VM(last_pool)->total_prev_len + at; } qstr qstr_find_strn(const char *str, size_t str_len) { @@ -177,9 +181,10 @@ qstr qstr_find_strn(const char *str, size_t str_len) { // search pools for the data for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL; pool = pool->prev) { - for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) { - if (Q_GET_HASH(*q) == str_hash && Q_GET_LENGTH(*q) == str_len && memcmp(Q_GET_DATA(*q), str, str_len) == 0) { - return pool->total_prev_len + (q - pool->qstrs); + qstr_attr_t *attrs = pool->attrs; + for (mp_uint_t at = 0, top = pool->len; at < top; at++) { + if (attrs[at].hash == str_hash && attrs[at].len == str_len && memcmp(pool->qstrs[at], str, str_len) == 0) { + return pool->total_prev_len + at; } } } @@ -200,14 +205,14 @@ qstr qstr_from_strn(const char *str, size_t len) { // qstr does not exist in interned pool so need to add it // compute number of bytes needed to intern this string - size_t n_bytes = MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + len + 1; + size_t n_bytes = len + 1; if (MP_STATE_VM(qstr_last_chunk) != NULL && MP_STATE_VM(qstr_last_used) + n_bytes > MP_STATE_VM(qstr_last_alloc)) { // not enough room at end of previously interned string so try to grow - byte *new_p = m_renew_maybe(byte, MP_STATE_VM(qstr_last_chunk), MP_STATE_VM(qstr_last_alloc), MP_STATE_VM(qstr_last_alloc) + n_bytes, false); + char *new_p = m_renew_maybe(char, MP_STATE_VM(qstr_last_chunk), MP_STATE_VM(qstr_last_alloc), MP_STATE_VM(qstr_last_alloc) + n_bytes, false); if (new_p == NULL) { // could not grow existing memory; shrink it to fit previous - (void)m_renew_maybe(byte, MP_STATE_VM(qstr_last_chunk), MP_STATE_VM(qstr_last_alloc), MP_STATE_VM(qstr_last_used), false); + (void)m_renew_maybe(char, MP_STATE_VM(qstr_last_chunk), MP_STATE_VM(qstr_last_alloc), MP_STATE_VM(qstr_last_used), false); MP_STATE_VM(qstr_last_chunk) = NULL; } else { // could grow existing memory @@ -221,10 +226,10 @@ qstr qstr_from_strn(const char *str, size_t len) { if (al < MICROPY_ALLOC_QSTR_CHUNK_INIT) { al = MICROPY_ALLOC_QSTR_CHUNK_INIT; } - MP_STATE_VM(qstr_last_chunk) = m_new_ll_maybe(byte, al); + MP_STATE_VM(qstr_last_chunk) = m_new_ll_maybe(char, al); if (MP_STATE_VM(qstr_last_chunk) == NULL) { // failed to allocate a large chunk so try with exact size - MP_STATE_VM(qstr_last_chunk) = m_new_ll_maybe(byte, n_bytes); + MP_STATE_VM(qstr_last_chunk) = m_new_ll_maybe(char, n_bytes); if (MP_STATE_VM(qstr_last_chunk) == NULL) { QSTR_EXIT(); m_malloc_fail(n_bytes); @@ -236,39 +241,41 @@ qstr qstr_from_strn(const char *str, size_t len) { } // allocate memory from the chunk for this new interned string's data - byte *q_ptr = MP_STATE_VM(qstr_last_chunk) + MP_STATE_VM(qstr_last_used); + char *q_ptr = MP_STATE_VM(qstr_last_chunk) + MP_STATE_VM(qstr_last_used); MP_STATE_VM(qstr_last_used) += n_bytes; // store the interned strings' data mp_uint_t hash = qstr_compute_hash((const byte *)str, len); - Q_SET_HASH(q_ptr, hash); - Q_SET_LENGTH(q_ptr, len); - memcpy(q_ptr + MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN, str, len); - q_ptr[MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + len] = '\0'; - q = qstr_add(q_ptr); + memcpy(q_ptr, str, len); + q_ptr[len] = '\0'; + q = qstr_add(hash, len, q_ptr); } QSTR_EXIT(); return q; } mp_uint_t PLACE_IN_ITCM(qstr_hash)(qstr q) { - return Q_GET_HASH(find_qstr(q)); + qstr_attr_t attr; + find_qstr(q, &attr); + return attr.hash; } size_t qstr_len(qstr q) { - const byte *qd = find_qstr(q); - return Q_GET_LENGTH(qd); + qstr_attr_t attr; + find_qstr(q, &attr); + return attr.len; } const char *qstr_str(qstr q) { - const byte *qd = find_qstr(q); - return (const char *)Q_GET_DATA(qd); + qstr_attr_t attr; + return find_qstr(q, &attr); } const byte *qstr_data(qstr q, size_t *len) { - const byte *qd = find_qstr(q); - *len = Q_GET_LENGTH(qd); - return Q_GET_DATA(qd); + qstr_attr_t attr; + const char *qd = find_qstr(q, &attr); + *len = attr.len; + return (byte *)qd; } void qstr_pool_info(size_t *n_pool, size_t *n_qstr, size_t *n_str_data_bytes, size_t *n_total_bytes) { @@ -280,13 +287,14 @@ void qstr_pool_info(size_t *n_pool, size_t *n_qstr, size_t *n_str_data_bytes, si for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL && pool != &CONST_POOL; pool = pool->prev) { *n_pool += 1; *n_qstr += pool->len; - for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) { - *n_str_data_bytes += Q_GET_ALLOC(*q); + for (const qstr_attr_t *q = pool->attrs, *q_top = pool->attrs + pool->len; q < q_top; q++) { + *n_str_data_bytes += sizeof(*q) + q->len + 1; } #if MICROPY_ENABLE_GC - *n_total_bytes += gc_nbytes(pool); // this counts actual bytes used in heap + // this counts actual bytes used in heap + *n_total_bytes += gc_nbytes(pool) - sizeof(qstr_attr_t) * pool->alloc; #else - *n_total_bytes += sizeof(qstr_pool_t) + sizeof(qstr) * pool->alloc; + *n_total_bytes += sizeof(qstr_pool_t) + sizeof(const char *) * pool->alloc; #endif } *n_total_bytes += *n_str_data_bytes; @@ -297,8 +305,8 @@ void qstr_pool_info(size_t *n_pool, size_t *n_qstr, size_t *n_str_data_bytes, si void qstr_dump_data(void) { QSTR_ENTER(); for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL && pool != &CONST_POOL; pool = pool->prev) { - for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) { - mp_printf(&mp_plat_print, "Q(%s)\n", Q_GET_DATA(*q)); + for (const char **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) { + mp_printf(&mp_plat_print, "Q(%s)\n", *q); } } QSTR_EXIT(); diff --git a/py/qstr.h b/py/qstr.h index c86e74324c..288bf5dbac 100644 --- a/py/qstr.h +++ b/py/qstr.h @@ -47,12 +47,30 @@ enum { typedef size_t qstr; +typedef struct _qstr_attr_t { + #if MICROPY_QSTR_BYTES_IN_HASH == 1 + uint8_t hash; + #elif MICROPY_QSTR_BYTES_IN_HASH == 2 + uint16_t hash; + #else + #error unimplemented qstr hash decoding + #endif + #if MICROPY_QSTR_BYTES_IN_LEN == 1 + uint8_t len; + #elif MICROPY_QSTR_BYTES_IN_LEN == 2 + uint16_t len; + #else + #error unimplemented qstr length decoding + #endif +} qstr_attr_t; + typedef struct _qstr_pool_t { struct _qstr_pool_t *prev; size_t total_prev_len; size_t alloc; size_t len; - const byte *qstrs[]; + qstr_attr_t *attrs; + const char *qstrs[]; } qstr_pool_t; #define QSTR_FROM_STR_STATIC(s) (qstr_from_strn((s), strlen(s))) diff --git a/py/qstrdefs.h b/py/qstrdefs.h index 04ee03d737..6337399d16 100644 --- a/py/qstrdefs.h +++ b/py/qstrdefs.h @@ -39,8 +39,13 @@ Q() Q(*) Q(_) Q(/) +#if MICROPY_PY_BUILTINS_STR_OP_MODULO Q(%#o) Q(%#x) +#else +Q({:#o}) +Q({:#x}) +#endif Q({:#b}) Q( ) Q(\n) diff --git a/py/repl.c b/py/repl.c index ccc8dd5c6b..6cc10bb007 100644 --- a/py/repl.c +++ b/py/repl.c @@ -281,6 +281,12 @@ size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print ++str; } + // after "import", suggest built-in modules + static const char import_str[] = "import "; + if (len >= 7 && !memcmp(org_str, import_str, 7)) { + obj = MP_OBJ_NULL; + } + // look for matches size_t match_len; qstr q_first, q_last; @@ -291,19 +297,12 @@ size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print if (q_first == 0) { // If there're no better alternatives, and if it's first word // in the line, try to complete "import". - static const char import_str[] = "import "; if (s_start == org_str && s_len > 0) { if (memcmp(s_start, import_str, s_len) == 0) { *compl_str = import_str + s_len; return sizeof(import_str) - 1 - s_len; } } - // after "import", suggest built-in modules - if (len >= 7 && !memcmp(org_str, import_str, 7)) { - obj = NULL; - match_str = find_completions( - s_start, s_len, obj, &match_len, &q_first, &q_last); - } if (q_first == 0) { *compl_str = " "; return s_len ? 0 : 4; diff --git a/py/runtime.c b/py/runtime.c index 28ecddd786..72eb2fa4c5 100644 --- a/py/runtime.c +++ b/py/runtime.c @@ -139,11 +139,13 @@ void mp_init(void) { } void mp_deinit(void) { + MP_THREAD_GIL_EXIT(); + // mp_obj_dict_free(&dict_main); // mp_map_deinit(&MP_STATE_VM(mp_loaded_modules_map)); // call port specific deinitialization if any - #ifdef MICROPY_PORT_INIT_FUNC + #ifdef MICROPY_PORT_DEINIT_FUNC MICROPY_PORT_DEINIT_FUNC; #endif } @@ -238,6 +240,7 @@ mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) { case MP_UNARY_OP_HASH: return arg; case MP_UNARY_OP_POSITIVE: + case MP_UNARY_OP_INT: return arg; case MP_UNARY_OP_NEGATIVE: // check for overflow @@ -275,13 +278,22 @@ mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) { return result; } } - #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("unsupported type for operator")); - #else - mp_raise_TypeError_varg( - translate("unsupported type for %q: '%q'"), - mp_unary_op_method_name[op], mp_obj_get_type_qstr(arg)); - #endif + // With MP_UNARY_OP_INT, mp_unary_op() becomes a fallback for mp_obj_get_int(). + // In this case provide a more focused error message to not confuse, e.g. chr(1.0) + if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { + if (op == MP_UNARY_OP_INT) { + mp_raise_TypeError(translate("can't convert to int")); + } else { + mp_raise_TypeError(translate("unsupported type for operator")); + } + } else { + if (op == MP_UNARY_OP_INT) { + mp_raise_TypeError_varg(translate("can't convert %q to int"), mp_obj_get_type_qstr(arg)); + } else { + mp_raise_TypeError_varg(translate("unsupported type for %q: '%q'"), + mp_unary_op_method_name[op], mp_obj_get_type_qstr(arg)); + } + } } } @@ -520,11 +532,11 @@ mp_obj_t PLACE_IN_ITCM(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t r default: goto unsupported_op; } - // TODO: We just should make mp_obj_new_int() inline and use that + // This is an inlined version of mp_obj_new_int, for speed if (MP_SMALL_INT_FITS(lhs_val)) { return MP_OBJ_NEW_SMALL_INT(lhs_val); } else { - return mp_obj_new_int(lhs_val); + return mp_obj_new_int_from_ll(lhs_val); } #if MICROPY_PY_BUILTINS_FLOAT } else if (mp_obj_is_float(rhs)) { @@ -1322,15 +1334,8 @@ mp_vm_return_kind_t mp_resume(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t th if (send_value == mp_const_none) { mp_load_method_maybe(self_in, MP_QSTR___next__, dest); if (dest[0] != MP_OBJ_NULL) { - nlr_buf_t nlr; - if (nlr_push(&nlr) == 0) { - *ret_val = mp_call_method_n_kw(0, 0, dest); - nlr_pop(); - return MP_VM_RETURN_YIELD; - } else { - *ret_val = MP_OBJ_FROM_PTR(nlr.ret_val); - return MP_VM_RETURN_EXCEPTION; - } + *ret_val = mp_call_method_n_kw(0, 0, dest); + return MP_VM_RETURN_YIELD; } } @@ -1339,10 +1344,6 @@ mp_vm_return_kind_t mp_resume(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t th if (send_value != MP_OBJ_NULL) { mp_load_method(self_in, MP_QSTR_send, dest); dest[2] = send_value; - // TODO: This should have exception wrapping like __next__ case - // above. Not done right away to think how to optimize native - // generators better, see: - // https://github.com/micropython/micropython/issues/2628 *ret_val = mp_call_method_n_kw(1, 0, dest); return MP_VM_RETURN_YIELD; } @@ -1404,7 +1405,7 @@ mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) { args[1] = mp_const_none; // TODO should be globals args[2] = mp_const_none; // TODO should be locals args[3] = fromlist; - args[4] = level; // must be 0; we don't yet support other values + args[4] = level; // TODO lookup __import__ and call that instead of going straight to builtin implementation return mp_builtin___import__(5, args); @@ -1446,15 +1447,8 @@ mp_obj_t mp_import_from(mp_obj_t module, qstr name) { qstr dot_name_q = qstr_from_strn(dot_name, dot_name_len); mp_local_free(dot_name); - mp_obj_t args[5]; - args[0] = MP_OBJ_NEW_QSTR(dot_name_q); - args[1] = mp_const_none; // TODO should be globals - args[2] = mp_const_none; // TODO should be locals - args[3] = mp_const_true; // Pass sentinel "non empty" value to force returning of leaf module - args[4] = MP_OBJ_NEW_SMALL_INT(0); - - // TODO lookup __import__ and call that instead of going straight to builtin implementation - return mp_builtin___import__(5, args); + // For fromlist, pass sentinel "non empty" value to force returning of leaf module + return mp_import_name(dot_name_q, mp_const_true, MP_OBJ_NEW_SMALL_INT(0)); #else @@ -1468,12 +1462,16 @@ void mp_import_all(mp_obj_t module) { DEBUG_printf("import all %p\n", module); // TODO: Support __all__ - mp_map_t *map = mp_obj_dict_get_map(MP_OBJ_FROM_PTR(mp_obj_module_get_globals(module))); + mp_map_t *map = &mp_obj_module_get_globals(module)->map; for (size_t i = 0; i < map->alloc; i++) { if (MP_MAP_SLOT_IS_FILLED(map, i)) { - qstr name = MP_OBJ_QSTR_VALUE(map->table[i].key); - if (*qstr_str(name) != '_') { - mp_store_name(name, map->table[i].value); + // Entry in module global scope may be generated programmatically + // (and thus be not a qstr for longer names). Avoid turning it in + // qstr if it has '_' and was used exactly to save memory. + const char *name = mp_obj_str_get_str(map->table[i].key); + if (*name != '_') { + qstr qname = mp_obj_str_get_qstr(map->table[i].key); + mp_store_name(qname, map->table[i].value); } } } diff --git a/py/runtime.h b/py/runtime.h index 74307d87cb..c30252a946 100644 --- a/py/runtime.h +++ b/py/runtime.h @@ -81,9 +81,10 @@ bool mp_sched_schedule(mp_obj_t function, mp_obj_t arg); // extra printing method specifically for mp_obj_t's which are integral type int mp_print_mp_int(const mp_print_t *print, mp_obj_t x, int base, int base_char, int flags, char fill, int width, int prec); +void mp_arg_check_num_sig(size_t n_args, size_t n_kw, uint32_t sig); void mp_arg_check_num(size_t n_args, mp_map_t *kw_args, size_t n_args_min, size_t n_args_max, bool takes_kw); -void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals); void mp_arg_check_num_kw_array(size_t n_args, size_t n_kw, size_t n_args_min, size_t n_args_max, bool takes_kw); +void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals); void mp_arg_parse_all_kw_array(size_t n_pos, size_t n_kw, const mp_obj_t *args, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals); NORETURN void mp_arg_error_terse_mismatch(void); NORETURN void mp_arg_error_unimpl_kw(void); @@ -198,6 +199,7 @@ NORETURN void mp_raise_recursion_depth(void); // helper functions for native/viper code mp_uint_t mp_convert_obj_to_native(mp_obj_t obj, mp_uint_t type); mp_obj_t mp_convert_native_to_obj(mp_uint_t val, mp_uint_t type); +mp_obj_dict_t *mp_native_swap_globals(mp_obj_dict_t *new_globals); mp_obj_t mp_native_call_function_n_kw(mp_obj_t fun_in, size_t n_args_kw, const mp_obj_t *args); void mp_native_raise(mp_obj_t o); diff --git a/py/runtime0.h b/py/runtime0.h index 566cec566a..33c92830ce 100644 --- a/py/runtime0.h +++ b/py/runtime0.h @@ -25,15 +25,18 @@ */ #ifndef MICROPY_INCLUDED_PY_RUNTIME0_H #define MICROPY_INCLUDED_PY_RUNTIME0_H - #include "mpconfig.h" -// These must fit in 8 bits; see scope.h +// The first four must fit in 8 bits, see emitbc.c +// The remaining must fit in 16 bits, see scope.h #define MP_SCOPE_FLAG_VARARGS (0x01) #define MP_SCOPE_FLAG_VARKEYWORDS (0x02) #define MP_SCOPE_FLAG_GENERATOR (0x04) #define MP_SCOPE_FLAG_DEFKWARGS (0x08) #define MP_SCOPE_FLAG_ASYNC (0x10) +#define MP_SCOPE_FLAG_REFGLOBALS (0x20) // used only if native emitter enabled +#define MP_SCOPE_FLAG_HASCONSTS (0x40) // used only if native emitter enabled +#define MP_SCOPE_FLAG_VIPERRET_POS (7) // 3 bits used for viper return type // types for native (viper) function signature #define MP_NATIVE_TYPE_OBJ (0x00) @@ -60,6 +63,7 @@ typedef enum { MP_UNARY_OP_LEN, // __len__ MP_UNARY_OP_HASH, // __hash__; must return a small int MP_UNARY_OP_ABS, // __abs__ + MP_UNARY_OP_INT, // __int__ MP_UNARY_OP_SIZEOF, // for sys.getsizeof() MP_UNARY_OP_NUM_RUNTIME, @@ -146,8 +150,12 @@ typedef enum { } mp_binary_op_t; typedef enum { - MP_F_CONVERT_OBJ_TO_NATIVE = 0, + MP_F_CONST_NONE_OBJ = 0, + MP_F_CONST_FALSE_OBJ, + MP_F_CONST_TRUE_OBJ, + MP_F_CONVERT_OBJ_TO_NATIVE, MP_F_CONVERT_NATIVE_TO_OBJ, + MP_F_NATIVE_SWAP_GLOBALS, MP_F_LOAD_NAME, MP_F_LOAD_GLOBAL, MP_F_LOAD_BUILD_CLASS, @@ -191,12 +199,14 @@ typedef enum { MP_F_DELETE_GLOBAL, MP_F_NEW_CELL, MP_F_MAKE_CLOSURE_FROM_RAW_CODE, + MP_F_ARG_CHECK_NUM_SIG, MP_F_SETUP_CODE_STATE, MP_F_SMALL_INT_FLOOR_DIVIDE, MP_F_SMALL_INT_MODULO, + MP_F_NATIVE_YIELD_FROM, MP_F_NUMBER_OF, } mp_fun_kind_t; -extern void *const mp_fun_table[MP_F_NUMBER_OF]; +extern const void *const mp_fun_table[MP_F_NUMBER_OF]; #endif // MICROPY_INCLUDED_PY_RUNTIME0_H diff --git a/py/scope.c b/py/scope.c index 4adf09afc4..1244240c8d 100644 --- a/py/scope.c +++ b/py/scope.c @@ -64,10 +64,9 @@ void scope_free(scope_t *scope) { m_del(scope_t, scope, 1); } -id_info_t *scope_find_or_add_id(scope_t *scope, qstr qst, bool *added) { +id_info_t *scope_find_or_add_id(scope_t *scope, qstr qst, scope_kind_t kind) { id_info_t *id_info = scope_find(scope, qst); if (id_info != NULL) { - *added = false; return id_info; } @@ -82,11 +81,10 @@ id_info_t *scope_find_or_add_id(scope_t *scope, qstr qst, bool *added) { // handled by the compiler because it adds arguments before compiling the body id_info = &scope->id_info[scope->id_info_len++]; - id_info->kind = 0; + id_info->kind = kind; id_info->flags = 0; id_info->local_num = 0; id_info->qst = qst; - *added = true; return id_info; } @@ -110,9 +108,8 @@ STATIC void scope_close_over_in_parents(scope_t *scope, qstr qst) { assert(scope->parent != NULL); // we should have at least 1 parent for (scope_t *s = scope->parent;; s = s->parent) { assert(s->parent != NULL); // we should not get to the outer scope - bool added; - id_info_t *id = scope_find_or_add_id(s, qst, &added); - if (added) { + id_info_t *id = scope_find_or_add_id(s, qst, ID_INFO_KIND_UNDECIDED); + if (id->kind == ID_INFO_KIND_UNDECIDED) { // variable not previously declared in this scope, so declare it as free and keep searching parents id->kind = ID_INFO_KIND_FREE; } else { @@ -130,21 +127,19 @@ STATIC void scope_close_over_in_parents(scope_t *scope, qstr qst) { } } -void scope_find_local_and_close_over(scope_t *scope, id_info_t *id, qstr qst) { +void scope_check_to_close_over(scope_t *scope, id_info_t *id) { if (scope->parent != NULL) { for (scope_t *s = scope->parent; s->parent != NULL; s = s->parent) { - id_info_t *id2 = scope_find(s, qst); + id_info_t *id2 = scope_find(s, id->qst); if (id2 != NULL) { if (id2->kind == ID_INFO_KIND_LOCAL || id2->kind == ID_INFO_KIND_CELL || id2->kind == ID_INFO_KIND_FREE) { id->kind = ID_INFO_KIND_FREE; - scope_close_over_in_parents(scope, qst); - return; + scope_close_over_in_parents(scope, id->qst); } break; } } } - id->kind = ID_INFO_KIND_GLOBAL_IMPLICIT; } #endif // MICROPY_ENABLE_COMPILER diff --git a/py/scope.h b/py/scope.h index c92a39e5e6..485a964abe 100644 --- a/py/scope.h +++ b/py/scope.h @@ -30,6 +30,7 @@ #include "py/emitglue.h" enum { + ID_INFO_KIND_UNDECIDED, ID_INFO_KIND_GLOBAL_IMPLICIT, ID_INFO_KIND_GLOBAL_EXPLICIT, ID_INFO_KIND_LOCAL, // in a function f, written and only referenced by f @@ -41,6 +42,7 @@ enum { ID_FLAG_IS_PARAM = 0x01, ID_FLAG_IS_STAR_PARAM = 0x02, ID_FLAG_IS_DBL_STAR_PARAM = 0x04, + ID_FLAG_VIPER_TYPE_POS = 4, }; typedef struct _id_info_t { @@ -71,11 +73,11 @@ typedef struct _scope_t { struct _scope_t *parent; struct _scope_t *next; mp_parse_node_t pn; + mp_raw_code_t *raw_code; uint16_t source_file; // a qstr uint16_t simple_name; // a qstr - mp_raw_code_t *raw_code; - uint8_t scope_flags; // see runtime0.h - uint8_t emit_options; // see compile.h + uint16_t scope_flags; // see runtime0.h + uint16_t emit_options; // see emitglue.h uint16_t num_pos_args; uint16_t num_kwonly_args; uint16_t num_def_pos_args; @@ -89,9 +91,9 @@ typedef struct _scope_t { scope_t *scope_new(scope_kind_t kind, mp_parse_node_t pn, qstr source_file, mp_uint_t emit_options); void scope_free(scope_t *scope); -id_info_t *scope_find_or_add_id(scope_t *scope, qstr qstr, bool *added); +id_info_t *scope_find_or_add_id(scope_t *scope, qstr qstr, scope_kind_t kind); id_info_t *scope_find(scope_t *scope, qstr qstr); id_info_t *scope_find_global(scope_t *scope, qstr qstr); -void scope_find_local_and_close_over(scope_t *scope, id_info_t *id, qstr qst); +void scope_check_to_close_over(scope_t *scope, id_info_t *id); #endif // MICROPY_INCLUDED_PY_SCOPE_H diff --git a/py/stream.c b/py/stream.c index 159d32ffb4..35cbc4e211 100644 --- a/py/stream.c +++ b/py/stream.c @@ -561,7 +561,7 @@ off_t mp_stream_posix_lseek(mp_obj_t stream, off_t offset, int whence) { struct mp_stream_seek_t seek_s; seek_s.offset = offset; seek_s.whence = whence; - mp_uint_t res = stream_p->ioctl(stream, MP_STREAM_SEEK, (mp_uint_t)(uintptr_t)&seek_s, &mp_stream_errno); + mp_uint_t res = stream_p->ioctl(MP_OBJ_FROM_PTR(stream), MP_STREAM_SEEK, (mp_uint_t)(uintptr_t)&seek_s, &mp_stream_errno); if (res == MP_STREAM_ERROR) { return -1; } diff --git a/py/stream.h b/py/stream.h index be0b4ace72..3aa0245be1 100644 --- a/py/stream.h +++ b/py/stream.h @@ -42,6 +42,7 @@ #define MP_STREAM_SET_OPTS (7) // Set stream options #define MP_STREAM_GET_DATA_OPTS (8) // Get data/message options #define MP_STREAM_SET_DATA_OPTS (9) // Set data/message options +#define MP_STREAM_GET_FILENO (10) // Get fileno of underlying file // These poll ioctl values are compatible with Linux #define MP_STREAM_POLL_RD (0x0001) @@ -121,10 +122,11 @@ mp_obj_t mp_stream_flush(mp_obj_t self); #if MICROPY_STREAMS_POSIX_API // Functions with POSIX-compatible signatures -ssize_t mp_stream_posix_write(mp_obj_t stream, const void *buf, size_t len); -ssize_t mp_stream_posix_read(mp_obj_t stream, void *buf, size_t len); -off_t mp_stream_posix_lseek(mp_obj_t stream, off_t offset, int whence); -int mp_stream_posix_fsync(mp_obj_t stream); +// "stream" is assumed to be a pointer to a concrete object with the stream protocol +ssize_t mp_stream_posix_write(void *stream, const void *buf, size_t len); +ssize_t mp_stream_posix_read(void *stream, void *buf, size_t len); +off_t mp_stream_posix_lseek(void *stream, off_t offset, int whence); +int mp_stream_posix_fsync(void *stream); #endif #if MICROPY_STREAMS_NON_BLOCK diff --git a/py/unicode.c b/py/unicode.c index 17f05861ca..1e41821d51 100644 --- a/py/unicode.c +++ b/py/unicode.c @@ -182,7 +182,7 @@ bool utf8_check(const byte *p, size_t len) { for (; p < end; p++) { byte c = *p; if (need) { - if (c >= 0x80) { + if (UTF8_IS_CONT(c)) { need--; } else { // mismatch diff --git a/py/vm.c b/py/vm.c index 21a9528b2b..615a550304 100644 --- a/py/vm.c +++ b/py/vm.c @@ -117,7 +117,7 @@ // returns: // MP_VM_RETURN_NORMAL, sp valid, return value in *sp // MP_VM_RETURN_YIELD, ip, sp valid, yielded value in *sp -// MP_VM_RETURN_EXCEPTION, exception in fastn[0] +// MP_VM_RETURN_EXCEPTION, exception in state[0] mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_state, volatile mp_obj_t inject_exc) { #define SELECTIVE_EXC_IP (0) #if SELECTIVE_EXC_IP @@ -830,17 +830,14 @@ mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_st #if MICROPY_PY_BUILTINS_SLICE ENTRY(MP_BC_BUILD_SLICE) : { MARK_EXC_IP_SELECTIVE(); - DECODE_UINT; - if (unum == 2) { - mp_obj_t stop = POP(); - mp_obj_t start = TOP(); - SET_TOP(mp_obj_new_slice(start, stop, mp_const_none)); - } else { - mp_obj_t step = POP(); - mp_obj_t stop = POP(); - mp_obj_t start = TOP(); - SET_TOP(mp_obj_new_slice(start, stop, step)); + mp_obj_t step = mp_const_none; + if (*ip++ == 3) { + // 3-argument slice includes step + step = POP(); } + mp_obj_t stop = POP(); + mp_obj_t start = TOP(); + SET_TOP(mp_obj_new_slice(start, stop, step)); DISPATCH(); } #endif @@ -1076,17 +1073,11 @@ mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_st ENTRY(MP_BC_RETURN_VALUE) : MARK_EXC_IP_SELECTIVE(); - // These next 3 lines pop a try-finally exception handler, if one - // is there on the exception stack. Without this the finally block - // is executed a second time when the return is executed, because - // the try-finally exception handler is still on the stack. - // TODO Possibly find a better way to handle this case. - if (currently_in_except_block) { - POP_EXC_BLOCK(); - } unwind_return: + // Search for and execute finally handlers that aren't already active while (exc_sp >= exc_stack) { - if (MP_TAGPTR_TAG1(exc_sp->val_sp)) { + if (!currently_in_except_block && MP_TAGPTR_TAG1(exc_sp->val_sp)) { + // Found a finally handler that isn't active. // Getting here the stack looks like: // (..., X, [iter0, iter1, ...,] ret_val) // where X is pointed to by exc_sp->val_sp and in the case @@ -1105,10 +1096,10 @@ mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_st // done (when WITH_CLEANUP or END_FINALLY reached). PUSH(MP_OBJ_NEW_SMALL_INT(-1)); ip = exc_sp->handler; - exc_sp--; + POP_EXC_BLOCK(); goto dispatch_loop; } - exc_sp--; + POP_EXC_BLOCK(); } nlr_pop(); code_state->sp = sp; @@ -1174,7 +1165,7 @@ mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_st MARK_EXC_IP_SELECTIVE(); // #define EXC_MATCH(exc, type) MP_OBJ_IS_TYPE(exc, type) #define EXC_MATCH(exc, type) mp_obj_exception_match(exc, type) -#define GENERATOR_EXIT_IF_NEEDED(t) if (t != MP_OBJ_NULL && EXC_MATCH(t, MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { RAISE(t); \ +#define GENERATOR_EXIT_IF_NEEDED(t) if (t != MP_OBJ_NULL && EXC_MATCH(t, MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { mp_obj_t raise_t = mp_make_raise_obj(t); RAISE(raise_t); \ } mp_vm_return_kind_t ret_kind; mp_obj_t send_value = POP(); @@ -1297,7 +1288,7 @@ mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_st { mp_obj_t obj = mp_obj_new_exception_msg(&mp_type_NotImplementedError, translate("byte code not implemented")); nlr_pop(); - fastn[0] = obj; + code_state->state[0] = obj; return MP_VM_RETURN_EXCEPTION; } @@ -1490,8 +1481,8 @@ mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_st #endif } else { // propagate exception to higher level - // TODO what to do about ip and sp? they don't really make sense at this point - fastn[0] = MP_OBJ_FROM_PTR(nlr.ret_val); // must put exception here because sp is invalid + // Note: ip and sp don't have usable values at this point + code_state->state[0] = MP_OBJ_FROM_PTR(nlr.ret_val); // put exception here because sp is invalid return MP_VM_RETURN_EXCEPTION; } } diff --git a/shared-bindings/_bleio/Characteristic.c b/shared-bindings/_bleio/Characteristic.c index 0aa832cf21..b69b71d0c9 100644 --- a/shared-bindings/_bleio/Characteristic.c +++ b/shared-bindings/_bleio/Characteristic.c @@ -219,6 +219,23 @@ const mp_obj_property_t bleio_characteristic_value_obj = { (mp_obj_t)&mp_const_none_obj }, }; +//| max_length: int +//| """The max length of this characteristic.""" +//| +STATIC mp_obj_t bleio_characteristic_get_max_length(mp_obj_t self_in) { + bleio_characteristic_obj_t *self = MP_OBJ_TO_PTR(self_in); + + return MP_OBJ_NEW_SMALL_INT(common_hal_bleio_characteristic_get_max_length(self)); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(bleio_characteristic_get_max_length_obj, bleio_characteristic_get_max_length); + +const mp_obj_property_t bleio_characteristic_max_length_obj = { + .base.type = &mp_type_property, + .proxy = { (mp_obj_t)&bleio_characteristic_get_max_length_obj, + (mp_obj_t)&mp_const_none_obj, + (mp_obj_t)&mp_const_none_obj }, +}; + //| descriptors: Descriptor //| """A tuple of :py:class:`Descriptor` objects related to this characteristic. (read-only)""" //| diff --git a/shared-bindings/_bleio/Characteristic.h b/shared-bindings/_bleio/Characteristic.h index a8486866f9..878d998a2d 100644 --- a/shared-bindings/_bleio/Characteristic.h +++ b/shared-bindings/_bleio/Characteristic.h @@ -40,6 +40,7 @@ extern bleio_characteristic_properties_t common_hal_bleio_characteristic_get_pro extern mp_obj_tuple_t *common_hal_bleio_characteristic_get_descriptors(bleio_characteristic_obj_t *self); extern bleio_service_obj_t *common_hal_bleio_characteristic_get_service(bleio_characteristic_obj_t *self); extern bleio_uuid_obj_t *common_hal_bleio_characteristic_get_uuid(bleio_characteristic_obj_t *self); +extern size_t common_hal_bleio_characteristic_get_max_length(bleio_characteristic_obj_t *self); extern size_t common_hal_bleio_characteristic_get_value(bleio_characteristic_obj_t *self, uint8_t *buf, size_t len); extern void common_hal_bleio_characteristic_add_descriptor(bleio_characteristic_obj_t *self, bleio_descriptor_obj_t *descriptor); extern void common_hal_bleio_characteristic_construct(bleio_characteristic_obj_t *self, bleio_service_obj_t *service, uint16_t handle, bleio_uuid_obj_t *uuid, bleio_characteristic_properties_t props, bleio_attribute_security_mode_t read_perm, bleio_attribute_security_mode_t write_perm, mp_int_t max_length, bool fixed_length, mp_buffer_info_t *initial_value_bufinfo); diff --git a/shared-bindings/_bleio/PacketBuffer.c b/shared-bindings/_bleio/PacketBuffer.c index 16ad02a461..b54a48230b 100644 --- a/shared-bindings/_bleio/PacketBuffer.c +++ b/shared-bindings/_bleio/PacketBuffer.c @@ -44,7 +44,7 @@ //| When we're the server, we ignore all connections besides the first to subscribe to //| notifications.""" //| -//| def __init__(self, characteristic: Characteristic, *, buffer_size: int) -> None: +//| def __init__(self, characteristic: Characteristic, *, buffer_size: int, max_packet_size: Optional[int] = None) -> None: //| """Monitor the given Characteristic. Each time a new value is written to the Characteristic //| add the newly-written bytes to a FIFO buffer. //| @@ -55,14 +55,17 @@ //| It may be a local Characteristic provided by a Peripheral Service, or a remote Characteristic //| in a remote Service that a Central has connected to. //| :param int buffer_size: Size of ring buffer (in packets of the Characteristic's maximum -//| length) that stores incoming packets coming from the peer.""" +//| length) that stores incoming packets coming from the peer. +//| :param int max_packet_size: Maximum size of packets. Overrides value from the characteristic. +//| (Remote characteristics may not have the correct length.)""" //| ... //| STATIC mp_obj_t bleio_packet_buffer_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - enum { ARG_characteristic, ARG_buffer_size }; + enum { ARG_characteristic, ARG_buffer_size, ARG_max_packet_size }; static const mp_arg_t allowed_args[] = { { MP_QSTR_characteristic, MP_ARG_REQUIRED | MP_ARG_OBJ }, { MP_QSTR_buffer_size, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_max_packet_size, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none}}, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; @@ -79,10 +82,15 @@ STATIC mp_obj_t bleio_packet_buffer_make_new(const mp_obj_type_t *type, size_t n mp_raise_TypeError(translate("Expected a Characteristic")); } + size_t max_packet_size = common_hal_bleio_characteristic_get_max_length(characteristic); + if (args[ARG_max_packet_size].u_obj != mp_const_none) { + max_packet_size = mp_obj_get_int(args[ARG_max_packet_size].u_obj); + } + bleio_packet_buffer_obj_t *self = m_new_obj(bleio_packet_buffer_obj_t); self->base.type = &bleio_packet_buffer_type; - common_hal_bleio_packet_buffer_construct(self, MP_OBJ_TO_PTR(characteristic), buffer_size); + common_hal_bleio_packet_buffer_construct(self, MP_OBJ_TO_PTR(characteristic), buffer_size, max_packet_size); return MP_OBJ_FROM_PTR(self); } @@ -95,7 +103,7 @@ STATIC void check_for_deinit(bleio_packet_buffer_obj_t *self) { //| def readinto(self, buf: WriteableBuffer) -> int: //| """Reads a single BLE packet into the ``buf``. Raises an exception if the next packet is longer -//| than the given buffer. Use `packet_size` to read the maximum length of a single packet. +//| than the given buffer. Use `incoming_packet_length` to read the maximum length of a single packet. //| //| :return: number of bytes read and stored into ``buf`` //| :rtype: int""" @@ -133,7 +141,7 @@ STATIC mp_obj_t bleio_packet_buffer_write(mp_uint_t n_args, const mp_obj_t *pos_ enum { ARG_data, ARG_header }; static const mp_arg_t allowed_args[] = { { MP_QSTR_data, MP_ARG_REQUIRED | MP_ARG_OBJ }, - { MP_QSTR_header, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, + { MP_QSTR_header, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none}}, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; @@ -147,7 +155,7 @@ STATIC mp_obj_t bleio_packet_buffer_write(mp_uint_t n_args, const mp_obj_t *pos_ mp_buffer_info_t header_bufinfo; header_bufinfo.len = 0; - if (args[ARG_header].u_obj != MP_OBJ_NULL) { + if (args[ARG_header].u_obj != mp_const_none) { mp_get_buffer_raise(args[ARG_header].u_obj, &header_bufinfo, MP_BUFFER_READ); } @@ -179,11 +187,6 @@ STATIC mp_obj_t bleio_packet_buffer_deinit(mp_obj_t self_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(bleio_packet_buffer_deinit_obj, bleio_packet_buffer_deinit); -//| packet_size: int -//| """`packet_size` is the same as `incoming_packet_length`. -//| The name `packet_size` is deprecated and -//| will be removed in CircuitPython 6.0.0.""" -//| //| incoming_packet_length: int //| """Maximum length in bytes of a packet we are reading.""" //| @@ -233,9 +236,6 @@ STATIC const mp_rom_map_elem_t bleio_packet_buffer_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&bleio_packet_buffer_readinto_obj) }, { MP_OBJ_NEW_QSTR(MP_QSTR_write), MP_ROM_PTR(&bleio_packet_buffer_write_obj) }, - // .packet_size is now an alias for .incoming_packet_length - // TODO: Remove in 6.0.0. - { MP_OBJ_NEW_QSTR(MP_QSTR_packet_size), MP_ROM_PTR(&bleio_packet_buffer_incoming_packet_length_obj) }, { MP_OBJ_NEW_QSTR(MP_QSTR_incoming_packet_length), MP_ROM_PTR(&bleio_packet_buffer_incoming_packet_length_obj) }, { MP_OBJ_NEW_QSTR(MP_QSTR_outgoing_packet_length), MP_ROM_PTR(&bleio_packet_buffer_outgoing_packet_length_obj) }, }; diff --git a/shared-bindings/_bleio/PacketBuffer.h b/shared-bindings/_bleio/PacketBuffer.h index 65ce3ded1f..b300cb0215 100644 --- a/shared-bindings/_bleio/PacketBuffer.h +++ b/shared-bindings/_bleio/PacketBuffer.h @@ -33,7 +33,7 @@ extern const mp_obj_type_t bleio_packet_buffer_type; extern void common_hal_bleio_packet_buffer_construct( bleio_packet_buffer_obj_t *self, bleio_characteristic_obj_t *characteristic, - size_t buffer_size); + size_t buffer_size, size_t max_packet_size); mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, uint8_t *data, size_t len, uint8_t *header, size_t header_len); mp_int_t common_hal_bleio_packet_buffer_readinto(bleio_packet_buffer_obj_t *self, uint8_t *data, size_t len); mp_int_t common_hal_bleio_packet_buffer_get_incoming_packet_length(bleio_packet_buffer_obj_t *self); diff --git a/shared-bindings/_typing/__init__.pyi b/shared-bindings/_typing/__init__.pyi index 9a6e963ea5..d1bf853f71 100644 --- a/shared-bindings/_typing/__init__.pyi +++ b/shared-bindings/_typing/__init__.pyi @@ -38,7 +38,7 @@ WriteableBuffer = Union[ """ AudioSample = Union[ - audiocore.WaveFile, audiocore.RawSample, audiomixer.Mixer, audiomp3.MP3Decoder + audiocore.WaveFile, audiocore.RawSample, audiomixer.Mixer, audiomp3.MP3Decoder, synthio.MidiTrack ] """Classes that implement the audiosample protocol @@ -46,6 +46,7 @@ AudioSample = Union[ - `audiocore.RawSample` - `audiomixer.Mixer` - `audiomp3.MP3Decoder` + - `synthio.MidiTrack` You can play these back with `audioio.AudioOut`, `audiobusio.I2SOut` or `audiopwmio.PWMAudioOut`. """ diff --git a/shared-bindings/audiocore/RawSample.c b/shared-bindings/audiocore/RawSample.c index 23a2d3f0be..13339222c1 100644 --- a/shared-bindings/audiocore/RawSample.c +++ b/shared-bindings/audiocore/RawSample.c @@ -30,7 +30,6 @@ #include "py/binary.h" #include "py/objproperty.h" #include "py/runtime.h" -#include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/util.h" #include "shared-bindings/audiocore/RawSample.h" #include "supervisor/shared/translate.h" @@ -83,26 +82,23 @@ STATIC mp_obj_t audioio_rawsample_make_new(const mp_obj_type_t *type, size_t n_a audioio_rawsample_obj_t *self = m_new_obj(audioio_rawsample_obj_t); self->base.type = &audioio_rawsample_type; mp_buffer_info_t bufinfo; - if (mp_get_buffer(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_READ)) { - uint8_t bytes_per_sample = 1; - bool signed_samples = bufinfo.typecode == 'b' || bufinfo.typecode == 'h'; - if (bufinfo.typecode == 'h' || bufinfo.typecode == 'H') { - bytes_per_sample = 2; - } else if (bufinfo.typecode != 'b' && bufinfo.typecode != 'B' && bufinfo.typecode != BYTEARRAY_TYPECODE) { - mp_raise_ValueError(translate("sample_source buffer must be a bytearray or array of type 'h', 'H', 'b' or 'B'")); - } - common_hal_audioio_rawsample_construct(self, ((uint8_t *)bufinfo.buf), bufinfo.len, - bytes_per_sample, signed_samples, args[ARG_channel_count].u_int, - args[ARG_sample_rate].u_int); - } else { - mp_raise_TypeError(translate("buffer must be a bytes-like object")); + mp_get_buffer_raise(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_READ); + uint8_t bytes_per_sample = 1; + bool signed_samples = bufinfo.typecode == 'b' || bufinfo.typecode == 'h'; + if (bufinfo.typecode == 'h' || bufinfo.typecode == 'H') { + bytes_per_sample = 2; + } else if (bufinfo.typecode != 'b' && bufinfo.typecode != 'B' && bufinfo.typecode != BYTEARRAY_TYPECODE) { + mp_raise_ValueError(translate("sample_source buffer must be a bytearray or array of type 'h', 'H', 'b' or 'B'")); } + common_hal_audioio_rawsample_construct(self, ((uint8_t *)bufinfo.buf), bufinfo.len, + bytes_per_sample, signed_samples, args[ARG_channel_count].u_int, + args[ARG_sample_rate].u_int); return MP_OBJ_FROM_PTR(self); } //| def deinit(self) -> None: -//| """Deinitialises the AudioOut and releases any hardware resources for reuse.""" +//| """Deinitialises the RawSample and releases any hardware resources for reuse.""" //| ... //| STATIC mp_obj_t audioio_rawsample_deinit(mp_obj_t self_in) { diff --git a/shared-bindings/audiocore/RawSample.h b/shared-bindings/audiocore/RawSample.h index b07add2dd1..71056f30c3 100644 --- a/shared-bindings/audiocore/RawSample.h +++ b/shared-bindings/audiocore/RawSample.h @@ -27,7 +27,6 @@ #ifndef MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOIO_RAWSAMPLE_H #define MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOIO_RAWSAMPLE_H -#include "common-hal/microcontroller/Pin.h" #include "shared-module/audiocore/RawSample.h" extern const mp_obj_type_t audioio_rawsample_type; diff --git a/shared-bindings/audiocore/WaveFile.c b/shared-bindings/audiocore/WaveFile.c index 73943f980f..5cf6deb2ed 100644 --- a/shared-bindings/audiocore/WaveFile.c +++ b/shared-bindings/audiocore/WaveFile.c @@ -44,7 +44,7 @@ //| """Load a .wav file for playback with `audioio.AudioOut` or `audiobusio.I2SOut`. //| //| :param typing.BinaryIO file: Already opened wave file -//| :param ~_typing.WriteableBuffer buffer: Optional pre-allocated buffer, that will be split in half and used for double-buffering of the data. If not provided, two 512 byte buffers are allocated internally. +//| :param ~_typing.WriteableBuffer buffer: Optional pre-allocated buffer, that will be split in half and used for double-buffering of the data. If not provided, two 256 byte buffers are allocated internally. //| //| //| Playing a wave file from flash:: diff --git a/shared-bindings/displayio/ColorConverter.c b/shared-bindings/displayio/ColorConverter.c index d102d7f9d1..a5b154b341 100644 --- a/shared-bindings/displayio/ColorConverter.c +++ b/shared-bindings/displayio/ColorConverter.c @@ -30,6 +30,7 @@ #include "lib/utils/context_manager_helpers.h" #include "py/binary.h" +#include "py/enum.h" #include "py/objproperty.h" #include "py/runtime.h" #include "shared-bindings/microcontroller/Pin.h" @@ -39,20 +40,20 @@ //| class ColorConverter: //| """Converts one color format to another.""" //| -//| def __init__(self, *, dither: bool = False) -> None: -//| """Create a ColorConverter object to convert color formats. Only supports RGB888 to RGB565 -//| currently. +//| def __init__(self, *, colorspace: Colorspace=Colorspace.RGB888, dither: bool = False) -> None: +//| """Create a ColorConverter object to convert color formats. +//| +//| :param Colorspace colorspace: The source colorspace, one of the Colorspace constants //| :param bool dither: Adds random noise to dither the output image""" //| ... //| -// TODO(tannewt): Add support for other color formats. -//| STATIC mp_obj_t displayio_colorconverter_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - enum { ARG_dither}; + enum { ARG_dither, ARG_input_colorspace }; static const mp_arg_t allowed_args[] = { - { MP_QSTR_dither, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} } + { MP_QSTR_dither, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_input_colorspace, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = (void *)&displayio_colorspace_RGB888_obj} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -60,13 +61,13 @@ STATIC mp_obj_t displayio_colorconverter_make_new(const mp_obj_type_t *type, siz displayio_colorconverter_t *self = m_new_obj(displayio_colorconverter_t); self->base.type = &displayio_colorconverter_type; - common_hal_displayio_colorconverter_construct(self, args[ARG_dither].u_bool); + common_hal_displayio_colorconverter_construct(self, args[ARG_dither].u_bool, (displayio_colorspace_t)cp_enum_value(&displayio_colorspace_type, args[ARG_input_colorspace].u_obj)); return MP_OBJ_FROM_PTR(self); } //| def convert(self, color: int) -> int: -//| """Converts the given RGB888 color to RGB565""" +//| """Converts the given color to RGB565 according to the Colorspace""" //| ... //| STATIC mp_obj_t displayio_colorconverter_obj_convert(mp_obj_t self_in, mp_obj_t color_obj) { diff --git a/shared-bindings/displayio/ColorConverter.h b/shared-bindings/displayio/ColorConverter.h index d5a5d05243..018db92c96 100644 --- a/shared-bindings/displayio/ColorConverter.h +++ b/shared-bindings/displayio/ColorConverter.h @@ -27,13 +27,14 @@ #ifndef MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO_COLORCONVERTER_H #define MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO_COLORCONVERTER_H +#include "shared-bindings/displayio/__init__.h" #include "shared-module/displayio/ColorConverter.h" #include "shared-module/displayio/Palette.h" extern const mp_obj_type_t displayio_colorconverter_type; -void common_hal_displayio_colorconverter_construct(displayio_colorconverter_t *self, bool dither); +void common_hal_displayio_colorconverter_construct(displayio_colorconverter_t *self, bool dither, displayio_colorspace_t input_colorspace); void common_hal_displayio_colorconverter_convert(displayio_colorconverter_t *colorconverter, const _displayio_colorspace_t *colorspace, uint32_t input_color, uint32_t *output_color); void common_hal_displayio_colorconverter_set_dither(displayio_colorconverter_t *self, bool dither); diff --git a/shared-bindings/displayio/__init__.c b/shared-bindings/displayio/__init__.c index bca4289b0e..b39e72b946 100644 --- a/shared-bindings/displayio/__init__.c +++ b/shared-bindings/displayio/__init__.c @@ -26,6 +26,7 @@ #include +#include "py/enum.h" #include "py/obj.h" #include "py/runtime.h" @@ -49,7 +50,6 @@ //| including synchronizing with refresh rates and partial updating.""" //| - //| def release_displays() -> None: //| """Releases any actively used displays so their busses and pins can be used again. This will also //| release the builtin display on boards that have one. You will need to reinitialize it yourself @@ -65,10 +65,48 @@ STATIC mp_obj_t displayio_release_displays(void) { } MP_DEFINE_CONST_FUN_OBJ_0(displayio_release_displays_obj, displayio_release_displays); +MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, RGB888, DISPLAYIO_COLORSPACE_RGB888); +MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, RGB565, DISPLAYIO_COLORSPACE_RGB565); +MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, RGB565_SWAPPED, DISPLAYIO_COLORSPACE_RGB565_SWAPPED); +MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, RGB555, DISPLAYIO_COLORSPACE_RGB555); +MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, RGB555_SWAPPED, DISPLAYIO_COLORSPACE_RGB555_SWAPPED); + +//| class Colorspace: +//| """The colorspace for a `ColorConverter` to operate in""" +//| +//| RGB888: Colorspace +//| """The standard 24-bit colorspace. Bits 0-7 are blue, 8-15 are green, and 16-24 are red. (0xRRGGBB)""" +//| +//| RGB565: Colorspace +//| """The standard 16-bit colorspace. Bits 0-4 are blue, bits 5-10 are green, and 11-15 are red (0bRRRRRGGGGGGBBBBB)""" +//| +//| RGB565_SWAPPED: Colorspace +//| """The swapped 16-bit colorspace. First, the high and low 8 bits of the number are swapped, then they are interpreted as for RGB565""" +//| +//| RGB555: Colorspace +//| """The standard 15-bit colorspace. Bits 0-4 are blue, bits 5-9 are green, and 11-14 are red. The top bit is ignored. (0bxRRRRRGGGGGBBBBB)""" +//| +//| RGB555_SWAPPED: Colorspace +//| """The swapped 15-bit colorspace. First, the high and low 8 bits of the number are swapped, then they are interpreted as for RGB555""" +//| +MAKE_ENUM_MAP(displayio_colorspace) { + MAKE_ENUM_MAP_ENTRY(displayio_colorspace, RGB888), + MAKE_ENUM_MAP_ENTRY(displayio_colorspace, RGB565), + MAKE_ENUM_MAP_ENTRY(displayio_colorspace, RGB565_SWAPPED), + MAKE_ENUM_MAP_ENTRY(displayio_colorspace, RGB555), + MAKE_ENUM_MAP_ENTRY(displayio_colorspace, RGB555_SWAPPED), +}; +STATIC MP_DEFINE_CONST_DICT(displayio_colorspace_locals_dict, displayio_colorspace_locals_table); + +MAKE_PRINTER(displayio, displayio_colorspace); +MAKE_ENUM_TYPE(displayio, ColorSpace, displayio_colorspace); + + STATIC const mp_rom_map_elem_t displayio_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_displayio) }, { MP_ROM_QSTR(MP_QSTR_Bitmap), MP_ROM_PTR(&displayio_bitmap_type) }, { MP_ROM_QSTR(MP_QSTR_ColorConverter), MP_ROM_PTR(&displayio_colorconverter_type) }, + { MP_ROM_QSTR(MP_QSTR_Colorspace), MP_ROM_PTR(&displayio_colorspace_type) }, { MP_ROM_QSTR(MP_QSTR_Display), MP_ROM_PTR(&displayio_display_type) }, { MP_ROM_QSTR(MP_QSTR_EPaperDisplay), MP_ROM_PTR(&displayio_epaperdisplay_type) }, { MP_ROM_QSTR(MP_QSTR_Group), MP_ROM_PTR(&displayio_group_type) }, diff --git a/shared-bindings/displayio/__init__.h b/shared-bindings/displayio/__init__.h index 4fc666c598..31af2ff2ba 100644 --- a/shared-bindings/displayio/__init__.h +++ b/shared-bindings/displayio/__init__.h @@ -27,6 +27,7 @@ #ifndef MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO___INIT___H #define MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO___INIT___H +#include "py/enum.h" #include "py/obj.h" typedef enum { @@ -39,6 +40,14 @@ typedef enum { CHIP_SELECT_TOGGLE_EVERY_BYTE } display_chip_select_behavior_t; +typedef enum { + DISPLAYIO_COLORSPACE_RGB888, + DISPLAYIO_COLORSPACE_RGB565, + DISPLAYIO_COLORSPACE_RGB555, + DISPLAYIO_COLORSPACE_RGB565_SWAPPED, + DISPLAYIO_COLORSPACE_RGB555_SWAPPED, +} displayio_colorspace_t; + typedef bool (*display_bus_bus_reset)(mp_obj_t bus); typedef bool (*display_bus_bus_free)(mp_obj_t bus); typedef bool (*display_bus_begin_transaction)(mp_obj_t bus); @@ -48,4 +57,7 @@ typedef void (*display_bus_end_transaction)(mp_obj_t bus); void common_hal_displayio_release_displays(void); +extern const mp_obj_type_t displayio_colorspace_type; +extern const cp_enum_obj_t displayio_colorspace_RGB888_obj; + #endif // MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO___INIT___H diff --git a/shared-bindings/imagecapture/ParallelImageCapture.c b/shared-bindings/imagecapture/ParallelImageCapture.c new file mode 100644 index 0000000000..ee04dcd5ee --- /dev/null +++ b/shared-bindings/imagecapture/ParallelImageCapture.c @@ -0,0 +1,145 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/obj.h" +#include "py/runtime.h" + +#include "lib/utils/context_manager_helpers.h" + +#include "shared-bindings/imagecapture/ParallelImageCapture.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "common-hal/imagecapture/ParallelImageCapture.h" + +//| class ParallelImageCapture: +//| """Capture image frames from a camera with parallel data interface""" +//| +//| def __init__( +//| self, +//| *, +//| data0: microcontroller.Pin, +//| data_count: int=8, +//| clock: microcontroller.Pin, +//| vsync: Optional[microcontroller.Pin], +//| href: Optional[microcontroller.Pin], +//| ): +//| """Create a parallel image capture object +//| :param microcontroller.Pin data0: The first data pin. Additional data pins are assumed to follow this pin directly in the microcontroller's standard pin ordering. +//| :param int data_count: The number of data pins. +//| :param microcontroller.Pin clock: The pixel clock input. +//| :param microcontroller.Pin vsync: The vertical sync input, which has a negative-going pulse at the beginning of each frame. +//| :param microcontroller.Pin href: The horizontal reference input, which is high whenever the camera is transmitting valid pixel information. +//| """ +//| ... +//| +STATIC mp_obj_t imagecapture_parallelimagecapture_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_data0, ARG_data_count, ARG_clock, ARG_vsync, ARG_href, + NUM_ARGS }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_data0, MP_ARG_OBJ | MP_ARG_REQUIRED | MP_ARG_KW_ONLY }, + { MP_QSTR_data_count, MP_ARG_INT | MP_ARG_KW_ONLY, { .u_int = 8 } }, + { MP_QSTR_clock, MP_ARG_OBJ | MP_ARG_REQUIRED | MP_ARG_KW_ONLY }, + { MP_QSTR_vsync, MP_ARG_OBJ | MP_ARG_REQUIRED | MP_ARG_KW_ONLY }, + { MP_QSTR_href, MP_ARG_OBJ | MP_ARG_REQUIRED | MP_ARG_KW_ONLY }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); + mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mcu_pin_obj_t *data0 = validate_obj_is_free_pin(args[ARG_data0].u_obj); + mcu_pin_obj_t *clock = validate_obj_is_free_pin(args[ARG_clock].u_obj); + mcu_pin_obj_t *vsync = validate_obj_is_free_pin_or_none(args[ARG_vsync].u_obj); + mcu_pin_obj_t *href = validate_obj_is_free_pin_or_none(args[ARG_href].u_obj); + + imagecapture_parallelimagecapture_obj_t *self = m_new_obj(imagecapture_parallelimagecapture_obj_t); + self->base.type = &imagecapture_parallelimagecapture_type; + + common_hal_imagecapture_parallelimagecapture_construct(self, data0, clock, vsync, href, args[ARG_data_count].u_int); + + return self; +} + +//| def capture(self, buffer: WriteableBuffer, width: int, height: int, bpp: int=16) -> None: +//| """Capture a single frame into the given buffer""" +//| ... +//| +STATIC mp_obj_t imagecapture_parallelimagecapture_capture(mp_obj_t self_in, mp_obj_t buffer) { + imagecapture_parallelimagecapture_obj_t *self = (imagecapture_parallelimagecapture_obj_t *)self_in; + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(buffer, &bufinfo, MP_BUFFER_RW); + common_hal_imagecapture_parallelimagecapture_capture(self, bufinfo.buf, bufinfo.len); + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(imagecapture_parallelimagecapture_capture_obj, imagecapture_parallelimagecapture_capture); + +//| def deinit(self) -> None: +//| """Deinitialize this instance""" +//| ... +//| +STATIC mp_obj_t imagecapture_parallelimagecapture_deinit(mp_obj_t self_in) { + imagecapture_parallelimagecapture_obj_t *self = (imagecapture_parallelimagecapture_obj_t *)self_in; + common_hal_imagecapture_parallelimagecapture_deinit(self); + return mp_const_none; +} + +STATIC MP_DEFINE_CONST_FUN_OBJ_1(imagecapture_parallelimagecapture_deinit_obj, imagecapture_parallelimagecapture_deinit); + +//| def __enter__(self) -> ParallelImageCapture: +//| """No-op used in Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes the hardware on context exit. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +STATIC mp_obj_t imagecapture_parallelimagecapture___exit__(size_t n_args, const mp_obj_t *args) { + (void)n_args; + common_hal_imagecapture_parallelimagecapture_deinit(args[0]); + return mp_const_none; +} + +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(imagecapture_parallelimagecapture___exit___obj, 4, 4, imagecapture_parallelimagecapture___exit__); + + +STATIC const mp_rom_map_elem_t imagecapture_parallelimagecapture_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&imagecapture_parallelimagecapture_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&imagecapture_parallelimagecapture___exit___obj) }, + + { MP_ROM_QSTR(MP_QSTR_capture), MP_ROM_PTR(&imagecapture_parallelimagecapture_capture_obj) }, +}; + +STATIC MP_DEFINE_CONST_DICT(imagecapture_parallelimagecapture_locals_dict, imagecapture_parallelimagecapture_locals_dict_table); + +const mp_obj_type_t imagecapture_parallelimagecapture_type = { + { &mp_type_type }, + .name = MP_QSTR_ParallelImageCapture, + .make_new = imagecapture_parallelimagecapture_make_new, + .locals_dict = (mp_obj_dict_t *)&imagecapture_parallelimagecapture_locals_dict, +}; diff --git a/shared-bindings/imagecapture/ParallelImageCapture.h b/shared-bindings/imagecapture/ParallelImageCapture.h new file mode 100644 index 0000000000..67e05f2bf2 --- /dev/null +++ b/shared-bindings/imagecapture/ParallelImageCapture.h @@ -0,0 +1,42 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * 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. + */ + +#pragma once + +#include "common-hal/microcontroller/Pin.h" + +typedef struct imagecapture_parallelimagecapture_obj imagecapture_parallelimagecapture_obj_t; +extern const mp_obj_type_t imagecapture_parallelimagecapture_type; + +void common_hal_imagecapture_parallelimagecapture_construct(imagecapture_parallelimagecapture_obj_t *self, + const mcu_pin_obj_t *data0, + const mcu_pin_obj_t *data_clock, + const mcu_pin_obj_t *vertical_sync, + const mcu_pin_obj_t *horizontal_sync, + int data_count); +void common_hal_imagecapture_parallelimagecapture_deinit(imagecapture_parallelimagecapture_obj_t *self); +bool common_hal_imagecapture_parallelimagecapture_deinited(imagecapture_parallelimagecapture_obj_t *self); +void common_hal_imagecapture_parallelimagecapture_capture(imagecapture_parallelimagecapture_obj_t *self, void *buffer, size_t bufsize); diff --git a/drivers/bus/spi.h b/shared-bindings/imagecapture/__init__.c similarity index 57% rename from drivers/bus/spi.h rename to shared-bindings/imagecapture/__init__.c index 5d150cd38f..8f7ce231a6 100644 --- a/drivers/bus/spi.h +++ b/shared-bindings/imagecapture/__init__.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2016-2018 Damien P. George + * Copyright (c) 2021 Jeff Epler for Adafruit Industries * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -23,33 +23,25 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef MICROPY_INCLUDED_DRIVERS_BUS_SPI_H -#define MICROPY_INCLUDED_DRIVERS_BUS_SPI_H -#include "py/mphal.h" +#include -enum { - MP_SPI_IOCTL_INIT, - MP_SPI_IOCTL_DEINIT, +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/imagecapture/ParallelImageCapture.h" + +//| """Support for "Parallel capture" interfaces""" +//| + +STATIC const mp_rom_map_elem_t imagecapture_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_imagecapture) }, + { MP_ROM_QSTR(MP_QSTR_ParallelImageCapture), MP_ROM_PTR(&imagecapture_parallelimagecapture_type) }, }; -typedef struct _mp_spi_proto_t { - int (*ioctl)(void *self, uint32_t cmd); - void (*transfer)(void *self, size_t len, const uint8_t *src, uint8_t *dest); -} mp_spi_proto_t; +STATIC MP_DEFINE_CONST_DICT(imagecapture_module_globals, imagecapture_module_globals_table); -typedef struct _mp_soft_spi_obj_t { - uint32_t delay_half; // microsecond delay for half SCK period - uint8_t polarity; - uint8_t phase; - mp_hal_pin_obj_t sck; - mp_hal_pin_obj_t mosi; - mp_hal_pin_obj_t miso; -} mp_soft_spi_obj_t; - -extern const mp_spi_proto_t mp_soft_spi_proto; - -int mp_soft_spi_ioctl(void *self, uint32_t cmd); -void mp_soft_spi_transfer(void *self, size_t len, const uint8_t *src, uint8_t *dest); - -#endif // MICROPY_INCLUDED_DRIVERS_BUS_SPI_H +const mp_obj_module_t imagecapture_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&imagecapture_module_globals, +}; diff --git a/shared-bindings/imagecapture/__init__.h b/shared-bindings/imagecapture/__init__.h new file mode 100644 index 0000000000..1e170aa941 --- /dev/null +++ b/shared-bindings/imagecapture/__init__.h @@ -0,0 +1,27 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * 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. + */ + +#pragma once diff --git a/shared-bindings/supervisor/Runtime.c b/shared-bindings/supervisor/Runtime.c index 26036e0d5a..9e97407f6e 100644 --- a/shared-bindings/supervisor/Runtime.c +++ b/shared-bindings/supervisor/Runtime.c @@ -59,7 +59,11 @@ STATIC supervisor_run_reason_t _run_reason; //| """Returns the USB enumeration status (read-only).""" //| STATIC mp_obj_t supervisor_runtime_get_usb_connected(mp_obj_t self) { + #if CIRCUITPY_USB return mp_obj_new_bool(tud_ready()); + #else + return mp_const_false; + #endif } MP_DEFINE_CONST_FUN_OBJ_1(supervisor_runtime_get_usb_connected_obj, supervisor_runtime_get_usb_connected); diff --git a/shared-bindings/support_matrix.rst b/shared-bindings/support_matrix.rst index a2fb7987d2..2d2172122a 100644 --- a/shared-bindings/support_matrix.rst +++ b/shared-bindings/support_matrix.rst @@ -6,6 +6,11 @@ Module Support Matrix - Which Modules Are Available on Which Boards The following table lists the available built-in modules for each CircuitPython capable board. +.. raw:: html + +

(all)

+ +.. rst-class:: support-matrix-table .. list-table:: :header-rows: 1 :widths: 7, 50 diff --git a/shared-bindings/synthio/MidiTrack.c b/shared-bindings/synthio/MidiTrack.c new file mode 100644 index 0000000000..65fc7a4ee1 --- /dev/null +++ b/shared-bindings/synthio/MidiTrack.c @@ -0,0 +1,169 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "lib/utils/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/util.h" +#include "shared-bindings/synthio/MidiTrack.h" +#include "supervisor/shared/translate.h" + +//| class MidiTrack: +//| """Simple square-wave MIDI synth""" +//| +//| def __init__(self, buffer: ReadableBuffer, tempo: int, *, sample_rate: int = 11025) -> None: +//| """Create a MidiTrack from the given stream of MIDI events. Only "Note On" and "Note Off" events +//| are supported; channel numbers and key velocities are ignored. Up to two notes may be on at the +//| same time. +//| +//| :param ~_typing.ReadableBuffer buffer: Stream of MIDI events, as stored in a MIDI file track chunk +//| :param int tempo: Tempo of the streamed events, in MIDI ticks per second +//| :param int sample_rate: The desired playback sample rate; higher sample rate requires more memory +//| +//| Simple melody:: +//| +//| import audioio +//| import board +//| import synthio +//| +//| dac = audioio.AudioOut(board.SPEAKER) +//| melody = synthio.MidiTrack(b"\\0\\x90H\\0*\\x80H\\0\\6\\x90J\\0*\\x80J\\0\\6\\x90L\\0*\\x80L\\0\\6\\x90J\\0" + +//| b"*\\x80J\\0\\6\\x90H\\0*\\x80H\\0\\6\\x90J\\0*\\x80J\\0\\6\\x90L\\0T\\x80L\\0" + +//| b"\\x0c\\x90H\\0T\\x80H\\0\\x0c\\x90H\\0T\\x80H\\0", tempo=640) +//| dac.play(melody) +//| print("playing") +//| while dac.playing: +//| pass +//| print("stopped")""" +//| ... +//| +STATIC mp_obj_t synthio_miditrack_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_buffer, ARG_tempo, ARG_sample_rate }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_buffer, MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_tempo, MP_ARG_INT | MP_ARG_REQUIRED }, + { MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 11025} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_READ); + + synthio_miditrack_obj_t *self = m_new_obj(synthio_miditrack_obj_t); + self->base.type = &synthio_miditrack_type; + + common_hal_synthio_miditrack_construct(self, + (uint8_t *)bufinfo.buf, bufinfo.len, + args[ARG_tempo].u_int, + args[ARG_sample_rate].u_int); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialises the MidiTrack and releases any hardware resources for reuse.""" +//| ... +//| +STATIC mp_obj_t synthio_miditrack_deinit(mp_obj_t self_in) { + synthio_miditrack_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_synthio_miditrack_deinit(self); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(synthio_miditrack_deinit_obj, synthio_miditrack_deinit); + +STATIC void check_for_deinit(synthio_miditrack_obj_t *self) { + if (common_hal_synthio_miditrack_deinited(self)) { + raise_deinited_error(); + } +} + +//| def __enter__(self) -> MidiTrack: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes the hardware when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +STATIC mp_obj_t synthio_miditrack_obj___exit__(size_t n_args, const mp_obj_t *args) { + (void)n_args; + common_hal_synthio_miditrack_deinit(args[0]); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(synthio_miditrack___exit___obj, 4, 4, synthio_miditrack_obj___exit__); + +//| sample_rate: Optional[int] +//| """32 bit value that tells how quickly samples are played in Hertz (cycles per second).""" +//| +STATIC mp_obj_t synthio_miditrack_obj_get_sample_rate(mp_obj_t self_in) { + synthio_miditrack_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return MP_OBJ_NEW_SMALL_INT(common_hal_synthio_miditrack_get_sample_rate(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(synthio_miditrack_get_sample_rate_obj, synthio_miditrack_obj_get_sample_rate); + +const mp_obj_property_t synthio_miditrack_sample_rate_obj = { + .base.type = &mp_type_property, + .proxy = {(mp_obj_t)&synthio_miditrack_get_sample_rate_obj, + (mp_obj_t)&mp_const_none_obj, + (mp_obj_t)&mp_const_none_obj}, +}; + +STATIC const mp_rom_map_elem_t synthio_miditrack_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&synthio_miditrack_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&synthio_miditrack___exit___obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_sample_rate), MP_ROM_PTR(&synthio_miditrack_sample_rate_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(synthio_miditrack_locals_dict, synthio_miditrack_locals_dict_table); + +STATIC const audiosample_p_t synthio_miditrack_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .sample_rate = (audiosample_sample_rate_fun)common_hal_synthio_miditrack_get_sample_rate, + .bits_per_sample = (audiosample_bits_per_sample_fun)common_hal_synthio_miditrack_get_bits_per_sample, + .channel_count = (audiosample_channel_count_fun)common_hal_synthio_miditrack_get_channel_count, + .reset_buffer = (audiosample_reset_buffer_fun)synthio_miditrack_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)synthio_miditrack_get_buffer, + .get_buffer_structure = (audiosample_get_buffer_structure_fun)synthio_miditrack_get_buffer_structure, +}; + +const mp_obj_type_t synthio_miditrack_type = { + { &mp_type_type }, + .name = MP_QSTR_MidiTrack, + .make_new = synthio_miditrack_make_new, + .locals_dict = (mp_obj_dict_t *)&synthio_miditrack_locals_dict, + .protocol = &synthio_miditrack_proto, +}; diff --git a/shared-bindings/synthio/MidiTrack.h b/shared-bindings/synthio/MidiTrack.h new file mode 100644 index 0000000000..d44d4c3bb7 --- /dev/null +++ b/shared-bindings/synthio/MidiTrack.h @@ -0,0 +1,43 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * 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. + */ + +#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_SYNTHIO_MIDITRACK_H +#define MICROPY_INCLUDED_SHARED_BINDINGS_SYNTHIO_MIDITRACK_H + +#include "shared-module/synthio/MidiTrack.h" + +extern const mp_obj_type_t synthio_miditrack_type; + +void common_hal_synthio_miditrack_construct(synthio_miditrack_obj_t *self, + const uint8_t *buffer, uint32_t len, uint32_t tempo, uint32_t sample_rate); + +void common_hal_synthio_miditrack_deinit(synthio_miditrack_obj_t *self); +bool common_hal_synthio_miditrack_deinited(synthio_miditrack_obj_t *self); +uint32_t common_hal_synthio_miditrack_get_sample_rate(synthio_miditrack_obj_t *self); +uint8_t common_hal_synthio_miditrack_get_bits_per_sample(synthio_miditrack_obj_t *self); +uint8_t common_hal_synthio_miditrack_get_channel_count(synthio_miditrack_obj_t *self); + +#endif // MICROPY_INCLUDED_SHARED_BINDINGS_SYNTHIO_MIDITRACK_H diff --git a/shared-bindings/synthio/__init__.c b/shared-bindings/synthio/__init__.c new file mode 100644 index 0000000000..d5165001fc --- /dev/null +++ b/shared-bindings/synthio/__init__.c @@ -0,0 +1,136 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "py/mperrno.h" +#include "py/obj.h" +#include "py/runtime.h" +#include "extmod/vfs_fat.h" + +#include "shared-bindings/synthio/__init__.h" +#include "shared-bindings/synthio/MidiTrack.h" + +//| """Support for MIDI synthesis""" +//| +//| def from_file(file: typing.BinaryIO, *, sample_rate: int = 11025) -> MidiTrack: +//| """Create an AudioSample from an already opened MIDI file. +//| Currently, only single-track MIDI (type 0) is supported. +//| +//| :param typing.BinaryIO file: Already opened MIDI file +//| :param int sample_rate: The desired playback sample rate; higher sample rate requires more memory +//| +//| +//| Playing a MIDI file from flash:: +//| +//| import audioio +//| import board +//| import synthio +//| +//| data = open("single-track.midi", "rb") +//| midi = synthio.from_file(data) +//| a = audioio.AudioOut(board.A0) +//| +//| print("playing") +//| a.play(midi) +//| while a.playing: +//| pass +//| print("stopped")""" +//| ... +//| +STATIC mp_obj_t synthio_from_file(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_file, ARG_sample_rate }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_file, MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 11025} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + if (!MP_OBJ_IS_TYPE(args[ARG_file].u_obj, &mp_type_fileio)) { + mp_raise_TypeError(translate("file must be a file opened in byte mode")); + } + pyb_file_obj_t *file = MP_OBJ_TO_PTR(args[ARG_file].u_obj); + + uint8_t chunk_header[14]; + f_rewind(&file->fp); + UINT bytes_read; + if (f_read(&file->fp, chunk_header, sizeof(chunk_header), &bytes_read) != FR_OK) { + mp_raise_OSError(MP_EIO); + } + if (bytes_read != sizeof(chunk_header) || + memcmp(chunk_header, "MThd\0\0\0\6\0\0\0\1", 12)) { + mp_raise_ValueError(translate("Invalid MIDI file")); + // TODO: for a multi-track MIDI (type 1), return an AudioMixer + } + + uint16_t tempo; + if (chunk_header[12] & 0x80) { + tempo = -(int8_t)chunk_header[12] * chunk_header[13]; + } else { + tempo = 2 * ((chunk_header[12] << 8) | chunk_header[13]); + } + + if (f_read(&file->fp, chunk_header, 8, &bytes_read) != FR_OK) { + mp_raise_OSError(MP_EIO); + } + if (bytes_read != 8 || memcmp(chunk_header, "MTrk", 4)) { + mp_raise_ValueError(translate("Invalid MIDI file")); + } + uint32_t track_size = (chunk_header[4] << 24) | + (chunk_header[5] << 16) | (chunk_header[6] << 8) | chunk_header[7]; + uint8_t *buffer = m_malloc(track_size, false); + if (f_read(&file->fp, buffer, track_size, &bytes_read) != FR_OK) { + mp_raise_OSError(MP_EIO); + } + if (bytes_read != track_size) { + mp_raise_ValueError(translate("Invalid MIDI file")); + } + + synthio_miditrack_obj_t *result = m_new_obj(synthio_miditrack_obj_t); + result->base.type = &synthio_miditrack_type; + + common_hal_synthio_miditrack_construct(result, buffer, track_size, + tempo, args[ARG_sample_rate].u_int); + + m_free(buffer); + + return MP_OBJ_FROM_PTR(result); +} +MP_DEFINE_CONST_FUN_OBJ_KW(synthio_from_file_obj, 1, synthio_from_file); + + +STATIC const mp_rom_map_elem_t synthio_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_synthio) }, + { MP_ROM_QSTR(MP_QSTR_MidiTrack), MP_ROM_PTR(&synthio_miditrack_type) }, + { MP_ROM_QSTR(MP_QSTR_from_file), MP_ROM_PTR(&synthio_from_file_obj) }, +}; + +STATIC MP_DEFINE_CONST_DICT(synthio_module_globals, synthio_module_globals_table); + +const mp_obj_module_t synthio_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&synthio_module_globals, +}; diff --git a/shared-bindings/synthio/__init__.h b/shared-bindings/synthio/__init__.h new file mode 100644 index 0000000000..14af1a5805 --- /dev/null +++ b/shared-bindings/synthio/__init__.h @@ -0,0 +1,34 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * 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. + */ + +#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_SYNTHIO___INIT___H +#define MICROPY_INCLUDED_SHARED_BINDINGS_SYNTHIO___INIT___H + +#include "py/obj.h" + +// Nothing now. + +#endif // MICROPY_INCLUDED_SHARED_BINDINGS_SYNTHIO___INIT___H diff --git a/shared-module/audiomixer/Mixer.c b/shared-module/audiomixer/Mixer.c index fdcd2dbfbf..20731933c4 100644 --- a/shared-module/audiomixer/Mixer.c +++ b/shared-module/audiomixer/Mixer.c @@ -103,11 +103,28 @@ void audiomixer_mixer_reset_buffer(audiomixer_mixer_obj_t *self, __attribute__((always_inline)) static inline uint32_t add16signed(uint32_t a, uint32_t b) { + #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) return __QADD16(a, b); + #else + uint32_t result = 0; + for (int8_t i = 0; i < 2; i++) { + int16_t ai = a >> (sizeof(int16_t) * 8 * i); + int16_t bi = b >> (sizeof(int16_t) * 8 * i); + int32_t intermediate = (int32_t)ai + bi; + if (intermediate > SHRT_MAX) { + intermediate = SHRT_MAX; + } else if (intermediate < SHRT_MIN) { + intermediate = SHRT_MIN; + } + result |= (((uint32_t)intermediate) & 0xffff) << (sizeof(int16_t) * 8 * i); + } + return result; + #endif } __attribute__((always_inline)) static inline uint32_t mult16signed(uint32_t val, int32_t mul) { + #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) mul <<= 16; int32_t hi, lo; enum { bits = 16 }; // saturate to 16 bits @@ -118,18 +135,46 @@ static inline uint32_t mult16signed(uint32_t val, int32_t mul) { asm volatile ("ssat %0, %1, %2, asr %3" : "=r" (hi) : "I" (bits), "r" (hi), "I" (shift)); asm volatile ("pkhbt %0, %1, %2, lsl #16" : "=r" (val) : "r" (lo), "r" (hi)); // pack return val; + #else + uint32_t result = 0; + float mod_mul = (float)mul / (float)((1 << 15) - 1); + for (int8_t i = 0; i < 2; i++) { + int16_t ai = (val >> (sizeof(uint16_t) * 8 * i)); + int32_t intermediate = ai * mod_mul; + if (intermediate > SHRT_MAX) { + intermediate = SHRT_MAX; + } else if (intermediate < SHRT_MIN) { + intermediate = SHRT_MIN; + } + intermediate &= 0x0000FFFF; + result |= (((uint32_t)intermediate)) << (sizeof(int16_t) * 8 * i); + } + return result; + #endif } static inline uint32_t tounsigned8(uint32_t val) { + #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) return __UADD8(val, 0x80808080); + #else + return val ^ 0x80808080; + #endif } static inline uint32_t tounsigned16(uint32_t val) { + #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) return __UADD16(val, 0x80008000); + #else + return val ^ 0x80008000; + #endif } static inline uint32_t tosigned16(uint32_t val) { + #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) return __UADD16(val, 0x80008000); + #else + return val ^ 0x80008000; + #endif } static inline uint32_t unpack8(uint16_t val) { diff --git a/shared-module/displayio/ColorConverter.c b/shared-module/displayio/ColorConverter.c index be9e9dc1a5..47cb903f3f 100644 --- a/shared-module/displayio/ColorConverter.c +++ b/shared-module/displayio/ColorConverter.c @@ -41,9 +41,10 @@ uint32_t displayio_colorconverter_dither_noise_2(uint32_t x, uint32_t y) { return displayio_colorconverter_dither_noise_1(x + y * 0xFFFF); } -void common_hal_displayio_colorconverter_construct(displayio_colorconverter_t *self, bool dither) { +void common_hal_displayio_colorconverter_construct(displayio_colorconverter_t *self, bool dither, displayio_colorspace_t input_colorspace) { self->dither = dither; self->transparent_color = NO_TRANSPARENT_COLOR; + self->input_colorspace = input_colorspace; } uint16_t displayio_colorconverter_compute_rgb565(uint32_t color_rgb888) { @@ -152,6 +153,33 @@ void displayio_colorconverter_convert(displayio_colorconverter_t *self, const _d return; } + switch (self->input_colorspace) { + case DISPLAYIO_COLORSPACE_RGB565_SWAPPED: + pixel = __builtin_bswap16(pixel); + FALLTHROUGH; + case DISPLAYIO_COLORSPACE_RGB565: { + uint32_t r8 = (pixel >> 11) << 3; + uint32_t g8 = ((pixel >> 5) << 2) & 0xff; + uint32_t b8 = (pixel << 3) & 0xff; + pixel = (r8 << 16) | (g8 << 8) | b8; + } + break; + + case DISPLAYIO_COLORSPACE_RGB555_SWAPPED: + pixel = __builtin_bswap16(pixel); + FALLTHROUGH; + case DISPLAYIO_COLORSPACE_RGB555: { + uint32_t r8 = (pixel >> 10) << 3; + uint32_t g8 = ((pixel >> 5) << 3) & 0xff; + uint32_t b8 = (pixel << 3) & 0xff; + pixel = (r8 << 16) | (g8 << 8) | b8; + } + break; + + case DISPLAYIO_COLORSPACE_RGB888: + break; + } + if (self->dither) { uint8_t randr = (displayio_colorconverter_dither_noise_2(input_pixel->tile_x,input_pixel->tile_y)); uint8_t randg = (displayio_colorconverter_dither_noise_2(input_pixel->tile_x + 33,input_pixel->tile_y)); diff --git a/shared-module/displayio/ColorConverter.h b/shared-module/displayio/ColorConverter.h index ebe4b27194..55f86982dc 100644 --- a/shared-module/displayio/ColorConverter.h +++ b/shared-module/displayio/ColorConverter.h @@ -36,6 +36,7 @@ typedef struct { mp_obj_base_t base; bool dither; + uint8_t input_colorspace; uint32_t transparent_color; } displayio_colorconverter_t; diff --git a/shared-module/rotaryio/IncrementalEncoder.c b/shared-module/rotaryio/IncrementalEncoder.c new file mode 100644 index 0000000000..330895606e --- /dev/null +++ b/shared-module/rotaryio/IncrementalEncoder.c @@ -0,0 +1,86 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * 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. + */ + +#if CIRCUITPY_ROTARYIO && CIRCUITPY_ROTARYIO_SOFTENCODER +#include "shared-module/rotaryio/IncrementalEncoder.h" +#include "common-hal/rotaryio/IncrementalEncoder.h" + +void shared_module_softencoder_state_init(rotaryio_incrementalencoder_obj_t *self, uint8_t quiescent_state) { + self->state = quiescent_state; + self->quarter_count = 0; + common_hal_rotaryio_incrementalencoder_set_position(self, 0); +} + +void shared_module_softencoder_state_update(rotaryio_incrementalencoder_obj_t *self, uint8_t new_state) { + #define BAD 7 + static const int8_t transitions[16] = { + 0, // 00 -> 00 no movement + -1, // 00 -> 01 3/4 ccw (11 detent) or 1/4 ccw (00 at detent) + +1, // 00 -> 10 3/4 cw or 1/4 cw + BAD, // 00 -> 11 non-Gray-code transition + +1, // 01 -> 00 2/4 or 4/4 cw + 0, // 01 -> 01 no movement + BAD, // 01 -> 10 non-Gray-code transition + -1, // 01 -> 11 4/4 or 2/4 ccw + -1, // 10 -> 00 2/4 or 4/4 ccw + BAD, // 10 -> 01 non-Gray-code transition + 0, // 10 -> 10 no movement + +1, // 10 -> 11 4/4 or 2/4 cw + BAD, // 11 -> 00 non-Gray-code transition + +1, // 11 -> 01 1/4 or 3/4 cw + -1, // 11 -> 10 1/4 or 3/4 ccw + 0, // 11 -> 11 no movement + }; + + new_state &= 0x3; + int idx = (self->state << 2) | new_state; + self->state = new_state; + + int8_t quarter_incr = transitions[idx]; + if (quarter_incr == BAD) { + // Missed a transition. We don't know which way we're going, so do nothing. + return; + } + + self->quarter_count += quarter_incr; + + if (self->quarter_count >= 4) { + self->position += 1; + self->quarter_count = 0; + } else if (self->quarter_count <= -4) { + self->position -= 1; + self->quarter_count = 0; + } +} + +mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t *self) { + return self->position; +} + +void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t *self, mp_int_t position) { + self->position = position; +} +#endif diff --git a/shared-module/rotaryio/IncrementalEncoder.h b/shared-module/rotaryio/IncrementalEncoder.h new file mode 100644 index 0000000000..82a5644b47 --- /dev/null +++ b/shared-module/rotaryio/IncrementalEncoder.h @@ -0,0 +1,34 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * 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. + */ + +#pragma once + +#include "common-hal/rotaryio/IncrementalEncoder.h" + +void shared_module_softencoder_state_init(rotaryio_incrementalencoder_obj_t *self, uint8_t quiescent_state); +void shared_module_softencoder_state_update(rotaryio_incrementalencoder_obj_t *self, uint8_t new_state); +mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t *self); +void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t *self, mp_int_t position); diff --git a/shared-module/storage/__init__.c b/shared-module/storage/__init__.c index 8f361cb2d1..0a64a1e3a7 100644 --- a/shared-module/storage/__init__.c +++ b/shared-module/storage/__init__.c @@ -224,7 +224,9 @@ void common_hal_storage_remount(const char *mount_path, bool readonly, bool disa } void common_hal_storage_erase_filesystem(void) { + #if CIRCUITPY_USB usb_disconnect(); + #endif mp_hal_delay_ms(1000); filesystem_init(false, true); // Force a re-format. common_hal_mcu_reset(); diff --git a/shared-module/struct/__init__.c b/shared-module/struct/__init__.c index 7a7ea845e7..258036c93b 100644 --- a/shared-module/struct/__init__.c +++ b/shared-module/struct/__init__.c @@ -153,9 +153,11 @@ void shared_modules_struct_pack_into(mp_obj_t fmt_in, byte *p, byte *end_p, size p += sz; } else { while (sz--) { - mp_binary_set_val(fmt_type, *fmt, args[i], &p); // Pad bytes don't have a corresponding argument. - if (*fmt != 'x') { + if (*fmt == 'x') { + mp_binary_set_val(fmt_type, *fmt, MP_OBJ_NEW_SMALL_INT(0), &p); + } else { + mp_binary_set_val(fmt_type, *fmt, args[i], &p); i++; } } diff --git a/shared-module/synthio/MidiTrack.c b/shared-module/synthio/MidiTrack.c new file mode 100644 index 0000000000..0827945ab5 --- /dev/null +++ b/shared-module/synthio/MidiTrack.c @@ -0,0 +1,212 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/runtime.h" +#include "shared-bindings/synthio/MidiTrack.h" + +#define LOUDNESS 0x4000 // 0.5 +#define BITS_PER_SAMPLE 16 +#define BYTES_PER_SAMPLE (BITS_PER_SAMPLE / 8) +#define SILENCE 0x80 + +STATIC uint8_t parse_note(const uint8_t *buffer, uint32_t len, uint32_t *pos) { + if (*pos + 1 >= len) { + mp_raise_ValueError_varg(translate("Error in MIDI stream at position %d"), *pos); + } + uint8_t note = buffer[(*pos)++]; + if (note > 127 || buffer[(*pos)++] > 127) { + mp_raise_ValueError_varg(translate("Error in MIDI stream at position %d"), *pos); + } + return note; +} + +STATIC void terminate_span(synthio_miditrack_obj_t *self, uint16_t *dur, uint16_t *max_dur) { + if (*dur) { + self->track[self->total_spans - 1].dur = *dur; + if (*dur > *max_dur) { + *max_dur = *dur; + } + *dur = 0; + } else { + self->total_spans--; + } +} + +STATIC void add_span(synthio_miditrack_obj_t *self, uint8_t note1, uint8_t note2) { + synthio_midi_span_t span = { 0, {note1, note2} }; + self->track = m_realloc(self->track, + (self->total_spans + 1) * sizeof(synthio_midi_span_t)); + self->track[self->total_spans++] = span; +} + +void common_hal_synthio_miditrack_construct(synthio_miditrack_obj_t *self, + const uint8_t *buffer, uint32_t len, uint32_t tempo, uint32_t sample_rate) { + + synthio_midi_span_t initial = { 0, {SILENCE, SILENCE} }; + self->sample_rate = sample_rate; + self->track = m_malloc(sizeof(synthio_midi_span_t), false); + self->next_span = 0; + self->total_spans = 1; + *self->track = initial; + + uint16_t dur = 0, max_dur = 0; + uint32_t pos = 0; + while (pos < len) { + uint8_t c; + uint32_t delta = 0; + do { + c = buffer[pos++]; + delta <<= 7; + delta |= c & 0x7f; + } while ((c & 0x80) && (pos < len)); + + if (c & 0x80) { + mp_raise_ValueError_varg(translate("Error in MIDI stream at position %d"), pos); + } + + dur += delta * sample_rate / tempo; + + switch (buffer[pos++] >> 4) { + case 8: { // Note Off + uint8_t note = parse_note(buffer, len, &pos); + + // Ignore if not a note which is playing + synthio_midi_span_t last_span = self->track[self->total_spans - 1]; + if (last_span.note[0] == note || last_span.note[1] == note) { + terminate_span(self, &dur, &max_dur); + if (last_span.note[0] == note) { + add_span(self, last_span.note[1], SILENCE); + } else { + add_span(self, last_span.note[0], SILENCE); + } + } + break; + } + case 9: { // Note On + uint8_t note = parse_note(buffer, len, &pos); + + // Ignore if two notes are already playing + synthio_midi_span_t last_span = self->track[self->total_spans - 1]; + if (last_span.note[1] == SILENCE) { + terminate_span(self, &dur, &max_dur); + if (last_span.note[0] == SILENCE) { + add_span(self, note, SILENCE); + } else { + add_span(self, last_span.note[0], note); + } + } + break; + } + case 10: + case 11: + case 14: // two data bytes to ignore + parse_note(buffer, len, &pos); + break; + case 12: + case 13: // one data byte to ignore + if (pos >= len || buffer[pos++] > 127) { + mp_raise_ValueError_varg(translate("Error in MIDI stream at position %d"), pos); + } + break; + case 15: // the full syntax is too complicated, just assume it's "End of Track" event + pos = len; + break; + default: // invalid event + mp_raise_ValueError_varg(translate("Error in MIDI stream at position %d"), pos); + } + } + terminate_span(self, &dur, &max_dur); + + self->buffer_length = max_dur * BYTES_PER_SAMPLE; + self->buffer = m_malloc(self->buffer_length, false); +} + +void common_hal_synthio_miditrack_deinit(synthio_miditrack_obj_t *self) { + m_free(self->buffer); + self->buffer = NULL; + m_free(self->track); + self->track = NULL; +} +bool common_hal_synthio_miditrack_deinited(synthio_miditrack_obj_t *self) { + return self->buffer == NULL; +} + +uint32_t common_hal_synthio_miditrack_get_sample_rate(synthio_miditrack_obj_t *self) { + return self->sample_rate; +} +uint8_t common_hal_synthio_miditrack_get_bits_per_sample(synthio_miditrack_obj_t *self) { + return BITS_PER_SAMPLE; +} +uint8_t common_hal_synthio_miditrack_get_channel_count(synthio_miditrack_obj_t *self) { + return 1; +} + +void synthio_miditrack_reset_buffer(synthio_miditrack_obj_t *self, + bool single_channel, uint8_t channel) { + + self->next_span = 0; +} + +STATIC const uint16_t notes[] = {8372, 8870, 9397, 9956, 10548, 11175, 11840, + 12544, 13290, 14080, 14917, 15804}; // 9th octave + +audioio_get_buffer_result_t synthio_miditrack_get_buffer(synthio_miditrack_obj_t *self, + bool single_channel, uint8_t channel, uint8_t **buffer, uint32_t *buffer_length) { + + if (self->next_span >= self->total_spans) { + *buffer_length = 0; + return GET_BUFFER_DONE; + } + + synthio_midi_span_t span = self->track[self->next_span++]; + *buffer_length = span.dur * BYTES_PER_SAMPLE; + uint8_t octave1 = span.note[0] / 12; // 0..10 + uint8_t octave2 = span.note[1] / 12; // 0..10 + int32_t base_freq1 = notes[span.note[0] % 12]; + int32_t base_freq2 = notes[span.note[1] % 12]; + int32_t sample_rate = self->sample_rate; + + for (uint16_t i = 0; i < span.dur; i++) { + int16_t semiperiod1 = span.note[0] == SILENCE ? 0 : + ((base_freq1 * i * 2) / sample_rate) >> (10 - octave1); + int16_t semiperiod2 = span.note[1] == SILENCE ? semiperiod1 : + ((base_freq2 * i * 2) / sample_rate) >> (10 - octave2); + self->buffer[i] = ((semiperiod1 % 2 + semiperiod2 % 2) - 1) * LOUDNESS; + } + *buffer = (uint8_t *)self->buffer; + + return self->next_span >= self->total_spans ? + GET_BUFFER_DONE : GET_BUFFER_MORE_DATA; +} + +void synthio_miditrack_get_buffer_structure(synthio_miditrack_obj_t *self, bool single_channel, + bool *single_buffer, bool *samples_signed, uint32_t *max_buffer_length, uint8_t *spacing) { + + *single_buffer = true; + *samples_signed = true; + *max_buffer_length = self->buffer_length; + *spacing = 1; +} diff --git a/shared-module/synthio/MidiTrack.h b/shared-module/synthio/MidiTrack.h new file mode 100644 index 0000000000..bd058daaee --- /dev/null +++ b/shared-module/synthio/MidiTrack.h @@ -0,0 +1,65 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * 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. + */ + +#ifndef MICROPY_INCLUDED_SHARED_MODULE_SYNTHIO_MIDITRACK_H +#define MICROPY_INCLUDED_SHARED_MODULE_SYNTHIO_MIDITRACK_H + +#include "py/obj.h" + +#include "shared-module/synthio/__init__.h" + +typedef struct { + uint16_t dur; + uint8_t note[2]; +} synthio_midi_span_t; + +typedef struct { + mp_obj_base_t base; + uint32_t sample_rate; + uint16_t *buffer; + uint16_t buffer_length; + synthio_midi_span_t *track; + uint16_t next_span; + uint16_t total_spans; +} synthio_miditrack_obj_t; + + +// These are not available from Python because it may be called in an interrupt. +void synthio_miditrack_reset_buffer(synthio_miditrack_obj_t *self, + bool single_channel, + uint8_t channel); + +audioio_get_buffer_result_t synthio_miditrack_get_buffer(synthio_miditrack_obj_t *self, + bool single_channel, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes + +void synthio_miditrack_get_buffer_structure(synthio_miditrack_obj_t *self, bool single_channel, + bool *single_buffer, bool *samples_signed, + uint32_t *max_buffer_length, uint8_t *spacing); + +#endif // MICROPY_INCLUDED_SHARED_MODULE_SYNTHIO_MIDITRACK_H diff --git a/shared-module/synthio/__init__.c b/shared-module/synthio/__init__.c new file mode 100644 index 0000000000..e69de29bb2 diff --git a/shared-module/synthio/__init__.h b/shared-module/synthio/__init__.h new file mode 100644 index 0000000000..d9d98a5341 --- /dev/null +++ b/shared-module/synthio/__init__.h @@ -0,0 +1,32 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * 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. + */ + +#ifndef MICROPY_INCLUDED_SHARED_MODULE_SYNTHIO__INIT__H +#define MICROPY_INCLUDED_SHARED_MODULE_SYNTHIO__INIT__H + +#include "shared-module/audiocore/__init__.h" + +#endif // MICROPY_INCLUDED_SHARED_MODULE_SYNTHIO__INIT__H diff --git a/supervisor/shared/cpu.c b/supervisor/shared/cpu.c new file mode 100644 index 0000000000..510225d197 --- /dev/null +++ b/supervisor/shared/cpu.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "supervisor/shared/cpu.h" + +bool cpu_interrupt_active(void) { + #if defined(__ARM_ARCH) && (__ARM_ARCH >= 6) + // Check VECTACTIVE in ICSR. We don't need to disable interrupts because if + // one occurs after we read, we won't continue until it is resolved. + return (*((volatile uint32_t *)0xE000ED04) & 0x1ff) != 0; + #else + // We don't know. + return false; + #endif +} diff --git a/supervisor/shared/cpu.h b/supervisor/shared/cpu.h new file mode 100644 index 0000000000..9e2bed1e55 --- /dev/null +++ b/supervisor/shared/cpu.h @@ -0,0 +1,36 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * 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. + */ + +#ifndef MICROPY_INCLUDED_SUPERVISOR_SHARED_CPU_H +#define MICROPY_INCLUDED_SUPERVISOR_SHARED_CPU_H + +#include +#include + +// True when we're in an interrupt handler. +bool cpu_interrupt_active(void); + +#endif // MICROPY_INCLUDED_SUPERVISOR_SHARED_CPU_H diff --git a/supervisor/shared/safe_mode.c b/supervisor/shared/safe_mode.c index f9e787c159..cd73e1b9f9 100644 --- a/supervisor/shared/safe_mode.c +++ b/supervisor/shared/safe_mode.c @@ -170,13 +170,13 @@ void print_safe_mode_message(safe_mode_t reason) { serial_write_compressed(translate("Crash into the HardFault_Handler.")); return; case MICROPY_NLR_JUMP_FAIL: - serial_write_compressed(translate("MicroPython NLR jump failed. Likely memory corruption.")); + serial_write_compressed(translate("NLR jump failed. Likely memory corruption.")); return; case MICROPY_FATAL_ERROR: - serial_write_compressed(translate("MicroPython fatal error.")); + serial_write_compressed(translate("Fatal error.")); break; case GC_ALLOC_OUTSIDE_VM: - serial_write_compressed(translate("Attempted heap allocation when MicroPython VM not running.")); + serial_write_compressed(translate("Attempted heap allocation when VM not running.")); break; #ifdef SOFTDEVICE_PRESENT // defined in ports/nrf/bluetooth/bluetooth_common.mk diff --git a/supervisor/shared/serial.c b/supervisor/shared/serial.c index 268cebdbba..bd2bf4ba22 100644 --- a/supervisor/shared/serial.c +++ b/supervisor/shared/serial.c @@ -28,6 +28,7 @@ #include "py/mpconfig.h" +#include "supervisor/shared/cpu.h" #include "supervisor/shared/display.h" #include "shared-bindings/terminalio/Terminal.h" #include "supervisor/serial.h" @@ -136,6 +137,10 @@ void serial_write_substring(const char *text, uint32_t length) { uint32_t count = 0; while (count < length && tud_cdc_connected()) { count += tud_cdc_write(text + count, length - count); + // If we're in an interrupt, then don't wait for more room. Queue up what we can. + if (cpu_interrupt_active()) { + break; + } usb_background(); } diff --git a/supervisor/shared/translate.c b/supervisor/shared/translate.c index c99cbf180d..7afbd43e21 100644 --- a/supervisor/shared/translate.c +++ b/supervisor/shared/translate.c @@ -129,7 +129,7 @@ __attribute__((always_inline)) #endif const compressed_string_t *translate(const char *original) { #ifndef NO_QSTR - #define QDEF(id, str) + #define QDEF(id, hash, len, str) #define TRANSLATION(id, firstbyte, ...) if (strcmp(original, id) == 0) { static const compressed_string_t v = { .data = firstbyte, .tail = { __VA_ARGS__ } }; return &v; } else #include "genhdr/qstrdefs.generated.h" #undef TRANSLATION diff --git a/supervisor/shared/workflow.h b/supervisor/shared/workflow.h index 22a9fa4684..2596dd2c45 100644 --- a/supervisor/shared/workflow.h +++ b/supervisor/shared/workflow.h @@ -26,7 +26,5 @@ #pragma once -extern void supervisor_workflow_reset(void); - extern bool supervisor_workflow_connecting(void); extern bool supervisor_workflow_active(void); diff --git a/supervisor/stub/serial.c b/supervisor/stub/serial.c index fc8bd221e7..6ca14fcfde 100644 --- a/supervisor/stub/serial.c +++ b/supervisor/stub/serial.c @@ -25,6 +25,7 @@ */ #include "supervisor/serial.h" +#include "supervisor/workflow.h" void serial_early_init(void) { @@ -49,3 +50,6 @@ bool serial_bytes_available(void) { void serial_write(const char *text) { (void)text; } + +void supervisor_workflow_reset(void) { +} diff --git a/supervisor/supervisor.mk b/supervisor/supervisor.mk index 1210896c7f..ad3a2c0fdc 100644 --- a/supervisor/supervisor.mk +++ b/supervisor/supervisor.mk @@ -4,6 +4,7 @@ SRC_SUPERVISOR = \ supervisor/shared/autoreload.c \ supervisor/shared/background_callback.c \ supervisor/shared/board.c \ + supervisor/shared/cpu.c \ supervisor/shared/filesystem.c \ supervisor/shared/flash.c \ supervisor/shared/micropython.c \ @@ -58,7 +59,7 @@ $(BUILD)/supervisor/shared/external_flash/external_flash.o: $(HEADER_BUILD)/devi endif -ifeq ($(USB),FALSE) +ifeq ($(CIRCUITPY_USB),0) ifeq ($(wildcard supervisor/serial.c),) SRC_SUPERVISOR += supervisor/stub/serial.c else @@ -120,8 +121,6 @@ else lib/tinyusb/src/class/vendor/vendor_device.c \ endif - - CFLAGS += -DUSB_AVAILABLE endif SUPERVISOR_O = $(addprefix $(BUILD)/, $(SRC_SUPERVISOR:.c=.o)) diff --git a/supervisor/workflow.h b/supervisor/workflow.h index 4008b83a11..27d063503a 100755 --- a/supervisor/workflow.h +++ b/supervisor/workflow.h @@ -26,5 +26,7 @@ #pragma once +void supervisor_workflow_reset(void); + // True when the user could be actively iterating on their code. bool workflow_active(void); diff --git a/tests/basics/async_with_break.py b/tests/basics/async_with_break.py new file mode 100644 index 0000000000..39bcbccb02 --- /dev/null +++ b/tests/basics/async_with_break.py @@ -0,0 +1,59 @@ +# test async with, escaped by a break + +class AContext: + async def __aenter__(self): + print('enter') + return 1 + async def __aexit__(self, exc_type, exc, tb): + print('exit', exc_type, exc) + +async def f1(): + while 1: + async with AContext(): + print('body') + break + print('no 1') + print('no 2') + +o = f1() +try: + print(o.send(None)) +except StopIteration: + print('finished') + +async def f2(): + while 1: + try: + async with AContext(): + print('body') + break + print('no 1') + finally: + print('finally') + print('no 2') + +o = f2() +try: + print(o.send(None)) +except StopIteration: + print('finished') + +async def f3(): + while 1: + try: + try: + async with AContext(): + print('body') + break + print('no 1') + finally: + print('finally inner') + finally: + print('finally outer') + print('no 2') + +o = f3() +try: + print(o.send(None)) +except StopIteration: + print('finished') diff --git a/tests/basics/async_with_break.py.exp b/tests/basics/async_with_break.py.exp new file mode 100644 index 0000000000..d077a88fad --- /dev/null +++ b/tests/basics/async_with_break.py.exp @@ -0,0 +1,15 @@ +enter +body +exit None None +finished +enter +body +exit None None +finally +finished +enter +body +exit None None +finally inner +finally outer +finished diff --git a/tests/basics/async_with_return.py b/tests/basics/async_with_return.py new file mode 100644 index 0000000000..9af88b839f --- /dev/null +++ b/tests/basics/async_with_return.py @@ -0,0 +1,50 @@ +# test async with, escaped by a return + +class AContext: + async def __aenter__(self): + print('enter') + return 1 + async def __aexit__(self, exc_type, exc, tb): + print('exit', exc_type, exc) + +async def f1(): + async with AContext(): + print('body') + return + +o = f1() +try: + o.send(None) +except StopIteration: + print('finished') + +async def f2(): + try: + async with AContext(): + print('body') + return + finally: + print('finally') + +o = f2() +try: + o.send(None) +except StopIteration: + print('finished') + +async def f3(): + try: + try: + async with AContext(): + print('body') + return + finally: + print('finally inner') + finally: + print('finally outer') + +o = f3() +try: + o.send(None) +except StopIteration: + print('finished') diff --git a/tests/basics/async_with_return.py.exp b/tests/basics/async_with_return.py.exp new file mode 100644 index 0000000000..d077a88fad --- /dev/null +++ b/tests/basics/async_with_return.py.exp @@ -0,0 +1,15 @@ +enter +body +exit None None +finished +enter +body +exit None None +finally +finished +enter +body +exit None None +finally inner +finally outer +finished diff --git a/tests/basics/bytearray_construct.py b/tests/basics/bytearray_construct.py index 9c8f3adaaa..75fdc41178 100644 --- a/tests/basics/bytearray_construct.py +++ b/tests/basics/bytearray_construct.py @@ -1,6 +1,7 @@ # test construction of bytearray from different objects -# bytes, tuple, list print(bytearray(b'123')) +print(bytearray('1234', 'utf-8')) +print(bytearray('12345', 'utf-8', 'strict')) print(bytearray((1, 2))) print(bytearray([1, 2])) diff --git a/tests/basics/bytes_count.py b/tests/basics/bytes_count.py index 95bcfe310e..5fa0730f5c 100644 --- a/tests/basics/bytes_count.py +++ b/tests/basics/bytes_count.py @@ -1,3 +1,9 @@ +try: + bytes.count +except AttributeError: + print("SKIP") + raise SystemExit + print(b"".count(b"")) print(b"".count(b"a")) print(b"a".count(b"")) diff --git a/tests/basics/class_getattr.py b/tests/basics/class_getattr.py index 1f875ce538..eadf2b209f 100644 --- a/tests/basics/class_getattr.py +++ b/tests/basics/class_getattr.py @@ -1,4 +1,4 @@ -# test that __getattr__, __getattrribute__ and instance members don't override builtins +# test that __getattr__ and instance members don't override builtins class C: def __init__(self): self.__add__ = lambda: print('member __add__') @@ -7,10 +7,8 @@ class C: def __getattr__(self, attr): print('__getattr__', attr) return None - def __getattrribute__(self, attr): - print('__getattrribute__', attr) - return None c = C() -c.__add__ -c + 1 # should call __add__ +c.add # should call __getattr__ +c.__add__() # should load __add__ instance directly +c + 1 # should call __add__ method directly diff --git a/tests/basics/class_staticclassmethod.py b/tests/basics/class_staticclassmethod.py index 1cb59d5c7b..edde419271 100644 --- a/tests/basics/class_staticclassmethod.py +++ b/tests/basics/class_staticclassmethod.py @@ -17,9 +17,24 @@ class C: def __add__(self, rhs): print('add', rhs) + # subscript special methods wrapped in staticmethod + @staticmethod + def __getitem__(item): + print('static get', item) + return 'item' + @staticmethod + def __setitem__(item, value): + print('static set', item, value) + @staticmethod + def __delitem__(item): + print('static del', item) + c = C() c.f(0) c.g(0) c - 1 c + 2 +print(c[1]) +c[1] = 2 +del c[3] diff --git a/tests/basics/core_class_superproperty.py b/tests/basics/core_class_superproperty.py index 69db10046a..3095ab51da 100644 --- a/tests/basics/core_class_superproperty.py +++ b/tests/basics/core_class_superproperty.py @@ -1,15 +1,19 @@ """ test that calling super() getter property in subclass will return the value """ + + class A: @property def p(self): - return {"a":10} + return {"a": 10} + class AA(A): @property def p(self): return super().p + a = AA() print(a.p) diff --git a/tests/basics/fun_name.py b/tests/basics/fun_name.py index a724f41118..53ca935616 100644 --- a/tests/basics/fun_name.py +++ b/tests/basics/fun_name.py @@ -15,3 +15,10 @@ try: except AttributeError: print('SKIP') raise SystemExit + +# __name__ of a bound native method is not implemented in uPy +# the test here is to make sure it doesn't crash +try: + str((1).to_bytes.__name__) +except AttributeError: + pass diff --git a/tests/basics/gen_yield_from.py b/tests/basics/gen_yield_from.py index 4e68aec63b..037644e1ec 100644 --- a/tests/basics/gen_yield_from.py +++ b/tests/basics/gen_yield_from.py @@ -13,34 +13,6 @@ g = gen2() print(list(g)) -# Like above, but terminate subgen using StopIteration -def gen3(): - yield 1 - yield 2 - raise StopIteration - -def gen4(): - print("here1") - print((yield from gen3())) - print("here2") - -g = gen4() -print(list(g)) - -# Like above, but terminate subgen using StopIteration with value -def gen5(): - yield 1 - yield 2 - raise StopIteration(123) - -def gen6(): - print("here1") - print((yield from gen5())) - print("here2") - -g = gen6() -print(list(g)) - # StopIteration from within a Python function, within a native iterator (map), within a yield from def gen7(x): if x < 3: diff --git a/tests/basics/gen_yield_from.py.exp b/tests/basics/gen_yield_from.py.exp deleted file mode 100644 index 507f2b9caf..0000000000 --- a/tests/basics/gen_yield_from.py.exp +++ /dev/null @@ -1,14 +0,0 @@ -here1 -3 -here2 -[1, 2] -here1 -None -here2 -[1, 2] -here1 -123 -here2 -[1, 2] -444 -[0, 1, 2] diff --git a/tests/basics/gen_yield_from_close.py b/tests/basics/gen_yield_from_close.py index 8339861056..e3e0116ff7 100644 --- a/tests/basics/gen_yield_from_close.py +++ b/tests/basics/gen_yield_from_close.py @@ -55,14 +55,14 @@ except StopIteration: # Yet another variation - leaf generator gets GeneratorExit, -# but raises StopIteration instead. This still should close chain properly. +# and reraises a new GeneratorExit. This still should close chain properly. def gen5(): yield 1 try: yield 2 except GeneratorExit: - print("leaf caught GeneratorExit and raised StopIteration instead") - raise StopIteration(123) + print("leaf caught GeneratorExit and reraised GeneratorExit") + raise GeneratorExit(123) yield 3 yield 4 diff --git a/tests/basics/gen_yield_from_close.py.exp b/tests/basics/gen_yield_from_close.py.exp deleted file mode 100644 index a44d1353df..0000000000 --- a/tests/basics/gen_yield_from_close.py.exp +++ /dev/null @@ -1,20 +0,0 @@ --1 -1 -StopIteration --1 -1 -2 -leaf caught GeneratorExit and swallowed it -delegating caught GeneratorExit -StopIteration --1 -1 -2 -leaf caught GeneratorExit and raised StopIteration instead -delegating caught GeneratorExit -StopIteration -123 -RuntimeError -0 -1 -close diff --git a/tests/basics/gen_yield_from_throw.py b/tests/basics/gen_yield_from_throw.py index d6754d5cd1..703158f4d4 100644 --- a/tests/basics/gen_yield_from_throw.py +++ b/tests/basics/gen_yield_from_throw.py @@ -16,15 +16,3 @@ try: print(next(g)) except TypeError: print("got TypeError from downstream!") - -# case where generator doesn't intercept the thrown/injected exception -def gen3(): - yield 123 - yield 456 - -g3 = gen3() -print(next(g3)) -try: - g3.throw(StopIteration) -except StopIteration: - print('got StopIteration from downstream!') diff --git a/tests/basics/gen_yield_from_throw.py.exp b/tests/basics/gen_yield_from_throw.py.exp deleted file mode 100644 index 6ce97ad86e..0000000000 --- a/tests/basics/gen_yield_from_throw.py.exp +++ /dev/null @@ -1,6 +0,0 @@ -1 -got ValueError from upstream! -str1 -got TypeError from downstream! -123 -got StopIteration from downstream! diff --git a/tests/basics/gen_yield_from_throw2.py b/tests/basics/gen_yield_from_throw2.py index 5c0fc7dbc9..6b59a7835a 100644 --- a/tests/basics/gen_yield_from_throw2.py +++ b/tests/basics/gen_yield_from_throw2.py @@ -1,18 +1,24 @@ -# generator ignores a thrown GeneratorExit (this is allowed) +# outer generator ignores a thrown GeneratorExit (this is allowed) def gen(): try: yield 123 except GeneratorExit: print('GeneratorExit') - yield 456 + +def gen2(): + try: + yield from gen() + except GeneratorExit: + print('GeneratorExit outer') + yield 789 # thrown a class -g = gen() +g = gen2() print(next(g)) print(g.throw(GeneratorExit)) # thrown an instance -g = gen() +g = gen2() print(next(g)) print(g.throw(GeneratorExit())) diff --git a/tests/basics/generator_close.py b/tests/basics/generator_close.py index aa563f2a8a..1ccc78dbe4 100644 --- a/tests/basics/generator_close.py +++ b/tests/basics/generator_close.py @@ -31,13 +31,14 @@ except StopIteration: print("StopIteration") -# Throwing StopIteration in response to close() is ok +# Throwing GeneratorExit in response to close() is ok def gen2(): try: yield 1 yield 2 except: - raise StopIteration + print('raising GeneratorExit') + raise GeneratorExit g = gen2() next(g) diff --git a/tests/basics/generator_close.py.exp b/tests/basics/generator_close.py.exp deleted file mode 100644 index fcd5839357..0000000000 --- a/tests/basics/generator_close.py.exp +++ /dev/null @@ -1,10 +0,0 @@ -None -StopIteration -1 -None -StopIteration -[1, 2] -None -StopIteration -None -ValueError diff --git a/tests/basics/generator_name.py b/tests/basics/generator_name.py new file mode 100644 index 0000000000..77259a8218 --- /dev/null +++ b/tests/basics/generator_name.py @@ -0,0 +1,16 @@ +# test __name__ on generator functions + +def Fun(): + yield + +class A: + def Fun(self): + yield + +try: + print(Fun.__name__) + print(A.Fun.__name__) + print(A().Fun.__name__) +except AttributeError: + print('SKIP') + raise SystemExit diff --git a/tests/basics/generator_pep479.py b/tests/basics/generator_pep479.py new file mode 100644 index 0000000000..e422c349e7 --- /dev/null +++ b/tests/basics/generator_pep479.py @@ -0,0 +1,29 @@ +# tests for correct PEP479 behaviour (introduced in Python 3.5) + +# basic case: StopIteration is converted into a RuntimeError +def gen(): + yield 1 + raise StopIteration +g = gen() +print(next(g)) +try: + next(g) +except RuntimeError: + print('RuntimeError') + +# trying to continue a failed generator now raises StopIteration +try: + next(g) +except StopIteration: + print('StopIteration') + +# throwing a StopIteration which is uncaught will be converted into a RuntimeError +def gen(): + yield 1 + yield 2 +g = gen() +print(next(g)) +try: + g.throw(StopIteration) +except RuntimeError: + print('RuntimeError') diff --git a/tests/basics/generator_pep479.py.exp b/tests/basics/generator_pep479.py.exp new file mode 100644 index 0000000000..c64fe49561 --- /dev/null +++ b/tests/basics/generator_pep479.py.exp @@ -0,0 +1,5 @@ +1 +RuntimeError +StopIteration +1 +RuntimeError diff --git a/tests/basics/generator_return.py b/tests/basics/generator_return.py index 5814ce8379..2b3464a02a 100644 --- a/tests/basics/generator_return.py +++ b/tests/basics/generator_return.py @@ -8,3 +8,9 @@ try: print(next(g)) except StopIteration as e: print(type(e), e.args) + +# trying next again should raise StopIteration with no arguments +try: + print(next(g)) +except StopIteration as e: + print(type(e), e.args) diff --git a/tests/basics/generator_throw.py b/tests/basics/generator_throw.py new file mode 100644 index 0000000000..1a390f399d --- /dev/null +++ b/tests/basics/generator_throw.py @@ -0,0 +1,43 @@ +# case where generator doesn't intercept the thrown/injected exception +def gen(): + yield 123 + yield 456 + +g = gen() +print(next(g)) +try: + g.throw(KeyError) +except KeyError: + print('got KeyError from downstream!') + +# case where a thrown exception is caught and stops the generator +def gen(): + try: + yield 1 + yield 2 + except: + pass +g = gen() +print(next(g)) +try: + g.throw(ValueError) +except StopIteration: + print('got StopIteration') + +# generator ignores a thrown GeneratorExit (this is allowed) +def gen(): + try: + yield 123 + except GeneratorExit: + print('GeneratorExit') + yield 456 + +# thrown a class +g = gen() +print(next(g)) +print(g.throw(GeneratorExit)) + +# thrown an instance +g = gen() +print(next(g)) +print(g.throw(GeneratorExit())) diff --git a/tests/basics/getattr.py b/tests/basics/getattr.py index a021e38fb0..2257da3bf9 100644 --- a/tests/basics/getattr.py +++ b/tests/basics/getattr.py @@ -9,3 +9,20 @@ class A: a = A({'a':1, 'b':2}) print(a.a, a.b) + +# test that any exception raised in __getattr__ propagates out +class A: + def __getattr__(self, attr): + if attr == "value": + raise ValueError(123) + else: + raise AttributeError(456) +a = A() +try: + a.value +except ValueError as er: + print(er) +try: + a.attr +except AttributeError as er: + print(er) diff --git a/tests/io/buffered_writer.py b/tests/basics/io_buffered_writer.py similarity index 100% rename from tests/io/buffered_writer.py rename to tests/basics/io_buffered_writer.py diff --git a/tests/io/buffered_writer.py.exp b/tests/basics/io_buffered_writer.py.exp similarity index 100% rename from tests/io/buffered_writer.py.exp rename to tests/basics/io_buffered_writer.py.exp diff --git a/tests/io/bytesio_cow.py b/tests/basics/io_bytesio_cow.py similarity index 100% rename from tests/io/bytesio_cow.py rename to tests/basics/io_bytesio_cow.py diff --git a/tests/io/bytesio_ext.py b/tests/basics/io_bytesio_ext.py similarity index 100% rename from tests/io/bytesio_ext.py rename to tests/basics/io_bytesio_ext.py diff --git a/tests/io/bytesio_ext2.py b/tests/basics/io_bytesio_ext2.py similarity index 100% rename from tests/io/bytesio_ext2.py rename to tests/basics/io_bytesio_ext2.py diff --git a/tests/io/bytesio_ext2.py.exp b/tests/basics/io_bytesio_ext2.py.exp similarity index 100% rename from tests/io/bytesio_ext2.py.exp rename to tests/basics/io_bytesio_ext2.py.exp diff --git a/tests/io/iobase.py b/tests/basics/io_iobase.py similarity index 100% rename from tests/io/iobase.py rename to tests/basics/io_iobase.py diff --git a/tests/io/stringio1.py b/tests/basics/io_stringio1.py similarity index 100% rename from tests/io/stringio1.py rename to tests/basics/io_stringio1.py diff --git a/tests/io/stringio_with.py b/tests/basics/io_stringio_with.py similarity index 100% rename from tests/io/stringio_with.py rename to tests/basics/io_stringio_with.py diff --git a/tests/io/write_ext.py b/tests/basics/io_write_ext.py similarity index 100% rename from tests/io/write_ext.py rename to tests/basics/io_write_ext.py diff --git a/tests/io/write_ext.py.exp b/tests/basics/io_write_ext.py.exp similarity index 100% rename from tests/io/write_ext.py.exp rename to tests/basics/io_write_ext.py.exp diff --git a/tests/basics/namedtuple_asdict.py b/tests/basics/namedtuple_asdict.py index c5681376fd..34c4e6f713 100644 --- a/tests/basics/namedtuple_asdict.py +++ b/tests/basics/namedtuple_asdict.py @@ -1,8 +1,8 @@ try: try: - from collections import namedtuple - except ImportError: from ucollections import namedtuple + except ImportError: + from collections import namedtuple except ImportError: print("SKIP") raise SystemExit diff --git a/tests/basics/op_precedence.py b/tests/basics/op_precedence.py index 519a2a1137..7d8302ba4d 100644 --- a/tests/basics/op_precedence.py +++ b/tests/basics/op_precedence.py @@ -37,7 +37,7 @@ print(2 + 2 * 2) # BAD: (-2)**2 = 4 print(-2**2) # OK: 2**(-1) = 0.5 -print(2**-1) +print(2**-0) # (expr...) print((2 + 2) * 2) diff --git a/tests/basics/scope_implicit.py b/tests/basics/scope_implicit.py new file mode 100644 index 0000000000..aecda77156 --- /dev/null +++ b/tests/basics/scope_implicit.py @@ -0,0 +1,31 @@ +# test implicit scoping rules + +# implicit nonlocal, with variable defined after closure +def f(): + def g(): + return x # implicit nonlocal + x = 3 # variable defined after function that closes over it + return g +print(f()()) + +# implicit nonlocal at inner level, with variable defined after closure +def f(): + def g(): + def h(): + return x # implicit nonlocal + return h + x = 4 # variable defined after function that closes over it + return g +print(f()()()) + +# local variable which should not be implicitly made nonlocal +def f(): + x = 0 + def g(): + x # local because next statement assigns to it + x = 1 + g() +try: + f() +except NameError: + print('NameError') diff --git a/tests/basics/special_methods.py b/tests/basics/special_methods.py index 9f57247c12..b56bc1c9c4 100644 --- a/tests/basics/special_methods.py +++ b/tests/basics/special_methods.py @@ -93,6 +93,9 @@ class Cud(): print("__isub__ called") return self + def __int__(self): + return 42 + cud1 = Cud() cud2 = Cud() @@ -104,5 +107,16 @@ cud1 >= cud2 cud1 > cud2 cud1 + cud2 cud1 - cud2 +print(int(cud1)) + +class BadInt: + def __int__(self): + print("__int__ called") + return None + +try: + int(BadInt()) +except TypeError: + print("TypeError") # more in special_methods2.py diff --git a/tests/basics/special_methods2.py b/tests/basics/special_methods2.py index c21618e93d..c72c8cf00f 100644 --- a/tests/basics/special_methods2.py +++ b/tests/basics/special_methods2.py @@ -134,6 +134,6 @@ print('a' in dir(Cud)) # ne is not supported, !(eq) is called instead #cud1 != cud2 # -# in the followin test, cpython still calls __eq__ +# in the following test, cpython still calls __eq__ # cud3=cud1 # cud3==cud1 diff --git a/tests/basics/string_count.py b/tests/basics/string_count.py index 462ccb8299..8fb5c98f82 100644 --- a/tests/basics/string_count.py +++ b/tests/basics/string_count.py @@ -1,3 +1,9 @@ +try: + str.count +except AttributeError: + print("SKIP") + raise SystemExit + print("".count("")) print("".count("a")) print("a".count("")) diff --git a/tests/basics/struct1.py b/tests/basics/struct1.py index 107006cc3f..ec29ea9080 100644 --- a/tests/basics/struct1.py +++ b/tests/basics/struct1.py @@ -121,3 +121,5 @@ except: # check padding bytes print(struct.pack("xb", 3)) +# Make sure pack doesn't reuse a larger value and error +print(struct.pack("xH", 0x100)) diff --git a/tests/basics/subclass_native_call.py b/tests/basics/subclass_native_call.py deleted file mode 100644 index c645575225..0000000000 --- a/tests/basics/subclass_native_call.py +++ /dev/null @@ -1,30 +0,0 @@ -# test calling a subclass of a native class that supports calling - -# For this test we need a native class that can be subclassed (has make_new) -# and is callable (has call). The only one available is machine.Signal, which -# in turns needs PinBase. -try: - import umachine as machine -except ImportError: - import machine -try: - machine.PinBase - machine.Signal -except AttributeError: - print("SKIP") - raise SystemExit - -class Pin(machine.PinBase): - #def __init__(self): - # self.v = 0 - - def value(self, v=None): - return 42 - -class MySignal(machine.Signal): - pass - -s = MySignal(Pin()) - -# apply call to the subclass, which should call the native base -print(s()) diff --git a/tests/basics/subclass_native_call.py.exp b/tests/basics/subclass_native_call.py.exp deleted file mode 100644 index d81cc0710e..0000000000 --- a/tests/basics/subclass_native_call.py.exp +++ /dev/null @@ -1 +0,0 @@ -42 diff --git a/tests/basics/try_finally1.py b/tests/basics/try_finally1.py index 2416f6d188..67ebe0b590 100644 --- a/tests/basics/try_finally1.py +++ b/tests/basics/try_finally1.py @@ -69,3 +69,28 @@ try: # top-level catch-all except to not fail script except: print("catch-all except") print() + +# case where a try-except within a finally cancels the exception +print("exc-finally-subexcept") +try: + print("try1") +finally: + try: + print("try2") + foo + except: + print("except2") + print("finally1") +print() + +# case where exception is raised after a finally has finished (tests that the finally doesn't run again) +def func(): + try: + print("try") + finally: + print("finally") + foo +try: + func() +except: + print("except") diff --git a/tests/basics/try_finally_return3.py b/tests/basics/try_finally_return3.py new file mode 100644 index 0000000000..a2a06ee975 --- /dev/null +++ b/tests/basics/try_finally_return3.py @@ -0,0 +1,103 @@ +# test 'return' within the finally block, with nested finally's +# only inactive finally's should be executed, and only once + +# basic nested finally's, the print should only be executed once +def f(): + try: + raise TypeError + finally: + print(1) + try: + raise ValueError + finally: + return 42 +print(f()) + +# similar to above but more nesting +def f(): + try: + raise ValueError + finally: + print(1) + try: + raise TypeError + finally: + print(2) + try: + pass + finally: + return 42 +print(f()) + +# similar to above but even more nesting +def f(): + try: + raise ValueError + finally: + print(1) + try: + raise TypeError + finally: + print(2) + try: + raise Exception + finally: + print(3) + return 42 +print(f()) + +# upon return some try's are active, some finally's are active, some inactive +def f(): + try: + try: + pass + finally: + print(2) + return 42 + finally: + print(1) +print(f()) + +# same as above but raise instead of pass +def f(): + try: + try: + raise ValueError + finally: + print(2) + return 42 + finally: + print(1) +print(f()) + +# upon return exception stack holds: active finally, inactive finally, active finally +def f(): + try: + raise Exception + finally: + print(1) + try: + try: + pass + finally: + print(3) + return 42 + finally: + print(2) +print(f()) + +# same as above but raise instead of pass in innermost try block +def f(): + try: + raise Exception + finally: + print(1) + try: + try: + raise Exception + finally: + print(3) + return 42 + finally: + print(2) +print(f()) diff --git a/tests/basics/try_finally_return4.py b/tests/basics/try_finally_return4.py new file mode 100644 index 0000000000..8b54fe92ce --- /dev/null +++ b/tests/basics/try_finally_return4.py @@ -0,0 +1,83 @@ +# test try-finally with return, where unwinding return has to go through +# another try-finally which may affect the behaviour of the return + +# case where a simple try-finally executes during an unwinding return +def f(x): + try: + try: + if x: + return 42 + finally: + try: + print(1) + finally: + print(2) + print(3) + print(4) + finally: + print(5) +print(f(0)) +print(f(1)) + +# case where an unwinding return is replaced by another one +def f(x): + try: + try: + if x: + return 42 + finally: + try: + print(1) + return 43 + finally: + print(2) + print(3) + print(4) + finally: + print(5) +print(f(0)) +print(f(1)) + +# case where an unwinding return is cancelled by an exception +def f(x): + try: + try: + if x: + return 42 + finally: + try: + print(1) + raise ValueError # cancels any active return + finally: + print(2) + print(3) + print(4) + finally: + print(5) +try: + print(f(0)) +except: + print('caught') +try: + print(f(1)) +except: + print('caught') + +# case where an unwinding return is cancelled then resumed +def f(x): + try: + try: + if x: + return 42 + finally: + try: + print(1) + raise Exception # cancels any active return + except: # cancels the exception and resumes any active return + print(2) + print(3) + print(4) + finally: + print(5) +print(f(0)) +print(f(1)) diff --git a/tests/basics/with_raise.py b/tests/basics/with_raise.py new file mode 100644 index 0000000000..67eab09b41 --- /dev/null +++ b/tests/basics/with_raise.py @@ -0,0 +1,44 @@ +# test with when context manager raises in __enter__/__exit__ + +class CtxMgr: + def __init__(self, id): + self.id = id + + def __enter__(self): + print("__enter__", self.id) + if 10 <= self.id < 20: + raise Exception('enter', self.id) + return self + + def __exit__(self, a, b, c): + print("__exit__", self.id, repr(a), repr(b)) + if 15 <= self.id < 25: + raise Exception('exit', self.id) + +# no raising +try: + with CtxMgr(1): + pass +except Exception as e: + print(e) + +# raise in enter +try: + with CtxMgr(10): + pass +except Exception as e: + print(e) + +# raise in enter and exit +try: + with CtxMgr(15): + pass +except Exception as e: + print(e) + +# raise in exit +try: + with CtxMgr(20): + pass +except Exception as e: + print(e) diff --git a/tests/circuitpython-manual/audiocore/single-track.midi b/tests/circuitpython-manual/audiocore/single-track.midi new file mode 100755 index 0000000000..3b3dcea822 Binary files /dev/null and b/tests/circuitpython-manual/audiocore/single-track.midi differ diff --git a/tests/cmdline/cmd_showbc.py b/tests/cmdline/cmd_showbc.py index 58f8a7f70d..326f2373f6 100644 --- a/tests/cmdline/cmd_showbc.py +++ b/tests/cmdline/cmd_showbc.py @@ -2,6 +2,7 @@ # test printing of all bytecodes # fmt: off + def f(): # constants a = None + False + True @@ -15,9 +16,9 @@ def f(): c = [1, 2] d = {1, 2} e = {} - f = {1:2} - g = 'a' - h = b'a' + f = {1: 2} + g = "a" + h = b"a" # unary/binary ops i = 1 @@ -59,7 +60,7 @@ def f(): # comprehensions a = (b for c in d if e) a = [b for c in d if e] - a = {b:b for c in d if e} + a = {b: b for c in d if e} # function calls a() @@ -108,7 +109,9 @@ def f(): # closed over variables x = 1 + def closure(): + nonlocal x a = x + 1 x = 1 del x @@ -126,12 +129,14 @@ def f(): return return 1 + # function with lots of locals def f(): l1 = l2 = l3 = l4 = l5 = l6 = l7 = l8 = l9 = l10 = 1 m1 = m2 = m3 = m4 = m5 = m6 = m7 = m8 = m9 = m10 = 2 l10 + m10 + # functions with default args def f(a=1): pass @@ -139,16 +144,19 @@ def f(a=1): def f(b=2): return b + a + # function which yields def f(): yield yield 1 yield from 1 + # class class Class: pass + # delete name del Class diff --git a/tests/cmdline/cmd_showbc.py.exp b/tests/cmdline/cmd_showbc.py.exp index 6ae5fa20ec..ac4cedd340 100644 --- a/tests/cmdline/cmd_showbc.py.exp +++ b/tests/cmdline/cmd_showbc.py.exp @@ -7,7 +7,7 @@ arg names: (N_EXC_STACK 0) bc=-1 line=1 ######## - bc=\\d\+ line=156 + bc=\\d\+ line=164 00 MAKE_FUNCTION \.\+ \\d\+ STORE_NAME f \\d\+ MAKE_FUNCTION \.\+ @@ -40,7 +40,7 @@ Raw bytecode (code_info_size=\\d\+, bytecode_size=\\d\+): (INIT_CELL 16) bc=-4 line=1 ######## - bc=\\d\+ line=127 + bc=\\d\+ line=130 00 LOAD_CONST_NONE 01 LOAD_CONST_FALSE 02 BINARY_OP 26 __add__ @@ -326,7 +326,7 @@ Raw bytecode (code_info_size=\\d\+, bytecode_size=\\d\+): (N_EXC_STACK 0) bc=-1 line=1 ######## - bc=\\d\+ line=133 + bc=\\d\+ line=137 00 LOAD_CONST_SMALL_INT 1 01 DUP_TOP 02 STORE_FAST 0 @@ -382,7 +382,7 @@ arg names: a (N_EXC_STACK 0) (INIT_CELL 0) ######## - bc=\\d\+ line=139 + bc=\\d\+ line=144 00 LOAD_CONST_SMALL_INT 2 01 BUILD_TUPLE 1 03 LOAD_NULL @@ -399,9 +399,9 @@ arg names: (N_STATE 2) (N_EXC_STACK 0) bc=-1 line=1 - bc=0 line=144 - bc=3 line=145 - bc=6 line=146 + bc=0 line=150 + bc=3 line=151 + bc=6 line=152 00 LOAD_CONST_NONE 01 YIELD_VALUE 02 POP_TOP @@ -423,7 +423,7 @@ arg names: (N_STATE 1) (N_EXC_STACK 0) bc=-1 line=1 - bc=13 line=150 + bc=13 line=157 00 LOAD_NAME __name__ (cache=0) 04 STORE_NAME __module__ 07 LOAD_CONST_STRING 'Class' @@ -438,7 +438,7 @@ arg names: self (N_STATE 4) (N_EXC_STACK 0) bc=-1 line=1 - bc=0 line=157 + bc=0 line=165 00 LOAD_GLOBAL super (cache=0) \\d\+ LOAD_GLOBAL __class__ (cache=0) \\d\+ LOAD_FAST 0 @@ -518,7 +518,7 @@ arg names: * (N_EXC_STACK 0) bc=-\\d\+ line=1 ######## - bc=\\d\+ line=114 + bc=\\d\+ line=117 00 LOAD_DEREF 0 02 LOAD_CONST_SMALL_INT 1 03 BINARY_OP 26 __add__ @@ -537,7 +537,7 @@ arg names: * b (N_EXC_STACK 0) bc=-\\d\+ line=1 ######## - bc=\\d\+ line=140 + bc=\\d\+ line=145 00 LOAD_FAST 1 01 LOAD_DEREF 0 03 BINARY_OP 26 __add__ diff --git a/tests/cpydiff/types_bytes_format.py b/tests/cpydiff/types_bytes_format.py new file mode 100644 index 0000000000..ad04987711 --- /dev/null +++ b/tests/cpydiff/types_bytes_format.py @@ -0,0 +1,7 @@ +""" +categories: Types,bytes +description: bytes objects support .format() method +cause: MicroPython strives to be a more regular implementation, so if both `str` and `bytes` support ``__mod__()`` (the % operator), it makes sense to support ``format()`` for both too. Support for ``__mod__`` can also be compiled out, which leaves only ``format()`` for bytes formatting. +workaround: If you are interested in CPython compatibility, don't use ``.format()`` on bytes objects. +""" +print(b"{}".format(1)) diff --git a/tests/extmod/machine1.py b/tests/extmod/machine1.py deleted file mode 100644 index 6ff38cc051..0000000000 --- a/tests/extmod/machine1.py +++ /dev/null @@ -1,28 +0,0 @@ -# test machine module - -try: - try: - import umachine as machine - except ImportError: - import machine - machine.mem8 -except: - print("SKIP") - raise SystemExit - -print(machine.mem8) - -try: - machine.mem16[1] -except ValueError: - print("ValueError") - -try: - machine.mem16[1] = 1 -except ValueError: - print("ValueError") - -try: - del machine.mem8[0] -except TypeError: - print("TypeError") diff --git a/tests/extmod/machine1.py.exp b/tests/extmod/machine1.py.exp deleted file mode 100644 index bb421ea5cf..0000000000 --- a/tests/extmod/machine1.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -<8-bit memory> -ValueError -ValueError -TypeError diff --git a/tests/extmod/machine_pinbase.py b/tests/extmod/machine_pinbase.py deleted file mode 100644 index f6b27d1d1d..0000000000 --- a/tests/extmod/machine_pinbase.py +++ /dev/null @@ -1,30 +0,0 @@ -try: - import umachine as machine -except ImportError: - import machine -try: - machine.PinBase -except AttributeError: - print("SKIP") - raise SystemExit - - -class MyPin(machine.PinBase): - def __init__(self): - print("__init__") - self.v = False - - def value(self, v=None): - print("value:", v) - if v is None: - self.v = not self.v - return int(self.v) - - -p = MyPin() - -print(p.value()) -print(p.value()) -print(p.value()) -p.value(1) -p.value(0) diff --git a/tests/extmod/machine_pinbase.py.exp b/tests/extmod/machine_pinbase.py.exp deleted file mode 100644 index b31cd98308..0000000000 --- a/tests/extmod/machine_pinbase.py.exp +++ /dev/null @@ -1,9 +0,0 @@ -__init__ -value: None -1 -value: None -0 -value: None -1 -value: 1 -value: 0 diff --git a/tests/extmod/machine_pulse.py b/tests/extmod/machine_pulse.py deleted file mode 100644 index 7a8fe14d06..0000000000 --- a/tests/extmod/machine_pulse.py +++ /dev/null @@ -1,44 +0,0 @@ -try: - import umachine as machine -except ImportError: - import machine -try: - machine.PinBase - machine.time_pulse_us -except AttributeError: - print("SKIP") - raise SystemExit - - -class ConstPin(machine.PinBase): - def __init__(self, value): - self.v = value - - def value(self, v=None): - if v is None: - return self.v - else: - self.v = v - - -class TogglePin(machine.PinBase): - def __init__(self): - self.v = 0 - - def value(self, v=None): - if v is None: - self.v = 1 - self.v - print("value:", self.v) - return self.v - - -p = TogglePin() - -t = machine.time_pulse_us(p, 1) -print(type(t)) -t = machine.time_pulse_us(p, 0) -print(type(t)) - -p = ConstPin(0) -print(machine.time_pulse_us(p, 1, 10)) -print(machine.time_pulse_us(p, 0, 10)) diff --git a/tests/extmod/machine_pulse.py.exp b/tests/extmod/machine_pulse.py.exp deleted file mode 100644 index 20d4c10431..0000000000 --- a/tests/extmod/machine_pulse.py.exp +++ /dev/null @@ -1,9 +0,0 @@ -value: 1 -value: 0 - -value: 1 -value: 0 -value: 1 - --2 --1 diff --git a/tests/extmod/machine_signal.py b/tests/extmod/machine_signal.py deleted file mode 100644 index c453098402..0000000000 --- a/tests/extmod/machine_signal.py +++ /dev/null @@ -1,40 +0,0 @@ -# test machine.Signal class - -try: - import umachine as machine -except ImportError: - import machine -try: - machine.PinBase - machine.Signal -except AttributeError: - print("SKIP") - raise SystemExit - - -class Pin(machine.PinBase): - def __init__(self): - self.v = 0 - - def value(self, v=None): - if v is None: - return self.v - else: - self.v = int(v) - - -# test non-inverted -p = Pin() -s = machine.Signal(p) -s.value(0) -print(p.value(), s.value()) -s.value(1) -print(p.value(), s.value()) - -# test inverted, and using on/off methods -p = Pin() -s = machine.Signal(p, invert=True) -s.off() -print(p.value(), s.value()) -s.on() -print(p.value(), s.value()) diff --git a/tests/extmod/machine_signal.py.exp b/tests/extmod/machine_signal.py.exp deleted file mode 100644 index 7e9dd67966..0000000000 --- a/tests/extmod/machine_signal.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -0 0 -1 1 -1 0 -0 1 diff --git a/tests/extmod/ubinascii_a2b_base64.py b/tests/extmod/ubinascii_a2b_base64.py index 39b85274b6..c65d69ddbe 100644 --- a/tests/extmod/ubinascii_a2b_base64.py +++ b/tests/extmod/ubinascii_a2b_base64.py @@ -29,7 +29,7 @@ print(binascii.a2b_base64(b"Zm9v===")) print(binascii.a2b_base64(b"Zm9v===YmFy")) # Unicode strings can be decoded -print(binascii.a2b_base64(u"Zm9v===YmFy")) +print(binascii.a2b_base64("Zm9v===YmFy")) try: print(binascii.a2b_base64(b"abc")) diff --git a/tests/extmod/ucryptolib_aes128_cbc.py b/tests/extmod/ucryptolib_aes128_cbc.py new file mode 100644 index 0000000000..d861d2c6bf --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_cbc.py @@ -0,0 +1,16 @@ +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 2, b"5678" * 4) +enc = crypto.encrypt(bytes(range(32))) +print(enc) +crypto = aes(b"1234" * 4, 2, b"5678" * 4) +print(crypto.decrypt(enc)) diff --git a/tests/extmod/ucryptolib_aes128_cbc.py.exp b/tests/extmod/ucryptolib_aes128_cbc.py.exp new file mode 100644 index 0000000000..cc73553b2a --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_cbc.py.exp @@ -0,0 +1,2 @@ +b'\x1d\x84\xfa\xaa%\x0e9\x143\x8b6\xf8\xdf^yh\xd0\x94g\xf4\xcf\x1d\xa0I)\x8a\xa0\x00u0+C' +b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' diff --git a/tests/extmod/ucryptolib_aes128_ecb.py b/tests/extmod/ucryptolib_aes128_ecb.py new file mode 100644 index 0000000000..5c0e179986 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb.py @@ -0,0 +1,16 @@ +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 1) +enc = crypto.encrypt(bytes(range(32))) +print(enc) +crypto = aes(b"1234" * 4, 1) +print(crypto.decrypt(enc)) diff --git a/tests/extmod/ucryptolib_aes128_ecb.py.exp b/tests/extmod/ucryptolib_aes128_ecb.py.exp new file mode 100644 index 0000000000..b0fd15b447 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb.py.exp @@ -0,0 +1,2 @@ +b'Iz\xfe9\x17\xac\xa4X\x12\x04\x10\xf5K~#\xc7\xac;\xf9\xc6E\xa8\xca~\xf1\xee\xd3f%\xf1\x8d\xfe' +b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' diff --git a/tests/extmod/ucryptolib_aes128_ecb_enc.py b/tests/extmod/ucryptolib_aes128_ecb_enc.py new file mode 100644 index 0000000000..1d4484b0bc --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_enc.py @@ -0,0 +1,17 @@ +# This tests minimal configuration of ucrypto module, which is +# AES128 encryption (anything else, including AES128 decryption, +# is optional). +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 1) +enc = crypto.encrypt(bytes(range(32))) +print(enc) diff --git a/tests/extmod/ucryptolib_aes128_ecb_enc.py.exp b/tests/extmod/ucryptolib_aes128_ecb_enc.py.exp new file mode 100644 index 0000000000..9921d4b83a --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_enc.py.exp @@ -0,0 +1 @@ +b'Iz\xfe9\x17\xac\xa4X\x12\x04\x10\xf5K~#\xc7\xac;\xf9\xc6E\xa8\xca~\xf1\xee\xd3f%\xf1\x8d\xfe' diff --git a/tests/extmod/ucryptolib_aes128_ecb_inpl.py b/tests/extmod/ucryptolib_aes128_ecb_inpl.py new file mode 100644 index 0000000000..88ccb02daf --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_inpl.py @@ -0,0 +1,15 @@ +# Inplace operations (input and output buffer is the same) +try: + from ucryptolib import aes +except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 1) +buf = bytearray(bytes(range(32))) +crypto.encrypt(buf, buf) +print(buf) + +crypto = aes(b"1234" * 4, 1) +crypto.decrypt(buf, buf) +print(buf) diff --git a/tests/extmod/ucryptolib_aes128_ecb_inpl.py.exp b/tests/extmod/ucryptolib_aes128_ecb_inpl.py.exp new file mode 100644 index 0000000000..b7f7bf5409 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_inpl.py.exp @@ -0,0 +1,2 @@ +bytearray(b'Iz\xfe9\x17\xac\xa4X\x12\x04\x10\xf5K~#\xc7\xac;\xf9\xc6E\xa8\xca~\xf1\xee\xd3f%\xf1\x8d\xfe') +bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f') diff --git a/tests/extmod/ucryptolib_aes128_ecb_into.py b/tests/extmod/ucryptolib_aes128_ecb_into.py new file mode 100644 index 0000000000..ff832d7ef3 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_into.py @@ -0,0 +1,16 @@ +# Operations with pre-allocated output buffer +try: + from ucryptolib import aes +except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 1) +enc = bytearray(32) +crypto.encrypt(bytes(range(32)), enc) +print(enc) + +crypto = aes(b"1234" * 4, 1) +dec = bytearray(32) +crypto.decrypt(enc, dec) +print(dec) diff --git a/tests/extmod/ucryptolib_aes128_ecb_into.py.exp b/tests/extmod/ucryptolib_aes128_ecb_into.py.exp new file mode 100644 index 0000000000..b7f7bf5409 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_into.py.exp @@ -0,0 +1,2 @@ +bytearray(b'Iz\xfe9\x17\xac\xa4X\x12\x04\x10\xf5K~#\xc7\xac;\xf9\xc6E\xa8\xca~\xf1\xee\xd3f%\xf1\x8d\xfe') +bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f') diff --git a/tests/extmod/ucryptolib_aes256_cbc.py b/tests/extmod/ucryptolib_aes256_cbc.py new file mode 100644 index 0000000000..c01846f199 --- /dev/null +++ b/tests/extmod/ucryptolib_aes256_cbc.py @@ -0,0 +1,16 @@ +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 8, 2, b"5678" * 4) +enc = crypto.encrypt(bytes(range(32))) +print(enc) +crypto = aes(b"1234" * 8, 2, b"5678" * 4) +print(crypto.decrypt(enc)) diff --git a/tests/extmod/ucryptolib_aes256_cbc.py.exp b/tests/extmod/ucryptolib_aes256_cbc.py.exp new file mode 100644 index 0000000000..51262db9c6 --- /dev/null +++ b/tests/extmod/ucryptolib_aes256_cbc.py.exp @@ -0,0 +1,2 @@ +b'\xb4\x0b\xff\xdd\xfc\xb5\x03\x88[m\xc1\x01+:\x03M\x18\xb03\x0f\x971g\x10\xb1\x98>\x9b\x17\xb7-\xb2' +b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' diff --git a/tests/extmod/ucryptolib_aes256_ecb.py b/tests/extmod/ucryptolib_aes256_ecb.py new file mode 100644 index 0000000000..0760063c14 --- /dev/null +++ b/tests/extmod/ucryptolib_aes256_ecb.py @@ -0,0 +1,16 @@ +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 8, 1) +enc = crypto.encrypt(bytes(range(32))) +print(enc) +crypto = aes(b"1234" * 8, 1) +print(crypto.decrypt(enc)) diff --git a/tests/extmod/ucryptolib_aes256_ecb.py.exp b/tests/extmod/ucryptolib_aes256_ecb.py.exp new file mode 100644 index 0000000000..a00a4eb2f5 --- /dev/null +++ b/tests/extmod/ucryptolib_aes256_ecb.py.exp @@ -0,0 +1,2 @@ +b'\xe2\xe0\xdd\xef\xc3\xcd\x88/!>\xf6\xa2\xef/\xd15z+`\xb2\xb2\xd7}!:V>\xeb\x19\xbf|\xea' +b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' diff --git a/tests/extmod/uctypes_error.py b/tests/extmod/uctypes_error.py index fb876de6d9..d429562615 100644 --- a/tests/extmod/uctypes_error.py +++ b/tests/extmod/uctypes_error.py @@ -35,3 +35,9 @@ try: S.x = 1 except TypeError: print("TypeError") + +# unsupported unary op +try: + hash(S) +except TypeError: + print("TypeError") diff --git a/tests/extmod/uctypes_error.py.exp b/tests/extmod/uctypes_error.py.exp index 802c260d2b..f2e9c12f7f 100644 --- a/tests/extmod/uctypes_error.py.exp +++ b/tests/extmod/uctypes_error.py.exp @@ -2,3 +2,4 @@ TypeError TypeError TypeError TypeError +TypeError diff --git a/tests/extmod/uctypes_le.py b/tests/extmod/uctypes_le.py index f69da30b61..466191c27a 100644 --- a/tests/extmod/uctypes_le.py +++ b/tests/extmod/uctypes_le.py @@ -6,7 +6,13 @@ except ImportError: desc = { "s0": uctypes.UINT16 | 0, - "sub": (0, {"b0": uctypes.UINT8 | 0, "b1": uctypes.UINT8 | 1}), + "sub": ( + 0, + { + "b0": uctypes.UINT8 | 0, + "b1": uctypes.UINT8 | 1, + }, + ), "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "bitf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 8 << uctypes.BF_LEN, diff --git a/tests/extmod/uctypes_native_le.py b/tests/extmod/uctypes_native_le.py index 7958e5c22a..10477e6694 100644 --- a/tests/extmod/uctypes_native_le.py +++ b/tests/extmod/uctypes_native_le.py @@ -16,7 +16,13 @@ if sys.byteorder != "little": desc = { "s0": uctypes.UINT16 | 0, - "sub": (0, {"b0": uctypes.UINT8 | 0, "b1": uctypes.UINT8 | 1}), + "sub": ( + 0, + { + "b0": uctypes.UINT8 | 0, + "b1": uctypes.UINT8 | 1, + }, + ), "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "bitf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 8 << uctypes.BF_LEN, diff --git a/tests/extmod/uctypes_ptr_le.py b/tests/extmod/uctypes_ptr_le.py index a69467e62c..5d8094ee48 100644 --- a/tests/extmod/uctypes_ptr_le.py +++ b/tests/extmod/uctypes_ptr_le.py @@ -23,6 +23,9 @@ buf = addr.to_bytes(uctypes.sizeof(desc), "little") S = uctypes.struct(uctypes.addressof(buf), desc, uctypes.LITTLE_ENDIAN) +print(addr == int(S.ptr)) +print(addr == int(S.ptr2)) + print(S.ptr[0]) assert S.ptr[0] == ord("0") print(S.ptr[1]) diff --git a/tests/extmod/uctypes_ptr_le.py.exp b/tests/extmod/uctypes_ptr_le.py.exp index 30d159edd1..92f6caa069 100644 --- a/tests/extmod/uctypes_ptr_le.py.exp +++ b/tests/extmod/uctypes_ptr_le.py.exp @@ -1,3 +1,5 @@ +True +True 48 49 0x3130 diff --git a/tests/extmod/uctypes_sizeof_layout.py b/tests/extmod/uctypes_sizeof_layout.py new file mode 100644 index 0000000000..2108e81502 --- /dev/null +++ b/tests/extmod/uctypes_sizeof_layout.py @@ -0,0 +1,27 @@ +try: + import uctypes +except ImportError: + print("SKIP") + raise SystemExit + +desc = { + "f1": 0 | uctypes.UINT32, + "f2": 4 | uctypes.UINT8, +} + + +# uctypes.NATIVE is default +print(uctypes.sizeof(desc) == uctypes.sizeof(desc, uctypes.NATIVE)) + +# Here we assume that that we run on a platform with convential ABI +# (which rounds up structure size based on max alignment). For platforms +# where that doesn't hold, this tests should be just disabled in the runner. +print(uctypes.sizeof(desc, uctypes.NATIVE) > uctypes.sizeof(desc, uctypes.LITTLE_ENDIAN)) + +# When taking sizeof of instantiated structure, layout type param +# is prohibited (because structure already has its layout type). +s = uctypes.struct(0, desc, uctypes.LITTLE_ENDIAN) +try: + uctypes.sizeof(s, uctypes.LITTLE_ENDIAN) +except TypeError: + print("TypeError") diff --git a/tests/extmod/uctypes_sizeof_layout.py.exp b/tests/extmod/uctypes_sizeof_layout.py.exp new file mode 100644 index 0000000000..281f20856e --- /dev/null +++ b/tests/extmod/uctypes_sizeof_layout.py.exp @@ -0,0 +1,3 @@ +True +True +TypeError diff --git a/tests/extmod/uctypes_sizeof_native.py b/tests/extmod/uctypes_sizeof_native.py index 9aa5d84ec6..991cd25f52 100644 --- a/tests/extmod/uctypes_sizeof_native.py +++ b/tests/extmod/uctypes_sizeof_native.py @@ -10,10 +10,17 @@ assert uctypes.sizeof(S1) == 0 S2 = {"a": uctypes.UINT8 | 0} assert uctypes.sizeof(S2) == 1 -S3 = {"a": uctypes.UINT8 | 0, "b": uctypes.UINT8 | 1} +S3 = { + "a": uctypes.UINT8 | 0, + "b": uctypes.UINT8 | 1, +} assert uctypes.sizeof(S3) == 2 -S4 = {"a": uctypes.UINT8 | 0, "b": uctypes.UINT32 | 4, "c": uctypes.UINT8 | 8} +S4 = { + "a": uctypes.UINT8 | 0, + "b": uctypes.UINT32 | 4, + "c": uctypes.UINT8 | 8, +} assert uctypes.sizeof(S4) == 12 S5 = { @@ -21,7 +28,13 @@ S5 = { "b": uctypes.UINT32 | 4, "c": uctypes.UINT8 | 8, "d": uctypes.UINT32 | 0, - "sub": (4, {"b0": uctypes.UINT8 | 0, "b1": uctypes.UINT8 | 1}), + "sub": ( + 4, + { + "b0": uctypes.UINT8 | 0, + "b1": uctypes.UINT8 | 1, + }, + ), } assert uctypes.sizeof(S5) == 12 @@ -30,12 +43,18 @@ s5 = uctypes.struct(0, S5) assert uctypes.sizeof(s5) == 12 assert uctypes.sizeof(s5.sub) == 2 -S6 = {"ptr": (uctypes.PTR | 0, uctypes.UINT8)} +S6 = { + "ptr": (uctypes.PTR | 0, uctypes.UINT8), +} # As if there're no other arch bitnesses assert uctypes.sizeof(S6) in (4, 8) -S7 = {"arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 5)} +S7 = { + "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 5), +} assert uctypes.sizeof(S7) == 5 -S8 = {"arr": (uctypes.ARRAY | 0, 3, {"a": uctypes.UINT32 | 0, "b": uctypes.UINT8 | 4})} +S8 = { + "arr": (uctypes.ARRAY | 0, 3, {"a": uctypes.UINT32 | 0, "b": uctypes.UINT8 | 4}), +} assert uctypes.sizeof(S8) == 24 diff --git a/tests/extmod/uctypes_sizeof_od.py b/tests/extmod/uctypes_sizeof_od.py new file mode 100644 index 0000000000..2f070095b5 --- /dev/null +++ b/tests/extmod/uctypes_sizeof_od.py @@ -0,0 +1,53 @@ +try: + from ucollections import OrderedDict + import uctypes +except ImportError: + print("SKIP") + raise SystemExit + +desc = OrderedDict( + { + # arr is array at offset 0, of UINT8 elements, array size is 2 + "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), + # arr2 is array at offset 0, size 2, of structures defined recursively + "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), + "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), + "arr4": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0, "w": uctypes.UINT16 | 1}), + "sub": ( + 0, + { + "b1": uctypes.BFUINT8 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "b2": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + }, + ), + } +) + +data = bytearray(b"01234567") + +S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) + +print(uctypes.sizeof(S.arr)) +assert uctypes.sizeof(S.arr) == 2 + +print(uctypes.sizeof(S.arr2)) +assert uctypes.sizeof(S.arr2) == 2 + +print(uctypes.sizeof(S.arr3)) + +try: + print(uctypes.sizeof(S.arr3[0])) +except TypeError: + print("TypeError") + +print(uctypes.sizeof(S.arr4)) +assert uctypes.sizeof(S.arr4) == 6 + +print(uctypes.sizeof(S.sub)) +assert uctypes.sizeof(S.sub) == 1 + +# invalid descriptor +try: + print(uctypes.sizeof([])) +except TypeError: + print("TypeError") diff --git a/tests/extmod/uctypes_sizeof_od.py.exp b/tests/extmod/uctypes_sizeof_od.py.exp new file mode 100644 index 0000000000..b35b11aa0c --- /dev/null +++ b/tests/extmod/uctypes_sizeof_od.py.exp @@ -0,0 +1,7 @@ +2 +2 +4 +TypeError +6 +1 +TypeError diff --git a/tests/extmod/uhashlib_md5.py b/tests/extmod/uhashlib_md5.py new file mode 100644 index 0000000000..07d5f31692 --- /dev/null +++ b/tests/extmod/uhashlib_md5.py @@ -0,0 +1,21 @@ +try: + import uhashlib as hashlib +except ImportError: + try: + import hashlib + except ImportError: + # This is neither uPy, nor cPy, so must be uPy with + # uhashlib module disabled. + print("SKIP") + raise SystemExit + +try: + hashlib.md5 +except AttributeError: + # MD5 is only available on some ports + print("SKIP") + raise SystemExit + +md5 = hashlib.md5(b"hello") +md5.update(b"world") +print(md5.digest()) diff --git a/tests/extmod/ujson_dump_iobase.py b/tests/extmod/ujson_dump_iobase.py index c51994ef5d..7ecf23afb6 100644 --- a/tests/extmod/ujson_dump_iobase.py +++ b/tests/extmod/ujson_dump_iobase.py @@ -25,6 +25,7 @@ class S(io.IOBase): # uPy passes a bytearray, CPython passes a str buf = str(buf, "ascii") self.buf += buf + return len(buf) # dump to the user stream diff --git a/tests/extmod/urandom_extra.py b/tests/extmod/urandom_extra.py index 636a225394..78e17379dc 100644 --- a/tests/extmod/urandom_extra.py +++ b/tests/extmod/urandom_extra.py @@ -67,13 +67,3 @@ try: random.choice([]) except IndexError: print("IndexError") - -print("random") -for i in range(50): - assert 0 <= random.random() < 1 - -print("uniform") -for i in range(50): - assert 0 <= random.uniform(0, 4) <= 4 - assert 2 <= random.uniform(2, 6) <= 6 - assert -2 <= random.uniform(-2, 2) <= 2 diff --git a/tests/extmod/urandom_extra_float.py b/tests/extmod/urandom_extra_float.py new file mode 100644 index 0000000000..65918da136 --- /dev/null +++ b/tests/extmod/urandom_extra_float.py @@ -0,0 +1,24 @@ +try: + import urandom as random +except ImportError: + try: + import random + except ImportError: + print("SKIP") + raise SystemExit + +try: + random.randint +except AttributeError: + print("SKIP") + raise SystemExit + +print("random") +for i in range(50): + assert 0 <= random.random() < 1 + +print("uniform") +for i in range(50): + assert 0 <= random.uniform(0, 4) <= 4 + assert 2 <= random.uniform(2, 6) <= 6 + assert -2 <= random.uniform(-2, 2) <= 2 diff --git a/tests/extmod/ure_limit.py b/tests/extmod/ure_limit.py new file mode 100644 index 0000000000..99c6a818e8 --- /dev/null +++ b/tests/extmod/ure_limit.py @@ -0,0 +1,34 @@ +# Test overflow in ure.compile output code. + +try: + import ure as re +except ImportError: + print("SKIP") + raise SystemExit + + +def test_re(r): + try: + re.compile(r) + except: + print("Error") + + +# too many chars in [] +test_re("[" + "a" * 256 + "]") + +# too many groups +test_re("(a)" * 256) + +# jump too big for ? +test_re("(" + "a" * 62 + ")?") + +# jump too big for * +test_re("(" + "a" * 60 + ".)*") +test_re("(" + "a" * 60 + "..)*") + +# jump too big for + +test_re("(" + "a" * 62 + ")+") + +# jump too big for | +test_re("b" * 63 + "|a") diff --git a/tests/extmod/ure_limit.py.exp b/tests/extmod/ure_limit.py.exp new file mode 100644 index 0000000000..8353be536c --- /dev/null +++ b/tests/extmod/ure_limit.py.exp @@ -0,0 +1,7 @@ +Error +Error +Error +Error +Error +Error +Error diff --git a/tests/extmod/uselect_poll_basic.py b/tests/extmod/uselect_poll_basic.py new file mode 100644 index 0000000000..ab750078d3 --- /dev/null +++ b/tests/extmod/uselect_poll_basic.py @@ -0,0 +1,36 @@ +try: + import usocket as socket, uselect as select, uerrno as errno +except ImportError: + try: + import socket, select, errno + + select.poll # Raises AttributeError for CPython implementations without poll() + except (ImportError, AttributeError): + print("SKIP") + raise SystemExit + + +poller = select.poll() + +s = socket.socket() + +poller.register(s) +# https://docs.python.org/3/library/select.html#select.poll.register +# "Registering a file descriptor that’s already registered is not an error, +# and has the same effect as registering the descriptor exactly once." +poller.register(s) + +# 2 args are mandatory unlike register() +try: + poller.modify(s) +except TypeError: + print("modify:TypeError") + +poller.modify(s, select.POLLIN) + +poller.unregister(s) + +try: + poller.modify(s, select.POLLIN) +except OSError as e: + assert e.args[0] == errno.ENOENT diff --git a/tests/extmod/vfs_fat_more.py b/tests/extmod/vfs_fat_more.py index acae8c5844..d5ecd50467 100644 --- a/tests/extmod/vfs_fat_more.py +++ b/tests/extmod/vfs_fat_more.py @@ -1,5 +1,3 @@ -import uerrno - try: import uos except ImportError: diff --git a/tests/extmod/vfs_userfs.py b/tests/extmod/vfs_userfs.py index 60bf4d0997..06e546b081 100644 --- a/tests/extmod/vfs_userfs.py +++ b/tests/extmod/vfs_userfs.py @@ -1,9 +1,11 @@ # test VFS functionality with a user-defined filesystem # also tests parts of uio.IOBase implementation -import sys, uio +import sys try: + import uio + uio.IOBase import uos diff --git a/tests/float/builtin_float_abs.py b/tests/float/builtin_float_abs.py new file mode 100644 index 0000000000..f7ce9e156f --- /dev/null +++ b/tests/float/builtin_float_abs.py @@ -0,0 +1,13 @@ +# test builtin abs function with float args + +for val in ( + "1.0", + "-1.0", + "0.0", + "-0.0", + "nan", + "-nan", + "inf", + "-inf", +): + print(val, abs(float(val))) diff --git a/tests/float/builtin_float_hash.py b/tests/float/builtin_float_hash.py index f77b1a1834..1388bb0e83 100644 --- a/tests/float/builtin_float_hash.py +++ b/tests/float/builtin_float_hash.py @@ -1,9 +1,25 @@ # test builtin hash function with float args # these should hash to an integer with a specific value -for val in ("0.0", "-0.0", "1.0", "2.0", "-12.0", "12345.0"): +for val in ( + "0.0", + "-0.0", + "1.0", + "2.0", + "-12.0", + "12345.0", +): print(val, hash(float(val))) # just check that these values are hashable -for val in ("0.1", "-0.1", "10.3", "0.4e3", "1e16", "inf", "-inf", "nan"): +for val in ( + "0.1", + "-0.1", + "10.3", + "0.4e3", + "1e16", + "inf", + "-inf", + "nan", +): print(val, type(hash(float(val)))) diff --git a/tests/float/cmath_fun.py b/tests/float/cmath_fun.py index 26f6c227cf..5622918282 100644 --- a/tests/float/cmath_fun.py +++ b/tests/float/cmath_fun.py @@ -22,7 +22,9 @@ for r in base_values: test_values_non_zero.append(complex(r, -i)) if r != 0.0 and i != 0.0: test_values_non_zero.append(complex(-r, -i)) -test_values = [complex(0.0, 0.0)] + test_values_non_zero +test_values = [ + complex(0.0, 0.0), +] + test_values_non_zero print(test_values) functions = [ @@ -54,6 +56,6 @@ for f_name, f, test_vals in functions: else: # some test (eg cmath.sqrt(-0.5)) disagree with CPython with tiny real part real = ret.real - if abs(real) < 1e15: + if abs(real) < 1e-6: real = 0.0 print("complex(%.5g, %.5g)" % (real, ret.imag)) diff --git a/tests/float/cmath_fun_special.py b/tests/float/cmath_fun_special.py index 1d9abac6b4..33b94d04db 100644 --- a/tests/float/cmath_fun_special.py +++ b/tests/float/cmath_fun_special.py @@ -21,7 +21,9 @@ for r in base_values: if r != 0.0 and i != 0.0: test_values_non_zero.append(complex(-r, -i)) -functions = [("log10", log10, test_values_non_zero)] +functions = [ + ("log10", log10, test_values_non_zero), +] for f_name, f, test_vals in functions: print(f_name) diff --git a/tests/float/float_parse.py b/tests/float/float_parse.py index bef1122ac0..de27c33e7b 100644 --- a/tests/float/float_parse.py +++ b/tests/float/float_parse.py @@ -30,3 +30,7 @@ print(float("1e4294967301")) print(float("1e-4294967301")) print(float("1e18446744073709551621")) print(float("1e-18446744073709551621")) + +# check small decimals are as close to their true value as possible +for n in range(1, 10): + print(float("0.%u" % n) == n / 10) diff --git a/tests/float/math_domain_special.py b/tests/float/math_domain_special.py index e5bfa9f032..880594dce2 100644 --- a/tests/float/math_domain_special.py +++ b/tests/float/math_domain_special.py @@ -27,7 +27,7 @@ for name, f, args in ( ("gamma", math.gamma, (-2, -1, 0, 1)), ("lgamma", math.lgamma, (-2, -1, 0, 1)), ): - for x in args + (inf, nan): + for x in args + (inf, -inf, nan): try: ans = f(x) print("%.4f" % ans) diff --git a/tests/float/math_factorial_intbig.py b/tests/float/math_factorial_intbig.py new file mode 100644 index 0000000000..a4694b3d68 --- /dev/null +++ b/tests/float/math_factorial_intbig.py @@ -0,0 +1,15 @@ +try: + import math + + math.factorial +except (ImportError, AttributeError): + print("SKIP") + raise SystemExit + + +for fun in (math.factorial,): + for x in range(-1, 30): + try: + print("%d" % fun(x)) + except ValueError as e: + print("ValueError") diff --git a/tests/float/math_fun.py b/tests/float/math_fun.py index dac57d7822..f43216c6fb 100644 --- a/tests/float/math_fun.py +++ b/tests/float/math_fun.py @@ -45,7 +45,10 @@ for function_name, function, test_vals in functions: except ValueError as e: print(str(e)) -tuple_functions = [("frexp", frexp, test_values), ("modf", modf, test_values)] +tuple_functions = [ + ("frexp", frexp, test_values), + ("modf", modf, test_values), +] for function_name, function, test_vals in tuple_functions: print(function_name) @@ -59,10 +62,64 @@ binary_functions = [ copysign, [(23.0, 42.0), (-23.0, 42.0), (23.0, -42.0), (-23.0, -42.0), (1.0, 0.0), (1.0, -0.0)], ), - ("pow", pow, ((1.0, 0.0), (0.0, 1.0), (2.0, 0.5), (-3.0, 5.0), (-3.0, -4.0))), - ("atan2", atan2, ((1.0, 0.0), (0.0, 1.0), (2.0, 0.5), (-3.0, 5.0), (-3.0, -4.0))), - ("fmod", fmod, ((1.0, 1.0), (0.0, 1.0), (2.0, 0.5), (-3.0, 5.0), (-3.0, -4.0))), - ("ldexp", ldexp, ((1.0, 0), (0.0, 1), (2.0, 2), (3.0, -2), (-3.0, -4))), + ( + "pow", + pow, + ( + (1.0, 0.0), + (0.0, 1.0), + (2.0, 0.5), + (-3.0, 5.0), + (-3.0, -4.0), + ), + ), + ( + "atan2", + atan2, + ( + (1.0, 0.0), + (0.0, 1.0), + (2.0, 0.5), + (-3.0, 5.0), + (-3.0, -4.0), + ), + ), + ( + "fmod", + fmod, + ( + (1.0, 1.0), + (0.0, 1.0), + (2.0, 0.5), + (-3.0, 5.0), + (-3.0, -4.0), + ), + ), + ( + "ldexp", + ldexp, + ( + (1.0, 0), + (0.0, 1), + (2.0, 2), + (3.0, -2), + (-3.0, -4), + ), + ), + ( + "log", + log, + ( + (2.0, 2.0), + (3.0, 2.0), + (4.0, 5.0), + (0.0, 1.0), + (1.0, 0.0), + (-1.0, 1.0), + (1.0, -1.0), + (2.0, 1.0), + ), + ), ] for function_name, function, test_vals in binary_functions: diff --git a/tests/float/math_fun_special.py b/tests/float/math_fun_special.py index f4e53e8914..8f51b29acb 100644 --- a/tests/float/math_fun_special.py +++ b/tests/float/math_fun_special.py @@ -8,8 +8,24 @@ except (ImportError, NameError): print("SKIP") raise SystemExit -test_values = [-8.0, -2.5, -1, -0.5, 0.0, 0.5, 2.5, 8.0] -pos_test_values = [0.001, 0.1, 0.5, 1.0, 1.5, 10.0] +test_values = [ + -8.0, + -2.5, + -1, + -0.5, + 0.0, + 0.5, + 2.5, + 8.0, +] +pos_test_values = [ + 0.001, + 0.1, + 0.5, + 1.0, + 1.5, + 10.0, +] functions = [ ("expm1", expm1, test_values), @@ -17,14 +33,22 @@ functions = [ ("log10", log10, test_values), ("cosh", cosh, test_values), ("sinh", sinh, test_values), - ("tanh", tanh, test_values), + ("tanh", tanh, [-1e6, -100] + test_values + [100, 1e6]), ("acosh", acosh, [1.0, 5.0, 1.0]), ("asinh", asinh, test_values), ("atanh", atanh, [-0.99, -0.5, 0.0, 0.5, 0.99]), ("erf", erf, test_values), ("erfc", erfc, test_values), ("gamma", gamma, pos_test_values), - ("lgamma", lgamma, pos_test_values + [50.0, 100.0]), + ( + "lgamma", + lgamma, + pos_test_values + + [ + 50.0, + 100.0, + ], + ), ] for function_name, function, test_vals in functions: diff --git a/tests/import/import_long_dyn.py b/tests/import/import_long_dyn.py new file mode 100644 index 0000000000..709e019f31 --- /dev/null +++ b/tests/import/import_long_dyn.py @@ -0,0 +1 @@ +from import_long_dyn2 import * diff --git a/tests/import/import_long_dyn2.py b/tests/import/import_long_dyn2.py new file mode 100644 index 0000000000..c3cb1f2469 --- /dev/null +++ b/tests/import/import_long_dyn2.py @@ -0,0 +1 @@ +globals()["long_long_very_long_long_name"] = 1 diff --git a/tests/import/module_getattr.py b/tests/import/module_getattr.py new file mode 100644 index 0000000000..df7a621815 --- /dev/null +++ b/tests/import/module_getattr.py @@ -0,0 +1,24 @@ +# test __getattr__ on module + +# ensure that does_not_exist doesn't exist to start with +this = __import__(__name__) +try: + this.does_not_exist + assert False +except AttributeError: + pass + +# define __getattr__ +def __getattr__(attr): + if attr == "does_not_exist": + return False + raise AttributeError + + +# do feature test (will also test functionality if the feature exists) +if not hasattr(this, "does_not_exist"): + print("SKIP") + raise SystemExit + +# check that __getattr__ works as expected +print(this.does_not_exist) diff --git a/tests/pyb/switch.py.exp b/tests/import/module_getattr.py.exp similarity index 100% rename from tests/pyb/switch.py.exp rename to tests/import/module_getattr.py.exp diff --git a/tests/io/open_append.py b/tests/io/open_append.py index a696823bc5..49cdd094b3 100644 --- a/tests/io/open_append.py +++ b/tests/io/open_append.py @@ -3,13 +3,13 @@ try: except ImportError: import os -if not hasattr(os, "unlink"): +if not hasattr(os, "remove"): print("SKIP") raise SystemExit # cleanup in case testfile exists try: - os.unlink("testfile") + os.remove("testfile") except OSError: pass @@ -32,6 +32,6 @@ f.close() # cleanup try: - os.unlink("testfile") + os.remove("testfile") except OSError: pass diff --git a/tests/io/open_plus.py b/tests/io/open_plus.py index bba96fa2f9..3cb2330eed 100644 --- a/tests/io/open_plus.py +++ b/tests/io/open_plus.py @@ -3,13 +3,13 @@ try: except ImportError: import os -if not hasattr(os, "unlink"): +if not hasattr(os, "remove"): print("SKIP") raise SystemExit # cleanup in case testfile exists try: - os.unlink("testfile") + os.remove("testfile") except OSError: pass @@ -42,6 +42,6 @@ f.close() # cleanup try: - os.unlink("testfile") + os.remove("testfile") except OSError: pass diff --git a/tests/micropython/heapalloc_bytesio.py b/tests/micropython/heapalloc_bytesio.py deleted file mode 100644 index 4aae2abf06..0000000000 --- a/tests/micropython/heapalloc_bytesio.py +++ /dev/null @@ -1,18 +0,0 @@ -try: - import uio -except ImportError: - print("SKIP") - raise SystemExit - -import micropython - -data = b"1234" * 16 -buf = uio.BytesIO(64) - -micropython.heap_lock() - -buf.write(data) - -micropython.heap_unlock() - -print(buf.getvalue()) diff --git a/tests/micropython/heapalloc_bytesio.py.exp b/tests/micropython/heapalloc_bytesio.py.exp deleted file mode 100644 index 675761c2bb..0000000000 --- a/tests/micropython/heapalloc_bytesio.py.exp +++ /dev/null @@ -1 +0,0 @@ -b'1234123412341234123412341234123412341234123412341234123412341234' diff --git a/tests/micropython/native_const.py b/tests/micropython/native_const.py new file mode 100644 index 0000000000..b48499550e --- /dev/null +++ b/tests/micropython/native_const.py @@ -0,0 +1,21 @@ +# test loading constants in native functions + + +@micropython.native +def f(): + return b"bytes" + + +print(f()) + + +@micropython.native +def f(): + @micropython.native + def g(): + return 123 + + return g + + +print(f()()) diff --git a/tests/micropython/native_const.py.exp b/tests/micropython/native_const.py.exp new file mode 100644 index 0000000000..9002a0c2e5 --- /dev/null +++ b/tests/micropython/native_const.py.exp @@ -0,0 +1,2 @@ +b'bytes' +123 diff --git a/tests/micropython/native_try.py b/tests/micropython/native_try.py new file mode 100644 index 0000000000..492b59085c --- /dev/null +++ b/tests/micropython/native_try.py @@ -0,0 +1,45 @@ +# test native try handling + +# basic try-finally +@micropython.native +def f(): + try: + fail + finally: + print("finally") + + +try: + f() +except NameError: + print("NameError") + +# nested try-except with try-finally +@micropython.native +def f(): + try: + try: + fail + finally: + print("finally") + except NameError: + print("NameError") + + +f() + +# check that locals written to in try blocks keep their values +@micropython.native +def f(): + a = 100 + try: + print(a) + a = 200 + fail + except NameError: + print(a) + a = 300 + print(a) + + +f() diff --git a/tests/micropython/native_try.py.exp b/tests/micropython/native_try.py.exp new file mode 100644 index 0000000000..96596ce5f5 --- /dev/null +++ b/tests/micropython/native_try.py.exp @@ -0,0 +1,7 @@ +finally +NameError +finally +NameError +100 +200 +300 diff --git a/tests/micropython/native_try_deep.py b/tests/micropython/native_try_deep.py new file mode 100644 index 0000000000..3d31248df0 --- /dev/null +++ b/tests/micropython/native_try_deep.py @@ -0,0 +1,36 @@ +# test native try handling + +# deeply nested try (9 deep) +@micropython.native +def f(): + try: + try: + try: + try: + try: + try: + try: + try: + try: + raise ValueError + finally: + print(8) + finally: + print(7) + finally: + print(6) + finally: + print(5) + finally: + print(4) + finally: + print(3) + finally: + print(2) + finally: + print(1) + except ValueError: + print("ValueError") + + +f() diff --git a/tests/micropython/native_try_deep.py.exp b/tests/micropython/native_try_deep.py.exp new file mode 100644 index 0000000000..84c6beae31 --- /dev/null +++ b/tests/micropython/native_try_deep.py.exp @@ -0,0 +1,9 @@ +8 +7 +6 +5 +4 +3 +2 +1 +ValueError diff --git a/tests/micropython/native_with.py b/tests/micropython/native_with.py new file mode 100644 index 0000000000..4e20b23856 --- /dev/null +++ b/tests/micropython/native_with.py @@ -0,0 +1,36 @@ +# test with handling within a native function + + +class C: + def __init__(self): + print("__init__") + + def __enter__(self): + print("__enter__") + + def __exit__(self, a, b, c): + print("__exit__", a, b, c) + + +# basic with +@micropython.native +def f(): + with C(): + print(1) + + +f() + +# nested with and try-except +@micropython.native +def f(): + try: + with C(): + print(1) + fail + print(2) + except NameError: + print("NameError") + + +f() diff --git a/tests/micropython/native_with.py.exp b/tests/micropython/native_with.py.exp new file mode 100644 index 0000000000..6eef7822fb --- /dev/null +++ b/tests/micropython/native_with.py.exp @@ -0,0 +1,9 @@ +__init__ +__enter__ +1 +__exit__ None None None +__init__ +__enter__ +1 +__exit__ name 'fail' is not defined None +NameError diff --git a/tests/micropython/viper_args.py b/tests/micropython/viper_args.py index 223026b963..8e3225331a 100644 --- a/tests/micropython/viper_args.py +++ b/tests/micropython/viper_args.py @@ -40,7 +40,21 @@ def f4(x1: int, x2: int, x3: int, x4: int): f4(1, 2, 3, 4) -# only up to 4 arguments currently supported + +@micropython.viper +def f5(x1: int, x2: int, x3: int, x4: int, x5: int): + print(x1, x2, x3, x4, x5) + + +f5(1, 2, 3, 4, 5) + + +@micropython.viper +def f6(x1: int, x2: int, x3: int, x4: int, x5: int, x6: int): + print(x1, x2, x3, x4, x5, x6) + + +f6(1, 2, 3, 4, 5, 6) # test compiling *x, **x, * args (currently unsupported at runtime) @micropython.viper diff --git a/tests/micropython/viper_args.py.exp b/tests/micropython/viper_args.py.exp index 0ca0f4e906..6d64c584a5 100644 --- a/tests/micropython/viper_args.py.exp +++ b/tests/micropython/viper_args.py.exp @@ -3,3 +3,5 @@ 1 2 1 2 3 1 2 3 4 +1 2 3 4 5 +1 2 3 4 5 6 diff --git a/tests/micropython/viper_cond.py b/tests/micropython/viper_cond.py index d31a5f3cf8..d5ebf837bd 100644 --- a/tests/micropython/viper_cond.py +++ b/tests/micropython/viper_cond.py @@ -29,3 +29,13 @@ def g(): g() + +# using an int as a conditional that has the lower 16-bits clear +@micropython.viper +def h(): + z = 0x10000 + if z: + print("z", z) + + +h() diff --git a/tests/micropython/viper_cond.py.exp b/tests/micropython/viper_cond.py.exp index dff7103934..beacd48fe6 100644 --- a/tests/micropython/viper_cond.py.exp +++ b/tests/micropython/viper_cond.py.exp @@ -1,3 +1,4 @@ not x False x True y 1 +z 65536 diff --git a/tests/micropython/viper_const.py b/tests/micropython/viper_const.py new file mode 100644 index 0000000000..230b282f23 --- /dev/null +++ b/tests/micropython/viper_const.py @@ -0,0 +1,21 @@ +# test loading constants in viper functions + + +@micropython.viper +def f(): + return b"bytes" + + +print(f()) + + +@micropython.viper +def f(): + @micropython.viper + def g() -> int: + return 123 + + return g + + +print(f()()) diff --git a/tests/micropython/viper_const.py.exp b/tests/micropython/viper_const.py.exp new file mode 100644 index 0000000000..9002a0c2e5 --- /dev/null +++ b/tests/micropython/viper_const.py.exp @@ -0,0 +1,2 @@ +b'bytes' +123 diff --git a/tests/micropython/viper_const_intbig.py b/tests/micropython/viper_const_intbig.py new file mode 100644 index 0000000000..42574820a3 --- /dev/null +++ b/tests/micropython/viper_const_intbig.py @@ -0,0 +1,9 @@ +# check loading constants + + +@micropython.viper +def f(): + return 123456789012345678901234567890 + + +print(f()) diff --git a/tests/micropython/viper_const_intbig.py.exp b/tests/micropython/viper_const_intbig.py.exp new file mode 100644 index 0000000000..1d52d220f8 --- /dev/null +++ b/tests/micropython/viper_const_intbig.py.exp @@ -0,0 +1 @@ +123456789012345678901234567890 diff --git a/tests/micropython/viper_error.py b/tests/micropython/viper_error.py index fa136197d7..790f3d75c4 100644 --- a/tests/micropython/viper_error.py +++ b/tests/micropython/viper_error.py @@ -15,9 +15,6 @@ test("@micropython.viper\ndef f() -> 1: pass") # unknown type test("@micropython.viper\ndef f(x:unknown_type): pass") -# too many arguments -test("@micropython.viper\ndef f(a, b, c, d, e): pass") - # local used before type known test( """ diff --git a/tests/micropython/viper_error.py.exp b/tests/micropython/viper_error.py.exp index 3a8cb02994..da9a0ca93e 100644 --- a/tests/micropython/viper_error.py.exp +++ b/tests/micropython/viper_error.py.exp @@ -1,7 +1,6 @@ -SyntaxError('parameter annotation must be an identifier',) -SyntaxError('return annotation must be an identifier',) +SyntaxError('annotation must be an identifier',) +SyntaxError('annotation must be an identifier',) ViperTypeError("unknown type 'unknown_type'",) -ViperTypeError("Viper functions don't currently support more than 4 arguments",) ViperTypeError("local 'x' used before type known",) ViperTypeError("local 'x' has type 'int' but source is 'object'",) ViperTypeError("can't implicitly convert 'ptr' to 'bool'",) diff --git a/tests/micropython/viper_globals.py b/tests/micropython/viper_globals.py new file mode 100644 index 0000000000..9532dfd895 --- /dev/null +++ b/tests/micropython/viper_globals.py @@ -0,0 +1,22 @@ +# test that viper functions capture their globals context + +gl = {} + +exec( + """ +@micropython.viper +def f(): + return x +""", + gl, +) + +# x is not yet in the globals, f should not see it +try: + print(gl["f"]()) +except NameError: + print("NameError") + +# x is in globals, f should now see it +gl["x"] = 123 +print(gl["f"]()) diff --git a/tests/micropython/viper_globals.py.exp b/tests/micropython/viper_globals.py.exp new file mode 100644 index 0000000000..5731b89c1b --- /dev/null +++ b/tests/micropython/viper_globals.py.exp @@ -0,0 +1,2 @@ +NameError +123 diff --git a/tests/micropython/viper_try.py b/tests/micropython/viper_try.py new file mode 100644 index 0000000000..61335af221 --- /dev/null +++ b/tests/micropython/viper_try.py @@ -0,0 +1,45 @@ +# test try handling within a viper function + +# basic try-finally +@micropython.viper +def f(): + try: + fail + finally: + print("finally") + + +try: + f() +except NameError: + print("NameError") + +# nested try-except with try-finally +@micropython.viper +def f(): + try: + try: + fail + finally: + print("finally") + except NameError: + print("NameError") + + +f() + +# check that locals written to in try blocks keep their values +@micropython.viper +def f(): + a = 100 + try: + print(a) + a = 200 + fail + except NameError: + print(a) + a = 300 + print(a) + + +f() diff --git a/tests/micropython/viper_try.py.exp b/tests/micropython/viper_try.py.exp new file mode 100644 index 0000000000..96596ce5f5 --- /dev/null +++ b/tests/micropython/viper_try.py.exp @@ -0,0 +1,7 @@ +finally +NameError +finally +NameError +100 +200 +300 diff --git a/tests/micropython/viper_with.py b/tests/micropython/viper_with.py new file mode 100644 index 0000000000..d640c8ae0f --- /dev/null +++ b/tests/micropython/viper_with.py @@ -0,0 +1,36 @@ +# test with handling within a viper function + + +class C: + def __init__(self): + print("__init__") + + def __enter__(self): + print("__enter__") + + def __exit__(self, a, b, c): + print("__exit__", a, b, c) + + +# basic with +@micropython.viper +def f(): + with C(): + print(1) + + +f() + +# nested with and try-except +@micropython.viper +def f(): + try: + with C(): + print(1) + fail + print(2) + except NameError: + print("NameError") + + +f() diff --git a/tests/micropython/viper_with.py.exp b/tests/micropython/viper_with.py.exp new file mode 100644 index 0000000000..6eef7822fb --- /dev/null +++ b/tests/micropython/viper_with.py.exp @@ -0,0 +1,9 @@ +__init__ +__enter__ +1 +__exit__ None None None +__init__ +__enter__ +1 +__exit__ name 'fail' is not defined None +NameError diff --git a/tests/misc/features.py b/tests/misc/features.py index 419d8795f9..455b44fb1e 100644 --- a/tests/misc/features.py +++ b/tests/misc/features.py @@ -1,3 +1,9 @@ +try: + str.count +except AttributeError: + print("SKIP") + raise SystemExit + # mad.py # Alf Clement 27-Mar-2014 # diff --git a/tests/misc/print_exception.py b/tests/misc/print_exception.py index 11ed320f60..edb3045878 100644 --- a/tests/misc/print_exception.py +++ b/tests/misc/print_exception.py @@ -35,7 +35,7 @@ def print_exc(e): # basic exception message try: - 1 / 0 + raise Exception("msg") except Exception as e: print("caught") print_exc(e) @@ -46,7 +46,7 @@ def f(): def g(): - 2 / 0 + raise Exception("fail") try: @@ -58,7 +58,7 @@ except Exception as e: # Here we have a function with lots of bytecode generated for a single source-line, and # there is an error right at the end of the bytecode. It should report the correct line. def f(): - f([1, 2], [1, 2], [1, 2], {1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: X}) + f([1, 2], [1, 2], [1, 2], {1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: f.X}) return 1 diff --git a/tests/pyb/accel.py b/tests/pyb/accel.py deleted file mode 100644 index e5a1a2ed7a..0000000000 --- a/tests/pyb/accel.py +++ /dev/null @@ -1,9 +0,0 @@ -import pyb - -accel = pyb.Accel() -print(accel) -accel.x() -accel.y() -accel.z() -accel.tilt() -accel.filtered_xyz() diff --git a/tests/pyb/accel.py.exp b/tests/pyb/accel.py.exp deleted file mode 100644 index 28070be177..0000000000 --- a/tests/pyb/accel.py.exp +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/pyb/adc.py b/tests/pyb/adc.py deleted file mode 100644 index fff5a3019e..0000000000 --- a/tests/pyb/adc.py +++ /dev/null @@ -1,63 +0,0 @@ -from pyb import ADC, Timer - -adct = ADC(16) # Temperature 930 -> 20C -print(adct) -adcv = ADC(17) # Voltage 1500 -> 3.3V -print(adcv) - -# read single sample; 2.5V-5V is pass range -val = adcv.read() -assert val > 1000 and val < 2000 - -# timer for read_timed -tim = Timer(5, freq=500) - -# read into bytearray -buf = bytearray(b"\xff" * 50) -adcv.read_timed(buf, tim) -print(len(buf)) -for i in buf: - assert i > 50 and i < 150 - -# read into arrays with different element sizes -import array - -arv = array.array("h", 25 * [0x7FFF]) -adcv.read_timed(arv, tim) -print(len(arv)) -for i in arv: - assert i > 1000 and i < 2000 - -arv = array.array("i", 30 * [-1]) -adcv.read_timed(arv, tim) -print(len(arv)) -for i in arv: - assert i > 1000 and i < 2000 - -# Test read_timed_multi -arv = bytearray(b"\xff" * 50) -art = bytearray(b"\xff" * 50) -ADC.read_timed_multi((adcv, adct), (arv, art), tim) -for i in arv: - assert i > 60 and i < 125 -# Wide range: unsure of accuracy of temp sensor. -for i in art: - assert i > 15 and i < 200 - -arv = array.array("i", 25 * [-1]) -art = array.array("i", 25 * [-1]) -ADC.read_timed_multi((adcv, adct), (arv, art), tim) -for i in arv: - assert i > 1000 and i < 2000 -# Wide range: unsure of accuracy of temp sensor. -for i in art: - assert i > 50 and i < 2000 - -arv = array.array("h", 25 * [0x7FFF]) -art = array.array("h", 25 * [0x7FFF]) -ADC.read_timed_multi((adcv, adct), (arv, art), tim) -for i in arv: - assert i > 1000 and i < 2000 -# Wide range: unsure of accuracy of temp sensor. -for i in art: - assert i > 50 and i < 2000 diff --git a/tests/pyb/adc.py.exp b/tests/pyb/adc.py.exp deleted file mode 100644 index 1aae16fb01..0000000000 --- a/tests/pyb/adc.py.exp +++ /dev/null @@ -1,5 +0,0 @@ - - -50 -25 -30 diff --git a/tests/pyb/adcall.py b/tests/pyb/adcall.py deleted file mode 100644 index cfe179a97b..0000000000 --- a/tests/pyb/adcall.py +++ /dev/null @@ -1,31 +0,0 @@ -from pyb import Pin, ADCAll - -pins = [Pin.cpu.A0, Pin.cpu.A1, Pin.cpu.A2, Pin.cpu.A3] - -# set pins to IN mode, init ADCAll, then check pins are ANALOG -for p in pins: - p.init(p.IN) -adc = ADCAll(12) -for p in pins: - print(p) - -# set pins to IN mode, init ADCAll with mask, then check some pins are ANALOG -for p in pins: - p.init(p.IN) -adc = ADCAll(12, 0x70003) -for p in pins: - print(p) - -# init all pins to ANALOG -adc = ADCAll(12) -print(adc) - -# read all channels -for c in range(19): - print(type(adc.read_channel(c))) - -# call special reading functions -print(0 < adc.read_core_temp() < 100) -print(0 < adc.read_core_vbat() < 4) -print(0 < adc.read_core_vref() < 2) -print(0 < adc.read_vref() < 4) diff --git a/tests/pyb/adcall.py.exp b/tests/pyb/adcall.py.exp deleted file mode 100644 index 5a85ba770e..0000000000 --- a/tests/pyb/adcall.py.exp +++ /dev/null @@ -1,32 +0,0 @@ -Pin(Pin.cpu.A0, mode=Pin.ANALOG) -Pin(Pin.cpu.A1, mode=Pin.ANALOG) -Pin(Pin.cpu.A2, mode=Pin.ANALOG) -Pin(Pin.cpu.A3, mode=Pin.ANALOG) -Pin(Pin.cpu.A0, mode=Pin.ANALOG) -Pin(Pin.cpu.A1, mode=Pin.ANALOG) -Pin(Pin.cpu.A2, mode=Pin.IN) -Pin(Pin.cpu.A3, mode=Pin.IN) - - - - - - - - - - - - - - - - - - - - -True -True -True -True diff --git a/tests/pyb/can.py b/tests/pyb/can.py deleted file mode 100644 index 7d27318d86..0000000000 --- a/tests/pyb/can.py +++ /dev/null @@ -1,314 +0,0 @@ -try: - from pyb import CAN -except ImportError: - print("SKIP") - raise SystemExit - -from array import array -import micropython -import pyb - -# test we can correctly create by id or name -for bus in (-1, 0, 1, 2, 3, "YA", "YB", "YC"): - try: - CAN(bus, CAN.LOOPBACK) - print("CAN", bus) - except ValueError: - print("ValueError", bus) -CAN(1).deinit() - -CAN.initfilterbanks(14) -can = CAN(1) -print(can) - -# Test state when de-init'd -print(can.state() == can.STOPPED) - -can.init(CAN.LOOPBACK) -print(can) -print(can.any(0)) - -# Test state when freshly created -print(can.state() == can.ERROR_ACTIVE) - -# Test that restart can be called -can.restart() - -# Test info returns a sensible value -print(can.info()) - -# Catch all filter -can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) - -can.send("abcd", 123, timeout=5000) -print(can.any(0), can.info()) -print(can.recv(0)) - -can.send("abcd", -1, timeout=5000) -print(can.recv(0)) - -can.send("abcd", 0x7FF + 1, timeout=5000) -print(can.recv(0)) - -# Test too long message -try: - can.send("abcdefghi", 0x7FF, timeout=5000) -except ValueError: - print("passed") -else: - print("failed") - -# Test that recv can work without allocating memory on the heap - -buf = bytearray(10) -l = [0, 0, 0, memoryview(buf)] -l2 = None - -micropython.heap_lock() - -can.send("", 42) -l2 = can.recv(0, l) -assert l is l2 -print(l, len(l[3]), buf) - -can.send("1234", 42) -l2 = can.recv(0, l) -assert l is l2 -print(l, len(l[3]), buf) - -can.send("01234567", 42) -l2 = can.recv(0, l) -assert l is l2 -print(l, len(l[3]), buf) - -can.send("abc", 42) -l2 = can.recv(0, l) -assert l is l2 -print(l, len(l[3]), buf) - -micropython.heap_unlock() - -# Test that recv can work with different arrays behind the memoryview -can.send("abc", 1) -print(bytes(can.recv(0, [0, 0, 0, memoryview(array("B", range(8)))])[3])) -can.send("def", 1) -print(bytes(can.recv(0, [0, 0, 0, memoryview(array("b", range(8)))])[3])) - -# Test for non-list passed as second arg to recv -can.send("abc", 1) -try: - can.recv(0, 1) -except TypeError: - print("TypeError") - -# Test for too-short-list passed as second arg to recv -can.send("abc", 1) -try: - can.recv(0, [0, 0, 0]) -except ValueError: - print("ValueError") - -# Test for non-memoryview passed as 4th element to recv -can.send("abc", 1) -try: - can.recv(0, [0, 0, 0, 0]) -except TypeError: - print("TypeError") - -# Test for read-only-memoryview passed as 4th element to recv -can.send("abc", 1) -try: - can.recv(0, [0, 0, 0, memoryview(bytes(8))]) -except ValueError: - print("ValueError") - -# Test for bad-typecode-memoryview passed as 4th element to recv -can.send("abc", 1) -try: - can.recv(0, [0, 0, 0, memoryview(array("i", range(8)))]) -except ValueError: - print("ValueError") - -del can - -# Testing extended IDs -can = CAN(1, CAN.LOOPBACK, extframe=True) -# Catch all filter -can.setfilter(0, CAN.MASK32, 0, (0, 0)) - -print(can) - -try: - can.send("abcde", 0x7FF + 1, timeout=5000) -except ValueError: - print("failed") -else: - r = can.recv(0) - if r[0] == 0x7FF + 1 and r[3] == b"abcde": - print("passed") - else: - print("failed, wrong data received") - -# Test filters -for n in [0, 8, 16, 24]: - filter_id = 0b00001000 << n - filter_mask = 0b00011100 << n - id_ok = 0b00001010 << n - id_fail = 0b00011010 << n - - can.clearfilter(0) - can.setfilter(0, pyb.CAN.MASK32, 0, (filter_id, filter_mask)) - - can.send("ok", id_ok, timeout=3) - if can.any(0): - msg = can.recv(0) - print((hex(filter_id), hex(filter_mask), hex(msg[0]), msg[3])) - - can.send("fail", id_fail, timeout=3) - if can.any(0): - msg = can.recv(0) - print((hex(filter_id), hex(filter_mask), hex(msg[0]), msg[3])) - -del can - -# Test RxCallbacks -can = CAN(1, CAN.LOOPBACK) -can.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4)) -can.setfilter(1, CAN.LIST16, 1, (5, 6, 7, 8)) - - -def cb0(bus, reason): - print("cb0") - if reason == 0: - print("pending") - if reason == 1: - print("full") - if reason == 2: - print("overflow") - - -def cb1(bus, reason): - print("cb1") - if reason == 0: - print("pending") - if reason == 1: - print("full") - if reason == 2: - print("overflow") - - -def cb0a(bus, reason): - print("cb0a") - if reason == 0: - print("pending") - if reason == 1: - print("full") - if reason == 2: - print("overflow") - - -def cb1a(bus, reason): - print("cb1a") - if reason == 0: - print("pending") - if reason == 1: - print("full") - if reason == 2: - print("overflow") - - -can.rxcallback(0, cb0) -can.rxcallback(1, cb1) - -can.send("11111111", 1, timeout=5000) -can.send("22222222", 2, timeout=5000) -can.send("33333333", 3, timeout=5000) -can.rxcallback(0, cb0a) -can.send("44444444", 4, timeout=5000) - -can.send("55555555", 5, timeout=5000) -can.send("66666666", 6, timeout=5000) -can.send("77777777", 7, timeout=5000) -can.rxcallback(1, cb1a) -can.send("88888888", 8, timeout=5000) - -print(can.recv(0)) -print(can.recv(0)) -print(can.recv(0)) -print(can.recv(1)) -print(can.recv(1)) -print(can.recv(1)) - -can.send("11111111", 1, timeout=5000) -can.send("55555555", 5, timeout=5000) - -print(can.recv(0)) -print(can.recv(1)) - -del can - -# Testing asynchronous send -can = CAN(1, CAN.LOOPBACK) -can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) - -while can.any(0): - can.recv(0) - -can.send("abcde", 1, timeout=0) -print(can.any(0)) -while not can.any(0): - pass - -print(can.recv(0)) - -try: - can.send("abcde", 2, timeout=0) - can.send("abcde", 3, timeout=0) - can.send("abcde", 4, timeout=0) - can.send("abcde", 5, timeout=0) -except OSError as e: - if str(e) == "16": - print("passed") - else: - print("failed") - -pyb.delay(500) -while can.any(0): - print(can.recv(0)) - -# Testing rtr messages -bus1 = CAN(1, CAN.LOOPBACK) -bus2 = CAN(2, CAN.LOOPBACK, extframe=True) -while bus1.any(0): - bus1.recv(0) -while bus2.any(0): - bus2.recv(0) -bus1.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4)) -bus1.setfilter(1, CAN.LIST16, 0, (5, 6, 7, 8), rtr=(True, True, True, True)) -bus1.setfilter(2, CAN.MASK16, 0, (64, 64, 32, 32), rtr=(False, True)) -bus2.setfilter(0, CAN.LIST32, 0, (1, 2), rtr=(True, True)) -bus2.setfilter(1, CAN.LIST32, 0, (3, 4), rtr=(True, False)) -bus2.setfilter(2, CAN.MASK32, 0, (16, 16), rtr=(False,)) -bus2.setfilter(2, CAN.MASK32, 0, (32, 32), rtr=(True,)) - -bus1.send("", 1, rtr=True) -print(bus1.any(0)) -bus1.send("", 5, rtr=True) -print(bus1.recv(0)) -bus1.send("", 6, rtr=True) -print(bus1.recv(0)) -bus1.send("", 7, rtr=True) -print(bus1.recv(0)) -bus1.send("", 16, rtr=True) -print(bus1.any(0)) -bus1.send("", 32, rtr=True) -print(bus1.recv(0)) - -bus2.send("", 1, rtr=True) -print(bus2.recv(0)) -bus2.send("", 2, rtr=True) -print(bus2.recv(0)) -bus2.send("", 3, rtr=True) -print(bus2.recv(0)) -bus2.send("", 4, rtr=True) -print(bus2.any(0)) diff --git a/tests/pyb/can.py.exp b/tests/pyb/can.py.exp deleted file mode 100644 index 687935e7f4..0000000000 --- a/tests/pyb/can.py.exp +++ /dev/null @@ -1,76 +0,0 @@ -ValueError -1 -ValueError 0 -CAN 1 -CAN 2 -ValueError 3 -CAN YA -CAN YB -ValueError YC -CAN(1) -True -CAN(1, CAN.LOOPBACK, extframe=False, auto_restart=False) -False -True -[0, 0, 0, 0, 0, 0, 0, 0] -True [0, 0, 0, 0, 0, 0, 1, 0] -(123, False, 0, b'abcd') -(2047, False, 0, b'abcd') -(0, False, 0, b'abcd') -passed -[42, False, 0, ] 0 bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') -[42, False, 0, ] 4 bytearray(b'1234\x00\x00\x00\x00\x00\x00') -[42, False, 0, ] 8 bytearray(b'01234567\x00\x00') -[42, False, 0, ] 3 bytearray(b'abc34567\x00\x00') -b'abc' -b'def' -TypeError -ValueError -TypeError -ValueError -ValueError -CAN(1, CAN.LOOPBACK, extframe=True, auto_restart=False) -passed -('0x8', '0x1c', '0xa', b'ok') -('0x800', '0x1c00', '0xa00', b'ok') -('0x80000', '0x1c0000', '0xa0000', b'ok') -('0x8000000', '0x1c000000', '0xa000000', b'ok') -cb0 -pending -cb0 -full -cb0a -overflow -cb1 -pending -cb1 -full -cb1a -overflow -(1, False, 0, b'11111111') -(2, False, 1, b'22222222') -(4, False, 3, b'44444444') -(5, False, 0, b'55555555') -(6, False, 1, b'66666666') -(8, False, 3, b'88888888') -cb0a -pending -cb1a -pending -(1, False, 0, b'11111111') -(5, False, 0, b'55555555') -False -(1, False, 0, b'abcde') -passed -(2, False, 0, b'abcde') -(3, False, 0, b'abcde') -(4, False, 0, b'abcde') -False -(5, True, 4, b'') -(6, True, 5, b'') -(7, True, 6, b'') -False -(32, True, 9, b'') -(1, True, 0, b'') -(2, True, 1, b'') -(3, True, 2, b'') -False diff --git a/tests/pyb/dac.py b/tests/pyb/dac.py deleted file mode 100644 index 506cf272b3..0000000000 --- a/tests/pyb/dac.py +++ /dev/null @@ -1,18 +0,0 @@ -import pyb - -if not hasattr(pyb, "DAC"): - print("SKIP") - raise SystemExit - -dac = pyb.DAC(1) -print(dac) -dac.noise(100) -dac.triangle(100) -dac.write(0) -dac.write_timed(bytearray(10), 100, mode=pyb.DAC.NORMAL) -pyb.delay(20) -dac.write(0) - -# test buffering arg -dac = pyb.DAC(1, buffering=True) -dac.write(0) diff --git a/tests/pyb/dac.py.exp b/tests/pyb/dac.py.exp deleted file mode 100644 index 7ee99652a8..0000000000 --- a/tests/pyb/dac.py.exp +++ /dev/null @@ -1 +0,0 @@ -DAC(1, bits=8) diff --git a/tests/pyb/extint.py b/tests/pyb/extint.py deleted file mode 100644 index 927b2bceba..0000000000 --- a/tests/pyb/extint.py +++ /dev/null @@ -1,17 +0,0 @@ -import pyb - -# test basic functionality -ext = pyb.ExtInt("Y1", pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l: print("line:", l)) -ext.disable() -ext.enable() -print(ext.line()) -ext.swint() - -# test swint while disabled, then again after re-enabled -ext.disable() -ext.swint() -ext.enable() -ext.swint() - -# disable now that the test is finished -ext.disable() diff --git a/tests/pyb/extint.py.exp b/tests/pyb/extint.py.exp deleted file mode 100644 index 1f9da9844a..0000000000 --- a/tests/pyb/extint.py.exp +++ /dev/null @@ -1,3 +0,0 @@ -6 -line: 6 -line: 6 diff --git a/tests/pyb/halerror.py.exp b/tests/pyb/halerror.py.exp deleted file mode 100644 index 0f3f26253d..0000000000 --- a/tests/pyb/halerror.py.exp +++ /dev/null @@ -1,2 +0,0 @@ -OSError(5,) -OSError(110,) diff --git a/tests/pyb/i2c_error.py.exp b/tests/pyb/i2c_error.py.exp deleted file mode 100644 index bd403f7f47..0000000000 --- a/tests/pyb/i2c_error.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -OSError(5,) -OSError(5,) -OSError(5,) -OSError(5,) diff --git a/tests/pyb/irq.py b/tests/pyb/irq.py deleted file mode 100644 index 04e70a7b79..0000000000 --- a/tests/pyb/irq.py +++ /dev/null @@ -1,24 +0,0 @@ -import pyb - - -def test_irq(): - # test basic disable/enable - i1 = pyb.disable_irq() - print(i1) - pyb.enable_irq() # by default should enable IRQ - - # check that interrupts are enabled by waiting for ticks - pyb.delay(10) - - # check nested disable/enable - i1 = pyb.disable_irq() - i2 = pyb.disable_irq() - print(i1, i2) - pyb.enable_irq(i2) - pyb.enable_irq(i1) - - # check that interrupts are enabled by waiting for ticks - pyb.delay(10) - - -test_irq() diff --git a/tests/pyb/irq.py.exp b/tests/pyb/irq.py.exp deleted file mode 100644 index aea065f045..0000000000 --- a/tests/pyb/irq.py.exp +++ /dev/null @@ -1,2 +0,0 @@ -True -True False diff --git a/tests/pyb/led.py b/tests/pyb/led.py deleted file mode 100644 index d2a17ebc9a..0000000000 --- a/tests/pyb/led.py +++ /dev/null @@ -1,40 +0,0 @@ -import pyb -from pyb import LED - -l1 = pyb.LED(1) -l2 = pyb.LED(2) -l3 = pyb.LED(3) -l4 = pyb.LED(4) - -leds = [LED(i) for i in range(1, 5)] -pwm_leds = leds[2:] - -# test printing -for l in leds: - print(l) - -# test on and off -for l in leds: - l.on() - assert l.intensity() == 255 - pyb.delay(100) - l.off() - assert l.intensity() == 0 - pyb.delay(100) - -# test toggle -for l in 2 * leds: - l.toggle() - assert l.intensity() in (0, 255) - pyb.delay(100) - -# test intensity -for l in pwm_leds: - for i in range(256): - l.intensity(i) - assert l.intensity() == i - pyb.delay(1) - for i in range(255, -1, -1): - l.intensity(i) - assert l.intensity() == i - pyb.delay(1) diff --git a/tests/pyb/led.py.exp b/tests/pyb/led.py.exp deleted file mode 100644 index 4e8d856cd9..0000000000 --- a/tests/pyb/led.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -LED(1) -LED(2) -LED(3) -LED(4) diff --git a/tests/pyb/modstm.py b/tests/pyb/modstm.py deleted file mode 100644 index f1e147c052..0000000000 --- a/tests/pyb/modstm.py +++ /dev/null @@ -1,13 +0,0 @@ -# test stm module - -import stm -import pyb - -# test storing a full 32-bit number -# turn on then off the A15(=yellow) LED -BSRR = 0x18 -stm.mem32[stm.GPIOA + BSRR] = 0x00008000 -pyb.delay(100) -print(hex(stm.mem32[stm.GPIOA + stm.GPIO_ODR] & 0x00008000)) -stm.mem32[stm.GPIOA + BSRR] = 0x80000000 -print(hex(stm.mem32[stm.GPIOA + stm.GPIO_ODR] & 0x00008000)) diff --git a/tests/pyb/modstm.py.exp b/tests/pyb/modstm.py.exp deleted file mode 100644 index a24c9f8657..0000000000 --- a/tests/pyb/modstm.py.exp +++ /dev/null @@ -1,2 +0,0 @@ -0x8000 -0x0 diff --git a/tests/pyb/modtime.py b/tests/pyb/modtime.py deleted file mode 100644 index 1f5b5f32fe..0000000000 --- a/tests/pyb/modtime.py +++ /dev/null @@ -1,76 +0,0 @@ -import time - -DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] - - -def is_leap(year): - return (year % 4) == 0 - - -def test(): - seconds = 0 - wday = 5 # Jan 1, 2000 was a Saturday - for year in range(2000, 2034): - print("Testing %d" % year) - yday = 1 - for month in range(1, 13): - if month == 2 and is_leap(year): - DAYS_PER_MONTH[2] = 29 - else: - DAYS_PER_MONTH[2] = 28 - for day in range(1, DAYS_PER_MONTH[month] + 1): - secs = time.mktime((year, month, day, 0, 0, 0, 0, 0)) - if secs != seconds: - print( - "mktime failed for %d-%02d-%02d got %d expected %d" - % (year, month, day, secs, seconds) - ) - tuple = time.localtime(seconds) - secs = time.mktime(tuple) - if secs != seconds: - print( - "localtime failed for %d-%02d-%02d got %d expected %d" - % (year, month, day, secs, seconds) - ) - return - seconds += 86400 - if yday != tuple[7]: - print( - "locatime for %d-%02d-%02d got yday %d, expecting %d" - % (year, month, day, tuple[7], yday) - ) - return - if wday != tuple[6]: - print( - "locatime for %d-%02d-%02d got wday %d, expecting %d" - % (year, month, day, tuple[6], wday) - ) - return - yday += 1 - wday = (wday + 1) % 7 - - -def spot_test(seconds, expected_time): - actual_time = time.localtime(seconds) - for i in range(len(actual_time)): - if actual_time[i] != expected_time[i]: - print( - "time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time - ) - return - print("time.localtime(", seconds, ") returned", actual_time, "(pass)") - - -test() -spot_test(0, (2000, 1, 1, 0, 0, 0, 5, 1)) -spot_test(1, (2000, 1, 1, 0, 0, 1, 5, 1)) -spot_test(59, (2000, 1, 1, 0, 0, 59, 5, 1)) -spot_test(60, (2000, 1, 1, 0, 1, 0, 5, 1)) -spot_test(3599, (2000, 1, 1, 0, 59, 59, 5, 1)) -spot_test(3600, (2000, 1, 1, 1, 0, 0, 5, 1)) -spot_test(-1, (1999, 12, 31, 23, 59, 59, 4, 365)) -spot_test(447549467, (2014, 3, 7, 23, 17, 47, 4, 66)) -spot_test(-940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) -spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) -spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) -spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) diff --git a/tests/pyb/modtime.py.exp b/tests/pyb/modtime.py.exp deleted file mode 100644 index 3e1f6e920c..0000000000 --- a/tests/pyb/modtime.py.exp +++ /dev/null @@ -1,46 +0,0 @@ -Testing 2000 -Testing 2001 -Testing 2002 -Testing 2003 -Testing 2004 -Testing 2005 -Testing 2006 -Testing 2007 -Testing 2008 -Testing 2009 -Testing 2010 -Testing 2011 -Testing 2012 -Testing 2013 -Testing 2014 -Testing 2015 -Testing 2016 -Testing 2017 -Testing 2018 -Testing 2019 -Testing 2020 -Testing 2021 -Testing 2022 -Testing 2023 -Testing 2024 -Testing 2025 -Testing 2026 -Testing 2027 -Testing 2028 -Testing 2029 -Testing 2030 -Testing 2031 -Testing 2032 -Testing 2033 -time.localtime( 0 ) returned (2000, 1, 1, 0, 0, 0, 5, 1) (pass) -time.localtime( 1 ) returned (2000, 1, 1, 0, 0, 1, 5, 1) (pass) -time.localtime( 59 ) returned (2000, 1, 1, 0, 0, 59, 5, 1) (pass) -time.localtime( 60 ) returned (2000, 1, 1, 0, 1, 0, 5, 1) (pass) -time.localtime( 3599 ) returned (2000, 1, 1, 0, 59, 59, 5, 1) (pass) -time.localtime( 3600 ) returned (2000, 1, 1, 1, 0, 0, 5, 1) (pass) -time.localtime( -1 ) returned (1999, 12, 31, 23, 59, 59, 4, 365) (pass) -time.localtime( 447549467 ) returned (2014, 3, 7, 23, 17, 47, 4, 66) (pass) -time.localtime( -940984933 ) returned (1970, 3, 7, 23, 17, 47, 5, 66) (pass) -time.localtime( -1072915199 ) returned (1966, 1, 1, 0, 0, 1, 5, 1) (pass) -time.localtime( -1072915200 ) returned (1966, 1, 1, 0, 0, 0, 5, 1) (pass) -time.localtime( -1072915201 ) returned (1965, 12, 31, 23, 59, 59, 4, 365) (pass) diff --git a/tests/pyb/pin.py b/tests/pyb/pin.py deleted file mode 100644 index c5a4443321..0000000000 --- a/tests/pyb/pin.py +++ /dev/null @@ -1,33 +0,0 @@ -from pyb import Pin - -p = Pin("Y1", Pin.IN) -print(p) -print(p.name()) -print(p.pin()) -print(p.port()) - -p = Pin("Y1", Pin.IN, Pin.PULL_UP) -p = Pin("Y1", Pin.IN, pull=Pin.PULL_UP) -p = Pin("Y1", mode=Pin.IN, pull=Pin.PULL_UP) -print(p) -print(p.value()) - -p.init(p.IN, p.PULL_DOWN) -p.init(p.IN, pull=p.PULL_DOWN) -p.init(mode=p.IN, pull=p.PULL_DOWN) -print(p) -print(p.value()) - -p.init(p.OUT_PP) -p.low() -print(p.value()) -p.high() -print(p.value()) -p.value(0) -print(p.value()) -p.value(1) -print(p.value()) -p.value(False) -print(p.value()) -p.value(True) -print(p.value()) diff --git a/tests/pyb/pin.py.exp b/tests/pyb/pin.py.exp deleted file mode 100644 index f2f7038fd4..0000000000 --- a/tests/pyb/pin.py.exp +++ /dev/null @@ -1,14 +0,0 @@ -Pin(Pin.cpu.C6, mode=Pin.IN) -C6 -6 -2 -Pin(Pin.cpu.C6, mode=Pin.IN, pull=Pin.PULL_UP) -1 -Pin(Pin.cpu.C6, mode=Pin.IN, pull=Pin.PULL_DOWN) -0 -0 -1 -0 -1 -0 -1 diff --git a/tests/pyb/pyb1.py b/tests/pyb/pyb1.py deleted file mode 100644 index e9626ecf4e..0000000000 --- a/tests/pyb/pyb1.py +++ /dev/null @@ -1,39 +0,0 @@ -# basic tests of pyb module - -import pyb - -# test delay - -pyb.delay(-1) -pyb.delay(0) -pyb.delay(1) - -start = pyb.millis() -pyb.delay(17) -print((pyb.millis() - start) // 5) # should print 3 - -# test udelay - -pyb.udelay(-1) -pyb.udelay(0) -pyb.udelay(1) - -start = pyb.millis() -pyb.udelay(17000) -print((pyb.millis() - start) // 5) # should print 3 - -# other - -pyb.disable_irq() -pyb.enable_irq() - -print(pyb.have_cdc()) - -pyb.sync() - -print(len(pyb.unique_id())) - -pyb.wfi() - -pyb.fault_debug(True) -pyb.fault_debug(False) diff --git a/tests/pyb/pyb1.py.exp b/tests/pyb/pyb1.py.exp deleted file mode 100644 index 5816ea967b..0000000000 --- a/tests/pyb/pyb1.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -3 -3 -True -12 diff --git a/tests/pyb/pyb_f405.py b/tests/pyb/pyb_f405.py deleted file mode 100644 index 6ca943dcea..0000000000 --- a/tests/pyb/pyb_f405.py +++ /dev/null @@ -1,10 +0,0 @@ -# test pyb module on F405 MCUs - -import os, pyb - -if not "STM32F405" in os.uname().machine: - print("SKIP") - raise SystemExit - -print(pyb.freq()) -print(type(pyb.rng())) diff --git a/tests/pyb/pyb_f405.py.exp b/tests/pyb/pyb_f405.py.exp deleted file mode 100644 index a90aa02686..0000000000 --- a/tests/pyb/pyb_f405.py.exp +++ /dev/null @@ -1,2 +0,0 @@ -(168000000, 168000000, 42000000, 84000000) - diff --git a/tests/pyb/pyb_f411.py b/tests/pyb/pyb_f411.py deleted file mode 100644 index 58d5fa2d41..0000000000 --- a/tests/pyb/pyb_f411.py +++ /dev/null @@ -1,9 +0,0 @@ -# test pyb module on F411 MCUs - -import os, pyb - -if not "STM32F411" in os.uname().machine: - print("SKIP") - raise SystemExit - -print(pyb.freq()) diff --git a/tests/pyb/pyb_f411.py.exp b/tests/pyb/pyb_f411.py.exp deleted file mode 100644 index 79e0a10621..0000000000 --- a/tests/pyb/pyb_f411.py.exp +++ /dev/null @@ -1 +0,0 @@ -(96000000, 96000000, 24000000, 48000000) diff --git a/tests/pyb/rtc.py b/tests/pyb/rtc.py deleted file mode 100644 index 41b52f260d..0000000000 --- a/tests/pyb/rtc.py +++ /dev/null @@ -1,84 +0,0 @@ -import pyb, stm -from pyb import RTC - -rtc = RTC() -rtc.init() -print(rtc) - -# make sure that 1 second passes correctly -rtc.datetime((2014, 1, 1, 1, 0, 0, 0, 0)) -pyb.delay(1002) -print(rtc.datetime()[:7]) - - -def set_and_print(datetime): - rtc.datetime(datetime) - print(rtc.datetime()[:7]) - - -# make sure that setting works correctly -set_and_print((2000, 1, 1, 1, 0, 0, 0, 0)) -set_and_print((2000, 1, 31, 1, 0, 0, 0, 0)) -set_and_print((2000, 12, 31, 1, 0, 0, 0, 0)) -set_and_print((2016, 12, 31, 1, 0, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 0, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 1, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 12, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 13, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 23, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 23, 1, 0, 0)) -set_and_print((2016, 12, 31, 7, 23, 59, 0, 0)) -set_and_print((2016, 12, 31, 7, 23, 59, 1, 0)) -set_and_print((2016, 12, 31, 7, 23, 59, 59, 0)) -set_and_print((2099, 12, 31, 7, 23, 59, 59, 0)) - -# check that calibration works correctly -# save existing calibration value: -cal_tmp = rtc.calibration() - - -def set_and_print_calib(cal): - rtc.calibration(cal) - print(rtc.calibration()) - - -set_and_print_calib(512) -set_and_print_calib(511) -set_and_print_calib(345) -set_and_print_calib(1) -set_and_print_calib(0) -set_and_print_calib(-1) -set_and_print_calib(-123) -set_and_print_calib(-510) -set_and_print_calib(-511) - -# restore existing calibration value -rtc.calibration(cal_tmp) - -# Check register settings for wakeup -def set_and_print_wakeup(ms): - try: - rtc.wakeup(ms) - wucksel = stm.mem32[stm.RTC + stm.RTC_CR] & 7 - wut = stm.mem32[stm.RTC + stm.RTC_WUTR] & 0xFFFF - except ValueError: - wucksel = -1 - wut = -1 - print((wucksel, wut)) - - -set_and_print_wakeup(0) -set_and_print_wakeup(1) -set_and_print_wakeup(4000) -set_and_print_wakeup(4001) -set_and_print_wakeup(8000) -set_and_print_wakeup(8001) -set_and_print_wakeup(16000) -set_and_print_wakeup(16001) -set_and_print_wakeup(32000) -set_and_print_wakeup(32001) -set_and_print_wakeup(0x10000 * 1000) -set_and_print_wakeup(0x10001 * 1000) -set_and_print_wakeup(0x1FFFF * 1000) -set_and_print_wakeup(0x20000 * 1000) -set_and_print_wakeup(0x20001 * 1000) # exception diff --git a/tests/pyb/rtc.py.exp b/tests/pyb/rtc.py.exp deleted file mode 100644 index 7d3aaf6af7..0000000000 --- a/tests/pyb/rtc.py.exp +++ /dev/null @@ -1,40 +0,0 @@ - -(2014, 1, 1, 1, 0, 0, 1) -(2000, 1, 1, 1, 0, 0, 0) -(2000, 1, 31, 1, 0, 0, 0) -(2000, 12, 31, 1, 0, 0, 0) -(2016, 12, 31, 1, 0, 0, 0) -(2016, 12, 31, 7, 0, 0, 0) -(2016, 12, 31, 7, 1, 0, 0) -(2016, 12, 31, 7, 12, 0, 0) -(2016, 12, 31, 7, 13, 0, 0) -(2016, 12, 31, 7, 23, 0, 0) -(2016, 12, 31, 7, 23, 1, 0) -(2016, 12, 31, 7, 23, 59, 0) -(2016, 12, 31, 7, 23, 59, 1) -(2016, 12, 31, 7, 23, 59, 59) -(2099, 12, 31, 7, 23, 59, 59) -512 -511 -345 -1 -0 --1 --123 --510 --511 -(3, 0) -(3, 15) -(3, 65535) -(2, 32775) -(2, 65535) -(1, 32771) -(1, 65535) -(0, 32769) -(0, 65535) -(4, 31) -(4, 65535) -(6, 0) -(6, 65534) -(6, 65535) -(-1, -1) diff --git a/tests/pyb/servo.py b/tests/pyb/servo.py deleted file mode 100644 index d15cafe483..0000000000 --- a/tests/pyb/servo.py +++ /dev/null @@ -1,16 +0,0 @@ -from pyb import Servo - -servo = Servo(1) -print(servo) - -servo.angle(0) -servo.angle(10, 100) - -servo.speed(-10) -servo.speed(10, 100) - -servo.pulse_width(1500) -print(servo.pulse_width()) - -servo.calibration(630, 2410, 1490, 2460, 2190) -print(servo.calibration()) diff --git a/tests/pyb/servo.py.exp b/tests/pyb/servo.py.exp deleted file mode 100644 index ac6032ba5f..0000000000 --- a/tests/pyb/servo.py.exp +++ /dev/null @@ -1,3 +0,0 @@ - -1500 -(630, 2410, 1490, 2460, 2190) diff --git a/tests/pyb/switch.py b/tests/pyb/switch.py deleted file mode 100644 index 7c44adb136..0000000000 --- a/tests/pyb/switch.py +++ /dev/null @@ -1,6 +0,0 @@ -from pyb import Switch - -sw = Switch() -print(sw()) -sw.callback(print) -sw.callback(None) diff --git a/tests/pyb/timer.py b/tests/pyb/timer.py deleted file mode 100644 index 61320690a6..0000000000 --- a/tests/pyb/timer.py +++ /dev/null @@ -1,13 +0,0 @@ -# check basic functionality of the timer class - -import pyb -from pyb import Timer - -tim = Timer(4) -tim = Timer(4, prescaler=100, period=200) -print(tim.prescaler()) -print(tim.period()) -tim.prescaler(300) -print(tim.prescaler()) -tim.period(400) -print(tim.period()) diff --git a/tests/pyb/timer.py.exp b/tests/pyb/timer.py.exp deleted file mode 100644 index 5c46230303..0000000000 --- a/tests/pyb/timer.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -100 -200 -300 -400 diff --git a/tests/pyb/timer_callback.py b/tests/pyb/timer_callback.py deleted file mode 100644 index 51242fba4b..0000000000 --- a/tests/pyb/timer_callback.py +++ /dev/null @@ -1,54 +0,0 @@ -# check callback feature of the timer class - -import pyb -from pyb import Timer - -# callback function that disables the callback when called -def cb1(t): - print("cb1") - t.callback(None) - - -# callback function that disables the timer when called -def cb2(t): - print("cb2") - t.deinit() - - -# callback where cb4 closes over cb3.y -def cb3(x): - y = x - - def cb4(t): - print("cb4", y) - t.callback(None) - - return cb4 - - -# create a timer with a callback, using callback(None) to stop -tim = Timer(1, freq=100, callback=cb1) -pyb.delay(5) -print("before cb1") -pyb.delay(15) - -# create a timer with a callback, using deinit to stop -tim = Timer(2, freq=100, callback=cb2) -pyb.delay(5) -print("before cb2") -pyb.delay(15) - -# create a timer, then set the freq, then set the callback -tim = Timer(4) -tim.init(freq=100) -tim.callback(cb1) -pyb.delay(5) -print("before cb1") -pyb.delay(15) - -# test callback with a closure -tim.init(freq=100) -tim.callback(cb3(3)) -pyb.delay(5) -print("before cb4") -pyb.delay(15) diff --git a/tests/pyb/timer_callback.py.exp b/tests/pyb/timer_callback.py.exp deleted file mode 100644 index 9be7cf5b90..0000000000 --- a/tests/pyb/timer_callback.py.exp +++ /dev/null @@ -1,8 +0,0 @@ -before cb1 -cb1 -before cb2 -cb2 -before cb1 -cb1 -before cb4 -cb4 3 diff --git a/tests/pyb/uart.py b/tests/pyb/uart.py deleted file mode 100644 index afa7b8b340..0000000000 --- a/tests/pyb/uart.py +++ /dev/null @@ -1,32 +0,0 @@ -from pyb import UART - -# test we can correctly create by id or name -for bus in (-1, 0, 1, 2, 3, 4, 5, 6, 7, "XA", "XB", "YA", "YB", "Z"): - try: - UART(bus, 9600) - print("UART", bus) - except ValueError: - print("ValueError", bus) - -uart = UART(1) -uart = UART(1, 9600) -uart = UART(1, 9600, bits=8, parity=None, stop=1) -print(uart) - -uart.init(2400) -print(uart) - -print(uart.any()) -print(uart.write("123")) -print(uart.write(b"abcd")) -print(uart.writechar(1)) - -# make sure this method exists -uart.sendbreak() - -# non-blocking mode -uart = UART(1, 9600, timeout=0) -print(uart.write(b"1")) -print(uart.write(b"abcd")) -print(uart.writechar(1)) -print(uart.read(100)) diff --git a/tests/pyb/uart.py.exp b/tests/pyb/uart.py.exp deleted file mode 100644 index b5fe0cd0bd..0000000000 --- a/tests/pyb/uart.py.exp +++ /dev/null @@ -1,24 +0,0 @@ -ValueError -1 -ValueError 0 -UART 1 -UART 2 -UART 3 -UART 4 -ValueError 5 -UART 6 -ValueError 7 -UART XA -UART XB -UART YA -UART YB -ValueError Z -UART(1, baudrate=9600, bits=8, parity=None, stop=1, timeout=1000, timeout_char=3, read_buf_len=64) -UART(1, baudrate=2400, bits=8, parity=None, stop=1, timeout=1000, timeout_char=7, read_buf_len=64) -0 -3 -4 -None -1 -4 -None -None diff --git a/tests/run-tests b/tests/run-tests index e28600361b..e00d6930f0 100755 --- a/tests/run-tests +++ b/tests/run-tests @@ -149,13 +149,15 @@ def run_micropython(pyb, args, test_file, is_special=False): else: # run on pyboard - import pyboard pyb.enter_raw_repl() try: output_mupy = pyb.execfile(test_file) - except pyboard.PyboardError: + except pyboard.PyboardError as e: had_crash = True - output_mupy = b'CRASH' + if not is_special and e.args[0] == 'exception': + output_mupy = e.args[1] + e.args[2] + b'CRASH' + else: + output_mupy = b'CRASH' # canonical form for all ports/platforms is to use \n for end-of-line output_mupy = output_mupy.replace(b'\r\n', b'\n') @@ -298,8 +300,12 @@ def run_tests(pyb, tests, args, base_path=".", num_threads=1): skip_tests.add('thread/stress_recurse.py') # has reliability issues if upy_float_precision == 0: + skip_tests.add('extmod/uctypes_le_float.py') + skip_tests.add('extmod/uctypes_native_float.py') + skip_tests.add('extmod/uctypes_sizeof_float.py') skip_tests.add('extmod/ujson_dumps_float.py') skip_tests.add('extmod/ujson_loads_float.py') + skip_tests.add('extmod/urandom_extra_float.py') skip_tests.add('misc/rge_sm.py') if upy_float_precision < 32: skip_tests.add('float/float2int_intbig.py') # requires fp32, there's float2int_fp30_intbig.py instead @@ -348,6 +354,16 @@ def run_tests(pyb, tests, args, base_path=".", num_threads=1): skip_tests.add('basics/subclass_native_init.py')# native subclassing corner cases not support skip_tests.add('misc/rge_sm.py') # too large skip_tests.add('micropython/opt_level.py') # don't assume line numbers are stored + elif args.target == 'nrf': + skip_tests.add('basics/memoryview1.py') # no item assignment for memoryview + skip_tests.add('extmod/ticks_diff.py') # unimplemented: utime.ticks_diff + skip_tests.add('extmod/time_ms_us.py') # unimplemented: utime.ticks_ms + skip_tests.add('extmod/urandom_basic.py') # unimplemented: urandom.seed + skip_tests.add('micropython/opt_level.py') # no support for line numbers + skip_tests.add('misc/non_compliant.py') # no item assignment for bytearray + for t in tests: + if t.startswith('basics/io_'): + skip_tests.add(t) # Some tests are known to fail on 64-bit machines if pyb is None and platform.architecture()[0] == '64bit': @@ -360,31 +376,21 @@ def run_tests(pyb, tests, args, base_path=".", num_threads=1): # Some tests are known to fail with native emitter # Remove them from the below when they work if args.emit == 'native': - skip_tests.update({'basics/%s.py' % t for t in 'gen_yield_from gen_yield_from_close gen_yield_from_ducktype gen_yield_from_exc gen_yield_from_executing gen_yield_from_iter gen_yield_from_send gen_yield_from_stopped gen_yield_from_throw gen_yield_from_throw2 gen_yield_from_throw3 generator1 generator2 generator_args generator_close generator_closure generator_exc generator_pend_throw generator_return generator_send'.split()}) # require yield + skip_tests.update({'basics/%s.py' % t for t in 'gen_yield_from gen_yield_from_close gen_yield_from_ducktype gen_yield_from_exc gen_yield_from_executing gen_yield_from_iter gen_yield_from_send gen_yield_from_stopped gen_yield_from_throw gen_yield_from_throw2 gen_yield_from_throw3 generator1 generator2 generator_args generator_close generator_closure generator_exc generator_name generator_pend_throw generator_return generator_send'.split()}) # require yield skip_tests.update({'basics/%s.py' % t for t in 'bytes_gen class_store_class globals_del string_join gen_stack_overflow'.split()}) # require yield - skip_tests.update({'basics/async_%s.py' % t for t in 'def await await2 for for2 with with2 coroutine'.split()}) # require yield + skip_tests.update({'basics/async_%s.py' % t for t in 'def await await2 for for2 with with2 with_break with_return coroutine'.split()}) # require yield skip_tests.update({'basics/%s.py' % t for t in 'try_reraise try_reraise2'.split()}) # require raise_varargs - skip_tests.update({'basics/%s.py' % t for t in 'with_break with_continue with_return'.split()}) # require complete with support - skip_tests.add('basics/array_construct2.py') # requires generators - skip_tests.add('basics/bool1.py') # seems to randomly fail - skip_tests.add('basics/builtin_hash_gen.py') # requires yield - skip_tests.add('basics/class_bind_self.py') # requires yield skip_tests.add('basics/del_deref.py') # requires checking for unbound local skip_tests.add('basics/del_local.py') # requires checking for unbound local skip_tests.add('basics/exception_chain.py') # raise from is not supported - skip_tests.add('basics/for_range.py') # requires yield_value - skip_tests.add('basics/try_finally_loops.py') # requires proper try finally code - skip_tests.add('basics/try_finally_return.py') # requires proper try finally code - skip_tests.add('basics/try_finally_return2.py') # requires proper try finally code + skip_tests.add('basics/scope_implicit.py') # requires checking for unbound local + skip_tests.add('basics/try_finally_return2.py') # requires raise_varargs skip_tests.add('basics/unboundlocal.py') # requires checking for unbound local - skip_tests.add('import/gen_context.py') # requires yield_value skip_tests.add('misc/features.py') # requires raise_varargs - skip_tests.add('misc/rge_sm.py') # requires yield skip_tests.add('misc/print_exception.py') # because native doesn't have proper traceback info skip_tests.add('misc/sys_exc_info.py') # sys.exc_info() is not supported for native skip_tests.add('micropython/emg_exc.py') # because native doesn't have proper traceback info skip_tests.add('micropython/heapalloc_traceback.py') # because native doesn't have proper traceback info - skip_tests.add('micropython/heapalloc_iter.py') # requires generators skip_tests.add('micropython/schedule.py') # native code doesn't check pending events skip_tests.add('stress/gc_trace.py') # requires yield skip_tests.add('stress/recursive_gen.py') # requires yield @@ -403,8 +409,8 @@ def run_tests(pyb, tests, args, base_path=".", num_threads=1): if verdict == "exclude": return - test_basename = os.path.basename(test_file) - test_name = os.path.splitext(test_basename)[0] + test_basename = test_file.replace('..', '_').replace('./', '').replace('/', '_') + test_name = os.path.splitext(os.path.basename(test_file))[0] is_native = test_name.startswith("native_") or test_name.startswith("viper_") is_endian = test_name.endswith("_endian") is_int_big = test_name.startswith("int_big") or test_name.endswith("_intbig") @@ -560,10 +566,12 @@ the last matching regex is used: cmd_parser.add_argument('files', nargs='*', help='input test files') args = cmd_parser.parse_args() - EXTERNAL_TARGETS = ('pyboard', 'wipy', 'esp8266', 'esp32', 'minimal') + EXTERNAL_TARGETS = ('pyboard', 'wipy', 'esp8266', 'esp32', 'minimal', 'nrf') if args.target == 'unix' or args.list_tests: pyb = None elif args.target in EXTERNAL_TARGETS: + global pyboard + sys.path.append('../tools') import pyboard pyb = pyboard.Pyboard(args.device, args.baudrate, args.user, args.password) pyb.enter_raw_repl() @@ -575,7 +583,7 @@ the last matching regex is used: if args.target == 'pyboard': # run pyboard tests test_dirs = ('basics', 'micropython', 'float', 'misc', 'stress', 'extmod', 'pyb', 'pybnative', 'inlineasm') - elif args.target in ('esp8266', 'esp32', 'minimal'): + elif args.target in ('esp8266', 'esp32', 'minimal', 'nrf'): test_dirs = ('basics', 'micropython', 'float', 'misc', 'extmod') elif args.target == 'wipy': # run WiPy tests diff --git a/tests/unicode/unicode.py b/tests/unicode/unicode.py index f5af9cfff4..072e049fde 100644 --- a/tests/unicode/unicode.py +++ b/tests/unicode/unicode.py @@ -47,3 +47,7 @@ try: str(bytearray(b"ab\xc0a"), "utf8") except UnicodeError: print("UnicodeError") +try: + str(b"\xf0\xe0\xed\xe8", "utf8") +except UnicodeError: + print("UnicodeError") diff --git a/tests/unix/ffi_float.py b/tests/unix/ffi_float.py index b12bce9682..d039398965 100644 --- a/tests/unix/ffi_float.py +++ b/tests/unix/ffi_float.py @@ -19,7 +19,14 @@ def ffi_open(names): libc = ffi_open(("libc.so", "libc.so.0", "libc.so.6", "libc.dylib")) -strtof = libc.func("f", "strtof", "sp") +try: + strtof = libc.func("f", "strtof", "sp") +except OSError: + # Some libc's (e.g. Android's Bionic) define strtof as macro/inline func + # in terms of strtod(). + print("SKIP") + raise SystemExit + print("%.6f" % strtof("1.23", None)) strtod = libc.func("d", "strtod", "sp") diff --git a/tests/wipy/adc.py b/tests/wipy/adc.py deleted file mode 100644 index 73264113f3..0000000000 --- a/tests/wipy/adc.py +++ /dev/null @@ -1,115 +0,0 @@ -""" -ADC test for the CC3200 based boards. -""" - -from machine import ADC -import os - -mch = os.uname().machine -if "LaunchPad" in mch: - adc_pin = "GP5" - adc_channel = 3 -elif "WiPy" in mch: - adc_pin = "GP3" - adc_channel = 1 -else: - raise Exception("Board not supported!") - -adc = ADC(0) -print(adc) -adc = ADC() -print(adc) -adc = ADC(0, bits=12) -print(adc) - -apin = adc.channel(adc_channel) -print(apin) -apin = adc.channel(id=adc_channel) -print(apin) -apin = adc.channel(adc_channel, pin=adc_pin) -print(apin) -apin = adc.channel(id=adc_channel, pin=adc_pin) -print(apin) - -print(apin.value() > 3000) -print(apin() > 3000) - -# de-init must work -apin.deinit() -print(apin) - -adc.deinit() -print(adc) -print(apin) -adc.init() -print(adc) -print(apin) -apin.init() -print(apin) -print(apin() > 3000) - -# check for memory leaks... -for i in range(0, 1000): - adc = ADC() - apin = adc.channel(adc_channel) - -# next ones should raise -try: - adc = ADC(bits=17) -except: - print("Exception") - -try: - adc = ADC(id=1) -except: - print("Exception") - -try: - adc = ADC(0, 16) -except: - print("Exception") - -adc = ADC() -try: - apin = adc.channel(4) -except: - print("Exception") - -try: - apin = adc.channel(-1) -except: - print("Exception") - -try: - apin = adc.channel(0, pin="GP3") -except: - print("Exception") - -apin = adc.channel(1) -apin.deinit() -try: - apin() -except: - print("Exception") - -try: - apin.value() -except: - print("Exception") - -adc.deinit() -try: - apin.value() -except: - print("Exception") - -try: - apin = adc.channel(1) -except: - print("Exception") - -# re-init must work -adc.init() -apin.init() -print(apin) -print(apin() > 3000) diff --git a/tests/wipy/adc.py.exp b/tests/wipy/adc.py.exp deleted file mode 100644 index a65cf4963b..0000000000 --- a/tests/wipy/adc.py.exp +++ /dev/null @@ -1,28 +0,0 @@ -ADC(0, bits=12) -ADC(0, bits=12) -ADC(0, bits=12) -ADCChannel(1, pin=GP3) -ADCChannel(1, pin=GP3) -ADCChannel(1, pin=GP3) -ADCChannel(1, pin=GP3) -True -True -ADCChannel(1) -ADC(0) -ADCChannel(1) -ADC(0, bits=12) -ADCChannel(1) -ADCChannel(1, pin=GP3) -True -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -ADCChannel(1, pin=GP3) -True diff --git a/tests/wipy/modwipy.py b/tests/wipy/modwipy.py deleted file mode 100644 index 59df3ae90a..0000000000 --- a/tests/wipy/modwipy.py +++ /dev/null @@ -1,21 +0,0 @@ -""" -wipy module test for the CC3200 based boards -""" - -import os -import wipy - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - -print(wipy.heartbeat() == True) -wipy.heartbeat(False) -print(wipy.heartbeat() == False) -wipy.heartbeat(True) -print(wipy.heartbeat() == True) - -try: - wipy.heartbeat(True, 1) -except: - print("Exception") diff --git a/tests/wipy/modwipy.py.exp b/tests/wipy/modwipy.py.exp deleted file mode 100644 index 52eeb534ee..0000000000 --- a/tests/wipy/modwipy.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -True -True -True -Exception diff --git a/tests/wipy/os.py b/tests/wipy/os.py deleted file mode 100644 index 1f4debcade..0000000000 --- a/tests/wipy/os.py +++ /dev/null @@ -1,164 +0,0 @@ -""" -os module test for the CC3200 based boards -""" - -from machine import SD -import os - -mch = os.uname().machine -if "LaunchPad" in mch: - sd_pins = ("GP16", "GP17", "GP15") -elif "WiPy" in mch: - sd_pins = ("GP10", "GP11", "GP15") -else: - raise Exception("Board not supported!") - -sd = SD(pins=sd_pins) - -os.mount(sd, "/sd") -os.mkfs("/sd") -os.chdir("/flash") -print(os.listdir()) - -os.chdir("/sd") -print(os.listdir()) - -# create a test directory in flash -os.mkdir("/flash/test") -os.chdir("/flash/test") -print(os.getcwd()) -os.chdir("..") -print(os.getcwd()) -os.chdir("test") -print(os.getcwd()) -# create a new file -f = open("test.txt", "w") -test_bytes = os.urandom(1024) -n_w = f.write(test_bytes) -print(n_w == len(test_bytes)) -f.close() -f = open("test.txt", "r") -r = bytes(f.read(), "ascii") -# check that we can write and read it correctly -print(r == test_bytes) -f.close() -os.rename("test.txt", "newtest.txt") -print(os.listdir()) -os.rename("/flash/test", "/flash/newtest") -print(os.listdir("/flash")) -os.remove("newtest.txt") -os.chdir("..") -os.rmdir("newtest") - -# create a test directory in the sd card -os.mkdir("/sd/test") -os.chdir("/sd/test") -print(os.getcwd()) -os.chdir("..") -print(os.getcwd()) -os.chdir("test") -print(os.getcwd()) -# create a new file -f = open("test.txt", "w") -test_bytes = os.urandom(1024) -n_w = f.write(test_bytes) -print(n_w == len(test_bytes)) -f.close() -f = open("test.txt", "r") -r = bytes(f.read(), "ascii") -# check that we can write and read it correctly -print(r == test_bytes) -f.close() - -print("CC3200" in os.uname().machine) -print("WiPy" == os.uname().sysname) - -os.sync() -os.stat("/flash") -os.stat("/flash/sys") -os.stat("/flash/boot.py") -os.stat("/sd") -os.stat("/") -os.chdir("/sd/test") -os.remove("test.txt") -os.chdir("/sd") -os.rmdir("test") -os.listdir("/sd") -print(os.listdir("/")) -os.unmount("/sd") -print(os.listdir("/")) -os.mkfs(sd) -os.mount(sd, "/sd") -print(os.listdir("/")) -os.chdir("/flash") - -# next ones must raise -sd.deinit() -try: - os.listdir("/sd") -except: - print("Exception") - -# re-initialization must work -sd.init() -print(os.listdir("/sd")) - -try: - os.mount(sd, "/sd") -except: - print("Exception") - -try: - os.mount(sd, "/sd2") -except: - print("Exception") - -os.unmount("/sd") -try: - os.listdir("/sd") -except: - print("Exception") - -try: - os.unmount("/flash") -except: - print("Exception") - -try: - os.unmount("/something") -except: - print("Exception") - -try: - os.unmount("something") -except: - print("Exception") - -try: - os.mkfs("flash") # incorrect path format -except: - print("Exception") - -try: - os.remove("/flash/nofile.txt") -except: - print("Exception") - -try: - os.rename("/flash/nofile.txt", "/flash/nofile2.txt") -except: - print("Exception") - -try: - os.chdir("/flash/nodir") -except: - print("Exception") - -try: - os.listdir("/flash/nodir") -except: - print("Exception") - -os.mount(sd, "/sd") -print(os.listdir("/")) -os.unmount("/sd") diff --git a/tests/wipy/os.py.exp b/tests/wipy/os.py.exp deleted file mode 100644 index a0f01e35e1..0000000000 --- a/tests/wipy/os.py.exp +++ /dev/null @@ -1,32 +0,0 @@ -['main.py', 'sys', 'lib', 'cert', 'boot.py'] -[] -/flash/test -/flash -/flash/test -True -True -['newtest.txt'] -['main.py', 'sys', 'lib', 'cert', 'boot.py', 'newtest'] -/sd/test -/sd -/sd/test -True -True -True -True -['flash', 'sd'] -['flash'] -['flash', 'sd'] -[] -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -['flash', 'sd'] diff --git a/tests/wipy/pin.py b/tests/wipy/pin.py deleted file mode 100644 index 43537bba5c..0000000000 --- a/tests/wipy/pin.py +++ /dev/null @@ -1,217 +0,0 @@ -""" -This test need a set of pins which can be set as inputs and have no external -pull up or pull down connected. -GP12 and GP17 must be connected together -""" -from machine import Pin -import os - -mch = os.uname().machine -if "LaunchPad" in mch: - pin_map = [ - "GP24", - "GP12", - "GP14", - "GP15", - "GP16", - "GP17", - "GP28", - "GP8", - "GP6", - "GP30", - "GP31", - "GP3", - "GP0", - "GP4", - "GP5", - ] - max_af_idx = 15 -elif "WiPy" in mch: - pin_map = [ - "GP23", - "GP24", - "GP12", - "GP13", - "GP14", - "GP9", - "GP17", - "GP28", - "GP22", - "GP8", - "GP30", - "GP31", - "GP0", - "GP4", - "GP5", - ] - max_af_idx = 15 -else: - raise Exception("Board not supported!") - -# test initial value -p = Pin("GP12", Pin.IN) -Pin("GP17", Pin.OUT, value=1) -print(p() == 1) -Pin("GP17", Pin.OUT, value=0) -print(p() == 0) - - -def test_noinit(): - for p in pin_map: - pin = Pin(p) - pin.value() - - -def test_pin_read(pull): - # enable the pull resistor on all pins, then read the value - for p in pin_map: - pin = Pin(p, mode=Pin.IN, pull=pull) - for p in pin_map: - print(pin()) - - -def test_pin_af(): - for p in pin_map: - for af in Pin(p).alt_list(): - if af[1] <= max_af_idx: - Pin(p, mode=Pin.ALT, alt=af[1]) - Pin(p, mode=Pin.ALT_OPEN_DRAIN, alt=af[1]) - - -# test un-initialized pins -test_noinit() -# test with pull-up and pull-down -test_pin_read(Pin.PULL_UP) -test_pin_read(Pin.PULL_DOWN) - -# test all constructor combinations -pin = Pin(pin_map[0]) -pin = Pin(pin_map[0], mode=Pin.IN) -pin = Pin(pin_map[0], mode=Pin.OUT) -pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.PULL_DOWN) -pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.PULL_UP) -pin = Pin(pin_map[0], mode=Pin.OPEN_DRAIN, pull=Pin.PULL_UP) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_DOWN) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=None) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.LOW_POWER) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.MED_POWER) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.HIGH_POWER) -pin = Pin(pin_map[0], mode=Pin.OUT, drive=pin.LOW_POWER) -pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_DOWN) -pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP) -pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP) -test_pin_af() # try the entire af range on all pins - -# test pin init and printing -pin = Pin(pin_map[0]) -pin.init(mode=Pin.IN) -print(pin) -pin.init(Pin.IN, Pin.PULL_DOWN) -print(pin) -pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.LOW_POWER) -print(pin) -pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.HIGH_POWER) -print(pin) - -# test value in OUT mode -pin = Pin(pin_map[0], mode=Pin.OUT) -pin.value(0) -pin.toggle() # test toggle -print(pin()) -pin.toggle() # test toggle again -print(pin()) -# test different value settings -pin(1) -print(pin.value()) -pin(0) -print(pin.value()) -pin.value(1) -print(pin()) -pin.value(0) -print(pin()) - -# test all getters and setters -pin = Pin(pin_map[0], mode=Pin.OUT) -# mode -print(pin.mode() == Pin.OUT) -pin.mode(Pin.IN) -print(pin.mode() == Pin.IN) -# pull -pin.pull(None) -print(pin.pull() == None) -pin.pull(Pin.PULL_DOWN) -print(pin.pull() == Pin.PULL_DOWN) -# drive -pin.drive(Pin.MED_POWER) -print(pin.drive() == Pin.MED_POWER) -pin.drive(Pin.HIGH_POWER) -print(pin.drive() == Pin.HIGH_POWER) -# id -print(pin.id() == pin_map[0]) - -# all the next ones MUST raise -try: - pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.IN) # incorrect drive value -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], mode=Pin.LOW_POWER, pull=Pin.PULL_UP) # incorrect mode value -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.HIGH_POWER) # incorrect pull value -except Exception: - print("Exception") - -try: - pin = Pin("A0", Pin.OUT, Pin.PULL_DOWN) # incorrect pin id -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], Pin.IN, Pin.PULL_UP, alt=0) # af specified in GPIO mode -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_UP, alt=7) # af specified in GPIO mode -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP, alt=0) # incorrect af -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=-1) # incorrect af -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=16) # incorrect af -except Exception: - print("Exception") - -try: - pin.mode(Pin.PULL_UP) # incorrect pin mode -except Exception: - print("Exception") - -try: - pin.pull(Pin.OUT) # incorrect pull -except Exception: - print("Exception") - -try: - pin.drive(Pin.IN) # incorrect drive strength -except Exception: - print("Exception") - -try: - pin.id("ABC") # id cannot be set -except Exception: - print("Exception") diff --git a/tests/wipy/pin.py.exp b/tests/wipy/pin.py.exp deleted file mode 100644 index 0e3dddcf2b..0000000000 --- a/tests/wipy/pin.py.exp +++ /dev/null @@ -1,60 +0,0 @@ -True -True -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -Pin('GP23', mode=Pin.IN, pull=None, drive=Pin.MED_POWER, alt=-1) -Pin('GP23', mode=Pin.IN, pull=Pin.PULL_DOWN, drive=Pin.MED_POWER, alt=-1) -Pin('GP23', mode=Pin.OUT, pull=Pin.PULL_UP, drive=Pin.LOW_POWER, alt=-1) -Pin('GP23', mode=Pin.OUT, pull=Pin.PULL_UP, drive=Pin.HIGH_POWER, alt=-1) -1 -0 -1 -0 -1 -0 -True -True -True -True -True -True -True -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception diff --git a/tests/wipy/pin_irq.py b/tests/wipy/pin_irq.py deleted file mode 100644 index be5e1f426c..0000000000 --- a/tests/wipy/pin_irq.py +++ /dev/null @@ -1,120 +0,0 @@ -""" -Pin IRQ test for the CC3200 based boards. -""" - -from machine import Pin -import machine -import os -import time - -mch = os.uname().machine -if "LaunchPad" in mch: - pins = ["GP16", "GP13"] -elif "WiPy" in mch: - pins = ["GP16", "GP13"] -else: - raise Exception("Board not supported!") - -pin0 = Pin(pins[0], mode=Pin.OUT, value=1) -pin1 = Pin(pins[1], mode=Pin.IN, pull=Pin.PULL_UP) - - -def pin_handler(pin_o): - global pin_irq_count_trigger - global pin_irq_count_total - global _trigger - if _trigger & pin1_irq.flags(): - pin_irq_count_trigger += 1 - pin_irq_count_total += 1 - - -pin_irq_count_trigger = 0 -pin_irq_count_total = 0 -_trigger = Pin.IRQ_FALLING -pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) -for i in range(0, 10): - pin0.toggle() - time.sleep_ms(5) -print(pin_irq_count_trigger == 5) -print(pin_irq_count_total == 5) - -pin_irq_count_trigger = 0 -pin_irq_count_total = 0 -_trigger = Pin.IRQ_RISING -pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) -for i in range(0, 200): - pin0.toggle() - time.sleep_ms(5) -print(pin_irq_count_trigger == 100) -print(pin_irq_count_total == 100) - -pin1_irq.disable() -pin0(1) -pin_irq_count_trigger = 0 -pin_irq_count_total = 0 -_trigger = Pin.IRQ_FALLING -pin1_irq.init(trigger=_trigger, handler=pin_handler) -pin0(0) -time.sleep_us(50) -print(pin_irq_count_trigger == 1) -print(pin_irq_count_total == 1) -pin0(1) -time.sleep_us(50) -print(pin_irq_count_trigger == 1) -print(pin_irq_count_total == 1) - -# check the call method -pin1_irq() -print(pin_irq_count_trigger == 1) # no flags since the irq was manually triggered -print(pin_irq_count_total == 2) - -pin1_irq.disable() -pin_irq_count_trigger = 0 -pin_irq_count_total = 0 -for i in range(0, 10): - pin0.toggle() - time.sleep_ms(5) -print(pin_irq_count_trigger == 0) -print(pin_irq_count_total == 0) - -# test waking up from suspended mode on low level -pin0(0) -t0 = time.ticks_ms() -pin1_irq.init(trigger=Pin.IRQ_LOW_LEVEL, wake=machine.SLEEP) -machine.sleep() -print(time.ticks_ms() - t0 < 10) -print("Awake") - -# test waking up from suspended mode on high level -pin0(1) -t0 = time.ticks_ms() -pin1_irq.init(trigger=Pin.IRQ_HIGH_LEVEL, wake=machine.SLEEP) -machine.sleep() -print(time.ticks_ms() - t0 < 10) -print("Awake") - -# check for memory leaks -for i in range(0, 1000): - pin0_irq = pin0.irq(trigger=_trigger, handler=pin_handler) - pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) - -# next ones must raise -try: - pin1_irq.init(trigger=123456, handler=pin_handler) -except: - print("Exception") - -try: - pin1_irq.init(trigger=Pin.IRQ_LOW_LEVEL, wake=1789456) -except: - print("Exception") - -try: - pin0_irq = pin0.irq( - trigger=Pin.IRQ_RISING, wake=machine.SLEEP - ) # GP16 can't wake up from DEEPSLEEP -except: - print("Exception") - -pin0_irq.disable() -pin1_irq.disable() diff --git a/tests/wipy/pin_irq.py.exp b/tests/wipy/pin_irq.py.exp deleted file mode 100644 index 458bd95668..0000000000 --- a/tests/wipy/pin_irq.py.exp +++ /dev/null @@ -1,19 +0,0 @@ -True -True -True -True -True -True -True -True -True -True -True -True -True -Awake -True -Awake -Exception -Exception -Exception diff --git a/tests/wipy/reset/reset.py b/tests/wipy/reset/reset.py deleted file mode 100644 index 8d314f3b49..0000000000 --- a/tests/wipy/reset/reset.py +++ /dev/null @@ -1,17 +0,0 @@ -""" -Reset script for the cc3200 boards -This is needed to force the board to reboot -with the default WLAN AP settings -""" - -from machine import WDT -import time -import os - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - -wdt = WDT(timeout=1000) -print(wdt) -time.sleep_ms(900) diff --git a/tests/wipy/reset/reset.py.exp b/tests/wipy/reset/reset.py.exp deleted file mode 100644 index 4b6cc11e0d..0000000000 --- a/tests/wipy/reset/reset.py.exp +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/wipy/rtc.py b/tests/wipy/rtc.py deleted file mode 100644 index c62e400fe3..0000000000 --- a/tests/wipy/rtc.py +++ /dev/null @@ -1,119 +0,0 @@ -""" -RTC test for the CC3200 based boards. -""" - -from machine import RTC -import os -import time - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - -rtc = RTC() -print(rtc) -print(rtc.now()[:6]) - -rtc = RTC(datetime=(2015, 8, 29, 9, 0, 0, 0, None)) -print(rtc.now()[:6]) - -rtc.deinit() -print(rtc.now()[:6]) - -rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) -print(rtc.now()[:6]) -seconds = rtc.now()[5] -time.sleep_ms(1000) -print(rtc.now()[5] - seconds == 1) -seconds = rtc.now()[5] -time.sleep_ms(2000) -print(rtc.now()[5] - seconds == 2) - -# initialization with shorter tuples -rtc.init((2015, 9, 19, 8, 0, 0, 0)) -print(rtc.now()[5]) -rtc.init((2015, 9, 19, 8, 0, 0)) -print(rtc.now()[5]) -rtc.init((2015, 9, 19, 8, 0)) -print(rtc.now()[5]) -rtc.init((2015, 9, 19, 8)) -print(rtc.now()[4]) -rtc.init((2015, 9, 19)) -print(rtc.now()[3]) - - -def set_and_print(datetime): - rtc.init(datetime) - print(rtc.now()[:6]) - - -# make sure that setting works correctly -set_and_print((2000, 1, 1, 0, 0, 0, 0, None)) -set_and_print((2000, 1, 31, 0, 0, 0, 0, None)) -set_and_print((2000, 12, 31, 0, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 0, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 0, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 1, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 12, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 13, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 23, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 23, 1, 0, 0, None)) -set_and_print((2016, 12, 31, 23, 59, 0, 50, None)) -set_and_print((2016, 12, 31, 23, 59, 1, 900, None)) -set_and_print((2016, 12, 31, 23, 59, 59, 100, None)) -set_and_print((2048, 12, 31, 23, 59, 59, 99999, None)) - -rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) -rtc.alarm(0, 5000) -rtc.alarm(time=2000) -time.sleep_ms(1000) -left = rtc.alarm_left() -print(abs(left - 1000) <= 10) -time.sleep_ms(1000) -print(rtc.alarm_left() == 0) -time.sleep_ms(100) -print(rtc.alarm_left(0) == 0) - -rtc.alarm(time=1000, repeat=True) -time.sleep_ms(1500) -left = rtc.alarm_left() -print(abs(left - 500) <= 15) - -rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) -rtc.alarm(time=(2015, 8, 29, 9, 0, 45)) -time.sleep_ms(1000) -left = rtc.alarm_left() -print(abs(left - 44000) <= 90) -rtc.alarm_cancel() -rtc.deinit() - -# next ones must raise -try: - rtc.alarm(5000) -except: - print("Exception") - -try: - rtc.alarm_left(1) -except: - print("Exception") - -try: - rtc.alarm_cancel(1) -except: - print("Exception") - -try: - rtc.alarm(5000) -except: - print("Exception") - -try: - rtc = RTC(200000000) -except: - print("Exception") - -try: - rtc = RTC((2015, 8, 29, 9, 0, 0, 0, None)) -except: - print("Exception") diff --git a/tests/wipy/rtc.py.exp b/tests/wipy/rtc.py.exp deleted file mode 100644 index 44f8f8b81c..0000000000 --- a/tests/wipy/rtc.py.exp +++ /dev/null @@ -1,37 +0,0 @@ - -(2015, 1, 1, 0, 0, 0) -(2015, 8, 29, 9, 0, 0) -(2015, 1, 1, 0, 0, 0) -(2015, 8, 29, 9, 0, 0) -True -True -0 -0 -0 -0 -0 -(2000, 1, 1, 0, 0, 0) -(2000, 1, 31, 0, 0, 0) -(2000, 12, 31, 0, 0, 0) -(2016, 12, 31, 0, 0, 0) -(2016, 12, 31, 0, 0, 0) -(2016, 12, 31, 1, 0, 0) -(2016, 12, 31, 12, 0, 0) -(2016, 12, 31, 13, 0, 0) -(2016, 12, 31, 23, 0, 0) -(2016, 12, 31, 23, 1, 0) -(2016, 12, 31, 23, 59, 0) -(2016, 12, 31, 23, 59, 1) -(2016, 12, 31, 23, 59, 59) -(2048, 12, 31, 23, 59, 59) -True -True -True -True -True -Exception -Exception -Exception -Exception -Exception -Exception diff --git a/tests/wipy/sd.py b/tests/wipy/sd.py deleted file mode 100644 index 381d46f30a..0000000000 --- a/tests/wipy/sd.py +++ /dev/null @@ -1,45 +0,0 @@ -""" -SD card test for the CC3200 based boards. -""" - -from machine import SD -import os - -mch = os.uname().machine -if "LaunchPad" in mch: - sd_pins = ("GP16", "GP17", "GP15") -elif "WiPy" in mch: - sd_pins = ("GP10", "GP11", "GP15") -else: - raise Exception("Board not supported!") - -sd = SD(pins=sd_pins) -print(sd) -sd.deinit() -print(sd) -sd.init(sd_pins) -print(sd) - -sd = SD(0, pins=sd_pins) -sd = SD(id=0, pins=sd_pins) -sd = SD(0, sd_pins) - -# check for memory leaks -for i in range(0, 1000): - sd = sd = SD(0, pins=sd_pins) - -# next ones should raise -try: - sd = SD(pins=()) -except Exception: - print("Exception") - -try: - sd = SD(pins=("GP10", "GP11", "GP8")) -except Exception: - print("Exception") - -try: - sd = SD(pins=("GP10", "GP11")) -except Exception: - print("Exception") diff --git a/tests/wipy/sd.py.exp b/tests/wipy/sd.py.exp deleted file mode 100644 index eaa5f08efb..0000000000 --- a/tests/wipy/sd.py.exp +++ /dev/null @@ -1,6 +0,0 @@ - - - -Exception -Exception -Exception diff --git a/tests/wipy/skipped/rtc_irq.py b/tests/wipy/skipped/rtc_irq.py deleted file mode 100644 index 99712f8d18..0000000000 --- a/tests/wipy/skipped/rtc_irq.py +++ /dev/null @@ -1,93 +0,0 @@ -""" -RTC IRQ test for the CC3200 based boards. -""" - -from machine import RTC -import machine -import os -import time - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - - -def rtc_ticks_ms(rtc): - timedate = rtc.now() - return (timedate[5] * 1000) + (timedate[6] // 1000) - - -rtc_irq_count = 0 - - -def alarm_handler(rtc_o): - global rtc_irq - global rtc_irq_count - if rtc_irq.flags() & RTC.ALARM0: - rtc_irq_count += 1 - - -rtc = RTC() -rtc.alarm(time=500, repeat=True) -rtc_irq = rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler) - -# active mode -time.sleep_ms(1000) -rtc.alarm_cancel() -print(rtc_irq_count == 2) -rtc_irq_count = 0 -rtc.alarm(time=200, repeat=True) -time.sleep_ms(1000) -rtc.alarm_cancel() -print(rtc_irq_count == 5) - -rtc_irq_count = 0 -rtc.alarm(time=100, repeat=True) -time.sleep_ms(1000) -rtc.alarm_cancel() -print(rtc_irq_count == 10) - -# deep sleep mode -rtc.alarm_cancel() -rtc_irq_count = 0 -rtc.alarm(time=50, repeat=True) -rtc_irq.init(trigger=RTC.ALARM0, handler=alarm_handler, wake=machine.SLEEP | machine.IDLE) -while rtc_irq_count < 3: - machine.sleep() -print(rtc_irq_count == 3) - -# no repetition -rtc.alarm_cancel() -rtc_irq_count = 0 -rtc.alarm(time=100, repeat=False) -time.sleep_ms(250) -print(rtc_irq_count == 1) - -rtc.alarm_cancel() -t0 = rtc_ticks_ms(rtc) -rtc.alarm(time=500, repeat=False) -machine.sleep() -t1 = rtc_ticks_ms(rtc) -print(abs(t1 - t0 - 500) < 20) - -# deep sleep repeated mode -rtc.alarm_cancel() -rtc_irq_count = 0 -rtc.alarm(time=500, repeat=True) -t0 = rtc_ticks_ms(rtc) -rtc_irq = rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler, wake=machine.SLEEP) -while rtc_irq_count < 3: - machine.sleep() - t1 = rtc_ticks_ms(rtc) - print(abs(t1 - t0 - (500 * rtc_irq_count)) < 25) - -# next ones must raise -try: - rtc_irq = rtc.irq(trigger=10, handler=alarm_handler) -except: - print("Exception") - -try: - rtc_irq = rtc.irq(trigger=RTC.ALARM0, wake=1789456) -except: - print("Exception") diff --git a/tests/wipy/skipped/rtc_irq.py.exp b/tests/wipy/skipped/rtc_irq.py.exp deleted file mode 100644 index a3eebc2d11..0000000000 --- a/tests/wipy/skipped/rtc_irq.py.exp +++ /dev/null @@ -1,11 +0,0 @@ -True -True -True -True -True -True -True -True -True -Exception -Exception diff --git a/tests/wipy/time.py b/tests/wipy/time.py deleted file mode 100644 index c1d105d64d..0000000000 --- a/tests/wipy/time.py +++ /dev/null @@ -1,93 +0,0 @@ -import time - -DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] - - -def is_leap(year): - return (year % 4) == 0 - - -def test(): - seconds = 0 - wday = 5 # Jan 1, 2000 was a Saturday - for year in range(2000, 2049): - print("Testing %d" % year) - yday = 1 - for month in range(1, 13): - if month == 2 and is_leap(year): - DAYS_PER_MONTH[2] = 29 - else: - DAYS_PER_MONTH[2] = 28 - for day in range(1, DAYS_PER_MONTH[month] + 1): - secs = time.mktime((year, month, day, 0, 0, 0, 0, 0)) - if secs != seconds: - print( - "mktime failed for %d-%02d-%02d got %d expected %d" - % (year, month, day, secs, seconds) - ) - tuple = time.localtime(seconds) - secs = time.mktime(tuple) - if secs != seconds: - print( - "localtime failed for %d-%02d-%02d got %d expected %d" - % (year, month, day, secs, seconds) - ) - return - seconds += 86400 - if yday != tuple[7]: - print( - "locatime for %d-%02d-%02d got yday %d, expecting %d" - % (year, month, day, tuple[7], yday) - ) - return - if wday != tuple[6]: - print( - "locatime for %d-%02d-%02d got wday %d, expecting %d" - % (year, month, day, tuple[6], wday) - ) - return - yday += 1 - wday = (wday + 1) % 7 - - -def spot_test(seconds, expected_time): - actual_time = time.localtime(seconds) - for i in range(len(actual_time)): - if actual_time[i] != expected_time[i]: - print( - "time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time - ) - return - print("time.localtime(", seconds, ") returned", actual_time, "(pass)") - - -test() -spot_test(0, (2000, 1, 1, 0, 0, 0, 5, 1)) -spot_test(1, (2000, 1, 1, 0, 0, 1, 5, 1)) -spot_test(59, (2000, 1, 1, 0, 0, 59, 5, 1)) -spot_test(60, (2000, 1, 1, 0, 1, 0, 5, 1)) -spot_test(3599, (2000, 1, 1, 0, 59, 59, 5, 1)) -spot_test(3600, (2000, 1, 1, 1, 0, 0, 5, 1)) -spot_test(-1, (1999, 12, 31, 23, 59, 59, 4, 365)) -spot_test(447549467, (2014, 3, 7, 23, 17, 47, 4, 66)) -spot_test(-940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) -spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) -spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) -spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) - -t1 = time.time() -time.sleep(2) -t2 = time.time() -print(abs(time.ticks_diff(t1, t2) - 2) <= 1) - -t1 = time.ticks_ms() -time.sleep_ms(50) -t2 = time.ticks_ms() -print(abs(time.ticks_diff(t1, t2) - 50) <= 1) - -t1 = time.ticks_us() -time.sleep_us(1000) -t2 = time.ticks_us() -print(time.ticks_diff(t1, t2) < 1500) - -print(time.ticks_diff(time.ticks_cpu(), time.ticks_cpu()) < 16384) diff --git a/tests/wipy/time.py.exp b/tests/wipy/time.py.exp deleted file mode 100644 index 24d798f929..0000000000 --- a/tests/wipy/time.py.exp +++ /dev/null @@ -1,65 +0,0 @@ -Testing 2000 -Testing 2001 -Testing 2002 -Testing 2003 -Testing 2004 -Testing 2005 -Testing 2006 -Testing 2007 -Testing 2008 -Testing 2009 -Testing 2010 -Testing 2011 -Testing 2012 -Testing 2013 -Testing 2014 -Testing 2015 -Testing 2016 -Testing 2017 -Testing 2018 -Testing 2019 -Testing 2020 -Testing 2021 -Testing 2022 -Testing 2023 -Testing 2024 -Testing 2025 -Testing 2026 -Testing 2027 -Testing 2028 -Testing 2029 -Testing 2030 -Testing 2031 -Testing 2032 -Testing 2033 -Testing 2034 -Testing 2035 -Testing 2036 -Testing 2037 -Testing 2038 -Testing 2039 -Testing 2040 -Testing 2041 -Testing 2042 -Testing 2043 -Testing 2044 -Testing 2045 -Testing 2046 -Testing 2047 -Testing 2048 -time.localtime( 0 ) returned (2000, 1, 1, 0, 0, 0, 5, 1) (pass) -time.localtime( 1 ) returned (2000, 1, 1, 0, 0, 1, 5, 1) (pass) -time.localtime( 59 ) returned (2000, 1, 1, 0, 0, 59, 5, 1) (pass) -time.localtime( 60 ) returned (2000, 1, 1, 0, 1, 0, 5, 1) (pass) -time.localtime( 3599 ) returned (2000, 1, 1, 0, 59, 59, 5, 1) (pass) -time.localtime( 3600 ) returned (2000, 1, 1, 1, 0, 0, 5, 1) (pass) -time.localtime( -1 ) returned (1999, 12, 31, 23, 59, 59, 4, 365) (pass) -time.localtime( 447549467 ) returned (2014, 3, 7, 23, 17, 47, 4, 66) (pass) -time.localtime( -940984933 ) returned (1970, 3, 7, 23, 17, 47, 5, 66) (pass) -time.localtime( -1072915199 ) returned (1966, 1, 1, 0, 0, 1, 5, 1) (pass) -time.localtime( -1072915200 ) returned (1966, 1, 1, 0, 0, 0, 5, 1) (pass) -time.localtime( -1072915201 ) returned (1965, 12, 31, 23, 59, 59, 4, 365) (pass) -True -True -True -True diff --git a/tests/wipy/timer.py b/tests/wipy/timer.py deleted file mode 100644 index db25870db0..0000000000 --- a/tests/wipy/timer.py +++ /dev/null @@ -1,118 +0,0 @@ -""" -Timer test for the CC3200 based boards. -""" - -from machine import Timer -import os -import time - -mch = os.uname().machine -if "LaunchPad" in mch: - pwm_pin = "GP24" -elif "WiPy" in mch: - pwm_pin = "GP24" -else: - raise Exception("Board not supported!") - -for i in range(4): - tim = Timer(i, mode=Timer.PERIODIC) - print(tim) - ch = tim.channel(Timer.A, freq=5) - print(ch) - ch = tim.channel(Timer.B, freq=5) - print(ch) - tim = Timer(i, mode=Timer.ONE_SHOT) - print(tim) - ch = tim.channel(Timer.A, freq=50) - print(ch) - ch = tim.channel(Timer.B, freq=50) - print(ch) - tim = Timer(i, mode=Timer.PWM) - print(tim) - ch = tim.channel(Timer.A, freq=50000, duty_cycle=2000, polarity=Timer.POSITIVE) - print(ch) - ch = tim.channel(Timer.B, freq=50000, duty_cycle=8000, polarity=Timer.NEGATIVE) - print(ch) - tim.deinit() - print(tim) - -for i in range(4): - tim = Timer(i, mode=Timer.PERIODIC) - tim.deinit() - - -class TimerTest: - def __init__(self): - self.tim = Timer(0, mode=Timer.PERIODIC) - self.int_count = 0 - - def timer_isr(self, tim_ch): - self.int_count += 1 - - -timer_test = TimerTest() -ch = timer_test.tim.channel(Timer.A, freq=5) -print(ch.freq() == 5) -ch.irq(handler=timer_test.timer_isr, trigger=Timer.TIMEOUT) -time.sleep_ms(1001) -print(timer_test.int_count == 5) - -ch.freq(100) -timer_test.int_count = 0 -time.sleep_ms(1001) -print(timer_test.int_count == 100) - -ch.freq(1000) -time.sleep_ms(1500) -timer_test.int_count = 0 -time.sleep_ms(2000) -print(timer_test.int_count == 2000) - -timer_test.tim.deinit() -timer_test.tim.init(mode=Timer.ONE_SHOT) -ch = timer_test.tim.channel(Timer.A, period=100000) -ch.irq(handler=timer_test.timer_isr, trigger=Timer.TIMEOUT) -timer_test.int_count = 0 -time.sleep_ms(101) -print(timer_test.int_count == 1) -time.sleep_ms(101) -print(timer_test.int_count == 1) -timer_test.tim.deinit() -print(timer_test.tim) - -# 32 bit modes -tim = Timer(0, mode=Timer.PERIODIC, width=32) -ch = tim.channel(Timer.A | Timer.B, period=5000000) - -# check for memory leaks... -for i in range(1000): - tim = Timer(0, mode=Timer.PERIODIC) - ch = tim.channel(Timer.A, freq=5) - -# next ones must fail -try: - tim = Timer(0, mode=12) -except: - print("Exception") - -try: - tim = Timer(4, mode=Timer.ONE_SHOT) -except: - print("Exception") - -try: - tim = Timer(0, mode=Timer.PWM, width=32) -except: - print("Exception") - -tim = Timer(0, mode=Timer.PWM) - -try: - ch = tim.channel(TIMER_A | TIMER_B, freq=10) -except: - print("Exception") - -try: - ch = tim.channel(TIMER_A, freq=4) -except: - print("Exception") diff --git a/tests/wipy/timer.py.exp b/tests/wipy/timer.py.exp deleted file mode 100644 index 972d8198cc..0000000000 --- a/tests/wipy/timer.py.exp +++ /dev/null @@ -1,52 +0,0 @@ -Timer(0, mode=Timer.PERIODIC) -timer.channel(Timer.A, freq=5) -timer.channel(Timer.B, freq=5) -Timer(0, mode=Timer.ONE_SHOT) -timer.channel(Timer.A, freq=50) -timer.channel(Timer.B, freq=50) -Timer(0, mode=Timer.PWM) -timer.channel(Timer.A, freq=50000, polarity=Timer.POSITIVE, duty_cycle=20.00) -timer.channel(Timer.B, freq=50000, polarity=Timer.NEGATIVE, duty_cycle=80.00) -Timer(0, mode=Timer.PWM) -Timer(1, mode=Timer.PERIODIC) -timer.channel(Timer.A, freq=5) -timer.channel(Timer.B, freq=5) -Timer(1, mode=Timer.ONE_SHOT) -timer.channel(Timer.A, freq=50) -timer.channel(Timer.B, freq=50) -Timer(1, mode=Timer.PWM) -timer.channel(Timer.A, freq=50000, polarity=Timer.POSITIVE, duty_cycle=20.00) -timer.channel(Timer.B, freq=50000, polarity=Timer.NEGATIVE, duty_cycle=80.00) -Timer(1, mode=Timer.PWM) -Timer(2, mode=Timer.PERIODIC) -timer.channel(Timer.A, freq=5) -timer.channel(Timer.B, freq=5) -Timer(2, mode=Timer.ONE_SHOT) -timer.channel(Timer.A, freq=50) -timer.channel(Timer.B, freq=50) -Timer(2, mode=Timer.PWM) -timer.channel(Timer.A, freq=50000, polarity=Timer.POSITIVE, duty_cycle=20.00) -timer.channel(Timer.B, freq=50000, polarity=Timer.NEGATIVE, duty_cycle=80.00) -Timer(2, mode=Timer.PWM) -Timer(3, mode=Timer.PERIODIC) -timer.channel(Timer.A, freq=5) -timer.channel(Timer.B, freq=5) -Timer(3, mode=Timer.ONE_SHOT) -timer.channel(Timer.A, freq=50) -timer.channel(Timer.B, freq=50) -Timer(3, mode=Timer.PWM) -timer.channel(Timer.A, freq=50000, polarity=Timer.POSITIVE, duty_cycle=20.00) -timer.channel(Timer.B, freq=50000, polarity=Timer.NEGATIVE, duty_cycle=80.00) -Timer(3, mode=Timer.PWM) -True -True -True -True -True -True -Timer(0, mode=Timer.ONE_SHOT) -Exception -Exception -Exception -Exception -Exception diff --git a/tests/wipy/uart.py b/tests/wipy/uart.py deleted file mode 100644 index 0b1744d4ff..0000000000 --- a/tests/wipy/uart.py +++ /dev/null @@ -1,164 +0,0 @@ -""" -UART test for the CC3200 based boards. -UART0 and UART1 must be connected together for this test to pass. -""" - -from machine import UART -from machine import Pin -import os -import time - -mch = os.uname().machine -if "LaunchPad" in mch: - uart_id_range = range(0, 2) - uart_pins = [ - [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], - [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], - ] -elif "WiPy" in mch: - uart_id_range = range(0, 2) - uart_pins = [ - [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], - [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], - ] -else: - raise Exception("Board not supported!") - -# just in case we have the repl duplicated on any of the uarts -os.dupterm(None) - -for uart_id in uart_id_range: - uart = UART(uart_id, 38400) - print(uart) - uart.init(57600, 8, None, 1, pins=uart_pins[uart_id][0]) - uart.init(baudrate=9600, stop=2, parity=UART.EVEN, pins=uart_pins[uart_id][1]) - uart.init(baudrate=115200, parity=UART.ODD, stop=0, pins=uart_pins[uart_id][0]) - uart = UART(baudrate=1000000) - uart.sendbreak() - -uart = UART(baudrate=1000000) -uart = UART() -print(uart) -uart = UART(baudrate=38400, pins=("GP12", "GP13")) -print(uart) -uart = UART(pins=("GP12", "GP13")) -print(uart) -uart = UART(pins=(None, "GP17")) -print(uart) -uart = UART(baudrate=57600, pins=("GP16", "GP17")) -print(uart) - -# now it's time for some loopback tests between the uarts -uart0 = UART(0, 1000000, pins=uart_pins[0][0]) -print(uart0) -uart1 = UART(1, 1000000, pins=uart_pins[1][0]) -print(uart1) - -print(uart0.write(b"123456") == 6) -print(uart1.read() == b"123456") - -print(uart1.write(b"123") == 3) -print(uart0.read(1) == b"1") -print(uart0.read(2) == b"23") -print(uart0.read() == None) - -uart0.write(b"123") -buf = bytearray(3) -print(uart1.readinto(buf, 1) == 1) -print(buf) -print(uart1.readinto(buf) == 2) -print(buf) - -# try initializing without the id -uart0 = UART(baudrate=1000000, pins=uart_pins[0][0]) -uart0.write(b"1234567890") -time.sleep_ms(2) # because of the fifo interrupt levels -print(uart1.any() == 10) -print(uart1.readline() == b"1234567890") -print(uart1.any() == 0) - -uart0.write(b"1234567890") -print(uart1.read() == b"1234567890") - -# tx only mode -uart0 = UART(0, 1000000, pins=("GP12", None)) -print(uart0.write(b"123456") == 6) -print(uart1.read() == b"123456") -print(uart1.write(b"123") == 3) -print(uart0.read() == None) - -# rx only mode -uart0 = UART(0, 1000000, pins=(None, "GP13")) -print(uart0.write(b"123456") == 6) -print(uart1.read() == None) -print(uart1.write(b"123") == 3) -print(uart0.read() == b"123") - -# leave pins as they were (rx only mode) -uart0 = UART(0, 1000000, pins=None) -print(uart0.write(b"123456") == 6) -print(uart1.read() == None) -print(uart1.write(b"123") == 3) -print(uart0.read() == b"123") - -# no pin assignment -uart0 = UART(0, 1000000, pins=(None, None)) -print(uart0.write(b"123456789") == 9) -print(uart1.read() == None) -print(uart1.write(b"123456789") == 9) -print(uart0.read() == None) -print(Pin.board.GP12) -print(Pin.board.GP13) - -# check for memory leaks... -for i in range(0, 1000): - uart0 = UART(0, 1000000) - uart1 = UART(1, 1000000) - -# next ones must raise -try: - UART(0, 9600, parity=None, pins=("GP12", "GP13", "GP7")) -except Exception: - print("Exception") - -try: - UART(0, 9600, parity=UART.ODD, pins=("GP12", "GP7")) -except Exception: - print("Exception") - -uart0 = UART(0, 1000000) -uart0.deinit() -try: - uart0.any() -except Exception: - print("Exception") - -try: - uart0.read() -except Exception: - print("Exception") - -try: - uart0.write("abc") -except Exception: - print("Exception") - -try: - uart0.sendbreak("abc") -except Exception: - print("Exception") - -try: - UART(2, 9600) -except Exception: - print("Exception") - -for uart_id in uart_id_range: - uart = UART(uart_id, 1000000) - uart.deinit() - # test printing an unitialized uart - print(uart) - # initialize it back and check that it works again - uart.init(115200) - print(uart) - uart.read() diff --git a/tests/wipy/uart.py.exp b/tests/wipy/uart.py.exp deleted file mode 100644 index c8aeb77eff..0000000000 --- a/tests/wipy/uart.py.exp +++ /dev/null @@ -1,52 +0,0 @@ -UART(0, baudrate=38400, bits=8, parity=None, stop=1) -UART(1, baudrate=38400, bits=8, parity=None, stop=1) -UART(0, baudrate=9600, bits=8, parity=None, stop=1) -UART(0, baudrate=38400, bits=8, parity=None, stop=1) -UART(0, baudrate=9600, bits=8, parity=None, stop=1) -UART(1, baudrate=9600, bits=8, parity=None, stop=1) -UART(1, baudrate=57600, bits=8, parity=None, stop=1) -UART(0, baudrate=1000000, bits=8, parity=None, stop=1) -UART(1, baudrate=1000000, bits=8, parity=None, stop=1) -True -True -True -True -True -True -True -bytearray(b'1\x00\x00') -True -bytearray(b'23\x00') -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -Pin('GP12', mode=Pin.IN, pull=None, drive=Pin.MED_POWER, alt=-1) -Pin('GP13', mode=Pin.IN, pull=None, drive=Pin.MED_POWER, alt=-1) -Exception -Exception -Exception -Exception -Exception -Exception -Exception -UART(0) -UART(0, baudrate=115200, bits=8, parity=None, stop=1) -UART(1) -UART(1, baudrate=115200, bits=8, parity=None, stop=1) diff --git a/tests/wipy/uart_irq.py b/tests/wipy/uart_irq.py deleted file mode 100644 index e631e46a9c..0000000000 --- a/tests/wipy/uart_irq.py +++ /dev/null @@ -1,157 +0,0 @@ -""" -UART IRQ test for the CC3200 based boards. -""" - -from machine import UART -import os -import time - -mch = os.uname().machine -if "LaunchPad" in mch: - uart_pins = [ - [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], - [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], - ] -elif "WiPy" in mch: - uart_pins = [ - [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], - [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], - ] -else: - raise Exception("Board not supported!") - -# just in case we have stdio duplicated on any of the uarts -os.dupterm(None) - -uart0 = UART(0, 1000000, pins=uart_pins[0][0]) -uart1 = UART(1, 1000000, pins=uart_pins[1][0]) - -uart0_int_count = 0 -uart1_int_count = 0 - - -def uart0_handler(uart_o): - global uart0_irq - global uart0_int_count - if uart0_irq.flags() & UART.RX_ANY: - uart0_int_count += 1 - - -def uart1_handler(uart_o): - global uart1_irq - global uart1_int_count - if uart1_irq.flags() & UART.RX_ANY: - uart1_int_count += 1 - - -uart0_irq = uart0.irq(trigger=UART.RX_ANY, handler=uart0_handler) -uart1_irq = uart1.irq(trigger=UART.RX_ANY, handler=uart1_handler) - -uart0.write(b"123") -# wait for the characters to be received -while not uart1.any(): - pass - -time.sleep_us(100) -print(uart1.any() == 3) -print(uart1_int_count > 0) -print(uart1_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b"123") - -uart1.write(b"12345") -# wait for the characters to be received -while not uart0.any(): - pass - -time.sleep_us(100) -print(uart0.any() == 5) -print(uart0_int_count > 0) -print(uart0_irq.flags() == 0) -print(uart1_irq.flags() == 0) -print(uart0.read() == b"12345") - -# do it again -uart1_int_count = 0 -uart0.write(b"123") -# wait for the characters to be received -while not uart1.any(): - pass - -time.sleep_us(100) -print(uart1.any() == 3) -print(uart1_int_count > 0) -print(uart1_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b"123") - -# disable the interrupt -uart1_irq.disable() -# do it again -uart1_int_count = 0 -uart0.write(b"123") -# wait for the characters to be received -while not uart1.any(): - pass - -time.sleep_us(100) -print(uart1.any() == 3) -print(uart1_int_count == 0) # no interrupt triggered this time -print(uart1_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b"123") - -# enable the interrupt -uart1_irq.enable() -# do it again -uart1_int_count = 0 -uart0.write(b"123") -# wait for the characters to be received -while not uart1.any(): - pass - -time.sleep_us(100) -print(uart1.any() == 3) -print(uart1_int_count > 0) -print(uart1_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b"123") - -uart1_irq.init(trigger=UART.RX_ANY, handler=None) # No handler -# do it again -uart1_int_count = 0 -uart0.write(b"123") -# wait for the characters to be received -while not uart1.any(): - pass - -time.sleep_us(100) -print(uart1.any() == 3) -print(uart1_int_count == 0) # no interrupt handler called -print(uart1_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b"123") - -# check for memory leaks -for i in range(0, 1000): - uart0_irq = uart0.irq(trigger=UART.RX_ANY, handler=uart0_handler) - uart1_irq = uart1.irq(trigger=UART.RX_ANY, handler=uart1_handler) - -# next ones must raise -try: - uart0_irq = uart0.irq(trigger=100, handler=uart0_handler) -except: - print("Exception") - -try: - uart0_irq = uart0.irq(trigger=0) -except: - print("Exception") - -try: - uart0_irq = uart0.irq(trigger=UART.RX_ANY, wake=Sleep.SUSPENDED) -except: - print("Exception") - -uart0_irq.disable() -uart1_irq.disable() diff --git a/tests/wipy/uart_irq.py.exp b/tests/wipy/uart_irq.py.exp deleted file mode 100644 index b165e824a0..0000000000 --- a/tests/wipy/uart_irq.py.exp +++ /dev/null @@ -1,33 +0,0 @@ -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -Exception -Exception -Exception diff --git a/tests/wipy/wdt.py b/tests/wipy/wdt.py deleted file mode 100644 index 56f6ea8d95..0000000000 --- a/tests/wipy/wdt.py +++ /dev/null @@ -1,38 +0,0 @@ -""" -WDT test for the CC3200 based boards -""" - -from machine import WDT -import time - -# test the invalid cases first -try: - wdt = WDT(1) -except Exception: - print("Exception") - -try: - wdt = WDT(0, 500) -except Exception: - print("Exception") - -try: - wdt = WDT(1, timeout=2000) -except Exception: - print("Exception") - -wdt = WDT(timeout=1000) -print(wdt) - -try: - wdt = WDT(0, timeout=2000) -except Exception: - print("Exception") - -time.sleep_ms(500) -wdt.feed() -print(wdt) -time.sleep_ms(900) -wdt.feed() -print(wdt) -time.sleep_ms(950) diff --git a/tests/wipy/wdt.py.exp b/tests/wipy/wdt.py.exp deleted file mode 100644 index 71f5e13b53..0000000000 --- a/tests/wipy/wdt.py.exp +++ /dev/null @@ -1,7 +0,0 @@ -Exception -Exception -Exception - -Exception - - diff --git a/tests/wipy/wlan/machine.py b/tests/wipy/wlan/machine.py deleted file mode 100644 index f69b117b74..0000000000 --- a/tests/wipy/wlan/machine.py +++ /dev/null @@ -1,42 +0,0 @@ -""" -machine test for the CC3200 based boards. -""" - -import machine -import os -from network import WLAN - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - -wifi = WLAN() - -print(machine) -machine.idle() -print(machine.freq() == (80000000,)) -print(machine.unique_id() == wifi.mac()) - -machine.main("main.py") - -rand_nums = [] -for i in range(0, 100): - rand = machine.rng() - if rand not in rand_nums: - rand_nums.append(rand) - else: - print("RNG number repeated") - break - -for i in range(0, 10): - machine.idle() - -print("Active") - -print(machine.reset_cause() >= 0) -print(machine.wake_reason() >= 0) - -try: - machine.main(123456) -except: - print("Exception") diff --git a/tests/wipy/wlan/machine.py.exp b/tests/wipy/wlan/machine.py.exp deleted file mode 100644 index cc5b3f61da..0000000000 --- a/tests/wipy/wlan/machine.py.exp +++ /dev/null @@ -1,7 +0,0 @@ - -True -True -Active -True -True -Exception diff --git a/tests/wipy/wlan/server.py b/tests/wipy/wlan/server.py deleted file mode 100644 index 40f56745c9..0000000000 --- a/tests/wipy/wlan/server.py +++ /dev/null @@ -1,41 +0,0 @@ -""" -network server test for the CC3200 based boards. -""" - -import os -import network - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - -server = network.Server() - -print(server.timeout() == 300) -print(server.isrunning() == True) -server.deinit() -print(server.isrunning() == False) - -server.init(login=("test-user", "test-password"), timeout=60) -print(server.isrunning() == True) -print(server.timeout() == 60) - -server.deinit() -print(server.isrunning() == False) -server.init() -print(server.isrunning() == True) - -try: - server.init(1) -except: - print("Exception") - -try: - server.init(0, login=("0000000000011111111111222222222222333333", "abc")) -except: - print("Exception") - -try: - server.timeout(1) -except: - print("Exception") diff --git a/tests/wipy/wlan/server.py.exp b/tests/wipy/wlan/server.py.exp deleted file mode 100644 index a125ec934d..0000000000 --- a/tests/wipy/wlan/server.py.exp +++ /dev/null @@ -1,10 +0,0 @@ -True -True -True -True -True -True -True -Exception -Exception -Exception diff --git a/tests/wipy/wlan/wlan.py b/tests/wipy/wlan/wlan.py deleted file mode 100644 index dd85c86967..0000000000 --- a/tests/wipy/wlan/wlan.py +++ /dev/null @@ -1,183 +0,0 @@ -""" -WLAN test for the CC3200 based boards. -""" - -from network import WLAN -import os -import time -import testconfig - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - - -def wait_for_connection(wifi, timeout=10): - while not wifi.isconnected() and timeout > 0: - time.sleep(1) - timeout -= 1 - if wifi.isconnected(): - print("Connected") - else: - print("Connection failed!") - - -wifi = WLAN(0, WLAN.STA) -print(wifi.mode() == WLAN.STA) -print(wifi.antenna() == WLAN.INT_ANT) - -wifi = WLAN(mode=WLAN.AP) -print(wifi.mode() == WLAN.AP) -print(wifi.channel() == 1) -print(wifi.auth() == None) -print(wifi.antenna() == WLAN.INT_ANT) -wifi = WLAN(0, mode=WLAN.AP, ssid="test-wlan", auth=(WLAN.WPA, "123456abc"), channel=7) -print(wifi.mode() == WLAN.AP) -print(wifi.channel() == 7) -print(wifi.ssid() == "test-wlan") -print(wifi.auth() == (WLAN.WPA, "123456abc")) -print(wifi.antenna() == WLAN.INT_ANT) - -wifi = WLAN(mode=WLAN.STA) -print(wifi.mode() == WLAN.STA) -time.sleep(5) # this ensures a full network scan -scan_r = wifi.scan() -print(len(scan_r) > 3) -for net in scan_r: - if net.ssid == testconfig.wlan_ssid: - # test that the scan results contains the desired params - print(len(net.bssid) == 6) - print(net.channel == None) - print(net.sec == testconfig.wlan_auth[0]) - print(net.rssi < 0) - print("Network found") - break - -wifi.mode(WLAN.STA) -print(wifi.mode() == WLAN.STA) -wifi.channel(7) -print(wifi.channel() == 7) -wifi.ssid("t-wlan") -print(wifi.ssid() == "t-wlan") -wifi.auth(None) -print(wifi.auth() == None) -wifi.auth((WLAN.WEP, "11223344556677889900")) -print(wifi.auth() == (WLAN.WEP, "11223344556677889900")) -wifi.antenna(WLAN.INT_ANT) -print(wifi.antenna() == WLAN.INT_ANT) - -wifi.antenna(WLAN.EXT_ANT) -print(wifi.antenna() == WLAN.EXT_ANT) -time.sleep(2) # this ensures a full network scan -scan_r = wifi.scan() -print(len(scan_r) > 3) -for net in scan_r: - if net.ssid == testconfig.wlan_ssid: - print("Network found") - break - -wifi.antenna(WLAN.INT_ANT) -wifi.mode(WLAN.STA) -print(wifi.mode() == WLAN.STA) -wifi.connect(testconfig.wlan_ssid, auth=testconfig.wlan_auth, timeout=10000) -wait_for_connection(wifi) - -wifi.ifconfig(config="dhcp") -wait_for_connection(wifi) -print("0.0.0.0" not in wifi.ifconfig()) -wifi.ifconfig(0, ("192.168.178.109", "255.255.255.0", "192.168.178.1", "8.8.8.8")) -wait_for_connection(wifi) -print(wifi.ifconfig(0) == ("192.168.178.109", "255.255.255.0", "192.168.178.1", "8.8.8.8")) -wait_for_connection(wifi) - -print(wifi.isconnected() == True) -wifi.disconnect() -print(wifi.isconnected() == False) - -t0 = time.ticks_ms() -wifi.connect(testconfig.wlan_ssid, auth=testconfig.wlan_auth, timeout=0) -print(time.ticks_ms() - t0 < 500) - -wifi.disconnect() -print(wifi.isconnected() == False) - -# test init again -wifi.init(WLAN.AP, ssid="www.wipy.io", auth=None, channel=5, antenna=WLAN.INT_ANT) -print(wifi.mode() == WLAN.AP) - -# get the current instance without re-init -wifi = WLAN() -print(wifi.mode() == WLAN.AP) -wifi = WLAN(0) -print(wifi.mode() == WLAN.AP) - -# test the MAC address length -print(len(wifi.mac()) == 6) - -# next ones MUST raise -try: - wifi.init(mode=12345) -except: - print("Exception") - -try: - wifi.init(1, mode=WLAN.AP) -except: - print("Exception") - -try: - wifi.init(mode=WLAN.AP, ssid=None) -except: - print("Exception") - -try: - wifi = WLAN(mode=WLAN.AP, channel=12) -except: - print("Exception") - -try: - wifi.antenna(2) -except: - print("Exception") - -try: - wifi.mode(10) -except: - print("Exception") - -try: - wifi.ssid( - "11111sdfasdfasdfasdf564sdf654asdfasdf123451245ssdgfsdf1111111111111111111111111234123412341234asdfasdf" - ) -except: - print("Exception") - -try: - wifi.auth((0)) -except: - print("Exception") - -try: - wifi.auth((0, None)) -except: - print("Exception") - -try: - wifi.auth((10, 10)) -except: - print("Exception") - -try: - wifi.channel(0) -except: - print("Exception") - -try: - wifi.ifconfig(1, "dhcp") -except: - print("Exception") - -try: - wifi.ifconfig(config=()) -except: - print("Exception") diff --git a/tests/wipy/wlan/wlan.py.exp b/tests/wipy/wlan/wlan.py.exp deleted file mode 100644 index 2bb3537a22..0000000000 --- a/tests/wipy/wlan/wlan.py.exp +++ /dev/null @@ -1,55 +0,0 @@ -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -Network found -True -True -True -True -True -True -True -True -Network found -True -Connected -Connected -True -Connected -True -Connected -True -True -True -True -True -True -True -True -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception diff --git a/tools/build_board_info.py b/tools/build_board_info.py index 94f6e50af1..66ca48a02d 100644 --- a/tools/build_board_info.py +++ b/tools/build_board_info.py @@ -266,7 +266,7 @@ def generate_download_info(): # Delete the release we are replacing for board in current_info: info = current_info[board] - for version in info["versions"]: + for version in list(info["versions"]): previous_releases.add(version["version"]) previous_languages.update(version["languages"]) if version["stable"] == new_stable or ( diff --git a/tools/mpy-tool.py b/tools/mpy-tool.py index c989b63007..9572f8f2aa 100755 --- a/tools/mpy-tool.py +++ b/tools/mpy-tool.py @@ -59,9 +59,9 @@ MP_BC_MAKE_CLOSURE = 0x62 MP_BC_MAKE_CLOSURE_DEFARGS = 0x63 MP_BC_RAISE_VARARGS = 0x5C # extra byte if caching enabled: -MP_BC_LOAD_NAME = 0x1C -MP_BC_LOAD_GLOBAL = 0x1D -MP_BC_LOAD_ATTR = 0x1E +MP_BC_LOAD_NAME = 0x1B +MP_BC_LOAD_GLOBAL = 0x1C +MP_BC_LOAD_ATTR = 0x1D MP_BC_STORE_ATTR = 0x26 # load opcode names @@ -163,6 +163,14 @@ def mp_opcode_format(bytecode, ip, opcode_format=make_opcode_format()): ip_start = ip f = (opcode_format[opcode >> 2] >> (2 * (opcode & 3))) & 3 if f == MP_OPCODE_QSTR: + if config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE: + if ( + opcode == MP_BC_LOAD_NAME + or opcode == MP_BC_LOAD_GLOBAL + or opcode == MP_BC_LOAD_ATTR + or opcode == MP_BC_STORE_ATTR + ): + ip += 1 ip += 3 else: extra_byte = ( @@ -319,7 +327,8 @@ class RawCode: opcode = "0x%02x" % opcode if f == 1: qst = self._unpack_qstr(ip + 1).qstr_id - print(" {}, {} & 0xff, {} >> 8,".format(opcode, qst, qst)) + extra = "" if sz == 3 else " 0x%02x," % self.bytecode[ip + 3] + print(" {}, {} & 0xff, {} >> 8,{}".format(opcode, qst, qst, extra)) else: print( " {},{}".format( @@ -419,10 +428,10 @@ class RawCode: n = struct.unpack("