Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision

Target

Select target project
  • astro/rust-card10
  • rnestler/rust-card10
  • dbrgn/rust-card10
  • toon/rust-card10
  • mwall/rust-card10
  • puzzlewolf/rust-card10
  • rnd/rust-card10
  • lilpep/rust-card10
  • rafael/rust-card10
  • squeed/rust-card10
  • arist/rust-card10
11 results
Select Git revision
Show changes
Commits on Source (184)
Showing
with 1267 additions and 185 deletions
#!/usr/bin/env bash
set -e
cargo build --release
arm-none-eabi-objcopy -O binary target/thumbv7em-none-eabi/release/$2 card10.bin
python c/bootloader/crc_patch.py card10.bin
echo "Copy this file to the device in USB Mass Storage mode:"
ls -l card10.bin
target/ target/
venv/
.idea/
# nix results
result*
nix: l0dables:
stage: build stage: build
image: nixos/nix:latest image: nixos/nix:latest
variables: variables:
...@@ -6,4 +6,28 @@ nix: ...@@ -6,4 +6,28 @@ nix:
script: script:
- nix-channel --add https://nixos.org/channels/nixos-19.03 nixpkgs - nix-channel --add https://nixos.org/channels/nixos-19.03 nixpkgs
- nix-channel --update - nix-channel --update
- nix-build - nix-build -A l0dables
- cp -r result/apps apps
artifacts:
paths:
- apps
expire_in: 1 week
firmware:
stage: build
image: nixos/nix:latest
variables:
GIT_SUBMODULE_STRATEGY: recursive
script:
- nix-channel --add https://nixos.org/channels/nixos-19.03 nixpkgs
- nix-channel --update
- nix-build release.nix
- cp -r result/* .
artifacts:
paths:
- card10.bin
- apps
- main.py
- menu.py
- card10.cfg
expire_in: 1 week
[submodule "c"] [submodule "card10-sys/firmware"]
path = c path = card10-sys/firmware
url = https://git.card10.badge.events.ccc.de/card10/firmware.git url = https://git.card10.badge.events.ccc.de/card10/firmware.git
From baef13b1adb6f7bf01a7dfd7f4f44a5a3e950b1d Mon Sep 17 00:00:00 2001
From: Astro <astro@spaceboyz.net>
Date: Thu, 5 Sep 2019 02:22:45 +0200
Subject: [PATCH] hack(epicardium): reduce init delay from 2s to 0.1s
---
epicardium/main.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/epicardium/main.c b/epicardium/main.c
index 51edbe93..7607d39d 100644
--- a/epicardium/main.c
+++ b/epicardium/main.c
@@ -32,7 +32,7 @@ int main(void)
epic_disp_print(10, 20, "Epicardium", 0xfe20, 0x0000);
epic_disp_print(off > 0 ? off : 0, 40, version_buf, 0xfe20, 0x0000);
epic_disp_update();
- mxc_delay(2000000);
+ mxc_delay(100000);
LOG_DEBUG("startup", "Initializing tasks ...");
--
2.22.1
This diff is collapsed.
[workspace] [workspace]
members = [ members = [
"l0dable", "card10-sys",
"card10-alloc",
"card10-l0dable",
"example", "example",
"rkanoid", "rkanoid",
"draw-image",
] ]
default-members = [ default-members = [
"example", "example",
"rkanoid", "rkanoid",
"draw-image",
] ]
[profile.release] [profile.release]
...@@ -16,3 +21,6 @@ debug = true ...@@ -16,3 +21,6 @@ debug = true
opt-level = "s" opt-level = "s"
lto = true lto = true
panic = "abort" panic = "abort"
[patch.crates-io]
alloc-cortex-m = { git = 'https://github.com/rust-embedded/alloc-cortex-m' }
# Rust support for the card10 CCCamp15 badge # Rust support for the card10 CCCamp19 badge
## Prerequisites ## Prepare your card10
**Jailbreaking is no longer necessary!**
Starting with firmware v1.9, running ELF binaries requires a
`/card10.cfg` with the following content:
You need Rust Nightly and the arm-none-eabi-gcc toolchain, including libc. ```
execute_elf=true
```
### Arch Linux ## Prebuilt binaries
sudo pacman -S arm-none-eabi-gcc arm-none-eabi-binutils arm-none-eabi-newlib By courtesy of this Gitlab's CI system, and NixOS, we build `.elf`
files for you drop into the `apps/` directory of your card10 badge.
## Usage For each commit in this repository, we also build complete firmware
images with the required configuration and our example binaries.
You need Rust nightly. Use rustup or NixOS. https://git.card10.badge.events.ccc.de/astro/rust-card10/-/jobs
## Prerequisites
You need rust nightly and a working setup to compile the card10
firmware including the matching libc.
1) For instructions how to setup rust please see https://rustup.rs.
Please ensure that you installed the latest rust nightly toolchain
and add the `thumbv7em-none-eabi` target.
```shell ```shell
rustup update nightly rustup toolchain install nightly
rustup override set nightly rustup update
rustup target add thumbv7em-none-eabi rustup target add thumbv7em-none-eabi --toolchain nightly
``` ```
When cloning use `--recursive` to get the submodules, otherwise update them
afterwards: 2) For instructions how to setup the card10 firmware check the dependency
chapter in https://firmware.card10.badge.events.ccc.de/how-to-build.html.
3) Additionally you may need the packages for the llvm and libc i386
dev headers.
4) Clone this repository with `--recursive` to get the submodules,
otherwise update them afterwards:
```shell ```shell
git submodule update --init --recursive git submodule update --init --recursive
``` ```
Check out this repo's submodule (the C firmware). ## Build and run Rust loadables
### Setup
If you want to come up with your own rust based loadable crate a few
preparations are required:
- Setup the new crate repository.
- Add `card10-l0dable = "^0.1"` as a dependency to your new crate.
- Change the configuration of the default cargo release profile inside your
`Cargo.toml` file:
```
[profile.release]
opt-level = "s"
panic = "abort"
```
- Create (or update) the `thumbv7em-none-eabi` target configuration at
`$PROJECT/.cargo/config` with the following rustflags:
```
[target.thumbv7em-none-eabi]
rustflags = [
"-C", "linker=arm-none-eabi-gcc",
"-C", "link-args=-Tl0dable.ld -n -pie -fPIC",
"-C", "relocation-model=pic",
]
[build]
target = "thumbv7em-none-eabi"
```
- Ensure that your crate is marked as a `non_std` project and make
`card10-l0dable` aware of your custom main function. This should require
the following update to your `main.rs` file.
```main.rs
#![no_std]
#![no_main]
use card10_l0dable::main;
main!(main);
fn main() {}
```
### Compilation
To compile the project use the nightly toolchain and define the proper target.
```shell ```shell
cd example cargo +nightly build --release --target thumbv7em-none-eabi
cargo build --release
``` ```
Then copy the resulting ### Transfer to card10
`../target/thumbv7em-none-eabi/release/l0dable-example` to the badge
in USB Mass Storage mode in the `/apps/` subfolder. Don't forget to Then copy the resulting executable from the target directory
rename with the `.elf` extension! `target/thumbv7em-none-eabi/release/example` into the
`apps` directory of your badge.
**Attention**: Its necessary to rename the executable to add the `elf`
extension (e.g `example` must be renamed as `example.elf`).
## Crates ## Crates
| Crate | Description | | Crate | Documentation | Description |
| ---- | --- | | ---- | --- | --- |
| example | l0dable example | | card10-sys | [docs.rs][card10-sys] | Unsafe C bindings for l0dables |
| l0dable | Helpers for building l0dables | | card10-alloc | [docs.rs][card10-alloc] | alloc::* support for l0dables |
| card10-l0dable | [docs.rs][card10-l0dable] | High-level crate for building l0dables |
| example | | l0dable example |
| rkanoid | | Arkanoid clone |
| draw-image | | Example of drawing a static image to the display |
[card10-sys]: https://docs.rs/card10-sys/
[card10-alloc]: https://docs.rs/card10-alloc/
[card10-l0dable]: https://docs.rs/card10-l0dable/
## Misc
### How to update the firmware bindings
## TODO 1) Update the `card10-sys/firmware` submodule to the latest firmware state.
2) Rebuild the firmware as described above.
3) Run the following script from the project root directory
```shell
python card10-sys/firmware/epicardium/api/genapi.py -H card10-sys/firmware/epicardium/epicardium.h -c card10-sys/vendor/client.c -s card10-sys/vendor/server.c
```
- [ ] alloc 4) Rebuild your app :)
c @ ea85141f
Subproject commit ea85141fe8993084882ffb945112e6891318f153
[package]
name = "card10-alloc"
version = "0.1.1"
authors = ["Astro <astro@spaceboyz.net>"]
license = "MIT/Apache-2.0"
edition = "2018"
description = "Dynamic memory allocation for card10 l0dables"
repository = "https://git.card10.badge.events.ccc.de/astro/rust-card10"
homepage = "https://git.card10.badge.events.ccc.de/astro/rust-card10"
documentation = "https://docs.rs/card10-alloc"
categories = ["no-std", "memory-management"]
keywords = [
"CCC",
"CCCamp2019",
"CCCamp19",
"card10",
"l0dable",
]
[dependencies]
alloc-cortex-m = "0.3"
card10-sys = { path = "../card10-sys" }
//! Support for dynamically allocated memory
//!
//! Reproduces l0dable hardware.c's `_sbrk()`
//!
//! Unfortunately, we cannot link `_sbrk()` directly because it
//! references the unwieldy `errno`.
//!
//! ## Example
//!
//! ```rust
//! #![no_std]
//! #![no_main]
//!
//! extern crate alloc;
//! use alloc::vec;
//! use card10_l0dable::*;
//!
//! main!(main);
//! fn main() {
//! // Pass stack headroom
//! card10_alloc::init(128 * 1024);
//! let mut xs = vec![];
//! xs.push(23);
//! }
//! ```
#![no_std]
#![feature(asm)]
#![feature(alloc_error_handler)]
use core::alloc::Layout;
use alloc_cortex_m::CortexMHeap;
use card10_sys as _;
#[global_allocator]
static ALLOCATOR: CortexMHeap = CortexMHeap::empty();
extern "C" {
static mut __heap_start: u32;
}
#[inline(always)]
fn sp() -> usize {
let mut value;
unsafe {
asm!("mov $0, sp" : "=r" (value) ::: "volatile");
}
value
}
/// Call this before using anything from `alloc`.
///
/// Consider the size of your stack-allocated variables for the
/// `stack_headroom` parameter.
///
/// Returns heap size
pub fn init(stack_headroom: usize) -> usize {
let start = unsafe { &__heap_start } as *const _ as usize;
let size = sp() - stack_headroom - start;
unsafe { ALLOCATOR.init(start, size); }
size
}
#[alloc_error_handler]
fn on_oom(_layout: Layout) -> ! {
panic!("OOM")
}
[package]
edition = "2018"
name = "card10-l0dable"
version = "0.3.0"
authors = [
"Astro <astro@spaceboyz.net>",
"Kloenk <me@kloenk.de>",
"Bruno Kirschner <bruno.kirschner@online.de>",
"Puzzlewolf <camp@nora.pink>",
"Raphael Nestler <raphael.nestler@gmail.com>",
"Danilo Bargen <mail@dbrgn.ch>",
"toon <toon@c3d2.de>",
"Sergey Pepyakin <sergei@parity.io>",
]
license = "MIT/Apache-2.0"
repository = "https://git.card10.badge.events.ccc.de/astro/rust-card10"
homepage = "https://git.card10.badge.events.ccc.de/astro/rust-card10"
keywords = [
"CCC",
"CCCamp2019",
"CCCamp19",
"card10",
"l0dable",
]
categories = ["no-std"]
description = "make l0dables for the Card10 (CCCamp 2019) badge"
documentation = "https://docs.rs/card10-l0dable"
[dependencies]
card10-sys = { path = "../card10-sys" }
embedded-graphics = "0.5"
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright (c) 2014 The Rust Project Developers
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.
use core::mem::uninitialized; /// Accelerometer, Gyroscope, Orientation
use core::marker::PhantomData;
use super::bindings::*;
use core::fmt::Write; use core::{
fmt::{self, Display, Write},
marker::PhantomData,
mem::MaybeUninit,
};
use card10_sys::*;
pub trait SensorType { pub trait SensorType {
/// sensor_type in C, sensor_id in Python /// sensor_type in C, sensor_id in Python
...@@ -10,6 +14,7 @@ pub trait SensorType { ...@@ -10,6 +14,7 @@ pub trait SensorType {
fn convert_single(value: i16) -> f32; fn convert_single(value: i16) -> f32;
} }
#[derive(Debug)]
pub struct Accelerometer; pub struct Accelerometer;
impl SensorType for Accelerometer { impl SensorType for Accelerometer {
fn sensor_type() -> u32 { fn sensor_type() -> u32 {
...@@ -20,6 +25,7 @@ impl SensorType for Accelerometer { ...@@ -20,6 +25,7 @@ impl SensorType for Accelerometer {
} }
} }
#[derive(Debug)]
pub struct Gyroscope; pub struct Gyroscope;
impl SensorType for Gyroscope { impl SensorType for Gyroscope {
fn sensor_type() -> u32 { fn sensor_type() -> u32 {
...@@ -30,6 +36,7 @@ impl SensorType for Gyroscope { ...@@ -30,6 +36,7 @@ impl SensorType for Gyroscope {
} }
} }
#[derive(Debug)]
pub struct Orientation; pub struct Orientation;
impl SensorType for Orientation { impl SensorType for Orientation {
fn sensor_type() -> u32 { fn sensor_type() -> u32 {
...@@ -48,43 +55,68 @@ pub struct Sensor<S: SensorType> { ...@@ -48,43 +55,68 @@ pub struct Sensor<S: SensorType> {
} }
impl<S: SensorType> Sensor<S> { impl<S: SensorType> Sensor<S> {
pub fn start() -> Self { /// Use one of:
/// - `BHI160::<Accelerometer>::start()`
/// - `BHI160::<Gyroscope>::start()`
/// - `BHI160::<Orientation>::start()`
fn new(stream_id: i32) -> Self {
Self {
stream_id,
_kind: PhantomData,
}
}
pub fn start() -> Result<Self, Error> {
let mut cfg = bhi160_sensor_config { let mut cfg = bhi160_sensor_config {
sample_buffer_len: 200, sample_buffer_len: 200,
sample_rate: 4, sample_rate: 4,
dynamic_range: 2, dynamic_range: 2,
_padding: [0u8; 8], _padding: [0u8; 8],
}; };
let stream_id = unsafe {
epic_bhi160_enable_sensor(S::sensor_type(), &mut cfg) let stream_id = unsafe { epic_bhi160_enable_sensor(S::sensor_type(), &mut cfg) };
if stream_id < 0 {
let error = match -stream_id {
errno::EBUSY => Error::DriverBusy,
_ => Error::Unknown(stream_id),
}; };
Sensor {
stream_id, return Err(error);
_kind: PhantomData,
} }
Ok(Sensor::new(stream_id))
} }
pub fn read(&self) -> SensorData<S> { pub fn read(&self) -> Result<SensorData<S>, Error> {
let mut buf: [bhi160_data_vector; DATA_MAX] = unsafe { let mut buffer = MaybeUninit::<[bhi160_data_vector; DATA_MAX]>::zeroed();
uninitialized() let buffer_pointer = buffer.as_mut_ptr() as *mut _;
};
let n = unsafe { let packet_count = unsafe { epic_stream_read(self.stream_id, buffer_pointer, DATA_MAX) };
epic_stream_read(self.stream_id, buf.as_mut_ptr() as *mut _, buf.len()) if packet_count < 0 {
let error = match -packet_count {
errno::ENODEV => Error::SensorUnavailable,
errno::EBADF => Error::SensorDescriptorUnknown,
errno::EINVAL => Error::InvalidSampleCount,
errno::EBUSY => Error::CouldNotAcquireLock,
_ => Error::Unknown(packet_count),
}; };
if n < 0 {
panic!("epic_stream_read fail"); return Err(error);
} }
let n = n as usize;
SensorData { Ok(SensorData {
buf, n, buf: unsafe { buffer.assume_init() },
n: packet_count as usize,
_kind: PhantomData, _kind: PhantomData,
} })
} }
} }
impl<S: SensorType> Drop for Sensor<S> { impl<S: SensorType> Drop for Sensor<S> {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { epic_bhi160_disable_sensor(S::sensor_type()); } unsafe {
epic_bhi160_disable_sensor(S::sensor_type());
}
} }
} }
...@@ -95,13 +127,11 @@ pub struct SensorData<S> { ...@@ -95,13 +127,11 @@ pub struct SensorData<S> {
} }
impl<'a, S: SensorType> IntoIterator for &'a SensorData<S> { impl<'a, S: SensorType> IntoIterator for &'a SensorData<S> {
type Item = SensorDataItem; type Item = SensorDataItem<S>;
type IntoIter = SensorDataIter<'a, S>; type IntoIter = SensorDataIter<'a, S>;
fn into_iter(self) -> Self::IntoIter { fn into_iter(self) -> Self::IntoIter {
SensorDataIter { SensorDataIter { data: self, pos: 0 }
data: self,
pos: 0,
}
} }
} }
...@@ -111,33 +141,54 @@ pub struct SensorDataIter<'a, S> { ...@@ -111,33 +141,54 @@ pub struct SensorDataIter<'a, S> {
} }
impl<'a, S: SensorType> Iterator for SensorDataIter<'a, S> { impl<'a, S: SensorType> Iterator for SensorDataIter<'a, S> {
type Item = SensorDataItem; type Item = SensorDataItem<S>;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
while self.pos < self.data.n { while self.pos < self.data.n {
let vec = &self.data.buf[self.pos]; let vec = &self.data.buf[self.pos];
self.pos += 1; if vec.data_type != DATA_TYPE_VECTOR {
if vec.data_type == DATA_TYPE_VECTOR { writeln!(crate::UART, "Sensor: skip type {}\r", vec.data_type).ok();
let item = SensorDataItem { continue;
x: S::convert_single(vec.x), }
y: S::convert_single(vec.y),
z: S::convert_single(vec.z), let item = SensorDataItem::<S> {
x_raw: vec.x,
y_raw: vec.y,
z_raw: vec.z,
status: vec.status, status: vec.status,
_kind: PhantomData,
}; };
self.pos += 1;
return Some(item); return Some(item);
} else {
writeln!(crate::UART, "Sensor: skip type {}\r", vec.data_type).unwrap();
}
} }
None None
} }
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct SensorDataItem { pub struct SensorDataItem<S: SensorType> {
x: f32, pub x_raw: i16,
y: f32, pub y_raw: i16,
z: f32, pub z_raw: i16,
status: u8, pub status: u8,
_kind: PhantomData<S>,
}
impl<S: SensorType> SensorDataItem<S> {
pub fn get_x(&self) -> f32 {
S::convert_single(self.x_raw)
}
pub fn get_y(&self) -> f32 {
S::convert_single(self.y_raw)
}
pub fn get_z(&self) -> f32 {
S::convert_single(self.z_raw)
}
} }
#[repr(C)] #[repr(C)]
...@@ -152,3 +203,38 @@ pub struct bhi160_data_vector { ...@@ -152,3 +203,38 @@ pub struct bhi160_data_vector {
} }
const DATA_TYPE_VECTOR: u8 = 0; const DATA_TYPE_VECTOR: u8 = 0;
// -----------------------------------------------------------------------------
// BHI160 Error
// -----------------------------------------------------------------------------
#[derive(Debug)]
pub enum Error {
/// The descriptor table lock could not be acquired.
CouldNotAcquireLock,
/// The BHI160 driver is currently busy with other tasks and could not be
/// acquired for enabling a sensor.
DriverBusy,
/// The requested sample `count` is not a multiple of the sensor's sample
/// size.
InvalidSampleCount,
/// The given sensor descriptor is unknown.
SensorDescriptorUnknown,
/// Sensor is not currently available.
SensorUnavailable,
/// Not yet documented and therefore unknown error types.
Unknown(i32),
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::CouldNotAcquireLock => writeln!(f, "Could not acquire BHI160 lock."),
Error::DriverBusy => writeln!(f, "The BHI160 Driver is busy."),
Error::InvalidSampleCount => writeln!(f, "Sample couldn't invalid."),
Error::SensorDescriptorUnknown => writeln!(f, "Unknown BHI160 sensor descriptor."),
Error::SensorUnavailable => writeln!(f, "The BHI160 sensor is currently unavailable."),
Error::Unknown(id) => writeln!(f, "Unknown error id: {}", id),
}
}
}
/// Enviromental sensor
use card10_sys::*;
use core::mem::uninitialized; use core::mem::uninitialized;
use super::bindings::*;
pub struct BME680; pub struct BME680;
pub type SensorData = bme680_sensor_data; pub type SensorData = bme680_sensor_data;
...@@ -7,7 +9,7 @@ pub type SensorData = bme680_sensor_data; ...@@ -7,7 +9,7 @@ pub type SensorData = bme680_sensor_data;
impl BME680 { impl BME680 {
pub fn start() -> Self { pub fn start() -> Self {
if unsafe { epic_bme680_init() } != 0 { if unsafe { epic_bme680_init() } != 0 {
panic!("Cannot start light sensor"); panic!("Cannot start BME680 sensor");
} }
BME680 BME680
} }
...@@ -24,6 +26,8 @@ impl BME680 { ...@@ -24,6 +26,8 @@ impl BME680 {
impl Drop for BME680 { impl Drop for BME680 {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { epic_bme680_deinit(); } unsafe {
epic_bme680_deinit();
}
} }
} }
use super::bindings::*; use card10_sys::*;
/// Button inputs
pub struct Buttons { pub struct Buttons {
state: u32, state: u32,
} }
impl Buttons { impl Buttons {
/// Read the current button state
pub fn read() -> Self { pub fn read() -> Self {
let mask = let mask = epic_button_BUTTON_LEFT_BOTTOM
epic_button_BUTTON_LEFT_BOTTOM | | epic_button_BUTTON_RIGHT_BOTTOM
epic_button_BUTTON_RIGHT_BOTTOM | | epic_button_BUTTON_LEFT_TOP
epic_button_BUTTON_LEFT_TOP | | epic_button_BUTTON_RIGHT_TOP
epic_button_BUTTON_RIGHT_TOP | | epic_button_BUTTON_RESET;
epic_button_BUTTON_RESET;
let state = unsafe { epic_buttons_read(mask as u8) }.into(); let state = unsafe { epic_buttons_read(mask as u8) }.into();
Buttons { state } Buttons { state }
} }
......
use super::bindings::*; use super::framebuffer::FrameBuffer;
use card10_sys::*;
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
#[repr(C)] #[repr(C)]
...@@ -31,9 +32,7 @@ impl Color { ...@@ -31,9 +32,7 @@ impl Color {
pub fn rgb8(r8: u8, g8: u8, b8: u8) -> Self { pub fn rgb8(r8: u8, g8: u8, b8: u8) -> Self {
let c = let c =
((u16::from(r8) & 0xF8) << 8) | ((u16::from(r8) & 0xF8) << 8) | ((u16::from(g8) & 0xFA) << 3) | (u16::from(b8) & 0xF8);
((u16::from(g8) & 0xFA) << 3) |
(u16::from(b8) & 0xF8);
Color(c) Color(c)
} }
...@@ -50,7 +49,7 @@ impl Color { ...@@ -50,7 +49,7 @@ impl Color {
} }
pub fn g8(&self) -> u8 { pub fn g8(&self) -> u8 {
self.r() << 2 self.g() << 2
} }
pub fn b(&self) -> u8 { pub fn b(&self) -> u8 {
...@@ -58,7 +57,7 @@ impl Color { ...@@ -58,7 +57,7 @@ impl Color {
} }
pub fn b8(&self) -> u8 { pub fn b8(&self) -> u8 {
self.r() << 3 self.b() << 3
} }
} }
...@@ -76,59 +75,167 @@ pub enum FillStyle { ...@@ -76,59 +75,167 @@ pub enum FillStyle {
pub struct Display; pub struct Display;
#[repr(u8)]
pub enum Font {
Font8 = disp_font_name_DISP_FONT8 as u8,
Font12 = disp_font_name_DISP_FONT12 as u8,
Font16 = disp_font_name_DISP_FONT16 as u8,
Font20 = disp_font_name_DISP_FONT20 as u8,
Font24 = disp_font_name_DISP_FONT24 as u8,
}
/// Immediate mode routines
impl Display { impl Display {
pub const W: u16 = 160; pub const W: i16 = 160;
pub const H: u16 = 80; pub const H: i16 = 80;
pub const FONT_W: u16 = 14; pub const FONT_W: i16 = 14;
pub const FONT_H: u16 = 20; pub const FONT_H: i16 = 20;
/// Open the display, return an instance
pub fn open() -> Self { pub fn open() -> Self {
unsafe { epic_disp_open(); } unsafe {
epic_disp_open();
}
Display Display
} }
/// Write Epicardium's framebuffer to the display
pub fn update(&self) { pub fn update(&self) {
unsafe { epic_disp_update(); } unsafe {
epic_disp_update();
}
} }
/// Clear everything with a solid `color`
pub fn clear(&self, color: Color) { pub fn clear(&self, color: Color) {
unsafe { epic_disp_clear(color.0); } unsafe {
epic_disp_clear(color.0);
}
} }
/// Print text
///
/// s must be 0-terminated /// s must be 0-terminated
pub fn print(&self, x: u16, y: u16, s: &[u8], fg: Color, bg: Color) { pub fn print(&self, x: i16, y: i16, s: &[u8], fg: Color, bg: Color) {
unsafe { unsafe {
epic_disp_print(x, y, s.as_ptr(), fg.0, bg.0); epic_disp_print(x, y, s.as_ptr(), fg.0, bg.0);
} }
} }
pub fn pixel(&self, x: u16, y: u16, color: Color) { /// Print text with a selected font
///
/// s must be 0-terminated
pub fn print_adv(&self, font: Font, x: i16, y: i16, s: &[u8], fg: Color, bg: Color) {
unsafe {
epic_disp_print_adv(font as u8, x, y, s.as_ptr(), fg.0, bg.0);
}
}
/// Set a pixel
pub fn pixel(&self, x: i16, y: i16, color: Color) {
unsafe { unsafe {
epic_disp_pixel(x, y, color.0); epic_disp_pixel(x, y, color.0);
} }
} }
pub fn line(&self, x1: u16, y1: u16, x2: u16, y2: u16, color: Color, linestyle: LineStyle, pixelsize: u16) { /// Draw a line
pub fn line(
&self,
x1: i16,
y1: i16,
x2: i16,
y2: i16,
color: Color,
linestyle: LineStyle,
pixelsize: u16,
) {
unsafe { unsafe {
epic_disp_line(x1, y1, x2, y2, color.0, linestyle as u32, pixelsize); epic_disp_line(x1, y1, x2, y2, color.0, linestyle as u32, pixelsize);
} }
} }
pub fn rect(&self, x1: u16, y1: u16, x2: u16, y2: u16, color: Color, fillstyle: FillStyle, pixelsize: u16) { pub fn rect(
&self,
x1: i16,
y1: i16,
x2: i16,
y2: i16,
color: Color,
fillstyle: FillStyle,
pixelsize: u16,
) {
unsafe { unsafe {
epic_disp_rect(x1, y1, x2, y2, color.0, fillstyle as u32, pixelsize); epic_disp_rect(x1, y1, x2, y2, color.0, fillstyle as u32, pixelsize);
} }
} }
pub fn circ(&self, x: u16, y: u16, rad: u16, color: Color, fillstyle: FillStyle, pixelsize: u16) { /// Draw a circle
pub fn circ(
&self,
x: i16,
y: i16,
rad: u16,
color: Color,
fillstyle: FillStyle,
pixelsize: u16,
) {
unsafe { unsafe {
epic_disp_circ(x, y, rad, color.0, fillstyle as u32, pixelsize); epic_disp_circ(x, y, rad, color.0, fillstyle as u32, pixelsize);
} }
} }
/// Obtain a handle for a framebuffer.
///
/// Don't use `display.send()` but `framebuffer.send()` as long as
/// it is in use.
pub fn framebuffer<'d>(&'d mut self) -> FrameBuffer<'d> {
FrameBuffer::uninitialized(self)
}
} }
impl Drop for Display { impl Drop for Display {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { epic_disp_close(); } unsafe {
} epic_disp_close();
}
}
}
/// Convenience text display
///
/// Requires `card10_alloc::init()` and `extern crate alloc;`
#[macro_export]
macro_rules! display {
($disp: expr, $x: expr, $y: expr, $fg: expr, $bg: expr,
$fmt: expr) => ({
use alloc::format;
let s = format!(concat!($fmt, "\0"));
$disp.print($x, $y, s.as_bytes(), $fg, $bg);
});
($disp: expr, $x: expr, $y: expr, $fg: expr, $bg: expr,
$fmt: expr, $($arg: tt)*) => ({
use alloc::format;
let s = format!(concat!($fmt, "\0"), $($arg)*);
$disp.print($x, $y, s.as_bytes(), $fg, $bg);
});
}
/// Convenience text display with selected font
///
/// Requires `card10_alloc::init()` and `extern crate alloc;`
#[macro_export]
macro_rules! display_adv {
($disp: expr, $font: tt, $x: expr, $y: expr, $fg: expr, $bg: expr,
$fmt: expr) => ({
use alloc::format;
use card10_l0dable::Font;
let s = format!(concat!($fmt, "\0"));
$disp.print_adv(Font::$font, $x, $y, s.as_bytes(), $fg, $bg);
});
($disp: expr, $font: tt, $x: expr, $y: expr, $fg: expr, $bg: expr,
$fmt: expr, $($arg: tt)*) => ({
use alloc::format;
let s = format!(concat!($fmt, "\0"), $($arg)*);
$disp.print_adv(Font::$font, $x, $y, s.as_bytes(), $fg, $bg);
});
} }
...@@ -37,7 +37,7 @@ impl<'a> fmt::Write for FmtBuffer<'a> { ...@@ -37,7 +37,7 @@ impl<'a> fmt::Write for FmtBuffer<'a> {
} }
} }
/// 256 bytes ought to be enough for any string /// 255 bytes ought to be enough for any C string
pub fn str_to_cstr(s: &str) -> [u8; 256] { pub fn str_to_cstr(s: &str) -> [u8; 256] {
let mut buf: [u8; 256] = unsafe { uninitialized() }; let mut buf: [u8; 256] = unsafe { uninitialized() };
let mut fmt = FmtBuffer::new(buf.as_mut()); let mut fmt = FmtBuffer::new(buf.as_mut());
......
use core::slice::from_raw_parts;
extern "C" {
static Font8: Font;
static Font12: Font;
static Font16: Font;
static Font20: Font;
static Font24: Font;
}
#[repr(C)]
pub struct Font {
table: *const u8,
pub w: u16,
pub h: u16,
}
impl Font {
pub fn font8() -> &'static Self {
unsafe { &Font8 }
}
pub fn font12() -> &'static Self {
unsafe { &Font12 }
}
pub fn font16() -> &'static Self {
unsafe { &Font16 }
}
pub fn font20() -> &'static Self {
unsafe { &Font20 }
}
pub fn font24() -> &'static Self {
unsafe { &Font24 }
}
fn bytes_per_row(&self) -> usize {
self.w as usize / 8 + 1
}
pub fn get_glyph(&self, c: char) -> Option<Glyph> {
let h = self.h as usize;
let bytes_per_row = self.bytes_per_row();
let table = unsafe {
from_raw_parts(self.table, ('~' as usize - (' ' as usize) - 1) * bytes_per_row * h)
};
let offset = (c as usize - (' ' as usize)) * bytes_per_row * h;
if offset < table.len() {
let table = &table[offset..(offset + bytes_per_row * h)];
Some(Glyph {
table,
bytes_per_row,
})
} else {
None
}
}
}
pub struct Glyph<'a> {
table: &'a [u8],
bytes_per_row: usize,
}
impl<'a> Glyph<'a> {
pub fn get_pixel(&self, x: usize, y: usize) -> bool {
let offset = x / 8 + y * self.bytes_per_row;
self.table[offset] & (1 << (7 - (x & 7))) != 0
}
}