GithubHelp home page GithubHelp logo

swift-embedded's Introduction

Build Status

This project aims to bring Swift to the world of embedded systems and IoT. It enables using Swift on microcontrollers with no operating system and with minimal resources available.

What version of Swift does it support?

Swift 5.1... enjoy the latest features of Swift on bare metal! 🚀

Are all features of Swift available?

Yes, except for full unicode support. To save some memory, it includes simplified support only – you can use unicode characters in your strings, but they are ignored by operations like .uppercased() ("žluťoučký".uppercased() returns "žLUťOUčKý" instead of "ŽLUŤOUČKÝ").

Any limitations?

Code size. A "hello world" application has a little bit over one megabyte because it includes a big part of the Swift standard library. However, it is a fixed cost (does not grow proportionally with your program) and you can fit quite a lot on a microcontroller with 2MB of flash!

What boards are supported?

Short answer: NUCLEO-F439ZI, but adding support for any other STM32F4-based board with 2MB of flash memory should require only few lines of code.

The toolchain itself should be able to target any microcontroller using the thumbv7-m or thumbv7-em architecture. However, any practical embedded application is going to require a package providing access to hardware peripherals. I am currently focusing on supporting the STM32F4 family of microcontrollers – the stm32 Swift package provides access to the basic hardware peripherals of those microcontrollers, such as UART, SPI or GPIO.

To make building an embedded application as simple as possible, I have created a small cross command-line utility. It is a wrapper around swift build that handles all the things such as setting up a linker script or using the right compiler flags, making compiling an app a simple one-liner: cross build.


This project is in an early phase, and there is still a lot to work on. Also, if you want to know more about the process of porting Swift to embedded systems, feel free to check out my thesis Swift for Embedded Systems.

Getting Started

Installing the toolchain

  1. Download the latest build of the toolchain from here and put the .xctoolchain file to either /Library/Developer/Toolchains/ or ~/Library/Developer/Toolchains/:

    $ mkdir -p /Library/Developer/Toolchains
    $ sudo xattr -dr com.apple.quarantine <downloaded file>.xctoolchain # required on macOS Catalina only
    $ mv <downloaded file>.xctoolchain ~/Library/Developer/Toolchains

    Why the xattr -dr ... on macOS Catalina? It makes sure you won't get the "XYZ can’t be opened because Apple cannot check it for malicious software" message. The toolchain is properly signed, but it is currently not notarized, as Apple newly requires (starting from Feb 2020) the hardened runtime feature to be enabled and this seems to break the toolchain. I hope to resolve this soon!

  2. Activate the toolchain with:

    $ export TOOLCHAINS=baremetal.YYYYMMDD
  3. Install the cross utility

    $ brew install swift-embedded/formulae/cross
  4. Check that swift and other command-line utilities now reference the newly downloaded toolchain.

    $ xcrun -f swift
    /Users/alandragomirecky/Library/Developer/Toolchains/swift-LOCAL-2019-12-10-a.xctoolchain/usr/bin/swift

    You need to have Xcode installed. Otherwise, xcrun won't find the toolchain.

Running an example

  1. Checkout this repository:

    $ git clone https://github.com/swift-embedded/swift-embedded
  2. Go to a directory with some example app and compile it:

    $ cd swift-embedded/examples/Blinky
    $ cross build
  3. Flash and run the application. One option is using the openocd (brew install openocd):

    In a terminal, run openocd (it connects to your board and starts a gdb server)

    $ openocd -f board/st_nucleo_f4.cfg

    In an another terminal, load your application to the board and start it:

    $ xcrun arm-none-eabi-gdb .build/debug/Blinky -ex 'tar ext :3333' -ex 'load'

    Always make sure you have set the TOOLCHAINS environment variable, so you are using the right toolchain! Or use something like direnv, so you don't have to think about it 😏.

Using the Swift Package Manager and the cross utility

The Swift Package Manager is fully supported and is part of the pre-built baremetal toolchain. Furthermore, it should be possible to use any existing package for your bare-metal application, as long as it does not depend on some unsupported library (e. g. Foundation).

One thing to keep in mind is that running swift build builds your application for the computer at which you are running the command. To cross-compile the application for some bare-metal device, you would have to create a destination.json file specifying all the cross-compilation settings and run swift build --destination destination.json.

Creating the destination.json file is not a trivial task, and always having to add --destination destination.json gets tedious quite quickly. Both those things are solved by the cross utility. It works as follows:

  1. Create a Cross.toml next to your Package.swift file. Its content can be as simple as:

    target = "STM32F439ZI"
  2. Running cross build then a) automatically creates the required destination.json file in the build directory and b) invokes swift build with the proper --destination flag.

