Skip to content

Commit

Permalink
Merge pull request #1 from Fitbit/initial
Browse files Browse the repository at this point in the history
Initial version
  • Loading branch information
orviwan authored Dec 19, 2019
2 parents 683fccc + 56747a6 commit 76ebab6
Show file tree
Hide file tree
Showing 15 changed files with 386 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
build
node_modules
package-lock.json
yarn-error.log
yarn.lock
21 changes: 21 additions & 0 deletions LICENCE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Fitbit, Inc

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.
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,18 @@
# sdk-calendar-clock

Fitbit SDK example application which demonstrates the Companion Calendar API.

![Screenshot](screenshot.png)

The companion fetches calendar data using the Companion Calendar API and sends it to the
device using the File Transfer API. The application decides which event to display.

> Note: Only a subset of the calendar data is sent to the device, if you need to
> use different fields, then you need to include them in the file transfer.
Find out more information on the
[Fitbit Developer Website](https://dev.fitbit.com).

## License

This example is licensed under the [MIT License](./LICENSE).
72 changes: 72 additions & 0 deletions app/appointment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { inbox } from "file-transfer";
import { readFileSync } from "fs";

import { dataFile, dataType } from "../common/constants";
import { toEpochSec } from "../common/utils";

let data;
let handleCalendarUpdatedCallback;

export function initialize(callback) {
handleCalendarUpdatedCallback = callback;
data = loadData();
inbox.addEventListener("newfile", fileHandler);
fileHandler();
updatedData();
}

export function next() {
if (existsData()) {
// Exclude all-day events
let events = data.filter(event => {
return !event.isAllDay;
});

if (events.length > 0) {
const currentDate = toEpochSec(new Date());

// Get all future events
let futureEvents = events.filter(event => {
return event.startDate > currentDate;
});

if (futureEvents.length > 0) {
// Get the first future appointment
return futureEvents[0];
}
}
}
return;
}

function fileHandler() {
let fileName;
do {
fileName = inbox.nextFile();
data = loadData();
updatedData();
} while (fileName);
}

function loadData() {
try {
return readFileSync(`/private/data/${dataFile}`, dataType);
} catch (ex) {
console.error(`Appointment: loadData() failed. ${ex}`);
return;
}
}

function existsData() {
if (data === undefined) {
console.warn("Appointment: No data found.");
return false;
}
return true;
}

function updatedData() {
if (typeof handleCalendarUpdatedCallback === "function" && existsData()) {
handleCalendarUpdatedCallback();
}
}
29 changes: 29 additions & 0 deletions app/clock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import clock from "clock";
import { preferences } from "user-settings";
import * as util from "../common/utils";

let handleClockTickCallback;

export function initialize(granularity, callback) {
clock.granularity = granularity ? granularity : "minutes";
handleClockTickCallback = callback;
clock.addEventListener("tick", tick);
}

export function tick(evt) {
const today = evt ? evt.date : new Date();
const mins = util.zeroPad(today.getMinutes());
let hours = today.getHours();

if (preferences.clockDisplay === "12h") {
// 12h format
hours = hours % 12 || 12;
} else {
// 24h format
hours = util.zeroPad(hours);
}

if (typeof handleClockTickCallback === "function") {
handleClockTickCallback({ time: `${hours}:${mins}` });
}
}
33 changes: 33 additions & 0 deletions app/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import document from "document";

import * as appointment from "./appointment";
import * as clock from "./clock";
import { fromEpochSec, timeUntil, trimString } from "../common/utils";

const time = document.getElementById("time");
const title = document.getElementById("title");
const details = document.getElementById("details");

clock.initialize("minutes", data => {
// Clock ticked, update UI
time.text = data.time;
renderAppointment();
});

appointment.initialize(() => {
// We have fresh calendar data
clock.tick();
});

function renderAppointment() {
let event = appointment.next();
if (event) {
title.text = event.title.substr(0, 20);
details.text = `${timeUntil(fromEpochSec(event.startDate))} ${
event.location ? `@ ${event.location}` : ""
}`;
} else {
title.text = "No appointments";
details.text = "";
}
}
3 changes: 3 additions & 0 deletions common/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const dataType = "cbor";
export const dataFile = "appointments.cbor";
export const millisecondsPerMinute = 1000 * 60;
64 changes: 64 additions & 0 deletions common/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* Add zero in front of numbers < 10
* @param {number} i
*/
export function zeroPad(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}

/**
* Convert a Date object to seconds since January 1, 1970
* @param {Date} date
*/
export function toEpochSec(date) {
return Math.floor(date.getTime() / 1000);
}

/**
* Convert a seconds since January 1, 1970 to a Date object
* @param {Number} seconds
*/
export function fromEpochSec(seconds) {
return new Date(seconds * 1000);
}

/**
* Returns a friendly time until a specified date
* @param {Date} date
*/
export function timeUntil(date) {
const today = new Date();
const days = parseInt((date - today) / (1000 * 60 * 60 * 24));
const hours = parseInt((Math.abs(date - today) / (1000 * 60 * 60)) % 24);
const minutes = parseInt(
(Math.abs(date.getTime() - today.getTime()) / (1000 * 60)) % 60
);

if (days > 0) {
return `in ${days} ${pluralize(days, "day")}`;
}

if (hours > 0) {
return `in ${hours}${pluralize(hours, "hr")}${
hours < 3 && minutes > 0 ? ` ${minutes}${pluralize(minutes, "min")}` : ""
}`;
}

if (minutes > 0) {
return `in ${minutes}${pluralize(minutes, "min")}`;
}

return "Now";
}

/**
* Pluralizes the units if required
* @param {Number} number
* @param {String} unit
*/
function pluralize(number, unit) {
return number === 1 ? unit : `${unit}s`;
}
57 changes: 57 additions & 0 deletions companion/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import calendars from "calendars";
import * as cbor from "cbor";
import { me as companion } from "companion";
import { outbox } from "file-transfer";

import { toEpochSec } from "../common/utils";
import { dataFile, millisecondsPerMinute } from "../common/constants";

companion.wakeInterval = 15 * millisecondsPerMinute;
companion.addEventListener("wakeinterval", refreshData);

refreshData();

function refreshData() {
let dataEvents = [];

calendars
.searchSources()
.then(results => {
return calendars.searchCalendars();
})
.then(results => {
// Filter events to 48hr window
const startDate = new Date();
const endDate = new Date();
startDate.setHours(0, 0, 0, 0);
endDate.setHours(128, 59, 59, 999);
const eventsQuery = { startDate, endDate };

return calendars.searchEvents(eventsQuery);
})
.then(results => {
results.forEach(event => {
// console.log(`> event: ${event.title} (${event.startDate})`);
dataEvents.push({
title: event.title,
location: event.location,
startDate: toEpochSec(event.startDate),
endDate: toEpochSec(event.endDate),
isAllDay: event.isAllDay
});
});
if (dataEvents && dataEvents.length > 0) {
sendData(dataEvents);
}
})
.catch(error => {
console.error(error);
console.error(error.stack);
});
}

function sendData(data) {
outbox.enqueue(dataFile, cbor.encode(data)).catch(error => {
console.warn(`Failed to enqueue data. Error: ${error}`);
});
}
33 changes: 33 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "sdk-calendar-clock",
"version": "0.1.0",
"private": true,
"license": "MIT",
"devDependencies": {
"@fitbit/sdk": "~4.1.0",
"@fitbit/sdk-cli": "^1.7.1"
},
"fitbit": {
"appUUID": "24855175-1a50-42f2-8178-019cb091a886",
"appType": "clockface",
"appDisplayName": "SDK Calendar Clock",
"iconFile": "resources/icon.png",
"wipeColor": "#ffffff",
"requestedPermissions": [
"access_calendar",
"run_background"
],
"buildTargets": [
"higgs",
"meson",
"gemini",
"mira"
],
"i18n": {},
"defaultLanguage": "en-US"
},
"scripts": {
"build": "fitbit-build",
"debug": "fitbit"
}
}
6 changes: 6 additions & 0 deletions resources/index.gui
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<svg>
<rect id="background" />
<text id="time">13:37</text>
<text id="title">Appointment Title</text>
<textarea id="details">Appointment Date @ Appointment Location</textarea>
</svg>
37 changes: 37 additions & 0 deletions resources/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
text {
font-size: 32;
font-family: System-Regular;
font-weight: regular;
text-length: 32;
text-anchor: middle;
fill: white;
}

#background {
width: 100%;
height: 100%;
fill: black;
}

#time {
x: 50%;
y: 25%;
font-size: 45;
}

#title {
x: 50%;
y: $+20;
font-family: System-Bold;
}

#details {
font-size: 28;
font-family: System-Regular;
font-weight: regular;
text-length: 128;
text-anchor: middle;
fill: white;
x: 0;
y: $-15;
}
6 changes: 6 additions & 0 deletions resources/widgets.gui
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<svg>
<defs>
<link rel="stylesheet" href="styles.css" />
<link rel="import" href="/mnt/sysassets/widgets_common.gui" />
</defs>
</svg>
Binary file added screenshot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 76ebab6

Please sign in to comment.