DEV Community

Cover image for How to build a Garmin watch app: our Clay Sniper story and a Connect IQ tutorial
Kirill Lukyanov
Kirill Lukyanov

Posted on Originally published at klukyanov.ru

How to build a Garmin watch app: our Clay Sniper story and a Connect IQ tutorial

Garmin has its own programming language, its own toolchain and its own app store, and most tutorials about it are either years old or stop at "hello world". We just shipped Clay Sniper for Garmin watches, a training app for clay shooters, and went from the first commit to a store submission in two days. Here is how it is built, and a practical walkthrough for building your own Connect IQ app.

This is part 1 of a series. Part 2 will be about watch faces.

TL;DR

Garmin apps are written in Monkey C with the free Connect IQ SDK. The easiest editor is VS Code with Garmin's official Monkey C extension. You test in the bundled simulator, sideload a .prg file to your own watch over USB, and publish a signed .iq package through Garmin's web portal. If you know Java, JavaScript or Swift, your first app will run in the simulator in an evening. The hard parts come later: dozens of watch models with different screens and sensors, and a manual publishing process with no API.

What we built

Clay Sniper is an iPhone journal for clay shooting (sporting, trap, skeet). It has always had an Apple Watch app: you stand on the station and tap hit or miss after every target. Many shooters wear Garmin, so we ported the same logic.

The Garmin version:

  • Buttons, not taps. UP is a hit, DOWN is a miss, BACK undoes the last shot. A single vibration confirms a hit, a double one a miss, so you never look at the screen with a gun in your hands.
  • Series and disciplines. Official programs including 5-Stand; the watch shows the next station and target type, and closes the series on the last target.
  • Heart rate, split into "during series" and "between series".
  • Garmin Connect activity. The workout is saved as a regular "Shooting" activity with custom FIT fields: hits, misses, hit rate.
  • Sync to iPhone, where the full stats live.
  • Competition mode. The phone sends today's competitions and station schedule to the watch.

The first commit was on October 13, version 1.0.0 went to the Connect IQ Store on October 15. Version 1.1.0 is live in the store, 1.2.0 is in review.

How it is built

About 2,000 lines of Monkey C in 12 files, ~400 of them tests. Three layers:

  1. Core. Workout state, a list of actions (hit, miss, undo, pause, heart rate) and a reducer. This is the same Flux pattern as our iOS apps and the same rules as the Apple Watch version. The reducer knows nothing about the screen or sensors, so it is trivial to test.
  2. Store. The only place where state changes, and where side effects live: ActivityRecording, custom FIT fields via FitContributor, vibration, settings in Application.Storage, the outbox for the phone.
  3. Views. Menu2 settings, the shot screen, a controls menu and a summary. Views only draw state and turn button presses into actions.

One difference from Swift: Monkey C has no cheap value copies and the app has tens of kilobytes of memory, so the reducer mutates state in place instead of returning a new copy. "State changes only through dispatch" still holds.

Watch to iPhone

There is no direct channel between your watch app and your phone app. Messages go through the Garmin Connect app. On the watch you use Communications, on iOS the Connect IQ Mobile SDK (we added it via Swift Package Manager).

  1. The user taps "Connect watch" once, picks the watch in Garmin Connect, and is sent back to our app via a URL scheme.
  2. After a workout the watch puts it in a persistent outbox and sends it in parts via Communications.transmit. An hour of heart rate is hundreds of samples, so it is chunked 100 pairs per part.
  3. The phone reassembles the parts, saves the workout and replies with an ack. Only then does the watch drop it from the outbox.
  4. No phone nearby? The workout waits and is resent on the next app start or when the phone asks for a sync.

Messages are plain dictionaries with short keys, versioned, and new fields are always optional, so an older phone app still accepts workouts from a newer watch app.

Connect IQ app types

Pick the type first. It is declared in the manifest and decides what your code is allowed to do.

Type Manifest What it is Example
Watch face watchface the main screen, always visible; no button input, updates once a minute in low-power mode Clay Sniper Range (part 2)
Device app watch-app launched from the activity list, full screen, buttons and sensors, records its own activity Clay Sniper
Data field datafield one cell on a built-in activity screen (run, bike) custom power or pace
Widget widget a quick summary scrolled from the watch face; shown as a glance on newer watches weather, calendar
Music audio-content-provider syncs tracks from a streaming service music apps