What IDEs are supported?

  • Xcode is not (it does not support the baremetal platform introduced by this project and its extensibility is very limited).
  • However, the toolchain contains modified sourcekit-lsp, so you should be able to use any editor with LSP support!
    • Visual Studio Code

      • For autocompletion, install sourcekit-lsp extension and set the toolchain's and sourcekit-lsp's paths in settings:

        "sourcekit-lsp.serverPath": "/Path/to/toolchain/swift-LOCAL-2020-01-04-a.xctoolchain/usr/bin/sourcekit-lsp",
        "sourcekit-lsp.toolchainPath": "/Path/to/toolchain/swift-LOCAL-2020-01-04-a.xctoolchain",
      • To integrate openocd and arm-none-eabi-gdb into vscode, you can use the Cortex-Debug extension. Example launch configuration:

        {
            "cwd": "${workspaceRoot}",
            "executable": "./.build/debug/Blinky",
            "name": "Debug Microcontroller",
            "request": "launch",
            "type": "cortex-debug",
            "servertype": "openocd",
            "configFiles": ["board/st_nucleo_f4.cfg"]
        }

        arm-none-eabi-gdb does not understand Swift, so you will not be able to read Swift variables etc.

    • Vim

      • I use coc.nvim with the following settings:

            "languageserver": {
                "swift": {
                    "command": "xcrun",
                    "args": [
                        "sourcekit-lsp"
                    ],
                    "filetypes": [
                        "swift",
                        "c",
                        "cpp"
                    ],
                    "initializationOptions": {},
                    "settings": {},
                    "rootPatterns": [
                        "Cross.toml"
                    ],
                    "requireRootPattern": true
                }

        Make sure to have the TOOLCHAINS environment variable set!

License

swift-embedded's People

Contributors

dragomirecky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swift-embedded's Issues

ESP32 support?

Hey, I just started using ESP32 in my project and it works great on C and I'm wondering if it is possible to launch Swift on it.

@dragomirecky could you please tell is it possible to launch swift on ESP32 or not?

Not able to load ont on NUCLEON-H743ZI2

Thanks for the good explanation and setup. I managed to get a board NUCLEO-H743ZI2 like described in the readme.

My toolchain is set to

xcrun -f swift
/Users/stijnwillems/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/swift

When I try to run openocd it fails

openocd -f board/st_nucleo_f4.cfg
Open On-Chip Debugger 0.10.0
Licensed under GNU GPL v2
For bug reports, read
	http://openocd.org/doc/doxygen/bugs.html
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
adapter speed: 2000 kHz
adapter_nsrst_delay: 100
none separate
srst_only separate srst_nogate srst_open_drain connect_deassert_srst
Info : Unable to match requested speed 2000 kHz, using 1800 kHz
Info : Unable to match requested speed 2000 kHz, using 1800 kHz
Info : clock speed 1800 kHz
Error: open failed
in procedure 'init'
in procedure 'ocd_bouncer'

But as my knowledge is not big on the openocd part I got opened a new therminal and tride to load the builded blinky in to the

xcrun arm-none-eabi-gdb .build/debug/Blinky -ex 'tar ext :3333' -ex 'load'

GNU gdb (GNU Tools for Arm Embedded Processors 8-2019-q1-update) 8.2.50.20181213-git
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "--host=x86_64-apple-darwin10 --target=arm-none-eabi".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from .build/debug/Blinky...

warning: Section .debug_names in /Users/stijnwillems/Developer/OpenSource/swift-embedded/examples/Blinky/.build/thumbv7m-unknown-none-eabi/debug/Blinky length 368 does not match section length 33060, ignoring .debug_names.

warning: Could not find DWO CU /Users/stijnwillems/Developer/OpenSource/swift-embedded/examples/Blinky/.build/thumbv7m-unknown-none-eabi/debug/ModuleCache/BDVD4G0YREPI/HardwareExt-27Z9BOINAXY0Z.pcm(0xf4d17d3941b52b0c) referenced by CU at offset 0x7539 [in module /Users/stijnwillems/Developer/OpenSource/swift-embedded/examples/Blinky/.build/thumbv7m-unknown-none-eabi/debug/Blinky]

So unfortunatly I am somewhat stuck now. Could you point me in a direction to look for a solution?

Flashing Nucleo-F439ZI board takes a long time

Hi @dragomirecky, this is a great project, thanks so much for making it public.

I got a Nucleo-F439ZI board and followed your tutorial. And it worked, i.e. I can build, flash, and run your Blinky example. Success!

I have two questions that maybe you can answer:

  1. Flashing the built Blinky binary to the STM32 with OpenOCD/GDB takes about 35 seconds for me. Is this normal? I find it quite annoying compared to other microcontrollers, which can usually be flashed in a few seconds at most.

    I realize that the Swift binary is much bigger, but I still find it surprising that the transfer rate during flashing isn't higher than 40 kB/s or so.

  2. The built Blinky binary is 3.7 MB (debug build built with cross build) or 3.3 MB (release build, cross build -c release), which is more than the storage space on the STM32, right? I don't understand how this works. What's in the binary that's not being written to the STM32? Debug symbols? What does gdb do to determine which parts of the binary to flash to the microcontroller?

cross no longer works, manual script fails on linking

Hello! Awesome project, I am attempting to try a compile here, using the toolchain & it dies at the part where it tries to link with __Vector. Any advice?

swiftc -Xcc -ffunction-sections -Xcc -fdata-sections -Xcc -mthumb -Xlinker --gc-sections -Xfrontend -metadata-sections -Xfrontend -function-sections -Xfrontend -data-sections -static-stdlib -target thumbv7m-unknown-none-eabi -use-ld=/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../lib/gcc/arm-none-eabi/8.2.1/../../../../arm-none-eabi/bin/ld -Xcc -D_BAREMETAL -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../lib/gcc/arm-none-eabi/8.2.1/thumb/v7e-m/nofp/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../lib/gcc/thumb/v7e-m/nofp/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../lib/gcc/arm-none-eabi/8.2.1/../../../../arm-none-eabi/lib/arm-none-eabi/8.2.1/thumb/v7e-m/nofp/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../lib/gcc/arm-none-eabi/8.2.1/../../../../arm-none-eabi/lib/thumb/v7e-m/nofp/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../arm-none-eabi/lib/arm-none-eabi/8.2.1/thumb/v7e-m/nofp/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../arm-none-eabi/lib/thumb/v7e-m/nofp/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../arm-none-eabi/usr/lib/arm-none-eabi/8.2.1/thumb/v7e-m/nofp/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../arm-none-eabi/usr/lib/thumb/v7e-m/nofp/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../lib/gcc/arm-none-eabi/8.2.1/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../lib/gcc/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../lib/gcc/arm-none-eabi/8.2.1/../../../../arm-none-eabi/lib/arm-none-eabi/8.2.1/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../lib/gcc/arm-none-eabi/8.2.1/../../../../arm-none-eabi/lib/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../arm-none-eabi/lib/arm-none-eabi/8.2.1/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../arm-none-eabi/lib/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../arm-none-eabi/usr/lib/arm-none-eabi/8.2.1/ -L/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../arm-none-eabi/usr/lib/ -lswiftCore -lswiftStdlibStubsBaremetal -lstdc++_nano -lc -lg -lm -lgcc -Xlinker -T -Xlinker ./linker.ld test.swift
/Users/ericlewis/Library/Developer/Toolchains/swift-LOCAL-2020-02-15-a.xctoolchain/usr/bin/../lib/gcc/arm-none-eabi/8.2.1/../../../../arm-none-eabi/bin/ld:./linker.ld:54: undefined symbol `__Vectors' referenced in expression
clang: error: ld.lld command failed with exit code 1 (use -v to see invocation)

Thanks

Thanks for releasing.
Was looking for it just yesterday! ^_^

Regarding code size, is it possible to apply tree-shaking?

STM32F767 support

I'm expecting to receive Pyboard D-series (STM32F767) any day now. It features 4 MB of FLASH, WiFi+BT and more
Hello @dragomirecky, could you tell if swift-embedded now support STM32F767?

I'm wondering how to use wifi/bt on microcontroller in swift. I need two things:

  • BLE connectivity with iOS/Android
  • connect to the server using WebSockets

I'd love to write anything needed, but I need your help in the very beginning

Not able to run the LSP

When trying to setup visual studio code like in the ReadMe I got errors that it could not run the sourcekit-lsp. I'm trying this on Catalina.

Then I just tried to run it. But this failed with message below. Any idea's?

swift-LOCAL-2020-02-15-a.xctoolchain ./usr/bin/sourcekit-lsp

Fatal error: fatal error encountered decoding message MessageDecodingError(code: LanguageServerProtocol.ErrorCode(rawValue: -32700), message: "expected \':\' in message header", id: nil, messageKind: LanguageServerProtocol.MessageDecodingError.MessageKind.unknown): file /Users/jenkins/data/workspace/swift-embedded/swift/src/sourcekit-lsp/Sources/LanguageServerProtocolJSONRPC/JSONRPCConnection.swift, line 191
[1]    8624 illegal hardware instruction  ./usr/bin/sourcekit-lsp

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.