summaryrefslogtreecommitdiff
path: root/shared-module
diff options
context:
space:
mode:
authorBenjamin Shockley <benjaminshockley@hotmail.com>2020-08-20 13:48:15 -0500
committerGitHub <noreply@github.com>2020-08-20 13:48:15 -0500
commit0084f0af24e4e219bc040c52ee723959423de6e2 (patch)
tree1aebdb362f08bf6417caa87836e3e4e739afc964 /shared-module
parent9aebe2f1efc99871fcf283c304e3a8700050d736 (diff)
parent4d7b9cde33934a44c4c905a49d2f831339fc8bd2 (diff)
Merge pull request #2 from adafruit/master
Master
Diffstat (limited to 'shared-module')
-rw-r--r--shared-module/_bleio/Address.c45
-rw-r--r--shared-module/_bleio/Address.h (renamed from shared-module/bleio/Address.h)9
-rw-r--r--shared-module/_bleio/Attribute.c46
-rw-r--r--shared-module/_bleio/Attribute.h41
-rw-r--r--shared-module/_bleio/Characteristic.h (renamed from shared-module/bleio/Characteristic.h)35
-rw-r--r--shared-module/_bleio/ScanEntry.c86
-rw-r--r--shared-module/_bleio/ScanEntry.h (renamed from shared-module/bleio/ScanEntry.h)13
-rw-r--r--shared-module/_bleio/ScanResults.c139
-rw-r--r--shared-module/_bleio/ScanResults.h64
-rw-r--r--shared-module/_eve/__init__.c316
-rw-r--r--shared-module/_eve/__init__.h37
-rw-r--r--shared-module/_pew/PewPew.c125
-rw-r--r--shared-module/_pew/PewPew.h48
-rw-r--r--shared-module/_pew/__init__.c87
-rw-r--r--shared-module/_pew/__init__.h32
-rw-r--r--shared-module/_pixelbuf/PixelBuf.c290
-rw-r--r--shared-module/_pixelbuf/PixelBuf.h71
-rw-r--r--shared-module/_pixelbuf/__init__.c0
-rw-r--r--shared-module/_stage/__init__.c72
-rw-r--r--shared-module/_stage/__init__.h7
-rw-r--r--shared-module/aesio/__init__.c58
-rw-r--r--shared-module/aesio/__init__.h59
-rw-r--r--shared-module/aesio/aes.c608
-rw-r--r--shared-module/aesio/aes.h105
-rw-r--r--shared-module/audiocore/RawSample.c (renamed from shared-module/audioio/RawSample.c)10
-rw-r--r--shared-module/audiocore/RawSample.h (renamed from shared-module/audioio/RawSample.h)2
-rw-r--r--shared-module/audiocore/WaveFile.c (renamed from shared-module/audioio/WaveFile.c)39
-rw-r--r--shared-module/audiocore/WaveFile.h (renamed from shared-module/audioio/WaveFile.h)5
-rw-r--r--shared-module/audiocore/__init__.c72
-rw-r--r--shared-module/audiocore/__init__.h77
-rw-r--r--shared-module/audioio/Mixer.c341
-rw-r--r--shared-module/audioio/__init__.c125
-rw-r--r--shared-module/audioio/__init__.h23
-rw-r--r--shared-module/audiomixer/Mixer.c320
-rw-r--r--shared-module/audiomixer/Mixer.h (renamed from shared-module/audioio/Mixer.h)28
-rw-r--r--shared-module/audiomixer/MixerVoice.c87
-rw-r--r--shared-module/audiomixer/MixerVoice.h46
-rw-r--r--shared-module/audiomixer/__init__.c0
-rw-r--r--shared-module/audiomixer/__init__.h32
-rw-r--r--shared-module/audiomp3/MP3Decoder.c352
-rw-r--r--shared-module/audiomp3/MP3Decoder.h72
-rw-r--r--shared-module/audiomp3/__init__.c0
-rw-r--r--shared-module/audiomp3/__init__.h30
-rw-r--r--shared-module/audiopwmio/__init__.c0
-rw-r--r--shared-module/audiopwmio/__init__.h32
-rw-r--r--shared-module/bitbangio/SPI.c11
-rw-r--r--shared-module/bleio/AdvertisementData.h85
-rw-r--r--shared-module/board/__init__.c164
-rw-r--r--shared-module/board/__init__.h32
-rw-r--r--shared-module/displayio/Bitmap.c152
-rw-r--r--shared-module/displayio/Bitmap.h12
-rw-r--r--shared-module/displayio/ColorConverter.c178
-rw-r--r--shared-module/displayio/ColorConverter.h15
-rw-r--r--shared-module/displayio/Display.c433
-rw-r--r--shared-module/displayio/Display.h67
-rw-r--r--shared-module/displayio/EPaperDisplay.c387
-rw-r--r--shared-module/displayio/EPaperDisplay.h68
-rw-r--r--shared-module/displayio/FourWire.c135
-rw-r--r--shared-module/displayio/FourWire.h46
-rw-r--r--shared-module/displayio/Group.c394
-rw-r--r--shared-module/displayio/Group.h31
-rw-r--r--shared-module/displayio/I2CDisplay.c123
-rw-r--r--shared-module/displayio/I2CDisplay.h (renamed from shared-module/bleio/Service.h)25
-rw-r--r--shared-module/displayio/OnDiskBitmap.c135
-rw-r--r--shared-module/displayio/OnDiskBitmap.h7
-rw-r--r--shared-module/displayio/Palette.c71
-rw-r--r--shared-module/displayio/Palette.h45
-rw-r--r--shared-module/displayio/Shape.c90
-rw-r--r--shared-module/displayio/Shape.h46
-rw-r--r--shared-module/displayio/Sprite.c99
-rw-r--r--shared-module/displayio/TileGrid.c587
-rw-r--r--shared-module/displayio/TileGrid.h88
-rw-r--r--shared-module/displayio/__init__.c430
-rw-r--r--shared-module/displayio/__init__.h48
-rw-r--r--shared-module/displayio/area.h73
-rw-r--r--shared-module/displayio/display_core.c351
-rw-r--r--shared-module/displayio/display_core.h90
-rw-r--r--shared-module/fontio/BuiltinFont.c79
-rw-r--r--shared-module/fontio/BuiltinFont.h (renamed from shared-module/displayio/Sprite.h)25
-rw-r--r--shared-module/fontio/__init__.c27
-rw-r--r--shared-module/framebufferio/FramebufferDisplay.c312
-rw-r--r--shared-module/framebufferio/FramebufferDisplay.h92
-rw-r--r--shared-module/framebufferio/__init__.c0
-rw-r--r--shared-module/framebufferio/__init__.h0
-rw-r--r--shared-module/gamepad/GamePad.c33
-rw-r--r--shared-module/gamepad/GamePad.h2
-rw-r--r--shared-module/gamepad/__init__.c29
-rw-r--r--shared-module/gamepadshift/GamePadShift.c51
-rw-r--r--shared-module/gamepadshift/GamePadShift.h43
-rw-r--r--shared-module/gamepadshift/__init__.c57
-rw-r--r--shared-module/gamepadshift/__init__.h33
-rw-r--r--shared-module/network/__init__.c18
-rw-r--r--shared-module/network/__init__.h6
-rw-r--r--shared-module/os/__init__.c1
-rw-r--r--shared-module/rgbmatrix/RGBMatrix.c208
-rw-r--r--shared-module/rgbmatrix/RGBMatrix.h0
-rw-r--r--shared-module/rgbmatrix/__init__.c0
-rw-r--r--shared-module/rgbmatrix/__init__.h0
-rw-r--r--shared-module/rgbmatrix/allocator.h29
-rw-r--r--shared-module/storage/__init__.c9
-rw-r--r--shared-module/struct/__init__.c113
-rw-r--r--shared-module/terminalio/Terminal.c130
-rw-r--r--shared-module/terminalio/Terminal.h46
-rw-r--r--shared-module/terminalio/__init__.c27
-rw-r--r--shared-module/terminalio/__init__.h30
-rw-r--r--shared-module/time/__init__.c45
-rw-r--r--shared-module/touchio/TouchIn.c115
-rw-r--r--shared-module/touchio/TouchIn.h44
-rw-r--r--shared-module/touchio/__init__.c1
-rw-r--r--shared-module/usb_hid/Device.c37
-rw-r--r--shared-module/usb_hid/__init__.c129
-rw-r--r--shared-module/usb_midi/PortIn.c37
-rw-r--r--shared-module/usb_midi/PortIn.h (renamed from shared-module/bleio/Scanner.h)18
-rw-r--r--shared-module/usb_midi/PortOut.c37
-rw-r--r--shared-module/usb_midi/PortOut.h (renamed from shared-module/bleio/Device.h)22
-rw-r--r--shared-module/usb_midi/__init__.c63
-rw-r--r--shared-module/usb_midi/__init__.h32
-rw-r--r--shared-module/ustack/__init__.c1
-rw-r--r--shared-module/vectorio/Circle.c55
-rw-r--r--shared-module/vectorio/Circle.h16
-rw-r--r--shared-module/vectorio/Polygon.c146
-rw-r--r--shared-module/vectorio/Polygon.h17
-rw-r--r--shared-module/vectorio/Rectangle.c34
-rw-r--r--shared-module/vectorio/Rectangle.h14
-rw-r--r--shared-module/vectorio/VectorShape.c334
-rw-r--r--shared-module/vectorio/VectorShape.h53
-rw-r--r--shared-module/vectorio/__init__.c2
-rw-r--r--shared-module/vectorio/__init__.h14
-rw-r--r--shared-module/wiznet/wiznet5k.c86
-rw-r--r--shared-module/wiznet/wiznet5k.h9
130 files changed, 10070 insertions, 1295 deletions
diff --git a/shared-module/_bleio/Address.c b/shared-module/_bleio/Address.c
new file mode 100644
index 000000000..8c8b043fe
--- /dev/null
+++ b/shared-module/_bleio/Address.c
@@ -0,0 +1,45 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Dan Halbert for Adafruit Industries
+ * Copyright (c) 2018 Artur Pacholec
+ *
+ * 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 <string.h>
+
+#include "py/objstr.h"
+#include "shared-bindings/_bleio/Address.h"
+#include "shared-module/_bleio/Address.h"
+
+void common_hal_bleio_address_construct(bleio_address_obj_t *self, uint8_t *bytes, uint8_t address_type) {
+ self->bytes = mp_obj_new_bytes(bytes, NUM_BLEIO_ADDRESS_BYTES);
+ self->type = address_type;
+}
+
+mp_obj_t common_hal_bleio_address_get_address_bytes(bleio_address_obj_t *self) {
+ return self->bytes;
+}
+
+uint8_t common_hal_bleio_address_get_type(bleio_address_obj_t *self) {
+ return self->type;
+}
diff --git a/shared-module/bleio/Address.h b/shared-module/_bleio/Address.h
index f0998c163..39789842f 100644
--- a/shared-module/bleio/Address.h
+++ b/shared-module/_bleio/Address.h
@@ -3,6 +3,7 @@
*
* The MIT License (MIT)
*
+ * Copyright (c) 2019 Dan Halbert for Adafruit Industries
* Copyright (c) 2018 Artur Pacholec
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -27,14 +28,14 @@
#ifndef MICROPY_INCLUDED_SHARED_MODULE_BLEIO_ADDRESS_H
#define MICROPY_INCLUDED_SHARED_MODULE_BLEIO_ADDRESS_H
-#include "shared-bindings/bleio/AddressType.h"
+#include "py/obj.h"
-#define BLEIO_ADDRESS_BYTES 6
+#define NUM_BLEIO_ADDRESS_BYTES 6
typedef struct {
mp_obj_base_t base;
- bleio_address_type_t type;
- uint8_t value[BLEIO_ADDRESS_BYTES];
+ uint8_t type;
+ mp_obj_t bytes; // a bytes() object
} bleio_address_obj_t;
#endif // MICROPY_INCLUDED_SHARED_MODULE_BLEIO_ADDRESS_H
diff --git a/shared-module/_bleio/Attribute.c b/shared-module/_bleio/Attribute.c
new file mode 100644
index 000000000..3acfcf1f5
--- /dev/null
+++ b/shared-module/_bleio/Attribute.c
@@ -0,0 +1,46 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Dan Halbert 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 <string.h>
+
+#include "py/runtime.h"
+#include "shared-bindings/_bleio/Attribute.h"
+
+void common_hal_bleio_attribute_security_mode_check_valid(bleio_attribute_security_mode_t security_mode) {
+ switch (security_mode) {
+ case SECURITY_MODE_NO_ACCESS:
+ case SECURITY_MODE_OPEN:
+ case SECURITY_MODE_ENC_NO_MITM:
+ case SECURITY_MODE_ENC_WITH_MITM:
+ case SECURITY_MODE_LESC_ENC_WITH_MITM:
+ case SECURITY_MODE_SIGNED_NO_MITM:
+ case SECURITY_MODE_SIGNED_WITH_MITM:
+ break;
+ default:
+ mp_raise_ValueError(translate("Invalid security_mode"));
+ break;
+ }
+}
diff --git a/shared-module/_bleio/Attribute.h b/shared-module/_bleio/Attribute.h
new file mode 100644
index 000000000..a498a14a5
--- /dev/null
+++ b/shared-module/_bleio/Attribute.h
@@ -0,0 +1,41 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Dan Halbert 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_SHARED_MODULE_BLEIO_ATTRIBUTE_H
+#define MICROPY_INCLUDED_SHARED_MODULE_BLEIO_ATTRIBUTE_H
+
+// BLE security modes: 0x<level><mode>
+typedef enum {
+ SECURITY_MODE_NO_ACCESS = 0x00,
+ SECURITY_MODE_OPEN = 0x11,
+ SECURITY_MODE_ENC_NO_MITM = 0x21,
+ SECURITY_MODE_ENC_WITH_MITM = 0x31,
+ SECURITY_MODE_LESC_ENC_WITH_MITM = 0x41,
+ SECURITY_MODE_SIGNED_NO_MITM = 0x12,
+ SECURITY_MODE_SIGNED_WITH_MITM = 0x22,
+} bleio_attribute_security_mode_t;
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_BLEIO_ATTRIBUTE_H
diff --git a/shared-module/bleio/Characteristic.h b/shared-module/_bleio/Characteristic.h
index 94c43f81e..409a57c76 100644
--- a/shared-module/bleio/Characteristic.h
+++ b/shared-module/_bleio/Characteristic.h
@@ -3,7 +3,7 @@
*
* The MIT License (MIT)
*
- * Copyright (c) 2018 Artur Pacholec
+ * Copyright (c) 2019 Dan Halbert 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
@@ -27,26 +27,17 @@
#ifndef MICROPY_INCLUDED_SHARED_MODULE_BLEIO_CHARACTERISTIC_H
#define MICROPY_INCLUDED_SHARED_MODULE_BLEIO_CHARACTERISTIC_H
-#include "shared-module/bleio/Service.h"
-#include "common-hal/bleio/UUID.h"
-
-typedef struct {
- mp_obj_base_t base;
- bleio_service_obj_t *service;
- bleio_uuid_obj_t *uuid;
- mp_obj_t value_data;
- uint16_t handle;
- struct {
- bool broadcast : 1;
- bool read : 1;
- bool write_wo_resp : 1;
- bool write : 1;
- bool notify : 1;
- bool indicate : 1;
- } props;
- uint16_t user_desc_handle;
- uint16_t cccd_handle;
- uint16_t sccd_handle;
-} bleio_characteristic_obj_t;
+typedef enum {
+ CHAR_PROP_NONE = 0,
+ CHAR_PROP_BROADCAST = 1u << 0,
+ CHAR_PROP_INDICATE = 1u << 1,
+ CHAR_PROP_NOTIFY = 1u << 2,
+ CHAR_PROP_READ = 1u << 3,
+ CHAR_PROP_WRITE = 1u << 4,
+ CHAR_PROP_WRITE_NO_RESPONSE = 1u << 5,
+ CHAR_PROP_ALL = (CHAR_PROP_BROADCAST | CHAR_PROP_INDICATE | CHAR_PROP_NOTIFY |
+ CHAR_PROP_READ | CHAR_PROP_WRITE | CHAR_PROP_WRITE_NO_RESPONSE)
+} bleio_characteristic_properties_enum_t;
+typedef uint8_t bleio_characteristic_properties_t;
#endif // MICROPY_INCLUDED_SHARED_MODULE_BLEIO_CHARACTERISTIC_H
diff --git a/shared-module/_bleio/ScanEntry.c b/shared-module/_bleio/ScanEntry.c
new file mode 100644
index 000000000..785209c4a
--- /dev/null
+++ b/shared-module/_bleio/ScanEntry.c
@@ -0,0 +1,86 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Dan Halbert for Adafruit Industries
+ * Copyright (c) 2018 Artur Pacholec
+ * Copyright (c) 2017 Glenn Ruben Bakke
+ *
+ * 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 <string.h>
+
+#include "shared-bindings/_bleio/Address.h"
+#include "shared-module/_bleio/Address.h"
+#include "shared-module/_bleio/ScanEntry.h"
+
+mp_obj_t common_hal_bleio_scanentry_get_address(bleio_scanentry_obj_t *self) {
+ return MP_OBJ_FROM_PTR(self->address);
+}
+
+mp_obj_t common_hal_bleio_scanentry_get_advertisement_bytes(bleio_scanentry_obj_t *self) {
+ return MP_OBJ_FROM_PTR(self->data);
+}
+
+mp_int_t common_hal_bleio_scanentry_get_rssi(bleio_scanentry_obj_t *self) {
+ return self->rssi;
+}
+
+bool common_hal_bleio_scanentry_get_connectable(bleio_scanentry_obj_t *self) {
+ return self->connectable;
+}
+
+bool common_hal_bleio_scanentry_get_scan_response(bleio_scanentry_obj_t *self) {
+ return self->scan_response;
+}
+
+bool bleio_scanentry_data_matches(const uint8_t* data, size_t len, const uint8_t* prefixes, size_t prefixes_length, bool any) {
+ if (prefixes_length == 0) {
+ return true;
+ }
+ size_t i = 0;
+ while(i < prefixes_length) {
+ uint8_t prefix_length = prefixes[i];
+ i += 1;
+ size_t j = 0;
+ while (j < len) {
+ uint8_t structure_length = data[j];
+ j += 1;
+ if (structure_length == 0) {
+ break;
+ }
+ if (structure_length >= prefix_length && memcmp(data + j, prefixes + i, prefix_length) == 0) {
+ if (any) {
+ return true;
+ }
+ } else if (!any) {
+ return false;
+ }
+ j += structure_length;
+ }
+ i += prefix_length;
+ }
+ return !any;
+}
+
+bool common_hal_bleio_scanentry_matches(bleio_scanentry_obj_t *self, const uint8_t* prefixes, size_t prefixes_len, bool all) {
+ return bleio_scanentry_data_matches(self->data->data, self->data->len, prefixes, prefixes_len, !all);
+}
diff --git a/shared-module/bleio/ScanEntry.h b/shared-module/_bleio/ScanEntry.h
index 2f01669e2..94361a397 100644
--- a/shared-module/bleio/ScanEntry.h
+++ b/shared-module/_bleio/ScanEntry.h
@@ -3,6 +3,7 @@
*
* The MIT License (MIT)
*
+ * Copyright (c) 2019 Dan Halbert for Adafruit Industries
* Copyright (c) 2018 Artur Pacholec
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -27,14 +28,20 @@
#ifndef MICROPY_INCLUDED_SHARED_MODULE_BLEIO_SCANENTRY_H
#define MICROPY_INCLUDED_SHARED_MODULE_BLEIO_SCANENTRY_H
-#include "shared-module/bleio/Address.h"
+#include "py/obj.h"
+#include "py/objstr.h"
+#include "shared-bindings/_bleio/Address.h"
typedef struct {
mp_obj_base_t base;
- bleio_address_obj_t address;
bool connectable;
+ bool scan_response;
int8_t rssi;
- mp_obj_t data;
+ bleio_address_obj_t *address;
+ mp_obj_str_t *data;
+ uint64_t time_received;
} bleio_scanentry_obj_t;
+bool bleio_scanentry_data_matches(const uint8_t* data, size_t len, const uint8_t* prefixes, size_t prefix_length, bool any);
+
#endif // MICROPY_INCLUDED_SHARED_MODULE_BLEIO_SCANENTRY_H
diff --git a/shared-module/_bleio/ScanResults.c b/shared-module/_bleio/ScanResults.c
new file mode 100644
index 000000000..cb48d636d
--- /dev/null
+++ b/shared-module/_bleio/ScanResults.c
@@ -0,0 +1,139 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Dan Halbert for Adafruit Industries
+ * Copyright (c) 2018 Artur Pacholec
+ * Copyright (c) 2017 Glenn Ruben Bakke
+ *
+ * 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 <string.h>
+
+#include "lib/utils/interrupt_char.h"
+#include "py/objstr.h"
+#include "py/runtime.h"
+#include "shared-bindings/_bleio/ScanEntry.h"
+#include "shared-bindings/_bleio/ScanResults.h"
+
+bleio_scanresults_obj_t* shared_module_bleio_new_scanresults(size_t buffer_size, uint8_t* prefixes, size_t prefixes_len, mp_int_t minimum_rssi) {
+ bleio_scanresults_obj_t* self = m_new_obj(bleio_scanresults_obj_t);
+ self->base.type = &bleio_scanresults_type;
+ ringbuf_alloc(&self->buf, buffer_size, false);
+ self->prefixes = prefixes;
+ self->prefix_length = prefixes_len;
+ self->minimum_rssi = minimum_rssi;
+ return self;
+}
+
+mp_obj_t common_hal_bleio_scanresults_next(bleio_scanresults_obj_t *self) {
+ while (ringbuf_num_filled(&self->buf) == 0 && !self->done && !mp_hal_is_interrupted()) {
+ RUN_BACKGROUND_TASKS;
+ }
+ if (ringbuf_num_filled(&self->buf) == 0 || mp_hal_is_interrupted()) {
+ return mp_const_none;
+ }
+
+ // Create a ScanEntry out of the data on the buffer.
+ uint8_t type = ringbuf_get(&self->buf);
+ bool connectable = (type & (1 << 0)) != 0;
+ bool scan_response = (type & (1 << 1)) != 0;
+ uint64_t ticks_ms;
+ ringbuf_get_n(&self->buf, (uint8_t*) &ticks_ms, sizeof(ticks_ms));
+ uint8_t rssi = ringbuf_get(&self->buf);
+ uint8_t peer_addr[NUM_BLEIO_ADDRESS_BYTES];
+ ringbuf_get_n(&self->buf, peer_addr, sizeof(peer_addr));
+ uint8_t addr_type = ringbuf_get(&self->buf);
+ uint16_t len;
+ ringbuf_get_n(&self->buf, (uint8_t*) &len, sizeof(len));
+
+ mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_bytes_of_zeros(len));
+ ringbuf_get_n(&self->buf, (uint8_t*) o->data, len);
+
+ bleio_scanentry_obj_t *entry = m_new_obj(bleio_scanentry_obj_t);
+ entry->base.type = &bleio_scanentry_type;
+ entry->rssi = rssi;
+
+ bleio_address_obj_t *address = m_new_obj(bleio_address_obj_t);
+ address->base.type = &bleio_address_type;
+ common_hal_bleio_address_construct(MP_OBJ_TO_PTR(address), peer_addr, addr_type);
+ entry->address = address;
+
+ entry->data = o;
+ entry->time_received = ticks_ms;
+ entry->connectable = connectable;
+ entry->scan_response = scan_response;
+
+ return MP_OBJ_FROM_PTR(entry);
+}
+
+
+void shared_module_bleio_scanresults_append(bleio_scanresults_obj_t* self,
+ uint64_t ticks_ms,
+ bool connectable,
+ bool scan_response,
+ int8_t rssi,
+ uint8_t *peer_addr,
+ uint8_t addr_type,
+ uint8_t *data,
+ uint16_t len) {
+ int32_t packet_size = sizeof(uint8_t) + sizeof(ticks_ms) + sizeof(rssi) + NUM_BLEIO_ADDRESS_BYTES +
+ sizeof(addr_type) + sizeof(len) + len;
+ int32_t empty_space = self->buf.size - ringbuf_num_filled(&self->buf);
+ if (packet_size >= empty_space) {
+ // We can't fit the packet so skip it.
+ return;
+ }
+ // Filter the packet.
+ if (rssi < self->minimum_rssi) {
+ return;
+ }
+
+ // If any prefixes are provided, then only include packets that include at least one of them.
+ if (!bleio_scanentry_data_matches(data, len, self->prefixes, self->prefix_length, true)) {
+ return;
+ }
+ uint8_t type = 0;
+ if (connectable) {
+ type |= 1 << 0;
+ }
+ if (scan_response) {
+ type |= 1 << 1;
+ }
+
+ // Add the packet to the buffer.
+ ringbuf_put(&self->buf, type);
+ ringbuf_put_n(&self->buf, (uint8_t*) &ticks_ms, sizeof(ticks_ms));
+ ringbuf_put(&self->buf, rssi);
+ ringbuf_put_n(&self->buf, peer_addr, NUM_BLEIO_ADDRESS_BYTES);
+ ringbuf_put(&self->buf, addr_type);
+ ringbuf_put_n(&self->buf, (uint8_t*) &len, sizeof(len));
+ ringbuf_put_n(&self->buf, data, len);
+}
+
+bool shared_module_bleio_scanresults_get_done(bleio_scanresults_obj_t* self) {
+ return self->done;
+}
+
+void shared_module_bleio_scanresults_set_done(bleio_scanresults_obj_t* self, bool done) {
+ self->done = done;
+ self->common_hal_data = NULL;
+}
diff --git a/shared-module/_bleio/ScanResults.h b/shared-module/_bleio/ScanResults.h
new file mode 100644
index 000000000..8912357a9
--- /dev/null
+++ b/shared-module/_bleio/ScanResults.h
@@ -0,0 +1,64 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Dan Halbert for Adafruit Industries
+ * Copyright (c) 2018 Artur Pacholec
+ *
+ * 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_BLEIO_SCANRESULTS_H
+#define MICROPY_INCLUDED_SHARED_MODULE_BLEIO_SCANRESULTS_H
+
+#include <stdint.h>
+
+#include "py/obj.h"
+#include "py/ringbuf.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ // Pointers that needs to live until the scan is done.
+ void* common_hal_data;
+ ringbuf_t buf;
+ // Prefixes is a length encoded array of prefixes.
+ uint8_t* prefixes;
+ size_t prefix_length;
+ mp_int_t minimum_rssi;
+ bool active;
+ bool done;
+} bleio_scanresults_obj_t;
+
+bleio_scanresults_obj_t* shared_module_bleio_new_scanresults(size_t buffer_size, uint8_t* prefixes, size_t prefixes_len, mp_int_t minimum_rssi);
+
+bool shared_module_bleio_scanresults_get_done(bleio_scanresults_obj_t* self);
+void shared_module_bleio_scanresults_set_done(bleio_scanresults_obj_t* self, bool done);
+
+void shared_module_bleio_scanresults_append(bleio_scanresults_obj_t* self,
+ uint64_t ticks_ms,
+ bool connectable,
+ bool scan_result,
+ int8_t rssi,
+ uint8_t *peer_addr,
+ uint8_t addr_type,
+ uint8_t* data,
+ uint16_t len);
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_BLEIO_SCANRESULTS_H
diff --git a/shared-module/_eve/__init__.c b/shared-module/_eve/__init__.c
new file mode 100644
index 000000000..0f1e12d9f
--- /dev/null
+++ b/shared-module/_eve/__init__.c
@@ -0,0 +1,316 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2020 James Bowman for Excamera Labs
+ *
+ * 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 <stddef.h>
+#include <stdint.h>
+#include "py/runtime.h"
+#include "shared-module/_eve/__init__.h"
+
+STATIC void write(common_hal__eve_t *eve, size_t len, void *buf) {
+ eve->dest[2] = mp_obj_new_bytearray_by_ref(len, buf);
+ mp_call_method_n_kw(1, 0, eve->dest);
+}
+
+void common_hal__eve_flush(common_hal__eve_t *eve) {
+ if (eve->n != 0) {
+ write(eve, eve->n, eve->buf);
+ eve->n = 0;
+ }
+}
+
+static void *append(common_hal__eve_t *eve, size_t m) {
+ if ((eve->n + m) > sizeof(eve->buf))
+ common_hal__eve_flush(eve);
+ uint8_t *r = eve->buf + eve->n;
+ eve->n += m;
+ return (void*)r;
+}
+
+void common_hal__eve_add(common_hal__eve_t *eve, size_t len, void *buf) {
+ if (len <= sizeof(eve->buf)) {
+ uint8_t *p = (uint8_t*)append(eve, len);
+ // memcpy(p, buffer_info.buf, buffer_info.len);
+ uint8_t *s = buf; for (size_t i = 0; i < len; i++) *p++ = *s++;
+ } else {
+ common_hal__eve_flush(eve);
+ write(eve, len, buf);
+ }
+}
+
+#define C4(eve, u) (*(uint32_t*)append((eve), sizeof(uint32_t)) = (u))
+
+void common_hal__eve_Vertex2f(common_hal__eve_t *eve, mp_float_t x, mp_float_t y) {
+ int16_t ix = (int)(eve->vscale * x);
+ int16_t iy = (int)(eve->vscale * y);
+ C4(eve, (1 << 30) | ((ix & 32767) << 15) | (iy & 32767));
+}
+
+void common_hal__eve_VertexFormat(common_hal__eve_t *eve, uint32_t frac)
+{
+ C4(eve, ((27 << 24) | ((frac & 7))));
+ eve->vscale = 1 << eve->vscale;
+}
+
+
+
+void common_hal__eve_AlphaFunc(common_hal__eve_t *eve, uint32_t func, uint32_t ref) {
+ C4(eve, ((9 << 24) | ((func & 7) << 8) | ((ref & 255))));
+}
+
+
+void common_hal__eve_Begin(common_hal__eve_t *eve, uint32_t prim) {
+ C4(eve, ((31 << 24) | ((prim & 15))));
+}
+
+
+void common_hal__eve_BitmapExtFormat(common_hal__eve_t *eve, uint32_t fmt) {
+ C4(eve, ((46 << 24) | (fmt & 65535)));
+}
+
+
+void common_hal__eve_BitmapHandle(common_hal__eve_t *eve, uint32_t handle) {
+ C4(eve, ((5 << 24) | ((handle & 31))));
+}
+
+
+void common_hal__eve_BitmapLayoutH(common_hal__eve_t *eve, uint32_t linestride, uint32_t height) {
+ C4(eve, ((40 << 24) | (((linestride) & 3) << 2) | (((height) & 3))));
+}
+
+
+void common_hal__eve_BitmapLayout(common_hal__eve_t *eve, uint32_t format, uint32_t linestride, uint32_t height) {
+ C4(eve, ((7 << 24) | ((format & 31) << 19) | ((linestride & 1023) << 9) | ((height & 511))));
+}
+
+
+void common_hal__eve_BitmapSizeH(common_hal__eve_t *eve, uint32_t width, uint32_t height) {
+ C4(eve, ((41 << 24) | (((width) & 3) << 2) | (((height) & 3))));
+}
+
+
+void common_hal__eve_BitmapSize(common_hal__eve_t *eve, uint32_t filter, uint32_t wrapx, uint32_t wrapy, uint32_t width, uint32_t height) {
+ C4(eve, ((8 << 24) | ((filter & 1) << 20) | ((wrapx & 1) << 19) | ((wrapy & 1) << 18) | ((width & 511) << 9) | ((height & 511))));
+}
+
+
+void common_hal__eve_BitmapSource(common_hal__eve_t *eve, uint32_t addr) {
+ C4(eve, ((1 << 24) | ((addr & 0xffffff))));
+}
+
+
+void common_hal__eve_BitmapSwizzle(common_hal__eve_t *eve, uint32_t r, uint32_t g, uint32_t b, uint32_t a) {
+ C4(eve, ((47 << 24) | ((r & 7) << 9) | ((g & 7) << 6) | ((b & 7) << 3) | ((a & 7))));
+}
+
+
+void common_hal__eve_BitmapTransformA(common_hal__eve_t *eve, uint32_t p, uint32_t v) {
+ C4(eve, ((21 << 24) | ((p & 1) << 17) | ((v & 131071))));
+}
+
+
+void common_hal__eve_BitmapTransformB(common_hal__eve_t *eve, uint32_t p, uint32_t v) {
+ C4(eve, ((22 << 24) | ((p & 1) << 17) | ((v & 131071))));
+}
+
+
+void common_hal__eve_BitmapTransformC(common_hal__eve_t *eve, uint32_t v) {
+ C4(eve, ((23 << 24) | ((v & 16777215))));
+}
+
+
+void common_hal__eve_BitmapTransformD(common_hal__eve_t *eve, uint32_t p, uint32_t v) {
+ C4(eve, ((24 << 24) | ((p & 1) << 17) | ((v & 131071))));
+}
+
+
+void common_hal__eve_BitmapTransformE(common_hal__eve_t *eve, uint32_t p, uint32_t v) {
+ C4(eve, ((25 << 24) | ((p & 1) << 17) | ((v & 131071))));
+}
+
+
+void common_hal__eve_BitmapTransformF(common_hal__eve_t *eve, uint32_t v) {
+ C4(eve, ((26 << 24) | ((v & 16777215))));
+}
+
+
+void common_hal__eve_BlendFunc(common_hal__eve_t *eve, uint32_t src, uint32_t dst) {
+ C4(eve, ((11 << 24) | ((src & 7) << 3) | ((dst & 7))));
+}
+
+
+void common_hal__eve_Call(common_hal__eve_t *eve, uint32_t dest) {
+ C4(eve, ((29 << 24) | ((dest & 65535))));
+}
+
+
+void common_hal__eve_Cell(common_hal__eve_t *eve, uint32_t cell) {
+ C4(eve, ((6 << 24) | ((cell & 127))));
+}
+
+
+void common_hal__eve_ClearColorA(common_hal__eve_t *eve, uint32_t alpha) {
+ C4(eve, ((15 << 24) | ((alpha & 255))));
+}
+
+
+void common_hal__eve_ClearColorRGB(common_hal__eve_t *eve, uint32_t red, uint32_t green, uint32_t blue) {
+ C4(eve, ((2 << 24) | ((red & 255) << 16) | ((green & 255) << 8) | ((blue & 255))));
+}
+
+
+void common_hal__eve_Clear(common_hal__eve_t *eve, uint32_t c, uint32_t s, uint32_t t) {
+ C4(eve, ((38 << 24) | ((c & 1) << 2) | ((s & 1) << 1) | ((t & 1))));
+}
+
+
+void common_hal__eve_ClearStencil(common_hal__eve_t *eve, uint32_t s) {
+ C4(eve, ((17 << 24) | ((s & 255))));
+}
+
+
+void common_hal__eve_ClearTag(common_hal__eve_t *eve, uint32_t s) {
+ C4(eve, ((18 << 24) | ((s & 255))));
+}
+
+
+void common_hal__eve_ColorA(common_hal__eve_t *eve, uint32_t alpha) {
+ C4(eve, ((16 << 24) | ((alpha & 255))));
+}
+
+
+void common_hal__eve_ColorMask(common_hal__eve_t *eve, uint32_t r, uint32_t g, uint32_t b, uint32_t a) {
+ C4(eve, ((32 << 24) | ((r & 1) << 3) | ((g & 1) << 2) | ((b & 1) << 1) | ((a & 1))));
+}
+
+
+void common_hal__eve_ColorRGB(common_hal__eve_t *eve, uint32_t red, uint32_t green, uint32_t blue) {
+ C4(eve, ((4 << 24) | ((red & 255) << 16) | ((green & 255) << 8) | ((blue & 255))));
+}
+
+
+void common_hal__eve_Display(common_hal__eve_t *eve) {
+ C4(eve, ((0 << 24)));
+}
+
+
+void common_hal__eve_End(common_hal__eve_t *eve) {
+ C4(eve, ((33 << 24)));
+}
+
+
+void common_hal__eve_Jump(common_hal__eve_t *eve, uint32_t dest) {
+ C4(eve, ((30 << 24) | ((dest & 65535))));
+}
+
+
+void common_hal__eve_LineWidth(common_hal__eve_t *eve, uint32_t width) {
+ C4(eve, ((14 << 24) | ((width & 4095))));
+}
+
+
+void common_hal__eve_Macro(common_hal__eve_t *eve, uint32_t m) {
+ C4(eve, ((37 << 24) | ((m & 1))));
+}
+
+
+void common_hal__eve_Nop(common_hal__eve_t *eve) {
+ C4(eve, ((45 << 24)));
+}
+
+
+void common_hal__eve_PaletteSource(common_hal__eve_t *eve, uint32_t addr) {
+ C4(eve, ((42 << 24) | (((addr) & 4194303))));
+}
+
+
+void common_hal__eve_PointSize(common_hal__eve_t *eve, uint32_t size) {
+ C4(eve, ((13 << 24) | ((size & 8191))));
+}
+
+
+void common_hal__eve_RestoreContext(common_hal__eve_t *eve) {
+ C4(eve, ((35 << 24)));
+}
+
+
+void common_hal__eve_Return(common_hal__eve_t *eve) {
+ C4(eve, ((36 << 24)));
+}
+
+
+void common_hal__eve_SaveContext(common_hal__eve_t *eve) {
+ C4(eve, ((34 << 24)));
+}
+
+
+void common_hal__eve_ScissorSize(common_hal__eve_t *eve, uint32_t width, uint32_t height) {
+ C4(eve, ((28 << 24) | ((width & 4095) << 12) | ((height & 4095))));
+}
+
+
+void common_hal__eve_ScissorXY(common_hal__eve_t *eve, uint32_t x, uint32_t y) {
+ C4(eve, ((27 << 24) | ((x & 2047) << 11) | ((y & 2047))));
+}
+
+
+void common_hal__eve_StencilFunc(common_hal__eve_t *eve, uint32_t func, uint32_t ref, uint32_t mask) {
+ C4(eve, ((10 << 24) | ((func & 7) << 16) | ((ref & 255) << 8) | ((mask & 255))));
+}
+
+
+void common_hal__eve_StencilMask(common_hal__eve_t *eve, uint32_t mask) {
+ C4(eve, ((19 << 24) | ((mask & 255))));
+}
+
+
+void common_hal__eve_StencilOp(common_hal__eve_t *eve, uint32_t sfail, uint32_t spass) {
+ C4(eve, ((12 << 24) | ((sfail & 7) << 3) | ((spass & 7))));
+}
+
+
+void common_hal__eve_TagMask(common_hal__eve_t *eve, uint32_t mask) {
+ C4(eve, ((20 << 24) | ((mask & 1))));
+}
+
+
+void common_hal__eve_Tag(common_hal__eve_t *eve, uint32_t s) {
+ C4(eve, ((3 << 24) | ((s & 255))));
+}
+
+
+void common_hal__eve_VertexTranslateX(common_hal__eve_t *eve, uint32_t x) {
+ C4(eve, ((43 << 24) | (((x) & 131071))));
+}
+
+
+void common_hal__eve_VertexTranslateY(common_hal__eve_t *eve, uint32_t y) {
+ C4(eve, ((44 << 24) | (((y) & 131071))));
+}
+
+
+void common_hal__eve_Vertex2ii(common_hal__eve_t *eve, uint32_t x, uint32_t y, uint32_t handle, uint32_t cell) {
+ C4(eve, ((2 << 30) | (((x) & 511) << 21) | (((y) & 511) << 12) | (((handle) & 31) << 7) | (((cell) & 127) << 0)));
+}
diff --git a/shared-module/_eve/__init__.h b/shared-module/_eve/__init__.h
new file mode 100644
index 000000000..5217d860a
--- /dev/null
+++ b/shared-module/_eve/__init__.h
@@ -0,0 +1,37 @@
+/*
+ * This file is part of the Micro Python project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2020 James Bowman for Excamera Labs
+ *
+ * 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__EVE___INIT___H
+#define MICROPY_INCLUDED_SHARED_MODULE__EVE___INIT___H
+
+typedef struct _common_hal__eve_t {
+ mp_obj_t dest[3]; // Own 'write' method, plus argument
+ int vscale; // fixed-point scaling used for Vertex2f
+ size_t n; // Current size of command buffer
+ uint8_t buf[512]; // Command buffer
+} common_hal__eve_t;
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE__EVE___INIT___H
diff --git a/shared-module/_pew/PewPew.c b/shared-module/_pew/PewPew.c
new file mode 100644
index 000000000..568dc6425
--- /dev/null
+++ b/shared-module/_pew/PewPew.c
@@ -0,0 +1,125 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Radomir Dopieralski
+ *
+ * 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 <stdbool.h>
+
+#include "py/mpstate.h"
+#include "py/runtime.h"
+#include "__init__.h"
+#include "PewPew.h"
+
+#include "shared-bindings/digitalio/Pull.h"
+#include "shared-bindings/digitalio/DigitalInOut.h"
+#include "shared-bindings/util.h"
+#include "samd/timers.h"
+#include "supervisor/shared/translate.h"
+#include "timer_handler.h"
+
+
+static uint8_t pewpew_tc_index = 0xff;
+
+
+void pewpew_interrupt_handler(uint8_t index) {
+ if (index != pewpew_tc_index) {
+ return;
+ }
+ Tc* tc = tc_insts[index];
+ if (!tc->COUNT16.INTFLAG.bit.MC0) {
+ return;
+ }
+
+ pew_tick();
+
+ // Clear the interrupt bit.
+ tc->COUNT16.INTFLAG.reg = TC_INTFLAG_MC0;
+}
+
+void pew_init() {
+ pew_obj_t* pew = MP_STATE_VM(pew_singleton);
+
+ common_hal_digitalio_digitalinout_switch_to_input(pew->buttons, PULL_UP);
+
+ for (size_t i = 0; i < pew->rows_size; ++i) {
+ digitalio_digitalinout_obj_t *pin = MP_OBJ_TO_PTR(pew->rows[i]);
+ common_hal_digitalio_digitalinout_switch_to_output(pin, false,
+ DRIVE_MODE_PUSH_PULL);
+ }
+ for (size_t i = 0; i < pew->cols_size; ++i) {
+ digitalio_digitalinout_obj_t *pin = MP_OBJ_TO_PTR(pew->cols[i]);
+ common_hal_digitalio_digitalinout_switch_to_output(pin, true,
+ DRIVE_MODE_OPEN_DRAIN);
+ }
+ if (pewpew_tc_index == 0xff) {
+ // Find a spare timer.
+ uint8_t index = find_free_timer();
+ if (index == 0xff) {
+ mp_raise_RuntimeError(translate("All timers in use"));
+ }
+ Tc *tc = tc_insts[index];
+
+ pewpew_tc_index = index;
+ set_timer_handler(true, index, TC_HANDLER_PEW);
+
+ // We use GCLK0 for SAMD21 and GCLK1 for SAMD51 because they both run
+ // at 48mhz making our math the same across the boards.
+ #ifdef SAMD21
+ turn_on_clocks(true, index, 0);
+ #endif
+ #ifdef SAMD51
+ turn_on_clocks(true, index, 1);
+ #endif
+
+
+ #ifdef SAMD21
+ tc->COUNT16.CTRLA.reg = TC_CTRLA_MODE_COUNT16 |
+ TC_CTRLA_PRESCALER_DIV64 |
+ TC_CTRLA_WAVEGEN_MFRQ;
+ #endif
+ #ifdef SAMD51
+ tc_reset(tc);
+ tc_set_enable(tc, false);
+ tc->COUNT16.CTRLA.reg = TC_CTRLA_MODE_COUNT16
+ | TC_CTRLA_PRESCALER_DIV64;
+ tc->COUNT16.WAVE.reg = TC_WAVE_WAVEGEN_MFRQ;
+ #endif
+
+ tc_set_enable(tc, true);
+ tc->COUNT16.CC[0].reg = 64;
+
+ // Clear our interrupt in case it was set earlier
+ tc->COUNT16.INTFLAG.reg = TC_INTFLAG_MC0;
+ tc->COUNT16.INTENSET.reg = TC_INTENSET_MC0;
+ tc_enable_interrupts(pewpew_tc_index);
+ }
+}
+
+void pew_reset(void) {
+ if (pewpew_tc_index != 0xff) {
+ tc_reset(tc_insts[pewpew_tc_index]);
+ pewpew_tc_index = 0xff;
+ }
+ MP_STATE_VM(pew_singleton) = NULL;
+}
diff --git a/shared-module/_pew/PewPew.h b/shared-module/_pew/PewPew.h
new file mode 100644
index 000000000..da1cae0a2
--- /dev/null
+++ b/shared-module/_pew/PewPew.h
@@ -0,0 +1,48 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Radomir Dopieralski
+ *
+ * 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_PEW_PEWPEW_H
+#define MICROPY_INCLUDED_PEW_PEWPEW_H
+
+#include <stdint.h>
+#include "shared-bindings/digitalio/DigitalInOut.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ uint8_t* buffer;
+ mp_obj_t* rows;
+ mp_obj_t* cols;
+ digitalio_digitalinout_obj_t *buttons;
+ uint8_t rows_size;
+ uint8_t cols_size;
+ uint8_t pressed;
+} pew_obj_t;
+
+void pew_init(void);
+void pewpew_interrupt_handler(uint8_t index);
+void pew_reset(void);
+
+#endif // MICROPY_INCLUDED_PEW_PEWPEW_H
diff --git a/shared-module/_pew/__init__.c b/shared-module/_pew/__init__.c
new file mode 100644
index 000000000..f3b23c606
--- /dev/null
+++ b/shared-module/_pew/__init__.c
@@ -0,0 +1,87 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Radomir Dopieralski
+ *
+ * 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 <stdbool.h>
+
+#include "py/mpstate.h"
+#include "__init__.h"
+#include "PewPew.h"
+
+#include "shared-bindings/digitalio/DigitalInOut.h"
+
+
+void pew_tick(void) {
+ static uint8_t col = 0;
+ static uint8_t turn = 0;
+ static uint8_t pressed = 0;
+ static uint8_t last_pressed = 0;
+ digitalio_digitalinout_obj_t *pin;
+
+ pew_obj_t* pew = MP_STATE_VM(pew_singleton);
+ if (!pew) { return; }
+
+ pin = MP_OBJ_TO_PTR(pew->cols[col]);
+ ++col;
+ if (col >= pew->cols_size) {
+ pew->pressed |= last_pressed & pressed;
+ last_pressed = pressed;
+ pressed = 0;
+ col = 0;
+ ++turn;
+ if (turn > 11) {
+ turn = 0;
+ }
+ }
+ if (!common_hal_digitalio_digitalinout_get_value(pew->buttons)) {
+ pressed |= 1 << col;
+ }
+ common_hal_digitalio_digitalinout_set_value(pin, true);
+ for (size_t x = 0; x < pew->rows_size; ++x) {
+ pin = MP_OBJ_TO_PTR(pew->rows[x]);
+ uint8_t color = pew->buffer[col * (pew->rows_size) + x];
+ bool value = false;
+ switch (color & 0x03) {
+ case 3:
+ value = true;
+ break;
+ case 2:
+ if (turn == 2 || turn == 5 || turn == 8 || turn == 11) {
+ value = true;
+ }
+ break;
+ case 1:
+ if (turn == 0) {
+ value = true;
+ }
+ break;
+ case 0:
+ break;
+ }
+ common_hal_digitalio_digitalinout_set_value(pin, value);
+ }
+ pin = MP_OBJ_TO_PTR(pew->cols[col]);
+ common_hal_digitalio_digitalinout_set_value(pin, false);
+}
diff --git a/shared-module/_pew/__init__.h b/shared-module/_pew/__init__.h
new file mode 100644
index 000000000..4f953c610
--- /dev/null
+++ b/shared-module/_pew/__init__.h
@@ -0,0 +1,32 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Radomir Dopieralski
+ *
+ * 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_PEW_H
+#define MICROPY_INCLUDED_PEW_H
+
+void pew_tick(void);
+
+#endif // MICROPY_INCLUDED_PEW_H
diff --git a/shared-module/_pixelbuf/PixelBuf.c b/shared-module/_pixelbuf/PixelBuf.c
new file mode 100644
index 000000000..9d671e454
--- /dev/null
+++ b/shared-module/_pixelbuf/PixelBuf.c
@@ -0,0 +1,290 @@
+/*
+ * This file is part of the Circuit Python project, https://github.com/adafruit/circuitpython
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Roy Hooper
+ *
+ * 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/objstr.h"
+#include "py/objtype.h"
+#include "py/runtime.h"
+#include "shared-bindings/_pixelbuf/PixelBuf.h"
+#include <string.h>
+
+// Helper to ensure we have the native super class instead of a subclass.
+static pixelbuf_pixelbuf_obj_t* native_pixelbuf(mp_obj_t pixelbuf_obj) {
+ mp_obj_t native_pixelbuf = mp_instance_cast_to_native_base(pixelbuf_obj, &pixelbuf_pixelbuf_type);
+ mp_obj_assert_native_inited(native_pixelbuf);
+ return MP_OBJ_TO_PTR(native_pixelbuf);
+}
+
+void common_hal__pixelbuf_pixelbuf_construct(pixelbuf_pixelbuf_obj_t *self, size_t n,
+ pixelbuf_byteorder_details_t* byteorder, mp_float_t brightness, bool auto_write,
+ uint8_t* header, size_t header_len, uint8_t* trailer, size_t trailer_len) {
+
+ self->pixel_count = n;
+ self->byteorder = *byteorder; // Copied because we modify for dotstar
+ self->bytes_per_pixel = byteorder->is_dotstar ? 4 : byteorder->bpp;
+ self->auto_write = false;
+
+ size_t pixel_len = self->pixel_count * self->bytes_per_pixel;
+ self->transmit_buffer_obj = mp_obj_new_bytes_of_zeros(header_len + pixel_len + trailer_len);
+ mp_obj_str_t *o = MP_OBJ_TO_PTR(self->transmit_buffer_obj);
+
+ // Abuse the bytes object a bit by mutating it's data by dropping the const. If the user's
+ // Python code holds onto it, they'll find out that it changes. At least this way it isn't
+ // mutable by the code itself.
+ uint8_t* transmit_buffer = (uint8_t*) o->data;
+ memcpy(transmit_buffer, header, header_len);
+ memcpy(transmit_buffer + header_len + pixel_len, trailer, trailer_len);
+ self->post_brightness_buffer = transmit_buffer + header_len;
+
+ if (self->byteorder.is_dotstar) {
+ // Initialize the buffer with the dotstar start bytes.
+ // Note: Header and end must be setup by caller
+ for (uint i = 0; i < self->pixel_count * 4; i += 4) {
+ self->post_brightness_buffer[i] = DOTSTAR_LED_START_FULL_BRIGHT;
+ }
+ }
+ // Call set_brightness so that it can allocate a second buffer if needed.
+ self->brightness = 1.0;
+ common_hal__pixelbuf_pixelbuf_set_brightness(MP_OBJ_FROM_PTR(self), brightness);
+
+ // Turn on auto_write. We don't want to do it with the above brightness call.
+ self->auto_write = auto_write;
+}
+
+size_t common_hal__pixelbuf_pixelbuf_get_len(mp_obj_t self_in) {
+ pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in);
+ return self->pixel_count;
+}
+
+uint8_t common_hal__pixelbuf_pixelbuf_get_bpp(mp_obj_t self_in) {
+ pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in);
+ return self->byteorder.bpp;
+}
+
+mp_obj_t common_hal__pixelbuf_pixelbuf_get_byteorder_string(mp_obj_t self_in) {
+ pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in);
+ return self->byteorder.order_string;
+}
+
+bool common_hal__pixelbuf_pixelbuf_get_auto_write(mp_obj_t self_in) {
+ pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in);
+ return self->auto_write;
+}
+
+void common_hal__pixelbuf_pixelbuf_set_auto_write(mp_obj_t self_in, bool auto_write) {
+ pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in);
+ self->auto_write = auto_write;
+}
+
+mp_float_t common_hal__pixelbuf_pixelbuf_get_brightness(mp_obj_t self_in) {
+ pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in);
+ return self->brightness;
+}
+
+void common_hal__pixelbuf_pixelbuf_set_brightness(mp_obj_t self_in, mp_float_t brightness) {
+ pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in);
+ // Skip out if the brightness is already set. The default of self->brightness is 1.0. So, this
+ // also prevents the pre_brightness_buffer allocation when brightness is set to 1.0 again.
+ mp_float_t change = brightness - self->brightness;
+ if (-0.001 < change && change < 0.001) {
+ return;
+ }
+ self->brightness = brightness;
+ size_t pixel_len = self->pixel_count * self->bytes_per_pixel;
+ if (self->pre_brightness_buffer == NULL) {
+ self->pre_brightness_buffer = m_malloc(pixel_len, false);
+ memcpy(self->pre_brightness_buffer, self->post_brightness_buffer, pixel_len);
+ }
+ for (size_t i = 0; i < pixel_len; i++) {
+ // Don't adjust per-pixel luminance bytes in dotstar mode
+ if (self->byteorder.is_dotstar && i % 4 == 0) {
+ continue;
+ }
+ self->post_brightness_buffer[i] = self->pre_brightness_buffer[i] * self->brightness;
+ }
+
+ if (self->auto_write) {
+ common_hal__pixelbuf_pixelbuf_show(self_in);
+ }
+}
+
+void _pixelbuf_parse_color(pixelbuf_pixelbuf_obj_t* self, mp_obj_t color, uint8_t* r, uint8_t* g, uint8_t* b, uint8_t* w) {
+ pixelbuf_byteorder_details_t *byteorder = &self->byteorder;
+ // w is shared between white in NeoPixels and brightness in dotstars (so that DotStars can have
+ // per-pixel brightness). Set the defaults here in case it isn't set below.
+ if (byteorder->is_dotstar) {
+ *w = 255;
+ } else {
+ *w = 0;
+ }
+
+ if (MP_OBJ_IS_INT(color)) {
+ mp_int_t value = mp_obj_get_int_truncated(color);
+ *r = value >> 16 & 0xff;
+ *g = (value >> 8) & 0xff;
+ *b = value & 0xff;
+ } else {
+ mp_obj_t *items;
+ size_t len;
+ mp_obj_get_array(color, &len, &items);
+ if (len < 3 || len > 4) {
+ mp_raise_ValueError_varg(translate("Expected tuple of length %d, got %d"), byteorder->bpp, len);
+ }
+
+ *r = mp_obj_get_int_truncated(items[PIXEL_R]);
+ *g = mp_obj_get_int_truncated(items[PIXEL_G]);
+ *b = mp_obj_get_int_truncated(items[PIXEL_B]);
+ if (len > 3) {
+ if (mp_obj_is_float(items[PIXEL_W])) {
+ *w = 255 * mp_obj_get_float(items[PIXEL_W]);
+ } else {
+ *w = mp_obj_get_int_truncated(items[PIXEL_W]);
+ }
+ return;
+ }
+ }
+ // Int colors can't set white directly so convert to white when all components are equal.
+ // Also handles RGBW values assigned an RGB tuple.
+ if (!byteorder->is_dotstar && byteorder->bpp == 4 && byteorder->has_white && *r == *g && *r == *b) {
+ *w = *r;
+ *r = 0;
+ *g = 0;
+ *b = 0;
+ }
+}
+
+void _pixelbuf_set_pixel_color(pixelbuf_pixelbuf_obj_t* self, size_t index, uint8_t r, uint8_t g, uint8_t b, uint8_t w) {
+ // DotStars don't have white, instead they have 5 bit brightness so pack it into w. Shift right
+ // by three to leave the top five bits.
+ if (self->bytes_per_pixel == 4 && self->byteorder.is_dotstar) {
+ w = DOTSTAR_LED_START | w >> 3;
+ }
+ pixelbuf_rgbw_t *rgbw_order = &self->byteorder.byteorder;
+ size_t offset = index * self->bytes_per_pixel;
+ if (self->pre_brightness_buffer != NULL) {
+ uint8_t* pre_brightness_buffer = self->pre_brightness_buffer + offset;
+ if (self->bytes_per_pixel == 4) {
+ pre_brightness_buffer[rgbw_order->w] = w;
+ }
+
+ pre_brightness_buffer[rgbw_order->r] = r;
+ pre_brightness_buffer[rgbw_order->g] = g;
+ pre_brightness_buffer[rgbw_order->b] = b;
+ }
+
+ uint8_t* post_brightness_buffer = self->post_brightness_buffer + offset;
+ if (self->bytes_per_pixel == 4) {
+ // Only apply brightness if w is actually white (aka not DotStar.)
+ if (!self->byteorder.is_dotstar) {
+ w *= self->brightness;
+ }
+ post_brightness_buffer[rgbw_order->w] = w;
+ }
+ post_brightness_buffer[rgbw_order->r] = r * self->brightness;
+ post_brightness_buffer[rgbw_order->g] = g * self->brightness;
+ post_brightness_buffer[rgbw_order->b] = b * self->brightness;
+}
+
+void _pixelbuf_set_pixel(pixelbuf_pixelbuf_obj_t* self, size_t index, mp_obj_t value) {
+ uint8_t r;
+ uint8_t g;
+ uint8_t b;
+ uint8_t w;
+ _pixelbuf_parse_color(self, value, &r, &g, &b, &w);
+ _pixelbuf_set_pixel_color(self, index, r, g, b, w);
+}
+
+void common_hal__pixelbuf_pixelbuf_set_pixels(mp_obj_t self_in, size_t start, mp_int_t step, size_t slice_len, mp_obj_t* values) {
+ pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in);
+ for (size_t i = 0; i < slice_len; i++) {
+ _pixelbuf_set_pixel(self, start, values[i]);
+ start+=step;
+ }
+ if (self->auto_write) {
+ common_hal__pixelbuf_pixelbuf_show(self_in);
+ }
+}
+
+void common_hal__pixelbuf_pixelbuf_set_pixel(mp_obj_t self_in, size_t index, mp_obj_t value) {
+ pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in);
+ _pixelbuf_set_pixel(self, index, value);
+ if (self->auto_write) {
+ common_hal__pixelbuf_pixelbuf_show(self_in);
+ }
+}
+
+mp_obj_t common_hal__pixelbuf_pixelbuf_get_pixel(mp_obj_t self_in, size_t index) {
+ pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in);
+ mp_obj_t elems[self->byteorder.bpp];
+ uint8_t* pixel_buffer = self->post_brightness_buffer;
+ if (self->pre_brightness_buffer != NULL) {
+ pixel_buffer = self->pre_brightness_buffer;
+ }
+ pixel_buffer += self->byteorder.bpp * index;
+
+ pixelbuf_rgbw_t *rgbw_order = &self->byteorder.byteorder;
+ elems[0] = MP_OBJ_NEW_SMALL_INT(pixel_buffer[rgbw_order->r]);
+ elems[1] = MP_OBJ_NEW_SMALL_INT(pixel_buffer[rgbw_order->g]);
+ elems[2] = MP_OBJ_NEW_SMALL_INT(pixel_buffer[rgbw_order->b]);
+ if (self->byteorder.bpp > 3) {
+ uint8_t w = pixel_buffer[rgbw_order->w];
+ if (self->byteorder.is_dotstar) {
+ elems[3] = mp_obj_new_float((w & 0b00011111) / 31.0);
+ } else {
+ elems[3] = MP_OBJ_NEW_SMALL_INT(w);
+ }
+ }
+
+ return mp_obj_new_tuple(self->byteorder.bpp, elems);
+}
+
+void common_hal__pixelbuf_pixelbuf_show(mp_obj_t self_in) {
+ pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in);
+ mp_obj_t dest[2 + 1];
+ mp_load_method(self_in, MP_QSTR__transmit, dest);
+
+ dest[2] = self->transmit_buffer_obj;
+
+ mp_call_method_n_kw(1, 0, dest);
+}
+
+void common_hal__pixelbuf_pixelbuf_fill(mp_obj_t self_in, mp_obj_t fill_color) {
+ pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in);
+
+ uint8_t r;
+ uint8_t g;
+ uint8_t b;
+ uint8_t w;
+ _pixelbuf_parse_color(self, fill_color, &r, &g, &b, &w);
+
+ for (size_t i = 0; i < self->pixel_count; i++) {
+ _pixelbuf_set_pixel_color(self, i, r, g, b, w);
+ }
+ if (self->auto_write) {
+ common_hal__pixelbuf_pixelbuf_show(self_in);
+ }
+}
diff --git a/shared-module/_pixelbuf/PixelBuf.h b/shared-module/_pixelbuf/PixelBuf.h
new file mode 100644
index 000000000..a9fbed366
--- /dev/null
+++ b/shared-module/_pixelbuf/PixelBuf.h
@@ -0,0 +1,71 @@
+/*
+ * This file is part of the Circuit Python project, https://github.com/adafruit/circuitpython
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Roy Hooper
+ *
+ * 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/objarray.h"
+
+#ifndef PIXELBUF_SHARED_MODULE_H
+#define PIXELBUF_SHARED_MODULE_H
+
+typedef struct {
+ uint8_t r;
+ uint8_t g;
+ uint8_t b;
+ uint8_t w;
+} pixelbuf_rgbw_t;
+
+typedef struct {
+ uint8_t bpp;
+ pixelbuf_rgbw_t byteorder;
+ bool has_white;
+ bool is_dotstar;
+ mp_obj_t order_string;
+} pixelbuf_byteorder_details_t;
+
+typedef struct {
+ mp_obj_base_t base;
+ size_t pixel_count;
+ size_t bytes_per_pixel;
+ pixelbuf_byteorder_details_t byteorder;
+ mp_float_t brightness;
+ mp_obj_t transmit_buffer_obj;
+ // The post_brightness_buffer is offset into the buffer allocated in transmit_buffer_obj to
+ // account for any header.
+ uint8_t *post_brightness_buffer;
+ uint8_t *pre_brightness_buffer;
+ bool auto_write;
+} pixelbuf_pixelbuf_obj_t;
+
+#define PIXEL_R 0
+#define PIXEL_G 1
+#define PIXEL_B 2
+#define PIXEL_W 3
+
+#define DOTSTAR_LED_START 0b11100000
+#define DOTSTAR_LED_START_FULL_BRIGHT 0xFF
+
+#endif
diff --git a/shared-module/_pixelbuf/__init__.c b/shared-module/_pixelbuf/__init__.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/shared-module/_pixelbuf/__init__.c
diff --git a/shared-module/_stage/__init__.c b/shared-module/_stage/__init__.c
index 86f5ee795..0323c32cb 100644
--- a/shared-module/_stage/__init__.c
+++ b/shared-module/_stage/__init__.c
@@ -31,43 +31,67 @@
#include "shared-bindings/_stage/Text.h"
-bool render_stage(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1,
+void render_stage(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1,
mp_obj_t *layers, size_t layers_size,
uint16_t *buffer, size_t buffer_size,
- busio_spi_obj_t *spi) {
+ displayio_display_obj_t *display,
+ uint8_t scale, uint16_t background) {
+
+ displayio_area_t area;
+ area.x1 = x0;
+ area.y1 = y0;
+ area.x2 = x1;
+ area.y2 = y1;
+ displayio_display_core_set_region_to_update(
+ &display->core, display->set_column_command, display->set_row_command,
+ NO_COMMAND, NO_COMMAND, display->data_as_commands, false, &area);
+
+ while (!displayio_display_core_begin_transaction(&display->core)) {
+ RUN_BACKGROUND_TASKS;
+ }
+ display->core.send(display->core.bus, DISPLAY_COMMAND,
+ CHIP_SELECT_TOGGLE_EVERY_BYTE,
+ &display->write_ram_command, 1);
size_t index = 0;
for (uint16_t y = y0; y < y1; ++y) {
- for (uint16_t x = x0; x < x1; ++x) {
- for (size_t layer = 0; layer < layers_size; ++layer) {
+ for (uint8_t yscale = 0; yscale < scale; ++yscale) {
+ for (uint16_t x = x0; x < x1; ++x) {
uint16_t c = TRANSPARENT;
- layer_obj_t *obj = MP_OBJ_TO_PTR(layers[layer]);
- if (obj->base.type == &mp_type_layer) {
- c = get_layer_pixel(obj, x, y);
- } else if (obj->base.type == &mp_type_text) {
- c = get_text_pixel((text_obj_t *)obj, x, y);
+ for (size_t layer = 0; layer < layers_size; ++layer) {
+ layer_obj_t *obj = MP_OBJ_TO_PTR(layers[layer]);
+ if (obj->base.type == &mp_type_layer) {
+ c = get_layer_pixel(obj, x, y);
+ } else if (obj->base.type == &mp_type_text) {
+ c = get_text_pixel((text_obj_t *)obj, x, y);
+ }
+ if (c != TRANSPARENT) {
+ break;
+ }
}
- if (c != TRANSPARENT) {
- buffer[index] = c;
- break;
+ if (c == TRANSPARENT) {
+ c = background;
}
- }
- index += 1;
- // The buffer is full, send it.
- if (index >= buffer_size) {
- if (!common_hal_busio_spi_write(spi,
- ((uint8_t*)buffer), buffer_size * 2)) {
- return false;
+ for (uint8_t xscale = 0; xscale < scale; ++xscale) {
+ buffer[index] = c;
+ index += 1;
+ // The buffer is full, send it.
+ if (index >= buffer_size) {
+ display->core.send(display->core.bus, DISPLAY_DATA,
+ CHIP_SELECT_UNTOUCHED,
+ ((uint8_t*)buffer), buffer_size * 2);
+ index = 0;
+ }
}
- index = 0;
}
}
}
// Send the remaining data.
if (index) {
- if (!common_hal_busio_spi_write(spi, ((uint8_t*)buffer), index * 2)) {
- return false;
- }
+ display->core.send(display->core.bus, DISPLAY_DATA,
+ CHIP_SELECT_UNTOUCHED,
+ ((uint8_t*)buffer), index * 2);
}
- return true;
+
+ displayio_display_core_end_transaction(&display->core);
}
diff --git a/shared-module/_stage/__init__.h b/shared-module/_stage/__init__.h
index d56a26940..7a1826200 100644
--- a/shared-module/_stage/__init__.h
+++ b/shared-module/_stage/__init__.h
@@ -27,16 +27,17 @@
#ifndef MICROPY_INCLUDED_SHARED_MODULE__STAGE_H
#define MICROPY_INCLUDED_SHARED_MODULE__STAGE_H
-#include "shared-bindings/busio/SPI.h"
+#include "shared-bindings/displayio/Display.h"
#include <stdint.h>
#include <stdbool.h>
#include "py/obj.h"
#define TRANSPARENT (0x1ff8)
-bool render_stage(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1,
+void render_stage(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1,
mp_obj_t *layers, size_t layers_size,
uint16_t *buffer, size_t buffer_size,
- busio_spi_obj_t *spi);
+ displayio_display_obj_t *display,
+ uint8_t scale, uint16_t background);
#endif // MICROPY_INCLUDED_SHARED_MODULE__STAGE
diff --git a/shared-module/aesio/__init__.c b/shared-module/aesio/__init__.c
new file mode 100644
index 000000000..2cacaeb66
--- /dev/null
+++ b/shared-module/aesio/__init__.c
@@ -0,0 +1,58 @@
+#include <string.h>
+
+#include "py/runtime.h"
+
+#include "shared-bindings/aesio/__init__.h"
+#include "shared-module/aesio/__init__.h"
+
+void common_hal_aesio_aes_construct(aesio_aes_obj_t *self, const uint8_t *key,
+ uint32_t key_length, const uint8_t *iv,
+ int mode, int counter) {
+ self->mode = mode;
+ self->counter = counter;
+ common_hal_aesio_aes_rekey(self, key, key_length, iv);
+}
+
+void common_hal_aesio_aes_rekey(aesio_aes_obj_t *self, const uint8_t *key,
+ uint32_t key_length, const uint8_t *iv) {
+ memset(&self->ctx, 0, sizeof(self->ctx));
+ if (iv != NULL) {
+ AES_init_ctx_iv(&self->ctx, key, key_length, iv);
+ } else {
+ AES_init_ctx(&self->ctx, key, key_length);
+ }
+}
+
+void common_hal_aesio_aes_set_mode(aesio_aes_obj_t *self, int mode) {
+ self->mode = mode;
+}
+
+void common_hal_aesio_aes_encrypt(aesio_aes_obj_t *self, uint8_t *buffer,
+ size_t length) {
+ switch (self->mode) {
+ case AES_MODE_ECB:
+ AES_ECB_encrypt(&self->ctx, buffer);
+ break;
+ case AES_MODE_CBC:
+ AES_CBC_encrypt_buffer(&self->ctx, buffer, length);
+ break;
+ case AES_MODE_CTR:
+ AES_CTR_xcrypt_buffer(&self->ctx, buffer, length);
+ break;
+ }
+}
+
+void common_hal_aesio_aes_decrypt(aesio_aes_obj_t *self, uint8_t *buffer,
+ size_t length) {
+ switch (self->mode) {
+ case AES_MODE_ECB:
+ AES_ECB_decrypt(&self->ctx, buffer);
+ break;
+ case AES_MODE_CBC:
+ AES_CBC_decrypt_buffer(&self->ctx, buffer, length);
+ break;
+ case AES_MODE_CTR:
+ AES_CTR_xcrypt_buffer(&self->ctx, buffer, length);
+ break;
+ }
+}
diff --git a/shared-module/aesio/__init__.h b/shared-module/aesio/__init__.h
new file mode 100644
index 000000000..1a0bb8696
--- /dev/null
+++ b/shared-module/aesio/__init__.h
@@ -0,0 +1,59 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Dan Halbert 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_SHARED_MODULE_AESIO__INIT__H
+#define MICROPY_INCLUDED_SHARED_MODULE_AESIO__INIT__H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "py/obj.h"
+#include "py/proto.h"
+
+#include "shared-module/aesio/aes.h"
+
+// These values were chosen to correspond with the values
+// present in pycrypto.
+enum AES_MODE {
+ AES_MODE_ECB = 1,
+ AES_MODE_CBC = 2,
+ AES_MODE_CTR = 6,
+};
+
+typedef struct {
+ mp_obj_base_t base;
+
+ // The tinyaes context
+ struct AES_ctx ctx;
+
+ // Which AES mode this instance of the object is configured to use
+ enum AES_MODE mode;
+
+ // Counter for running in CTR mode
+ uint32_t counter;
+} aesio_aes_obj_t;
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_AESIO__INIT__H
diff --git a/shared-module/aesio/aes.c b/shared-module/aesio/aes.c
new file mode 100644
index 000000000..b62b5afc4
--- /dev/null
+++ b/shared-module/aesio/aes.c
@@ -0,0 +1,608 @@
+/*
+
+This is an implementation of the AES algorithm, specifically ECB, CTR and CBC mode.
+Block size can be chosen in aes.h - available choices are AES128, AES192, AES256.
+
+The implementation is verified against the test vectors in:
+ National Institute of Standards and Technology Special Publication 800-38A 2001 ED
+
+ECB-AES128
+----------
+
+ plain-text:
+ 6bc1bee22e409f96e93d7e117393172a
+ ae2d8a571e03ac9c9eb76fac45af8e51
+ 30c81c46a35ce411e5fbc1191a0a52ef
+ f69f2445df4f9b17ad2b417be66c3710
+
+ key:
+ 2b7e151628aed2a6abf7158809cf4f3c
+
+ resulting cipher
+ 3ad77bb40d7a3660a89ecaf32466ef97
+ f5d3d58503b9699de785895a96fdbaaf
+ 43b1cd7f598ece23881b00e3ed030688
+ 7b0c785e27e8ad3f8223207104725dd4
+
+
+NOTE: String length must be evenly divisible by 16byte (str_len % 16 == 0)
+ You should pad the end of the string with zeros if this is not the case.
+ For AES192/256 the key size is proportionally larger.
+
+*/
+
+/*****************************************************************************/
+/* Includes: */
+/*****************************************************************************/
+#include <string.h> // CBC mode, for memset
+#include "aes.h"
+
+/*****************************************************************************/
+/* Defines: */
+/*****************************************************************************/
+// The number of columns comprising a state in AES. This is a constant in AES.
+// Value=4
+#define Nb 4UL
+
+#if defined(AES256) && (AES256 == 1)
+ #define Nk256 8UL
+ #define Nr256 14UL
+#endif
+#if defined(AES192) && (AES192 == 1)
+ #define Nk192 6UL
+ #define Nr192 12UL
+#endif
+#if defined(AES128) && (AES128 == 1)
+ #define Nk128 4UL // The number of 32 bit words in a key.
+ #define Nr128 10UL // The number of rounds in AES Cipher.
+#endif
+
+// jcallan@github points out that declaring Multiply as a function reduces code
+// size considerably with the Keil ARM compiler. See this link for more
+// information: https://github.com/kokke/tiny-AES-C/pull/3
+#ifndef MULTIPLY_AS_A_FUNCTION
+ #define MULTIPLY_AS_A_FUNCTION 0
+#endif
+
+
+
+
+/*****************************************************************************/
+/* Private variables: */
+/*****************************************************************************/
+// state - array holding the intermediate results during decryption.
+typedef uint8_t state_t[4][4];
+
+
+
+// The lookup-tables are marked const so they can be placed in read-only storage
+// instead of RAM The numbers below can be computed dynamically trading ROM for
+// RAM - This can be useful in (embedded) bootloader applications, where ROM is
+// often limited.
+static const uint8_t sbox[256] = {
+ //0 1 2 3 4 5 6 7 8 9 A B C D E F
+ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
+ 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
+ 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
+ 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
+ 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
+ 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
+ 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
+ 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
+ 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
+ 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
+ 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
+ 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
+ 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
+ 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
+ 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
+ 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 };
+
+static const uint8_t rsbox[256] = {
+ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
+ 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
+ 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
+ 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
+ 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
+ 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
+ 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
+ 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
+ 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
+ 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
+ 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
+ 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
+ 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
+ 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
+ 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
+ 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d };
+
+// The round constant word array, Rcon[i], contains the values given by x to the
+// power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8)
+static const uint8_t Rcon[11] = {
+ 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 };
+
+/*
+ * Jordan Goulder points out in PR #12
+ * (https://github.com/kokke/tiny-AES-C/pull/12), that you can remove most of
+ * the elements in the Rcon array, because they are unused.
+ *
+ * From Wikipedia's article on the Rijndael key schedule @
+ * https://en.wikipedia.org/wiki/Rijndael_key_schedule#Rcon
+ *
+ * "Only the first some of these constants are actually used – up to rcon[10]
+ * for AES-128 (as 11 round keys are needed), up to rcon[8] for AES-192, up to
+ * rcon[7] for AES-256. rcon[0] is not used in AES algorithm."
+ */
+
+
+/*****************************************************************************/
+/* Private functions: */
+/*****************************************************************************/
+static const uint8_t *GetRoundKey(const struct AES_ctx *ctx) {
+ switch (ctx->KeyLength) {
+#if defined(AES128) && (AES128 == 1)
+ case 16: return ctx->RoundKey128;
+#endif
+#if defined(AES192) && (AES192 == 1)
+ case 24: return ctx->RoundKey192;
+#endif
+#if defined(AES256) && (AES256 == 1)
+ case 32: return ctx->RoundKey256;
+#endif
+ }
+ return NULL;
+}
+
+
+/*
+static uint8_t getSBoxValue(uint8_t num)
+{
+ return sbox[num];
+}
+*/
+#define getSBoxValue(num) (sbox[(num)])
+/*
+static uint8_t getSBoxInvert(uint8_t num)
+{
+ return rsbox[num];
+}
+*/
+#define getSBoxInvert(num) (rsbox[(num)])
+
+// This function produces Nb(Nr+1) round keys. The round keys are used in each
+// round to decrypt the states.
+static void KeyExpansion(struct AES_ctx* ctx, const uint8_t* Key)
+{
+ uint8_t* RoundKey = (uint8_t *)GetRoundKey(ctx);
+
+ unsigned i, j, k;
+ uint8_t tempa[4]; // Used for the column/row operations
+
+ // The first round key is the key itself.
+ for (i = 0; i < ctx->Nk; ++i)
+ {
+ RoundKey[(i * 4) + 0] = Key[(i * 4) + 0];
+ RoundKey[(i * 4) + 1] = Key[(i * 4) + 1];
+ RoundKey[(i * 4) + 2] = Key[(i * 4) + 2];
+ RoundKey[(i * 4) + 3] = Key[(i * 4) + 3];
+ }
+
+ // All other round keys are found from the previous round keys.
+ for (i = ctx->Nk; i < Nb * (ctx->Nr + 1); ++i)
+ {
+ {
+ k = (i - 1) * 4;
+ tempa[0]=RoundKey[k + 0];
+ tempa[1]=RoundKey[k + 1];
+ tempa[2]=RoundKey[k + 2];
+ tempa[3]=RoundKey[k + 3];
+
+ }
+
+ if (i % ctx->Nk == 0)
+ {
+ // This function shifts the 4 bytes in a word to the left once.
+ // [a0,a1,a2,a3] becomes [a1,a2,a3,a0]
+
+ // Function RotWord()
+ {
+ const uint8_t u8tmp = tempa[0];
+ tempa[0] = tempa[1];
+ tempa[1] = tempa[2];
+ tempa[2] = tempa[3];
+ tempa[3] = u8tmp;
+ }
+
+ // SubWord() is a function that takes a four-byte input word and applies
+ // the S-box to each of the four bytes to produce an output word.
+
+ // Function Subword()
+ {
+ tempa[0] = getSBoxValue(tempa[0]);
+ tempa[1] = getSBoxValue(tempa[1]);
+ tempa[2] = getSBoxValue(tempa[2]);
+ tempa[3] = getSBoxValue(tempa[3]);
+ }
+
+ tempa[0] = tempa[0] ^ Rcon[i/ctx->Nk];
+ }
+#if defined(AES256) && (AES256 == 1)
+ if (ctx->KeyLength == 32) {
+ if (i % ctx->Nk == 4)
+ {
+ // Function Subword()
+ {
+ tempa[0] = getSBoxValue(tempa[0]);
+ tempa[1] = getSBoxValue(tempa[1]);
+ tempa[2] = getSBoxValue(tempa[2]);
+ tempa[3] = getSBoxValue(tempa[3]);
+ }
+ }
+ }
+#endif
+ j = i * 4; k=(i - ctx->Nk) * 4;
+ RoundKey[j + 0] = RoundKey[k + 0] ^ tempa[0];
+ RoundKey[j + 1] = RoundKey[k + 1] ^ tempa[1];
+ RoundKey[j + 2] = RoundKey[k + 2] ^ tempa[2];
+ RoundKey[j + 3] = RoundKey[k + 3] ^ tempa[3];
+ }
+}
+
+void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key, uint32_t keylen)
+{
+ ctx->KeyLength = keylen;
+ switch (ctx->KeyLength) {
+#if defined(AES128) && (AES128 == 1)
+ case 16: ctx->Nr = Nr128; ctx->Nk = Nk128; break;
+#endif
+#if defined(AES192) && (AES192 == 1)
+ case 24: ctx->Nr = Nr192; ctx->Nk = Nk192; break;
+#endif
+#if defined(AES256) && (AES256 == 1)
+ case 32: ctx->Nr = Nr256; ctx->Nk = Nk256; break;
+#endif
+ default: ctx->Nr = 0; ctx->Nk = 0; break;
+ }
+ KeyExpansion(ctx, key);
+}
+#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
+void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, uint32_t keylen, const uint8_t* iv)
+{
+ AES_init_ctx(ctx, key, keylen);
+ memcpy (ctx->Iv, iv, AES_BLOCKLEN);
+}
+void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv)
+{
+ memcpy (ctx->Iv, iv, AES_BLOCKLEN);
+}
+#endif
+
+// This function adds the round key to state. The round key is added to the
+// state by an XOR function.
+static void AddRoundKey(uint8_t round, state_t* state, const uint8_t* RoundKey)
+{
+ uint8_t i,j;
+ for (i = 0; i < 4; ++i)
+ {
+ for (j = 0; j < 4; ++j)
+ {
+ (*state)[i][j] ^= RoundKey[(round * Nb * 4) + (i * Nb) + j];
+ }
+ }
+}
+
+// The SubBytes Function Substitutes the values in the state matrix with values
+// in an S-box.
+static void SubBytes(state_t* state)
+{
+ uint8_t i, j;
+ for (i = 0; i < 4; ++i)
+ {
+ for (j = 0; j < 4; ++j)
+ {
+ (*state)[j][i] = getSBoxValue((*state)[j][i]);
+ }
+ }
+}
+
+// The ShiftRows() function shifts the rows in the state to the left. Each row
+// is shifted with different offset. Offset = Row number. So the first row is
+// not shifted.
+static void ShiftRows(state_t* state)
+{
+ uint8_t temp;
+
+ // Rotate first row 1 columns to left
+ temp = (*state)[0][1];
+ (*state)[0][1] = (*state)[1][1];
+ (*state)[1][1] = (*state)[2][1];
+ (*state)[2][1] = (*state)[3][1];
+ (*state)[3][1] = temp;
+
+ // Rotate second row 2 columns to left
+ temp = (*state)[0][2];
+ (*state)[0][2] = (*state)[2][2];
+ (*state)[2][2] = temp;
+
+ temp = (*state)[1][2];
+ (*state)[1][2] = (*state)[3][2];
+ (*state)[3][2] = temp;
+
+ // Rotate third row 3 columns to left
+ temp = (*state)[0][3];
+ (*state)[0][3] = (*state)[3][3];
+ (*state)[3][3] = (*state)[2][3];
+ (*state)[2][3] = (*state)[1][3];
+ (*state)[1][3] = temp;
+}
+
+static uint8_t xtime(uint8_t x)
+{
+ return ((x<<1) ^ (((x>>7) & 1) * 0x1b));
+}
+
+// MixColumns function mixes the columns of the state matrix
+static void MixColumns(state_t* state)
+{
+ uint8_t i;
+ uint8_t Tmp, Tm, t;
+ for (i = 0; i < 4; ++i)
+ {
+ t = (*state)[i][0];
+ Tmp = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3] ;
+ Tm = (*state)[i][0] ^ (*state)[i][1] ; Tm = xtime(Tm); (*state)[i][0] ^= Tm ^ Tmp ;
+ Tm = (*state)[i][1] ^ (*state)[i][2] ; Tm = xtime(Tm); (*state)[i][1] ^= Tm ^ Tmp ;
+ Tm = (*state)[i][2] ^ (*state)[i][3] ; Tm = xtime(Tm); (*state)[i][2] ^= Tm ^ Tmp ;
+ Tm = (*state)[i][3] ^ t ; Tm = xtime(Tm); (*state)[i][3] ^= Tm ^ Tmp ;
+ }
+}
+
+// Multiply is used to multiply numbers in the field GF(2^8)
+// Note: The last call to xtime() is unneeded, but often ends up generating a smaller binary
+// The compiler seems to be able to vectorize the operation better this way.
+// See https://github.com/kokke/tiny-AES-c/pull/34
+#if MULTIPLY_AS_A_FUNCTION
+static uint8_t Multiply(uint8_t x, uint8_t y)
+{
+ return (((y & 1) * x) ^
+ ((y>>1 & 1) * xtime(x)) ^
+ ((y>>2 & 1) * xtime(xtime(x))) ^
+ ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^
+ ((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))); /* this last call to xtime() can be omitted */
+ }
+#else
+#define Multiply(x, y) \
+ ( ((y & 1) * x) ^ \
+ ((y>>1 & 1) * xtime(x)) ^ \
+ ((y>>2 & 1) * xtime(xtime(x))) ^ \
+ ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^ \
+ ((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))) \
+
+#endif
+
+#if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
+// MixColumns function mixes the columns of the state matrix. The method used to
+// multiply may be difficult to understand for the inexperienced. Please use the
+// references to gain more information.
+static void InvMixColumns(state_t* state)
+{
+ int i;
+ uint8_t a, b, c, d;
+ for (i = 0; i < 4; ++i)
+ {
+ a = (*state)[i][0];
+ b = (*state)[i][1];
+ c = (*state)[i][2];
+ d = (*state)[i][3];
+
+ (*state)[i][0] = Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09);
+ (*state)[i][1] = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d);
+ (*state)[i][2] = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b);
+ (*state)[i][3] = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e);
+ }
+}
+
+
+// The SubBytes Function Substitutes the values in the state matrix with values
+// in an S-box.
+static void InvSubBytes(state_t* state)
+{
+ uint8_t i, j;
+ for (i = 0; i < 4; ++i)
+ {
+ for (j = 0; j < 4; ++j)
+ {
+ (*state)[j][i] = getSBoxInvert((*state)[j][i]);
+ }
+ }
+}
+
+static void InvShiftRows(state_t* state)
+{
+ uint8_t temp;
+
+ // Rotate first row 1 columns to right
+ temp = (*state)[3][1];
+ (*state)[3][1] = (*state)[2][1];
+ (*state)[2][1] = (*state)[1][1];
+ (*state)[1][1] = (*state)[0][1];
+ (*state)[0][1] = temp;
+
+ // Rotate second row 2 columns to right
+ temp = (*state)[0][2];
+ (*state)[0][2] = (*state)[2][2];
+ (*state)[2][2] = temp;
+
+ temp = (*state)[1][2];
+ (*state)[1][2] = (*state)[3][2];
+ (*state)[3][2] = temp;
+
+ // Rotate third row 3 columns to right
+ temp = (*state)[0][3];
+ (*state)[0][3] = (*state)[1][3];
+ (*state)[1][3] = (*state)[2][3];
+ (*state)[2][3] = (*state)[3][3];
+ (*state)[3][3] = temp;
+}
+#endif // #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
+
+// Cipher is the main function that encrypts the PlainText.
+static void Cipher(state_t* state, const struct AES_ctx* ctx)
+{
+ const uint8_t* RoundKey = GetRoundKey(ctx);
+ uint8_t round = 0;
+
+ // Add the First round key to the state before starting the rounds.
+ AddRoundKey(0, state, RoundKey);
+
+ // There will be Nr rounds. The first Nr-1 rounds are identical. These Nr
+ // rounds are executed in the loop below. Last one without MixColumns()
+ for (round = 1; ; ++round)
+ {
+ SubBytes(state);
+ ShiftRows(state);
+ if (round == ctx->Nr) {
+ break;
+ }
+ MixColumns(state);
+ AddRoundKey(round, state, RoundKey);
+ }
+ // Add round key to last round
+ AddRoundKey(ctx->Nr, state, RoundKey);
+}
+
+#if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
+static void InvCipher(state_t* state, const struct AES_ctx* ctx)
+{
+ const uint8_t* RoundKey = GetRoundKey(ctx);
+ uint8_t round = 0;
+
+ // Add the First round key to the state before starting the rounds.
+ AddRoundKey(ctx->Nr, state, RoundKey);
+
+ // There will be Nr rounds. The first Nr-1 rounds are identical. These Nr
+ // rounds are executed in the loop below. Last one without InvMixColumn()
+ for (round = (ctx->Nr - 1); ; --round)
+ {
+ InvShiftRows(state);
+ InvSubBytes(state);
+ AddRoundKey(round, state, RoundKey);
+ if (round == 0) {
+ break;
+ }
+ InvMixColumns(state);
+ }
+
+}
+#endif // #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
+
+/*****************************************************************************/
+/* Public functions: */
+/*****************************************************************************/
+#if defined(ECB) && (ECB == 1)
+
+
+void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf)
+{
+ // The next function call encrypts the PlainText with the Key using AES
+ // algorithm.
+ Cipher((state_t*)buf, ctx);
+}
+
+void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf)
+{
+ // The next function call decrypts the PlainText with the Key using AES
+ // algorithm.
+ InvCipher((state_t*)buf, ctx);
+}
+
+
+#endif // #if defined(ECB) && (ECB == 1)
+
+
+
+
+
+#if defined(CBC) && (CBC == 1)
+
+
+static void XorWithIv(uint8_t* buf, const uint8_t* Iv)
+{
+ uint8_t i;
+ for (i = 0; i < AES_BLOCKLEN; ++i) // The block in AES is always 128bit no matter the key size
+ {
+ buf[i] ^= Iv[i];
+ }
+}
+
+void AES_CBC_encrypt_buffer(struct AES_ctx *ctx, uint8_t* buf, uint32_t length)
+{
+ uintptr_t i;
+ uint8_t *Iv = ctx->Iv;
+ for (i = 0; i < length; i += AES_BLOCKLEN)
+ {
+ XorWithIv(buf, Iv);
+ Cipher((state_t*)buf, ctx);
+ Iv = buf;
+ buf += AES_BLOCKLEN;
+ }
+ /* store Iv in ctx for next call */
+ memcpy(ctx->Iv, Iv, AES_BLOCKLEN);
+}
+
+void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length)
+{
+ uintptr_t i;
+ uint8_t storeNextIv[AES_BLOCKLEN];
+ for (i = 0; i < length; i += AES_BLOCKLEN)
+ {
+ memcpy(storeNextIv, buf, AES_BLOCKLEN);
+ InvCipher((state_t*)buf, ctx);
+ XorWithIv(buf, ctx->Iv);
+ memcpy(ctx->Iv, storeNextIv, AES_BLOCKLEN);
+ buf += AES_BLOCKLEN;
+ }
+
+}
+
+#endif // #if defined(CBC) && (CBC == 1)
+
+
+
+#if defined(CTR) && (CTR == 1)
+
+/* Symmetrical operation: same function for encrypting as for decrypting. Note
+any IV/nonce should never be reused with the same key */
+void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length)
+{
+ uint8_t buffer[AES_BLOCKLEN];
+
+ unsigned i;
+ int bi;
+ for (i = 0, bi = AES_BLOCKLEN; i < length; ++i, ++bi)
+ {
+ if (bi == AES_BLOCKLEN) /* we need to regen xor compliment in buffer */
+ {
+ memcpy(buffer, ctx->Iv, AES_BLOCKLEN);
+ Cipher((state_t*)buffer, ctx);
+
+ /* Increment Iv and handle overflow */
+ for (bi = (AES_BLOCKLEN - 1); bi >= 0; --bi)
+ {
+ /* inc will overflow */
+ if (ctx->Iv[bi] == 255)
+ {
+ ctx->Iv[bi] = 0;
+ continue;
+ }
+ ctx->Iv[bi] += 1;
+ break;
+ }
+ bi = 0;
+ }
+
+ buf[i] = (buf[i] ^ buffer[bi]);
+ }
+}
+
+#endif // #if defined(CTR) && (CTR == 1)
diff --git a/shared-module/aesio/aes.h b/shared-module/aesio/aes.h
new file mode 100644
index 000000000..a87fa5be7
--- /dev/null
+++ b/shared-module/aesio/aes.h
@@ -0,0 +1,105 @@
+#ifndef _AES_H_
+#define _AES_H_
+
+#include <stdint.h>
+
+// #define the macros below to 1/0 to enable/disable the mode of operation.
+//
+// CBC enables AES encryption in CBC-mode of operation.
+// CTR enables encryption in counter-mode.
+// ECB enables the basic ECB 16-byte block algorithm. All can be enabled simultaneously.
+
+// The #ifndef-guard allows it to be configured before #include'ing or at compile time.
+#ifndef CBC
+ #define CBC 1
+#endif
+
+#ifndef ECB
+ #define ECB 1
+#endif
+
+#ifndef CTR
+ #define CTR 1
+#endif
+
+
+#define AES128 1
+#define AES192 1
+#define AES256 1
+
+#define AES_BLOCKLEN 16 // Block length in bytes - AES is 128b block only
+
+#if defined(AES256) && (AES256 == 1)
+ #define AES_KEYLEN256 32
+ #define AES_keyExpSize256 240
+#endif
+#if defined(AES192) && (AES192 == 1)
+ #define AES_KEYLEN192 24
+ #define AES_keyExpSize192 208
+#endif
+#if defined(AES128) && (AES128 == 1)
+ #define AES_KEYLEN128 16 // Key length in bytes
+ #define AES_keyExpSize128 176
+#endif
+
+struct AES_ctx
+{
+ union {
+#if defined(AES256) && (AES256 == 1)
+ uint8_t RoundKey256[AES_keyExpSize256];
+#endif
+#if defined(AES192) && (AES192 == 1)
+ uint8_t RoundKey192[AES_keyExpSize192];
+#endif
+#if defined(AES128) && (AES128 == 1)
+ uint8_t RoundKey128[AES_keyExpSize128];
+#endif
+ };
+#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
+ uint8_t Iv[AES_BLOCKLEN];
+#endif
+ uint32_t KeyLength;
+ uint8_t Nr;
+ uint8_t Nk;
+};
+
+void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key, uint32_t keylen);
+#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
+void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, uint32_t keylen, const uint8_t* iv);
+void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv);
+#endif
+
+#if defined(ECB) && (ECB == 1)
+// buffer size is exactly AES_BLOCKLEN bytes;
+// you need only AES_init_ctx as IV is not used in ECB
+// NB: ECB is considered insecure for most uses
+void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf);
+void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf);
+
+#endif // #if defined(ECB) && (ECB == !)
+
+
+#if defined(CBC) && (CBC == 1)
+// buffer size MUST be mutile of AES_BLOCKLEN;
+// Suggest https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme
+// NOTES: you need to set IV in ctx via AES_init_ctx_iv() or AES_ctx_set_iv()
+// no IV should ever be reused with the same key
+void AES_CBC_encrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length);
+void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length);
+
+#endif // #if defined(CBC) && (CBC == 1)
+
+
+#if defined(CTR) && (CTR == 1)
+
+// Same function for encrypting as for decrypting.
+// IV is incremented for every block, and used after encryption as XOR-compliment for output
+// Suggesting https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme
+// NOTES: you need to set IV in ctx with AES_init_ctx_iv() or AES_ctx_set_iv()
+// no IV should ever be reused with the same key
+void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length);
+
+#endif // #if defined(CTR) && (CTR == 1)
+
+
+#endif // _AES_H_
diff --git a/shared-module/audioio/RawSample.c b/shared-module/audiocore/RawSample.c
index 6422e346b..a69ddeb65 100644
--- a/shared-module/audioio/RawSample.c
+++ b/shared-module/audiocore/RawSample.c
@@ -24,11 +24,11 @@
* THE SOFTWARE.
*/
-#include "shared-bindings/audioio/RawSample.h"
+#include "shared-bindings/audiocore/RawSample.h"
#include <stdint.h>
-#include "shared-module/audioio/RawSample.h"
+#include "shared-module/audiocore/RawSample.h"
void common_hal_audioio_rawsample_construct(audioio_rawsample_obj_t* self,
uint8_t* buffer,
@@ -60,6 +60,12 @@ void common_hal_audioio_rawsample_set_sample_rate(audioio_rawsample_obj_t* self,
uint32_t sample_rate) {
self->sample_rate = sample_rate;
}
+uint8_t common_hal_audioio_rawsample_get_bits_per_sample(audioio_rawsample_obj_t* self) {
+ return self->bits_per_sample;
+}
+uint8_t common_hal_audioio_rawsample_get_channel_count(audioio_rawsample_obj_t* self) {
+ return self->channel_count;
+}
void audioio_rawsample_reset_buffer(audioio_rawsample_obj_t* self,
bool single_channel,
diff --git a/shared-module/audioio/RawSample.h b/shared-module/audiocore/RawSample.h
index fe5283db4..6c2c19c9b 100644
--- a/shared-module/audioio/RawSample.h
+++ b/shared-module/audiocore/RawSample.h
@@ -29,7 +29,7 @@
#include "py/obj.h"
-#include "shared-module/audioio/__init__.h"
+#include "shared-module/audiocore/__init__.h"
typedef struct {
mp_obj_base_t base;
diff --git a/shared-module/audioio/WaveFile.c b/shared-module/audiocore/WaveFile.c
index d5dd9419c..0248d42e2 100644
--- a/shared-module/audioio/WaveFile.c
+++ b/shared-module/audiocore/WaveFile.c
@@ -24,7 +24,7 @@
* THE SOFTWARE.
*/
-#include "shared-bindings/audioio/WaveFile.h"
+#include "shared-bindings/audiocore/WaveFile.h"
#include <stdint.h>
#include <string.h>
@@ -32,7 +32,7 @@
#include "py/mperrno.h"
#include "py/runtime.h"
-#include "shared-module/audioio/WaveFile.h"
+#include "shared-module/audiocore/WaveFile.h"
#include "supervisor/shared/translate.h"
struct wave_format_chunk {
@@ -46,7 +46,9 @@ struct wave_format_chunk {
};
void common_hal_audioio_wavefile_construct(audioio_wavefile_obj_t* self,
- pyb_file_obj_t* file) {
+ pyb_file_obj_t* file,
+ uint8_t *buffer,
+ size_t buffer_size) {
// Load the wave
self->file = file;
uint8_t chunk_header[16];
@@ -84,7 +86,6 @@ void common_hal_audioio_wavefile_construct(audioio_wavefile_obj_t* self,
}
// Get the sample_rate
self->sample_rate = format.sample_rate;
- self->len = 256;
self->channel_count = format.num_channels;
self->bits_per_sample = format.bits_per_sample;
@@ -111,21 +112,31 @@ void common_hal_audioio_wavefile_construct(audioio_wavefile_obj_t* self,
// Try to allocate two buffers, one will be loaded from file and the other
// DMAed to DAC.
- self->buffer = m_malloc(self->len, false);
- if (self->buffer == NULL) {
- common_hal_audioio_wavefile_deinit(self);
- mp_raise_msg(&mp_type_MemoryError, translate("Couldn't allocate first buffer"));
- }
+ if (buffer_size) {
+ self->len = buffer_size / 2;
+ self->buffer = buffer;
+ self->second_buffer = buffer + self->len;
+ } else {
+ self->len = 256;
+ self->buffer = m_malloc(self->len, false);
+ if (self->buffer == NULL) {
+ common_hal_audioio_wavefile_deinit(self);
+ mp_raise_msg(&mp_type_MemoryError,
+ translate("Couldn't allocate first buffer"));
+ }
- self->second_buffer = m_malloc(self->len, false);
- if (self->second_buffer == NULL) {
- common_hal_audioio_wavefile_deinit(self);
- mp_raise_msg(&mp_type_MemoryError, translate("Couldn't allocate second buffer"));
+ self->second_buffer = m_malloc(self->len, false);
+ if (self->second_buffer == NULL) {
+ common_hal_audioio_wavefile_deinit(self);
+ mp_raise_msg(&mp_type_MemoryError,
+ translate("Couldn't allocate second buffer"));
+ }
}
}
void common_hal_audioio_wavefile_deinit(audioio_wavefile_obj_t* self) {
self->buffer = NULL;
+ self->second_buffer = NULL;
}
bool common_hal_audioio_wavefile_deinited(audioio_wavefile_obj_t* self) {
@@ -205,7 +216,7 @@ audioio_get_buffer_result_t audioio_wavefile_get_buffer(audioio_wavefile_obj_t*
} else {
*buffer = self->buffer;
}
- if (f_read(&self->file->fp, *buffer, num_bytes_to_load, &length_read) != FR_OK) {
+ if (f_read(&self->file->fp, *buffer, num_bytes_to_load, &length_read) != FR_OK || length_read != num_bytes_to_load) {
return GET_BUFFER_ERROR;
}
self->bytes_remaining -= length_read;
diff --git a/shared-module/audioio/WaveFile.h b/shared-module/audiocore/WaveFile.h
index 75a46c03b..3eecbf15c 100644
--- a/shared-module/audioio/WaveFile.h
+++ b/shared-module/audiocore/WaveFile.h
@@ -27,9 +27,10 @@
#ifndef MICROPY_INCLUDED_SHARED_MODULE_AUDIOIO_WAVEFILE_H
#define MICROPY_INCLUDED_SHARED_MODULE_AUDIOIO_WAVEFILE_H
+#include "extmod/vfs_fat.h"
#include "py/obj.h"
-#include "shared-module/audioio/__init__.h"
+#include "shared-module/audiocore/__init__.h"
typedef struct {
mp_obj_base_t base;
@@ -44,7 +45,7 @@ typedef struct {
uint32_t bytes_remaining;
uint8_t channel_count;
- uint16_t sample_rate;
+ uint32_t sample_rate;
uint32_t len;
pyb_file_obj_t* file;
diff --git a/shared-module/audiocore/__init__.c b/shared-module/audiocore/__init__.c
new file mode 100644
index 000000000..ac9d41b60
--- /dev/null
+++ b/shared-module/audiocore/__init__.c
@@ -0,0 +1,72 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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 "shared-module/audioio/__init__.h"
+
+#include "py/obj.h"
+#include "shared-bindings/audiocore/RawSample.h"
+#include "shared-bindings/audiocore/WaveFile.h"
+#include "shared-module/audiocore/RawSample.h"
+#include "shared-module/audiocore/WaveFile.h"
+
+#include "shared-bindings/audiomixer/Mixer.h"
+#include "shared-module/audiomixer/Mixer.h"
+
+uint32_t audiosample_sample_rate(mp_obj_t sample_obj) {
+ const audiosample_p_t *proto = mp_proto_get_or_throw(MP_QSTR_protocol_audiosample, sample_obj);
+ return proto->sample_rate(MP_OBJ_TO_PTR(sample_obj));
+}
+
+uint8_t audiosample_bits_per_sample(mp_obj_t sample_obj) {
+ const audiosample_p_t *proto = mp_proto_get_or_throw(MP_QSTR_protocol_audiosample, sample_obj);
+ return proto->bits_per_sample(MP_OBJ_TO_PTR(sample_obj));
+}
+
+uint8_t audiosample_channel_count(mp_obj_t sample_obj) {
+ const audiosample_p_t *proto = mp_proto_get_or_throw(MP_QSTR_protocol_audiosample, sample_obj);
+ return proto->channel_count(MP_OBJ_TO_PTR(sample_obj));
+}
+
+void audiosample_reset_buffer(mp_obj_t sample_obj, bool single_channel, uint8_t audio_channel) {
+ const audiosample_p_t *proto = mp_proto_get_or_throw(MP_QSTR_protocol_audiosample, sample_obj);
+ proto->reset_buffer(MP_OBJ_TO_PTR(sample_obj), single_channel, audio_channel);
+}
+
+audioio_get_buffer_result_t audiosample_get_buffer(mp_obj_t sample_obj,
+ bool single_channel,
+ uint8_t channel,
+ uint8_t** buffer, uint32_t* buffer_length) {
+ const audiosample_p_t *proto = mp_proto_get_or_throw(MP_QSTR_protocol_audiosample, sample_obj);
+ return proto->get_buffer(MP_OBJ_TO_PTR(sample_obj), single_channel, channel, buffer, buffer_length);
+}
+
+void audiosample_get_buffer_structure(mp_obj_t sample_obj, bool single_channel,
+ bool* single_buffer, bool* samples_signed,
+ uint32_t* max_buffer_length, uint8_t* spacing) {
+ const audiosample_p_t *proto = mp_proto_get_or_throw(MP_QSTR_protocol_audiosample, sample_obj);
+ proto->get_buffer_structure(MP_OBJ_TO_PTR(sample_obj), single_channel, single_buffer,
+ samples_signed, max_buffer_length, spacing);
+}
diff --git a/shared-module/audiocore/__init__.h b/shared-module/audiocore/__init__.h
new file mode 100644
index 000000000..7a56454b8
--- /dev/null
+++ b/shared-module/audiocore/__init__.h
@@ -0,0 +1,77 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Dan Halbert 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_SHARED_MODULE_AUDIOCORE__INIT__H
+#define MICROPY_INCLUDED_SHARED_MODULE_AUDIOCORE__INIT__H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "py/obj.h"
+#include "py/proto.h"
+
+typedef enum {
+ GET_BUFFER_DONE, // No more data to read
+ GET_BUFFER_MORE_DATA, // More data to read.
+ GET_BUFFER_ERROR, // Error while reading data.
+} audioio_get_buffer_result_t;
+
+typedef uint32_t (*audiosample_sample_rate_fun)(mp_obj_t);
+typedef uint8_t (*audiosample_bits_per_sample_fun)(mp_obj_t);
+typedef uint8_t (*audiosample_channel_count_fun)(mp_obj_t);
+typedef void (*audiosample_reset_buffer_fun)(mp_obj_t,
+ bool single_channel, uint8_t audio_channel);
+typedef audioio_get_buffer_result_t (*audiosample_get_buffer_fun)(mp_obj_t,
+ bool single_channel, uint8_t channel, uint8_t** buffer,
+ uint32_t* buffer_length);
+typedef void (*audiosample_get_buffer_structure_fun)(mp_obj_t,
+ bool single_channel, bool* single_buffer,
+ bool* samples_signed, uint32_t *max_buffer_length,
+ uint8_t* spacing);
+
+typedef struct _audiosample_p_t {
+ MP_PROTOCOL_HEAD // MP_QSTR_protocol_audiosample
+ audiosample_sample_rate_fun sample_rate;
+ audiosample_bits_per_sample_fun bits_per_sample;
+ audiosample_channel_count_fun channel_count;
+ audiosample_reset_buffer_fun reset_buffer;
+ audiosample_get_buffer_fun get_buffer;
+ audiosample_get_buffer_structure_fun get_buffer_structure;
+} audiosample_p_t;
+
+uint32_t audiosample_sample_rate(mp_obj_t sample_obj);
+uint8_t audiosample_bits_per_sample(mp_obj_t sample_obj);
+uint8_t audiosample_channel_count(mp_obj_t sample_obj);
+void audiosample_reset_buffer(mp_obj_t sample_obj, bool single_channel, uint8_t audio_channel);
+audioio_get_buffer_result_t audiosample_get_buffer(mp_obj_t sample_obj,
+ bool single_channel,
+ uint8_t channel,
+ uint8_t** buffer, uint32_t* buffer_length);
+void audiosample_get_buffer_structure(mp_obj_t sample_obj, bool single_channel,
+ bool* single_buffer, bool* samples_signed,
+ uint32_t* max_buffer_length, uint8_t* spacing);
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_AUDIOCORE__INIT__H
diff --git a/shared-module/audioio/Mixer.c b/shared-module/audioio/Mixer.c
deleted file mode 100644
index 8020a621e..000000000
--- a/shared-module/audioio/Mixer.c
+++ /dev/null
@@ -1,341 +0,0 @@
-/*
- * This file is part of the Micro Python project, http://micropython.org/
- *
- * The MIT License (MIT)
- *
- * Copyright (c) 2018 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 "shared-bindings/audioio/Mixer.h"
-
-#include <stdint.h>
-
-#include "py/runtime.h"
-#include "shared-module/audioio/__init__.h"
-#include "shared-module/audioio/RawSample.h"
-
-void common_hal_audioio_mixer_construct(audioio_mixer_obj_t* self,
- uint8_t voice_count,
- uint32_t buffer_size,
- uint8_t bits_per_sample,
- bool samples_signed,
- uint8_t channel_count,
- uint32_t sample_rate) {
- self->len = buffer_size / 2 / sizeof(uint32_t) * sizeof(uint32_t);
-
- self->first_buffer = m_malloc(self->len, false);
- if (self->first_buffer == NULL) {
- common_hal_audioio_mixer_deinit(self);
- mp_raise_msg(&mp_type_MemoryError, translate("Couldn't allocate first buffer"));
- }
-
- self->second_buffer = m_malloc(self->len, false);
- if (self->second_buffer == NULL) {
- common_hal_audioio_mixer_deinit(self);
- mp_raise_msg(&mp_type_MemoryError, translate("Couldn't allocate second buffer"));
- }
-
- self->bits_per_sample = bits_per_sample;
- self->samples_signed = samples_signed;
- self->channel_count = channel_count;
- self->sample_rate = sample_rate;
- self->voice_count = voice_count;
-
- for (uint8_t i = 0; i < self->voice_count; i++) {
- self->voice[i].sample = NULL;
- }
-}
-
-void common_hal_audioio_mixer_deinit(audioio_mixer_obj_t* self) {
- self->first_buffer = NULL;
- self->second_buffer = NULL;
-}
-
-bool common_hal_audioio_mixer_deinited(audioio_mixer_obj_t* self) {
- return self->first_buffer == NULL;
-}
-
-uint32_t common_hal_audioio_mixer_get_sample_rate(audioio_mixer_obj_t* self) {
- return self->sample_rate;
-}
-
-void common_hal_audioio_mixer_play(audioio_mixer_obj_t* self, mp_obj_t sample, uint8_t v, bool loop) {
- if (v >= self->voice_count) {
- mp_raise_ValueError(translate("Voice index too high"));
- }
- if (audiosample_sample_rate(sample) != self->sample_rate) {
- mp_raise_ValueError(translate("The sample's sample rate does not match the mixer's"));
- }
- if (audiosample_channel_count(sample) != self->channel_count) {
- mp_raise_ValueError(translate("The sample's channel count does not match the mixer's"));
- }
- if (audiosample_bits_per_sample(sample) != self->bits_per_sample) {
- mp_raise_ValueError(translate("The sample's bits_per_sample does not match the mixer's"));
- }
- bool single_buffer;
- bool samples_signed;
- uint32_t max_buffer_length;
- uint8_t spacing;
- audiosample_get_buffer_structure(sample, false, &single_buffer, &samples_signed,
- &max_buffer_length, &spacing);
- if (samples_signed != self->samples_signed) {
- mp_raise_ValueError(translate("The sample's signedness does not match the mixer's"));
- }
- audioio_mixer_voice_t* voice = &self->voice[v];
- voice->sample = sample;
- voice->loop = loop;
-
- audiosample_reset_buffer(sample, false, 0);
- audioio_get_buffer_result_t result = audiosample_get_buffer(sample, false, 0, (uint8_t**) &voice->remaining_buffer, &voice->buffer_length);
- // Track length in terms of words.
- voice->buffer_length /= sizeof(uint32_t);
- voice->more_data = result == GET_BUFFER_MORE_DATA;
-}
-
-void common_hal_audioio_mixer_stop_voice(audioio_mixer_obj_t* self, uint8_t voice) {
- self->voice[voice].sample = NULL;
-}
-
-bool common_hal_audioio_mixer_get_playing(audioio_mixer_obj_t* self) {
- for (int32_t v = 0; v < self->voice_count; v++) {
- if (self->voice[v].sample != NULL) {
- return true;
- }
- }
- return false;
-}
-
-void audioio_mixer_reset_buffer(audioio_mixer_obj_t* self,
- bool single_channel,
- uint8_t channel) {
- for (int32_t i = 0; i < self->voice_count; i++) {
- self->voice[i].sample = NULL;
- }
-}
-
-uint32_t add8signed(uint32_t a, uint32_t b) {
- #if (defined (__ARM_FEATURE_DSP) && (__ARM_FEATURE_DSP == 1))
- return __QADD8(a, b);
- #else
- uint32_t result = 0;
- for (int8_t i = 0; i < 4; i++) {
- int8_t ai = a >> (sizeof(int8_t) * 8 * i);
- int8_t bi = b >> (sizeof(int8_t) * 8 * i);
- int32_t intermediate = (int32_t) ai + bi;
- if (intermediate > CHAR_MAX) {
- intermediate = CHAR_MAX;
- } else if (intermediate < CHAR_MIN) {
- //intermediate = CHAR_MIN;
- }
- result |= (((uint32_t) intermediate) & 0xff) << (sizeof(int8_t) * 8 * i);
- }
- return result;
- #endif
-}
-
-uint32_t add8unsigned(uint32_t a, uint32_t b) {
- #if (defined (__ARM_FEATURE_DSP) && (__ARM_FEATURE_DSP == 1))
- // Subtract out the DC offset, add and then shift back.
- a = __USUB8(a, 0x80808080);
- b = __USUB8(b, 0x80808080);
- uint32_t sum = __QADD8(a, b);
- return __UADD8(sum, 0x80808080);
- #else
- uint32_t result = 0;
- for (int8_t i = 0; i < 4; i++) {
- int8_t ai = (a >> (sizeof(uint8_t) * 8 * i)) - 128;
- int8_t bi = (b >> (sizeof(uint8_t) * 8 * i)) - 128;
- int32_t intermediate = (int32_t) ai + bi;
- if (intermediate > UCHAR_MAX) {
- intermediate = UCHAR_MAX;
- }
- result |= ((uint8_t) intermediate + 128) << (sizeof(uint8_t) * 8 * i);
- }
- return result;
- #endif
-}
-
-uint32_t add16signed(uint32_t a, uint32_t b) {
- #if (defined (__ARM_FEATURE_DSP) && (__ARM_FEATURE_DSP == 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
-}
-
-uint32_t add16unsigned(uint32_t a, uint32_t b) {
- #if (defined (__ARM_FEATURE_DSP) && (__ARM_FEATURE_DSP == 1))
- // Subtract out the DC offset, add and then shift back.
- a = __USUB16(a, 0x80008000);
- b = __USUB16(b, 0x80008000);
- uint32_t sum = __QADD16(a, b);
- return __UADD16(sum, 0x80008000);
- #else
- uint32_t result = 0;
- for (int8_t i = 0; i < 2; i++) {
- int16_t ai = (a >> (sizeof(uint16_t) * 8 * i)) - 0x8000;
- int16_t bi = (b >> (sizeof(uint16_t) * 8 * i)) - 0x8000;
- int32_t intermediate = (int32_t) ai + bi;
- if (intermediate > USHRT_MAX) {
- intermediate = USHRT_MAX;
- }
- result |= ((uint16_t) intermediate + 0x8000) << (sizeof(int16_t) * 8 * i);
- }
- return result;
- #endif
-}
-
-audioio_get_buffer_result_t audioio_mixer_get_buffer(audioio_mixer_obj_t* self,
- bool single_channel,
- uint8_t channel,
- uint8_t** buffer,
- uint32_t* buffer_length) {
- if (!single_channel) {
- channel = 0;
- }
-
- uint32_t channel_read_count = self->left_read_count;
- if (channel == 1) {
- channel_read_count = self->right_read_count;
- }
- *buffer_length = self->len;
-
- bool need_more_data = self->read_count == channel_read_count;
- if (need_more_data) {
- uint32_t* word_buffer;
- if (self->use_first_buffer) {
- *buffer = (uint8_t*) self->first_buffer;
- word_buffer = self->first_buffer;
- } else {
- *buffer = (uint8_t*) self->second_buffer;
- word_buffer = self->second_buffer;
- }
- self->use_first_buffer = !self->use_first_buffer;
- bool voices_active = false;
- for (int32_t v = 0; v < self->voice_count; v++) {
- audioio_mixer_voice_t* voice = &self->voice[v];
-
- uint32_t j = 0;
- bool voice_done = voice->sample == NULL;
- for (uint32_t i = 0; i < self->len / sizeof(uint32_t); i++) {
- if (!voice_done && j >= voice->buffer_length) {
- if (!voice->more_data) {
- if (voice->loop) {
- audiosample_reset_buffer(voice->sample, false, 0);
- } else {
- voice->sample = NULL;
- voice_done = true;
- }
- }
- if (!voice_done) {
- // Load another buffer
- audioio_get_buffer_result_t result = audiosample_get_buffer(voice->sample, false, 0, (uint8_t**) &voice->remaining_buffer, &voice->buffer_length);
- // Track length in terms of words.
- voice->buffer_length /= sizeof(uint32_t);
- voice->more_data = result == GET_BUFFER_MORE_DATA;
- j = 0;
- }
- }
- // First active voice gets copied over verbatim.
- uint32_t sample_value;
- if (voice_done) {
- // Exit early if another voice already set all samples once.
- if (voices_active) {
- continue;
- }
- sample_value = 0;
- if (!self->samples_signed) {
- if (self->bits_per_sample == 8) {
- sample_value = 0x7f7f7f7f;
- } else {
- sample_value = 0x7fff7fff;
- }
- }
- } else {
- sample_value = voice->remaining_buffer[j];
- }
-
- if (!voices_active) {
- word_buffer[i] = sample_value;
- } else {
- if (self->bits_per_sample == 8) {
- if (self->samples_signed) {
- word_buffer[i] = add8signed(word_buffer[i], sample_value);
- } else {
- word_buffer[i] = add8unsigned(word_buffer[i], sample_value);
- }
- } else {
- if (self->samples_signed) {
- word_buffer[i] = add16signed(word_buffer[i], sample_value);
- } else {
- word_buffer[i] = add16unsigned(word_buffer[i], sample_value);
- }
- }
- }
- j++;
- }
- voice->buffer_length -= j;
- voice->remaining_buffer += j;
-
- voices_active = true;
- }
-
- self->read_count += 1;
- } else if (!self->use_first_buffer) {
- *buffer = (uint8_t*) self->first_buffer;
- } else {
- *buffer = (uint8_t*) self->second_buffer;
- }
-
-
- if (channel == 0) {
- self->left_read_count += 1;
- } else if (channel == 1) {
- self->right_read_count += 1;
- *buffer = *buffer + self->bits_per_sample / 8;
- }
- return GET_BUFFER_MORE_DATA;
-}
-
-void audioio_mixer_get_buffer_structure(audioio_mixer_obj_t* self, bool single_channel,
- bool* single_buffer, bool* samples_signed,
- uint32_t* max_buffer_length, uint8_t* spacing) {
- *single_buffer = false;
- *samples_signed = self->samples_signed;
- *max_buffer_length = self->len;
- if (single_channel) {
- *spacing = self->channel_count;
- } else {
- *spacing = 1;
- }
-}
diff --git a/shared-module/audioio/__init__.c b/shared-module/audioio/__init__.c
index b87b06a83..e69de29bb 100644
--- a/shared-module/audioio/__init__.c
+++ b/shared-module/audioio/__init__.c
@@ -1,125 +0,0 @@
-/*
- * This file is part of the MicroPython project, http://micropython.org/
- *
- * The MIT License (MIT)
- *
- * Copyright (c) 2018 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 "shared-module/audioio/__init__.h"
-
-#include "py/obj.h"
-#include "shared-bindings/audioio/Mixer.h"
-#include "shared-bindings/audioio/RawSample.h"
-#include "shared-bindings/audioio/WaveFile.h"
-#include "shared-module/audioio/Mixer.h"
-#include "shared-module/audioio/RawSample.h"
-#include "shared-module/audioio/WaveFile.h"
-
-uint32_t audiosample_sample_rate(mp_obj_t sample_obj) {
- if (MP_OBJ_IS_TYPE(sample_obj, &audioio_rawsample_type)) {
- audioio_rawsample_obj_t* sample = MP_OBJ_TO_PTR(sample_obj);
- return sample->sample_rate;
- } else if (MP_OBJ_IS_TYPE(sample_obj, &audioio_wavefile_type)) {
- audioio_wavefile_obj_t* file = MP_OBJ_TO_PTR(sample_obj);
- return file->sample_rate;
- } else if (MP_OBJ_IS_TYPE(sample_obj, &audioio_mixer_type)) {
- audioio_mixer_obj_t* mixer = MP_OBJ_TO_PTR(sample_obj);
- return mixer->sample_rate;
- }
- return 16000;
-}
-
-uint8_t audiosample_bits_per_sample(mp_obj_t sample_obj) {
- if (MP_OBJ_IS_TYPE(sample_obj, &audioio_rawsample_type)) {
- audioio_rawsample_obj_t* sample = MP_OBJ_TO_PTR(sample_obj);
- return sample->bits_per_sample;
- } else if (MP_OBJ_IS_TYPE(sample_obj, &audioio_wavefile_type)) {
- audioio_wavefile_obj_t* file = MP_OBJ_TO_PTR(sample_obj);
- return file->bits_per_sample;
- } else if (MP_OBJ_IS_TYPE(sample_obj, &audioio_mixer_type)) {
- audioio_mixer_obj_t* mixer = MP_OBJ_TO_PTR(sample_obj);
- return mixer->bits_per_sample;
- }
- return 8;
-}
-
-uint8_t audiosample_channel_count(mp_obj_t sample_obj) {
- if (MP_OBJ_IS_TYPE(sample_obj, &audioio_rawsample_type)) {
- audioio_rawsample_obj_t* sample = MP_OBJ_TO_PTR(sample_obj);
- return sample->channel_count;
- } else if (MP_OBJ_IS_TYPE(sample_obj, &audioio_wavefile_type)) {
- audioio_wavefile_obj_t* file = MP_OBJ_TO_PTR(sample_obj);
- return file->channel_count;
- } else if (MP_OBJ_IS_TYPE(sample_obj, &audioio_mixer_type)) {
- audioio_mixer_obj_t* mixer = MP_OBJ_TO_PTR(sample_obj);
- return mixer->channel_count;
- }
- return 1;
-}
-
-void audiosample_reset_buffer(mp_obj_t sample_obj, bool single_channel, uint8_t audio_channel) {
- if (MP_OBJ_IS_TYPE(sample_obj, &audioio_rawsample_type)) {
- audioio_rawsample_obj_t* sample = MP_OBJ_TO_PTR(sample_obj);
- audioio_rawsample_reset_buffer(sample, single_channel, audio_channel);
- } else if (MP_OBJ_IS_TYPE(sample_obj, &audioio_wavefile_type)) {
- audioio_wavefile_obj_t* file = MP_OBJ_TO_PTR(sample_obj);
- audioio_wavefile_reset_buffer(file, single_channel, audio_channel);
- } else if (MP_OBJ_IS_TYPE(sample_obj, &audioio_mixer_type)) {
- audioio_mixer_obj_t* file = MP_OBJ_TO_PTR(sample_obj);
- audioio_mixer_reset_buffer(file, single_channel, audio_channel);
- }
-}
-
-audioio_get_buffer_result_t audiosample_get_buffer(mp_obj_t sample_obj,
- bool single_channel,
- uint8_t channel,
- uint8_t** buffer, uint32_t* buffer_length) {
- if (MP_OBJ_IS_TYPE(sample_obj, &audioio_rawsample_type)) {
- audioio_rawsample_obj_t* sample = MP_OBJ_TO_PTR(sample_obj);
- return audioio_rawsample_get_buffer(sample, single_channel, channel, buffer, buffer_length);
- } else if (MP_OBJ_IS_TYPE(sample_obj, &audioio_wavefile_type)) {
- audioio_wavefile_obj_t* file = MP_OBJ_TO_PTR(sample_obj);
- return audioio_wavefile_get_buffer(file, single_channel, channel, buffer, buffer_length);
- } else if (MP_OBJ_IS_TYPE(sample_obj, &audioio_mixer_type)) {
- audioio_mixer_obj_t* file = MP_OBJ_TO_PTR(sample_obj);
- return audioio_mixer_get_buffer(file, single_channel, channel, buffer, buffer_length);
- }
- return GET_BUFFER_DONE;
-}
-
-void audiosample_get_buffer_structure(mp_obj_t sample_obj, bool single_channel,
- bool* single_buffer, bool* samples_signed,
- uint32_t* max_buffer_length, uint8_t* spacing) {
- if (MP_OBJ_IS_TYPE(sample_obj, &audioio_rawsample_type)) {
- audioio_rawsample_obj_t* sample = MP_OBJ_TO_PTR(sample_obj);
- audioio_rawsample_get_buffer_structure(sample, single_channel, single_buffer,
- samples_signed, max_buffer_length, spacing);
- } else if (MP_OBJ_IS_TYPE(sample_obj, &audioio_wavefile_type)) {
- audioio_wavefile_obj_t* file = MP_OBJ_TO_PTR(sample_obj);
- audioio_wavefile_get_buffer_structure(file, single_channel, single_buffer, samples_signed,
- max_buffer_length, spacing);
- } else if (MP_OBJ_IS_TYPE(sample_obj, &audioio_mixer_type)) {
- audioio_mixer_obj_t* file = MP_OBJ_TO_PTR(sample_obj);
- audioio_mixer_get_buffer_structure(file, single_channel, single_buffer, samples_signed,
- max_buffer_length, spacing);
- }
-}
diff --git a/shared-module/audioio/__init__.h b/shared-module/audioio/__init__.h
index c805f3116..53b2d4a16 100644
--- a/shared-module/audioio/__init__.h
+++ b/shared-module/audioio/__init__.h
@@ -27,27 +27,6 @@
#ifndef MICROPY_INCLUDED_SHARED_MODULE_AUDIOIO__INIT__H
#define MICROPY_INCLUDED_SHARED_MODULE_AUDIOIO__INIT__H
-#include <stdbool.h>
-#include <stdint.h>
-
-#include "py/obj.h"
-
-typedef enum {
- GET_BUFFER_DONE, // No more data to read
- GET_BUFFER_MORE_DATA, // More data to read.
- GET_BUFFER_ERROR, // Error while reading data.
-} audioio_get_buffer_result_t;
-
-uint32_t audiosample_sample_rate(mp_obj_t sample_obj);
-uint8_t audiosample_bits_per_sample(mp_obj_t sample_obj);
-uint8_t audiosample_channel_count(mp_obj_t sample_obj);
-void audiosample_reset_buffer(mp_obj_t sample_obj, bool single_channel, uint8_t audio_channel);
-audioio_get_buffer_result_t audiosample_get_buffer(mp_obj_t sample_obj,
- bool single_channel,
- uint8_t channel,
- uint8_t** buffer, uint32_t* buffer_length);
-void audiosample_get_buffer_structure(mp_obj_t sample_obj, bool single_channel,
- bool* single_buffer, bool* samples_signed,
- uint32_t* max_buffer_length, uint8_t* spacing);
+#include "shared-module/audiocore/__init__.h"
#endif // MICROPY_INCLUDED_SHARED_MODULE_AUDIOIO__INIT__H
diff --git a/shared-module/audiomixer/Mixer.c b/shared-module/audiomixer/Mixer.c
new file mode 100644
index 000000000..6c1ba1973
--- /dev/null
+++ b/shared-module/audiomixer/Mixer.c
@@ -0,0 +1,320 @@
+/*
+ * This file is part of the Micro Python project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries
+ * 2018 DeanM for Adafruit Industries
+ * 2019 Michael Schroeder
+ *
+ * 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 "shared-bindings/audiomixer/Mixer.h"
+#include "shared-bindings/audiomixer/MixerVoice.h"
+
+#include <stdint.h>
+
+#include "py/runtime.h"
+#include "shared-module/audiocore/__init__.h"
+#include "shared-module/audiocore/RawSample.h"
+
+void common_hal_audiomixer_mixer_construct(audiomixer_mixer_obj_t* self,
+ uint8_t voice_count,
+ uint32_t buffer_size,
+ uint8_t bits_per_sample,
+ bool samples_signed,
+ uint8_t channel_count,
+ uint32_t sample_rate) {
+ self->len = buffer_size / 2 / sizeof(uint32_t) * sizeof(uint32_t);
+
+ self->first_buffer = m_malloc(self->len, false);
+ if (self->first_buffer == NULL) {
+ common_hal_audiomixer_mixer_deinit(self);
+ mp_raise_msg(&mp_type_MemoryError, translate("Couldn't allocate first buffer"));
+ }
+
+ self->second_buffer = m_malloc(self->len, false);
+ if (self->second_buffer == NULL) {
+ common_hal_audiomixer_mixer_deinit(self);
+ mp_raise_msg(&mp_type_MemoryError, translate("Couldn't allocate second buffer"));
+ }
+
+ self->bits_per_sample = bits_per_sample;
+ self->samples_signed = samples_signed;
+ self->channel_count = channel_count;
+ self->sample_rate = sample_rate;
+ self->voice_count = voice_count;
+}
+
+void common_hal_audiomixer_mixer_deinit(audiomixer_mixer_obj_t* self) {
+ self->first_buffer = NULL;
+ self->second_buffer = NULL;
+}
+
+bool common_hal_audiomixer_mixer_deinited(audiomixer_mixer_obj_t* self) {
+ return self->first_buffer == NULL;
+}
+
+uint32_t common_hal_audiomixer_mixer_get_sample_rate(audiomixer_mixer_obj_t* self) {
+ return self->sample_rate;
+}
+
+uint8_t common_hal_audiomixer_mixer_get_channel_count(audiomixer_mixer_obj_t* self) {
+ return self->channel_count;
+}
+
+uint8_t common_hal_audiomixer_mixer_get_bits_per_sample(audiomixer_mixer_obj_t* self) {
+ return self->bits_per_sample;
+}
+
+bool common_hal_audiomixer_mixer_get_playing(audiomixer_mixer_obj_t* self) {
+ for (uint8_t v = 0; v < self->voice_count; v++) {
+ if (common_hal_audiomixer_mixervoice_get_playing(MP_OBJ_TO_PTR(self->voice[v]))) {
+ return true;
+ }
+ }
+ return false;
+}
+
+void audiomixer_mixer_reset_buffer(audiomixer_mixer_obj_t* self,
+ bool single_channel,
+ uint8_t channel) {
+ for (uint8_t i = 0; i < self->voice_count; i++) {
+ common_hal_audiomixer_mixervoice_stop(self->voice[i]);
+ }
+}
+
+__attribute__((always_inline))
+static inline uint32_t add16signed(uint32_t a, uint32_t b) {
+ return __QADD16(a, b);
+}
+
+__attribute__((always_inline))
+static inline uint32_t mult16signed(uint32_t val, int32_t mul) {
+ mul <<= 16;
+ int32_t hi, lo;
+ enum { bits = 16 }; // saturate to 16 bits
+ enum { shift = 15 }; // shift is done automatically
+ asm volatile("smulwb %0, %1, %2" : "=r" (lo) : "r" (mul), "r" (val));
+ asm volatile("smulwt %0, %1, %2" : "=r" (hi) : "r" (mul), "r" (val));
+ asm volatile("ssat %0, %1, %2, asr %3" : "=r" (lo) : "I" (bits), "r" (lo), "I" (shift));
+ 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;
+}
+
+static inline uint32_t tounsigned8(uint32_t val) {
+ return __UADD8(val, 0x80808080);
+}
+
+static inline uint32_t tounsigned16(uint32_t val) {
+ return __UADD16(val, 0x80008000);
+}
+
+static inline uint32_t tosigned16(uint32_t val) {
+ return __UADD16(val, 0x80008000);
+}
+
+static inline uint32_t unpack8(uint16_t val) {
+ return ((val & 0xff00) << 16) | ((val & 0x00ff) << 8);
+}
+
+static inline uint32_t pack8(uint32_t val) {
+ return ((val & 0xff000000) >> 16) | ((val & 0xff00) >> 8);
+}
+
+static void mix_down_one_voice(audiomixer_mixer_obj_t* self,
+ audiomixer_mixervoice_obj_t* voice, bool voices_active,
+ uint32_t* word_buffer, uint32_t length) {
+ while (length != 0) {
+ if (voice->buffer_length == 0) {
+ if (!voice->more_data) {
+ if (voice->loop) {
+ audiosample_reset_buffer(voice->sample, false, 0);
+ } else {
+ voice->sample = NULL;
+ break;
+ }
+ }
+ if (voice->sample) {
+ // Load another buffer
+ audioio_get_buffer_result_t result = audiosample_get_buffer(voice->sample, false, 0, (uint8_t**) &voice->remaining_buffer, &voice->buffer_length);
+ // Track length in terms of words.
+ voice->buffer_length /= sizeof(uint32_t);
+ voice->more_data = result == GET_BUFFER_MORE_DATA;
+ }
+ }
+
+ uint32_t n = MIN(voice->buffer_length, length);
+ uint32_t *src = voice->remaining_buffer;
+ uint16_t level = voice->level;
+
+ // First active voice gets copied over verbatim.
+ if (!voices_active) {
+ if (MP_LIKELY(self->bits_per_sample == 16)) {
+ if (MP_LIKELY(self->samples_signed)) {
+ for (uint32_t i = 0; i<n; i++) {
+ uint32_t v = src[i];
+ word_buffer[i] = mult16signed(v, level);
+ }
+ } else {
+ for (uint32_t i = 0; i<n; i++) {
+ uint32_t v = src[i];
+ v = tosigned16(v);
+ word_buffer[i] = mult16signed(v, level);
+ }
+ }
+ } else {
+ uint16_t *hword_buffer = (uint16_t*)word_buffer;
+ uint16_t *hsrc = (uint16_t*)src;
+ for (uint32_t i = 0; i<n*2; i++) {
+ uint32_t word = unpack8(hsrc[i]);
+ if (MP_LIKELY(!self->samples_signed)) {
+ word = tosigned16(word);
+ }
+ word = mult16signed(word, level);
+ hword_buffer[i] = pack8(word);
+ }
+ }
+ } else {
+ if (MP_LIKELY(self->bits_per_sample == 16)) {
+ if (MP_LIKELY(self->samples_signed)) {
+ for (uint32_t i = 0; i<n; i++) {
+ uint32_t word = src[i];
+ word_buffer[i] = add16signed(mult16signed(word, level), word_buffer[i]);
+ }
+ } else {
+ for (uint32_t i = 0; i<n; i++) {
+ uint32_t word = src[i];
+ word = tosigned16(word);
+ word_buffer[i] = add16signed(mult16signed(word, level), word_buffer[i]);
+ }
+ }
+ } else {
+ uint16_t *hword_buffer = (uint16_t*)word_buffer;
+ uint16_t *hsrc = (uint16_t*)src;
+ for (uint32_t i = 0; i<n*2; i++) {
+ uint32_t word = unpack8(hsrc[i]);
+ if (MP_LIKELY(!self->samples_signed)) {
+ word = tosigned16(word);
+ }
+ word = mult16signed(word, level);
+ word = add16signed(word, unpack8(hword_buffer[i]));
+ hword_buffer[i] = pack8(word);
+ }
+ }
+ }
+ length -= n;
+ word_buffer += n;
+ voice->remaining_buffer += n;
+ voice->buffer_length -= n;
+ }
+
+ if (length && !voices_active) {
+ for (uint32_t i = 0; i<length; i++) {
+ word_buffer[i] = 0;
+ }
+ }
+}
+
+audioio_get_buffer_result_t audiomixer_mixer_get_buffer(audiomixer_mixer_obj_t* self,
+ bool single_channel,
+ uint8_t channel,
+ uint8_t** buffer,
+ uint32_t* buffer_length) {
+ if (!single_channel) {
+ channel = 0;
+ }
+
+ uint32_t channel_read_count = self->left_read_count;
+ if (channel == 1) {
+ channel_read_count = self->right_read_count;
+ }
+ *buffer_length = self->len;
+
+ bool need_more_data = self->read_count == channel_read_count;
+ if (need_more_data) {
+ uint32_t* word_buffer;
+ if (self->use_first_buffer) {
+ *buffer = (uint8_t*) self->first_buffer;
+ word_buffer = self->first_buffer;
+ } else {
+ *buffer = (uint8_t*) self->second_buffer;
+ word_buffer = self->second_buffer;
+ }
+ self->use_first_buffer = !self->use_first_buffer;
+ bool voices_active = false;
+ uint32_t length = self->len / sizeof(uint32_t);
+
+ for (int32_t v = 0; v < self->voice_count; v++) {
+ audiomixer_mixervoice_obj_t* voice = MP_OBJ_TO_PTR(self->voice[v]);
+ if(voice->sample) {
+ mix_down_one_voice(self, voice, voices_active, word_buffer, length);
+ voices_active = true;
+ }
+ }
+
+ if (!voices_active) {
+ for (uint32_t i = 0; i<length; i++) {
+ word_buffer[i] = 0;
+ }
+ }
+
+ if (!self->samples_signed) {
+ if (self->bits_per_sample == 16) {
+ for (uint32_t i = 0; i < length; i++) {
+ word_buffer[i] = tounsigned16(word_buffer[i]);
+ }
+ } else {
+ for (uint32_t i = 0; i < length; i++) {
+ word_buffer[i] = tounsigned8(word_buffer[i]);
+ }
+ }
+ }
+
+ self->read_count += 1;
+ } else if (!self->use_first_buffer) {
+ *buffer = (uint8_t*) self->first_buffer;
+ } else {
+ *buffer = (uint8_t*) self->second_buffer;
+ }
+
+
+ if (channel == 0) {
+ self->left_read_count += 1;
+ } else if (channel == 1) {
+ self->right_read_count += 1;
+ *buffer = *buffer + self->bits_per_sample / 8;
+ }
+ return GET_BUFFER_MORE_DATA;
+}
+
+void audiomixer_mixer_get_buffer_structure(audiomixer_mixer_obj_t* self, bool single_channel,
+ bool* single_buffer, bool* samples_signed,
+ uint32_t* max_buffer_length, uint8_t* spacing) {
+ *single_buffer = false;
+ *samples_signed = self->samples_signed;
+ *max_buffer_length = self->len;
+ if (single_channel) {
+ *spacing = self->channel_count;
+ } else {
+ *spacing = 1;
+ }
+}
diff --git a/shared-module/audioio/Mixer.h b/shared-module/audiomixer/Mixer.h
index 6a88fe0bd..ab4780efc 100644
--- a/shared-module/audioio/Mixer.h
+++ b/shared-module/audiomixer/Mixer.h
@@ -24,20 +24,13 @@
* THE SOFTWARE.
*/
-#ifndef MICROPY_INCLUDED_SHARED_MODULE_AUDIOIO_MIXER_H
-#define MICROPY_INCLUDED_SHARED_MODULE_AUDIOIO_MIXER_H
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_AUDIOMIXER_MIXER_H
+#define MICROPY_INCLUDED_SHARED_MODULE_AUDIOMIXER_MIXER_H
#include "py/obj.h"
+#include "py/objtuple.h"
-#include "shared-module/audioio/__init__.h"
-
-typedef struct {
- mp_obj_t sample;
- bool loop;
- bool more_data;
- uint32_t* remaining_buffer;
- uint32_t buffer_length;
-} audioio_mixer_voice_t;
+#include "shared-module/audiocore/__init__.h"
typedef struct {
mp_obj_base_t base;
@@ -55,21 +48,22 @@ typedef struct {
uint32_t right_read_count;
uint8_t voice_count;
- audioio_mixer_voice_t voice[];
-} audioio_mixer_obj_t;
+ mp_obj_tuple_t *voice_tuple;
+ mp_obj_t voice[];
+} audiomixer_mixer_obj_t;
// These are not available from Python because it may be called in an interrupt.
-void audioio_mixer_reset_buffer(audioio_mixer_obj_t* self,
+void audiomixer_mixer_reset_buffer(audiomixer_mixer_obj_t* self,
bool single_channel,
uint8_t channel);
-audioio_get_buffer_result_t audioio_mixer_get_buffer(audioio_mixer_obj_t* self,
+audioio_get_buffer_result_t audiomixer_mixer_get_buffer(audiomixer_mixer_obj_t* self,
bool single_channel,
uint8_t channel,
uint8_t** buffer,
uint32_t* buffer_length); // length in bytes
-void audioio_mixer_get_buffer_structure(audioio_mixer_obj_t* self, bool single_channel,
+void audiomixer_mixer_get_buffer_structure(audiomixer_mixer_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_AUDIOIO_MIXER_H
+#endif // MICROPY_INCLUDED_SHARED_MODULE_AUDIOMIXER_MIXER_H
diff --git a/shared-module/audiomixer/MixerVoice.c b/shared-module/audiomixer/MixerVoice.c
new file mode 100644
index 000000000..9be104afc
--- /dev/null
+++ b/shared-module/audiomixer/MixerVoice.c
@@ -0,0 +1,87 @@
+/*
+ * This file is part of the Micro Python project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 DeanM 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 "shared-bindings/audiomixer/Mixer.h"
+#include "shared-module/audiomixer/MixerVoice.h"
+
+#include <stdint.h>
+
+#include "py/runtime.h"
+#include "shared-module/audiomixer/__init__.h"
+#include "shared-module/audiocore/RawSample.h"
+
+void common_hal_audiomixer_mixervoice_construct(audiomixer_mixervoice_obj_t *self) {
+ self->sample = NULL;
+ self->level = 1 << 15;
+}
+
+void common_hal_audiomixer_mixervoice_set_parent(audiomixer_mixervoice_obj_t* self, audiomixer_mixer_obj_t *parent) {
+ self->parent = parent;
+}
+
+float common_hal_audiomixer_mixervoice_get_level(audiomixer_mixervoice_obj_t* self) {
+ return ((float) self->level / (1 << 15));
+}
+
+void common_hal_audiomixer_mixervoice_set_level(audiomixer_mixervoice_obj_t* self, float level) {
+ self->level = level * (1 << 15);
+}
+
+void common_hal_audiomixer_mixervoice_play(audiomixer_mixervoice_obj_t* self, mp_obj_t sample, bool loop) {
+ if (audiosample_sample_rate(sample) != self->parent->sample_rate) {
+ mp_raise_ValueError(translate("The sample's sample rate does not match the mixer's"));
+ }
+ if (audiosample_channel_count(sample) != self->parent->channel_count) {
+ mp_raise_ValueError(translate("The sample's channel count does not match the mixer's"));
+ }
+ if (audiosample_bits_per_sample(sample) != self->parent->bits_per_sample) {
+ mp_raise_ValueError(translate("The sample's bits_per_sample does not match the mixer's"));
+ }
+ bool single_buffer;
+ bool samples_signed;
+ uint32_t max_buffer_length;
+ uint8_t spacing;
+ audiosample_get_buffer_structure(sample, false, &single_buffer, &samples_signed,
+ &max_buffer_length, &spacing);
+ if (samples_signed != self->parent->samples_signed) {
+ mp_raise_ValueError(translate("The sample's signedness does not match the mixer's"));
+ }
+ self->sample = sample;
+ self->loop = loop;
+
+ audiosample_reset_buffer(sample, false, 0);
+ audioio_get_buffer_result_t result = audiosample_get_buffer(sample, false, 0, (uint8_t**) &self->remaining_buffer, &self->buffer_length);
+ // Track length in terms of words.
+ self->buffer_length /= sizeof(uint32_t);
+ self->more_data = result == GET_BUFFER_MORE_DATA;
+}
+
+bool common_hal_audiomixer_mixervoice_get_playing(audiomixer_mixervoice_obj_t* self) {
+ return self->sample != NULL;
+}
+
+void common_hal_audiomixer_mixervoice_stop(audiomixer_mixervoice_obj_t* self) {
+ self->sample = NULL;
+}
diff --git a/shared-module/audiomixer/MixerVoice.h b/shared-module/audiomixer/MixerVoice.h
new file mode 100644
index 000000000..a85316e3d
--- /dev/null
+++ b/shared-module/audiomixer/MixerVoice.h
@@ -0,0 +1,46 @@
+/*
+ * This file is part of the Micro Python project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 DeanM 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 SHARED_MODULE_AUDIOMIXER_MIXERVOICE_H_
+#define SHARED_MODULE_AUDIOMIXER_MIXERVOICE_H_
+
+#include "py/obj.h"
+
+#include "shared-module/audiomixer/__init__.h"
+#include "shared-module/audiomixer/Mixer.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ audiomixer_mixer_obj_t *parent;
+ mp_obj_t sample;
+ bool loop;
+ bool more_data;
+ uint32_t* remaining_buffer;
+ uint32_t buffer_length;
+ uint16_t level;
+} audiomixer_mixervoice_obj_t;
+
+
+#endif /* SHARED_MODULE_AUDIOMIXER_MIXERVOICE_H_ */
diff --git a/shared-module/audiomixer/__init__.c b/shared-module/audiomixer/__init__.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/shared-module/audiomixer/__init__.c
diff --git a/shared-module/audiomixer/__init__.h b/shared-module/audiomixer/__init__.h
new file mode 100644
index 000000000..35b731558
--- /dev/null
+++ b/shared-module/audiomixer/__init__.h
@@ -0,0 +1,32 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Dan Halbert 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_SHARED_MODULE_AUDIOMIXER__INIT__H
+#define MICROPY_INCLUDED_SHARED_MODULE_AUDIOMIXER__INIT__H
+
+#include "shared-module/audiocore/__init__.h"
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_AUDIOMIXER__INIT__H
diff --git a/shared-module/audiomp3/MP3Decoder.c b/shared-module/audiomp3/MP3Decoder.c
new file mode 100644
index 000000000..30357c616
--- /dev/null
+++ b/shared-module/audiomp3/MP3Decoder.c
@@ -0,0 +1,352 @@
+/*
+ * This file is part of the Micro Python project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries
+ * Copyright (c) 2019 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 "shared-bindings/audiomp3/MP3Decoder.h"
+
+#include <stdint.h>
+#include <string.h>
+#include <math.h>
+
+#include "py/mperrno.h"
+#include "py/runtime.h"
+
+#include "shared-module/audiomp3/MP3Decoder.h"
+#include "supervisor/shared/translate.h"
+#include "lib/mp3/src/mp3common.h"
+
+#define MAX_BUFFER_LEN (MAX_NSAMP * MAX_NGRAN * MAX_NCHAN * sizeof(int16_t))
+
+/** Fill the input buffer if it is less than half full.
+ *
+ * Returns true if the input buffer contains any useful data,
+ * false otherwise. (The input buffer will be padded to the end with
+ * 0 bytes, which do not interfere with MP3 decoding)
+ *
+ * Raises OSError if f_read fails.
+ *
+ * Sets self->eof if any read of the file returns 0 bytes
+ */
+STATIC bool mp3file_update_inbuf(audiomp3_mp3file_obj_t* self) {
+ // If buffer is over half full, do nothing
+ if (self->inbuf_offset < self->inbuf_length/2) return true;
+
+ // If we didn't previously reach the end of file, we can try reading now
+ if (!self->eof) {
+
+ // Move the unconsumed portion of the buffer to the start
+ uint8_t *end_of_buffer = self->inbuf + self->inbuf_length;
+ uint8_t *new_end_of_data = self->inbuf + self->inbuf_length - self->inbuf_offset;
+ memmove(self->inbuf, self->inbuf + self->inbuf_offset,
+ self->inbuf_length - self->inbuf_offset);
+ self->inbuf_offset = 0;
+
+ UINT to_read = end_of_buffer - new_end_of_data;
+ UINT bytes_read = 0;
+ memset(new_end_of_data, 0, to_read);
+ if (f_read(&self->file->fp, new_end_of_data, to_read, &bytes_read) != FR_OK) {
+ self->eof = true;
+ mp_raise_OSError(MP_EIO);
+ }
+
+ if (bytes_read == 0) {
+ self->eof = true;
+ }
+
+ if (to_read != bytes_read) {
+ new_end_of_data += bytes_read;
+ memset(new_end_of_data, 0, end_of_buffer - new_end_of_data);
+ }
+
+ }
+
+ // Return true iff there are at least some useful bytes in the buffer
+ return self->inbuf_offset < self->inbuf_length;
+}
+
+#define READ_PTR(self) (self->inbuf + self->inbuf_offset)
+#define BYTES_LEFT(self) (self->inbuf_length - self->inbuf_offset)
+#define CONSUME(self, n) (self->inbuf_offset += n)
+
+// http://id3.org/d3v2.3.0
+// http://id3.org/id3v2.3.0
+STATIC void mp3file_skip_id3v2(audiomp3_mp3file_obj_t* self) {
+ mp3file_update_inbuf(self);
+ if (BYTES_LEFT(self) < 10) {
+ return;
+ }
+ uint8_t *data = READ_PTR(self);
+ if (!(
+ data[0] == 'I' &&
+ data[1] == 'D' &&
+ data[2] == '3' &&
+ data[3] != 0xff &&
+ data[4] != 0xff &&
+ (data[5] & 0x1f) == 0 &&
+ (data[6] & 0x80) == 0 &&
+ (data[7] & 0x80) == 0 &&
+ (data[8] & 0x80) == 0 &&
+ (data[9] & 0x80) == 0)) {
+ return;
+ }
+ uint32_t size = (data[6] << 21) | (data[7] << 14) | (data[8] << 7) | (data[9]);
+ size += 10; // size excludes the "header" (but not the "extended header")
+ // First, deduct from size whatever is left in buffer
+ uint32_t to_consume = MIN(size, BYTES_LEFT(self));
+ CONSUME(self, to_consume);
+ size -= to_consume;
+
+ // Next, seek in the file after the header
+ f_lseek(&self->file->fp, f_tell(&self->file->fp) + size);
+ return;
+}
+
+/* If a sync word can be found, advance to it and return true. Otherwise,
+ * return false.
+ */
+STATIC bool mp3file_find_sync_word(audiomp3_mp3file_obj_t* self) {
+ do {
+ mp3file_update_inbuf(self);
+ int offset = MP3FindSyncWord(READ_PTR(self), BYTES_LEFT(self));
+ if (offset >= 0) {
+ CONSUME(self, offset);
+ mp3file_update_inbuf(self);
+ return true;
+ }
+ CONSUME(self, MAX(0, BYTES_LEFT(self) - 16));
+ } while (!self->eof);
+ return false;
+}
+
+STATIC bool mp3file_get_next_frame_info(audiomp3_mp3file_obj_t* self, MP3FrameInfo* fi) {
+ int err;
+ do {
+ err = MP3GetNextFrameInfo(self->decoder, fi, READ_PTR(self));
+ if (err == ERR_MP3_NONE) {
+ break;
+ }
+ CONSUME(self, 1);
+ mp3file_find_sync_word(self);
+ } while (!self->eof);
+ return err == ERR_MP3_NONE;
+}
+
+void common_hal_audiomp3_mp3file_construct(audiomp3_mp3file_obj_t* self,
+ pyb_file_obj_t* file,
+ uint8_t *buffer,
+ size_t buffer_size) {
+ // XXX Adafruit_MP3 uses a 2kB input buffer and two 4kB output buffers.
+ // for a whopping total of 10kB buffers (+mp3 decoder state and frame buffer)
+ // At 44kHz, that's 23ms of output audio data.
+ //
+ // We will choose a slightly different allocation strategy for the output:
+ // Make sure the buffers are sized exactly to match (a multiple of) the
+ // frame size; this is typically 2304 * 2 bytes, so a little bit bigger
+ // than the two 4kB output buffers, except that the alignment allows to
+ // never allocate that extra frame buffer.
+
+ self->inbuf_length = 2048;
+ self->inbuf_offset = self->inbuf_length;
+ self->inbuf = m_malloc(self->inbuf_length, false);
+ if (self->inbuf == NULL) {
+ common_hal_audiomp3_mp3file_deinit(self);
+ mp_raise_msg(&mp_type_MemoryError,
+ translate("Couldn't allocate input buffer"));
+ }
+ self->decoder = MP3InitDecoder();
+ if (self->decoder == NULL) {
+ common_hal_audiomp3_mp3file_deinit(self);
+ mp_raise_msg(&mp_type_MemoryError,
+ translate("Couldn't allocate decoder"));
+ }
+
+ if ((intptr_t)buffer & 1) {
+ buffer += 1; buffer_size -= 1;
+ }
+ if (buffer_size >= 2 * MAX_BUFFER_LEN) {
+ self->buffers[0] = (int16_t*)(void*)buffer;
+ self->buffers[1] = (int16_t*)(void*)(buffer + MAX_BUFFER_LEN);
+ } else {
+ self->buffers[0] = m_malloc(MAX_BUFFER_LEN, false);
+ if (self->buffers[0] == NULL) {
+ common_hal_audiomp3_mp3file_deinit(self);
+ mp_raise_msg(&mp_type_MemoryError,
+ translate("Couldn't allocate first buffer"));
+ }
+
+ self->buffers[1] = m_malloc(MAX_BUFFER_LEN, false);
+ if (self->buffers[1] == NULL) {
+ common_hal_audiomp3_mp3file_deinit(self);
+ mp_raise_msg(&mp_type_MemoryError,
+ translate("Couldn't allocate second buffer"));
+ }
+ }
+
+ common_hal_audiomp3_mp3file_set_file(self, file);
+}
+
+void common_hal_audiomp3_mp3file_set_file(audiomp3_mp3file_obj_t* self, pyb_file_obj_t* file) {
+ self->file = file;
+ f_lseek(&self->file->fp, 0);
+ self->inbuf_offset = self->inbuf_length;
+ self->eof = 0;
+ self->other_channel = -1;
+ mp3file_update_inbuf(self);
+ mp3file_find_sync_word(self);
+ // It **SHOULD** not be necessary to do this; the buffer should be filled
+ // with fresh content before it is returned by get_buffer(). The fact that
+ // this is necessary to avoid a glitch at the start of playback of a second
+ // track using the same decoder object means there's still a bug in
+ // get_buffer() that I didn't understand.
+ memset(self->buffers[0], 0, MAX_BUFFER_LEN);
+ memset(self->buffers[1], 0, MAX_BUFFER_LEN);
+ MP3FrameInfo fi;
+ if(!mp3file_get_next_frame_info(self, &fi)) {
+ mp_raise_msg(&mp_type_RuntimeError,
+ translate("Failed to parse MP3 file"));
+ }
+
+ self->sample_rate = fi.samprate;
+ self->channel_count = fi.nChans;
+ self->frame_buffer_size = fi.outputSamps*sizeof(int16_t);
+ self->len = 2 * self->frame_buffer_size;
+}
+
+void common_hal_audiomp3_mp3file_deinit(audiomp3_mp3file_obj_t* self) {
+ MP3FreeDecoder(self->decoder);
+ self->decoder = NULL;
+ self->inbuf = NULL;
+ self->buffers[0] = NULL;
+ self->buffers[1] = NULL;
+ self->file = NULL;
+}
+
+bool common_hal_audiomp3_mp3file_deinited(audiomp3_mp3file_obj_t* self) {
+ return self->buffers[0] == NULL;
+}
+
+uint32_t common_hal_audiomp3_mp3file_get_sample_rate(audiomp3_mp3file_obj_t* self) {
+ return self->sample_rate;
+}
+
+void common_hal_audiomp3_mp3file_set_sample_rate(audiomp3_mp3file_obj_t* self,
+ uint32_t sample_rate) {
+ self->sample_rate = sample_rate;
+}
+
+uint8_t common_hal_audiomp3_mp3file_get_bits_per_sample(audiomp3_mp3file_obj_t* self) {
+ return 16;
+}
+
+uint8_t common_hal_audiomp3_mp3file_get_channel_count(audiomp3_mp3file_obj_t* self) {
+ return self->channel_count;
+}
+
+bool audiomp3_mp3file_samples_signed(audiomp3_mp3file_obj_t* self) {
+ return true;
+}
+
+void audiomp3_mp3file_reset_buffer(audiomp3_mp3file_obj_t* self,
+ bool single_channel,
+ uint8_t channel) {
+ if (single_channel && channel == 1) {
+ return;
+ }
+ // We don't reset the buffer index in case we're looping and we have an odd number of buffer
+ // loads
+ f_lseek(&self->file->fp, 0);
+ self->inbuf_offset = self->inbuf_length;
+ self->eof = 0;
+ self->other_channel = -1;
+ mp3file_update_inbuf(self);
+ mp3file_skip_id3v2(self);
+ mp3file_find_sync_word(self);
+}
+
+audioio_get_buffer_result_t audiomp3_mp3file_get_buffer(audiomp3_mp3file_obj_t* self,
+ bool single_channel,
+ uint8_t channel,
+ uint8_t** bufptr,
+ uint32_t* buffer_length) {
+ if (!self->inbuf) {
+ return GET_BUFFER_ERROR;
+ }
+ if (!single_channel) {
+ channel = 0;
+ }
+
+ *buffer_length = self->frame_buffer_size;
+
+ if (channel == self->other_channel) {
+ *bufptr = (uint8_t*)(self->buffers[self->other_buffer_index] + channel);
+ self->other_channel = -1;
+ return GET_BUFFER_MORE_DATA;
+ }
+
+
+ self->buffer_index = !self->buffer_index;
+ self->other_channel = 1-channel;
+ self->other_buffer_index = self->buffer_index;
+ int16_t *buffer = (int16_t *)(void *)self->buffers[self->buffer_index];
+ *bufptr = (uint8_t*)buffer;
+
+ mp3file_skip_id3v2(self);
+ if (!mp3file_find_sync_word(self)) {
+ return self->eof ? GET_BUFFER_DONE : GET_BUFFER_ERROR;
+ }
+ int bytes_left = BYTES_LEFT(self);
+ uint8_t *inbuf = READ_PTR(self);
+ int err = MP3Decode(self->decoder, &inbuf, &bytes_left, buffer, 0);
+ CONSUME(self, BYTES_LEFT(self) - bytes_left);
+ if (err) {
+ return GET_BUFFER_DONE;
+ }
+
+ return GET_BUFFER_MORE_DATA;
+}
+
+void audiomp3_mp3file_get_buffer_structure(audiomp3_mp3file_obj_t* self, bool single_channel,
+ bool* single_buffer, bool* samples_signed,
+ uint32_t* max_buffer_length, uint8_t* spacing) {
+ *single_buffer = false;
+ *samples_signed = true;
+ *max_buffer_length = self->frame_buffer_size;
+ if (single_channel) {
+ *spacing = self->channel_count;
+ } else {
+ *spacing = 1;
+ }
+}
+
+float common_hal_audiomp3_mp3file_get_rms_level(audiomp3_mp3file_obj_t* self) {
+ float sumsq = 0.f;
+ // Assumes no DC component to the audio. Is that a safe assumption?
+ int16_t *buffer = (int16_t *)(void *)self->buffers[self->buffer_index];
+ for(size_t i=0; i<self->frame_buffer_size / sizeof(int16_t); i++) {
+ sumsq += (float)buffer[i] * buffer[i];
+ }
+ return sqrtf(sumsq) / (self->frame_buffer_size / sizeof(int16_t));
+}
diff --git a/shared-module/audiomp3/MP3Decoder.h b/shared-module/audiomp3/MP3Decoder.h
new file mode 100644
index 000000000..9ee1d0949
--- /dev/null
+++ b/shared-module/audiomp3/MP3Decoder.h
@@ -0,0 +1,72 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Scott Shawcroft
+ * Copyright (c) 2019 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.
+ */
+
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_AUDIOIO_MP3FILE_H
+#define MICROPY_INCLUDED_SHARED_MODULE_AUDIOIO_MP3FILE_H
+
+#include "extmod/vfs_fat.h"
+#include "py/obj.h"
+
+#include "shared-module/audiocore/__init__.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ struct _MP3DecInfo *decoder;
+ uint8_t* inbuf;
+ uint32_t inbuf_length;
+ uint32_t inbuf_offset;
+ int16_t* buffers[2];
+ uint32_t len;
+ uint32_t frame_buffer_size;
+
+ uint32_t sample_rate;
+ pyb_file_obj_t* file;
+
+ uint8_t buffer_index;
+ uint8_t channel_count;
+ bool eof;
+
+ int8_t other_channel;
+ int8_t other_buffer_index;
+} audiomp3_mp3file_obj_t;
+
+// These are not available from Python because it may be called in an interrupt.
+void audiomp3_mp3file_reset_buffer(audiomp3_mp3file_obj_t* self,
+ bool single_channel,
+ uint8_t channel);
+audioio_get_buffer_result_t audiomp3_mp3file_get_buffer(audiomp3_mp3file_obj_t* self,
+ bool single_channel,
+ uint8_t channel,
+ uint8_t** buffer,
+ uint32_t* buffer_length); // length in bytes
+void audiomp3_mp3file_get_buffer_structure(audiomp3_mp3file_obj_t* self, bool single_channel,
+ bool* single_buffer, bool* samples_signed,
+ uint32_t* max_buffer_length, uint8_t* spacing);
+
+float audiomp3_mp3file_get_rms_level(audiomp3_mp3file_obj_t* self);
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_AUDIOIO_MP3FILE_H
diff --git a/shared-module/audiomp3/__init__.c b/shared-module/audiomp3/__init__.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/shared-module/audiomp3/__init__.c
diff --git a/shared-module/audiomp3/__init__.h b/shared-module/audiomp3/__init__.h
new file mode 100644
index 000000000..e7b1f3aab
--- /dev/null
+++ b/shared-module/audiomp3/__init__.h
@@ -0,0 +1,30 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 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.
+ */
+
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_AUDIOMP3__INIT__H
+#define MICROPY_INCLUDED_SHARED_MODULE_AUDIOMP3__INIT__H
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_AUDIOMP3__INIT__H
diff --git a/shared-module/audiopwmio/__init__.c b/shared-module/audiopwmio/__init__.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/shared-module/audiopwmio/__init__.c
diff --git a/shared-module/audiopwmio/__init__.h b/shared-module/audiopwmio/__init__.h
new file mode 100644
index 000000000..964e4aafe
--- /dev/null
+++ b/shared-module/audiopwmio/__init__.h
@@ -0,0 +1,32 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Dan Halbert 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_SHARED_MODULE_AUDIOPWMIO__INIT__H
+#define MICROPY_INCLUDED_SHARED_MODULE_AUDIOPWMIO__INIT__H
+
+#include "shared-module/audiocore/__init__.h"
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_AUDIOPWMIO__INIT__H
diff --git a/shared-module/bitbangio/SPI.c b/shared-module/bitbangio/SPI.c
index 6d3a28523..e0ff1184f 100644
--- a/shared-module/bitbangio/SPI.c
+++ b/shared-module/bitbangio/SPI.c
@@ -43,19 +43,24 @@ void shared_module_bitbangio_spi_construct(bitbangio_spi_obj_t *self,
if (result != DIGITALINOUT_OK) {
mp_raise_ValueError(translate("Clock pin init failed."));
}
- if (mosi != mp_const_none) {
+ common_hal_digitalio_digitalinout_switch_to_output(&self->clock, self->polarity == 1, DRIVE_MODE_PUSH_PULL);
+
+ if (mosi != NULL) {
result = common_hal_digitalio_digitalinout_construct(&self->mosi, mosi);
if (result != DIGITALINOUT_OK) {
common_hal_digitalio_digitalinout_deinit(&self->clock);
mp_raise_ValueError(translate("MOSI pin init failed."));
}
self->has_mosi = true;
+ common_hal_digitalio_digitalinout_switch_to_output(&self->mosi, false, DRIVE_MODE_PUSH_PULL);
}
- if (miso != mp_const_none) {
+
+ if (miso != NULL) {
+ // Starts out as input by default, no need to change.
result = common_hal_digitalio_digitalinout_construct(&self->miso, miso);
if (result != DIGITALINOUT_OK) {
common_hal_digitalio_digitalinout_deinit(&self->clock);
- if (mosi != mp_const_none) {
+ if (mosi != NULL) {
common_hal_digitalio_digitalinout_deinit(&self->mosi);
}
mp_raise_ValueError(translate("MISO pin init failed."));
diff --git a/shared-module/bleio/AdvertisementData.h b/shared-module/bleio/AdvertisementData.h
deleted file mode 100644
index 738d53b23..000000000
--- a/shared-module/bleio/AdvertisementData.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * This file is part of the MicroPython project, http://micropython.org/
- *
- * The MIT License (MIT)
- *
- * Copyright (c) 2018 Artur Pacholec
- *
- * 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_BLEIO_ADVERTISEMENTDATA_H
-#define MICROPY_INCLUDED_SHARED_MODULE_BLEIO_ADVERTISEMENTDATA_H
-
-#include "py/obj.h"
-
-// Taken from https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile
-enum {
- AdFlags = 0x01,
- AdIncompleteListOf16BitServiceClassUUIDs = 0x02,
- AdCompleteListOf16BitServiceClassUUIDs = 0x03,
- AdIncompleteListOf32BitServiceClassUUIDs = 0x04,
- AdCompleteListOf32BitServiceClassUUIDs = 0x05,
- AdIncompleteListOf128BitServiceClassUUIDs = 0x06,
- AdCompleteListOf128BitServiceClassUUIDs = 0x07,
- AdShortenedLocalName = 0x08,
- AdCompleteLocalName = 0x09,
- AdTxPowerLevel = 0x0A,
- AdClassOfDevice = 0x0D,
- AdSimplePairingHashC = 0x0E,
- AdSimplePairingRandomizerR = 0x0F,
- AdSecurityManagerTKValue = 0x10,
- AdSecurityManagerOOBFlags = 0x11,
- AdSlaveConnectionIntervalRange = 0x12,
- AdListOf16BitServiceSolicitationUUIDs = 0x14,
- AdListOf128BitServiceSolicitationUUIDs = 0x15,
- AdServiceData = 0x16,
- AdPublicTargetAddress = 0x17,
- AdRandomTargetAddress = 0x18,
- AdAppearance = 0x19,
- AdAdvertisingInterval = 0x1A,
- AdLEBluetoothDeviceAddress = 0x1B,
- AdLERole = 0x1C,
- AdSimplePairingHashC256 = 0x1D,
- AdSimplePairingRandomizerR256 = 0x1E,
- AdListOf32BitServiceSolicitationUUIDs = 0x1F,
- AdServiceData32BitUUID = 0x20,
- AdServiceData128BitUUID = 0x21,
- AdLESecureConnectionsConfirmationValue = 0x22,
- AdLESecureConnectionsRandomValue = 0x23,
- AdURI = 0x24,
- AdIndoorPositioning = 0x25,
- AdTransportDiscoveryData = 0x26,
- AdLESupportedFeatures = 0x27,
- AdChannelMapUpdateIndication = 0x28,
- AdPBADV = 0x29,
- AdMeshMessage = 0x2A,
- AdMeshBeacon = 0x2B,
- Ad3DInformationData = 0x3D,
- AdManufacturerSpecificData = 0xFF,
-};
-
-typedef struct {
- mp_obj_t device_name;
- mp_obj_t services;
- mp_obj_t data;
- bool connectable;
-} bleio_advertisement_data_t;
-
-#endif // MICROPY_INCLUDED_SHARED_MODULE_BLEIO_ADVERTISEMENTDATA_H
diff --git a/shared-module/board/__init__.c b/shared-module/board/__init__.c
new file mode 100644
index 000000000..0fbf916cd
--- /dev/null
+++ b/shared-module/board/__init__.c
@@ -0,0 +1,164 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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 "shared-bindings/microcontroller/Pin.h"
+#include "supervisor/shared/translate.h"
+#include "mpconfigboard.h"
+#include "py/runtime.h"
+
+#if CIRCUITPY_BUSIO
+#include "shared-bindings/busio/I2C.h"
+#include "shared-bindings/busio/SPI.h"
+#include "shared-bindings/busio/UART.h"
+#endif
+
+#if CIRCUITPY_DISPLAYIO
+#include "shared-module/displayio/__init__.h"
+#endif
+
+#if BOARD_I2C
+// Statically allocate the I2C object so it can live past the end of the heap and into the next VM.
+// That way it can be used by built-in I2CDisplay displays and be accessible through board.I2C().
+STATIC busio_i2c_obj_t i2c_obj;
+STATIC mp_obj_t i2c_singleton = NULL;
+
+mp_obj_t common_hal_board_get_i2c(void) {
+ return i2c_singleton;
+}
+
+mp_obj_t common_hal_board_create_i2c(void) {
+ if (i2c_singleton != NULL) {
+ return i2c_singleton;
+ }
+ busio_i2c_obj_t *self = &i2c_obj;
+ self->base.type = &busio_i2c_type;
+
+ common_hal_busio_i2c_construct(self, DEFAULT_I2C_BUS_SCL, DEFAULT_I2C_BUS_SDA, 400000, 0);
+ i2c_singleton = (mp_obj_t)self;
+ return i2c_singleton;
+}
+#endif
+
+
+#if BOARD_SPI
+// Statically allocate the SPI object so it can live past the end of the heap and into the next VM.
+// That way it can be used by built-in FourWire displays and be accessible through board.SPI().
+STATIC busio_spi_obj_t spi_obj;
+STATIC mp_obj_t spi_singleton = NULL;
+
+mp_obj_t common_hal_board_get_spi(void) {
+ return spi_singleton;
+}
+
+mp_obj_t common_hal_board_create_spi(void) {
+ if (spi_singleton != NULL) {
+ return spi_singleton;
+ }
+ busio_spi_obj_t *self = &spi_obj;
+ self->base.type = &busio_spi_type;
+
+ const mcu_pin_obj_t* clock = MP_OBJ_TO_PTR(DEFAULT_SPI_BUS_SCK);
+ const mcu_pin_obj_t* mosi = MP_OBJ_TO_PTR(DEFAULT_SPI_BUS_MOSI);
+ const mcu_pin_obj_t* miso = MP_OBJ_TO_PTR(DEFAULT_SPI_BUS_MISO);
+ common_hal_busio_spi_construct(self, clock, mosi, miso);
+ spi_singleton = (mp_obj_t)self;
+ return spi_singleton;
+}
+#endif
+
+#if BOARD_UART
+mp_obj_t common_hal_board_get_uart(void) {
+ return MP_STATE_VM(shared_uart_bus);
+}
+
+mp_obj_t common_hal_board_create_uart(void) {
+ busio_uart_obj_t *self = m_new_ll_obj(busio_uart_obj_t);
+ self->base.type = &busio_uart_type;
+
+ const mcu_pin_obj_t* rx = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_RX);
+ const mcu_pin_obj_t* tx = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_TX);
+#ifdef DEFAULT_UART_BUS_RTS
+ const mcu_pin_obj_t* rts = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_RTS);
+#else
+ const mcu_pin_obj_t* rts = NULL;
+#endif
+#ifdef DEFAULT_UART_BUS_CTS
+ const mcu_pin_obj_t* cts = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_CTS);
+#else
+ const mcu_pin_obj_t* cts = NULL;
+#endif
+#ifdef DEFAULT_UART_IS_RS485
+ const mcu_pin_obj_t* rs485_dir = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_RS485DIR);
+#ifdef DEFAULT_UART_RS485_INVERT
+ const bool rs485_invert = true;
+#else
+ const bool rs485_invert = false;
+#endif
+#else
+ const mcu_pin_obj_t* rs485_dir = NULL;
+ const bool rs485_invert = false;
+#endif
+
+ common_hal_busio_uart_construct(self, tx, rx, rts, cts, rs485_dir, rs485_invert,
+ 9600, 8, PARITY_NONE, 1, 1.0f, 64, NULL, false);
+ MP_STATE_VM(shared_uart_bus) = MP_OBJ_FROM_PTR(self);
+ return MP_STATE_VM(shared_uart_bus);
+}
+#endif
+
+void reset_board_busses(void) {
+#if BOARD_I2C
+ bool display_using_i2c = false;
+ #if CIRCUITPY_DISPLAYIO
+ for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) {
+ if (displays[i].i2cdisplay_bus.bus == i2c_singleton) {
+ display_using_i2c = true;
+ break;
+ }
+ }
+ #endif
+ if (!display_using_i2c) {
+ i2c_singleton = NULL;
+ }
+#endif
+#if BOARD_SPI
+ bool display_using_spi = false;
+ #if CIRCUITPY_DISPLAYIO
+ for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) {
+ if (displays[i].fourwire_bus.bus == spi_singleton) {
+ display_using_spi = true;
+ break;
+ }
+ }
+ #endif
+ if (!display_using_spi) {
+ spi_singleton = NULL;
+ }
+#endif
+#if BOARD_UART
+ MP_STATE_VM(shared_uart_bus) = NULL;
+#endif
+}
diff --git a/shared-module/board/__init__.h b/shared-module/board/__init__.h
new file mode 100644
index 000000000..f7eecd417
--- /dev/null
+++ b/shared-module/board/__init__.h
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_BOARD__INIT__H
+#define MICROPY_INCLUDED_SHARED_MODULE_BOARD__INIT__H
+
+void reset_board_busses(void);
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_BOARD__INIT__H
diff --git a/shared-module/displayio/Bitmap.c b/shared-module/displayio/Bitmap.c
index addc341a7..8bcda6086 100644
--- a/shared-module/displayio/Bitmap.c
+++ b/shared-module/displayio/Bitmap.c
@@ -33,20 +33,21 @@
void common_hal_displayio_bitmap_construct(displayio_bitmap_t *self, uint32_t width,
uint32_t height, uint32_t bits_per_value) {
uint32_t row_width = width * bits_per_value;
- // word align
- if (row_width % 32 != 0) {
- self->stride = (row_width / 32 + 1);
+ // align to size_t
+ uint8_t align_bits = 8 * sizeof(size_t);
+ if (row_width % align_bits != 0) {
+ self->stride = (row_width / align_bits + 1);
} else {
- self->stride = row_width / 32;
+ self->stride = row_width / align_bits;
}
self->width = width;
self->height = height;
- self->data = m_malloc(self->stride * height * sizeof(uint32_t), false);
-
+ self->data = m_malloc(self->stride * height * sizeof(size_t), false);
+ self->read_only = false;
self->bits_per_value = bits_per_value;
- if (bits_per_value > 8) {
- mp_raise_NotImplementedError(translate("Only bit maps of 8 bit color or less are supported"));
+ if (bits_per_value > 8 && bits_per_value != 16 && bits_per_value != 32) {
+ mp_raise_NotImplementedError(translate("Invalid bits per value"));
}
// Division and modulus can be slow because it has to handle any integer. We know bits_per_value
@@ -56,46 +57,129 @@ void common_hal_displayio_bitmap_construct(displayio_bitmap_t *self, uint32_t wi
self->x_shift = 0; // Used to divide the index by the number of pixels per word. Its used in a
// shift which effectively divides by 2 ** x_shift.
uint32_t power_of_two = 1;
- while (power_of_two < 32 / bits_per_value ) {
+ while (power_of_two < align_bits / bits_per_value ) {
self->x_shift++;
power_of_two <<= 1;
}
self->x_mask = (1 << self->x_shift) - 1; // Used as a modulus on the x value
self->bitmask = (1 << bits_per_value) - 1;
+
+ self->dirty_area.x1 = 0;
+ self->dirty_area.x2 = width;
+ self->dirty_area.y1 = 0;
+ self->dirty_area.y2 = height;
}
-void common_hal_displayio_bitmap_load_row(displayio_bitmap_t *self, uint16_t y, uint8_t* data, uint16_t len) {
- if (len != self->stride * sizeof(uint32_t)) {
- mp_raise_ValueError(translate("row must be packed and word aligned"));
- }
- uint32_t* row_value = self->data + (y * self->stride);
- // Do the memcpy ourselves since we may want to flip endianness.
- for (uint32_t i = 0; i < self->stride; i++) {
- #pragma GCC diagnostic push
- #pragma GCC diagnostic ignored "-Wcast-align"
- uint32_t value = ((uint32_t *)data)[i];
- #pragma GCC diagnostic pop
- if (self->bits_per_value < 16) {
- value = ((value >> 24) & 0xff) |
- ((value << 8) & 0xff0000) |
- ((value >> 8) & 0xff00) |
- ((value << 24) & 0xff000000);
- }
- *row_value = value;
- row_value++;
- }
+uint16_t common_hal_displayio_bitmap_get_height(displayio_bitmap_t *self) {
+ return self->height;
+}
+
+uint16_t common_hal_displayio_bitmap_get_width(displayio_bitmap_t *self) {
+ return self->width;
+}
+
+uint32_t common_hal_displayio_bitmap_get_bits_per_value(displayio_bitmap_t *self) {
+ return self->bits_per_value;
}
+
uint32_t common_hal_displayio_bitmap_get_pixel(displayio_bitmap_t *self, int16_t x, int16_t y) {
if (x >= self->width || x < 0 || y >= self->height || y < 0) {
return 0;
}
int32_t row_start = y * self->stride;
- if (self->bits_per_value < 8) {
- uint32_t word = self->data[row_start + (x >> self->x_shift)];
+ uint32_t bytes_per_value = self->bits_per_value / 8;
+ if (bytes_per_value < 1) {
+ size_t word = self->data[row_start + (x >> self->x_shift)];
+
+ return (word >> (sizeof(size_t) * 8 - ((x & self->x_mask) + 1) * self->bits_per_value)) & self->bitmask;
+ } else {
+ size_t* row = self->data + row_start;
+ if (bytes_per_value == 1) {
+ return ((uint8_t*) row)[x];
+ } else if (bytes_per_value == 2) {
+ return ((uint16_t*) row)[x];
+ } else if (bytes_per_value == 4) {
+ return ((uint32_t*) row)[x];
+ }
+ }
+ return 0;
+}
+
+void common_hal_displayio_bitmap_set_pixel(displayio_bitmap_t *self, int16_t x, int16_t y, uint32_t value) {
+ if (self->read_only) {
+ mp_raise_RuntimeError(translate("Read-only object"));
+ }
+ // Update the dirty area.
+ if (self->dirty_area.x1 == self->dirty_area.x2) {
+ self->dirty_area.x1 = x;
+ self->dirty_area.x2 = x + 1;
+ self->dirty_area.y1 = y;
+ self->dirty_area.y2 = y + 1;
+ } else {
+ if (x < self->dirty_area.x1) {
+ self->dirty_area.x1 = x;
+ } else if (x >= self->dirty_area.x2) {
+ self->dirty_area.x2 = x + 1;
+ }
+ if (y < self->dirty_area.y1) {
+ self->dirty_area.y1 = y;
+ } else if (y >= self->dirty_area.y2) {
+ self->dirty_area.y2 = y + 1;
+ }
+ }
- return (word >> (32 - ((x & self->x_mask) + 1) * self->bits_per_value)) & self->bitmask;
+ // Update our data
+ int32_t row_start = y * self->stride;
+ uint32_t bytes_per_value = self->bits_per_value / 8;
+ if (bytes_per_value < 1) {
+ uint32_t bit_position = (sizeof(size_t) * 8 - ((x & self->x_mask) + 1) * self->bits_per_value);
+ uint32_t index = row_start + (x >> self->x_shift);
+ uint32_t word = self->data[index];
+ word &= ~(self->bitmask << bit_position);
+ word |= (value & self->bitmask) << bit_position;
+ self->data[index] = word;
} else {
- uint32_t bytes_per_value = self->bits_per_value / 8;
- return self->data[row_start + x * bytes_per_value];
+ size_t* row = self->data + row_start;
+ if (bytes_per_value == 1) {
+ ((uint8_t*) row)[x] = value;
+ } else if (bytes_per_value == 2) {
+ ((uint16_t*) row)[x] = value;
+ } else if (bytes_per_value == 4) {
+ ((uint32_t*) row)[x] = value;
+ }
+ }
+}
+
+displayio_area_t* displayio_bitmap_get_refresh_areas(displayio_bitmap_t *self, displayio_area_t* tail) {
+ if (self->dirty_area.x1 == self->dirty_area.x2) {
+ return tail;
+ }
+ self->dirty_area.next = tail;
+ return &self->dirty_area;
+}
+
+void displayio_bitmap_finish_refresh(displayio_bitmap_t *self) {
+ self->dirty_area.x1 = 0;
+ self->dirty_area.x2 = 0;
+}
+
+void common_hal_displayio_bitmap_fill(displayio_bitmap_t *self, uint32_t value) {
+ if (self->read_only) {
+ mp_raise_RuntimeError(translate("Read-only object"));
+ }
+ // Update the dirty area.
+ self->dirty_area.x1 = 0;
+ self->dirty_area.x2 = self->width;
+ self->dirty_area.y1 = 0;
+ self->dirty_area.y2 = self->height;
+
+ // build the packed word
+ uint32_t word = 0;
+ for (uint8_t i=0; i<32 / self->bits_per_value; i++) {
+ word |= (value & self->bitmask) << (32 - ((i+1)*self->bits_per_value));
+ }
+ // copy it in
+ for (uint32_t i=0; i<self->stride * self->height; i++) {
+ self->data[i] = word;
}
}
diff --git a/shared-module/displayio/Bitmap.h b/shared-module/displayio/Bitmap.h
index 781a4d12a..f4bd7ce4d 100644
--- a/shared-module/displayio/Bitmap.h
+++ b/shared-module/displayio/Bitmap.h
@@ -31,17 +31,23 @@
#include <stdint.h>
#include "py/obj.h"
+#include "shared-module/displayio/area.h"
typedef struct {
mp_obj_base_t base;
uint16_t width;
uint16_t height;
- uint32_t* data;
- uint16_t stride; // words
+ size_t* data;
+ uint16_t stride; // size_t's
uint8_t bits_per_value;
uint8_t x_shift;
- uint8_t x_mask;
+ size_t x_mask;
+ displayio_area_t dirty_area;
uint16_t bitmask;
+ bool read_only;
} displayio_bitmap_t;
+void displayio_bitmap_finish_refresh(displayio_bitmap_t *self);
+displayio_area_t* displayio_bitmap_get_refresh_areas(displayio_bitmap_t *self, displayio_area_t* tail);
+
#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_BITMAP_H
diff --git a/shared-module/displayio/ColorConverter.c b/shared-module/displayio/ColorConverter.c
index d20b24c01..c2c3214aa 100644
--- a/shared-module/displayio/ColorConverter.c
+++ b/shared-module/displayio/ColorConverter.c
@@ -26,16 +26,170 @@
#include "shared-bindings/displayio/ColorConverter.h"
-void common_hal_displayio_colorconverter_construct(displayio_colorconverter_t* self) {
-}
-
-bool common_hal_displayio_colorconverter_convert(displayio_colorconverter_t *self, uint32_t input_color, uint16_t* output_color) {
- // TODO(tannewt): Validate the color input against the input format.
- uint32_t r5 = (input_color >> 19);
- uint32_t g6 = (input_color >> 10) & 0x3f;
- uint32_t b5 = (input_color >> 3) & 0x1f;
- uint32_t packed = r5 << 11 | g6 << 5 | b5;
- // swap bytes
- *output_color = __builtin_bswap16(packed);
- return true;
+#include "py/misc.h"
+
+uint32_t displayio_colorconverter_dither_noise_1 (uint32_t n)
+{
+ n = (n >> 13) ^ n;
+ int nn = (n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff;
+ return (uint32_t) (((float)nn / (1073741824.0f*2)) * 255);
+}
+
+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) {
+ self->dither = dither;
+}
+
+uint16_t displayio_colorconverter_compute_rgb565(uint32_t color_rgb888) {
+ uint32_t r5 = (color_rgb888 >> 19);
+ uint32_t g6 = (color_rgb888 >> 10) & 0x3f;
+ uint32_t b5 = (color_rgb888 >> 3) & 0x1f;
+ return r5 << 11 | g6 << 5 | b5;
+}
+
+uint8_t displayio_colorconverter_compute_luma(uint32_t color_rgb888) {
+ uint32_t r8 = (color_rgb888 >> 16);
+ uint32_t g8 = (color_rgb888 >> 8) & 0xff;
+ uint32_t b8 = color_rgb888 & 0xff;
+ return (r8 * 19) / 255 + (g8 * 182) / 255 + (b8 + 54) / 255;
+}
+
+uint8_t displayio_colorconverter_compute_chroma(uint32_t color_rgb888) {
+ uint32_t r8 = (color_rgb888 >> 16);
+ uint32_t g8 = (color_rgb888 >> 8) & 0xff;
+ uint32_t b8 = color_rgb888 & 0xff;
+ uint8_t max = MAX(r8, MAX(g8, b8));
+ uint8_t min = MIN(r8, MIN(g8, b8));
+ return max - min;
+}
+
+uint8_t displayio_colorconverter_compute_hue(uint32_t color_rgb888) {
+ uint32_t r8 = (color_rgb888 >> 16);
+ uint32_t g8 = (color_rgb888 >> 8) & 0xff;
+ uint32_t b8 = color_rgb888 & 0xff;
+ uint8_t max = MAX(r8, MAX(g8, b8));
+ uint8_t min = MIN(r8, MIN(g8, b8));
+ uint8_t c = max - min;
+ if (c == 0) {
+ return 0;
+ }
+
+ int32_t hue = 0;
+ if (max == r8) {
+ hue = (((int32_t) (g8 - b8) * 40) / c) % 240;
+ } else if (max == g8) {
+ hue = (((int32_t) (b8 - r8) + (2 * c)) * 40) / c;
+ } else if (max == b8) {
+ hue = (((int32_t) (r8 - g8) + (4 * c)) * 40) / c;
+ }
+ if (hue < 0) {
+ hue += 240;
+ }
+
+ return hue;
+}
+
+void displayio_colorconverter_compute_tricolor(const _displayio_colorspace_t* colorspace, uint8_t pixel_hue, uint8_t pixel_luma, uint32_t* color) {
+
+ int16_t hue_diff = colorspace->tricolor_hue - pixel_hue;
+ if ((-10 <= hue_diff && hue_diff <= 10) || hue_diff <= -220 || hue_diff >= 220) {
+ if (colorspace->grayscale) {
+ *color = 0;
+ } else {
+ *color = 1;
+ }
+ } else if (!colorspace->grayscale) {
+ *color = 0;
+ }
+}
+
+void common_hal_displayio_colorconverter_convert(displayio_colorconverter_t *self, const _displayio_colorspace_t* colorspace, uint32_t input_color, uint32_t* output_color) {
+ displayio_input_pixel_t input_pixel;
+ input_pixel.pixel = input_color;
+ input_pixel.x = input_pixel.y = input_pixel.tile = input_pixel.tile_x = input_pixel.tile_y = 0;
+
+ displayio_output_pixel_t output_pixel;
+ output_pixel.pixel = 0;
+ output_pixel.opaque = false;
+
+ displayio_colorconverter_convert(self, colorspace, &input_pixel, &output_pixel);
+
+ (*output_color) = output_pixel.pixel;
+}
+
+void common_hal_displayio_colorconverter_set_dither(displayio_colorconverter_t* self, bool dither) {
+ self->dither = dither;
+}
+
+bool common_hal_displayio_colorconverter_get_dither(displayio_colorconverter_t* self) {
+ return self->dither;
+}
+
+void displayio_colorconverter_convert(displayio_colorconverter_t *self, const _displayio_colorspace_t* colorspace, const displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color) {
+ uint32_t pixel = input_pixel->pixel;
+
+ 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));
+ uint8_t randb = (displayio_colorconverter_dither_noise_2(input_pixel->tile_x,input_pixel->tile_y+33));
+
+ uint32_t r8 = (pixel >> 16);
+ uint32_t g8 = (pixel >> 8) & 0xff;
+ uint32_t b8 = pixel & 0xff;
+
+ if (colorspace->depth == 16) {
+ b8 = MIN(255,b8 + (randb&0x07));
+ r8 = MIN(255,r8 + (randr&0x07));
+ g8 = MIN(255,g8 + (randg&0x03));
+ } else {
+ int bitmask = 0xFF >> colorspace->depth;
+ b8 = MIN(255,b8 + (randb&bitmask));
+ r8 = MIN(255,r8 + (randr&bitmask));
+ g8 = MIN(255,g8 + (randg&bitmask));
+ }
+ pixel = r8 << 16 | g8 << 8 | b8;
+ }
+
+ if (colorspace->depth == 16) {
+ uint16_t packed = displayio_colorconverter_compute_rgb565(pixel);
+ if (colorspace->reverse_bytes_in_word) {
+ // swap bytes
+ packed = __builtin_bswap16(packed);
+ }
+ output_color->pixel = packed;
+ output_color->opaque = true;
+ return;
+ } else if (colorspace->tricolor) {
+ uint8_t luma = displayio_colorconverter_compute_luma(pixel);
+ output_color->pixel = luma >> (8 - colorspace->depth);
+ if (displayio_colorconverter_compute_chroma(pixel) <= 16) {
+ if (!colorspace->grayscale) {
+ output_color->pixel = 0;
+ }
+ output_color->opaque = true;
+ return;
+ }
+ uint8_t pixel_hue = displayio_colorconverter_compute_hue(pixel);
+ displayio_colorconverter_compute_tricolor(colorspace, pixel_hue, luma, &output_color->pixel);
+ return;
+ } else if (colorspace->grayscale && colorspace->depth <= 8) {
+ uint8_t luma = displayio_colorconverter_compute_luma(pixel);
+ output_color->pixel = luma >> (8 - colorspace->depth);
+ output_color->opaque = true;
+ return;
+ }
+ output_color->opaque = false;
+}
+
+
+
+// Currently no refresh logic is needed for a ColorConverter.
+bool displayio_colorconverter_needs_refresh(displayio_colorconverter_t *self) {
+ return false;
+}
+
+void displayio_colorconverter_finish_refresh(displayio_colorconverter_t *self) {
}
diff --git a/shared-module/displayio/ColorConverter.h b/shared-module/displayio/ColorConverter.h
index 62ef2eaab..10b1604a4 100644
--- a/shared-module/displayio/ColorConverter.h
+++ b/shared-module/displayio/ColorConverter.h
@@ -31,9 +31,24 @@
#include <stdint.h>
#include "py/obj.h"
+#include "shared-module/displayio/Palette.h"
typedef struct {
mp_obj_base_t base;
+ bool dither;
} displayio_colorconverter_t;
+bool displayio_colorconverter_needs_refresh(displayio_colorconverter_t *self);
+void displayio_colorconverter_finish_refresh(displayio_colorconverter_t *self);
+void displayio_colorconverter_convert(displayio_colorconverter_t *self, const _displayio_colorspace_t* colorspace, const displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color);
+
+uint32_t displayio_colorconverter_dither_noise_1 (uint32_t n);
+uint32_t displayio_colorconverter_dither_noise_2(uint32_t x, uint32_t y);
+
+uint16_t displayio_colorconverter_compute_rgb565(uint32_t color_rgb888);
+uint8_t displayio_colorconverter_compute_luma(uint32_t color_rgb888);
+uint8_t displayio_colorconverter_compute_chroma(uint32_t color_rgb888);
+uint8_t displayio_colorconverter_compute_hue(uint32_t color_rgb888);
+void displayio_colorconverter_compute_tricolor(const _displayio_colorspace_t* colorspace, uint8_t pixel_hue, uint8_t pixel_luma, uint32_t* color);
+
#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_COLORCONVERTER_H
diff --git a/shared-module/displayio/Display.c b/shared-module/displayio/Display.c
new file mode 100644
index 000000000..a3d877f1a
--- /dev/null
+++ b/shared-module/displayio/Display.c
@@ -0,0 +1,433 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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 "shared-bindings/displayio/Display.h"
+
+#include "py/runtime.h"
+#include "shared-bindings/displayio/FourWire.h"
+#include "shared-bindings/displayio/I2CDisplay.h"
+#include "shared-bindings/displayio/ParallelBus.h"
+#include "shared-bindings/microcontroller/Pin.h"
+#include "shared-bindings/time/__init__.h"
+#include "shared-module/displayio/__init__.h"
+#include "shared-module/displayio/display_core.h"
+#include "supervisor/shared/display.h"
+#include "supervisor/shared/tick.h"
+#include "supervisor/usb.h"
+
+#include <stdint.h>
+#include <string.h>
+
+void common_hal_displayio_display_construct(displayio_display_obj_t* self,
+ mp_obj_t bus, uint16_t width, uint16_t height, int16_t colstart, int16_t rowstart,
+ uint16_t rotation, uint16_t color_depth, bool grayscale, bool pixels_in_byte_share_row,
+ uint8_t bytes_per_cell, bool reverse_pixels_in_byte, bool reverse_bytes_in_word, uint8_t set_column_command,
+ uint8_t set_row_command, uint8_t write_ram_command, uint8_t set_vertical_scroll,
+ uint8_t* init_sequence, uint16_t init_sequence_len, const mcu_pin_obj_t* backlight_pin,
+ uint16_t brightness_command, mp_float_t brightness, bool auto_brightness,
+ bool single_byte_bounds, bool data_as_commands, bool auto_refresh, uint16_t native_frames_per_second, bool backlight_on_high) {
+ // Turn off auto-refresh as we init.
+ self->auto_refresh = false;
+ uint16_t ram_width = 0x100;
+ uint16_t ram_height = 0x100;
+ if (single_byte_bounds) {
+ ram_width = 0xff;
+ ram_height = 0xff;
+ }
+ displayio_display_core_construct(&self->core, bus, width, height, ram_width, ram_height, colstart, rowstart, rotation,
+ color_depth, grayscale, pixels_in_byte_share_row, bytes_per_cell, reverse_pixels_in_byte, reverse_bytes_in_word);
+
+ self->set_column_command = set_column_command;
+ self->set_row_command = set_row_command;
+ self->write_ram_command = write_ram_command;
+ self->brightness_command = brightness_command;
+ self->auto_brightness = auto_brightness;
+ self->first_manual_refresh = !auto_refresh;
+ self->data_as_commands = data_as_commands;
+ self->backlight_on_high = backlight_on_high;
+
+ self->native_frames_per_second = native_frames_per_second;
+ self->native_ms_per_frame = 1000 / native_frames_per_second;
+
+ uint32_t i = 0;
+ while (i < init_sequence_len) {
+ uint8_t *cmd = init_sequence + i;
+ uint8_t data_size = *(cmd + 1);
+ bool delay = (data_size & DELAY) != 0;
+ data_size &= ~DELAY;
+ uint8_t *data = cmd + 2;
+ while (!displayio_display_core_begin_transaction(&self->core)) {
+ RUN_BACKGROUND_TASKS;
+ }
+ if (self->data_as_commands) {
+ uint8_t full_command[data_size + 1];
+ full_command[0] = cmd[0];
+ memcpy(full_command + 1, data, data_size);
+ self->core.send(self->core.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, full_command, data_size + 1);
+ } else {
+ self->core.send(self->core.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, cmd, 1);
+ self->core.send(self->core.bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, data, data_size);
+ }
+ displayio_display_core_end_transaction(&self->core);
+ uint16_t delay_length_ms = 10;
+ if (delay) {
+ data_size++;
+ delay_length_ms = *(cmd + 1 + data_size);
+ if (delay_length_ms == 255) {
+ delay_length_ms = 500;
+ }
+ }
+ common_hal_time_delay_ms(delay_length_ms);
+ i += 2 + data_size;
+ }
+
+ supervisor_start_terminal(width, height);
+
+ // Always set the backlight type in case we're reusing memory.
+ self->backlight_inout.base.type = &mp_type_NoneType;
+ if (backlight_pin != NULL && common_hal_mcu_pin_is_free(backlight_pin)) {
+ // Avoid PWM types and functions when the module isn't enabled
+ #if (CIRCUITPY_PULSEIO)
+ pwmout_result_t result = common_hal_pulseio_pwmout_construct(&self->backlight_pwm, backlight_pin, 0, 50000, false);
+ if (result != PWMOUT_OK) {
+ self->backlight_inout.base.type = &digitalio_digitalinout_type;
+ common_hal_digitalio_digitalinout_construct(&self->backlight_inout, backlight_pin);
+ common_hal_never_reset_pin(backlight_pin);
+ } else {
+ self->backlight_pwm.base.type = &pulseio_pwmout_type;
+ common_hal_pulseio_pwmout_never_reset(&self->backlight_pwm);
+ }
+ #else
+ // Otherwise default to digital
+ self->backlight_inout.base.type = &digitalio_digitalinout_type;
+ common_hal_digitalio_digitalinout_construct(&self->backlight_inout, backlight_pin);
+ common_hal_never_reset_pin(backlight_pin);
+ #endif
+ }
+ if (!self->auto_brightness && (self->backlight_inout.base.type != &mp_type_NoneType ||
+ brightness_command != NO_BRIGHTNESS_COMMAND)) {
+ common_hal_displayio_display_set_brightness(self, brightness);
+ } else {
+ self->current_brightness = -1.0;
+ }
+
+ // Set the group after initialization otherwise we may send pixels while we delay in
+ // initialization.
+ common_hal_displayio_display_show(self, &circuitpython_splash);
+ self->auto_refresh = auto_refresh;
+}
+
+bool common_hal_displayio_display_show(displayio_display_obj_t* self, displayio_group_t* root_group) {
+ return displayio_display_core_show(&self->core, root_group);
+}
+
+uint16_t common_hal_displayio_display_get_width(displayio_display_obj_t* self){
+ return displayio_display_core_get_width(&self->core);
+}
+
+uint16_t common_hal_displayio_display_get_height(displayio_display_obj_t* self){
+ return displayio_display_core_get_height(&self->core);
+}
+
+bool common_hal_displayio_display_get_auto_brightness(displayio_display_obj_t* self) {
+ return self->auto_brightness;
+}
+
+void common_hal_displayio_display_set_auto_brightness(displayio_display_obj_t* self, bool auto_brightness) {
+ self->auto_brightness = auto_brightness;
+}
+
+mp_float_t common_hal_displayio_display_get_brightness(displayio_display_obj_t* self) {
+ return self->current_brightness;
+}
+
+bool common_hal_displayio_display_set_brightness(displayio_display_obj_t* self, mp_float_t brightness) {
+ self->updating_backlight = true;
+ if (!self->backlight_on_high){
+ brightness = 1.0-brightness;
+ }
+ bool ok = false;
+
+ // Avoid PWM types and functions when the module isn't enabled
+ #if (CIRCUITPY_PULSEIO)
+ bool ispwm = (self->backlight_pwm.base.type == &pulseio_pwmout_type) ? true : false;
+ #else
+ bool ispwm = false;
+ #endif
+
+ if (ispwm) {
+ #if (CIRCUITPY_PULSEIO)
+ common_hal_pulseio_pwmout_set_duty_cycle(&self->backlight_pwm, (uint16_t) (0xffff * brightness));
+ ok = true;
+ #else
+ ok = false;
+ #endif
+ } else if (self->backlight_inout.base.type == &digitalio_digitalinout_type) {
+ common_hal_digitalio_digitalinout_set_value(&self->backlight_inout, brightness > 0.99);
+ ok = true;
+ } else if (self->brightness_command != NO_BRIGHTNESS_COMMAND) {
+ ok = displayio_display_core_begin_transaction(&self->core);
+ if (ok) {
+ if (self->data_as_commands) {
+ uint8_t set_brightness[2] = {self->brightness_command, (uint8_t) (0xff * brightness)};
+ self->core.send(self->core.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, set_brightness, 2);
+ } else {
+ uint8_t command = self->brightness_command;
+ uint8_t hex_brightness = 0xff * brightness;
+ self->core.send(self->core.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, &command, 1);
+ self->core.send(self->core.bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, &hex_brightness, 1);
+ }
+ displayio_display_core_end_transaction(&self->core);
+ }
+
+ }
+ self->updating_backlight = false;
+ if (ok) {
+ self->current_brightness = brightness;
+ }
+ return ok;
+}
+
+mp_obj_t common_hal_displayio_display_get_bus(displayio_display_obj_t* self) {
+ return self->core.bus;
+}
+
+STATIC const displayio_area_t* _get_refresh_areas(displayio_display_obj_t *self) {
+ if (self->core.full_refresh) {
+ self->core.area.next = NULL;
+ return &self->core.area;
+ } else if (self->core.current_group != NULL) {
+ return displayio_group_get_refresh_areas(self->core.current_group, NULL);
+ }
+ return NULL;
+}
+
+STATIC void _send_pixels(displayio_display_obj_t* self, uint8_t* pixels, uint32_t length) {
+ if (!self->data_as_commands) {
+ self->core.send(self->core.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, &self->write_ram_command, 1);
+ }
+ self->core.send(self->core.bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, pixels, length);
+}
+
+STATIC bool _refresh_area(displayio_display_obj_t* self, const displayio_area_t* area) {
+ uint16_t buffer_size = 128; // In uint32_ts
+
+ displayio_area_t clipped;
+ // Clip the area to the display by overlapping the areas. If there is no overlap then we're done.
+ if (!displayio_display_core_clip_area(&self->core, area, &clipped)) {
+ return true;
+ }
+ uint16_t subrectangles = 1;
+ uint16_t rows_per_buffer = displayio_area_height(&clipped);
+ uint8_t pixels_per_word = (sizeof(uint32_t) * 8) / self->core.colorspace.depth;
+ uint16_t pixels_per_buffer = displayio_area_size(&clipped);
+ if (displayio_area_size(&clipped) > buffer_size * pixels_per_word) {
+ rows_per_buffer = buffer_size * pixels_per_word / displayio_area_width(&clipped);
+ if (rows_per_buffer == 0) {
+ rows_per_buffer = 1;
+ }
+ // If pixels are packed by column then ensure rows_per_buffer is on a byte boundary.
+ if (self->core.colorspace.depth < 8 && !self->core.colorspace.pixels_in_byte_share_row) {
+ uint8_t pixels_per_byte = 8 / self->core.colorspace.depth;
+ if (rows_per_buffer % pixels_per_byte != 0) {
+ rows_per_buffer -= rows_per_buffer % pixels_per_byte;
+ }
+ }
+ subrectangles = displayio_area_height(&clipped) / rows_per_buffer;
+ if (displayio_area_height(&clipped) % rows_per_buffer != 0) {
+ subrectangles++;
+ }
+ pixels_per_buffer = rows_per_buffer * displayio_area_width(&clipped);
+ buffer_size = pixels_per_buffer / pixels_per_word;
+ if (pixels_per_buffer % pixels_per_word) {
+ buffer_size += 1;
+ }
+ }
+
+ // Allocated and shared as a uint32_t array so the compiler knows the
+ // alignment everywhere.
+ uint32_t buffer[buffer_size];
+ uint32_t mask_length = (pixels_per_buffer / 32) + 1;
+ uint32_t mask[mask_length];
+ uint16_t remaining_rows = displayio_area_height(&clipped);
+
+ for (uint16_t j = 0; j < subrectangles; j++) {
+ displayio_area_t subrectangle = {
+ .x1 = clipped.x1,
+ .y1 = clipped.y1 + rows_per_buffer * j,
+ .x2 = clipped.x2,
+ .y2 = clipped.y1 + rows_per_buffer * (j + 1)
+ };
+ if (remaining_rows < rows_per_buffer) {
+ subrectangle.y2 = subrectangle.y1 + remaining_rows;
+ }
+ remaining_rows -= rows_per_buffer;
+
+ displayio_display_core_set_region_to_update(&self->core, self->set_column_command, self->set_row_command, NO_COMMAND, NO_COMMAND, self->data_as_commands, false, &subrectangle);
+
+ uint16_t subrectangle_size_bytes;
+ if (self->core.colorspace.depth >= 8) {
+ subrectangle_size_bytes = displayio_area_size(&subrectangle) * (self->core.colorspace.depth / 8);
+ } else {
+ subrectangle_size_bytes = displayio_area_size(&subrectangle) / (8 / self->core.colorspace.depth);
+ }
+
+ memset(mask, 0, mask_length * sizeof(mask[0]));
+ memset(buffer, 0, buffer_size * sizeof(buffer[0]));
+
+ displayio_display_core_fill_area(&self->core, &subrectangle, mask, buffer);
+
+ // Can't acquire display bus; skip the rest of the data.
+ if (!displayio_display_core_bus_free(&self->core)) {
+ return false;
+ }
+
+ displayio_display_core_begin_transaction(&self->core);
+ _send_pixels(self, (uint8_t*) buffer, subrectangle_size_bytes);
+ displayio_display_core_end_transaction(&self->core);
+
+ // TODO(tannewt): Make refresh displays faster so we don't starve other
+ // background tasks.
+ usb_background();
+ }
+ return true;
+}
+
+STATIC void _refresh_display(displayio_display_obj_t* self) {
+ if (!displayio_display_core_bus_free(&self->core)) {
+ // Can't acquire display bus; skip updating this display. Try next display.
+ return;
+ }
+ displayio_display_core_start_refresh(&self->core);
+ const displayio_area_t* current_area = _get_refresh_areas(self);
+ while (current_area != NULL) {
+ _refresh_area(self, current_area);
+ current_area = current_area->next;
+ }
+ displayio_display_core_finish_refresh(&self->core);
+}
+
+void common_hal_displayio_display_set_rotation(displayio_display_obj_t* self, int rotation){
+ bool transposed = (self->core.rotation == 90 || self->core.rotation == 270);
+ bool will_transposed = (rotation == 90 || rotation == 270);
+ if(transposed != will_transposed) {
+ int tmp = self->core.width;
+ self->core.width = self->core.height;
+ self->core.height = tmp;
+ }
+ displayio_display_core_set_rotation(&self->core, rotation);
+ supervisor_stop_terminal();
+ supervisor_start_terminal(self->core.width, self->core.height);
+ if (self->core.current_group != NULL) {
+ displayio_group_update_transform(self->core.current_group, &self->core.transform);
+ }
+}
+
+uint16_t common_hal_displayio_display_get_rotation(displayio_display_obj_t* self){
+ return self->core.rotation;
+}
+
+
+bool common_hal_displayio_display_refresh(displayio_display_obj_t* self, uint32_t target_ms_per_frame, uint32_t maximum_ms_per_real_frame) {
+ if (!self->auto_refresh && !self->first_manual_refresh) {
+ uint64_t current_time = supervisor_ticks_ms64();
+ uint32_t current_ms_since_real_refresh = current_time - self->core.last_refresh;
+ // Test to see if the real frame time is below our minimum.
+ if (current_ms_since_real_refresh > maximum_ms_per_real_frame) {
+ mp_raise_RuntimeError(translate("Below minimum frame rate"));
+ }
+ uint32_t current_ms_since_last_call = current_time - self->last_refresh_call;
+ self->last_refresh_call = current_time;
+ // Skip the actual refresh to help catch up.
+ if (current_ms_since_last_call > target_ms_per_frame) {
+ return false;
+ }
+ uint32_t remaining_time = target_ms_per_frame - (current_ms_since_real_refresh % target_ms_per_frame);
+ // We're ahead of the game so wait until we align with the frame rate.
+ while (supervisor_ticks_ms64() - self->last_refresh_call < remaining_time) {
+ RUN_BACKGROUND_TASKS;
+ }
+ }
+ self->first_manual_refresh = false;
+ _refresh_display(self);
+ return true;
+}
+
+bool common_hal_displayio_display_get_auto_refresh(displayio_display_obj_t* self) {
+ return self->auto_refresh;
+}
+
+void common_hal_displayio_display_set_auto_refresh(displayio_display_obj_t* self,
+ bool auto_refresh) {
+ self->first_manual_refresh = !auto_refresh;
+ self->auto_refresh = auto_refresh;
+}
+
+STATIC void _update_backlight(displayio_display_obj_t* self) {
+ if (!self->auto_brightness || self->updating_backlight) {
+ return;
+ }
+ if (supervisor_ticks_ms64() - self->last_backlight_refresh < 100) {
+ return;
+ }
+ // TODO(tannewt): Fade the backlight based on it's existing value and a target value. The target
+ // should account for ambient light when possible.
+ common_hal_displayio_display_set_brightness(self, 1.0);
+
+ self->last_backlight_refresh = supervisor_ticks_ms64();
+}
+
+void displayio_display_background(displayio_display_obj_t* self) {
+ _update_backlight(self);
+
+ if (self->auto_refresh && (supervisor_ticks_ms64() - self->core.last_refresh) > self->native_ms_per_frame) {
+ _refresh_display(self);
+ }
+}
+
+void release_display(displayio_display_obj_t* self) {
+ release_display_core(&self->core);
+ #if (CIRCUITPY_PULSEIO)
+ if (self->backlight_pwm.base.type == &pulseio_pwmout_type) {
+ common_hal_pulseio_pwmout_reset_ok(&self->backlight_pwm);
+ common_hal_pulseio_pwmout_deinit(&self->backlight_pwm);
+ } else if (self->backlight_inout.base.type == &digitalio_digitalinout_type) {
+ common_hal_digitalio_digitalinout_deinit(&self->backlight_inout);
+ }
+ #else
+ common_hal_digitalio_digitalinout_deinit(&self->backlight_inout);
+ #endif
+}
+
+void reset_display(displayio_display_obj_t* self) {
+ self->auto_refresh = true;
+ self->auto_brightness = true;
+ common_hal_displayio_display_show(self, NULL);
+}
+
+void displayio_display_collect_ptrs(displayio_display_obj_t* self) {
+ displayio_display_core_collect_ptrs(&self->core);
+}
diff --git a/shared-module/displayio/Display.h b/shared-module/displayio/Display.h
new file mode 100644
index 000000000..8adaf597f
--- /dev/null
+++ b/shared-module/displayio/Display.h
@@ -0,0 +1,67 @@
+/*
+ * 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.
+ */
+
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_DISPLAY_H
+#define MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_DISPLAY_H
+
+#include "shared-bindings/digitalio/DigitalInOut.h"
+#include "shared-bindings/displayio/Group.h"
+#include "shared-bindings/pulseio/PWMOut.h"
+
+#include "shared-module/displayio/area.h"
+#include "shared-module/displayio/display_core.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ displayio_display_core_t core;
+ union {
+ digitalio_digitalinout_obj_t backlight_inout;
+ pulseio_pwmout_obj_t backlight_pwm;
+ };
+ uint64_t last_backlight_refresh;
+ uint64_t last_refresh_call;
+ mp_float_t current_brightness;
+ uint16_t brightness_command;
+ uint16_t native_frames_per_second;
+ uint16_t native_ms_per_frame;
+ uint8_t set_column_command;
+ uint8_t set_row_command;
+ uint8_t write_ram_command;
+ bool auto_refresh;
+ bool first_manual_refresh;
+ bool data_as_commands;
+ bool auto_brightness;
+ bool updating_backlight;
+ bool backlight_on_high;
+} displayio_display_obj_t;
+
+void displayio_display_background(displayio_display_obj_t* self);
+void release_display(displayio_display_obj_t* self);
+void reset_display(displayio_display_obj_t* self);
+
+void displayio_display_collect_ptrs(displayio_display_obj_t* self);
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_DISPLAY_H
diff --git a/shared-module/displayio/EPaperDisplay.c b/shared-module/displayio/EPaperDisplay.c
new file mode 100644
index 000000000..6a55687b9
--- /dev/null
+++ b/shared-module/displayio/EPaperDisplay.c
@@ -0,0 +1,387 @@
+/*
+ * 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.
+ */
+
+#include "shared-bindings/displayio/EPaperDisplay.h"
+
+#include "py/gc.h"
+#include "py/runtime.h"
+#include "shared-bindings/displayio/ColorConverter.h"
+#include "shared-bindings/displayio/FourWire.h"
+#include "shared-bindings/displayio/I2CDisplay.h"
+#include "shared-bindings/displayio/ParallelBus.h"
+#include "shared-bindings/microcontroller/Pin.h"
+#include "shared-bindings/time/__init__.h"
+#include "shared-module/displayio/__init__.h"
+#include "supervisor/shared/display.h"
+#include "supervisor/shared/tick.h"
+#include "supervisor/usb.h"
+
+#include <stdint.h>
+#include <string.h>
+
+void common_hal_displayio_epaperdisplay_construct(displayio_epaperdisplay_obj_t* self,
+ mp_obj_t bus, uint8_t* start_sequence, uint16_t start_sequence_len, uint8_t* stop_sequence, uint16_t stop_sequence_len,
+ uint16_t width, uint16_t height, uint16_t ram_width, uint16_t ram_height,
+ int16_t colstart, int16_t rowstart, uint16_t rotation,
+ uint16_t set_column_window_command, uint16_t set_row_window_command,
+ uint16_t set_current_column_command, uint16_t set_current_row_command,
+ uint16_t write_black_ram_command, bool black_bits_inverted, uint16_t write_color_ram_command, bool color_bits_inverted, uint32_t highlight_color, uint16_t refresh_display_command, mp_float_t refresh_time,
+ const mcu_pin_obj_t* busy_pin, bool busy_state, mp_float_t seconds_per_frame, bool chip_select) {
+ if (highlight_color != 0x000000) {
+ self->core.colorspace.tricolor = true;
+ self->core.colorspace.tricolor_hue = displayio_colorconverter_compute_hue(highlight_color);
+ self->core.colorspace.tricolor_luma = displayio_colorconverter_compute_luma(highlight_color);
+ }
+
+ displayio_display_core_construct(&self->core, bus, width, height, ram_width, ram_height, colstart, rowstart, rotation, 1, true, true, 1, true, true);
+
+ self->set_column_window_command = set_column_window_command;
+ self->set_row_window_command = set_row_window_command;
+ self->set_current_column_command = set_current_column_command;
+ self->set_current_row_command = set_current_row_command;
+ self->write_black_ram_command = write_black_ram_command;
+ self->black_bits_inverted = black_bits_inverted;
+ self->write_color_ram_command = write_color_ram_command;
+ self->color_bits_inverted = color_bits_inverted;
+ self->refresh_display_command = refresh_display_command;
+ self->refresh_time = refresh_time * 1000;
+ self->busy_state = busy_state;
+ self->refreshing = false;
+ self->milliseconds_per_frame = seconds_per_frame * 1000;
+ self->chip_select = chip_select ? CHIP_SELECT_TOGGLE_EVERY_BYTE : CHIP_SELECT_UNTOUCHED;
+
+ self->start_sequence = start_sequence;
+ self->start_sequence_len = start_sequence_len;
+ self->stop_sequence = stop_sequence;
+ self->stop_sequence_len = stop_sequence_len;
+
+ self->busy.base.type = &mp_type_NoneType;
+ if (busy_pin != NULL) {
+ self->busy.base.type = &digitalio_digitalinout_type;
+ common_hal_digitalio_digitalinout_construct(&self->busy, busy_pin);
+ common_hal_never_reset_pin(busy_pin);
+ }
+
+ // Clear the color memory if it isn't in use.
+ if (highlight_color == 0x00 && write_color_ram_command != NO_COMMAND) {
+ // TODO: Clear
+ }
+
+ supervisor_start_terminal(width, height);
+
+ // Set the group after initialization otherwise we may send pixels while we delay in
+ // initialization.
+ common_hal_displayio_epaperdisplay_show(self, &circuitpython_splash);
+}
+
+bool common_hal_displayio_epaperdisplay_show(displayio_epaperdisplay_obj_t* self, displayio_group_t* root_group) {
+ return displayio_display_core_show(&self->core, root_group);
+}
+
+const displayio_area_t* displayio_epaperdisplay_get_refresh_areas(displayio_epaperdisplay_obj_t *self) {
+ if (self->core.full_refresh) {
+ self->core.area.next = NULL;
+ return &self->core.area;
+ }
+ const displayio_area_t* first_area = NULL;
+ if (self->core.current_group != NULL) {
+ first_area = displayio_group_get_refresh_areas(self->core.current_group, NULL);
+ }
+ if (first_area != NULL && self->set_row_window_command == NO_COMMAND) {
+ self->core.area.next = NULL;
+ return &self->core.area;
+ }
+ return first_area;
+}
+
+uint16_t common_hal_displayio_epaperdisplay_get_width(displayio_epaperdisplay_obj_t* self){
+ return displayio_display_core_get_width(&self->core);
+}
+
+uint16_t common_hal_displayio_epaperdisplay_get_height(displayio_epaperdisplay_obj_t* self){
+ return displayio_display_core_get_height(&self->core);
+}
+
+STATIC void wait_for_busy(displayio_epaperdisplay_obj_t* self) {
+ if (self->busy.base.type == &mp_type_NoneType) {
+ return;
+ }
+ while (common_hal_digitalio_digitalinout_get_value(&self->busy) == self->busy_state) {
+ RUN_BACKGROUND_TASKS;
+ }
+}
+
+STATIC void send_command_sequence(displayio_epaperdisplay_obj_t* self, bool should_wait_for_busy, uint8_t* sequence, uint32_t sequence_len) {
+ uint32_t i = 0;
+ while (i < sequence_len) {
+ uint8_t *cmd = sequence + i;
+ uint8_t data_size = *(cmd + 1);
+ bool delay = (data_size & DELAY) != 0;
+ data_size &= ~DELAY;
+ uint8_t *data = cmd + 2;
+ displayio_display_core_begin_transaction(&self->core);
+ self->core.send(self->core.bus, DISPLAY_COMMAND, self->chip_select, cmd, 1);
+ self->core.send(self->core.bus, DISPLAY_DATA, self->chip_select, data, data_size);
+ displayio_display_core_end_transaction(&self->core);
+ uint16_t delay_length_ms = 0;
+ if (delay) {
+ data_size++;
+ delay_length_ms = *(cmd + 1 + data_size);
+ if (delay_length_ms == 255) {
+ delay_length_ms = 500;
+ }
+ }
+ common_hal_time_delay_ms(delay_length_ms);
+ if (should_wait_for_busy) {
+ wait_for_busy(self);
+ }
+ i += 2 + data_size;
+ }
+}
+
+void displayio_epaperdisplay_start_refresh(displayio_epaperdisplay_obj_t* self) {
+ // run start sequence
+ self->core.bus_reset(self->core.bus);
+
+ send_command_sequence(self, true, self->start_sequence, self->start_sequence_len);
+ displayio_display_core_start_refresh(&self->core);
+}
+
+uint32_t common_hal_displayio_epaperdisplay_get_time_to_refresh(displayio_epaperdisplay_obj_t* self) {
+ if (self->core.last_refresh == 0) {
+ return 0;
+ }
+ // Refresh at seconds per frame rate.
+ uint32_t elapsed_time = supervisor_ticks_ms64() - self->core.last_refresh;
+ if (elapsed_time > self->milliseconds_per_frame) {
+ return 0;
+ }
+ return self->milliseconds_per_frame - elapsed_time;
+}
+
+void displayio_epaperdisplay_finish_refresh(displayio_epaperdisplay_obj_t* self) {
+ // Actually refresh the display now that all pixel RAM has been updated.
+ displayio_display_core_begin_transaction(&self->core);
+ self->core.send(self->core.bus, DISPLAY_COMMAND, self->chip_select, &self->refresh_display_command, 1);
+ displayio_display_core_end_transaction(&self->core);
+ self->refreshing = true;
+
+ displayio_display_core_finish_refresh(&self->core);
+}
+
+mp_obj_t common_hal_displayio_epaperdisplay_get_bus(displayio_epaperdisplay_obj_t* self) {
+ return self->core.bus;
+}
+
+bool displayio_epaperdisplay_refresh_area(displayio_epaperdisplay_obj_t* self, const displayio_area_t* area) {
+ uint16_t buffer_size = 128; // In uint32_ts
+
+ displayio_area_t clipped;
+ // Clip the area to the display by overlapping the areas. If there is no overlap then we're done.
+ if (!displayio_display_core_clip_area(&self->core, area, &clipped)) {
+ return true;
+ }
+ uint16_t subrectangles = 1;
+ uint16_t rows_per_buffer = displayio_area_height(&clipped);
+ uint8_t pixels_per_word = (sizeof(uint32_t) * 8) / self->core.colorspace.depth;
+ uint16_t pixels_per_buffer = displayio_area_size(&clipped);
+ if (displayio_area_size(&clipped) > buffer_size * pixels_per_word) {
+ rows_per_buffer = buffer_size * pixels_per_word / displayio_area_width(&clipped);
+ if (rows_per_buffer == 0) {
+ rows_per_buffer = 1;
+ }
+ subrectangles = displayio_area_height(&clipped) / rows_per_buffer;
+ if (displayio_area_height(&clipped) % rows_per_buffer != 0) {
+ subrectangles++;
+ }
+ pixels_per_buffer = rows_per_buffer * displayio_area_width(&clipped);
+ buffer_size = pixels_per_buffer / pixels_per_word;
+ if (pixels_per_buffer % pixels_per_word) {
+ buffer_size += 1;
+ }
+ }
+
+ // Allocated and shared as a uint32_t array so the compiler knows the
+ // alignment everywhere.
+ uint32_t buffer[buffer_size];
+ volatile uint32_t mask_length = (pixels_per_buffer / 32) + 1;
+ uint32_t mask[mask_length];
+
+ uint8_t passes = 1;
+ if (self->core.colorspace.tricolor) {
+ passes = 2;
+ }
+ for (uint8_t pass = 0; pass < passes; pass++) {
+ uint16_t remaining_rows = displayio_area_height(&clipped);
+
+ if (self->set_row_window_command != NO_COMMAND) {
+ displayio_display_core_set_region_to_update(&self->core, self->set_column_window_command, self->set_row_window_command, self->set_current_column_command, self->set_current_row_command, false, self->chip_select, &clipped);
+ }
+
+ uint8_t write_command = self->write_black_ram_command;
+ if (pass == 1) {
+ write_command = self->write_color_ram_command;
+ }
+ displayio_display_core_begin_transaction(&self->core);
+ self->core.send(self->core.bus, DISPLAY_COMMAND, self->chip_select, &write_command, 1);
+ displayio_display_core_end_transaction(&self->core);
+
+ for (uint16_t j = 0; j < subrectangles; j++) {
+ displayio_area_t subrectangle = {
+ .x1 = clipped.x1,
+ .y1 = clipped.y1 + rows_per_buffer * j,
+ .x2 = clipped.x2,
+ .y2 = clipped.y1 + rows_per_buffer * (j + 1)
+ };
+ if (remaining_rows < rows_per_buffer) {
+ subrectangle.y2 = subrectangle.y1 + remaining_rows;
+ }
+ remaining_rows -= rows_per_buffer;
+
+
+ uint16_t subrectangle_size_bytes = displayio_area_size(&subrectangle) / (8 / self->core.colorspace.depth);
+
+ memset(mask, 0, mask_length * sizeof(mask[0]));
+ memset(buffer, 0, buffer_size * sizeof(buffer[0]));
+
+ self->core.colorspace.grayscale = true;
+ if (pass == 1) {
+ self->core.colorspace.grayscale = false;
+ }
+ displayio_display_core_fill_area(&self->core, &subrectangle, mask, buffer);
+
+ // Invert it all.
+ if ((pass == 1 && self->color_bits_inverted) ||
+ (pass == 0 && self->black_bits_inverted)) {
+ for (uint16_t k = 0; k < buffer_size; k++) {
+ buffer[k] = ~buffer[k];
+ }
+ }
+
+ if (!displayio_display_core_begin_transaction(&self->core)) {
+ // Can't acquire display bus; skip the rest of the data. Try next display.
+ return false;
+ }
+ self->core.send(self->core.bus, DISPLAY_DATA, self->chip_select, (uint8_t*) buffer, subrectangle_size_bytes);
+ displayio_display_core_end_transaction(&self->core);
+
+ // TODO(tannewt): Make refresh displays faster so we don't starve other
+ // background tasks.
+ usb_background();
+ }
+ }
+
+ return true;
+}
+
+bool common_hal_displayio_epaperdisplay_refresh(displayio_epaperdisplay_obj_t* self) {
+
+ if (self->refreshing && self->busy.base.type == &digitalio_digitalinout_type) {
+ if (common_hal_digitalio_digitalinout_get_value(&self->busy) != self->busy_state) {
+ self->refreshing = false;
+ // Run stop sequence but don't wait for busy because busy is set when sleeping.
+ send_command_sequence(self, false, self->stop_sequence, self->stop_sequence_len);
+ } else {
+ return false;
+ }
+ }
+ if (self->core.current_group == NULL) {
+ return true;
+ }
+ // Refresh at seconds per frame rate.
+ if (common_hal_displayio_epaperdisplay_get_time_to_refresh(self) > 0) {
+ return false;
+ }
+ if (!displayio_display_core_bus_free(&self->core)) {
+ // Can't acquire display bus; skip updating this display. Try next display.
+ return false;
+ }
+ const displayio_area_t* current_area = displayio_epaperdisplay_get_refresh_areas(self);
+ if (current_area == NULL) {
+ return true;
+ }
+ displayio_epaperdisplay_start_refresh(self);
+ while (current_area != NULL) {
+ displayio_epaperdisplay_refresh_area(self, current_area);
+ current_area = current_area->next;
+ }
+ displayio_epaperdisplay_finish_refresh(self);
+ return true;
+}
+
+void displayio_epaperdisplay_background(displayio_epaperdisplay_obj_t* self) {
+ if (self->refreshing) {
+ bool refresh_done = false;
+ if (self->busy.base.type == &digitalio_digitalinout_type) {
+ bool busy = common_hal_digitalio_digitalinout_get_value(&self->busy);
+ refresh_done = busy != self->busy_state;
+ } else {
+ refresh_done = supervisor_ticks_ms64() - self->core.last_refresh > self->refresh_time;
+ }
+ if (refresh_done) {
+ self->refreshing = false;
+ // Run stop sequence but don't wait for busy because busy is set when sleeping.
+ send_command_sequence(self, false, self->stop_sequence, self->stop_sequence_len);
+ }
+ }
+}
+
+void release_epaperdisplay(displayio_epaperdisplay_obj_t* self) {
+ if (self->refreshing) {
+ wait_for_busy(self);
+ self->refreshing = false;
+ // Run stop sequence but don't wait for busy because busy is set when sleeping.
+ send_command_sequence(self, false, self->stop_sequence, self->stop_sequence_len);
+ }
+
+ release_display_core(&self->core);
+ if (self->busy.base.type == &digitalio_digitalinout_type) {
+ common_hal_digitalio_digitalinout_deinit(&self->busy);
+ }
+}
+
+void displayio_epaperdisplay_collect_ptrs(displayio_epaperdisplay_obj_t* self) {
+ displayio_display_core_collect_ptrs(&self->core);
+ gc_collect_ptr(self->start_sequence);
+ gc_collect_ptr(self->stop_sequence);
+}
+
+bool maybe_refresh_epaperdisplay(void) {
+ for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) {
+ if (displays[i].epaper_display.base.type != &displayio_epaperdisplay_type ||
+ displays[i].epaper_display.core.current_group != &circuitpython_splash) {
+ // Skip regular displays and those not showing the splash.
+ continue;
+ }
+ displayio_epaperdisplay_obj_t* display = &displays[i].epaper_display;
+ if (common_hal_displayio_epaperdisplay_get_time_to_refresh(display) != 0) {
+ return false;
+ }
+ return common_hal_displayio_epaperdisplay_refresh(display);
+ }
+ // Return true if no ePaper displays are available to pretend it was updated.
+ return true;
+}
diff --git a/shared-module/displayio/EPaperDisplay.h b/shared-module/displayio/EPaperDisplay.h
new file mode 100644
index 000000000..d08bed546
--- /dev/null
+++ b/shared-module/displayio/EPaperDisplay.h
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_EPAPERDISPLAY_H
+#define MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_EPAPERDISPLAY_H
+
+#include "shared-bindings/digitalio/DigitalInOut.h"
+#include "shared-bindings/displayio/Group.h"
+#include "shared-bindings/pulseio/PWMOut.h"
+
+#include "shared-module/displayio/area.h"
+#include "shared-module/displayio/display_core.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ displayio_display_core_t core;
+ digitalio_digitalinout_obj_t busy;
+ uint32_t milliseconds_per_frame;
+ uint8_t* start_sequence;
+ uint32_t start_sequence_len;
+ uint8_t* stop_sequence;
+ uint32_t stop_sequence_len;
+ uint16_t refresh_time;
+ uint16_t set_column_window_command;
+ uint16_t set_row_window_command;
+ uint16_t set_current_column_command;
+ uint16_t set_current_row_command;
+ uint16_t write_black_ram_command;
+ uint16_t write_color_ram_command;
+ uint8_t refresh_display_command;
+ uint8_t hue;
+ bool busy_state;
+ bool black_bits_inverted;
+ bool color_bits_inverted;
+ bool refreshing;
+ display_chip_select_behavior_t chip_select;
+} displayio_epaperdisplay_obj_t;
+
+void displayio_epaperdisplay_background(displayio_epaperdisplay_obj_t* self);
+void release_epaperdisplay(displayio_epaperdisplay_obj_t* self);
+bool maybe_refresh_epaperdisplay(void);
+
+void displayio_epaperdisplay_collect_ptrs(displayio_epaperdisplay_obj_t* self);
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_EPAPERDISPLAY_H
diff --git a/shared-module/displayio/FourWire.c b/shared-module/displayio/FourWire.c
new file mode 100644
index 000000000..17e8cfa1d
--- /dev/null
+++ b/shared-module/displayio/FourWire.c
@@ -0,0 +1,135 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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 "shared-bindings/displayio/FourWire.h"
+
+#include <stdint.h>
+
+#include "py/gc.h"
+#include "shared-bindings/busio/SPI.h"
+#include "shared-bindings/digitalio/DigitalInOut.h"
+#include "shared-bindings/microcontroller/Pin.h"
+#include "shared-bindings/microcontroller/__init__.h"
+#include "shared-bindings/time/__init__.h"
+#include "shared-module/displayio/display_core.h"
+
+void common_hal_displayio_fourwire_construct(displayio_fourwire_obj_t* self,
+ busio_spi_obj_t* spi, const mcu_pin_obj_t* command,
+ const mcu_pin_obj_t* chip_select, const mcu_pin_obj_t* reset, uint32_t baudrate,
+ uint8_t polarity, uint8_t phase) {
+
+ self->bus = spi;
+ common_hal_busio_spi_never_reset(self->bus);
+ // Our object is statically allocated off the heap so make sure the bus object lives to the end
+ // of the heap as well.
+ gc_never_free(self->bus);
+
+ self->frequency = baudrate;
+ self->polarity = polarity;
+ self->phase = phase;
+
+ common_hal_digitalio_digitalinout_construct(&self->command, command);
+ common_hal_digitalio_digitalinout_switch_to_output(&self->command, true, DRIVE_MODE_PUSH_PULL);
+ common_hal_digitalio_digitalinout_construct(&self->chip_select, chip_select);
+ common_hal_digitalio_digitalinout_switch_to_output(&self->chip_select, true, DRIVE_MODE_PUSH_PULL);
+
+ self->reset.base.type = &mp_type_NoneType;
+ if (reset != NULL) {
+ self->reset.base.type = &digitalio_digitalinout_type;
+ common_hal_digitalio_digitalinout_construct(&self->reset, reset);
+ common_hal_digitalio_digitalinout_switch_to_output(&self->reset, true, DRIVE_MODE_PUSH_PULL);
+ common_hal_never_reset_pin(reset);
+ common_hal_displayio_fourwire_reset(self);
+ }
+
+ common_hal_never_reset_pin(command);
+ common_hal_never_reset_pin(chip_select);
+}
+
+void common_hal_displayio_fourwire_deinit(displayio_fourwire_obj_t* self) {
+ if (self->bus == &self->inline_bus) {
+ common_hal_busio_spi_deinit(self->bus);
+ }
+
+ common_hal_reset_pin(self->command.pin);
+ common_hal_reset_pin(self->chip_select.pin);
+ common_hal_reset_pin(self->reset.pin);
+}
+
+bool common_hal_displayio_fourwire_reset(mp_obj_t obj) {
+ displayio_fourwire_obj_t* self = MP_OBJ_TO_PTR(obj);
+ if (self->reset.base.type == &mp_type_NoneType) {
+ return false;
+ }
+ common_hal_digitalio_digitalinout_set_value(&self->reset, false);
+ common_hal_time_delay_ms(1);
+ common_hal_digitalio_digitalinout_set_value(&self->reset, true);
+ common_hal_time_delay_ms(1);
+ return true;
+}
+
+bool common_hal_displayio_fourwire_bus_free(mp_obj_t obj) {
+ displayio_fourwire_obj_t* self = MP_OBJ_TO_PTR(obj);
+ if (!common_hal_busio_spi_try_lock(self->bus)) {
+ return false;
+ }
+ common_hal_busio_spi_unlock(self->bus);
+ return true;
+}
+
+bool common_hal_displayio_fourwire_begin_transaction(mp_obj_t obj) {
+ displayio_fourwire_obj_t* self = MP_OBJ_TO_PTR(obj);
+ if (!common_hal_busio_spi_try_lock(self->bus)) {
+ return false;
+ }
+ common_hal_busio_spi_configure(self->bus, self->frequency, self->polarity,
+ self->phase, 8);
+ common_hal_digitalio_digitalinout_set_value(&self->chip_select, false);
+ return true;
+}
+
+void common_hal_displayio_fourwire_send(mp_obj_t obj, display_byte_type_t data_type, display_chip_select_behavior_t chip_select, uint8_t *data, uint32_t data_length) {
+ displayio_fourwire_obj_t* self = MP_OBJ_TO_PTR(obj);
+ common_hal_digitalio_digitalinout_set_value(&self->command, data_type == DISPLAY_DATA);
+ if (chip_select == CHIP_SELECT_TOGGLE_EVERY_BYTE) {
+ // Toggle chip select after each command byte in case the display driver
+ // IC latches commands based on it.
+ for (size_t i = 0; i < data_length; i++) {
+ common_hal_busio_spi_write(self->bus, &data[i], 1);
+ common_hal_digitalio_digitalinout_set_value(&self->chip_select, true);
+ common_hal_mcu_delay_us(1);
+ common_hal_digitalio_digitalinout_set_value(&self->chip_select, false);
+ }
+ } else {
+ common_hal_busio_spi_write(self->bus, data, data_length);
+ }
+}
+
+void common_hal_displayio_fourwire_end_transaction(mp_obj_t obj) {
+ displayio_fourwire_obj_t* self = MP_OBJ_TO_PTR(obj);
+ common_hal_digitalio_digitalinout_set_value(&self->chip_select, true);
+ common_hal_busio_spi_unlock(self->bus);
+}
diff --git a/shared-module/displayio/FourWire.h b/shared-module/displayio/FourWire.h
new file mode 100644
index 000000000..a4260a3ac
--- /dev/null
+++ b/shared-module/displayio/FourWire.h
@@ -0,0 +1,46 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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_SHARED_MODULE_DISPLAYIO_FOURWIRE_H
+#define MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_FOURWIRE_H
+
+#include "common-hal/busio/SPI.h"
+#include "common-hal/digitalio/DigitalInOut.h"
+#include "shared-module/displayio/Group.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ busio_spi_obj_t* bus;
+ busio_spi_obj_t inline_bus;
+ digitalio_digitalinout_obj_t command;
+ digitalio_digitalinout_obj_t chip_select;
+ digitalio_digitalinout_obj_t reset;
+ uint32_t frequency;
+ uint8_t polarity;
+ uint8_t phase;
+} displayio_fourwire_obj_t;
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_FOURWIRE_H
diff --git a/shared-module/displayio/Group.c b/shared-module/displayio/Group.c
index 655376da0..15cf5b8e4 100644
--- a/shared-module/displayio/Group.c
+++ b/shared-module/displayio/Group.c
@@ -27,79 +27,385 @@
#include "shared-bindings/displayio/Group.h"
#include "py/runtime.h"
-#include "shared-bindings/displayio/Sprite.h"
+#include "shared-bindings/displayio/TileGrid.h"
-void common_hal_displayio_group_construct(displayio_group_t* self, uint32_t max_size) {
- mp_obj_t* children = m_new(mp_obj_t, max_size);
- displayio_group_construct(self, children, max_size);
+#if CIRCUITPY_VECTORIO
+#include "shared-bindings/vectorio/VectorShape.h"
+#endif
+
+
+void common_hal_displayio_group_construct(displayio_group_t* self, uint32_t max_size, uint32_t scale, mp_int_t x, mp_int_t y) {
+ displayio_group_child_t* children = m_new(displayio_group_child_t, max_size);
+ displayio_group_construct(self, children, max_size, scale, x, y);
+}
+
+bool common_hal_displayio_group_get_hidden(displayio_group_t* self) {
+ return self->hidden;
+}
+
+void common_hal_displayio_group_set_hidden(displayio_group_t* self, bool hidden) {
+ if (self->hidden == hidden) {
+ return;
+ }
+ self->hidden = hidden;
+ if (self->hidden_by_parent) {
+ return;
+ }
+ for (size_t i = 0; i < self->size; i++) {
+ mp_obj_t layer = self->children[i].native;
+ if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) {
+ displayio_tilegrid_set_hidden_by_parent(layer, hidden);
+ } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) {
+ displayio_group_set_hidden_by_parent(layer, hidden);
+ }
+ }
+}
+
+void displayio_group_set_hidden_by_parent(displayio_group_t *self, bool hidden) {
+ if (self->hidden_by_parent == hidden) {
+ return;
+ }
+ self->hidden_by_parent = hidden;
+ // If we're already hidden, then we're done.
+ if (self->hidden) {
+ return;
+ }
+ for (size_t i = 0; i < self->size; i++) {
+ mp_obj_t layer = self->children[i].native;
+ if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) {
+ displayio_tilegrid_set_hidden_by_parent(layer, hidden);
+ } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) {
+ displayio_group_set_hidden_by_parent(layer, hidden);
+ }
+ }
+}
+
+uint32_t common_hal_displayio_group_get_scale(displayio_group_t* self) {
+ return self->scale;
}
-void common_hal_displayio_group_append(displayio_group_t* self, mp_obj_t layer) {
+bool displayio_group_get_previous_area(displayio_group_t *self, displayio_area_t* area) {
+ bool first = true;
+ for (size_t i = 0; i < self->size; i++) {
+ mp_obj_t layer = self->children[i].native;
+ displayio_area_t layer_area;
+ if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) {
+ if (!displayio_tilegrid_get_previous_area(layer, &layer_area)) {
+ continue;
+ }
+ } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) {
+ if (!displayio_group_get_previous_area(layer, &layer_area)) {
+ continue;
+ }
+ }
+ if (first) {
+ displayio_area_copy(&layer_area, area);
+ first = false;
+ } else {
+ displayio_area_expand(area, &layer_area);
+ }
+ }
+ if (self->item_removed) {
+ if (first) {
+ displayio_area_copy(&self->dirty_area, area);
+ first = false;
+ } else {
+ displayio_area_expand(area, &self->dirty_area);
+ }
+ }
+ return !first;
+}
+
+static void _update_child_transforms(displayio_group_t* self) {
+ if (!self->in_group) {
+ return;
+ }
+ for (size_t i = 0; i < self->size; i++) {
+ mp_obj_t layer = self->children[i].native;
+#if CIRCUITPY_VECTORIO
+ if (MP_OBJ_IS_TYPE(layer, &vectorio_vector_shape_type)) {
+ vectorio_vector_shape_update_transform(layer, &self->absolute_transform);
+ }
+ else
+#endif
+ if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) {
+ displayio_tilegrid_update_transform(layer, &self->absolute_transform);
+ } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) {
+ displayio_group_update_transform(layer, &self->absolute_transform);
+ }
+ }
+}
+
+void displayio_group_update_transform(displayio_group_t *self,
+ const displayio_buffer_transform_t* parent_transform) {
+ self->in_group = parent_transform != NULL;
+ if (self->in_group) {
+ int16_t x = self->x;
+ int16_t y = self->y;
+ if (parent_transform->transpose_xy) {
+ x = y;
+ y = self->x;
+ }
+ self->absolute_transform.x = parent_transform->x + parent_transform->dx * x;
+ self->absolute_transform.y = parent_transform->y + parent_transform->dy * y;
+ self->absolute_transform.dx = parent_transform->dx * self->scale;
+ self->absolute_transform.dy = parent_transform->dy * self->scale;
+ self->absolute_transform.transpose_xy = parent_transform->transpose_xy;
+ self->absolute_transform.mirror_x = parent_transform->mirror_x;
+ self->absolute_transform.mirror_y = parent_transform->mirror_y;
+
+ self->absolute_transform.scale = parent_transform->scale * self->scale;
+ }
+ _update_child_transforms(self);
+}
+
+void common_hal_displayio_group_set_scale(displayio_group_t* self, uint32_t scale) {
+ if (self->scale == scale) {
+ return;
+ }
+ uint8_t parent_scale = self->absolute_transform.scale / self->scale;
+ self->absolute_transform.dx = self->absolute_transform.dx / self->scale * scale;
+ self->absolute_transform.dy = self->absolute_transform.dy / self->scale * scale;
+ self->absolute_transform.scale = parent_scale * scale;
+ self->scale = scale;
+ _update_child_transforms(self);
+}
+
+mp_int_t common_hal_displayio_group_get_x(displayio_group_t* self) {
+ return self->x;
+}
+
+void common_hal_displayio_group_set_x(displayio_group_t* self, mp_int_t x) {
+ if (self->x == x) {
+ return;
+ }
+ if (self->absolute_transform.transpose_xy) {
+ int16_t dy = self->absolute_transform.dy / self->scale;
+ self->absolute_transform.y += dy * (x - self->x);
+ } else {
+ int16_t dx = self->absolute_transform.dx / self->scale;
+ self->absolute_transform.x += dx * (x - self->x);
+ }
+
+ self->x = x;
+ _update_child_transforms(self);
+}
+
+mp_int_t common_hal_displayio_group_get_y(displayio_group_t* self) {
+ return self->y;
+}
+
+void common_hal_displayio_group_set_y(displayio_group_t* self, mp_int_t y) {
+ if (self->y == y) {
+ return;
+ }
+ if (self->absolute_transform.transpose_xy) {
+ int8_t dx = self->absolute_transform.dx / self->scale;
+ self->absolute_transform.x += dx * (y - self->y);
+ } else {
+ int8_t dy = self->absolute_transform.dy / self->scale;
+ self->absolute_transform.y += dy * (y - self->y);
+ }
+ self->y = y;
+ _update_child_transforms(self);
+}
+
+static mp_obj_t _add_layer(displayio_group_t* self, mp_obj_t layer) {
+ mp_obj_t native_layer;
+#if CIRCUITPY_VECTORIO
+ native_layer = mp_instance_cast_to_native_base(layer, &vectorio_vector_shape_type);
+ if (native_layer != MP_OBJ_NULL) {
+ vectorio_vector_shape_update_transform(native_layer, &self->absolute_transform);
+ return native_layer;
+ }
+#endif
+ native_layer = mp_instance_cast_to_native_base(layer, &displayio_group_type);
+ if (native_layer == MP_OBJ_NULL) {
+ native_layer = mp_instance_cast_to_native_base(layer, &displayio_tilegrid_type);
+ if (native_layer == MP_OBJ_NULL) {
+ mp_raise_ValueError(translate("Layer must be a Group or TileGrid subclass."));
+ }
+ displayio_tilegrid_t* tilegrid = native_layer;
+ if (tilegrid->in_group) {
+ mp_raise_ValueError(translate("Layer already in a group."));
+ } else {
+ tilegrid->in_group = true;
+ }
+ displayio_tilegrid_update_transform(tilegrid, &self->absolute_transform);
+ } else {
+ displayio_group_t* group = native_layer;
+ if (group->in_group) {
+ mp_raise_ValueError(translate("Layer already in a group."));
+ } else {
+ group->in_group = true;
+ }
+ displayio_group_update_transform(group, &self->absolute_transform);
+ }
+ return native_layer;
+}
+
+static void _remove_layer(displayio_group_t* self, size_t index) {
+ mp_obj_t layer = self->children[index].native;
+ displayio_area_t layer_area;
+ bool rendered_last_frame = false;
+#if CIRCUITPY_VECTORIO
+ if (MP_OBJ_IS_TYPE(layer, &vectorio_vector_shape_type)) {
+ bool has_dirty_area = vectorio_vector_shape_get_dirty_area(layer, &layer_area);
+ rendered_last_frame = has_dirty_area;
+ vectorio_vector_shape_update_transform(layer, NULL);
+ }
+ else
+#endif
+ if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) {
+ displayio_tilegrid_t* tilegrid = layer;
+ rendered_last_frame = displayio_tilegrid_get_previous_area(tilegrid, &layer_area);
+ displayio_tilegrid_update_transform(tilegrid, NULL);
+ } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) {
+ displayio_group_t* group = layer;
+ rendered_last_frame = displayio_group_get_previous_area(group, &layer_area);
+ displayio_group_update_transform(group, NULL);
+ }
+ if (!rendered_last_frame) {
+ return;
+ }
+ if (!self->item_removed) {
+ displayio_area_copy(&layer_area, &self->dirty_area);
+ } else {
+ displayio_area_expand(&self->dirty_area, &layer_area);
+ }
+ self->item_removed = true;
+}
+
+void common_hal_displayio_group_insert(displayio_group_t* self, size_t index, mp_obj_t layer) {
if (self->size == self->max_size) {
mp_raise_RuntimeError(translate("Group full"));
}
- self->children[self->size] = layer;
+ mp_obj_t native_layer = _add_layer(self, layer);
+ // Shift everything right.
+ for (size_t i = self->size; i > index; i--) {
+ self->children[i] = self->children[i - 1];
+ }
+ self->children[index].native = native_layer;
+ self->children[index].original = layer;
self->size++;
- self->needs_refresh = true;
}
-mp_obj_t common_hal_displayio_group_pop(displayio_group_t* self) {
- if (self->size == 0) {
- mp_raise_IndexError(translate("Group empty"));
- }
+mp_obj_t common_hal_displayio_group_pop(displayio_group_t* self, size_t index) {
self->size--;
- mp_obj_t item = self->children[self->size];
- self->children[self->size] = NULL;
- self->needs_refresh = true;
+ mp_obj_t item = self->children[index].original;
+ _remove_layer(self, index);
+
+ // Shift everything left.
+ for (size_t i = index; i < self->size; i++) {
+ self->children[i] = self->children[i + 1];
+ }
+ self->children[self->size].native = NULL;
+ self->children[self->size].original = NULL;
return item;
}
-void displayio_group_construct(displayio_group_t* self, mp_obj_t* child_array, uint32_t max_size) {
- self->x = 0;
- self->y = 0;
+mp_int_t common_hal_displayio_group_index(displayio_group_t* self, mp_obj_t layer) {
+ for (size_t i = 0; i < self->size; i++) {
+ if (self->children[i].original == layer) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+size_t common_hal_displayio_group_get_len(displayio_group_t* self) {
+ return self->size;
+}
+
+mp_obj_t common_hal_displayio_group_get(displayio_group_t* self, size_t index) {
+ return self->children[index].original;
+}
+
+void common_hal_displayio_group_set(displayio_group_t* self, size_t index, mp_obj_t layer) {
+ mp_obj_t native_layer = _add_layer(self, layer);
+ _remove_layer(self, index);
+ self->children[index].native = native_layer;
+ self->children[index].original = layer;
+}
+
+void displayio_group_construct(displayio_group_t* self, displayio_group_child_t* child_array, uint32_t max_size, uint32_t scale, mp_int_t x, mp_int_t y) {
+ self->x = x;
+ self->y = y;
self->children = child_array;
self->max_size = max_size;
- self->needs_refresh = false;
+ self->item_removed = false;
+ self->scale = scale;
+ self->in_group = false;
}
-bool displayio_group_get_pixel(displayio_group_t *self, int16_t x, int16_t y, uint16_t* pixel) {
- x -= self->x;
- y -= self->y;
+bool displayio_group_fill_area(displayio_group_t *self, const _displayio_colorspace_t* colorspace, const displayio_area_t* area, uint32_t* mask, uint32_t* buffer) {
+ // Track if any of the layers finishes filling in the given area. We can ignore any remaining
+ // layers at that point.
+ bool full_coverage = false;
for (int32_t i = self->size - 1; i >= 0 ; i--) {
- mp_obj_t layer = self->children[i];
- if (MP_OBJ_IS_TYPE(layer, &displayio_sprite_type)) {
- if (displayio_sprite_get_pixel(layer, x, y, pixel)) {
- return true;
+ mp_obj_t layer = self->children[i].native;
+#if CIRCUITPY_VECTORIO
+ if (MP_OBJ_IS_TYPE(layer, &vectorio_vector_shape_type)) {
+ if (vectorio_vector_shape_fill_area(layer, colorspace, area, mask, buffer)) {
+ full_coverage = true;
+ break;
+ }
+ }
+ else
+#endif
+ if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) {
+ if (displayio_tilegrid_fill_area(layer, colorspace, area, mask, buffer)) {
+ full_coverage = true;
+ break;
+ }
+ } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) {
+ if (displayio_group_fill_area(layer, colorspace, area, mask, buffer)) {
+ full_coverage = true;
+ break;
}
}
- // TODO: Tiled layer
}
- return false;
+ return full_coverage;
}
-bool displayio_group_needs_refresh(displayio_group_t *self) {
- if (self->needs_refresh) {
- return true;
- }
+void displayio_group_finish_refresh(displayio_group_t *self) {
+ self->item_removed = false;
for (int32_t i = self->size - 1; i >= 0 ; i--) {
- mp_obj_t layer = self->children[i];
- if (MP_OBJ_IS_TYPE(layer, &displayio_sprite_type)) {
- if (displayio_sprite_needs_refresh(layer)) {
- return true;
- }
+ mp_obj_t layer = self->children[i].native;
+#if CIRCUITPY_VECTORIO
+ if (MP_OBJ_IS_TYPE(layer, &vectorio_vector_shape_type)) {
+ vectorio_vector_shape_finish_refresh(layer);
+ }
+ else
+#endif
+ if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) {
+ displayio_tilegrid_finish_refresh(layer);
+ } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) {
+ displayio_group_finish_refresh(layer);
}
- // TODO: Tiled layer
}
- return false;
}
-void displayio_group_finish_refresh(displayio_group_t *self) {
- self->needs_refresh = false;
+displayio_area_t* displayio_group_get_refresh_areas(displayio_group_t *self, displayio_area_t* tail) {
+ if (self->item_removed) {
+ self->dirty_area.next = tail;
+ tail = &self->dirty_area;
+ }
+
for (int32_t i = self->size - 1; i >= 0 ; i--) {
- mp_obj_t layer = self->children[i];
- if (MP_OBJ_IS_TYPE(layer, &displayio_sprite_type)) {
- displayio_sprite_finish_refresh(layer);
+ mp_obj_t layer = self->children[i].native;
+#if CIRCUITPY_VECTORIO
+ if (MP_OBJ_IS_TYPE(layer, &vectorio_vector_shape_type)) {
+ tail = vectorio_vector_shape_get_refresh_areas(layer, tail);
+ }
+ else
+#endif
+ if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) {
+ tail = displayio_tilegrid_get_refresh_areas(layer, tail);
+ } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) {
+ tail = displayio_group_get_refresh_areas(layer, tail);
}
- // TODO: Tiled layer
}
+
+ return tail;
}
diff --git a/shared-module/displayio/Group.h b/shared-module/displayio/Group.h
index 272f3114c..5afaac1ba 100644
--- a/shared-module/displayio/Group.h
+++ b/shared-module/displayio/Group.h
@@ -31,24 +31,37 @@
#include <stdint.h>
#include "py/obj.h"
+#include "shared-module/displayio/area.h"
+#include "shared-module/displayio/Palette.h"
+
+typedef struct {
+ mp_obj_t native;
+ mp_obj_t original;
+} displayio_group_child_t;
typedef struct {
mp_obj_base_t base;
+ displayio_group_child_t* children;
+ displayio_buffer_transform_t absolute_transform;
+ displayio_area_t dirty_area; // Catch all for changed area
int16_t x;
int16_t y;
+ uint16_t scale;
uint16_t size;
uint16_t max_size;
- mp_obj_t* children;
- bool needs_refresh;
+ bool item_removed :1;
+ bool in_group :1;
+ bool hidden :1;
+ bool hidden_by_parent :1;
+ uint8_t padding :4;
} displayio_group_t;
-
-void common_hal_displayio_group_construct(displayio_group_t* self, uint32_t max_size);
-void common_hal_displayio_group_append(displayio_group_t* self, mp_obj_t layer);
-
-void displayio_group_construct(displayio_group_t* self, mp_obj_t* child_array, uint32_t max_size);
-bool displayio_group_get_pixel(displayio_group_t *group, int16_t x, int16_t y, uint16_t *pixel);
-bool displayio_group_needs_refresh(displayio_group_t *self);
+void displayio_group_construct(displayio_group_t* self, displayio_group_child_t* child_array, uint32_t max_size, uint32_t scale, mp_int_t x, mp_int_t y);
+void displayio_group_set_hidden_by_parent(displayio_group_t *self, bool hidden);
+bool displayio_group_get_previous_area(displayio_group_t *group, displayio_area_t* area);
+bool displayio_group_fill_area(displayio_group_t *group, const _displayio_colorspace_t* colorspace, const displayio_area_t* area, uint32_t* mask, uint32_t *buffer);
+void displayio_group_update_transform(displayio_group_t *group, const displayio_buffer_transform_t* parent_transform);
void displayio_group_finish_refresh(displayio_group_t *self);
+displayio_area_t* displayio_group_get_refresh_areas(displayio_group_t *self, displayio_area_t* tail);
#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_GROUP_H
diff --git a/shared-module/displayio/I2CDisplay.c b/shared-module/displayio/I2CDisplay.c
new file mode 100644
index 000000000..0c8f2e69a
--- /dev/null
+++ b/shared-module/displayio/I2CDisplay.c
@@ -0,0 +1,123 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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 "shared-bindings/displayio/I2CDisplay.h"
+
+#include <stdint.h>
+#include <string.h>
+
+#include "py/gc.h"
+#include "py/runtime.h"
+#include "shared-bindings/busio/I2C.h"
+#include "shared-bindings/digitalio/DigitalInOut.h"
+#include "shared-bindings/microcontroller/Pin.h"
+#include "shared-bindings/microcontroller/__init__.h"
+#include "shared-bindings/time/__init__.h"
+#include "shared-module/displayio/display_core.h"
+
+void common_hal_displayio_i2cdisplay_construct(displayio_i2cdisplay_obj_t* self,
+ busio_i2c_obj_t* i2c, uint16_t device_address, const mcu_pin_obj_t* reset) {
+
+ // Reset the display before probing
+ self->reset.base.type = &mp_type_NoneType;
+ if (reset != NULL) {
+ self->reset.base.type = &digitalio_digitalinout_type;
+ common_hal_digitalio_digitalinout_construct(&self->reset, reset);
+ common_hal_digitalio_digitalinout_switch_to_output(&self->reset, true, DRIVE_MODE_PUSH_PULL);
+ common_hal_never_reset_pin(reset);
+ common_hal_displayio_i2cdisplay_reset(self);
+ }
+
+ // Probe the bus to see if a device acknowledges the given address.
+ if (!common_hal_busio_i2c_probe(i2c, device_address)) {
+ mp_raise_ValueError_varg(translate("Unable to find I2C Display at %x"), device_address);
+ }
+
+ // Write to the device and return 0 on success or an appropriate error code from mperrno.h
+ self->bus = i2c;
+ common_hal_busio_i2c_never_reset(self->bus);
+ // Our object is statically allocated off the heap so make sure the bus object lives to the end
+ // of the heap as well.
+ gc_never_free(self->bus);
+
+ self->address = device_address;
+}
+
+void common_hal_displayio_i2cdisplay_deinit(displayio_i2cdisplay_obj_t* self) {
+ if (self->bus == &self->inline_bus) {
+ common_hal_busio_i2c_deinit(self->bus);
+ }
+
+ common_hal_reset_pin(self->reset.pin);
+}
+
+bool common_hal_displayio_i2cdisplay_reset(mp_obj_t obj) {
+ displayio_i2cdisplay_obj_t* self = MP_OBJ_TO_PTR(obj);
+ if (self->reset.base.type == &mp_type_NoneType) {
+ return false;
+ }
+
+ common_hal_digitalio_digitalinout_set_value(&self->reset, false);
+ common_hal_mcu_delay_us(4);
+ common_hal_digitalio_digitalinout_set_value(&self->reset, true);
+ return true;
+}
+
+bool common_hal_displayio_i2cdisplay_bus_free(mp_obj_t obj) {
+ displayio_i2cdisplay_obj_t* self = MP_OBJ_TO_PTR(obj);
+ if (!common_hal_busio_i2c_try_lock(self->bus)) {
+ return false;
+ }
+ common_hal_busio_i2c_unlock(self->bus);
+ return true;
+}
+
+bool common_hal_displayio_i2cdisplay_begin_transaction(mp_obj_t obj) {
+ displayio_i2cdisplay_obj_t* self = MP_OBJ_TO_PTR(obj);
+ return common_hal_busio_i2c_try_lock(self->bus);
+}
+
+void common_hal_displayio_i2cdisplay_send(mp_obj_t obj, display_byte_type_t data_type, display_chip_select_behavior_t chip_select, uint8_t *data, uint32_t data_length) {
+ displayio_i2cdisplay_obj_t* self = MP_OBJ_TO_PTR(obj);
+ if (data_type == DISPLAY_COMMAND) {
+ uint8_t command_bytes[2 * data_length];
+ for (uint32_t i = 0; i < data_length; i++) {
+ command_bytes[2 * i] = 0x80;
+ command_bytes[2 * i + 1] = data[i];
+ }
+ common_hal_busio_i2c_write(self->bus, self->address, command_bytes, 2 * data_length, true);
+ } else {
+ uint8_t data_bytes[data_length + 1];
+ data_bytes[0] = 0x40;
+ memcpy(data_bytes + 1, data, data_length);
+ common_hal_busio_i2c_write(self->bus, self->address, data_bytes, data_length + 1, true);
+ }
+}
+
+void common_hal_displayio_i2cdisplay_end_transaction(mp_obj_t obj) {
+ displayio_i2cdisplay_obj_t* self = MP_OBJ_TO_PTR(obj);
+ common_hal_busio_i2c_unlock(self->bus);
+}
diff --git a/shared-module/bleio/Service.h b/shared-module/displayio/I2CDisplay.h
index ff506d3f3..4636c3f73 100644
--- a/shared-module/bleio/Service.h
+++ b/shared-module/displayio/I2CDisplay.h
@@ -3,7 +3,7 @@
*
* The MIT License (MIT)
*
- * Copyright (c) 2018 Artur Pacholec
+ * 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
@@ -24,21 +24,18 @@
* THE SOFTWARE.
*/
-#ifndef MICROPY_INCLUDED_SHARED_MODULE_BLEIO_SERVICE_H
-#define MICROPY_INCLUDED_SHARED_MODULE_BLEIO_SERVICE_H
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_I2CDISPLAY_H
+#define MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_I2CDISPLAY_H
-#include "common-hal/bleio/UUID.h"
-#include "shared-module/bleio/Device.h"
+#include "common-hal/busio/I2C.h"
+#include "common-hal/digitalio/DigitalInOut.h"
typedef struct {
mp_obj_base_t base;
- uint16_t handle;
- bool is_secondary;
- bleio_uuid_obj_t *uuid;
- bleio_device_obj_t *device;
- mp_obj_t char_list;
- uint16_t start_handle;
- uint16_t end_handle;
-} bleio_service_obj_t;
+ busio_i2c_obj_t* bus;
+ busio_i2c_obj_t inline_bus;
+ digitalio_digitalinout_obj_t reset;
+ uint16_t address;
+} displayio_i2cdisplay_obj_t;
-#endif // MICROPY_INCLUDED_SHARED_MODULE_BLEIO_SERVICE_H
+#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_I2CDISPLAY_H
diff --git a/shared-module/displayio/OnDiskBitmap.c b/shared-module/displayio/OnDiskBitmap.c
index 6e4a4c6f0..993fc03de 100644
--- a/shared-module/displayio/OnDiskBitmap.c
+++ b/shared-module/displayio/OnDiskBitmap.c
@@ -38,13 +38,13 @@ static uint32_t read_word(uint16_t* bmp_header, uint16_t index) {
void common_hal_displayio_ondiskbitmap_construct(displayio_ondiskbitmap_t *self, pyb_file_obj_t* file) {
// Load the wave
self->file = file;
- uint16_t bmp_header[24];
+ uint16_t bmp_header[69];
f_rewind(&self->file->fp);
UINT bytes_read;
- if (f_read(&self->file->fp, bmp_header, 48, &bytes_read) != FR_OK) {
+ if (f_read(&self->file->fp, bmp_header, 138, &bytes_read) != FR_OK) {
mp_raise_OSError(MP_EIO);
}
- if (bytes_read != 48 ||
+ if (bytes_read != 138 ||
memcmp(bmp_header, "BM", 2) != 0) {
mp_raise_ValueError(translate("Invalid BMP file"));
}
@@ -53,25 +53,67 @@ void common_hal_displayio_ondiskbitmap_construct(displayio_ondiskbitmap_t *self,
self->data_offset = read_word(bmp_header, 5);
uint32_t header_size = read_word(bmp_header, 7);
- uint32_t compression = read_word(bmp_header, 15);
- if (!(header_size == 12 || header_size == 40 || header_size == 108 || header_size == 124) ||
- !(compression == 0)) {
- mp_raise_ValueError_varg(translate("Only Windows format, uncompressed BMP supported %d"), header_size);
- }
- // TODO(tannewt): Support bitfield compressed colors since RGB565 can be produced by the GIMP.
uint16_t bits_per_pixel = bmp_header[14];
- if (bits_per_pixel < 24) {
- mp_raise_ValueError_varg(translate("Only true color (24 bpp or higher) BMP supported %x"), bits_per_pixel);
- }
- self->bytes_per_pixel = bits_per_pixel / 8;
+ uint32_t compression = read_word(bmp_header, 15);
+ uint32_t number_of_colors = read_word(bmp_header, 23);
+
+ bool indexed = ((bits_per_pixel <= 8) && (number_of_colors != 0));
+ self->bitfield_compressed = (compression == 3);
+ self->bits_per_pixel = bits_per_pixel;
self->width = read_word(bmp_header, 9);
self->height = read_word(bmp_header, 11);
- uint32_t byte_width = self->width * self->bytes_per_pixel;
- self->stride = byte_width;
- // Rows are word aligned.
- if (self->stride % 4 != 0) {
- self->stride += 4 - self->stride % 4;
+
+ if (bits_per_pixel == 16){
+ if (((header_size >= 56)) || (self->bitfield_compressed)) {
+ self->r_bitmask = read_word(bmp_header, 27);
+ self->g_bitmask = read_word(bmp_header, 29);
+ self->b_bitmask = read_word(bmp_header, 31);
+
+ } else { // no compression or short header means 5:5:5
+ self->r_bitmask = 0x7c00;
+ self->g_bitmask = 0x3e0;
+ self->b_bitmask = 0x1f;
+ }
+ } else if (indexed && self->bits_per_pixel != 1) {
+ uint16_t palette_size = number_of_colors * sizeof(uint32_t);
+ uint16_t palette_offset = 0xe + header_size;
+
+ self->palette_data = m_malloc(palette_size, false);
+
+ f_rewind(&self->file->fp);
+ f_lseek(&self->file->fp, palette_offset);
+
+ UINT palette_bytes_read;
+ if (f_read(&self->file->fp, self->palette_data, palette_size, &palette_bytes_read) != FR_OK) {
+ mp_raise_OSError(MP_EIO);
+ }
+ if (palette_bytes_read != palette_size) {
+ mp_raise_ValueError(translate("Unable to read color palette data"));
+ }
+ } else if (!(header_size == 12 || header_size == 40 || header_size == 108 || header_size == 124)) {
+ mp_raise_ValueError_varg(translate("Only Windows format, uncompressed BMP supported: given header size is %d"), header_size);
+ }
+
+ if (bits_per_pixel == 8 && number_of_colors == 0) {
+ mp_raise_ValueError_varg(translate("Only monochrome, indexed 4bpp or 8bpp, and 16bpp or greater BMPs supported: %d bpp given"), bits_per_pixel);
+ }
+
+ uint8_t bytes_per_pixel = (self->bits_per_pixel / 8) ? (self->bits_per_pixel /8) : 1;
+ uint8_t pixels_per_byte = 8 / self->bits_per_pixel;
+ if (pixels_per_byte == 0){
+ self->stride = (self->width * bytes_per_pixel);
+ // Rows are word aligned.
+ if (self->stride % 4 != 0) {
+ self->stride += 4 - self->stride % 4;
+ }
+ } else {
+ uint32_t bit_stride = self->width * self->bits_per_pixel;
+ if (bit_stride % 32 != 0) {
+ bit_stride += 32 - bit_stride % 32;
+ }
+ self->stride = (bit_stride / 8);
}
+
}
@@ -80,14 +122,63 @@ uint32_t common_hal_displayio_ondiskbitmap_get_pixel(displayio_ondiskbitmap_t *s
if (x < 0 || x >= self->width || y < 0 || y >= self->height) {
return 0;
}
- uint32_t location = self->data_offset + (self->height - y) * self->stride + x * self->bytes_per_pixel;
+
+ uint32_t location;
+ uint8_t bytes_per_pixel = (self->bits_per_pixel / 8) ? (self->bits_per_pixel /8) : 1;
+ uint8_t pixels_per_byte = 8 / self->bits_per_pixel;
+ if (pixels_per_byte == 0){
+ location = self->data_offset + (self->height - y - 1) * self->stride + x * bytes_per_pixel;
+ } else {
+ location = self->data_offset + (self->height - y - 1) * self->stride + x / pixels_per_byte;
+ }
// We don't cache here because the underlying FS caches sectors.
f_lseek(&self->file->fp, location);
UINT bytes_read;
- uint32_t pixel = 0;
- uint32_t result = f_read(&self->file->fp, &pixel, self->bytes_per_pixel, &bytes_read);
+ uint32_t pixel_data = 0;
+ uint32_t result = f_read(&self->file->fp, &pixel_data, bytes_per_pixel, &bytes_read);
if (result == FR_OK) {
- return pixel;
+ uint32_t tmp = 0;
+ uint8_t red;
+ uint8_t green;
+ uint8_t blue;
+ if (bytes_per_pixel == 1) {
+ uint8_t offset = (x % pixels_per_byte) * self->bits_per_pixel;
+ uint8_t mask = (1 << self->bits_per_pixel) - 1;
+
+ uint8_t index = (pixel_data >> ((8 - self->bits_per_pixel) - offset)) & mask;
+ if (self->bits_per_pixel == 1) {
+ if (index == 1) {
+ return 0xFFFFFF;
+ } else {
+ return 0x000000;
+ }
+ }
+ return self->palette_data[index];
+ } else if (bytes_per_pixel == 2) {
+ if (self->g_bitmask == 0x07e0) { // 565
+ red =((pixel_data & self->r_bitmask) >>11);
+ green = ((pixel_data & self->g_bitmask) >>5);
+ blue = ((pixel_data & self->b_bitmask) >> 0);
+ } else { // 555
+ red =((pixel_data & self->r_bitmask) >>10);
+ green = ((pixel_data & self->g_bitmask) >>4);
+ blue = ((pixel_data & self->b_bitmask) >> 0);
+ }
+ tmp = (red << 19 | green << 10 | blue << 3);
+ return tmp;
+ } else if ((bytes_per_pixel == 4) && (self->bitfield_compressed)) {
+ return pixel_data & 0x00FFFFFF;
+ } else {
+ return pixel_data;
+ }
}
return 0;
}
+
+uint16_t common_hal_displayio_ondiskbitmap_get_height(displayio_ondiskbitmap_t *self) {
+ return self->height;
+}
+
+uint16_t common_hal_displayio_ondiskbitmap_get_width(displayio_ondiskbitmap_t *self) {
+ return self->width;
+}
diff --git a/shared-module/displayio/OnDiskBitmap.h b/shared-module/displayio/OnDiskBitmap.h
index 31d6c9550..28426f11b 100644
--- a/shared-module/displayio/OnDiskBitmap.h
+++ b/shared-module/displayio/OnDiskBitmap.h
@@ -40,8 +40,13 @@ typedef struct {
uint16_t height;
uint16_t data_offset;
uint16_t stride;
+ uint32_t r_bitmask;
+ uint32_t g_bitmask;
+ uint32_t b_bitmask;
+ bool bitfield_compressed;
pyb_file_obj_t* file;
- uint8_t bytes_per_pixel;
+ uint8_t bits_per_pixel;
+ uint32_t* palette_data;
} displayio_ondiskbitmap_t;
#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_ONDISKBITMAP_H
diff --git a/shared-module/displayio/Palette.c b/shared-module/displayio/Palette.c
index 5f410d786..1ef03aab4 100644
--- a/shared-module/displayio/Palette.c
+++ b/shared-module/displayio/Palette.c
@@ -26,45 +26,70 @@
#include "shared-bindings/displayio/Palette.h"
+#include "shared-module/displayio/ColorConverter.h"
+
void common_hal_displayio_palette_construct(displayio_palette_t* self, uint16_t color_count) {
self->color_count = color_count;
- self->colors = (uint32_t *) m_malloc(color_count * sizeof(uint16_t), false);
- uint32_t opaque_byte_count = color_count / 8;
- if (color_count % 8 > 0) {
- opaque_byte_count += 1;
- }
- self->opaque = (uint32_t *) m_malloc(opaque_byte_count, false);
+ self->colors = (_displayio_color_t *) m_malloc(color_count * sizeof(_displayio_color_t), false);
}
void common_hal_displayio_palette_make_opaque(displayio_palette_t* self, uint32_t palette_index) {
- self->opaque[palette_index / 32] &= ~(0x1 << (palette_index % 32));
+ self->colors[palette_index].transparent = false;
}
void common_hal_displayio_palette_make_transparent(displayio_palette_t* self, uint32_t palette_index) {
- self->opaque[palette_index / 32] |= (0x1 << (palette_index % 32));
+ self->colors[palette_index].transparent = true;
+}
+
+uint32_t common_hal_displayio_palette_get_len(displayio_palette_t* self) {
+ return self->color_count;
}
void common_hal_displayio_palette_set_color(displayio_palette_t* self, uint32_t palette_index, uint32_t color) {
- uint32_t shift = (palette_index % 2) * 16;
- uint32_t masked = self->colors[palette_index / 2] & ~(0xffff << shift);
- uint32_t b5 = (color >> 19);
- uint32_t g6 = (color >> 10) & 0x3f;
- uint32_t r5 = (color >> 3) & 0x1f;
- uint32_t packed = r5 << 11 | g6 << 5 | b5;
- // swap bytes
- packed = __builtin_bswap16(packed);
- self->colors[palette_index / 2] = masked | packed << shift;
+ if (self->colors[palette_index].rgb888 == color) {
+ return;
+ }
+ self->colors[palette_index].rgb888 = color;
+ self->colors[palette_index].luma = displayio_colorconverter_compute_luma(color);
+ self->colors[palette_index].rgb565 = displayio_colorconverter_compute_rgb565(color);
+
+ uint8_t chroma = displayio_colorconverter_compute_chroma(color);
+ self->colors[palette_index].chroma = chroma;
+ self->colors[palette_index].hue = displayio_colorconverter_compute_hue(color);
self->needs_refresh = true;
}
-bool displayio_palette_get_color(displayio_palette_t *self, uint32_t palette_index, uint16_t* color) {
- if (palette_index > self->color_count) {
- return false;
+uint32_t common_hal_displayio_palette_get_color(displayio_palette_t* self, uint32_t palette_index) {
+ return self->colors[palette_index].rgb888;
+}
+
+bool displayio_palette_get_color(displayio_palette_t *self, const _displayio_colorspace_t* colorspace, uint32_t palette_index, uint32_t* color) {
+ if (palette_index > self->color_count || self->colors[palette_index].transparent) {
+ return false; // returns opaque
}
- if ((self->opaque[palette_index / 32] & (0x1 << (palette_index % 32))) != 0) {
- return false;
+
+ if (colorspace->tricolor) {
+ uint8_t luma = self->colors[palette_index].luma;
+ *color = luma >> (8 - colorspace->depth);
+ // Chroma 0 means the color is a gray and has no hue so never color based on it.
+ if (self->colors[palette_index].chroma <= 16) {
+ if (!colorspace->grayscale) {
+ *color = 0;
+ }
+ return true;
+ }
+ uint8_t pixel_hue = self->colors[palette_index].hue;
+ displayio_colorconverter_compute_tricolor(colorspace, pixel_hue, luma, color);
+ } else if (colorspace->grayscale) {
+ *color = self->colors[palette_index].luma >> (8 - colorspace->depth);
+ } else {
+ uint16_t packed = self->colors[palette_index].rgb565;
+ if (colorspace->reverse_bytes_in_word) {
+ // swap bytes
+ packed = __builtin_bswap16(packed);
+ }
+ *color = packed;
}
- *color = (self->colors[palette_index / 2] >> (16 * (palette_index % 2))) & 0xffff;
return true;
}
diff --git a/shared-module/displayio/Palette.h b/shared-module/displayio/Palette.h
index 5a5f1d287..da72f250f 100644
--- a/shared-module/displayio/Palette.h
+++ b/shared-module/displayio/Palette.h
@@ -33,14 +33,51 @@
#include "py/obj.h"
typedef struct {
+ uint8_t depth;
+ uint8_t bytes_per_cell;
+ uint8_t tricolor_hue;
+ uint8_t tricolor_luma;
+ bool grayscale;
+ bool tricolor;
+ bool pixels_in_byte_share_row;
+ bool reverse_pixels_in_byte;
+ bool reverse_bytes_in_word;
+ bool dither;
+} _displayio_colorspace_t;
+
+typedef struct {
+ uint32_t rgb888;
+ uint16_t rgb565;
+ uint8_t luma;
+ uint8_t hue;
+ uint8_t chroma;
+ bool transparent; // This may have additional bits added later for blending.
+} _displayio_color_t;
+
+typedef struct {
+ uint32_t pixel;
+ uint16_t x;
+ uint16_t y;
+ uint8_t tile;
+ uint16_t tile_x;
+ uint16_t tile_y;
+} displayio_input_pixel_t;
+
+typedef struct {
+ uint32_t pixel;
+ bool opaque;
+} displayio_output_pixel_t;
+
+typedef struct {
mp_obj_base_t base;
- uint32_t* opaque;
- uint32_t* colors;
- uint8_t color_count;
+ _displayio_color_t* colors;
+ uint32_t color_count;
bool needs_refresh;
} displayio_palette_t;
-bool displayio_palette_get_color(displayio_palette_t *palette, uint32_t palette_index, uint16_t* color);
+// Returns false if color fetch did not succeed (out of range or transparent).
+// Returns true if color is opaque, and sets color.
+bool displayio_palette_get_color(displayio_palette_t *palette, const _displayio_colorspace_t* colorspace, uint32_t palette_index, uint32_t* color);
bool displayio_palette_needs_refresh(displayio_palette_t *self);
void displayio_palette_finish_refresh(displayio_palette_t *self);
diff --git a/shared-module/displayio/Shape.c b/shared-module/displayio/Shape.c
new file mode 100644
index 000000000..ab9ca735b
--- /dev/null
+++ b/shared-module/displayio/Shape.c
@@ -0,0 +1,90 @@
+/*
+ * This file is part of the Micro Python 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.
+ */
+
+#include "shared-bindings/displayio/Shape.h"
+
+#include <string.h>
+
+#include "py/runtime.h"
+
+void common_hal_displayio_shape_construct(displayio_shape_t *self, uint32_t width,
+ uint32_t height, bool mirror_x, bool mirror_y) {
+ self->mirror_x = mirror_x;
+ self->mirror_y = mirror_y;
+ self->width = width;
+ if (self->mirror_x) {
+ width /= 2;
+ width += self->width % 2 - 1;
+ }
+ self->half_width = width;
+
+ self->height = height;
+ if (self->mirror_y) {
+ height /= 2;
+ height += self->height % 2 - 1;
+ }
+ self->half_height = height;
+
+ self->data = m_malloc(height * sizeof(uint32_t), false);
+ for (uint16_t i = 0; i <= height; i++) {
+ self->data[2 * i] = 0;
+ self->data[2 * i + 1] = width;
+ }
+}
+
+void common_hal_displayio_shape_set_boundary(displayio_shape_t *self, uint16_t y, uint16_t start_x, uint16_t end_x) {
+ if (y < 0 || y >= self->height || (self->mirror_y && y > self->half_height)) {
+ mp_raise_ValueError(translate("y value out of bounds"));
+ }
+ if (start_x < 0 || start_x > self->width || end_x < 0 || end_x > self->width) {
+ mp_raise_ValueError(translate("x value out of bounds"));
+ }
+ uint16_t half_width = self->width / 2 - 1 + self->width % 2;
+ if (self->mirror_x && (start_x > half_width || end_x > half_width)) {
+ mp_raise_ValueError_varg(translate("Maximum x value when mirrored is %d"), half_width);
+ }
+ self->data[2 * y] = start_x;
+ self->data[2 * y + 1] = end_x;
+}
+
+uint32_t common_hal_displayio_shape_get_pixel(void *obj, int16_t x, int16_t y) {
+ displayio_shape_t *self = obj;
+ if (x >= self->width || x < 0 || y >= self->height || y < 0) {
+ return 0;
+ }
+ if (self->mirror_x && x > self->half_width) {
+ x = self->width - 1 - x;
+ }
+ if (self->mirror_y && y > self->half_height) {
+ y = self->height - y - 1;
+ }
+ uint16_t start_x = self->data[2 * y];
+ uint16_t end_x = self->data[2 * y + 1];
+ if (x < start_x || x > end_x) {
+ return 0;
+ }
+ return 1;
+}
diff --git a/shared-module/displayio/Shape.h b/shared-module/displayio/Shape.h
new file mode 100644
index 000000000..ca054fe00
--- /dev/null
+++ b/shared-module/displayio/Shape.h
@@ -0,0 +1,46 @@
+/*
+ * This file is part of the Micro Python 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.
+ */
+
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_SHAPE_H
+#define MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_SHAPE_H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "py/obj.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ uint16_t width;
+ uint16_t height;
+ uint16_t half_width;
+ uint16_t half_height;
+ uint16_t* data;
+ bool mirror_x;
+ bool mirror_y;
+} displayio_shape_t;
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_SHAPE_H
diff --git a/shared-module/displayio/Sprite.c b/shared-module/displayio/Sprite.c
deleted file mode 100644
index 87600f721..000000000
--- a/shared-module/displayio/Sprite.c
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * This file is part of the Micro Python project, http://micropython.org/
- *
- * The MIT License (MIT)
- *
- * Copyright (c) 2018 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 "shared-bindings/displayio/Sprite.h"
-
-#include "shared-bindings/displayio/Bitmap.h"
-#include "shared-bindings/displayio/ColorConverter.h"
-#include "shared-bindings/displayio/OnDiskBitmap.h"
-#include "shared-bindings/displayio/Palette.h"
-
-void common_hal_displayio_sprite_construct(displayio_sprite_t *self, mp_obj_t bitmap,
- mp_obj_t pixel_shader, uint16_t width, uint16_t height, uint16_t x, uint16_t y) {
- self->width = width;
- self->height = height;
- self->bitmap = bitmap;
- self->pixel_shader = pixel_shader;
- self->x = x;
- self->y = y;
-}
-
-void common_hal_displayio_sprite_get_position(displayio_sprite_t *self, int16_t* x, int16_t* y) {
- *x = self->x;
- *y = self->y;
-}
-
-void common_hal_displayio_sprite_set_position(displayio_sprite_t *self, int16_t x, int16_t y) {
- self->x = x;
- self->y = y;
- self->needs_refresh = true;
-}
-
-
-mp_obj_t common_hal_displayio_sprite_get_pixel_shader(displayio_sprite_t *self) {
- return self->pixel_shader;
-}
-
-void common_hal_displayio_sprite_set_pixel_shader(displayio_sprite_t *self, mp_obj_t pixel_shader) {
- self->pixel_shader = pixel_shader;
- self->needs_refresh = true;
-}
-
-bool displayio_sprite_get_pixel(displayio_sprite_t *self, int16_t x, int16_t y, uint16_t* pixel) {
- x -= self->x;
- y -= self->y;
- if (y < 0 || y >= self->height || x >= self->width || x < 0) {
- return false;
- }
- uint32_t value = 0;
- if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_bitmap_type)) {
- value = common_hal_displayio_bitmap_get_pixel(self->bitmap, x, y);
- } else if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_ondiskbitmap_type)) {
- value = common_hal_displayio_ondiskbitmap_get_pixel(self->bitmap, x, y);
- }
-
- if (self->pixel_shader == mp_const_none) {
- *pixel = value;
- return true;
- } else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type) && displayio_palette_get_color(self->pixel_shader, value, pixel)) {
- return true;
- } else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type) && common_hal_displayio_colorconverter_convert(self->pixel_shader, value, pixel)) {
- return true;
- }
-
- return false;
-}
-
-bool displayio_sprite_needs_refresh(displayio_sprite_t *self) {
- return self->needs_refresh || displayio_palette_needs_refresh(self->pixel_shader);
-}
-
-void displayio_sprite_finish_refresh(displayio_sprite_t *self) {
- self->needs_refresh = false;
- displayio_palette_finish_refresh(self->pixel_shader);
- // TODO(tannewt): We could double buffer changes to position and move them over here.
- // That way they won't change during a refresh and tear.
-}
diff --git a/shared-module/displayio/TileGrid.c b/shared-module/displayio/TileGrid.c
new file mode 100644
index 000000000..2766cbecd
--- /dev/null
+++ b/shared-module/displayio/TileGrid.c
@@ -0,0 +1,587 @@
+/*
+ * This file is part of the Micro Python project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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 "shared-bindings/displayio/TileGrid.h"
+
+#include "py/runtime.h"
+#include "shared-bindings/displayio/Bitmap.h"
+#include "shared-bindings/displayio/ColorConverter.h"
+#include "shared-bindings/displayio/OnDiskBitmap.h"
+#include "shared-bindings/displayio/Palette.h"
+#include "shared-bindings/displayio/Shape.h"
+
+void common_hal_displayio_tilegrid_construct(displayio_tilegrid_t *self, mp_obj_t bitmap,
+ uint16_t bitmap_width_in_tiles, uint16_t bitmap_height_in_tiles,
+ mp_obj_t pixel_shader, uint16_t width, uint16_t height,
+ uint16_t tile_width, uint16_t tile_height, uint16_t x, uint16_t y, uint8_t default_tile) {
+ uint32_t total_tiles = width * height;
+ // Sprites will only have one tile so save a little memory by inlining values in the pointer.
+ uint8_t inline_tiles = sizeof(uint8_t*);
+ if (total_tiles <= inline_tiles) {
+ self->tiles = 0;
+ // Pack values into the pointer since there are only a few.
+ for (uint32_t i = 0; i < inline_tiles; i++) {
+ ((uint8_t*) &self->tiles)[i] = default_tile;
+ }
+ self->inline_tiles = true;
+ } else {
+ self->tiles = (uint8_t*) m_malloc(total_tiles, false);
+ for (uint32_t i = 0; i < total_tiles; i++) {
+ self->tiles[i] = default_tile;
+ }
+ self->inline_tiles = false;
+ }
+ self->bitmap_width_in_tiles = bitmap_width_in_tiles;
+ self->tiles_in_bitmap = bitmap_width_in_tiles * bitmap_height_in_tiles;
+ self->width_in_tiles = width;
+ self->height_in_tiles = height;
+ self->x = x;
+ self->y = y;
+ self->pixel_width = width * tile_width;
+ self->pixel_height = height * tile_height;
+ self->tile_width = tile_width;
+ self->tile_height = tile_height;
+ self->bitmap = bitmap;
+ self->pixel_shader = pixel_shader;
+ self->in_group = false;
+ self->hidden = false;
+ self->hidden_by_parent = false;
+ self->previous_area.x1 = 0xffff;
+ self->previous_area.x2 = self->previous_area.x1;
+ self->flip_x = false;
+ self->flip_y = false;
+ self->transpose_xy = false;
+}
+
+
+bool common_hal_displayio_tilegrid_get_hidden(displayio_tilegrid_t* self) {
+ return self->hidden;
+}
+
+void common_hal_displayio_tilegrid_set_hidden(displayio_tilegrid_t* self, bool hidden) {
+ self->hidden = hidden;
+}
+
+void displayio_tilegrid_set_hidden_by_parent(displayio_tilegrid_t *self, bool hidden) {
+ self->hidden_by_parent = hidden;
+}
+
+bool displayio_tilegrid_get_previous_area(displayio_tilegrid_t *self, displayio_area_t* area) {
+ if (self->previous_area.x1 == self->previous_area.x2) {
+ return false;
+ }
+ displayio_area_copy(&self->previous_area, area);
+ return true;
+}
+
+void _update_current_x(displayio_tilegrid_t *self) {
+ int16_t width;
+ if (self->transpose_xy) {
+ width = self->pixel_height;
+ } else {
+ width = self->pixel_width;
+ }
+ if (self->absolute_transform->transpose_xy) {
+ self->current_area.y1 = self->absolute_transform->y + self->absolute_transform->dy * self->x;
+ self->current_area.y2 = self->absolute_transform->y + self->absolute_transform->dy * (self->x + width);
+ if (self->current_area.y2 < self->current_area.y1) {
+ int16_t temp = self->current_area.y2;
+ self->current_area.y2 = self->current_area.y1;
+ self->current_area.y1 = temp;
+ }
+ } else {
+ self->current_area.x1 = self->absolute_transform->x + self->absolute_transform->dx * self->x;
+ self->current_area.x2 = self->absolute_transform->x + self->absolute_transform->dx * (self->x + width);
+ if (self->current_area.x2 < self->current_area.x1) {
+ int16_t temp = self->current_area.x2;
+ self->current_area.x2 = self->current_area.x1;
+ self->current_area.x1 = temp;
+ }
+ }
+}
+
+void _update_current_y(displayio_tilegrid_t *self) {
+ int16_t height;
+ if (self->transpose_xy) {
+ height = self->pixel_width;
+ } else {
+ height = self->pixel_height;
+ }
+ if (self->absolute_transform->transpose_xy) {
+ self->current_area.x1 = self->absolute_transform->x + self->absolute_transform->dx * self->y;
+ self->current_area.x2 = self->absolute_transform->x + self->absolute_transform->dx * (self->y + height);
+ if (self->current_area.x2 < self->current_area.x1) {
+ int16_t temp = self->current_area.x2;
+ self->current_area.x2 = self->current_area.x1;
+ self->current_area.x1 = temp;
+ }
+ } else {
+ self->current_area.y1 = self->absolute_transform->y + self->absolute_transform->dy * self->y;
+ self->current_area.y2 = self->absolute_transform->y + self->absolute_transform->dy * (self->y + height);
+ if (self->current_area.y2 < self->current_area.y1) {
+ int16_t temp = self->current_area.y2;
+ self->current_area.y2 = self->current_area.y1;
+ self->current_area.y1 = temp;
+ }
+ }
+}
+
+void displayio_tilegrid_update_transform(displayio_tilegrid_t *self,
+ const displayio_buffer_transform_t* absolute_transform) {
+ self->in_group = absolute_transform != NULL;
+ self->absolute_transform = absolute_transform;
+ if (absolute_transform != NULL) {
+ self->moved = true;
+
+ _update_current_x(self);
+ _update_current_y(self);
+ }
+}
+
+mp_int_t common_hal_displayio_tilegrid_get_x(displayio_tilegrid_t *self) {
+ return self->x;
+}
+void common_hal_displayio_tilegrid_set_x(displayio_tilegrid_t *self, mp_int_t x) {
+ if (self->x == x) {
+ return;
+ }
+
+ self->moved = true;
+
+ self->x = x;
+ if (self->absolute_transform != NULL) {
+ _update_current_x(self);
+ }
+}
+mp_int_t common_hal_displayio_tilegrid_get_y(displayio_tilegrid_t *self) {
+ return self->y;
+}
+
+void common_hal_displayio_tilegrid_set_y(displayio_tilegrid_t *self, mp_int_t y) {
+ if (self->y == y) {
+ return;
+ }
+ self->moved = true;
+ self->y = y;
+ if (self->absolute_transform != NULL) {
+ _update_current_y(self);
+ }
+}
+
+mp_obj_t common_hal_displayio_tilegrid_get_pixel_shader(displayio_tilegrid_t *self) {
+ return self->pixel_shader;
+}
+
+void common_hal_displayio_tilegrid_set_pixel_shader(displayio_tilegrid_t *self, mp_obj_t pixel_shader) {
+ self->pixel_shader = pixel_shader;
+ self->full_change = true;
+}
+
+uint16_t common_hal_displayio_tilegrid_get_width(displayio_tilegrid_t *self) {
+ return self->width_in_tiles;
+}
+
+uint16_t common_hal_displayio_tilegrid_get_height(displayio_tilegrid_t *self) {
+ return self->height_in_tiles;
+}
+
+uint8_t common_hal_displayio_tilegrid_get_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y) {
+ uint8_t* tiles = self->tiles;
+ if (self->inline_tiles) {
+ tiles = (uint8_t*) &self->tiles;
+ }
+ if (tiles == NULL) {
+ return 0;
+ }
+ return tiles[y * self->width_in_tiles + x];
+}
+
+void common_hal_displayio_tilegrid_set_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y, uint8_t tile_index) {
+ if (tile_index >= self->tiles_in_bitmap) {
+ mp_raise_ValueError(translate("Tile index out of bounds"));
+ }
+ uint8_t* tiles = self->tiles;
+ if (self->inline_tiles) {
+ tiles = (uint8_t*) &self->tiles;
+ }
+ if (tiles == NULL) {
+ return;
+ }
+ tiles[y * self->width_in_tiles + x] = tile_index;
+ displayio_area_t temp_area;
+ displayio_area_t* tile_area;
+ if (!self->partial_change) {
+ tile_area = &self->dirty_area;
+ } else {
+ tile_area = &temp_area;
+ }
+ int16_t tx = (x - self->top_left_x) % self->width_in_tiles;
+ if (tx < 0) {
+ tx += self->width_in_tiles;
+ }
+ tile_area->x1 = tx * self->tile_width;
+ tile_area->x2 = tile_area->x1 + self->tile_width;
+ int16_t ty = (y - self->top_left_y) % self->height_in_tiles;
+ if (ty < 0) {
+ ty += self->height_in_tiles;
+ }
+ tile_area->y1 = ty * self->tile_height;
+ tile_area->y2 = tile_area->y1 + self->tile_height;
+
+ if (self->partial_change) {
+ displayio_area_expand(&self->dirty_area, &temp_area);
+ }
+
+ self->partial_change = true;
+}
+
+bool common_hal_displayio_tilegrid_get_flip_x(displayio_tilegrid_t *self) {
+ return self->flip_x;
+}
+
+void common_hal_displayio_tilegrid_set_flip_x(displayio_tilegrid_t *self, bool flip_x) {
+ if (self->flip_x == flip_x) {
+ return;
+ }
+ self->flip_x = flip_x;
+ self->full_change = true;
+}
+
+bool common_hal_displayio_tilegrid_get_flip_y(displayio_tilegrid_t *self) {
+ return self->flip_y;
+}
+
+void common_hal_displayio_tilegrid_set_flip_y(displayio_tilegrid_t *self, bool flip_y) {
+ if (self->flip_y == flip_y) {
+ return;
+ }
+ self->flip_y = flip_y;
+ self->full_change = true;
+}
+
+bool common_hal_displayio_tilegrid_get_transpose_xy(displayio_tilegrid_t *self) {
+ return self->transpose_xy;
+}
+
+void common_hal_displayio_tilegrid_set_transpose_xy(displayio_tilegrid_t *self, bool transpose_xy) {
+ if (self->transpose_xy == transpose_xy) {
+ return;
+ }
+ self->transpose_xy = transpose_xy;
+
+ // Square TileGrids do not change dimensions when transposed.
+ if (self->pixel_width == self->pixel_height) {
+ self->full_change = true;
+ return;
+ }
+
+ _update_current_x(self);
+ _update_current_y(self);
+
+ self->moved = true;
+}
+
+void common_hal_displayio_tilegrid_set_top_left(displayio_tilegrid_t *self, uint16_t x, uint16_t y) {
+ self->top_left_x = x;
+ self->top_left_y = y;
+ self->full_change = true;
+}
+
+bool displayio_tilegrid_fill_area(displayio_tilegrid_t *self, const _displayio_colorspace_t* colorspace, const displayio_area_t* area, uint32_t* mask, uint32_t *buffer) {
+ // If no tiles are present we have no impact.
+ uint8_t* tiles = self->tiles;
+ if (self->inline_tiles) {
+ tiles = (uint8_t*) &self->tiles;
+ }
+ if (tiles == NULL) {
+ return false;
+ }
+
+ bool hidden = self->hidden || self->hidden_by_parent;
+ if (hidden) {
+ return false;
+ }
+
+ displayio_area_t overlap;
+ if (!displayio_area_compute_overlap(area, &self->current_area, &overlap)) {
+ return false;
+ }
+
+ int16_t x_stride = 1;
+ int16_t y_stride = displayio_area_width(area);
+
+ bool flip_x = self->flip_x;
+ bool flip_y = self->flip_y;
+ if (self->transpose_xy != self->absolute_transform->transpose_xy) {
+ bool temp_flip = flip_x;
+ flip_x = flip_y;
+ flip_y = temp_flip;
+ }
+
+ // How many pixels are outside of our area between us and the start of the row.
+ uint16_t start = 0;
+ if ((self->absolute_transform->dx < 0) != flip_x) {
+ start += (area->x2 - area->x1 - 1) * x_stride;
+ x_stride *= -1;
+ }
+ if ((self->absolute_transform->dy < 0) != flip_y) {
+ start += (area->y2 - area->y1 - 1) * y_stride;
+ y_stride *= -1;
+ }
+
+ // Track if this layer finishes filling in the given area. We can ignore any remaining
+ // layers at that point.
+ bool full_coverage = displayio_area_equal(area, &overlap);
+
+ // TODO(tannewt): Skip coverage tracking if all pixels outside the overlap have already been
+ // set and our palette is all opaque.
+
+ // TODO(tannewt): Check to see if the pixel_shader has any transparency. If it doesn't then we
+ // can either return full coverage or bulk update the mask.
+ displayio_area_t transformed;
+ displayio_area_transform_within(flip_x != (self->absolute_transform->dx < 0), flip_y != (self->absolute_transform->dy < 0), self->transpose_xy != self->absolute_transform->transpose_xy,
+ &overlap,
+ &self->current_area,
+ &transformed);
+
+ int16_t start_x = (transformed.x1 - self->current_area.x1);
+ int16_t end_x = (transformed.x2 - self->current_area.x1);
+ int16_t start_y = (transformed.y1 - self->current_area.y1);
+ int16_t end_y = (transformed.y2 - self->current_area.y1);
+
+ int16_t y_shift = 0;
+ int16_t x_shift = 0;
+ if ((self->absolute_transform->dx < 0) != flip_x) {
+ x_shift = area->x2 - overlap.x2;
+ } else {
+ x_shift = overlap.x1 - area->x1;
+ }
+ if ((self->absolute_transform->dy < 0) != flip_y) {
+ y_shift = area->y2 - overlap.y2;
+ } else {
+ y_shift = overlap.y1 - area->y1;
+ }
+
+ // This untransposes x and y so it aligns with bitmap rows.
+ if (self->transpose_xy != self->absolute_transform->transpose_xy) {
+ int16_t temp_stride = x_stride;
+ x_stride = y_stride;
+ y_stride = temp_stride;
+ int16_t temp_shift = x_shift;
+ x_shift = y_shift;
+ y_shift = temp_shift;
+ }
+
+ uint8_t pixels_per_byte = 8 / colorspace->depth;
+
+ displayio_input_pixel_t input_pixel;
+ displayio_output_pixel_t output_pixel;
+
+ for (input_pixel.y = start_y; input_pixel.y < end_y; ++input_pixel.y) {
+ int16_t row_start = start + (input_pixel.y - start_y + y_shift) * y_stride; // in pixels
+ int16_t local_y = input_pixel.y / self->absolute_transform->scale;
+ for (input_pixel.x = start_x; input_pixel.x < end_x; ++input_pixel.x) {
+ // Compute the destination pixel in the buffer and mask based on the transformations.
+ int16_t offset = row_start + (input_pixel.x - start_x + x_shift) * x_stride; // in pixels
+
+ // This is super useful for debugging out of range accesses. Uncomment to use.
+ // if (offset < 0 || offset >= (int32_t) displayio_area_size(area)) {
+ // asm("bkpt");
+ // }
+
+ // Check the mask first to see if the pixel has already been set.
+ if ((mask[offset / 32] & (1 << (offset % 32))) != 0) {
+ continue;
+ }
+ int16_t local_x = input_pixel.x / self->absolute_transform->scale;
+ uint16_t tile_location = ((local_y / self->tile_height + self->top_left_y) % self->height_in_tiles) * self->width_in_tiles + (local_x / self->tile_width + self->top_left_x) % self->width_in_tiles;
+ input_pixel.tile = tiles[tile_location];
+ input_pixel.tile_x = (input_pixel.tile % self->bitmap_width_in_tiles) * self->tile_width + local_x % self->tile_width;
+ input_pixel.tile_y = (input_pixel.tile / self->bitmap_width_in_tiles) * self->tile_height + local_y % self->tile_height;
+
+ //uint32_t value = 0;
+ output_pixel.pixel = 0;
+ input_pixel.pixel = 0;
+
+ // We always want to read bitmap pixels by row first and then transpose into the destination
+ // buffer because most bitmaps are row associated.
+ if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_bitmap_type)) {
+ input_pixel.pixel = common_hal_displayio_bitmap_get_pixel(self->bitmap, input_pixel.tile_x, input_pixel.tile_y);
+ } else if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_shape_type)) {
+ input_pixel.pixel = common_hal_displayio_shape_get_pixel(self->bitmap, input_pixel.tile_x, input_pixel.tile_y);
+ } else if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_ondiskbitmap_type)) {
+ input_pixel.pixel = common_hal_displayio_ondiskbitmap_get_pixel(self->bitmap, input_pixel.tile_x, input_pixel.tile_y);
+ }
+
+ output_pixel.opaque = true;
+ if (self->pixel_shader == mp_const_none) {
+ output_pixel.pixel = input_pixel.pixel;
+ } else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type)) {
+ output_pixel.opaque = displayio_palette_get_color(self->pixel_shader, colorspace, input_pixel.pixel, &output_pixel.pixel);
+ } else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type)) {
+ displayio_colorconverter_convert(self->pixel_shader, colorspace, &input_pixel, &output_pixel);
+ }
+ if (!output_pixel.opaque) {
+ // A pixel is transparent so we haven't fully covered the area ourselves.
+ full_coverage = false;
+ } else {
+ mask[offset / 32] |= 1 << (offset % 32);
+ if (colorspace->depth == 16) {
+ *(((uint16_t*) buffer) + offset) = output_pixel.pixel;
+ } else if (colorspace->depth == 8) {
+ *(((uint8_t*) buffer) + offset) = output_pixel.pixel;
+ } else if (colorspace->depth < 8) {
+ // Reorder the offsets to pack multiple rows into a byte (meaning they share a column).
+ if (!colorspace->pixels_in_byte_share_row) {
+ uint16_t width = displayio_area_width(area);
+ uint16_t row = offset / width;
+ uint16_t col = offset % width;
+ // Dividing by pixels_per_byte does truncated division even if we multiply it back out.
+ offset = col * pixels_per_byte + (row / pixels_per_byte) * pixels_per_byte * width + row % pixels_per_byte;
+ // Also useful for validating that the bitpacking worked correctly.
+ // if (offset > displayio_area_size(area)) {
+ // asm("bkpt");
+ // }
+ }
+ uint8_t shift = (offset % pixels_per_byte) * colorspace->depth;
+ if (colorspace->reverse_pixels_in_byte) {
+ // Reverse the shift by subtracting it from the leftmost shift.
+ shift = (pixels_per_byte - 1) * colorspace->depth - shift;
+ }
+ ((uint8_t*)buffer)[offset / pixels_per_byte] |= output_pixel.pixel << shift;
+ }
+ }
+ }
+ }
+ return full_coverage;
+}
+
+void displayio_tilegrid_finish_refresh(displayio_tilegrid_t *self) {
+ bool first_draw = self->previous_area.x1 == self->previous_area.x2;
+ bool hidden = self->hidden || self->hidden_by_parent;
+ if (!first_draw && hidden) {
+ self->previous_area.x2 = self->previous_area.x1;
+ } else if (self->moved || first_draw) {
+ displayio_area_copy(&self->current_area, &self->previous_area);
+ }
+
+ self->moved = false;
+ self->full_change = false;
+ self->partial_change = false;
+ if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type)) {
+ displayio_palette_finish_refresh(self->pixel_shader);
+ } else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type)) {
+ displayio_colorconverter_finish_refresh(self->pixel_shader);
+ }
+ if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_bitmap_type)) {
+ displayio_bitmap_finish_refresh(self->bitmap);
+ } else if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_shape_type)) {
+ // TODO: Support shape changes.
+ } else if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_ondiskbitmap_type)) {
+ // OnDiskBitmap changes will trigger a complete reload so no need to
+ // track changes.
+ }
+ // TODO(tannewt): We could double buffer changes to position and move them over here.
+ // That way they won't change during a refresh and tear.
+}
+
+displayio_area_t* displayio_tilegrid_get_refresh_areas(displayio_tilegrid_t *self, displayio_area_t* tail) {
+ bool first_draw = self->previous_area.x1 == self->previous_area.x2;
+ bool hidden = self->hidden || self->hidden_by_parent;
+ // Check hidden first because it trumps all other changes.
+ if (hidden) {
+ if (!first_draw) {
+ self->previous_area.next = tail;
+ return &self->previous_area;
+ } else {
+ return tail;
+ }
+ } else if (self->moved && !first_draw) {
+ displayio_area_union(&self->previous_area, &self->current_area, &self->dirty_area);
+ if (displayio_area_size(&self->dirty_area) <= 2U * self->pixel_width * self->pixel_height) {
+ self->dirty_area.next = tail;
+ return &self->dirty_area;
+ }
+ self->previous_area.next = tail;
+ self->current_area.next = &self->previous_area;
+ return &self->current_area;
+ }
+
+ // If we have an in-memory bitmap, then check it for modifications.
+ if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_bitmap_type)) {
+ displayio_area_t* refresh_area = displayio_bitmap_get_refresh_areas(self->bitmap, tail);
+ if (refresh_area != tail) {
+ // Special case a TileGrid that shows a full bitmap and use its
+ // dirty area. Copy it to ours so we can transform it.
+ if (self->tiles_in_bitmap == 1) {
+ displayio_area_copy(refresh_area, &self->dirty_area);
+ self->partial_change = true;
+ } else {
+ self->full_change = true;
+ }
+ }
+ }
+
+ self->full_change = self->full_change ||
+ (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type) &&
+ displayio_palette_needs_refresh(self->pixel_shader)) ||
+ (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type) &&
+ displayio_colorconverter_needs_refresh(self->pixel_shader));
+ if (self->full_change || first_draw) {
+ self->current_area.next = tail;
+ return &self->current_area;
+ }
+
+ if (self->partial_change) {
+ if (self->absolute_transform->transpose_xy) {
+ int16_t x1 = self->dirty_area.x1;
+ self->dirty_area.x1 = self->absolute_transform->x + self->absolute_transform->dx * (self->y + self->dirty_area.y1);
+ self->dirty_area.y1 = self->absolute_transform->y + self->absolute_transform->dy * (self->x + x1);
+ int16_t x2 = self->dirty_area.x2;
+ self->dirty_area.x2 = self->absolute_transform->x + self->absolute_transform->dx * (self->y + self->dirty_area.y2);
+ self->dirty_area.y2 = self->absolute_transform->y + self->absolute_transform->dy * (self->x + x2);
+ } else {
+ self->dirty_area.x1 = self->absolute_transform->x + self->absolute_transform->dx * (self->x + self->dirty_area.x1);
+ self->dirty_area.y1 = self->absolute_transform->y + self->absolute_transform->dy * (self->y + self->dirty_area.y1);
+ self->dirty_area.x2 = self->absolute_transform->x + self->absolute_transform->dx * (self->x + self->dirty_area.x2);
+ self->dirty_area.y2 = self->absolute_transform->y + self->absolute_transform->dy * (self->y + self->dirty_area.y2);
+ }
+ if (self->dirty_area.y2 < self->dirty_area.y1) {
+ int16_t temp = self->dirty_area.y2;
+ self->dirty_area.y2 = self->dirty_area.y1;
+ self->dirty_area.y1 = temp;
+ }
+ if (self->dirty_area.x2 < self->dirty_area.x1) {
+ int16_t temp = self->dirty_area.x2;
+ self->dirty_area.x2 = self->dirty_area.x1;
+ self->dirty_area.x1 = temp;
+ }
+
+ self->dirty_area.next = tail;
+ return &self->dirty_area;
+ }
+ return tail;
+}
diff --git a/shared-module/displayio/TileGrid.h b/shared-module/displayio/TileGrid.h
new file mode 100644
index 000000000..e97d3dfd4
--- /dev/null
+++ b/shared-module/displayio/TileGrid.h
@@ -0,0 +1,88 @@
+/*
+ * This file is part of the Micro Python 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.
+ */
+
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_TILEGRID_H
+#define MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_TILEGRID_H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "py/obj.h"
+#include "shared-module/displayio/area.h"
+#include "shared-module/displayio/Palette.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ mp_obj_t bitmap;
+ mp_obj_t pixel_shader;
+ int16_t x;
+ int16_t y;
+ uint16_t pixel_width;
+ uint16_t pixel_height;
+ uint16_t bitmap_width_in_tiles;;
+ uint16_t tiles_in_bitmap;
+ uint16_t width_in_tiles;
+ uint16_t height_in_tiles;
+ uint16_t tile_width;
+ uint16_t tile_height;
+ uint16_t top_left_x;
+ uint16_t top_left_y;
+ uint8_t* tiles;
+ const displayio_buffer_transform_t* absolute_transform;
+ displayio_area_t dirty_area; // Stored as a relative area until the refresh area is fetched.
+ displayio_area_t previous_area; // Stored as an absolute area.
+ displayio_area_t current_area; // Stored as an absolute area so it applies across frames.
+ bool partial_change :1;
+ bool full_change :1;
+ bool moved :1;
+ bool inline_tiles :1;
+ bool in_group :1;
+ bool flip_x :1;
+ bool flip_y :1;
+ bool transpose_xy :1;
+ bool hidden :1;
+ bool hidden_by_parent :1;
+ uint8_t padding :6;
+} displayio_tilegrid_t;
+
+void displayio_tilegrid_set_hidden_by_parent(displayio_tilegrid_t *self, bool hidden);
+
+// Updating the screen is a three stage process.
+
+// The first stage is used to determine i
+displayio_area_t* displayio_tilegrid_get_refresh_areas(displayio_tilegrid_t *self, displayio_area_t* tail);
+
+// Area is always in absolute screen coordinates. Update transform is used to inform TileGrids how
+// they relate to it.
+bool displayio_tilegrid_fill_area(displayio_tilegrid_t *self, const _displayio_colorspace_t* colorspace, const displayio_area_t* area, uint32_t* mask, uint32_t *buffer);
+void displayio_tilegrid_update_transform(displayio_tilegrid_t *group, const displayio_buffer_transform_t* parent_transform);
+
+// Fills in area with the maximum bounds of all related pixels in the last rendered frame. Returns
+// false if the tilegrid wasn't rendered in the last frame.
+bool displayio_tilegrid_get_previous_area(displayio_tilegrid_t *self, displayio_area_t* area);
+void displayio_tilegrid_finish_refresh(displayio_tilegrid_t *self);
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_TILEGRID_H
diff --git a/shared-module/displayio/__init__.c b/shared-module/displayio/__init__.c
index df9c2963a..c898bbb98 100644
--- a/shared-module/displayio/__init__.c
+++ b/shared-module/displayio/__init__.c
@@ -1,80 +1,394 @@
-#include "shared-bindings/displayio/FourWire.h"
-extern displayio_fourwire_obj_t board_display_obj;
+#include <string.h>
-void start_region_update(displayio_fourwire_obj_t* display, uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1) {
- // TODO delegate between different display types
- displayio_fourwire_start_region_update(display, x0, y0, x1, y1);
+#include "shared-module/displayio/__init__.h"
+
+#include "lib/utils/interrupt_char.h"
+#include "py/reload.h"
+#include "py/runtime.h"
+#include "shared-bindings/board/__init__.h"
+#include "shared-bindings/displayio/Bitmap.h"
+#include "shared-bindings/displayio/Display.h"
+#include "shared-bindings/displayio/Group.h"
+#include "shared-bindings/displayio/Palette.h"
+#include "shared-module/displayio/area.h"
+#include "supervisor/shared/autoreload.h"
+#include "supervisor/shared/display.h"
+#include "supervisor/memory.h"
+
+#include "supervisor/spi_flash_api.h"
+#include "py/mpconfig.h"
+
+primary_display_t displays[CIRCUITPY_DISPLAY_LIMIT];
+
+#if CIRCUITPY_RGBMATRIX
+STATIC bool any_display_uses_this_rgbmatrix(rgbmatrix_rgbmatrix_obj_t* pm) {
+ for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) {
+ if (displays[i].framebuffer_display.base.type == &framebufferio_framebufferdisplay_type) {
+ framebufferio_framebufferdisplay_obj_t* display = &displays[i].framebuffer_display;
+ if (display->framebuffer == pm) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+#endif
+
+// Check for recursive calls to displayio_background.
+bool displayio_background_in_progress = false;
+
+void displayio_background(void) {
+ if (mp_hal_is_interrupted()) {
+ return;
+ }
+ if (reload_requested) {
+ // Reload is about to happen, so don't redisplay.
+ return;
+ }
+
+ if (displayio_background_in_progress) {
+ // Don't allow recursive calls to this routine.
+ return;
+ }
+
+ displayio_background_in_progress = true;
+
+ for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) {
+ if (displays[i].display.base.type == NULL || displays[i].display.base.type == &mp_type_NoneType) {
+ // Skip null display.
+ continue;
+ }
+ if (displays[i].display.base.type == &displayio_display_type) {
+ displayio_display_background(&displays[i].display);
+#if CIRCUITPY_FRAMEBUFFERIO
+ } else if (displays[i].framebuffer_display.base.type == &framebufferio_framebufferdisplay_type) {
+ framebufferio_framebufferdisplay_background(&displays[i].framebuffer_display);
+#endif
+ } else if (displays[i].epaper_display.base.type == &displayio_epaperdisplay_type) {
+ displayio_epaperdisplay_background(&displays[i].epaper_display);
+ }
+ }
+
+ // All done.
+ displayio_background_in_progress = false;
+}
+
+void common_hal_displayio_release_displays(void) {
+ // Release displays before busses so that they can send any final commands to turn the display
+ // off properly.
+ for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) {
+ mp_const_obj_t display_type = displays[i].display.base.type;
+ if (display_type == NULL || display_type == &mp_type_NoneType) {
+ continue;
+ } else if (display_type == &displayio_display_type) {
+ release_display(&displays[i].display);
+ } else if (display_type == &displayio_epaperdisplay_type) {
+ release_epaperdisplay(&displays[i].epaper_display);
+#if CIRCUITPY_FRAMEBUFFERIO
+ } else if (display_type == &framebufferio_framebufferdisplay_type) {
+ release_framebufferdisplay(&displays[i].framebuffer_display);
+#endif
+ }
+ displays[i].display.base.type = &mp_type_NoneType;
+ }
+ for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) {
+ mp_const_obj_t bus_type = displays[i].fourwire_bus.base.type;
+ if (bus_type == NULL || bus_type == &mp_type_NoneType) {
+ continue;
+ } else if (bus_type == &displayio_fourwire_type) {
+ common_hal_displayio_fourwire_deinit(&displays[i].fourwire_bus);
+ } else if (bus_type == &displayio_i2cdisplay_type) {
+ common_hal_displayio_i2cdisplay_deinit(&displays[i].i2cdisplay_bus);
+ } else if (bus_type == &displayio_parallelbus_type) {
+ common_hal_displayio_parallelbus_deinit(&displays[i].parallel_bus);
+#if CIRCUITPY_FRAMEBUFFERIO
+ } else if (bus_type == &rgbmatrix_RGBMatrix_type) {
+ common_hal_rgbmatrix_rgbmatrix_deinit(&displays[i].rgbmatrix);
+#endif
+ }
+ displays[i].fourwire_bus.base.type = &mp_type_NoneType;
+ }
+
+ supervisor_stop_terminal();
+}
+
+void reset_displays(void) {
+ // The SPI buses used by FourWires may be allocated on the heap so we need to move them inline.
+ for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) {
+ if (displays[i].fourwire_bus.base.type == &displayio_fourwire_type) {
+ displayio_fourwire_obj_t* fourwire = &displays[i].fourwire_bus;
+ if (((uint32_t) fourwire->bus) < ((uint32_t) &displays) ||
+ ((uint32_t) fourwire->bus) > ((uint32_t) &displays + CIRCUITPY_DISPLAY_LIMIT)) {
+ busio_spi_obj_t* original_spi = fourwire->bus;
+ #if BOARD_SPI
+ // We don't need to move original_spi if it is the board.SPI object because it is
+ // statically allocated already. (Doing so would also make it impossible to reference in
+ // a subsequent VM run.)
+ if (original_spi == common_hal_board_get_spi()) {
+ continue;
+ }
+ #endif
+ #ifdef BOARD_USE_INTERNAL_SPI
+ if (original_spi == (mp_obj_t)(&supervisor_flash_spi_bus)) {
+ continue;
+ }
+ #endif
+ memcpy(&fourwire->inline_bus, original_spi, sizeof(busio_spi_obj_t));
+ fourwire->bus = &fourwire->inline_bus;
+ // Check for other displays that use the same spi bus and swap them too.
+ for (uint8_t j = i + 1; j < CIRCUITPY_DISPLAY_LIMIT; j++) {
+ if (displays[i].fourwire_bus.base.type == &displayio_fourwire_type &&
+ displays[i].fourwire_bus.bus == original_spi) {
+ displays[i].fourwire_bus.bus = &fourwire->inline_bus;
+ }
+ }
+ }
+ } else if (displays[i].i2cdisplay_bus.base.type == &displayio_i2cdisplay_type) {
+ displayio_i2cdisplay_obj_t* i2c = &displays[i].i2cdisplay_bus;
+ if (((uint32_t) i2c->bus) < ((uint32_t) &displays) ||
+ ((uint32_t) i2c->bus) > ((uint32_t) &displays + CIRCUITPY_DISPLAY_LIMIT)) {
+ busio_i2c_obj_t* original_i2c = i2c->bus;
+ #if BOARD_I2C
+ // We don't need to move original_i2c if it is the board.I2C object because it is
+ // statically allocated already. (Doing so would also make it impossible to reference in
+ // a subsequent VM run.)
+ if (original_i2c == common_hal_board_get_i2c()) {
+ continue;
+ }
+ #endif
+ memcpy(&i2c->inline_bus, original_i2c, sizeof(busio_i2c_obj_t));
+ i2c->bus = &i2c->inline_bus;
+ // Check for other displays that use the same i2c bus and swap them too.
+ for (uint8_t j = i + 1; j < CIRCUITPY_DISPLAY_LIMIT; j++) {
+ if (displays[i].i2cdisplay_bus.base.type == &displayio_i2cdisplay_type &&
+ displays[i].i2cdisplay_bus.bus == original_i2c) {
+ displays[i].i2cdisplay_bus.bus = &i2c->inline_bus;
+ }
+ }
+ }
+#if CIRCUITPY_RGBMATRIX
+ } else if (displays[i].rgbmatrix.base.type == &rgbmatrix_RGBMatrix_type) {
+ rgbmatrix_rgbmatrix_obj_t * pm = &displays[i].rgbmatrix;
+ if(!any_display_uses_this_rgbmatrix(pm)) {
+ common_hal_rgbmatrix_rgbmatrix_deinit(pm);
+ }
+#endif
+ } else {
+ // Not an active display bus.
+ continue;
+ }
+ }
+
+ for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) {
+ // Reset the displayed group. Only the first will get the terminal but
+ // that's ok.
+ if (displays[i].display.base.type == &displayio_display_type) {
+ reset_display(&displays[i].display);
+ } else if (displays[i].epaper_display.base.type == &displayio_epaperdisplay_type) {
+ displayio_epaperdisplay_obj_t* display = &displays[i].epaper_display;
+ common_hal_displayio_epaperdisplay_show(display, NULL);
+#if CIRCUITPY_FRAMEBUFFERIO
+ } else if (displays[i].framebuffer_display.base.type == &framebufferio_framebufferdisplay_type) {
+ framebufferio_framebufferdisplay_obj_t* display = &displays[i].framebuffer_display;
+ display->auto_refresh = true;
+ common_hal_framebufferio_framebufferdisplay_show(display, NULL);
+#endif
+ }
+ }
}
-void finish_region_update(displayio_fourwire_obj_t* display) {
- // TODO delegate between different display types
- displayio_fourwire_finish_region_update(display);
+void displayio_gc_collect(void) {
+ for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) {
+#if CIRCUITPY_RGBMATRIX
+ if (displays[i].rgbmatrix.base.type == &rgbmatrix_RGBMatrix_type) {
+ rgbmatrix_rgbmatrix_collect_ptrs(&displays[i].rgbmatrix);
+ }
+#endif
+
+ if (displays[i].display.base.type == NULL) {
+ continue;
+ }
+
+ // Alternatively, we could use gc_collect_root over the whole object,
+ // but this is more precise, and is the only field that needs marking.
+ if (displays[i].display.base.type == &displayio_display_type) {
+ displayio_display_collect_ptrs(&displays[i].display);
+#if CIRCUITPY_FRAMEBUFFERIO
+ } else if (displays[i].framebuffer_display.base.type == &framebufferio_framebufferdisplay_type) {
+ framebufferio_framebufferdisplay_collect_ptrs(&displays[i].framebuffer_display);
+#endif
+ } else if (displays[i].epaper_display.base.type == &displayio_epaperdisplay_type) {
+ displayio_epaperdisplay_collect_ptrs(&displays[i].epaper_display);
+ }
+ }
}
-void finish_refresh(displayio_fourwire_obj_t* display) {
- // TODO delegate between different display types
- displayio_fourwire_finish_refresh(display);
+void displayio_area_expand(displayio_area_t* original, const displayio_area_t* addition) {
+ if (addition->x1 < original->x1) {
+ original->x1 = addition->x1;
+ }
+ if (addition->y1 < original->y1) {
+ original->y1 = addition->y1;
+ }
+ if (addition->x2 > original->x2) {
+ original->x2 = addition->x2;
+ }
+ if (addition->y2 > original->y2) {
+ original->y2 = addition->y2;
+ }
}
-bool frame_queued(displayio_fourwire_obj_t* display) {
- // TODO delegate between different display types
- return displayio_fourwire_frame_queued(display);
+void displayio_area_copy(const displayio_area_t* src, displayio_area_t* dst) {
+ dst->x1 = src->x1;
+ dst->y1 = src->y1;
+ dst->x2 = src->x2;
+ dst->y2 = src->y2;
}
-bool refresh_queued(displayio_fourwire_obj_t* display) {
- // TODO delegate between different display types
- return displayio_fourwire_refresh_queued(display);
+void displayio_area_scale(displayio_area_t* area, uint16_t scale) {
+ area->x1 *= scale;
+ area->y1 *= scale;
+ area->x2 *= scale;
+ area->y2 *= scale;
}
-bool send_pixels(displayio_fourwire_obj_t* display, uint32_t* pixels, uint32_t length) {
- // TODO delegate between different display types
- return displayio_fourwire_send_pixels(display, pixels, length);
+void displayio_area_shift(displayio_area_t* area, int16_t dx, int16_t dy) {
+ area->x1 += dx;
+ area->y1 += dy;
+ area->x2 += dx;
+ area->y2 += dy;
}
-void displayio_refresh_display(void) {
- displayio_fourwire_obj_t* display = &board_display_obj;
+bool displayio_area_compute_overlap(const displayio_area_t* a,
+ const displayio_area_t* b,
+ displayio_area_t* overlap) {
+ overlap->x1 = a->x1;
+ if (b->x1 > overlap->x1) {
+ overlap->x1 = b->x1;
+ }
+ overlap->x2 = a->x2;
+ if (b->x2 < overlap->x2) {
+ overlap->x2 = b->x2;
+ }
+ if (overlap->x1 >= overlap->x2) {
+ return false;
+ }
+ overlap->y1 = a->y1;
+ if (b->y1 > overlap->y1) {
+ overlap->y1 = b->y1;
+ }
+ overlap->y2 = a->y2;
+ if (b->y2 < overlap->y2) {
+ overlap->y2 = b->y2;
+ }
+ if (overlap->y1 >= overlap->y2) {
+ return false;
+ }
+ return true;
+}
- if (!frame_queued(display)) {
- return;
+void displayio_area_union(const displayio_area_t* a,
+ const displayio_area_t* b,
+ displayio_area_t* u) {
+ u->x1 = a->x1;
+ if (b->x1 < u->x1) {
+ u->x1 = b->x1;
+ }
+ u->x2 = a->x2;
+ if (b->x2 > u->x2) {
+ u->x2 = b->x2;
}
- if (refresh_queued(display)) {
- // We compute the pixels
- uint16_t x0 = 0;
- uint16_t y0 = 0;
- uint16_t x1 = display->width;
- uint16_t y1 = display->height;
- size_t index = 0;
- //size_t row_size = (x1 - x0);
- uint16_t buffer_size = 256;
- uint32_t buffer[buffer_size / 2];
- start_region_update(display, x0, y0, x1, y1);
- for (uint16_t y = y0; y < y1; ++y) {
- for (uint16_t x = x0; x < x1; ++x) {
- uint16_t* pixel = &(((uint16_t*)buffer)[index]);
- *pixel = 0;
- if (display->current_group != NULL) {
- displayio_group_get_pixel(display->current_group, x, y, pixel);
- }
+ u->y1 = a->y1;
+ if (b->y1 < u->y1) {
+ u->y1 = b->y1;
+ }
+ u->y2 = a->y2;
+ if (b->y2 > u->y2) {
+ u->y2 = b->y2;
+ }
+}
- index += 1;
- // The buffer is full, send it.
- if (index >= buffer_size) {
- if (!send_pixels(display, buffer, buffer_size / 2)) {
- finish_region_update(display);
- return;
- }
- index = 0;
- }
- }
+uint16_t displayio_area_width(const displayio_area_t* area) {
+ return area->x2 - area->x1;
+}
+
+uint16_t displayio_area_height(const displayio_area_t* area) {
+ return area->y2 - area->y1;
+}
+
+uint32_t displayio_area_size(const displayio_area_t* area) {
+ return displayio_area_width(area) * displayio_area_height(area);
+}
+
+bool displayio_area_equal(const displayio_area_t* a, const displayio_area_t* b) {
+ return a->x1 == b->x1 &&
+ a->y1 == b->y1 &&
+ a->x2 == b->x2 &&
+ a->y2 == b->y2;
+}
+
+// Original and whole must be in the same coordinate space.
+void displayio_area_transform_within(bool mirror_x, bool mirror_y, bool transpose_xy,
+ const displayio_area_t* original,
+ const displayio_area_t* whole,
+ displayio_area_t* transformed) {
+ if (mirror_x) {
+ transformed->x1 = whole->x1 + (whole->x2 - original->x2);
+ transformed->x2 = whole->x2 - (original->x1 - whole->x1);
+ } else {
+ transformed->x1 = original->x1;
+ transformed->x2 = original->x2;
+ }
+ if (mirror_y) {
+ transformed->y1 = whole->y1 + (whole->y2 - original->y2);
+ transformed->y2 = whole->y2 - (original->y1 - whole->y1);
+ } else {
+ transformed->y1 = original->y1;
+ transformed->y2 = original->y2;
+ }
+ if (transpose_xy) {
+ int16_t y1 = transformed->y1;
+ int16_t y2 = transformed->y2;
+ transformed->y1 = whole->y1 + (transformed->x1 - whole->x1);
+ transformed->y2 = whole->y1 + (transformed->x2 - whole->x1);
+ transformed->x2 = whole->x1 + (y2 - whole->y1);
+ transformed->x1 = whole->x1 + (y1 - whole->y1);
+ }
+}
+
+primary_display_t *allocate_display(void) {
+ for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) {
+ mp_const_obj_t display_type = displays[i].display.base.type;
+ if (display_type == NULL || display_type == &mp_type_NoneType) {
+ return &displays[i];
}
- // Send the remaining data.
- if (index && !send_pixels(display, buffer, index * 2)) {
- finish_region_update(display);
- return;
+ }
+ return NULL;
+}
+
+primary_display_t *allocate_display_or_raise(void) {
+ primary_display_t *result = allocate_display();
+ if (result) {
+ return result;
+ }
+ mp_raise_RuntimeError(translate("Too many displays"));
+}
+primary_display_t *allocate_display_bus(void) {
+ for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) {
+ mp_const_obj_t display_type = displays[i].display.base.type;
+ if (display_type == NULL || display_type == &mp_type_NoneType) {
+ return &displays[i];
}
- finish_region_update(display);
}
- finish_refresh(display);
+ return NULL;
+}
+
+primary_display_t *allocate_display_bus_or_raise(void) {
+ primary_display_t *result = allocate_display_bus();
+ if (result) {
+ return result;
+ }
+ mp_raise_RuntimeError(translate("Too many display busses"));
}
diff --git a/shared-module/displayio/__init__.h b/shared-module/displayio/__init__.h
index 556af430d..9eb10c28b 100644
--- a/shared-module/displayio/__init__.h
+++ b/shared-module/displayio/__init__.h
@@ -24,9 +24,49 @@
* THE SOFTWARE.
*/
-#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO___INIT___H
-#define MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO___INIT___H
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO___INIT___H
+#define MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO___INIT___H
-void displayio_refresh_display(void);
+#include "shared-bindings/displayio/Display.h"
+#include "shared-bindings/displayio/EPaperDisplay.h"
+#if CIRCUITPY_FRAMEBUFFERIO
+#include "shared-bindings/framebufferio/FramebufferDisplay.h"
+#endif
+#include "shared-bindings/displayio/FourWire.h"
+#include "shared-bindings/displayio/Group.h"
+#include "shared-bindings/displayio/I2CDisplay.h"
+#include "shared-bindings/displayio/ParallelBus.h"
+#include "shared-bindings/rgbmatrix/RGBMatrix.h"
-#endif // MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO___INIT___H
+typedef struct {
+ union {
+ displayio_fourwire_obj_t fourwire_bus;
+ displayio_i2cdisplay_obj_t i2cdisplay_bus;
+ displayio_parallelbus_obj_t parallel_bus;
+#if CIRCUITPY_RGBMATRIX
+ rgbmatrix_rgbmatrix_obj_t rgbmatrix;
+#endif
+ };
+ union {
+ displayio_display_obj_t display;
+ displayio_epaperdisplay_obj_t epaper_display;
+#if CIRCUITPY_FRAMEBUFFERIO
+ framebufferio_framebufferdisplay_obj_t framebuffer_display;
+#endif
+ };
+} primary_display_t;
+
+extern primary_display_t displays[CIRCUITPY_DISPLAY_LIMIT];
+
+extern displayio_group_t circuitpython_splash;
+
+void displayio_background(void);
+void reset_displays(void);
+void displayio_gc_collect(void);
+
+primary_display_t *allocate_display(void);
+primary_display_t *allocate_display_or_raise(void);
+primary_display_t *allocate_display_bus(void);
+primary_display_t *allocate_display_bus_or_raise(void);
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO___INIT___H
diff --git a/shared-module/displayio/area.h b/shared-module/displayio/area.h
new file mode 100644
index 000000000..ec7c389b4
--- /dev/null
+++ b/shared-module/displayio/area.h
@@ -0,0 +1,73 @@
+/*
+ * This file is part of the Micro Python 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.
+ */
+
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_AREA_H
+#define MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_AREA_H
+
+// Implementations are in __init__.c
+typedef struct _displayio_area_t displayio_area_t;
+
+struct _displayio_area_t {
+ int16_t x1;
+ int16_t y1;
+ int16_t x2; // Second point is exclusive.
+ int16_t y2;
+ const displayio_area_t* next; // Next area in the linked list.
+};
+
+typedef struct {
+ uint16_t x;
+ uint16_t y;
+ int8_t dx;
+ int8_t dy;
+ uint8_t scale;
+ uint16_t width;
+ uint16_t height;
+ bool mirror_x;
+ bool mirror_y;
+ bool transpose_xy;
+} displayio_buffer_transform_t;
+
+void displayio_area_union(const displayio_area_t* a,
+ const displayio_area_t* b,
+ displayio_area_t* u);
+void displayio_area_expand(displayio_area_t* original, const displayio_area_t* addition);
+void displayio_area_copy(const displayio_area_t* src, displayio_area_t* dst);
+void displayio_area_scale(displayio_area_t* area, uint16_t scale);
+void displayio_area_shift(displayio_area_t* area, int16_t dx, int16_t dy);
+bool displayio_area_compute_overlap(const displayio_area_t* a,
+ const displayio_area_t* b,
+ displayio_area_t* overlap);
+uint16_t displayio_area_width(const displayio_area_t* area);
+uint16_t displayio_area_height(const displayio_area_t* area);
+uint32_t displayio_area_size(const displayio_area_t* area);
+bool displayio_area_equal(const displayio_area_t* a, const displayio_area_t* b);
+void displayio_area_transform_within(bool mirror_x, bool mirror_y, bool transpose_xy,
+ const displayio_area_t* original,
+ const displayio_area_t* whole,
+ displayio_area_t* transformed);
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_AREA_H
diff --git a/shared-module/displayio/display_core.c b/shared-module/displayio/display_core.c
new file mode 100644
index 000000000..43f2d1937
--- /dev/null
+++ b/shared-module/displayio/display_core.c
@@ -0,0 +1,351 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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 "shared-bindings/displayio/Display.h"
+
+#include "py/gc.h"
+#include "py/runtime.h"
+#include "shared-bindings/displayio/FourWire.h"
+#include "shared-bindings/displayio/I2CDisplay.h"
+#include "shared-bindings/displayio/ParallelBus.h"
+#include "shared-bindings/microcontroller/Pin.h"
+#include "shared-bindings/time/__init__.h"
+#include "shared-module/displayio/__init__.h"
+#include "supervisor/shared/display.h"
+#include "supervisor/shared/tick.h"
+
+#include <stdint.h>
+#include <string.h>
+
+#define DISPLAYIO_CORE_DEBUG(...) (void)0
+// #define DISPLAYIO_CORE_DEBUG(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__)
+
+void displayio_display_core_construct(displayio_display_core_t* self,
+ mp_obj_t bus, uint16_t width, uint16_t height, uint16_t ram_width, uint16_t ram_height, int16_t colstart, int16_t rowstart, uint16_t rotation,
+ uint16_t color_depth, bool grayscale, bool pixels_in_byte_share_row, uint8_t bytes_per_cell, bool reverse_pixels_in_byte, bool reverse_bytes_in_word) {
+ self->colorspace.depth = color_depth;
+ self->colorspace.grayscale = grayscale;
+ self->colorspace.pixels_in_byte_share_row = pixels_in_byte_share_row;
+ self->colorspace.bytes_per_cell = bytes_per_cell;
+ self->colorspace.reverse_pixels_in_byte = reverse_pixels_in_byte;
+ self->colorspace.reverse_bytes_in_word = reverse_bytes_in_word;
+ self->colorspace.dither = false;
+ self->current_group = NULL;
+ self->colstart = colstart;
+ self->rowstart = rowstart;
+ self->last_refresh = 0;
+
+ // (framebufferdisplay already validated its 'bus' is a buffer-protocol object)
+ if (bus) {
+ if (MP_OBJ_IS_TYPE(bus, &displayio_parallelbus_type)) {
+ self->bus_reset = common_hal_displayio_parallelbus_reset;
+ self->bus_free = common_hal_displayio_parallelbus_bus_free;
+ self->begin_transaction = common_hal_displayio_parallelbus_begin_transaction;
+ self->send = common_hal_displayio_parallelbus_send;
+ self->end_transaction = common_hal_displayio_parallelbus_end_transaction;
+ } else if (MP_OBJ_IS_TYPE(bus, &displayio_fourwire_type)) {
+ self->bus_reset = common_hal_displayio_fourwire_reset;
+ self->bus_free = common_hal_displayio_fourwire_bus_free;
+ self->begin_transaction = common_hal_displayio_fourwire_begin_transaction;
+ self->send = common_hal_displayio_fourwire_send;
+ self->end_transaction = common_hal_displayio_fourwire_end_transaction;
+ } else if (MP_OBJ_IS_TYPE(bus, &displayio_i2cdisplay_type)) {
+ self->bus_reset = common_hal_displayio_i2cdisplay_reset;
+ self->bus_free = common_hal_displayio_i2cdisplay_bus_free;
+ self->begin_transaction = common_hal_displayio_i2cdisplay_begin_transaction;
+ self->send = common_hal_displayio_i2cdisplay_send;
+ self->end_transaction = common_hal_displayio_i2cdisplay_end_transaction;
+ } else {
+ mp_raise_ValueError(translate("Unsupported display bus type"));
+ }
+ }
+ self->bus = bus;
+
+
+ supervisor_start_terminal(width, height);
+
+ self->width = width;
+ self->height = height;
+ self->ram_width = ram_width;
+ self->ram_height = ram_height;
+
+ displayio_display_core_set_rotation(self, rotation);
+}
+
+void displayio_display_core_set_rotation( displayio_display_core_t* self,
+ int rotation) {
+ int height = self->height;
+ int width = self->width;
+
+ rotation = rotation % 360;
+ self->rotation = rotation;
+ self->transform.x = 0;
+ self->transform.y = 0;
+ self->transform.scale = 1;
+ self->transform.mirror_x = false;
+ self->transform.mirror_y = false;
+ self->transform.transpose_xy = false;
+ if (rotation == 0 || rotation == 180) {
+ if (rotation == 180) {
+ self->transform.mirror_x = true;
+ self->transform.mirror_y = true;
+ }
+ } else {
+ self->transform.transpose_xy = true;
+ if (rotation == 270) {
+ self->transform.mirror_y = true;
+ } else {
+ self->transform.mirror_x = true;
+ }
+ }
+
+ self->area.x1 = 0;
+ self->area.y1 = 0;
+ self->area.next = NULL;
+
+ self->transform.dx = 1;
+ self->transform.dy = 1;
+ if (self->transform.transpose_xy) {
+ self->area.x2 = height;
+ self->area.y2 = width;
+ if (self->transform.mirror_x) {
+ self->transform.x = height;
+ self->transform.dx = -1;
+ }
+ if (self->transform.mirror_y) {
+ self->transform.y = width;
+ self->transform.dy = -1;
+ }
+ } else {
+ self->area.x2 = width;
+ self->area.y2 = height;
+ if (self->transform.mirror_x) {
+ self->transform.x = width;
+ self->transform.dx = -1;
+ }
+ if (self->transform.mirror_y) {
+ self->transform.y = height;
+ self->transform.dy = -1;
+ }
+ }
+}
+
+bool displayio_display_core_show(displayio_display_core_t* self, displayio_group_t* root_group) {
+ if (root_group == NULL) {
+ if (!circuitpython_splash.in_group) {
+ root_group = &circuitpython_splash;
+ } else if (self->current_group == &circuitpython_splash) {
+ return true;
+ }
+ }
+ if (root_group == self->current_group) {
+ return true;
+ }
+ if (root_group != NULL && root_group->in_group) {
+ return false;
+ }
+ if (self->current_group != NULL) {
+ self->current_group->in_group = false;
+ }
+
+ if (root_group != NULL) {
+ displayio_group_update_transform(root_group, &self->transform);
+ root_group->in_group = true;
+ }
+ self->current_group = root_group;
+ self->full_refresh = true;
+ return true;
+}
+
+uint16_t displayio_display_core_get_width(displayio_display_core_t* self){
+ return self->width;
+}
+
+uint16_t displayio_display_core_get_height(displayio_display_core_t* self){
+ return self->height;
+}
+
+void displayio_display_core_set_dither(displayio_display_core_t* self, bool dither){
+ self->colorspace.dither = dither;
+}
+
+bool displayio_display_core_get_dither(displayio_display_core_t* self){
+ return self->colorspace.dither;
+}
+
+bool displayio_display_core_bus_free(displayio_display_core_t *self) {
+ return self->bus_free(self->bus);
+}
+
+bool displayio_display_core_begin_transaction(displayio_display_core_t* self) {
+ return self->begin_transaction(self->bus);
+}
+
+void displayio_display_core_end_transaction(displayio_display_core_t* self) {
+ self->end_transaction(self->bus);
+}
+
+void displayio_display_core_set_region_to_update(displayio_display_core_t* self, uint8_t column_command, uint8_t row_command, uint16_t set_current_column_command, uint16_t set_current_row_command, bool data_as_commands, bool always_toggle_chip_select, displayio_area_t* area) {
+ uint16_t x1 = area->x1;
+ uint16_t x2 = area->x2;
+ uint16_t y1 = area->y1;
+ uint16_t y2 = area->y2;
+ // Collapse down the dimension where multiple pixels are in a byte.
+ if (self->colorspace.depth < 8) {
+ uint8_t pixels_per_byte = 8 / self->colorspace.depth;
+ if (self->colorspace.pixels_in_byte_share_row) {
+ x1 /= pixels_per_byte * self->colorspace.bytes_per_cell;
+ x2 /= pixels_per_byte * self->colorspace.bytes_per_cell;
+ } else {
+ y1 /= pixels_per_byte * self->colorspace.bytes_per_cell;
+ y2 /= pixels_per_byte * self->colorspace.bytes_per_cell;
+ }
+ }
+
+ display_chip_select_behavior_t chip_select = CHIP_SELECT_UNTOUCHED;
+ if (always_toggle_chip_select || data_as_commands) {
+ chip_select = CHIP_SELECT_TOGGLE_EVERY_BYTE;
+ }
+
+ // Set column.
+ displayio_display_core_begin_transaction(self);
+ uint8_t data[5];
+ data[0] = column_command;
+ uint8_t data_length = 1;
+ display_byte_type_t data_type = DISPLAY_DATA;
+ if (!data_as_commands) {
+ self->send(self->bus, DISPLAY_COMMAND, CHIP_SELECT_UNTOUCHED, data, 1);
+ data_length = 0;
+ } else {
+ data_type = DISPLAY_COMMAND;
+ }
+ if (self->ram_width < 0x100) {
+ data[data_length++] = x1 + self->colstart;
+ data[data_length++] = x2 - 1 + self->colstart;
+ } else {
+ x1 += self->colstart;
+ x2 += self->colstart - 1;
+ data[data_length++] = x1 >> 8;
+ data[data_length++] = x1 & 0xff;
+ data[data_length++] = x2 >> 8;
+ data[data_length++] = x2 & 0xff;
+ }
+ self->send(self->bus, data_type, chip_select, data, data_length);
+ displayio_display_core_end_transaction(self);
+ if (set_current_column_command != NO_COMMAND) {
+ uint8_t command = set_current_column_command;
+ displayio_display_core_begin_transaction(self);
+ self->send(self->bus, DISPLAY_COMMAND, chip_select, &command, 1);
+ self->send(self->bus, DISPLAY_DATA, chip_select, data, data_length / 2);
+ displayio_display_core_end_transaction(self);
+ }
+
+
+ // Set row.
+ displayio_display_core_begin_transaction(self);
+ data[0] = row_command;
+ data_length = 1;
+ if (!data_as_commands) {
+ self->send(self->bus, DISPLAY_COMMAND, CHIP_SELECT_UNTOUCHED, data, 1);
+ data_length = 0;
+ }
+ if (self->ram_height < 0x100) {
+ data[data_length++] = y1 + self->rowstart;
+ data[data_length++] = y2 - 1 + self->rowstart;
+ } else {
+ y1 += self->rowstart;
+ y2 += self->rowstart - 1;
+ data[data_length++] = y1 >> 8;
+ data[data_length++] = y1 & 0xff;
+ data[data_length++] = y2 >> 8;
+ data[data_length++] = y2 & 0xff;
+ }
+ self->send(self->bus, data_type, chip_select, data, data_length);
+ displayio_display_core_end_transaction(self);
+
+ if (set_current_row_command != NO_COMMAND) {
+ uint8_t command = set_current_row_command;
+ displayio_display_core_begin_transaction(self);
+ self->send(self->bus, DISPLAY_COMMAND, chip_select, &command, 1);
+ self->send(self->bus, DISPLAY_DATA, chip_select, data, data_length / 2);
+ displayio_display_core_end_transaction(self);
+ }
+}
+
+void displayio_display_core_start_refresh(displayio_display_core_t* self) {
+ self->last_refresh = supervisor_ticks_ms64();
+}
+
+void displayio_display_core_finish_refresh(displayio_display_core_t* self) {
+ if (self->current_group != NULL) {
+ DISPLAYIO_CORE_DEBUG("displayiocore group_finish_refresh\n");
+ displayio_group_finish_refresh(self->current_group);
+ }
+ self->full_refresh = false;
+ self->last_refresh = supervisor_ticks_ms64();
+}
+
+void release_display_core(displayio_display_core_t* self) {
+ if (self->current_group != NULL) {
+ self->current_group->in_group = false;
+ }
+}
+
+void displayio_display_core_collect_ptrs(displayio_display_core_t* self) {
+ gc_collect_ptr(self->current_group);
+}
+
+bool displayio_display_core_fill_area(displayio_display_core_t *self, displayio_area_t* area, uint32_t* mask, uint32_t *buffer) {
+ return displayio_group_fill_area(self->current_group, &self->colorspace, area, mask, buffer);
+}
+
+bool displayio_display_core_clip_area(displayio_display_core_t *self, const displayio_area_t* area, displayio_area_t* clipped) {
+ bool overlaps = displayio_area_compute_overlap(&self->area, area, clipped);
+ if (!overlaps) {
+ return false;
+ }
+ // Expand the area if we have multiple pixels per byte and we need to byte
+ // align the bounds.
+ if (self->colorspace.depth < 8) {
+ uint8_t pixels_per_byte = 8 / self->colorspace.depth * self->colorspace.bytes_per_cell;
+ if (self->colorspace.pixels_in_byte_share_row) {
+ if (clipped->x1 % pixels_per_byte != 0) {
+ clipped->x1 -= clipped->x1 % pixels_per_byte;
+ }
+ if (clipped->x2 % pixels_per_byte != 0) {
+ clipped->x2 += pixels_per_byte - clipped->x2 % pixels_per_byte;
+ }
+ } else {
+ if (clipped->y1 % pixels_per_byte != 0) {
+ clipped->y1 -= clipped->y1 % pixels_per_byte;
+ }
+ if (clipped->y2 % pixels_per_byte != 0) {
+ clipped->y2 += pixels_per_byte - clipped->y2 % pixels_per_byte;
+ }
+ }
+ }
+ return true;
+}
diff --git a/shared-module/displayio/display_core.h b/shared-module/displayio/display_core.h
new file mode 100644
index 000000000..e4fd62d4a
--- /dev/null
+++ b/shared-module/displayio/display_core.h
@@ -0,0 +1,90 @@
+/*
+ * 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.
+ */
+
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_DISPLAY_CORE_H
+#define MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_DISPLAY_CORE_H
+
+#include "shared-bindings/displayio/__init__.h"
+#include "shared-bindings/displayio/Group.h"
+
+#include "shared-module/displayio/area.h"
+
+#define NO_COMMAND 0x100
+
+typedef struct {
+ mp_obj_t bus;
+ displayio_group_t *current_group;
+ uint64_t last_refresh;
+ display_bus_bus_reset bus_reset;
+ display_bus_bus_free bus_free;
+ display_bus_begin_transaction begin_transaction;
+ display_bus_send send;
+ display_bus_end_transaction end_transaction;
+ displayio_buffer_transform_t transform;
+ displayio_area_t area;
+ uint16_t width;
+ uint16_t height;
+ uint16_t rotation;
+ uint16_t ram_width;
+ uint16_t ram_height;
+ _displayio_colorspace_t colorspace;
+ int16_t colstart;
+ int16_t rowstart;
+ bool full_refresh; // New group means we need to refresh the whole display.
+} displayio_display_core_t;
+
+void displayio_display_core_construct(displayio_display_core_t* self,
+ mp_obj_t bus, uint16_t width, uint16_t height, uint16_t ram_width, uint16_t ram_height, int16_t colstart, int16_t rowstart, uint16_t rotation,
+ uint16_t color_depth, bool grayscale, bool pixels_in_byte_share_row, uint8_t bytes_per_cell, bool reverse_pixels_in_byte, bool reverse_bytes_in_word);
+
+bool displayio_display_core_show(displayio_display_core_t* self, displayio_group_t* root_group);
+
+uint16_t displayio_display_core_get_width(displayio_display_core_t* self);
+uint16_t displayio_display_core_get_height(displayio_display_core_t* self);
+
+void displayio_display_core_set_dither(displayio_display_core_t* self, bool dither);
+bool displayio_display_core_get_dither(displayio_display_core_t* self);
+
+void displayio_display_core_set_rotation(displayio_display_core_t* self, int rotation);
+
+bool displayio_display_core_bus_free(displayio_display_core_t *self);
+bool displayio_display_core_begin_transaction(displayio_display_core_t* self);
+void displayio_display_core_end_transaction(displayio_display_core_t* self);
+
+void displayio_display_core_set_region_to_update(displayio_display_core_t* self, uint8_t column_command, uint8_t row_command, uint16_t set_current_column_command, uint16_t set_current_row_command, bool data_as_commands, bool always_toggle_chip_select, displayio_area_t* area);
+
+void release_display_core(displayio_display_core_t* self);
+
+void displayio_display_core_start_refresh(displayio_display_core_t* self);
+void displayio_display_core_finish_refresh(displayio_display_core_t* self);
+
+void displayio_display_core_collect_ptrs(displayio_display_core_t* self);
+
+bool displayio_display_core_fill_area(displayio_display_core_t *self, displayio_area_t* area, uint32_t* mask, uint32_t *buffer);
+
+bool displayio_display_core_clip_area(displayio_display_core_t *self, const displayio_area_t* area, displayio_area_t* clipped);
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_DISPLAY_CORE_H
diff --git a/shared-module/fontio/BuiltinFont.c b/shared-module/fontio/BuiltinFont.c
new file mode 100644
index 000000000..58820d524
--- /dev/null
+++ b/shared-module/fontio/BuiltinFont.c
@@ -0,0 +1,79 @@
+/*
+ * This file is part of the Micro Python project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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 "shared-bindings/fontio/BuiltinFont.h"
+
+
+#include "shared-bindings/fontio/Glyph.h"
+
+#include "py/objnamedtuple.h"
+
+mp_obj_t common_hal_fontio_builtinfont_get_bitmap(const fontio_builtinfont_t *self) {
+ return MP_OBJ_FROM_PTR(self->bitmap);
+}
+
+mp_obj_t common_hal_fontio_builtinfont_get_bounding_box(const fontio_builtinfont_t *self) {
+ mp_obj_t *items = m_new(mp_obj_t, 2);
+ items[0] = MP_OBJ_NEW_SMALL_INT(self->width);
+ items[1] = MP_OBJ_NEW_SMALL_INT(self->height);
+ return mp_obj_new_tuple(2, items);
+}
+
+uint8_t fontio_builtinfont_get_glyph_index(const fontio_builtinfont_t *self, mp_uint_t codepoint) {
+ if (codepoint >= 0x20 && codepoint <= 0x7e) {
+ return codepoint - 0x20;
+ }
+ // Do a linear search of the mapping for unicode.
+ const byte* j = self->unicode_characters;
+ uint8_t k = 0;
+ while (j < self->unicode_characters + self->unicode_characters_len) {
+ unichar potential_c = utf8_get_char(j);
+ j = utf8_next_char(j);
+ if (codepoint == potential_c) {
+ return 0x7f - 0x20 + k;
+ }
+ k++;
+ }
+ return 0xff;
+}
+
+mp_obj_t common_hal_fontio_builtinfont_get_glyph(const fontio_builtinfont_t *self, mp_uint_t codepoint) {
+ uint8_t glyph_index = fontio_builtinfont_get_glyph_index(self, codepoint);
+ if (glyph_index == 0xff) {
+ return mp_const_none;
+ }
+ mp_obj_t field_values[8] = {
+ MP_OBJ_FROM_PTR(self->bitmap),
+ MP_OBJ_NEW_SMALL_INT(glyph_index),
+ MP_OBJ_NEW_SMALL_INT(self->width),
+ MP_OBJ_NEW_SMALL_INT(self->height),
+ MP_OBJ_NEW_SMALL_INT(0),
+ MP_OBJ_NEW_SMALL_INT(0),
+ MP_OBJ_NEW_SMALL_INT(self->width),
+ MP_OBJ_NEW_SMALL_INT(0)
+ };
+ return namedtuple_make_new((const mp_obj_type_t*) &fontio_glyph_type, 8, field_values, NULL);
+}
diff --git a/shared-module/displayio/Sprite.h b/shared-module/fontio/BuiltinFont.h
index dc368c4b7..30b4ade8c 100644
--- a/shared-module/displayio/Sprite.h
+++ b/shared-module/fontio/BuiltinFont.h
@@ -24,27 +24,24 @@
* THE SOFTWARE.
*/
-#ifndef MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_SPRITE_H
-#define MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_SPRITE_H
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_FONTIO_BUILTINFONT_H
+#define MICROPY_INCLUDED_SHARED_MODULE_FONTIO_BUILTINFONT_H
#include <stdbool.h>
#include <stdint.h>
#include "py/obj.h"
+#include "shared-bindings/displayio/Bitmap.h"
typedef struct {
mp_obj_base_t base;
- mp_obj_t bitmap;
- mp_obj_t pixel_shader;
- uint16_t x;
- uint16_t y;
- uint16_t width;
- uint16_t height;
- bool needs_refresh;
-} displayio_sprite_t;
+ const displayio_bitmap_t* bitmap;
+ uint8_t width;
+ uint8_t height;
+ const byte* unicode_characters;
+ uint16_t unicode_characters_len;
+} fontio_builtinfont_t;
-bool displayio_sprite_get_pixel(displayio_sprite_t *sprite, int16_t x, int16_t y, uint16_t *pixel);
-bool displayio_sprite_needs_refresh(displayio_sprite_t *self);
-void displayio_sprite_finish_refresh(displayio_sprite_t *self);
+uint8_t fontio_builtinfont_get_glyph_index(const fontio_builtinfont_t *self, mp_uint_t codepoint);
-#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_SPRITE_H
+#endif // MICROPY_INCLUDED_SHARED_MODULE_FONTIO_BUILTINFONT_H
diff --git a/shared-module/fontio/__init__.c b/shared-module/fontio/__init__.c
new file mode 100644
index 000000000..674343c53
--- /dev/null
+++ b/shared-module/fontio/__init__.c
@@ -0,0 +1,27 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2016 Scott Shawcroft
+ *
+ * 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.
+ */
+
+// Nothing now.
diff --git a/shared-module/framebufferio/FramebufferDisplay.c b/shared-module/framebufferio/FramebufferDisplay.c
new file mode 100644
index 000000000..f296da409
--- /dev/null
+++ b/shared-module/framebufferio/FramebufferDisplay.c
@@ -0,0 +1,312 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries
+ * Copyright (c) 2020 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 "shared-bindings/framebufferio/FramebufferDisplay.h"
+
+#include "py/gc.h"
+#include "py/runtime.h"
+#include "shared-bindings/microcontroller/Pin.h"
+#include "shared-bindings/time/__init__.h"
+#include "shared-module/displayio/__init__.h"
+#include "shared-module/displayio/display_core.h"
+#include "supervisor/shared/display.h"
+#include "supervisor/shared/tick.h"
+#include "supervisor/usb.h"
+
+#include <stdint.h>
+#include <string.h>
+
+void common_hal_framebufferio_framebufferdisplay_construct(framebufferio_framebufferdisplay_obj_t* self,
+ mp_obj_t framebuffer,
+ uint16_t rotation,
+ bool auto_refresh) {
+ // Turn off auto-refresh as we init.
+ self->auto_refresh = false;
+ self->framebuffer = framebuffer;
+ self->framebuffer_protocol = mp_proto_get_or_throw(MP_QSTR_protocol_framebuffer, framebuffer);
+
+ uint16_t ram_width = 0x100;
+ uint16_t ram_height = 0x100;
+
+ displayio_display_core_construct(
+ &self->core,
+ NULL,
+ self->framebuffer_protocol->get_width(self->framebuffer),
+ self->framebuffer_protocol->get_height(self->framebuffer),
+ ram_width,
+ ram_height,
+ 0,
+ 0,
+ rotation,
+ self->framebuffer_protocol->get_color_depth(self->framebuffer),
+ false,
+ false,
+ self->framebuffer_protocol->get_bytes_per_cell(self->framebuffer),
+ false,
+ false);
+
+ self->first_manual_refresh = !auto_refresh;
+
+ self->native_frames_per_second = self->framebuffer_protocol->get_native_frames_per_second(self->framebuffer);
+ self->native_ms_per_frame = 1000 / self->native_frames_per_second;
+
+ supervisor_start_terminal(self->core.width, self->core.height);
+
+ // Set the group after initialization otherwise we may send pixels while we delay in
+ // initialization.
+ common_hal_framebufferio_framebufferdisplay_show(self, &circuitpython_splash);
+ self->auto_refresh = auto_refresh;
+}
+
+bool common_hal_framebufferio_framebufferdisplay_show(framebufferio_framebufferdisplay_obj_t* self, displayio_group_t* root_group) {
+ return displayio_display_core_show(&self->core, root_group);
+}
+
+uint16_t common_hal_framebufferio_framebufferdisplay_get_width(framebufferio_framebufferdisplay_obj_t* self){
+ return displayio_display_core_get_width(&self->core);
+}
+
+uint16_t common_hal_framebufferio_framebufferdisplay_get_height(framebufferio_framebufferdisplay_obj_t* self){
+ return displayio_display_core_get_height(&self->core);
+}
+
+bool common_hal_framebufferio_framebufferdisplay_get_auto_brightness(framebufferio_framebufferdisplay_obj_t* self) {
+ if (self->framebuffer_protocol->get_auto_brightness) {
+ return self->framebuffer_protocol->get_auto_brightness(self->framebuffer);
+ }
+ return true;
+}
+
+bool common_hal_framebufferio_framebufferdisplay_set_auto_brightness(framebufferio_framebufferdisplay_obj_t* self, bool auto_brightness) {
+ if (self->framebuffer_protocol->set_auto_brightness) {
+ return self->framebuffer_protocol->set_auto_brightness(self->framebuffer, auto_brightness);
+ }
+ return false;
+}
+
+mp_float_t common_hal_framebufferio_framebufferdisplay_get_brightness(framebufferio_framebufferdisplay_obj_t* self) {
+ if (self->framebuffer_protocol->set_brightness) {
+ return self->framebuffer_protocol->get_brightness(self->framebuffer);
+ }
+ return -1;
+}
+
+bool common_hal_framebufferio_framebufferdisplay_set_brightness(framebufferio_framebufferdisplay_obj_t* self, mp_float_t brightness) {
+ bool ok = false;
+ if (self->framebuffer_protocol->set_brightness) {
+ self->framebuffer_protocol->set_brightness(self->framebuffer, brightness);
+ ok = true;
+ }
+ return ok;
+}
+
+mp_obj_t common_hal_framebufferio_framebufferdisplay_get_framebuffer(framebufferio_framebufferdisplay_obj_t* self) {
+ return self->framebuffer;
+}
+
+STATIC const displayio_area_t* _get_refresh_areas(framebufferio_framebufferdisplay_obj_t *self) {
+ if (self->core.full_refresh) {
+ self->core.area.next = NULL;
+ return &self->core.area;
+ } else if (self->core.current_group != NULL) {
+ return displayio_group_get_refresh_areas(self->core.current_group, NULL);
+ }
+ return NULL;
+}
+
+STATIC bool _refresh_area(framebufferio_framebufferdisplay_obj_t* self, const displayio_area_t* area) {
+ uint16_t buffer_size = 128; // In uint32_ts
+
+ displayio_area_t clipped;
+ // Clip the area to the display by overlapping the areas. If there is no overlap then we're done.
+ if (!displayio_display_core_clip_area(&self->core, area, &clipped)) {
+ return true;
+ }
+ uint16_t subrectangles = 1;
+ uint16_t rows_per_buffer = displayio_area_height(&clipped);
+ uint8_t pixels_per_word = (sizeof(uint32_t) * 8) / self->core.colorspace.depth;
+ uint16_t pixels_per_buffer = displayio_area_size(&clipped);
+ if (displayio_area_size(&clipped) > buffer_size * pixels_per_word) {
+ rows_per_buffer = buffer_size * pixels_per_word / displayio_area_width(&clipped);
+ if (rows_per_buffer == 0) {
+ rows_per_buffer = 1;
+ }
+ // If pixels are packed by column then ensure rows_per_buffer is on a byte boundary.
+ if (self->core.colorspace.depth < 8 && !self->core.colorspace.pixels_in_byte_share_row) {
+ uint8_t pixels_per_byte = 8 / self->core.colorspace.depth;
+ if (rows_per_buffer % pixels_per_byte != 0) {
+ rows_per_buffer -= rows_per_buffer % pixels_per_byte;
+ }
+ }
+ subrectangles = displayio_area_height(&clipped) / rows_per_buffer;
+ if (displayio_area_height(&clipped) % rows_per_buffer != 0) {
+ subrectangles++;
+ }
+ pixels_per_buffer = rows_per_buffer * displayio_area_width(&clipped);
+ buffer_size = pixels_per_buffer / pixels_per_word;
+ if (pixels_per_buffer % pixels_per_word) {
+ buffer_size += 1;
+ }
+ }
+
+ // Allocated and shared as a uint32_t array so the compiler knows the
+ // alignment everywhere.
+ uint32_t buffer[buffer_size];
+ uint32_t mask_length = (pixels_per_buffer / 32) + 1;
+ uint32_t mask[mask_length];
+ uint16_t remaining_rows = displayio_area_height(&clipped);
+
+ for (uint16_t j = 0; j < subrectangles; j++) {
+ displayio_area_t subrectangle = {
+ .x1 = clipped.x1,
+ .y1 = clipped.y1 + rows_per_buffer * j,
+ .x2 = clipped.x2,
+ .y2 = clipped.y1 + rows_per_buffer * (j + 1)
+ };
+ if (remaining_rows < rows_per_buffer) {
+ subrectangle.y2 = subrectangle.y1 + remaining_rows;
+ }
+ remaining_rows -= rows_per_buffer;
+
+ memset(mask, 0, mask_length * sizeof(mask[0]));
+ memset(buffer, 0, buffer_size * sizeof(buffer[0]));
+
+ displayio_display_core_fill_area(&self->core, &subrectangle, mask, buffer);
+
+ // COULDDO: this arithmetic only supports multiple-of-8 bpp
+ uint8_t *dest = self->bufinfo.buf + (subrectangle.y1 * self->core.width + subrectangle.x1) * (self->core.colorspace.depth / 8);
+ uint8_t *src = (uint8_t*)buffer;
+ size_t rowsize = (subrectangle.x2 - subrectangle.x1) * (self->core.colorspace.depth / 8);
+ size_t rowstride = self->core.width * (self->core.colorspace.depth/8);
+ for (uint16_t i = subrectangle.y1; i < subrectangle.y2; i++) {
+ memcpy(dest, src, rowsize);
+ dest += rowstride;
+ src += rowsize;
+ }
+
+ // TODO(tannewt): Make refresh displays faster so we don't starve other
+ // background tasks.
+ usb_background();
+ }
+ return true;
+}
+
+STATIC void _refresh_display(framebufferio_framebufferdisplay_obj_t* self) {
+ displayio_display_core_start_refresh(&self->core);
+ self->framebuffer_protocol->get_bufinfo(self->framebuffer, &self->bufinfo);
+ const displayio_area_t* current_area = _get_refresh_areas(self);
+ while (current_area != NULL) {
+ _refresh_area(self, current_area);
+ current_area = current_area->next;
+ }
+ displayio_display_core_finish_refresh(&self->core);
+ self->framebuffer_protocol->swapbuffers(self->framebuffer);
+}
+
+void common_hal_framebufferio_framebufferdisplay_set_rotation(framebufferio_framebufferdisplay_obj_t* self, int rotation){
+ bool transposed = (self->core.rotation == 90 || self->core.rotation == 270);
+ bool will_transposed = (rotation == 90 || rotation == 270);
+ if(transposed != will_transposed) {
+ int tmp = self->core.width;
+ self->core.width = self->core.height;
+ self->core.height = tmp;
+ }
+ displayio_display_core_set_rotation(&self->core, rotation);
+ supervisor_stop_terminal();
+ supervisor_start_terminal(self->core.width, self->core.height);
+ if (self->core.current_group != NULL) {
+ displayio_group_update_transform(self->core.current_group, &self->core.transform);
+ }
+}
+
+uint16_t common_hal_framebufferio_framebufferdisplay_get_rotation(framebufferio_framebufferdisplay_obj_t* self){
+ return self->core.rotation;
+}
+
+
+bool common_hal_framebufferio_framebufferdisplay_refresh(framebufferio_framebufferdisplay_obj_t* self, uint32_t target_ms_per_frame, uint32_t maximum_ms_per_real_frame) {
+ if (!self->auto_refresh && !self->first_manual_refresh) {
+ uint64_t current_time = supervisor_ticks_ms64();
+ uint32_t current_ms_since_real_refresh = current_time - self->core.last_refresh;
+ // Test to see if the real frame time is below our minimum.
+ if (current_ms_since_real_refresh > maximum_ms_per_real_frame) {
+ mp_raise_RuntimeError(translate("Below minimum frame rate"));
+ }
+ uint32_t current_ms_since_last_call = current_time - self->last_refresh_call;
+ self->last_refresh_call = current_time;
+ // Skip the actual refresh to help catch up.
+ if (current_ms_since_last_call > target_ms_per_frame) {
+ return false;
+ }
+ uint32_t remaining_time = target_ms_per_frame - (current_ms_since_real_refresh % target_ms_per_frame);
+ // We're ahead of the game so wait until we align with the frame rate.
+ while (supervisor_ticks_ms64() - self->last_refresh_call < remaining_time) {
+ RUN_BACKGROUND_TASKS;
+ }
+ }
+ self->first_manual_refresh = false;
+ _refresh_display(self);
+ return true;
+}
+
+bool common_hal_framebufferio_framebufferdisplay_get_auto_refresh(framebufferio_framebufferdisplay_obj_t* self) {
+ return self->auto_refresh;
+}
+
+void common_hal_framebufferio_framebufferdisplay_set_auto_refresh(framebufferio_framebufferdisplay_obj_t* self,
+ bool auto_refresh) {
+ self->first_manual_refresh = !auto_refresh;
+ self->auto_refresh = auto_refresh;
+}
+
+STATIC void _update_backlight(framebufferio_framebufferdisplay_obj_t* self) {
+ // TODO(tannewt): Fade the backlight based on it's existing value and a target value. The target
+ // should account for ambient light when possible.
+}
+
+void framebufferio_framebufferdisplay_background(framebufferio_framebufferdisplay_obj_t* self) {
+ _update_backlight(self);
+
+ if (self->auto_refresh && (supervisor_ticks_ms64() - self->core.last_refresh) > self->native_ms_per_frame) {
+ _refresh_display(self);
+ }
+}
+
+void release_framebufferdisplay(framebufferio_framebufferdisplay_obj_t* self) {
+ release_display_core(&self->core);
+ self->framebuffer_protocol->deinit(self->framebuffer);
+}
+
+void reset_framebufferdisplay(framebufferio_framebufferdisplay_obj_t* self) {
+ self->auto_refresh = true;
+ common_hal_framebufferio_framebufferdisplay_show(self, NULL);
+}
+
+void framebufferio_framebufferdisplay_collect_ptrs(framebufferio_framebufferdisplay_obj_t* self) {
+ gc_collect_ptr(self->framebuffer);
+ displayio_display_core_collect_ptrs(&self->core);
+}
diff --git a/shared-module/framebufferio/FramebufferDisplay.h b/shared-module/framebufferio/FramebufferDisplay.h
new file mode 100644
index 000000000..1b68d2ab0
--- /dev/null
+++ b/shared-module/framebufferio/FramebufferDisplay.h
@@ -0,0 +1,92 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Scott Shawcroft for Adafruit Industries
+ * Copyright (c) 2020 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.
+ */
+
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_FRAMEBUFFERDISPLAY_H
+#define MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_FRAMEBUFFERDISPLAY_H
+
+#include "py/obj.h"
+#include "py/proto.h"
+
+#include "shared-bindings/digitalio/DigitalInOut.h"
+#include "shared-bindings/displayio/Group.h"
+#include "shared-bindings/pulseio/PWMOut.h"
+
+#include "shared-module/displayio/area.h"
+#include "shared-module/displayio/display_core.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ displayio_display_core_t core;
+ mp_obj_t framebuffer;
+ const struct _framebuffer_p_t *framebuffer_protocol;
+ mp_buffer_info_t bufinfo;
+ uint64_t last_backlight_refresh;
+ uint64_t last_refresh_call;
+ uint16_t native_frames_per_second;
+ uint16_t native_ms_per_frame;
+ bool auto_refresh;
+ bool first_manual_refresh;
+} framebufferio_framebufferdisplay_obj_t;
+
+void framebufferio_framebufferdisplay_background(framebufferio_framebufferdisplay_obj_t* self);
+void release_framebufferdisplay(framebufferio_framebufferdisplay_obj_t* self);
+void reset_framebufferdisplay(framebufferio_framebufferdisplay_obj_t* self);
+
+void framebufferio_framebufferdisplay_collect_ptrs(framebufferio_framebufferdisplay_obj_t* self);
+
+mp_obj_t common_hal_framebufferio_framebufferdisplay_get_framebuffer(framebufferio_framebufferdisplay_obj_t* self);
+
+typedef void (*framebuffer_get_bufinfo_fun)(mp_obj_t, mp_buffer_info_t *bufinfo);
+typedef void (*framebuffer_swapbuffers_fun)(mp_obj_t);
+typedef void (*framebuffer_deinit_fun)(mp_obj_t);
+typedef bool (*framebuffer_set_brightness_fun)(mp_obj_t, mp_float_t);
+typedef mp_float_t (*framebuffer_get_brightness_fun)(mp_obj_t);
+typedef bool (*framebuffer_set_auto_brightness_fun)(mp_obj_t, bool);
+typedef bool (*framebuffer_get_auto_brightness_fun)(mp_obj_t);
+typedef int (*framebuffer_get_width_fun)(mp_obj_t);
+typedef int (*framebuffer_get_height_fun)(mp_obj_t);
+typedef int (*framebuffer_get_color_depth_fun)(mp_obj_t);
+typedef int (*framebuffer_get_bytes_per_cell_fun)(mp_obj_t);
+typedef int (*framebuffer_get_native_frames_per_second_fun)(mp_obj_t);
+
+typedef struct _framebuffer_p_t {
+ MP_PROTOCOL_HEAD // MP_QSTR_protocol_framebuffer
+ framebuffer_get_bufinfo_fun get_bufinfo;
+ framebuffer_swapbuffers_fun swapbuffers;
+ framebuffer_deinit_fun deinit;
+ framebuffer_get_width_fun get_width;
+ framebuffer_get_height_fun get_height;
+ framebuffer_get_color_depth_fun get_color_depth;
+ framebuffer_get_bytes_per_cell_fun get_bytes_per_cell;
+ framebuffer_get_native_frames_per_second_fun get_native_frames_per_second;
+ framebuffer_get_brightness_fun get_brightness;
+ framebuffer_set_brightness_fun set_brightness;
+ framebuffer_get_auto_brightness_fun get_auto_brightness;
+ framebuffer_set_auto_brightness_fun set_auto_brightness;
+} framebuffer_p_t;
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_FRAMEBUFFERDISPLAY_H
diff --git a/shared-module/framebufferio/__init__.c b/shared-module/framebufferio/__init__.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/shared-module/framebufferio/__init__.c
diff --git a/shared-module/framebufferio/__init__.h b/shared-module/framebufferio/__init__.h
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/shared-module/framebufferio/__init__.h
diff --git a/shared-module/gamepad/GamePad.c b/shared-module/gamepad/GamePad.c
index 2c14fa02a..7b4108eb2 100644
--- a/shared-module/gamepad/GamePad.c
+++ b/shared-module/gamepad/GamePad.c
@@ -24,27 +24,21 @@
* THE SOFTWARE.
*/
-#include <stdbool.h>
-
#include "py/mpstate.h"
-#include "__init__.h"
-#include "GamePad.h"
-
-#include "shared-bindings/digitalio/Pull.h"
#include "shared-bindings/digitalio/DigitalInOut.h"
-#include "shared-bindings/util.h"
-
+#include "shared-bindings/gamepad/GamePad.h"
+#include "supervisor/shared/tick.h"
-void gamepad_init(size_t n_pins, const mp_obj_t* pins) {
- gamepad_obj_t* gamepad_singleton = MP_STATE_VM(gamepad_singleton);
+void common_hal_gamepad_gamepad_init(gamepad_obj_t *gamepad,
+ const mp_obj_t pins[], size_t n_pins) {
for (size_t i = 0; i < 8; ++i) {
- gamepad_singleton->pins[i] = NULL;
+ gamepad->pins[i] = NULL;
}
- gamepad_singleton->pulls = 0;
+ gamepad->pulls = 0;
for (size_t i = 0; i < n_pins; ++i) {
digitalio_digitalinout_obj_t *pin = MP_OBJ_TO_PTR(pins[i]);
- digitalio_direction_t direction = common_hal_digitalio_digitalinout_get_direction(pin);
- if (direction != DIRECTION_INPUT) {
+ if (common_hal_digitalio_digitalinout_get_direction(pin) !=
+ DIRECTION_INPUT) {
common_hal_digitalio_digitalinout_switch_to_input(pin, PULL_UP);
}
digitalio_pull_t pull = common_hal_digitalio_digitalinout_get_pull(pin);
@@ -52,9 +46,14 @@ void gamepad_init(size_t n_pins, const mp_obj_t* pins) {
common_hal_digitalio_digitalinout_set_pull(pin, PULL_UP);
}
if (pull != PULL_DOWN) {
- gamepad_singleton->pulls |= 1 << i;
+ gamepad->pulls |= 1 << i;
}
- gamepad_singleton->pins[i] = pin;
+ gamepad->pins[i] = pin;
}
- gamepad_singleton->last = 0;
+ gamepad->last = 0;
+}
+
+void common_hal_gamepad_gamepad_deinit(gamepad_obj_t *self) {
+ MP_STATE_VM(gamepad_singleton) = NULL;
+ supervisor_disable_tick();
}
diff --git a/shared-module/gamepad/GamePad.h b/shared-module/gamepad/GamePad.h
index 9fd5c9626..048fbcd2b 100644
--- a/shared-module/gamepad/GamePad.h
+++ b/shared-module/gamepad/GamePad.h
@@ -39,6 +39,4 @@ typedef struct {
uint8_t pulls;
} gamepad_obj_t;
-void gamepad_init(size_t n_pins, const mp_obj_t* pins);
-
#endif // MICROPY_INCLUDED_GAMEPAD_GAMEPAD_H
diff --git a/shared-module/gamepad/__init__.c b/shared-module/gamepad/__init__.c
index 8414ddfbe..9874b2752 100644
--- a/shared-module/gamepad/__init__.c
+++ b/shared-module/gamepad/__init__.c
@@ -27,34 +27,41 @@
#include <stdbool.h>
#include "py/mpstate.h"
-#include "__init__.h"
-#include "GamePad.h"
+#include "shared-bindings/gamepad/__init__.h"
+#include "shared-bindings/gamepad/GamePad.h"
+#include "supervisor/shared/tick.h"
#include "shared-bindings/digitalio/DigitalInOut.h"
void gamepad_tick(void) {
- gamepad_obj_t* gamepad_singleton = MP_STATE_VM(gamepad_singleton);
- if (!gamepad_singleton) {
+ uint8_t current = 0;
+ uint8_t bit = 1;
+
+ void* singleton = MP_STATE_VM(gamepad_singleton);
+ if (singleton == NULL || !MP_OBJ_IS_TYPE(MP_OBJ_FROM_PTR(singleton), &gamepad_type)) {
return;
}
- uint8_t gamepad_current = 0;
- uint8_t bit = 1;
+
+ gamepad_obj_t *self = MP_OBJ_TO_PTR(singleton);
for (int i = 0; i < 8; ++i) {
- digitalio_digitalinout_obj_t* pin = gamepad_singleton->pins[i];
+ digitalio_digitalinout_obj_t* pin = self->pins[i];
if (!pin) {
break;
}
if (common_hal_digitalio_digitalinout_get_value(pin)) {
- gamepad_current |= bit;
+ current |= bit;
}
bit <<= 1;
}
- gamepad_current ^= gamepad_singleton->pulls;
- gamepad_singleton->pressed |= gamepad_singleton->last & gamepad_current;
- gamepad_singleton->last = gamepad_current;
+ current ^= self->pulls;
+ self->pressed |= self->last & current;
+ self->last = current;
}
void gamepad_reset(void) {
+ if (MP_STATE_VM(gamepad_singleton)) {
+ supervisor_disable_tick();
+ }
MP_STATE_VM(gamepad_singleton) = NULL;
}
diff --git a/shared-module/gamepadshift/GamePadShift.c b/shared-module/gamepadshift/GamePadShift.c
new file mode 100644
index 000000000..51da61702
--- /dev/null
+++ b/shared-module/gamepadshift/GamePadShift.c
@@ -0,0 +1,51 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2016 Radomir Dopieralski 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/mpstate.h"
+#include "shared-bindings/digitalio/DigitalInOut.h"
+#include "shared-module/gamepadshift/GamePadShift.h"
+#include "supervisor/shared/tick.h"
+
+void common_hal_gamepadshift_gamepadshift_init(gamepadshift_obj_t *gamepadshift,
+ digitalio_digitalinout_obj_t *clock_pin,
+ digitalio_digitalinout_obj_t *data_pin,
+ digitalio_digitalinout_obj_t *latch_pin) {
+ common_hal_digitalio_digitalinout_switch_to_input(data_pin, PULL_NONE);
+ gamepadshift->data_pin = data_pin;
+ common_hal_digitalio_digitalinout_switch_to_output(clock_pin, 0,
+ DRIVE_MODE_PUSH_PULL);
+ gamepadshift->clock_pin = clock_pin;
+ common_hal_digitalio_digitalinout_switch_to_output(latch_pin, 1,
+ DRIVE_MODE_PUSH_PULL);
+ gamepadshift->latch_pin = latch_pin;
+
+ gamepadshift->last = 0;
+}
+
+void common_hal_gamepadshift_gamepadshift_deinit(gamepadshift_obj_t *gamepadshift) {
+ MP_STATE_VM(gamepad_singleton) = NULL;
+ supervisor_disable_tick();
+}
diff --git a/shared-module/gamepadshift/GamePadShift.h b/shared-module/gamepadshift/GamePadShift.h
new file mode 100644
index 000000000..b4b26b7a9
--- /dev/null
+++ b/shared-module/gamepadshift/GamePadShift.h
@@ -0,0 +1,43 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2016 Radomir Dopieralski 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_GAMEPADSHIFT_GAMEPADSHIFT_H
+#define MICROPY_INCLUDED_GAMEPADSHIFT_GAMEPADSHIFT_H
+
+#include <stdint.h>
+
+#include "shared-bindings/digitalio/DigitalInOut.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ digitalio_digitalinout_obj_t* data_pin;
+ digitalio_digitalinout_obj_t* clock_pin;
+ digitalio_digitalinout_obj_t* latch_pin;
+ volatile uint8_t pressed;
+ volatile uint8_t last;
+} gamepadshift_obj_t;
+
+#endif // MICROPY_INCLUDED_GAMEPADSHIFT_GAMEPADSHIFT_H
diff --git a/shared-module/gamepadshift/__init__.c b/shared-module/gamepadshift/__init__.c
new file mode 100644
index 000000000..47a008c50
--- /dev/null
+++ b/shared-module/gamepadshift/__init__.c
@@ -0,0 +1,57 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Scott Shawcroft
+ *
+ * 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 "shared-module/gamepadshift/__init__.h"
+
+#include "py/mpstate.h"
+#include "shared-bindings/gamepadshift/GamePadShift.h"
+
+void gamepadshift_tick(void) {
+ void* singleton = MP_STATE_VM(gamepad_singleton);
+ if (singleton == NULL || !MP_OBJ_IS_TYPE(MP_OBJ_FROM_PTR(singleton), &gamepadshift_type)) {
+ return;
+ }
+
+ gamepadshift_obj_t *self = MP_OBJ_TO_PTR(singleton);
+ uint8_t current = 0;
+ uint8_t bit = 1;
+ common_hal_digitalio_digitalinout_set_value(self->latch_pin, 1);
+ for (int i = 0; i < 8; ++i) {
+ common_hal_digitalio_digitalinout_set_value(self->clock_pin, 0);
+ if (common_hal_digitalio_digitalinout_get_value(self->data_pin)) {
+ current |= bit;
+ }
+ common_hal_digitalio_digitalinout_set_value(self->clock_pin, 1);
+ bit <<= 1;
+ }
+ common_hal_digitalio_digitalinout_set_value(self->latch_pin, 0);
+ self->pressed |= self->last & current;
+ self->last = current;
+}
+
+void gamepadshift_reset(void) {
+ MP_STATE_VM(gamepad_singleton) = NULL;
+}
diff --git a/shared-module/gamepadshift/__init__.h b/shared-module/gamepadshift/__init__.h
new file mode 100644
index 000000000..225db7336
--- /dev/null
+++ b/shared-module/gamepadshift/__init__.h
@@ -0,0 +1,33 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2016 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_GAMEPADSHIFT___INIT___H
+#define MICROPY_INCLUDED_GAMEPADSHIFT___INIT___H
+
+void gamepadshift_tick(void);
+void gamepadshift_reset(void);
+
+#endif // MICROPY_INCLUDED_GAMEPADSHIFT___INIT___H
diff --git a/shared-module/network/__init__.c b/shared-module/network/__init__.c
index a674e8478..a45191d8c 100644
--- a/shared-module/network/__init__.c
+++ b/shared-module/network/__init__.c
@@ -31,11 +31,13 @@
#include "py/mphal.h"
#include "py/mperrno.h"
+#include "supervisor/shared/tick.h"
+
#include "shared-bindings/random/__init__.h"
#include "shared-module/network/__init__.h"
-// mod_network_nic_list needs to be declared in mpconfigport.h
+// mod_network_nic_list needs to be declared in mpconfigport.h
void network_module_init(void) {
@@ -43,17 +45,23 @@ void network_module_init(void) {
}
void network_module_deinit(void) {
+ for (mp_uint_t i = 0; i < MP_STATE_PORT(mod_network_nic_list).len; i++) {
+ mp_obj_t nic = MP_STATE_PORT(mod_network_nic_list).items[i];
+ mod_network_nic_type_t *nic_type = (mod_network_nic_type_t*)mp_obj_get_type(nic);
+ if (nic_type->deinit != NULL) nic_type->deinit(nic);
+ }
+ mp_obj_list_set_len(&MP_STATE_PORT(mod_network_nic_list), 0);
}
void network_module_background(void) {
static uint32_t next_tick = 0;
- uint32_t this_tick = ticks_ms;
+ uint32_t this_tick = supervisor_ticks_ms32();
if (this_tick < next_tick) return;
next_tick = this_tick + 1000;
for (mp_uint_t i = 0; i < MP_STATE_PORT(mod_network_nic_list).len; i++) {
mp_obj_t nic = MP_STATE_PORT(mod_network_nic_list).items[i];
- mod_network_nic_type_t *nic_type = (mod_network_nic_type_t*)mp_obj_get_type(nic);
+ mod_network_nic_type_t *nic_type = (mod_network_nic_type_t*)mp_obj_get_type(nic);
if (nic_type->timer_tick != NULL) nic_type->timer_tick(nic);
}
}
@@ -93,3 +101,7 @@ void network_module_create_random_mac_address(uint8_t *mac) {
mac[4] = (uint8_t)(rb2 >> 8);
mac[5] = (uint8_t)(rb2);
}
+
+uint16_t network_module_create_random_source_tcp_port(void) {
+ return 0xc000 | shared_modules_random_getrandbits(14);
+}
diff --git a/shared-module/network/__init__.h b/shared-module/network/__init__.h
index 00a3c3957..f4eb05bb5 100644
--- a/shared-module/network/__init__.h
+++ b/shared-module/network/__init__.h
@@ -25,11 +25,12 @@
* THE SOFTWARE.
*/
-void network_module_create_random_mac_address(uint8_t *mac);
-
#ifndef MICROPY_INCLUDED_SHARED_MODULE_NETWORK___INIT___H
#define MICROPY_INCLUDED_SHARED_MODULE_NETWORK___INIT___H
+void network_module_create_random_mac_address(uint8_t *mac);
+uint16_t network_module_create_random_source_tcp_port(void);
+
#define MOD_NETWORK_IPADDR_BUF_SIZE (4)
#define MOD_NETWORK_AF_INET (2)
@@ -62,6 +63,7 @@ typedef struct _mod_network_nic_type_t {
int (*settimeout)(struct _mod_network_socket_obj_t *socket, mp_uint_t timeout_ms, int *_errno);
int (*ioctl)(struct _mod_network_socket_obj_t *socket, mp_uint_t request, mp_uint_t arg, int *_errno);
void (*timer_tick)(struct _mod_network_socket_obj_t *socket);
+ void (*deinit)(struct _mod_network_socket_obj_t *socket);
} mod_network_nic_type_t;
typedef struct _mod_network_socket_obj_t {
diff --git a/shared-module/os/__init__.c b/shared-module/os/__init__.c
index 313893d97..8060eec4f 100644
--- a/shared-module/os/__init__.c
+++ b/shared-module/os/__init__.c
@@ -128,6 +128,7 @@ mp_obj_t common_hal_os_listdir(const char* path) {
while ((next = mp_iternext(iter_obj)) != MP_OBJ_STOP_ITERATION) {
// next[0] is the filename.
mp_obj_list_append(dir_list, mp_obj_subscr(next, MP_OBJ_NEW_SMALL_INT(0), MP_OBJ_SENTINEL));
+ RUN_BACKGROUND_TASKS;
}
return dir_list;
}
diff --git a/shared-module/rgbmatrix/RGBMatrix.c b/shared-module/rgbmatrix/RGBMatrix.c
new file mode 100644
index 000000000..6dad91679
--- /dev/null
+++ b/shared-module/rgbmatrix/RGBMatrix.c
@@ -0,0 +1,208 @@
+/*
+ * This file is part of the Micro Python project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2020 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 <string.h>
+
+#include "py/gc.h"
+#include "py/obj.h"
+#include "py/objarray.h"
+#include "py/objproperty.h"
+#include "py/runtime.h"
+
+#include "common-hal/rgbmatrix/RGBMatrix.h"
+#include "shared-module/rgbmatrix/allocator.h"
+#include "shared-bindings/rgbmatrix/RGBMatrix.h"
+#include "shared-bindings/microcontroller/Pin.h"
+#include "shared-bindings/microcontroller/__init__.h"
+#include "shared-bindings/util.h"
+#include "shared-module/framebufferio/FramebufferDisplay.h"
+
+extern Protomatter_core *_PM_protoPtr;
+
+void common_hal_rgbmatrix_rgbmatrix_construct(rgbmatrix_rgbmatrix_obj_t *self, int width, int bit_depth, uint8_t rgb_count, uint8_t *rgb_pins, uint8_t addr_count, uint8_t *addr_pins, uint8_t clock_pin, uint8_t latch_pin, uint8_t oe_pin, bool doublebuffer, mp_obj_t framebuffer, void *timer) {
+ self->width = width;
+ self->bit_depth = bit_depth;
+ self->rgb_count = rgb_count;
+ memcpy(self->rgb_pins, rgb_pins, rgb_count);
+ self->addr_count = addr_count;
+ memcpy(self->addr_pins, addr_pins, addr_count);
+ self->clock_pin = clock_pin;
+ self->oe_pin = oe_pin;
+ self->latch_pin = latch_pin;
+ self->doublebuffer = doublebuffer;
+
+ self->timer = timer ? timer : common_hal_rgbmatrix_timer_allocate();
+ if (self->timer == NULL) {
+ mp_raise_ValueError(translate("No timer available"));
+ }
+
+ self->width = width;
+ self->bufsize = 2 * width * rgb_count / 3 * (1 << addr_count);
+
+ common_hal_rgbmatrix_rgbmatrix_reconstruct(self, framebuffer);
+}
+
+void common_hal_rgbmatrix_rgbmatrix_reconstruct(rgbmatrix_rgbmatrix_obj_t* self, mp_obj_t framebuffer) {
+ if (framebuffer) {
+ self->framebuffer = framebuffer;
+ framebuffer = mp_obj_new_bytearray_of_zeros(self->bufsize);
+ mp_get_buffer_raise(self->framebuffer, &self->bufinfo, MP_BUFFER_READ);
+ if (mp_get_buffer(self->framebuffer, &self->bufinfo, MP_BUFFER_RW)) {
+ self->bufinfo.typecode = 'H' | MP_OBJ_ARRAY_TYPECODE_FLAG_RW;
+ } else {
+ self->bufinfo.typecode = 'H';
+ }
+ // verify that the matrix is big enough
+ mp_get_index(mp_obj_get_type(self->framebuffer), self->bufinfo.len, MP_OBJ_NEW_SMALL_INT(self->bufsize-1), false);
+ } else {
+ _PM_FREE(self->bufinfo.buf);
+ _PM_FREE(self->core.rgbPins);
+ _PM_FREE(self->core.addr);
+ _PM_FREE(self->core.screenData);
+
+ self->framebuffer = NULL;
+ self->bufinfo.buf = _PM_allocator_impl(self->bufsize);
+ self->bufinfo.len = self->bufsize;
+ self->bufinfo.typecode = 'H' | MP_OBJ_ARRAY_TYPECODE_FLAG_RW;
+ }
+
+ ProtomatterStatus stat = _PM_init(&self->core,
+ self->width, self->bit_depth,
+ self->rgb_count/6, self->rgb_pins,
+ self->addr_count, self->addr_pins,
+ self->clock_pin, self->latch_pin, self->oe_pin,
+ self->doublebuffer, self->timer);
+
+ if (stat == PROTOMATTER_OK) {
+ _PM_protoPtr = &self->core;
+ common_hal_mcu_disable_interrupts();
+ common_hal_rgbmatrix_timer_enable(self->timer);
+ stat = _PM_begin(&self->core);
+ _PM_convert_565(&self->core, self->bufinfo.buf, self->width);
+ common_hal_mcu_enable_interrupts();
+ _PM_swapbuffer_maybe(&self->core);
+ }
+
+ if (stat != PROTOMATTER_OK) {
+ // XXX this deinit() actually makes crashy-crashy
+ // can trigger it by sending inappropriate pins
+ common_hal_rgbmatrix_rgbmatrix_deinit(self);
+ switch (stat) {
+ case PROTOMATTER_ERR_PINS:
+ mp_raise_ValueError(translate("Invalid pin"));
+ break;
+ case PROTOMATTER_ERR_ARG:
+ mp_raise_ValueError(translate("Invalid argument"));
+ break;
+ case PROTOMATTER_ERR_MALLOC: /// should have already been signaled as NLR
+ default:
+ mp_raise_msg_varg(&mp_type_RuntimeError,
+ translate("Internal error #%d"), (int)stat);
+ break;
+ }
+ }
+
+ self->paused = 0;
+
+}
+
+STATIC void free_pin(uint8_t *pin) {
+ if (*pin != COMMON_HAL_MCU_NO_PIN) {
+ common_hal_mcu_pin_reset_number(*pin);
+ }
+ *pin = COMMON_HAL_MCU_NO_PIN;
+}
+
+STATIC void free_pin_seq(uint8_t *seq, int count) {
+ for (int i=0; i<count; i++) {
+ free_pin(&seq[i]);
+ }
+}
+
+void common_hal_rgbmatrix_rgbmatrix_deinit(rgbmatrix_rgbmatrix_obj_t* self) {
+ if (self->timer) {
+ common_hal_rgbmatrix_timer_free(self->timer);
+ self->timer = 0;
+ }
+
+ if (_PM_protoPtr == &self->core) {
+ _PM_protoPtr = NULL;
+ }
+
+ free_pin_seq(self->rgb_pins, self->rgb_count);
+ free_pin_seq(self->addr_pins, self->addr_count);
+ free_pin(&self->clock_pin);
+ free_pin(&self->latch_pin);
+ free_pin(&self->oe_pin);
+
+ if (self->core.rgbPins) {
+ _PM_free(&self->core);
+ }
+ memset(&self->core, 0, sizeof(self->core));
+
+ // If it was supervisor-allocated, it is supervisor-freed and the pointer
+ // is zeroed, otherwise the pointer is just zeroed
+ _PM_FREE(self->bufinfo.buf);
+ self->base.type = NULL;
+
+ // If a framebuffer was passed in to the constructor, NULL the reference
+ // here so that it will become GC'able
+ self->framebuffer = NULL;
+}
+
+void rgbmatrix_rgbmatrix_collect_ptrs(rgbmatrix_rgbmatrix_obj_t* self) {
+ gc_collect_ptr(self->framebuffer);
+ gc_collect_ptr(self->core.rgbPins);
+ gc_collect_ptr(self->core.addr);
+ gc_collect_ptr(self->core.screenData);
+}
+
+void common_hal_rgbmatrix_rgbmatrix_set_paused(rgbmatrix_rgbmatrix_obj_t* self, bool paused) {
+ if (paused && !self->paused) {
+ _PM_stop(&self->core);
+ } else if (!paused && self->paused) {
+ _PM_resume(&self->core);
+ }
+ self->paused = paused;
+}
+
+bool common_hal_rgbmatrix_rgbmatrix_get_paused(rgbmatrix_rgbmatrix_obj_t* self) {
+ return self->paused;
+}
+
+void common_hal_rgbmatrix_rgbmatrix_refresh(rgbmatrix_rgbmatrix_obj_t* self) {
+ _PM_convert_565(&self->core, self->bufinfo.buf, self->width);
+ _PM_swapbuffer_maybe(&self->core);
+}
+
+int common_hal_rgbmatrix_rgbmatrix_get_width(rgbmatrix_rgbmatrix_obj_t* self) {
+ return self->width;
+}
+
+int common_hal_rgbmatrix_rgbmatrix_get_height(rgbmatrix_rgbmatrix_obj_t* self) {
+ int computed_height = (self->rgb_count / 3) << (self->addr_count);
+ return computed_height;
+}
diff --git a/shared-module/rgbmatrix/RGBMatrix.h b/shared-module/rgbmatrix/RGBMatrix.h
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/shared-module/rgbmatrix/RGBMatrix.h
diff --git a/shared-module/rgbmatrix/__init__.c b/shared-module/rgbmatrix/__init__.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/shared-module/rgbmatrix/__init__.c
diff --git a/shared-module/rgbmatrix/__init__.h b/shared-module/rgbmatrix/__init__.h
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/shared-module/rgbmatrix/__init__.h
diff --git a/shared-module/rgbmatrix/allocator.h b/shared-module/rgbmatrix/allocator.h
new file mode 100644
index 000000000..5e6f0b41d
--- /dev/null
+++ b/shared-module/rgbmatrix/allocator.h
@@ -0,0 +1,29 @@
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_RGBMATRIX_ALLOCATOR_H
+#define MICROPY_INCLUDED_SHARED_MODULE_RGBMATRIX_ALLOCATOR_H
+
+#include <stdbool.h>
+#include "py/gc.h"
+#include "py/misc.h"
+#include "supervisor/memory.h"
+
+#define _PM_ALLOCATOR _PM_allocator_impl
+#define _PM_FREE(x) (_PM_free_impl((x)), (x)=NULL, (void)0)
+
+static inline void *_PM_allocator_impl(size_t sz) {
+ if (gc_alloc_possible()) {
+ return m_malloc(sz + sizeof(void*), true);
+ } else {
+ supervisor_allocation *allocation = allocate_memory(align32_size(sz), false);
+ return allocation ? allocation->ptr : NULL;
+ }
+}
+
+static inline void _PM_free_impl(void *ptr_in) {
+ supervisor_allocation *allocation = allocation_from_ptr(ptr_in);
+
+ if (allocation) {
+ free_memory(allocation);
+ }
+}
+
+#endif
diff --git a/shared-module/storage/__init__.c b/shared-module/storage/__init__.c
index f09edd785..c3d4b50c8 100644
--- a/shared-module/storage/__init__.c
+++ b/shared-module/storage/__init__.c
@@ -143,20 +143,19 @@ mp_obj_t common_hal_storage_getmount(const char *mount_path) {
return storage_object_from_path(mount_path);
}
-void common_hal_storage_remount(const char *mount_path, bool readonly) {
+void common_hal_storage_remount(const char *mount_path, bool readonly, bool disable_concurrent_write_protection) {
if (strcmp(mount_path, "/") != 0) {
mp_raise_OSError(MP_EINVAL);
}
#ifdef USB_AVAILABLE
- // TODO(dhalbert): is this is a good enough check? It checks for
- // CDC enabled. There is no "MSC enabled" check.
- if (usb_enabled()) {
+ if (!usb_msc_ejected()) {
mp_raise_RuntimeError(translate("Cannot remount '/' when USB is active."));
}
#endif
- supervisor_flash_set_usb_writable(readonly);
+ filesystem_set_internal_writable_by_usb(readonly);
+ filesystem_set_internal_concurrent_write_protection(!disable_concurrent_write_protection);
}
void common_hal_storage_erase_filesystem(void) {
diff --git a/shared-module/struct/__init__.c b/shared-module/struct/__init__.c
index 78c04f07b..245dbbda9 100644
--- a/shared-module/struct/__init__.c
+++ b/shared-module/struct/__init__.c
@@ -71,45 +71,6 @@ mp_uint_t get_fmt_num(const char **p) {
return val;
}
-void shared_modules_struct_pack_into(mp_obj_t fmt_in, byte *p, byte* end_p, size_t n_args, const mp_obj_t *args) {
- const char *fmt = mp_obj_str_get_str(fmt_in);
- char fmt_type = get_fmt_type(&fmt);
-
- size_t i;
- for (i = 0; i < n_args;) {
- mp_uint_t sz = 1;
- if (*fmt == '\0') {
- // more arguments given than used by format string; CPython raises struct.error here
- mp_raise_RuntimeError(translate("too many arguments provided with the given format"));
- }
- struct_validate_format(*fmt);
-
- if (unichar_isdigit(*fmt)) {
- sz = get_fmt_num(&fmt);
- }
- if (p + sz > end_p) {
- mp_raise_RuntimeError(translate("buffer too small"));
- }
-
- if (*fmt == 's') {
- mp_buffer_info_t bufinfo;
- mp_get_buffer_raise(args[i++], &bufinfo, MP_BUFFER_READ);
- mp_uint_t to_copy = sz;
- if (bufinfo.len < to_copy) {
- to_copy = bufinfo.len;
- }
- memcpy(p, bufinfo.buf, to_copy);
- memset(p + to_copy, 0, sz - to_copy);
- p += sz;
- } else {
- while (sz--) {
- mp_binary_set_val(fmt_type, *fmt, args[i++], &p);
- }
- }
- fmt++;
- }
-}
-
mp_uint_t calcsize_items(const char *fmt) {
mp_uint_t cnt = 0;
while (*fmt) {
@@ -120,7 +81,10 @@ mp_uint_t calcsize_items(const char *fmt) {
num = 1;
}
}
- cnt += num;
+ // Pad bytes are skipped and don't get included in the item count.
+ if (*fmt != 'x') {
+ cnt += num;
+ }
fmt++;
}
return cnt;
@@ -155,14 +119,71 @@ mp_uint_t shared_modules_struct_calcsize(mp_obj_t fmt_in) {
return size;
}
+void shared_modules_struct_pack_into(mp_obj_t fmt_in, byte *p, byte* end_p, size_t n_args, const mp_obj_t *args) {
+ const char *fmt = mp_obj_str_get_str(fmt_in);
+ char fmt_type = get_fmt_type(&fmt);
+ const mp_uint_t total_sz = shared_modules_struct_calcsize(fmt_in);
+
+ if (p + total_sz > end_p) {
+ mp_raise_RuntimeError(translate("buffer too small"));
+ }
+
+ size_t i;
+ for (i = 0; i < n_args;) {
+ mp_uint_t sz = 1;
+ if (*fmt == '\0') {
+ // more arguments given than used by format string; CPython raises struct.error here
+ mp_raise_RuntimeError(translate("too many arguments provided with the given format"));
+ }
+ struct_validate_format(*fmt);
+
+ if (unichar_isdigit(*fmt)) {
+ sz = get_fmt_num(&fmt);
+ }
+
+ if (*fmt == 's') {
+ mp_buffer_info_t bufinfo;
+ mp_get_buffer_raise(args[i++], &bufinfo, MP_BUFFER_READ);
+ mp_uint_t to_copy = sz;
+ if (bufinfo.len < to_copy) {
+ to_copy = bufinfo.len;
+ }
+ memcpy(p, bufinfo.buf, to_copy);
+ memset(p + to_copy, 0, sz - to_copy);
+ 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') {
+ i++;
+ }
+ }
+ }
+ fmt++;
+ }
+}
-mp_obj_tuple_t * shared_modules_struct_unpack_from(mp_obj_t fmt_in, byte *p, byte *end_p) {
+mp_obj_tuple_t * shared_modules_struct_unpack_from(mp_obj_t fmt_in, byte *p, byte *end_p, bool exact_size) {
const char *fmt = mp_obj_str_get_str(fmt_in);
char fmt_type = get_fmt_type(&fmt);
- mp_uint_t num_items = calcsize_items(fmt);
+ const mp_uint_t num_items = calcsize_items(fmt);
+ const mp_uint_t total_sz = shared_modules_struct_calcsize(fmt_in);
mp_obj_tuple_t *res = MP_OBJ_TO_PTR(mp_obj_new_tuple(num_items, NULL));
+ // If exact_size, make sure the buffer is exactly the right size.
+ // Otherwise just make sure it's big enough.
+ if (exact_size) {
+ if (p + total_sz != end_p) {
+ mp_raise_RuntimeError(translate("buffer size must match format"));
+ }
+ } else {
+ if (p + total_sz > end_p) {
+ mp_raise_RuntimeError(translate("buffer too small"));
+ }
+ }
+
for (uint i = 0; i < num_items;) {
mp_uint_t sz = 1;
@@ -171,9 +192,6 @@ mp_obj_tuple_t * shared_modules_struct_unpack_from(mp_obj_t fmt_in, byte *p, byt
if (unichar_isdigit(*fmt)) {
sz = get_fmt_num(&fmt);
}
- if (p + sz > end_p) {
- mp_raise_RuntimeError(translate("buffer too small"));
- }
mp_obj_t item;
if (*fmt == 's') {
item = mp_obj_new_bytes(p, sz);
@@ -182,7 +200,10 @@ mp_obj_tuple_t * shared_modules_struct_unpack_from(mp_obj_t fmt_in, byte *p, byt
} else {
while (sz--) {
item = mp_binary_get_val(fmt_type, *fmt, &p);
- res->items[i++] = item;
+ // Pad bytes are not stored.
+ if (*fmt != 'x') {
+ res->items[i++] = item;
+ }
}
}
fmt++;
diff --git a/shared-module/terminalio/Terminal.c b/shared-module/terminalio/Terminal.c
new file mode 100644
index 000000000..df92a5dc4
--- /dev/null
+++ b/shared-module/terminalio/Terminal.c
@@ -0,0 +1,130 @@
+/*
+ * 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.
+ */
+
+#include "shared-module/terminalio/Terminal.h"
+
+#include "shared-module/fontio/BuiltinFont.h"
+#include "shared-bindings/displayio/TileGrid.h"
+
+void common_hal_terminalio_terminal_construct(terminalio_terminal_obj_t *self, displayio_tilegrid_t* tilegrid, const fontio_builtinfont_t* font) {
+ self->cursor_x = 0;
+ self->cursor_y = 0;
+ self->font = font;
+ self->tilegrid = tilegrid;
+ self->first_row = 0;
+
+ for (uint16_t x = 0; x < self->tilegrid->width_in_tiles; x++) {
+ for (uint16_t y = 0; y < self->tilegrid->height_in_tiles; y++) {
+ common_hal_displayio_tilegrid_set_tile(self->tilegrid, x, y, 0);
+ }
+ }
+
+ common_hal_displayio_tilegrid_set_top_left(self->tilegrid, 0, 1);
+}
+
+size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, const byte *data, size_t len, int *errcode) {
+ const byte* i = data;
+ uint16_t start_y = self->cursor_y;
+ while (i < data + len) {
+ unichar c = utf8_get_char(i);
+ i = utf8_next_char(i);
+ // Always handle ASCII.
+ if (c < 128) {
+ if (c >= 0x20 && c <= 0x7e) {
+ uint8_t tile_index = fontio_builtinfont_get_glyph_index(self->font, c);
+ common_hal_displayio_tilegrid_set_tile(self->tilegrid, self->cursor_x, self->cursor_y, tile_index);
+ self->cursor_x++;
+ } else if (c == '\r') {
+ self->cursor_x = 0;
+ } else if (c == '\n') {
+ self->cursor_y++;
+ // Commands below are used by MicroPython in the REPL
+ } else if (c == '\b') {
+ if (self->cursor_x > 0) {
+ self->cursor_x--;
+ }
+ } else if (c == 0x1b) {
+ if (i[0] == '[') {
+ if (i[1] == 'K') {
+ // Clear the rest of the line.
+ for (uint16_t j = self->cursor_x; j < self->tilegrid->width_in_tiles; j++) {
+ common_hal_displayio_tilegrid_set_tile(self->tilegrid, j, self->cursor_y, 0);
+ }
+ i += 2;
+ } else {
+ // Handle commands of the form \x1b[####D
+ uint16_t n = 0;
+ uint8_t j = 1;
+ for (; j < 6; j++) {
+ if ('0' <= i[j] && i[j] <= '9') {
+ n = n * 10 + (i[j] - '0');
+ } else {
+ c = i[j];
+ break;
+ }
+ }
+ if (c == 'D') {
+ if (n > self->cursor_x) {
+ self->cursor_x = 0;
+ } else {
+ self->cursor_x -= n;
+ }
+ }
+ i += j + 1;
+ continue;
+ }
+ }
+ }
+ } else {
+ uint8_t tile_index = fontio_builtinfont_get_glyph_index(self->font, c);
+ if (tile_index != 0xff) {
+ common_hal_displayio_tilegrid_set_tile(self->tilegrid, self->cursor_x, self->cursor_y, tile_index);
+ self->cursor_x++;
+
+ }
+ }
+ if (self->cursor_x >= self->tilegrid->width_in_tiles) {
+ self->cursor_y++;
+ self->cursor_x %= self->tilegrid->width_in_tiles;
+ }
+ if (self->cursor_y >= self->tilegrid->height_in_tiles) {
+ self->cursor_y %= self->tilegrid->height_in_tiles;
+ }
+ if (self->cursor_y != start_y) {
+ // clear the new row
+ for (uint16_t j = 0; j < self->tilegrid->width_in_tiles; j++) {
+ common_hal_displayio_tilegrid_set_tile(self->tilegrid, j, self->cursor_y, 0);
+ start_y = self->cursor_y;
+ }
+ common_hal_displayio_tilegrid_set_top_left(self->tilegrid, 0, (start_y + self->tilegrid->height_in_tiles + 1) % self->tilegrid->height_in_tiles);
+ }
+ }
+ return i - data;
+}
+
+bool common_hal_terminalio_terminal_ready_to_tx(terminalio_terminal_obj_t *self) {
+ return true;
+}
diff --git a/shared-module/terminalio/Terminal.h b/shared-module/terminalio/Terminal.h
new file mode 100644
index 000000000..c31392cc4
--- /dev/null
+++ b/shared-module/terminalio/Terminal.h
@@ -0,0 +1,46 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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 SHARED_MODULE_TERMINALIO_TERMINAL_H
+#define SHARED_MODULE_TERMINALIO_TERMINAL_H
+
+#include <stdint.h>
+#include <stdbool.h>
+
+#include "py/obj.h"
+#include "shared-module/fontio/BuiltinFont.h"
+#include "shared-module/displayio/TileGrid.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ const fontio_builtinfont_t* font;
+ uint16_t cursor_x;
+ uint16_t cursor_y;
+ displayio_tilegrid_t* tilegrid;
+ uint16_t first_row;
+} terminalio_terminal_obj_t;
+
+#endif /* SHARED_MODULE_TERMINALIO_TERMINAL_H */
diff --git a/shared-module/terminalio/__init__.c b/shared-module/terminalio/__init__.c
new file mode 100644
index 000000000..3f61f4823
--- /dev/null
+++ b/shared-module/terminalio/__init__.c
@@ -0,0 +1,27 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 hathach 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 "shared-bindings/terminalio/__init__.h"
diff --git a/shared-module/terminalio/__init__.h b/shared-module/terminalio/__init__.h
new file mode 100644
index 000000000..e925dd429
--- /dev/null
+++ b/shared-module/terminalio/__init__.h
@@ -0,0 +1,30 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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 SHARED_MODULE_TERMINALIO___INIT___H
+#define SHARED_MODULE_TERMINALIO___INIT___H
+
+#endif /* SHARED_MODULE_TERMINALIO___INIT___H */
diff --git a/shared-module/time/__init__.c b/shared-module/time/__init__.c
new file mode 100644
index 000000000..347e68ae0
--- /dev/null
+++ b/shared-module/time/__init__.c
@@ -0,0 +1,45 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2016 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 "py/mphal.h"
+#include "supervisor/port.h"
+#include "supervisor/shared/tick.h"
+
+uint64_t common_hal_time_monotonic(void) {
+ return supervisor_ticks_ms64();
+}
+
+uint64_t common_hal_time_monotonic_ns(void) {
+ uint8_t subticks = 0;
+ uint64_t ticks = port_get_raw_ticks(&subticks);
+ // A tick is 976562.5 nanoseconds so multiply it by the base and add half instead of doing float
+ // math.
+ return 976562 * ticks + ticks / 2 + 30518 * subticks;
+}
+
+void common_hal_time_delay_ms(uint32_t delay) {
+ mp_hal_delay_ms(delay);
+}
diff --git a/shared-module/touchio/TouchIn.c b/shared-module/touchio/TouchIn.c
new file mode 100644
index 000000000..88d12b8b8
--- /dev/null
+++ b/shared-module/touchio/TouchIn.c
@@ -0,0 +1,115 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2016 Scott Shawcroft for Adafruit Industries
+ * Copyright (c) 2018 Nick Moore 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 <string.h>
+#include <stdio.h>
+
+#include "py/runtime.h"
+#include "py/mphal.h"
+#include "shared-bindings/touchio/TouchIn.h"
+
+// This is a capacitive touch sensing routine using a single digital
+// pin. The pin should be connected to the sensing pad, and to ground
+// via a 1Mohm or thereabout drain resistor. When a reading is taken,
+// the pin's capacitance is charged by setting it to a digital output
+// 'high' for a few microseconds, and then it is changed to a high
+// impedance input. We measure how long it takes to discharge through
+// the resistor (around 50us), using a busy-waiting loop, and average
+// over N_SAMPLES cycles to reduce the effects of noise.
+
+#define N_SAMPLES 10
+#define TIMEOUT_TICKS 10000
+
+static uint16_t get_raw_reading(touchio_touchin_obj_t *self) {
+
+ uint16_t ticks = 0;
+
+ for (uint16_t i = 0; i < N_SAMPLES; i++) {
+ // set pad to digital output high for 10us to charge it
+
+ common_hal_digitalio_digitalinout_switch_to_output(self->digitalinout, true, DRIVE_MODE_PUSH_PULL);
+ mp_hal_delay_us(10);
+
+ // set pad back to an input and take some samples
+
+ common_hal_digitalio_digitalinout_switch_to_input(self->digitalinout, PULL_NONE);
+
+ while(common_hal_digitalio_digitalinout_get_value(self->digitalinout)) {
+ if (ticks >= TIMEOUT_TICKS) return TIMEOUT_TICKS;
+ ticks++;
+ }
+ }
+ return ticks;
+}
+
+void common_hal_touchio_touchin_construct(touchio_touchin_obj_t* self, const mcu_pin_obj_t *pin) {
+ claim_pin(pin);
+ self->digitalinout = m_new_obj(digitalio_digitalinout_obj_t);
+ self->digitalinout->base.type = &digitalio_digitalinout_type;
+
+ common_hal_digitalio_digitalinout_construct(self->digitalinout, pin);
+
+ uint16_t raw_reading = get_raw_reading(self);
+ if (raw_reading == TIMEOUT_TICKS) {
+ mp_raise_ValueError(translate("No pulldown on pin; 1Mohm recommended"));
+ }
+ self->threshold = raw_reading * 1.05 + 100;
+}
+
+bool common_hal_touchio_touchin_deinited(touchio_touchin_obj_t* self) {
+ return self->digitalinout == MP_OBJ_NULL;
+}
+
+void common_hal_touchio_touchin_deinit(touchio_touchin_obj_t* self) {
+ if (common_hal_touchio_touchin_deinited(self)) {
+ return;
+ }
+
+ common_hal_digitalio_digitalinout_deinit(self->digitalinout);
+ self->digitalinout = MP_OBJ_NULL;
+}
+
+void touchin_reset() {
+}
+
+bool common_hal_touchio_touchin_get_value(touchio_touchin_obj_t *self) {
+ uint16_t reading = get_raw_reading(self);
+ return reading > self->threshold;
+}
+
+uint16_t common_hal_touchio_touchin_get_raw_value(touchio_touchin_obj_t *self) {
+ return get_raw_reading(self);
+}
+
+uint16_t common_hal_touchio_touchin_get_threshold(touchio_touchin_obj_t *self) {
+ return self->threshold;
+}
+
+void common_hal_touchio_touchin_set_threshold(touchio_touchin_obj_t *self,
+ uint16_t new_threshold) {
+ self->threshold = new_threshold;
+}
diff --git a/shared-module/touchio/TouchIn.h b/shared-module/touchio/TouchIn.h
new file mode 100644
index 000000000..8ff6fda8f
--- /dev/null
+++ b/shared-module/touchio/TouchIn.h
@@ -0,0 +1,44 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2016 Scott Shawcroft
+ * Copyright (c) 2018 Nick Moore 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_SHARED_MODULE_TOUCHIO_TOUCHIN_H
+#define MICROPY_INCLUDED_SHARED_MODULE_TOUCHIO_TOUCHIN_H
+
+#include "common-hal/microcontroller/Pin.h"
+#include "shared-bindings/digitalio/DigitalInOut.h"
+
+#include "py/obj.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ digitalio_digitalinout_obj_t *digitalinout;
+ uint16_t threshold;
+} touchio_touchin_obj_t;
+
+void touchin_reset(void);
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_TOUCHIO_TOUCHIN_H
diff --git a/shared-module/touchio/__init__.c b/shared-module/touchio/__init__.c
new file mode 100644
index 000000000..d2290447c
--- /dev/null
+++ b/shared-module/touchio/__init__.c
@@ -0,0 +1 @@
+// No touchio module functions.
diff --git a/shared-module/usb_hid/Device.c b/shared-module/usb_hid/Device.c
index 820e14ad0..8e9df6f04 100644
--- a/shared-module/usb_hid/Device.c
+++ b/shared-module/usb_hid/Device.c
@@ -25,11 +25,12 @@
*/
#include <string.h>
-#include "tick.h"
+
#include "py/runtime.h"
#include "shared-bindings/usb_hid/Device.h"
#include "shared-module/usb_hid/Device.h"
#include "supervisor/shared/translate.h"
+#include "supervisor/shared/tick.h"
#include "tusb.h"
uint8_t common_hal_usb_hid_device_get_usage_page(usb_hid_device_obj_t *self) {
@@ -46,41 +47,49 @@ void common_hal_usb_hid_device_send_report(usb_hid_device_obj_t *self, uint8_t*
}
// Wait until interface is ready, timeout = 2 seconds
- uint64_t end_ticks = ticks_ms + 2000;
- while ( (ticks_ms < end_ticks) && !tud_hid_generic_ready() ) { }
+ uint64_t end_ticks = supervisor_ticks_ms64() + 2000;
+ while ( (supervisor_ticks_ms64() < end_ticks) && !tud_hid_ready() ) {
+ RUN_BACKGROUND_TASKS;
+ }
- if ( !tud_hid_generic_ready() ) {
+ if ( !tud_hid_ready() ) {
mp_raise_msg(&mp_type_OSError, translate("USB Busy"));
}
memcpy(self->report_buffer, report, len);
- if ( !tud_hid_generic_report(self->report_id, self->report_buffer, len) ) {
+ if ( !tud_hid_report(self->report_id, self->report_buffer, len) ) {
mp_raise_msg(&mp_type_OSError, translate("USB Error"));
}
}
+static usb_hid_device_obj_t* get_hid_device(uint8_t report_id) {
+ for (uint8_t i = 0; i < USB_HID_NUM_DEVICES; i++) {
+ if (usb_hid_devices[i].report_id == report_id) {
+ return &usb_hid_devices[i];
+ }
+ }
+ return NULL;
+}
+
// Callbacks invoked when receive Get_Report request through control endpoint
-uint16_t tud_hid_generic_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen) {
+uint16_t tud_hid_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen) {
// only support Input Report
if ( report_type != HID_REPORT_TYPE_INPUT ) return 0;
- // index is ID-1
- uint8_t idx = ( report_id ? (report_id-1) : 0 );
-
// fill buffer with current report
- memcpy(buffer, usb_hid_devices[idx].report_buffer, reqlen);
+ memcpy(buffer, get_hid_device(report_id)->report_buffer, reqlen);
return reqlen;
}
// Callbacks invoked when receive Set_Report request through control endpoint
-void tud_hid_generic_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize) {
- // index is ID-1
- uint8_t idx = ( report_id ? (report_id-1) : 0 );
+void tud_hid_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize) {
+ usb_hid_device_obj_t* hid_device = get_hid_device(report_id);
if ( report_type == HID_REPORT_TYPE_OUTPUT ) {
// Check if it is Keyboard device
- if ( (usb_hid_devices[idx].usage_page == HID_USAGE_PAGE_DESKTOP) && (usb_hid_devices[idx].usage == HID_USAGE_DESKTOP_KEYBOARD) ) {
+ if (hid_device->usage_page == HID_USAGE_PAGE_DESKTOP &&
+ hid_device->usage == HID_USAGE_DESKTOP_KEYBOARD) {
// This is LED indicator (CapsLock, NumLock)
// TODO Light up some LED here
}
diff --git a/shared-module/usb_hid/__init__.c b/shared-module/usb_hid/__init__.c
index f14fdd41e..d88f9787a 100644
--- a/shared-module/usb_hid/__init__.c
+++ b/shared-module/usb_hid/__init__.c
@@ -24,131 +24,4 @@
* THE SOFTWARE.
*/
-#include "py/obj.h"
-#include "py/mphal.h"
-#include "py/runtime.h"
-
-#include "genhdr/autogen_usb_descriptor.h"
-#include "shared-module/usb_hid/Device.h"
-#include "shared-bindings/usb_hid/Device.h"
-#include "tusb.h"
-
-#ifdef USB_HID_REPORT_ID_KEYBOARD
-static uint8_t keyboard_report_buffer[USB_HID_REPORT_LENGTH_KEYBOARD];
-#endif
-
-#ifdef USB_HID_REPORT_ID_MOUSE
-static uint8_t mouse_report_buffer[USB_HID_REPORT_LENGTH_MOUSE];
-#endif
-
-#ifdef USB_HID_REPORT_ID_CONSUMER
-static uint8_t consumer_report_buffer[USB_HID_REPORT_LENGTH_CONSUMER];
-#endif
-
-#ifdef USB_HID_REPORT_ID_SYS_CONTROL
-static uint8_t sys_control_report_buffer[USB_HID_REPORT_LENGTH_SYS_CONTROL];
-#endif
-
-#ifdef USB_HID_REPORT_ID_GAMEPAD
-static uint8_t gamepad_report_buffer[USB_HID_REPORT_LENGTH_GAMEPAD];
-#endif
-
-#ifdef USB_HID_REPORT_ID_DIGITIZER
-static uint8_t digitizer_report_buffer[USB_HID_REPORT_LENGTH_DIGITIZER];
-#endif
-
-usb_hid_device_obj_t usb_hid_devices[] = {
-#ifdef USB_HID_REPORT_ID_KEYBOARD
- {
- .base = { .type = &usb_hid_device_type } ,
- .report_buffer = keyboard_report_buffer ,
- .report_id = USB_HID_REPORT_ID_KEYBOARD ,
- .report_length = USB_HID_REPORT_LENGTH_KEYBOARD ,
- .usage_page = HID_USAGE_PAGE_DESKTOP ,
- .usage = HID_USAGE_DESKTOP_KEYBOARD ,
- },
-#endif
-
-#ifdef USB_HID_REPORT_ID_MOUSE
- {
- .base = { .type = &usb_hid_device_type } ,
- .report_buffer = mouse_report_buffer ,
- .report_id = USB_HID_REPORT_ID_MOUSE ,
- .report_length = USB_HID_REPORT_LENGTH_MOUSE ,
- .usage_page = HID_USAGE_PAGE_DESKTOP ,
- .usage = HID_USAGE_DESKTOP_MOUSE ,
- },
-#endif
-
-#ifdef USB_HID_REPORT_ID_CONSUMER
- {
- .base = { .type = &usb_hid_device_type } ,
- .report_buffer = consumer_report_buffer ,
- .report_id = USB_HID_REPORT_ID_CONSUMER ,
- .report_length = USB_HID_REPORT_LENGTH_CONSUMER ,
- .usage_page = HID_USAGE_PAGE_CONSUMER ,
- .usage = HID_USAGE_CONSUMER_CONTROL ,
- },
-#endif
-
-#ifdef USB_HID_REPORT_ID_SYS_CONTROL
- {
- .base = { .type = &usb_hid_device_type } ,
- .report_buffer = sys_control_report_buffer ,
- .report_id = USB_HID_REPORT_ID_SYS_CONTROL ,
- .report_length = USB_HID_REPORT_LENGTH_SYS_CONTROL ,
- .usage_page = HID_USAGE_PAGE_DESKTOP ,
- .usage = HID_USAGE_DESKTOP_SYSTEM_CONTROL ,
- },
-#endif
-
-#ifdef USB_HID_REPORT_ID_GAMEPAD
- {
- .base = { .type = &usb_hid_device_type } ,
- .report_buffer = gamepad_report_buffer ,
- .report_id = USB_HID_REPORT_ID_GAMEPAD ,
- .report_length = USB_HID_REPORT_LENGTH_GAMEPAD ,
- .usage_page = HID_USAGE_PAGE_DESKTOP ,
- .usage = HID_USAGE_DESKTOP_GAMEPAD ,
- },
-#endif
-
-#ifdef USB_HID_REPORT_ID_DIGITIZER
- {
- .base = { .type = &usb_hid_device_type } ,
- .report_buffer = digitizer_report_buffer ,
- .report_id = USB_HID_REPORT_ID_DIGITIZER ,
- .report_length = USB_HID_REPORT_LENGTH_DIGITIZER ,
- .usage_page = 0x0D ,
- .usage = 0x02 ,
- },
-#endif
-};
-
-
-mp_obj_tuple_t common_hal_usb_hid_devices = {
- .base = {
- .type = &mp_type_tuple,
- },
- .len = USB_HID_NUM_DEVICES,
- .items = {
-#if USB_HID_NUM_DEVICES >= 1
- (mp_obj_t) &usb_hid_devices[0],
-#endif
-#if USB_HID_NUM_DEVICES >= 2
- (mp_obj_t) &usb_hid_devices[1],
-#endif
-#if USB_HID_NUM_DEVICES >= 3
- (mp_obj_t) &usb_hid_devices[2],
-#endif
-#if USB_HID_NUM_DEVICES >= 4
- (mp_obj_t) &usb_hid_devices[3],
-#endif
-#if USB_HID_NUM_DEVICES >= 5
- (mp_obj_t) &usb_hid_devices[4],
-#endif
-#if USB_HID_NUM_DEVICES >= 6
- (mp_obj_t) &usb_hid_devices[5],
-#endif
- }
-};
+// Nothing needed here. Tables of HID devices are generated in autogen_usb_descriptor.c at compile-time.
diff --git a/shared-module/usb_midi/PortIn.c b/shared-module/usb_midi/PortIn.c
new file mode 100644
index 000000000..31e320baa
--- /dev/null
+++ b/shared-module/usb_midi/PortIn.c
@@ -0,0 +1,37 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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 "shared-module/usb_midi/PortIn.h"
+#include "supervisor/shared/translate.h"
+#include "tusb.h"
+
+size_t common_hal_usb_midi_portin_read(usb_midi_portin_obj_t *self, uint8_t *data, size_t len, int *errcode) {
+ return tud_midi_read(data, len);
+}
+
+uint32_t common_hal_usb_midi_portin_bytes_available(usb_midi_portin_obj_t *self) {
+ return tud_midi_available();
+}
diff --git a/shared-module/bleio/Scanner.h b/shared-module/usb_midi/PortIn.h
index 76f5e5866..2f72aa4c2 100644
--- a/shared-module/bleio/Scanner.h
+++ b/shared-module/usb_midi/PortIn.h
@@ -3,7 +3,7 @@
*
* The MIT License (MIT)
*
- * Copyright (c) 2018 Artur Pacholec
+ * Copyright (c) 2018 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
@@ -24,16 +24,16 @@
* THE SOFTWARE.
*/
-#ifndef MICROPY_INCLUDED_SHARED_MODULE_BLEIO_SCANNER_H
-#define MICROPY_INCLUDED_SHARED_MODULE_BLEIO_SCANNER_H
+#ifndef SHARED_MODULE_USB_MIDI_PORTIN_H
+#define SHARED_MODULE_USB_MIDI_PORTIN_H
+
+#include <stdint.h>
+#include <stdbool.h>
#include "py/obj.h"
-typedef struct {
+typedef struct {
mp_obj_base_t base;
- mp_obj_t adv_reports;
- uint16_t interval;
- uint16_t window;
-} bleio_scanner_obj_t;
+} usb_midi_portin_obj_t;
-#endif // MICROPY_INCLUDED_SHARED_MODULE_BLEIO_SCANNER_H
+#endif /* SHARED_MODULE_USB_MIDI_PORTIN_H */
diff --git a/shared-module/usb_midi/PortOut.c b/shared-module/usb_midi/PortOut.c
new file mode 100644
index 000000000..0b37dcfd4
--- /dev/null
+++ b/shared-module/usb_midi/PortOut.c
@@ -0,0 +1,37 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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 "shared-module/usb_midi/PortOut.h"
+#include "supervisor/shared/translate.h"
+#include "tusb.h"
+
+size_t common_hal_usb_midi_portout_write(usb_midi_portout_obj_t *self, const uint8_t *data, size_t len, int *errcode) {
+ return tud_midi_write(0, data, len);
+}
+
+bool common_hal_usb_midi_portout_ready_to_tx(usb_midi_portout_obj_t *self) {
+ return tud_midi_mounted();
+}
diff --git a/shared-module/bleio/Device.h b/shared-module/usb_midi/PortOut.h
index 8d9ece5ef..6b1b88464 100644
--- a/shared-module/bleio/Device.h
+++ b/shared-module/usb_midi/PortOut.h
@@ -3,7 +3,7 @@
*
* The MIT License (MIT)
*
- * Copyright (c) 2018 Artur Pacholec
+ * Copyright (c) 2018 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
@@ -24,22 +24,16 @@
* THE SOFTWARE.
*/
-#ifndef MICROPY_INCLUDED_SHARED_MODULE_BLEIO_DEVICE_H
-#define MICROPY_INCLUDED_SHARED_MODULE_BLEIO_DEVICE_H
+#ifndef SHARED_MODULE_USB_MIDI_PORTOUT_H
+#define SHARED_MODULE_USB_MIDI_PORTOUT_H
+#include <stdint.h>
#include <stdbool.h>
-#include "shared-module/bleio/Address.h"
+#include "py/obj.h"
-typedef struct {
+typedef struct {
mp_obj_base_t base;
- bool is_peripheral;
- mp_obj_t name;
- bleio_address_obj_t address;
- volatile uint16_t conn_handle;
- mp_obj_t service_list;
- mp_obj_t notif_handler;
- mp_obj_t conn_handler;
-} bleio_device_obj_t;
+} usb_midi_portout_obj_t;
-#endif // MICROPY_INCLUDED_SHARED_MODULE_BLEIO_DEVICE_H
+#endif /* SHARED_MODULE_USB_MIDI_PORTOUT_H */
diff --git a/shared-module/usb_midi/__init__.c b/shared-module/usb_midi/__init__.c
new file mode 100644
index 000000000..73a314b99
--- /dev/null
+++ b/shared-module/usb_midi/__init__.c
@@ -0,0 +1,63 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 hathach 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 "shared-bindings/usb_midi/__init__.h"
+
+#include "genhdr/autogen_usb_descriptor.h"
+#include "py/obj.h"
+#include "py/mphal.h"
+#include "py/runtime.h"
+#include "py/objtuple.h"
+#include "shared-bindings/usb_midi/PortIn.h"
+#include "shared-bindings/usb_midi/PortOut.h"
+#include "supervisor/memory.h"
+#include "tusb.h"
+
+supervisor_allocation* usb_midi_allocation;
+
+void usb_midi_init(void) {
+ // TODO(tannewt): Make this dynamic.
+ uint16_t tuple_size = align32_size(sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t*) * 2);
+ uint16_t portin_size = align32_size(sizeof(usb_midi_portin_obj_t));
+ uint16_t portout_size = align32_size(sizeof(usb_midi_portout_obj_t));
+
+ // For each embedded MIDI Jack in the descriptor we create a Port
+ usb_midi_allocation = allocate_memory(tuple_size + portin_size + portout_size, false);
+
+ mp_obj_tuple_t *ports = (mp_obj_tuple_t *) usb_midi_allocation->ptr;
+ ports->base.type = &mp_type_tuple;
+ ports->len = 2;
+
+ usb_midi_portin_obj_t* in = (usb_midi_portin_obj_t *) (usb_midi_allocation->ptr + tuple_size / 4);
+ in->base.type = &usb_midi_portin_type;
+ ports->items[0] = MP_OBJ_FROM_PTR(in);
+
+ usb_midi_portout_obj_t* out = (usb_midi_portout_obj_t *) (usb_midi_allocation->ptr + tuple_size / 4 + portin_size / 4);
+ out->base.type = &usb_midi_portout_type;
+ ports->items[1] = MP_OBJ_FROM_PTR(out);
+
+ mp_map_lookup(&usb_midi_module_globals.map, MP_ROM_QSTR(MP_QSTR_ports), MP_MAP_LOOKUP)->value = MP_OBJ_FROM_PTR(ports);
+}
diff --git a/shared-module/usb_midi/__init__.h b/shared-module/usb_midi/__init__.h
new file mode 100644
index 000000000..e1ad1fbaf
--- /dev/null
+++ b/shared-module/usb_midi/__init__.h
@@ -0,0 +1,32 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 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 SHARED_MODULE_USB_MIDI___INIT___H
+#define SHARED_MODULE_USB_MIDI___INIT___H
+
+void usb_midi_init(void);
+
+#endif /* SHARED_MODULE_USB_MIDI___INIT___H */
diff --git a/shared-module/ustack/__init__.c b/shared-module/ustack/__init__.c
index 947f81f8e..1e168ad6a 100644
--- a/shared-module/ustack/__init__.c
+++ b/shared-module/ustack/__init__.c
@@ -49,4 +49,3 @@ uint32_t shared_module_ustack_stack_size() {
uint32_t shared_module_ustack_stack_usage() {
return mp_stack_usage();
}
-
diff --git a/shared-module/vectorio/Circle.c b/shared-module/vectorio/Circle.c
new file mode 100644
index 000000000..73629b8ce
--- /dev/null
+++ b/shared-module/vectorio/Circle.c
@@ -0,0 +1,55 @@
+
+#include "shared-bindings/vectorio/Circle.h"
+#include "shared-module/vectorio/__init__.h"
+#include "shared-module/displayio/area.h"
+
+#include "py/runtime.h"
+#include "stdlib.h"
+
+
+void common_hal_vectorio_circle_construct(vectorio_circle_t *self, uint16_t radius) {
+ self->radius = radius;
+ self->on_dirty.obj = NULL;
+}
+
+void common_hal_vectorio_circle_set_on_dirty(vectorio_circle_t *self, vectorio_event_t on_dirty) {
+ if (self->on_dirty.obj != NULL) {
+ mp_raise_TypeError(translate("circle can only be registered in one parent"));
+ }
+ self->on_dirty = on_dirty;
+}
+
+
+uint32_t common_hal_vectorio_circle_get_pixel(void *obj, int16_t x, int16_t y) {
+ vectorio_circle_t *self = obj;
+ int16_t radius = abs(self->radius);
+ x = abs(x);
+ y = abs(y);
+ if (x+y <= radius) return 1;
+ if (x > radius) return 0;
+ if (y > radius) return 0;
+ const bool pythagorasSmallerThanRadius = (int32_t)x*x + (int32_t)y*y <= (int32_t)radius*radius;
+ return pythagorasSmallerThanRadius ? 1 : 0;
+}
+
+
+void common_hal_vectorio_circle_get_area(void *circle, displayio_area_t *out_area) {
+ vectorio_circle_t *self = circle;
+ out_area->x1 = -1 * self->radius - 1;
+ out_area->y1 = -1 * self->radius - 1;
+ out_area->x2 = self->radius + 1;
+ out_area->y2 = self->radius + 1;
+}
+
+int16_t common_hal_vectorio_circle_get_radius(void *obj) {
+ vectorio_circle_t *self = obj;
+ return self->radius;
+}
+
+void common_hal_vectorio_circle_set_radius(void *obj, int16_t radius) {
+ vectorio_circle_t *self = obj;
+ self->radius = abs(radius);
+ if (self->on_dirty.obj != NULL) {
+ self->on_dirty.event(self->on_dirty.obj);
+ }
+}
diff --git a/shared-module/vectorio/Circle.h b/shared-module/vectorio/Circle.h
new file mode 100644
index 000000000..d6a77b166
--- /dev/null
+++ b/shared-module/vectorio/Circle.h
@@ -0,0 +1,16 @@
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_CIRCLE_H
+#define MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_CIRCLE_H
+
+#include <stdint.h>
+
+#include "py/obj.h"
+
+#include "shared-module/vectorio/__init__.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ uint16_t radius;
+ vectorio_event_t on_dirty;
+} vectorio_circle_t;
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_CIRCLE_H
diff --git a/shared-module/vectorio/Polygon.c b/shared-module/vectorio/Polygon.c
new file mode 100644
index 000000000..0025d4bfc
--- /dev/null
+++ b/shared-module/vectorio/Polygon.c
@@ -0,0 +1,146 @@
+
+#include "shared-module/vectorio/__init__.h"
+#include "shared-bindings/vectorio/Polygon.h"
+#include "shared-module/displayio/area.h"
+
+#include "py/runtime.h"
+#include "py/gc.h"
+
+#include "stdlib.h"
+#include <stdio.h>
+
+
+#define VECTORIO_POLYGON_DEBUG(...) (void)0
+// #define VECTORIO_POLYGON_DEBUG(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__)
+
+
+// Converts a list of points tuples to a flat list of ints for speedier internal use.
+// Also validates the points.
+static void _clobber_points_list(vectorio_polygon_t *self, mp_obj_t points_tuple_list) {
+ size_t len = 0;
+ mp_obj_t *items;
+ mp_obj_list_get(points_tuple_list, &len, &items);
+ VECTORIO_POLYGON_DEBUG("polygon_points_list len: %d\n", len);
+
+ if ( len < 3 ) {
+ mp_raise_TypeError_varg(translate("Polygon needs at least 3 points"));
+ }
+
+ if ( self->len < 2*len ) {
+ if ( self->points_list != NULL ) {
+ gc_free( self->points_list );
+ }
+ self->points_list = gc_alloc( 2 * len * sizeof(int), false, false );
+ }
+ self->len = 2*len;
+
+ for ( size_t i = 0; i < len; ++i) {
+ size_t tuple_len = 0;
+ mp_obj_t *tuple_items;
+ mp_obj_tuple_get(items[i], &tuple_len, &tuple_items);
+
+ if (tuple_len != 2) {
+ mp_raise_ValueError_varg(translate("%q must be a tuple of length 2"), MP_QSTR_point);
+ }
+ if ( !mp_obj_get_int_maybe(tuple_items[ 0 ], &self->points_list[2*i ])
+ || !mp_obj_get_int_maybe(tuple_items[ 1 ], &self->points_list[2*i + 1])
+ ) {
+ self->len = 0;
+ gc_free( self->points_list );
+ self->points_list = NULL;
+ mp_raise_ValueError_varg(translate("unsupported %q type"), MP_QSTR_point);
+ }
+ }
+}
+
+
+
+void common_hal_vectorio_polygon_construct(vectorio_polygon_t *self, mp_obj_t points_list) {
+ VECTORIO_POLYGON_DEBUG("%p polygon_construct\n", self);
+ self->points_list = NULL;
+ self->len = 0;
+ self->on_dirty.obj = NULL;
+ _clobber_points_list( self, points_list );
+}
+
+
+mp_obj_t common_hal_vectorio_polygon_get_points(vectorio_polygon_t *self) {
+ return self->points_list;
+}
+void common_hal_vectorio_polygon_set_points(vectorio_polygon_t *self, mp_obj_t points_list) {
+ _clobber_points_list( self, points_list );
+ if (self->on_dirty.obj != NULL) {
+ self->on_dirty.event(self->on_dirty.obj);
+ }
+}
+
+void common_hal_vectorio_polygon_set_on_dirty(vectorio_polygon_t *self, vectorio_event_t notification) {
+ if ( self->on_dirty.obj != NULL ) {
+ mp_raise_TypeError(translate("polygon can only be registered in one parent"));
+ }
+ self->on_dirty = notification;
+}
+
+
+void common_hal_vectorio_polygon_get_area(void *polygon, displayio_area_t *area) {
+ vectorio_polygon_t *self = polygon;
+
+ area->x1 = SHRT_MAX;
+ area->y1 = SHRT_MAX;
+ area->x2 = SHRT_MIN;
+ area->y2 = SHRT_MIN;
+ for (size_t i=0; i < self->len; ++i) {
+ int x = self->points_list[i];
+ ++i;
+ int y = self->points_list[i];
+ if (x <= area->x1) area->x1 = x-1;
+ if (y <= area->y1) area->y1 = y-1;
+ if (x >= area->x2) area->x2 = x+1;
+ if (y >= area->y2) area->y2 = y+1;
+ }
+}
+
+
+// <0 if the point is to the left of the line vector
+// 0 if the point is on the line
+// >0 if the point is to the right of the line vector
+__attribute__((always_inline)) static inline int line_side( mp_int_t x1, mp_int_t y1, mp_int_t x2, mp_int_t y2, int16_t px, int16_t py ) {
+ return (px - x1) * (y2 - y1)
+ - (py - y1) * (x2 - x1);
+}
+
+
+uint32_t common_hal_vectorio_polygon_get_pixel(void *obj, int16_t x, int16_t y) {
+ VECTORIO_POLYGON_DEBUG("%p polygon get_pixel %d, %d\n", obj, x, y);
+ vectorio_polygon_t *self = obj;
+
+ if (self->len == 0) {
+ return 0;
+ }
+
+ int winding_number = 0;
+ int x1 = self->points_list[0];
+ int y1 = self->points_list[1];
+ for (size_t i=2; i <= self->len + 1; ++i) {
+ VECTORIO_POLYGON_DEBUG(" {(%3d, %3d),", x1, y1);
+ int x2 = self->points_list[i % self->len];
+ ++i;
+ int y2 = self->points_list[i % self->len];
+ VECTORIO_POLYGON_DEBUG(" (%3d, %3d)}\n", x2, y2);
+ if ( y1 <= y ) {
+ if ( y2 > y && line_side(x1, y1, x2, y2, x, y) > 0 ) {
+ // Wind up, point is to the right of the edge vector
+ ++winding_number;
+ VECTORIO_POLYGON_DEBUG(" wind:%2d winding_number:%2d\n", 1, winding_number);
+ }
+ } else if ( y2 <= y && line_side(x1, y1, x2, y2, x, y) < 0 ) {
+ // Wind down, point is to the left of the edge vector
+ --winding_number;
+ VECTORIO_POLYGON_DEBUG(" wind:%2d winding_number:%2d\n", -1, winding_number);
+ }
+
+ x1 = x2;
+ y1 = y2;
+ }
+ return winding_number == 0 ? 0 : 1;
+}
diff --git a/shared-module/vectorio/Polygon.h b/shared-module/vectorio/Polygon.h
new file mode 100644
index 000000000..70de9036d
--- /dev/null
+++ b/shared-module/vectorio/Polygon.h
@@ -0,0 +1,17 @@
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_POLYGON_H
+#define MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_POLYGON_H
+
+#include <stdint.h>
+
+#include "py/obj.h"
+#include "shared-module/vectorio/__init__.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ // An int array[ x, y, ... ]
+ int *points_list;
+ size_t len;
+ vectorio_event_t on_dirty;
+} vectorio_polygon_t;
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_POLYGON_H
diff --git a/shared-module/vectorio/Rectangle.c b/shared-module/vectorio/Rectangle.c
new file mode 100644
index 000000000..5d48cc648
--- /dev/null
+++ b/shared-module/vectorio/Rectangle.c
@@ -0,0 +1,34 @@
+#include "shared-bindings/vectorio/Rectangle.h"
+#include "shared-module/displayio/area.h"
+
+#include "py/runtime.h"
+
+
+void common_hal_vectorio_rectangle_construct(vectorio_rectangle_t *self, uint32_t width, uint32_t height) {
+ self->width = width;
+ self->height = height;
+}
+
+
+uint32_t common_hal_vectorio_rectangle_get_pixel(void *obj, int16_t x, int16_t y) {
+ vectorio_rectangle_t *self = obj;
+ if (x < 0 || x > self->width || y > self->height || y < 0) {
+ return 0;
+ }
+ return 1;
+}
+
+
+void common_hal_vectorio_rectangle_get_area(void *rectangle, displayio_area_t *out_area) {
+ vectorio_rectangle_t *self = rectangle;
+ out_area->x1 = -1;
+ out_area->y1 = -1;
+ out_area->x2 = self->width;
+ out_area->y2 = self->height;
+}
+
+
+uint32_t common_hal_vectorio_rectangle_get_height(void *rectangle) {
+ vectorio_rectangle_t *self = rectangle;
+ return self->height;
+}
diff --git a/shared-module/vectorio/Rectangle.h b/shared-module/vectorio/Rectangle.h
new file mode 100644
index 000000000..56342a6d7
--- /dev/null
+++ b/shared-module/vectorio/Rectangle.h
@@ -0,0 +1,14 @@
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_RECTANGLE_H
+#define MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_RECTANGLE_H
+
+#include <stdint.h>
+
+#include "py/obj.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ uint16_t width;
+ uint16_t height;
+} vectorio_rectangle_t;
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_RECTANGLE_H
diff --git a/shared-module/vectorio/VectorShape.c b/shared-module/vectorio/VectorShape.c
new file mode 100644
index 000000000..bfe8a7b25
--- /dev/null
+++ b/shared-module/vectorio/VectorShape.c
@@ -0,0 +1,334 @@
+
+#include "stdlib.h"
+
+#include "shared-module/vectorio/__init__.h"
+#include "shared-bindings/vectorio/VectorShape.h"
+
+#include "py/runtime.h"
+#include "shared-bindings/time/__init__.h"
+#include "shared-bindings/displayio/ColorConverter.h"
+#include "shared-bindings/displayio/Palette.h"
+
+#include "shared-bindings/vectorio/Circle.h"
+#include "shared-bindings/vectorio/Polygon.h"
+#include "shared-bindings/vectorio/Rectangle.h"
+
+// Lifecycle actions.
+#define VECTORIO_SHAPE_DEBUG(...) (void)0
+// #define VECTORIO_SHAPE_DEBUG(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__)
+
+
+// Used in both logging and ifdefs, for extra variables
+// #define VECTORIO_PERF(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__)
+
+
+// Really verbose.
+#define VECTORIO_SHAPE_PIXEL_DEBUG(...) (void)0
+// #define VECTORIO_SHAPE_PIXEL_DEBUG(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__)
+
+
+inline __attribute__((always_inline))
+static int32_t max(int32_t a, int32_t b) {
+ return a > b ? a : b;
+}
+
+
+inline __attribute__((always_inline))
+static void _get_screen_area(vectorio_vector_shape_t *self, displayio_area_t *out_area) {
+ VECTORIO_SHAPE_DEBUG("%p get_screen_area tform:{x:%d y:%d dx:%d dy:%d scl:%d w:%d h:%d mx:%d my:%d tr:%d}", self,
+ self->absolute_transform->x, self->absolute_transform->y, self->absolute_transform->dx, self->absolute_transform->dy, self->absolute_transform->scale,
+ self->absolute_transform->width, self->absolute_transform->height, self->absolute_transform->mirror_x, self->absolute_transform->mirror_y, self->absolute_transform->transpose_xy
+ );
+ self->ishape.get_area(self->ishape.shape, out_area);
+ VECTORIO_SHAPE_DEBUG(" in:{(%5d,%5d), (%5d,%5d)}", out_area->x1, out_area->y1, out_area->x2, out_area->y2);
+ if (self->absolute_transform->transpose_xy) {
+ int16_t swap = out_area->x1;
+ out_area->x1 = (out_area->y1 + self->y) * self->absolute_transform->dx + self->absolute_transform->x;
+ out_area->y1 = (swap + self->x) * self->absolute_transform->dy + self->absolute_transform->y;
+ swap = out_area->x2;
+ out_area->x2 = (out_area->y2 + self->y) * self->absolute_transform->dx + self->absolute_transform->x;
+ out_area->y2 = (swap + self->x) * self->absolute_transform->dy + self->absolute_transform->y;
+ } else {
+ out_area->x1 = (out_area->x1 + self->x) * self->absolute_transform->dx + self->absolute_transform->x;
+ out_area->y1 = (out_area->y1 + self->y) * self->absolute_transform->dy + self->absolute_transform->y;
+ out_area->x2 = (out_area->x2 + self->x) * self->absolute_transform->dx + self->absolute_transform->x;
+ out_area->y2 = (out_area->y2 + self->y) * self->absolute_transform->dy + self->absolute_transform->y;
+ }
+ // We might have mirrored due to dx
+ if (out_area->x2 < out_area->x1) {
+ int16_t swap = out_area->x1;
+ out_area->x1 = out_area->x2;
+ out_area->x2 = swap;
+ }
+ if (out_area->y2 < out_area->y1) {
+ int16_t swap = out_area->y1;
+ out_area->y1 = out_area->y2;
+ out_area->y2 = swap;
+ }
+ VECTORIO_SHAPE_DEBUG(" out:{(%5d,%5d), (%5d,%5d)}\n", out_area->x1, out_area->y1, out_area->x2, out_area->y2);
+}
+
+
+// For use by Group to know where it needs to redraw on layer removal.
+bool vectorio_vector_shape_get_dirty_area(vectorio_vector_shape_t *self, displayio_area_t *out_area) {
+ displayio_area_copy(&self->ephemeral_dirty_area, out_area);
+ return true; // For now just always redraw.
+}
+
+
+// This must be invoked each time a shape changes its position or its shape in any way.
+void common_hal_vectorio_vector_shape_set_dirty(void *vector_shape) {
+ vectorio_vector_shape_t *self = vector_shape;
+ // In screen space. Need to offset the shape space.
+ displayio_area_t current_area;
+ _get_screen_area(self, &current_area);
+ VECTORIO_SHAPE_DEBUG("%p shape_dirty current:{(%3d,%3d), (%3d,%3d)} dirty:{(%3d,%3d), (%3d,%3d)}",
+ self,
+ current_area.x1, current_area.y1, current_area.x2, current_area.y2,
+ self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2);
+ self->dirty = true;
+ // Dirty area tracks the shape's footprint between draws. It's reset on refresh finish,
+ displayio_area_expand(&self->ephemeral_dirty_area, &current_area);
+ VECTORIO_SHAPE_DEBUG(" -> expanded:{(%3d,%3d), (%3d,%3d)}\n", self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2);
+}
+
+
+static displayio_buffer_transform_t null_transform = {
+ .x = 0,
+ .y = 0,
+ .dx = 1,
+ .dy = 1,
+ .scale = 1,
+ .width = 0,
+ .height = 0,
+ .mirror_x = false,
+ .mirror_y = false,
+ .transpose_xy = false
+};
+
+
+void common_hal_vectorio_vector_shape_construct(vectorio_vector_shape_t *self,
+ vectorio_ishape_t ishape,
+ mp_obj_t pixel_shader, uint16_t x, uint16_t y) {
+ VECTORIO_SHAPE_DEBUG("%p vector_shape_construct x:%3d, y:%3d\n", self, x, y);
+ self->x = x;
+ self->y = y;
+ self->pixel_shader = pixel_shader;
+ self->ishape = ishape;
+ self->dirty = true;
+ self->absolute_transform = &null_transform; // Critical to have a valid transform before getting screen area.
+ _get_screen_area(self, &self->ephemeral_dirty_area);
+ self->ephemeral_dirty_area.next = NULL;
+}
+
+
+mp_int_t common_hal_vectorio_vector_shape_get_x(vectorio_vector_shape_t *self) {
+ VECTORIO_SHAPE_DEBUG("%p get_x\n", self);
+ return self->x;
+}
+
+
+void common_hal_vectorio_vector_shape_set_x(vectorio_vector_shape_t *self, mp_int_t x) {
+ VECTORIO_SHAPE_DEBUG("%p set_x %d\n", self, x);
+ if (self->x == x) {
+ return;
+ }
+ self->x = x;
+ common_hal_vectorio_vector_shape_set_dirty(self);
+}
+
+
+mp_int_t common_hal_vectorio_vector_shape_get_y(vectorio_vector_shape_t *self) {
+ VECTORIO_SHAPE_DEBUG("%p get_y\n", self);
+ return self->y;
+}
+
+
+void common_hal_vectorio_vector_shape_set_y(vectorio_vector_shape_t *self, mp_int_t y) {
+ VECTORIO_SHAPE_DEBUG("%p set_y %d\n", self, y);
+ if (self->y == y) {
+ return;
+ }
+ self->y = y;
+ common_hal_vectorio_vector_shape_set_dirty(self);
+}
+
+
+mp_obj_t common_hal_vectorio_vector_shape_get_pixel_shader(vectorio_vector_shape_t *self) {
+ VECTORIO_SHAPE_DEBUG("%p get_pixel_shader\n", self);
+ return self->pixel_shader;
+}
+
+void common_hal_vectorio_vector_shape_set_pixel_shader(vectorio_vector_shape_t *self, mp_obj_t pixel_shader) {
+ VECTORIO_SHAPE_DEBUG("%p set_pixel_shader\n", self);
+ self->pixel_shader = pixel_shader;
+ common_hal_vectorio_vector_shape_set_dirty(self);
+}
+
+
+bool vectorio_vector_shape_fill_area(vectorio_vector_shape_t *self, const _displayio_colorspace_t* colorspace, const displayio_area_t* area, uint32_t* mask, uint32_t *buffer) {
+ // Shape areas are relative to 0,0. This will allow rotation about a known axis.
+ // The consequence is that the area reported by the shape itself is _relative_ to 0,0.
+ // To make it relative to the VectorShape position, we must shift it.
+ // Pixels are drawn on the screen_area (shifted) coordinate space, while pixels are _determined_ from
+ // the shape_area (unshifted) space.
+#ifdef VECTORIO_PERF
+ uint64_t start = common_hal_time_monotonic_ns();
+ uint64_t pixel_time = 0;
+#endif
+ displayio_area_t overlap;
+ VECTORIO_SHAPE_DEBUG("%p fill_area dirty:%d fill: {(%5d,%5d), (%5d,%5d)} dirty: {(%5d,%5d), (%5d,%5d)}",
+ self, self->dirty,
+ area->x1, area->y1, area->x2, area->y2,
+ self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2
+ );
+ if (!displayio_area_compute_overlap(area, &self->ephemeral_dirty_area, &overlap)) {
+ VECTORIO_SHAPE_DEBUG(" no overlap\n");
+ return false;
+ }
+ VECTORIO_SHAPE_DEBUG(", overlap: {(%3d,%3d), (%3d,%3d)}", overlap.x1, overlap.y1, overlap.x2, overlap.y2);
+
+ bool full_coverage = displayio_area_equal(area, &overlap);
+
+ uint8_t pixels_per_byte = 8 / colorspace->depth;
+
+ uint32_t linestride_px = displayio_area_width(area);
+ uint32_t line_dirty_offset_px = (overlap.y1 - area->y1) * linestride_px;
+ uint32_t column_dirty_offset_px = overlap.x1 - area->x1;
+ VECTORIO_SHAPE_DEBUG(", linestride:%3d line_offset:%3d col_offset:%3d depth:%2d ppb:%2d shape:%s",
+ linestride_px, line_dirty_offset_px, column_dirty_offset_px, colorspace->depth, pixels_per_byte, mp_obj_get_type_str(self->ishape.shape));
+
+ displayio_input_pixel_t input_pixel;
+ displayio_output_pixel_t output_pixel;
+
+ uint32_t mask_start_px = line_dirty_offset_px;
+ for (input_pixel.y = overlap.y1; input_pixel.y < overlap.y2; ++input_pixel.y) {
+ mask_start_px += column_dirty_offset_px;
+ for (input_pixel.x = overlap.x1; input_pixel.x < overlap.x2; ++input_pixel.x) {
+ // Check the mask first to see if the pixel has already been set.
+ uint32_t pixel_index = mask_start_px + (input_pixel.x - overlap.x1);
+ uint32_t *mask_doubleword = &(mask[pixel_index / 32]);
+ uint8_t mask_bit = pixel_index % 32;
+ VECTORIO_SHAPE_PIXEL_DEBUG("%p pixel_index: %5u mask_bit: %2u", self, pixel_index, mask_bit);
+ if ((*mask_doubleword & (1u << mask_bit)) != 0) {
+ VECTORIO_SHAPE_PIXEL_DEBUG(" masked\n");
+ continue;
+ }
+ output_pixel.pixel = 0;
+
+ // Get the target pixel based on the shape's coordinate space
+ int16_t pixel_to_get_x;
+ int16_t pixel_to_get_y;
+ if (self->absolute_transform->transpose_xy) {
+ pixel_to_get_x = (input_pixel.y - self->absolute_transform->dy * self->x - self->absolute_transform->y) / self->absolute_transform->dy;
+ pixel_to_get_y = (input_pixel.x - self->absolute_transform->dx * self->y - self->absolute_transform->x) / self->absolute_transform->dx;
+ } else {
+ pixel_to_get_x = (input_pixel.x - self->absolute_transform->dx * self->x) / self->absolute_transform->dx;
+ pixel_to_get_y = (input_pixel.y - self->absolute_transform->dy * self->y) / self->absolute_transform->dy;
+ }
+ VECTORIO_SHAPE_PIXEL_DEBUG(" get_pixel %p (%3d, %3d) -> ( %3d, %3d )", self->ishape.shape, input_pixel.x, input_pixel.y, pixel_to_get_x, pixel_to_get_y);
+#ifdef VECTORIO_PERF
+ uint64_t pre_pixel = common_hal_time_monotonic_ns();
+#endif
+ input_pixel.pixel = self->ishape.get_pixel(self->ishape.shape, pixel_to_get_x, pixel_to_get_y);
+#ifdef VECTORIO_PERF
+ uint64_t post_pixel = common_hal_time_monotonic_ns();
+ pixel_time += post_pixel - pre_pixel;
+#endif
+ VECTORIO_SHAPE_PIXEL_DEBUG(" -> %d", input_pixel.pixel);
+
+ output_pixel.opaque = true;
+ if (self->pixel_shader == mp_const_none) {
+ output_pixel.pixel = input_pixel.pixel;
+ } else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type)) {
+ output_pixel.opaque = displayio_palette_get_color(self->pixel_shader, colorspace, input_pixel.pixel, &output_pixel.pixel);
+ } else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type)) {
+ displayio_colorconverter_convert(self->pixel_shader, colorspace, &input_pixel, &output_pixel);
+ }
+ if (!output_pixel.opaque) {
+ VECTORIO_SHAPE_PIXEL_DEBUG(" (encountered transparent pixel; input area is not fully covered)\n");
+ full_coverage = false;
+ } else {
+ *mask_doubleword |= 1u << mask_bit;
+ if (colorspace->depth == 16) {
+ VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %04x 16\n", output_pixel.pixel);
+ *(((uint16_t*) buffer) + pixel_index) = output_pixel.pixel;
+ } else if (colorspace->depth == 8) {
+ VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %02x 8\n", output_pixel.pixel);
+ *(((uint8_t*) buffer) + pixel_index) = output_pixel.pixel;
+ } else if (colorspace->depth < 8) {
+ // Reorder the offsets to pack multiple rows into a byte (meaning they share a column).
+ if (!colorspace->pixels_in_byte_share_row) {
+ uint16_t width = linestride_px;
+ uint16_t row = pixel_index / width;
+ uint16_t col = pixel_index % width;
+ pixel_index = col * pixels_per_byte + (row / pixels_per_byte) * pixels_per_byte * width + row % pixels_per_byte;
+ }
+ uint8_t shift = (pixel_index % pixels_per_byte) * colorspace->depth;
+ if (colorspace->reverse_pixels_in_byte) {
+ // Reverse the shift by subtracting it from the leftmost shift.
+ shift = (pixels_per_byte - 1) * colorspace->depth - shift;
+ }
+ VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %2d %d\n", output_pixel.pixel, colorspace->depth);
+ ((uint8_t*)buffer)[pixel_index / pixels_per_byte] |= output_pixel.pixel << shift;
+ }
+ }
+ }
+ mask_start_px += linestride_px - column_dirty_offset_px;
+ }
+#ifdef VECTORIO_PERF
+ uint64_t end = common_hal_time_monotonic_ns();
+ uint32_t pixels = (overlap.x2 - overlap.x1) * (overlap.y2 - overlap.y1);
+ VECTORIO_PERF("draw %16s -> shape:{%4dpx, %4.1fms,%9.1fpps fill} shape_pixels:{%6.1fus total, %4.1fus/px}\n",
+ mp_obj_get_type_str(self->ishape.shape),
+ (overlap.x2 - overlap.x1) * (overlap.y2 - overlap.y1),
+ (double)((end - start) / 1000000.0),
+ (double)(max(1, pixels * (1000000000.0 / (end - start)))),
+ (double)(pixel_time / 1000.0),
+ (double)(pixel_time / 1000.0 / pixels)
+ );
+#endif
+ VECTORIO_SHAPE_DEBUG(" -> pixels:%4d\n");
+ return full_coverage;
+}
+
+
+void vectorio_vector_shape_finish_refresh(vectorio_vector_shape_t *self) {
+ if ( !self->dirty ) {
+ return;
+ }
+ VECTORIO_SHAPE_DEBUG("%p finish_refresh was:{(%3d,%3d), (%3d,%3d)}\n", self, self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2);
+ self->dirty = false;
+ // Reset dirty area tracking to current footprint
+ _get_screen_area(self, &self->ephemeral_dirty_area);
+ self->ephemeral_dirty_area.next = NULL;
+ VECTORIO_SHAPE_DEBUG("%p finish_refresh now:{(%3d,%3d), (%3d,%3d)}\n", self, self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2);
+
+ if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type)) {
+ displayio_palette_finish_refresh(self->pixel_shader);
+ } else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type)) {
+ displayio_colorconverter_finish_refresh(self->pixel_shader);
+ }
+}
+
+
+// Assembles a singly linked list of dirty areas from all components on the display.
+displayio_area_t* vectorio_vector_shape_get_refresh_areas(vectorio_vector_shape_t *self, displayio_area_t* tail) {
+ if (self->dirty
+ || (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type) && displayio_palette_needs_refresh(self->pixel_shader))
+ || (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type) && displayio_colorconverter_needs_refresh(self->pixel_shader))
+ ) {
+ VECTORIO_SHAPE_DEBUG("%p get_refresh_area dirty:%d {(%3d,%3d), (%3d,%3d)}", self, self->dirty, self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2);
+ common_hal_vectorio_vector_shape_set_dirty(self);
+ // vector.add_to_head
+ self->ephemeral_dirty_area.next = tail;
+ VECTORIO_SHAPE_DEBUG(" this_area: %p next: %p after: %p\n", &self->ephemeral_dirty_area, tail, tail == NULL ? NULL : tail->next);
+ return &self->ephemeral_dirty_area;
+ }
+ return tail;
+}
+
+void vectorio_vector_shape_update_transform(vectorio_vector_shape_t *self, displayio_buffer_transform_t *group_transform) {
+ self->absolute_transform = group_transform == NULL ? &null_transform : group_transform;
+ common_hal_vectorio_vector_shape_set_dirty(self);
+}
diff --git a/shared-module/vectorio/VectorShape.h b/shared-module/vectorio/VectorShape.h
new file mode 100644
index 000000000..56eb3d8a5
--- /dev/null
+++ b/shared-module/vectorio/VectorShape.h
@@ -0,0 +1,53 @@
+
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_SHAPE_H
+#define MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_SHAPE_H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "py/obj.h"
+#include "shared-module/displayio/area.h"
+#include "shared-module/displayio/Palette.h"
+
+typedef void get_area_function(mp_obj_t shape, displayio_area_t *out_area);
+typedef uint32_t get_pixel_function(mp_obj_t shape, int16_t x, int16_t y);
+
+// This struct binds a shape's common Shape support functions (its vector shape interface)
+// to its instance pointer. We only check at construction time what the type of the
+// associated shape is and link the correct functions up.
+// Later when using the shape for drawing logic these functions may be invoked
+// unconditionally. This simplifies the addition of new types and restricts the
+// respective responsibilities of VectorShape and actual shape implementations.
+typedef struct {
+ mp_obj_t shape;
+ get_area_function *get_area;
+ get_pixel_function *get_pixel;
+} vectorio_ishape_t;
+
+typedef struct {
+ mp_obj_base_t base;
+ vectorio_ishape_t ishape;
+ mp_obj_t pixel_shader;
+ int16_t x;
+ int16_t y;
+ displayio_buffer_transform_t *absolute_transform;
+ bool dirty; // True if we need to draw
+ // Tracks current shape footprint and expands outward as the shape dirties and changes.
+ // This is suboptimal if you move your shape far. Could add more state to only redraw
+ // exactly what we left behind.
+ displayio_area_t ephemeral_dirty_area;
+} vectorio_vector_shape_t;
+
+displayio_area_t* vectorio_vector_shape_get_refresh_areas(vectorio_vector_shape_t *self, displayio_area_t *tail);
+
+bool vectorio_vector_shape_get_dirty_area(vectorio_vector_shape_t *self, displayio_area_t *current_dirty_area);
+
+// Area is always in absolute screen coordinates.
+bool vectorio_vector_shape_fill_area(vectorio_vector_shape_t *self, const _displayio_colorspace_t *colorspace, const displayio_area_t *area, uint32_t *mask, uint32_t *buffer);
+
+// Fills in out_area with the maximum bounds of all related pixels in the last rendered frame. Returns
+// false if the vector shape wasn't rendered in the last frame.
+bool vectorio_vector_shape_get_previous_area(vectorio_vector_shape_t *self, displayio_area_t *out_area);
+void vectorio_vector_shape_finish_refresh(vectorio_vector_shape_t *self);
+
+#endif // MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_SHAPE_H
diff --git a/shared-module/vectorio/__init__.c b/shared-module/vectorio/__init__.c
new file mode 100644
index 000000000..f5227ef01
--- /dev/null
+++ b/shared-module/vectorio/__init__.c
@@ -0,0 +1,2 @@
+
+// Don't need anything in here yet
diff --git a/shared-module/vectorio/__init__.h b/shared-module/vectorio/__init__.h
new file mode 100644
index 000000000..8da85bba4
--- /dev/null
+++ b/shared-module/vectorio/__init__.h
@@ -0,0 +1,14 @@
+#ifndef MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_INIT_H
+#define MICROPY_INCLUDED_SHARED_MODULE_VECTORIO_INIT_H
+
+#include "py/obj.h"
+
+typedef void event_function(mp_obj_t obj);
+
+typedef struct {
+ mp_obj_t obj;
+ event_function *event;
+} vectorio_event_t;
+
+
+#endif
diff --git a/shared-module/wiznet/wiznet5k.c b/shared-module/wiznet/wiznet5k.c
index ee732859a..a603a5593 100644
--- a/shared-module/wiznet/wiznet5k.c
+++ b/shared-module/wiznet/wiznet5k.c
@@ -93,6 +93,16 @@ int wiznet5k_gethostbyname(mp_obj_t nic, const char *name, mp_uint_t len, uint8_
}
}
+int get_available_socket(wiznet5k_obj_t *wiz) {
+ for (uint8_t sn = 0; sn < _WIZCHIP_SOCK_NUM_; sn++) {
+ if ((wiz->socket_used & (1 << sn)) == 0) {
+ wiz->socket_used |= (1 << sn);
+ return sn;
+ }
+ }
+ return -1;
+}
+
int wiznet5k_socket_socket(mod_network_socket_obj_t *socket, int *_errno) {
if (socket->u_param.domain != MOD_NETWORK_AF_INET) {
*_errno = MP_EAFNOSUPPORT;
@@ -107,13 +117,7 @@ int wiznet5k_socket_socket(mod_network_socket_obj_t *socket, int *_errno) {
if (socket->u_param.fileno == -1) {
// get first unused socket number
- for (mp_uint_t sn = 0; sn < _WIZCHIP_SOCK_NUM_; sn++) {
- if ((wiznet5k_obj.socket_used & (1 << sn)) == 0) {
- wiznet5k_obj.socket_used |= (1 << sn);
- socket->u_param.fileno = sn;
- break;
- }
- }
+ socket->u_param.fileno = get_available_socket(&wiznet5k_obj);
if (socket->u_param.fileno == -1) {
// too many open sockets
*_errno = MP_EMFILE;
@@ -199,8 +203,12 @@ int wiznet5k_socket_accept(mod_network_socket_obj_t *socket, mod_network_socket_
}
int wiznet5k_socket_connect(mod_network_socket_obj_t *socket, byte *ip, mp_uint_t port, int *_errno) {
+ uint16_t src_port = network_module_create_random_source_tcp_port();
+ // make sure same outgoing port number can't be in use by two different sockets.
+ src_port = (src_port & ~(_WIZCHIP_SOCK_NUM_ - 1)) | socket->u_param.fileno;
+
// use "bind" function to open the socket in client mode
- if (wiznet5k_socket_bind(socket, ip, 0, _errno) != 0) {
+ if (wiznet5k_socket_bind(socket, NULL, src_port, _errno) != 0) {
return -1;
}
@@ -318,45 +326,67 @@ int wiznet5k_socket_ioctl(mod_network_socket_obj_t *socket, mp_uint_t request, m
}
void wiznet5k_socket_timer_tick(mod_network_socket_obj_t *socket) {
- if (wiznet5k_obj.dhcp_active) {
+ if (wiznet5k_obj.dhcp_socket >= 0) {
DHCP_time_handler();
DHCP_run();
}
}
-void wiznet5k_start_dhcp(void) {
+int wiznet5k_start_dhcp(void) {
+ // XXX this should throw an error if DHCP fails
static DHCP_INIT_BUFFER_TYPE dhcp_buf[DHCP_INIT_BUFFER_SIZE];
- if (!wiznet5k_obj.dhcp_active) {
+ if (wiznet5k_obj.dhcp_socket < 0) {
// Set up the socket to listen on UDP 68 before calling DHCP_init
- WIZCHIP_EXPORT(socket)(0, MOD_NETWORK_SOCK_DGRAM, DHCP_CLIENT_PORT, 0);
- DHCP_init(0, dhcp_buf);
- wiznet5k_obj.dhcp_active = 1;
+ wiznet5k_obj.dhcp_socket = get_available_socket(&wiznet5k_obj);
+ if (wiznet5k_obj.dhcp_socket < 0) return MP_EMFILE;
+
+ WIZCHIP_EXPORT(socket)(wiznet5k_obj.dhcp_socket, MOD_NETWORK_SOCK_DGRAM, DHCP_CLIENT_PORT, 0);
+ DHCP_init(wiznet5k_obj.dhcp_socket, dhcp_buf);
}
+ return 0;
}
-void wiznet5k_stop_dhcp(void) {
- if (wiznet5k_obj.dhcp_active) {
- wiznet5k_obj.dhcp_active = 0;
+int wiznet5k_stop_dhcp(void) {
+ if (wiznet5k_obj.dhcp_socket >= 0) {
DHCP_stop();
- WIZCHIP_EXPORT(close)(0);
+ WIZCHIP_EXPORT(close)(wiznet5k_obj.dhcp_socket);
+ wiznet5k_obj.socket_used &= ~(1 << wiznet5k_obj.dhcp_socket);
+ wiznet5k_obj.dhcp_socket = -1;
}
+ return 0;
}
bool wiznet5k_check_dhcp(void) {
- return wiznet5k_obj.dhcp_active;
+ return wiznet5k_obj.dhcp_socket >= 0;
+}
+
+void wiznet5k_reset(void) {
+ if (wiznet5k_obj.rst.pin) {
+ // hardware reset if using RST pin
+ common_hal_digitalio_digitalinout_set_value(&wiznet5k_obj.rst, 0);
+ mp_hal_delay_us(10); // datasheet says 2us
+ common_hal_digitalio_digitalinout_set_value(&wiznet5k_obj.rst, 1);
+ mp_hal_delay_ms(150); // datasheet says 150ms
+ } else {
+ // otherwise, software reset
+ wizchip_sw_reset();
+ }
+}
+
+void wiznet5k_socket_deinit(mod_network_socket_obj_t *socket) {
+ wiznet5k_reset();
}
/// Create and return a WIZNET5K object.
-mp_obj_t wiznet5k_create(mp_obj_t spi_in, mp_obj_t cs_in, mp_obj_t rst_in) {
+mp_obj_t wiznet5k_create(busio_spi_obj_t *spi_in, const mcu_pin_obj_t *cs_in, const mcu_pin_obj_t *rst_in) {
// init the wiznet5k object
wiznet5k_obj.base.type = (mp_obj_type_t*)&mod_network_nic_type_wiznet5k;
wiznet5k_obj.cris_state = 0;
- wiznet5k_obj.spi = MP_OBJ_TO_PTR(spi_in);
- common_hal_digitalio_digitalinout_construct(&wiznet5k_obj.cs, cs_in);
- common_hal_digitalio_digitalinout_construct(&wiznet5k_obj.rst, rst_in);
+ wiznet5k_obj.spi = spi_in;
wiznet5k_obj.socket_used = 0;
+ wiznet5k_obj.dhcp_socket = -1;
/*!< SPI configuration */
// XXX probably should check if the provided SPI is already configured, and
@@ -369,13 +399,11 @@ mp_obj_t wiznet5k_create(mp_obj_t spi_in, mp_obj_t cs_in, mp_obj_t rst_in) {
8 // 8 BITS
);
+ common_hal_digitalio_digitalinout_construct(&wiznet5k_obj.cs, cs_in);
common_hal_digitalio_digitalinout_switch_to_output(&wiznet5k_obj.cs, 1, DRIVE_MODE_PUSH_PULL);
- common_hal_digitalio_digitalinout_switch_to_output(&wiznet5k_obj.rst, 1, DRIVE_MODE_PUSH_PULL);
- common_hal_digitalio_digitalinout_set_value(&wiznet5k_obj.rst, 0);
- mp_hal_delay_us(10); // datasheet says 2us
- common_hal_digitalio_digitalinout_set_value(&wiznet5k_obj.rst, 1);
- mp_hal_delay_ms(160); // datasheet says 150ms
+ if (rst_in) common_hal_digitalio_digitalinout_construct(&wiznet5k_obj.rst, rst_in);
+ wiznet5k_reset();
reg_wizchip_cris_cbfunc(wiz_cris_enter, wiz_cris_exit);
reg_wizchip_cs_cbfunc(wiz_cs_select, wiz_cs_deselect);
@@ -394,8 +422,6 @@ mp_obj_t wiznet5k_create(mp_obj_t spi_in, mp_obj_t cs_in, mp_obj_t rst_in) {
// seems we need a small delay after init
mp_hal_delay_ms(250);
- wiznet5k_start_dhcp();
-
// register with network module
network_module_register_nic(&wiznet5k_obj);
diff --git a/shared-module/wiznet/wiznet5k.h b/shared-module/wiznet/wiznet5k.h
index 1284a44fd..19823ae55 100644
--- a/shared-module/wiznet/wiznet5k.h
+++ b/shared-module/wiznet/wiznet5k.h
@@ -39,7 +39,7 @@ typedef struct _wiznet5k_obj_t {
digitalio_digitalinout_obj_t cs;
digitalio_digitalinout_obj_t rst;
uint8_t socket_used;
- bool dhcp_active;
+ int8_t dhcp_socket; // -1 for DHCP not in use
} wiznet5k_obj_t;
int wiznet5k_gethostbyname(mp_obj_t nic, const char *name, mp_uint_t len, uint8_t *out_ip);
@@ -57,11 +57,12 @@ int wiznet5k_socket_setsockopt(mod_network_socket_obj_t *socket, mp_uint_t level
int wiznet5k_socket_settimeout(mod_network_socket_obj_t *socket, mp_uint_t timeout_ms, int *_errno);
int wiznet5k_socket_ioctl(mod_network_socket_obj_t *socket, mp_uint_t request, mp_uint_t arg, int *_errno);
void wiznet5k_socket_timer_tick(mod_network_socket_obj_t *socket);
+void wiznet5k_socket_deinit(mod_network_socket_obj_t *socket);
mp_obj_t wiznet5k_socket_disconnect(mp_obj_t self_in);
-mp_obj_t wiznet5k_create(mp_obj_t spi_in, mp_obj_t cs_in, mp_obj_t rst_in);
+mp_obj_t wiznet5k_create(busio_spi_obj_t *spi_in, const mcu_pin_obj_t *cs_in, const mcu_pin_obj_t *rst_in);
-void wiznet5k_start_dhcp(void);
-void wiznet5k_stop_dhcp(void);
+int wiznet5k_start_dhcp(void);
+int wiznet5k_stop_dhcp(void);
bool wiznet5k_check_dhcp(void);
extern const mod_network_nic_type_t mod_network_nic_type_wiznet5k;