If all you need is one number during a run, build a data field. We needed buttons, the HR sensor and activity recording, so watch-app.

What you need

Everything is free: no developer fee, no paid SDK. Works on macOS, Windows and Linux.

  • A Garmin account for the SDK Manager and the developer portal (apps-developer.garmin.com).
  • Connect IQ SDK Manager from developer.garmin.com/connect-iq (on a Mac also brew install --cask connectiq-sdk-manager). Pick an SDK version and download device definitions: the compiler cannot build for a model it has no definition for.
  • VS Code + the Monkey C extension: highlighting, completion, project templates, simulator and debugger.
  • A developer key. Every build is signed with it, and updates in the store must be signed with the same key. Don't lose it.
openssl genrsa -out developer_key.pem 4096
openssl pkcs8 -topk8 -inform PEM -outform DER \
  -in developer_key.pem -out developer_key.der -nocrypt
Enter fullscreen mode Exit fullscreen mode

Or run "Monkey C: Generate a Developer Key" in VS Code.

Monkey C in five minutes

  • Types are optional, turn them on. Build with strict type checking (-l 3): errors that would otherwise crash on the watch are caught at compile time.
  • The API lives in Toybox: WatchUi, Graphics, Sensor, Position, ActivityRecording, Communications, Application.Storage.
  • Check capabilities with has. if (info has :meanSeaLevelPressure). The API surface depends on the model, and this is the number one source of crashes.
  • Memory is tens of kilobytes. Our watch face uses 17 KB of the 124 KB available on a Fenix 6X Pro.
  • Resources are separate: strings, icons and menus in XML, translations in resources-rus, resources-deu and so on.

Your first app: a hit counter

A simplified Clay Sniper core: UP is a hit, DOWN is a miss, the screen shows hits/shots. Create the project with "Monkey C: New Project" and you get:

hit-counter/
  manifest.xml
  monkey.jungle         project.manifest = manifest.xml
  resources/drawables/  launcher icon
  resources/strings/    app name
  source/HitApp.mc
Enter fullscreen mode Exit fullscreen mode

The manifest:

<iq:manifest version="3" xmlns:iq="http://www.garmin.com/xml/connectiq">
  <iq:application id="your-uuid" type="watch-app" entry="HitApp"
      name="@Strings.AppName" launcherIcon="@Drawables.LauncherIcon"
      minApiLevel="3.4.0">
    <iq:products>
      <iq:product id="fenix6xpro"/>
      <iq:product id="fenix847mm"/>
      <iq:product id="fr55"/>
    </iq:products>
    <iq:permissions/>
    <iq:languages><iq:language>eng</iq:language></iq:languages>
    <iq:barrels/>
  </iq:application>
</iq:manifest>
Enter fullscreen mode Exit fullscreen mode

The UUID cannot change after publishing. minApiLevel="3.4.0" means roughly Fenix 6 generation and newer.

The code:

import Toybox.Application;
import Toybox.Graphics;
import Toybox.Lang;
import Toybox.WatchUi;

class HitApp extends Application.AppBase {
    function initialize() { AppBase.initialize(); }

    function getInitialView() as [WatchUi.Views] or [WatchUi.Views, WatchUi.InputDelegates] {
        var view = new HitView();
        return [view, new HitDelegate(view)];
    }
}

class HitView extends WatchUi.View {
    var hits as Number = 0;
    var shots as Number = 0;

    function initialize() { View.initialize(); }

    function onUpdate(dc as Graphics.Dc) as Void {
        dc.setColor(Graphics.COLOR_WHITE, Graphics.COLOR_BLACK);
        dc.clear();
        dc.drawText(dc.getWidth() / 2, dc.getHeight() / 2, Graphics.FONT_NUMBER_MEDIUM,
            hits.toString() + "/" + shots.toString(),
            Graphics.TEXT_JUSTIFY_CENTER | Graphics.TEXT_JUSTIFY_VCENTER);
    }
}

class HitDelegate extends WatchUi.BehaviorDelegate {
    var view as HitView;

    function initialize(v as HitView) {
        BehaviorDelegate.initialize();
        view = v;
    }

    function onPreviousPage() as Boolean { return shot(true); }
    function onNextPage() as Boolean { return shot(false); }

    function shot(hit as Boolean) as Boolean {
        view.shots += 1;
        if (hit) { view.hits += 1; }
        WatchUi.requestUpdate();
        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

BehaviorDelegate maps input to behaviors, not physical buttons: UP/DOWN on button watches, swipes on touch ones. One app, every model. (In Clay Sniper we actually swallow swipes on the shot screen so an accidental touch doesn't record a miss.)

From here it grows the way Clay Sniper did: Attention.vibrate, Sensor.enableSensorEvents for heart rate, ActivityRecording.createSession with SPORT_SHOOTING, FitContributor for custom fields — each with its permission in the manifest.

Build, simulate, test

monkeyc -f monkey.jungle -d fenix847mm -y developer_key.der -l 3 -o bin/HitCounter.prg
connectiq &
monkeydo bin/HitCounter.prg fenix847mm

monkeyc -f monkey.jungle -d fenix847mm -y developer_key.der --unit-test -o bin/test.prg
monkeydo bin/test.prg fenix847mm -t

monkeyc -f monkey.jungle -y developer_key.der -e -r -o bin/HitCounter.iq   # store package
Enter fullscreen mode Exit fullscreen mode

A test is a function annotated (:test) that returns true; it is stripped from release builds. A real one from Clay Sniper:

(:test)
function lastShotClosesSeries(logger as Test.Logger) as Boolean {
    var s = TestSupport.started(3);
    WorkoutReducer.reduce(s, A_HIT, null);
    WorkoutReducer.reduce(s, A_MISS, null);
    WorkoutReducer.reduce(s, A_HIT, null);
    Test.assertEqual(s.completedSeries.size(), 1);
    return s.totalHits() == 2 && s.totalShots() == 3 && s.seriesNumber() == 2;
}
Enter fullscreen mode Exit fullscreen mode

Test at least three models: a big screen (Fenix 8), an old one (Fenix 6) and a small one (Forerunner 55). Almost all of our layout bugs showed up on the small one.

Sideloading to your own watch

Build a .prg for your model, plug the watch in, and copy the file into GARMIN/APPS (not the root — the watch won't see it there). On a Mac the watch is an MTP device, so you need something like OpenMTP.

Publishing to the Connect IQ Store

There is no CLI or API, only the web portal.

  1. Build the .iq package (our package covered 90 models).
  2. Upload it and type the version number (it isn't stored in the project).
  3. Fill in the listing: name, description, category, a 500×500 cover under 300 KB, screenshots under 150 KB each.
  4. Answer whether the app collects data and has paid features.
  5. Wait for review. Garmin promises up to three business days; before approval the public page returns 404.

Gotchas we hit

What happened Why Fix
A build sideloaded over USB never synced workouts to the iPhone Messages go through Garmin Connect; our explanation is that it doesn't relay messages for an app installed outside the store Test watch-to-phone sync only on a store install; it works there. Keep USB builds for screens and buttons
Crash on Forerunner 55: Symbol Not Found No barometer, so meanSeaLevelPressure doesn't exist; strict typing doesn't catch it Read every optional field behind has, show a dash when missing
Copied app didn't show up File was in the device root Use GARMIN/APPS
Time overlapped labels on a 208 px screen Layout was designed on a big Fenix Pick font size and line count from the measured screen
First review took longer than promised Still "Pending" on day five Budget a week, don't edit the listing during review
Portal rejected a developer name with a space Form restriction We are "KLukyanov.ru"

The first one is the nasty one. Everything looks like a bug in your own code: the workout sits in the outbox, the phone stays silent, and the real cause is how the app was installed.

By the numbers

  • 2 days from first commit to store submission
  • ~2,000 lines of Monkey C, 29 unit tests
  • 90 watch models, Connect IQ 3.4+ (Fenix 6 and newer)
  • 6 UI languages

The code was written with an AI coding agent. It knows Monkey C worse than Swift, but it is very good at porting existing logic between languages, and the Apple Watch reducer was the spec. That is how two weeks became two days.

Next: watch faces

Our first watch face, Clay Sniper Range, is already submitted: a compass ring with the sun and a wind arrow, and everything a shooter checks before stepping onto the station — sunrise and sunset, daylight left, heart rate, temperature and pressure. A second one is in the works. Part 2 is about both.


Originally published at klukyanov.ru.

Shorter weekly write-ups (in Russian) — on Telegram.

Top comments (0)